From a4369674144c1ae9e3607ca6a7e27ad17e8bbfb2 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Tue, 24 Nov 2026 18:42:07 +0900 Subject: [PATCH 1/5] feat(mcp): add performance readout tools matching debug overlay (#468) --- .../2026-11-24-mcp-performance-readouts.md | 43 ++ changelog.d/mcp-perf-readouts-468.md | 4 + docs/en/mcp.md | 41 +- docs/zh/mcp.md | 41 +- packages/game/debug/debug_release_test.go | 9 +- packages/game/debug/debug_test.go | 47 ++ packages/game/debug/gc.go | 120 +++- packages/game/debug/gc_release.go | 9 + packages/game/debug/gc_test.go | 19 + packages/game/debug/overlay.go | 95 +++- packages/game/debug/profiler.go | 18 + packages/game/debug/profiler_release.go | 3 + packages/game/debug/profiler_test.go | 5 + packages/game/debug/release.go | 12 + packages/game/debug/types.go | 20 + packages/game/mcp/doc.go | 3 + packages/game/mcp/example_test.go | 3 + packages/game/mcp/mcp.go | 20 + packages/game/mcp/perf.go | 534 ++++++++++++++++++ packages/game/mcp/perf_test.go | 487 ++++++++++++++++ 20 files changed, 1484 insertions(+), 49 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-11-24-mcp-performance-readouts.md create mode 100644 changelog.d/mcp-perf-readouts-468.md create mode 100644 packages/game/mcp/perf.go create mode 100644 packages/game/mcp/perf_test.go diff --git a/.agents/notes/implemented/feature/2026-11-24-mcp-performance-readouts.md b/.agents/notes/implemented/feature/2026-11-24-mcp-performance-readouts.md new file mode 100644 index 00000000..ae4568b9 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-24-mcp-performance-readouts.md @@ -0,0 +1,43 @@ +# Agent Note: MCP performance readouts + +Status: implemented + +## Problem + +Coding agents driving or inspecting a running NSGo game over `nsgo mcp` (see [MCP scene, layer, entity and component inspection](2026-11-24-mcp-scene-entity-inspection.md)) can query scenes, layers, entities and components, but cannot observe live frame timing, update and draw costs, draw statistics, per-frame heap allocations, GC pauses, or named profiler zones. Without structured readouts backed by the same counters as `game/debug`'s on-screen overlay, agents cannot verify frame-budget compliance or diagnose spikes and allocation regressions programmatically. + +## Decision + +Add a dedicated `perf` tool group (`packages/game/mcp/perf.go`) exposing `game_perf_readout`, `game_perf_zones`, and `game_perf_reset` via `Bridge.Tools()`, reading directly from `debug.Overlay`, `debug.Profiler`, `debug.GCMonitor`, `debug.MemoryTracker`, `debug.DrawStats`, and `render3d.RenderStats`. Extend `packages/game/debug` minimally so `GCMonitor` also samples per-frame heap allocations with zero steady-state allocations, `Overlay` supports optional `DrawStats`, and `Overlay`/`Profiler`/`GCMonitor` expose clean reset helpers shared by both the HUD and MCP. + +## Architecture and contract + +- **Single source of truth with `debug.Overlay`**: `game_perf_readout` reads `FPS()`, `Average()`, `Latest()`, `Samples()`, `DrawStats()`, `Profiler()`, `GC()`, and `Memory()` directly from `Config.Overlay` (using the same `float64(d) / float64(time.Millisecond)` conversion as `debug/overlay.go`). Values returned by MCP match the on-screen debug overlay bit-for-bit, and `game_perf_reset` refreshes the visible overlay HUD via `Overlay.ResetStats()`. +- **Zero-alloc per-frame allocation tracking in `debug.GCMonitor`**: `GCMonitor` extends its pre-allocated `runtime/metrics` sample buffer from 3 to 5 entries to read `/gc/heap/allocs:objects` and `/gc/heap/allocs:bytes` alongside `/gc/pauses:seconds`, `/gc/cycles/total:gc-cycles`, and `/memory/classes/heap/objects:bytes`. Running window totals (`recentAllocs`, `recentAllocBytes`) are updated in O(1) as the ring buffer advances, preserving `debug.AssertZeroAllocs` in steady state while exposing `AllocsPerFrame()` and `AllocBytesPerFrame()` to both the overlay and MCP. +- **2D and 3D draw statistics**: `debug.DrawStats` (`DrawCalls`, `Sprites`, `Batches`, `Triangles`, `Vertices`) can be supplied via `debug.Options.DrawStats`, pushed with `Overlay.SetDrawStats`, or overridden via `mcp.Config.DrawStatsFunc`. Optional `mcp.Config.RenderStatsFunc` attaches full `render3d.RenderStats` telemetry under `render3d` and populates top-level `draw_calls`, `batches`, `triangles`, and `vertices` automatically when no 2D draw-stats source is configured. +- **Strict schemas and graceful degradation**: Every perf tool decodes arguments with `json.Decoder.DisallowUnknownFields()` and rejects negative limits. Calling `game_perf_readout` or `game_perf_reset` with no configured perf telemetry returns an explicit error rather than misleading zeros; configuring any subset of providers succeeds and reports active providers in `sources`. Calling `game_perf_zones` without a profiler returns an explicit error, while `game_perf_readout` with `include_zones: true` degrades cleanly when only an overlay is configured. +- **Release-build parity**: Every new method added to `packages/game/debug` (`DrawStats`, `SetDrawStats`, `HasDrawStats`, `ResetStats`, `Profiler.Reset`, `GCMonitor.AllocsPerFrame`, `GCMonitor.AllocBytesPerFrame`, `GCMonitor.Reset`) has a matching zero-cost no-op stub in the `//go:build release` files so `-tags release` builds remain unaffected. +- **Minimal merge footprint**: All tool schemas, response structs, and handlers live in `packages/game/mcp/perf.go`, with only additive `Config` fields and `b.perfTools()` hookup in `packages/game/mcp/mcp.go` so parallel MCP PRs (#462–#469) rebase cleanly. + +## Alternatives considered + +### Sampling `runtime.ReadMemStats` inside `mcp` on every `game_perf_readout` call + +Reading `runtime.ReadMemStats` directly in `mcp` would avoid extending `debug.GCMonitor` and would report heap/allocation numbers even when `Config.GC` is nil. This was rejected because `runtime.ReadMemStats` triggers a stop-the-world pause (distorting the very frame times being measured), produces ad-hoc inter-call deltas rather than per-frame averages, and would diverge from the numbers displayed in `debug.Overlay`. + +### Keeping `DrawStats` exclusively inside `packages/game/mcp` + +Defining `DrawStats` only inside `mcp` would avoid touching `packages/game/debug`. This was rejected because issue #468 requires MCP performance readouts to match the debug overlay's values; placing `DrawStats` on `debug.Overlay` lets games report draw counts once and have both the on-screen HUD and `game_perf_readout` reflect identical numbers. + +### Returning all-zero readouts when no performance providers are configured + +Returning a zeroed `PerfReadoutResult` on an empty `mcp.Config{}` avoids errors in unconfigured games. This was rejected because zero `fps`, zero `draw_calls`, and zero `allocs_per_frame` are indistinguishable from a paused or idle game; returning an explicit error when no provider is configured matches `game_entities_list` and `game_layers_list` in `inspect.go`. + +## Consequences + +- **Benefits**: Agents can inspect live FPS, average/latest/percentile frame timings, update/draw splits, 2D and 3D draw counts, per-frame heap allocations, GC pauses/hitches, asset memory budgets, chronological frame history, and profiler zones with guaranteed parity against `debug.Overlay`. Resetting metrics via MCP keeps the visible HUD synchronized. +- **Costs**: `packages/game/debug` gains a small additive API surface (`DrawStats`, `GCMonitor` allocation averages, and `Reset` methods) that must remain mirrored in its `release` build stubs. `packages/game/mcp` now imports `packages/game/debug` and `packages/game/render3d` (all three are Experimental packages, so Stable packages remain unaffected). + +## Verification + +Verified with `gofmt`, `go run ./cmd/gameschema -check`, `go tool nsgo check -target macos,windows,linux,android,web`, `go tool nsgo test ./mcp`, `go tool nsgo test ./debug`, `go tool nsgo test -tags release ./debug`, `go tool nsgo test -run TestStabilityTable .`, `go run ./tools/changelog check`, and `bun run verify-notes`. diff --git a/changelog.d/mcp-perf-readouts-468.md b/changelog.d/mcp-perf-readouts-468.md new file mode 100644 index 00000000..4366e623 --- /dev/null +++ b/changelog.d/mcp-perf-readouts-468.md @@ -0,0 +1,4 @@ +### Added + +- `game/mcp`: add `game_perf_readout`, `game_perf_zones`, and `game_perf_reset` MCP tools exposing frame timings, percentiles, draw statistics, per-frame allocations, GC/heap telemetry, asset memory, and 3D render statistics matching the debug overlay (#468). +- `game/debug`: track per-frame heap allocations (`/gc/heap/allocs:objects` and `/gc/heap/allocs:bytes`) in `GCMonitor`, add `DrawStats` support to `Overlay`, and add `Reset` methods on `Profiler`, `GCMonitor`, and `Overlay.ResetStats` (#468). diff --git a/docs/en/mcp.md b/docs/en/mcp.md index 8dc056bd..a8038b98 100644 --- a/docs/en/mcp.md +++ b/docs/en/mcp.md @@ -14,20 +14,22 @@ Call `mcp.Attach` (or `mcp.New` followed by `bridge.Attach`) on the engine gorou ```go bridge, err := mcp.Attach(cx, mcp.Config{ - Scenes: g.scenes, - SceneName: func(c *scene.Controller) string { return g.sceneNames[c] }, - SceneFunc: func() *scene.Scene { return g.activeScene }, - NamedScenes: map[string]*scene.Scene{"title": g.titleScene}, - WorldFunc: func() *entities.World { return g.world }, - EntityName: func(e entities.Entity) string { return g.names[e] }, - EntityTags: func(e entities.Entity) []string { return g.tags[e] }, - EntityLayer: func(e entities.Entity) string { return g.layers[e] }, - Loop: g.loop, - RandomStreams: g.rng, - Actions: g.actions, - Viewport: &g.viewport, - ViewSizeFunc: g.currentViewSize, - Console: g.console, + Scenes: g.scenes, + SceneName: func(c *scene.Controller) string { return g.sceneNames[c] }, + SceneFunc: func() *scene.Scene { return g.activeScene }, + NamedScenes: map[string]*scene.Scene{"title": g.titleScene}, + WorldFunc: func() *entities.World { return g.world }, + EntityName: func(e entities.Entity) string { return g.names[e] }, + EntityTags: func(e entities.Entity) []string { return g.tags[e] }, + EntityLayer: func(e entities.Entity) string { return g.layers[e] }, + Loop: g.loop, + RandomStreams: g.rng, + Actions: g.actions, + Viewport: &g.viewport, + ViewSizeFunc: g.currentViewSize, + Console: g.console, + Overlay: g.debugOverlay, + RenderStatsFunc: func() render3d.RenderStats { return g.lastRenderStats }, }) if err != nil { return err @@ -117,6 +119,9 @@ If `game_entity_spawn` fails while applying `parent` or `components`, or while r | `game_replay_play` | `name` or `yaml` (mutually exclusive), `run_to_end` (default `false`), `steps` (`1..3600`), `reset` (default `true` when `ResetFunc` or a seed target is configured) | Resets to the recording's seed and starts deterministic playback via `replay.Player`, optionally advancing all (`run_to_end`, recordings up to `3600` steps) or `steps` frames synchronously via `StepFunc` or the game loop's `StepNow`. A recording whose `rate` differs from the game's fixed step rate is refused. | | `game_replay_stop` | `{}` | Stops an active replay playback cleanly and reports how many frames were played. | | `game_replay_list` | `{}` | Lists stored recordings in sorted name order with `frames`, `seed`, `step_rate`, `events`, `actions`, `axes` and `metadata`. | +| `game_perf_readout` | `include_history` (optional, default `false`), `history_limit` (optional), `include_zones` (optional, default `false`), `zones_limit` (optional) | Live performance readout matching the debug overlay: `fps`, rolling average and latest `frame_ms`/`update_ms`/`draw_ms`, min/max/p50/p95/p99 frame times, draw stats (`draw_calls`, `sprites`, `batches`, `triangles`, `vertices`), per-frame heap allocations (`allocs_per_frame`, `alloc_bytes_per_frame`, `last_frame_allocs`, `last_frame_alloc_bytes`), `heap_bytes`, `gc_count`, GC pause/hitch metrics, optional `render3d` and `asset_memory` breakdowns, and optional chronological `history` and profiler `zones`. | +| `game_perf_zones` | `limit` (optional) | Named timing zones from `debug.Profiler` sorted by recent frame cost (`name`, `last_ms`, `avg_ms`, `max_ms`, `calls`), plus `recording`, `recorded_frames` and `total`. | +| `game_perf_reset` | `{}` | Resets accumulated `debug.Overlay` frame timings and pushed draw stats, `debug.Profiler` zones, and `debug.GCMonitor` history. | All tools reject unknown argument fields. @@ -187,6 +192,14 @@ bridge, err := mcp.Attach(cx, mcp.Config{ - `game_replay_play` accepts either a stored `name` or inline `yaml` text and replays either synchronously (`run_to_end: true` or `steps: N`) or frame by frame as the game loop advances. Without `StepFunc`, synchronous playback advances the Bridge's loop with `Loop.StepNow`, so `game_loop_status` counts the replayed steps and game time. Like `game_loop_step`, a single call advances at most `MaxLoopSteps` (`3600`) steps. - After the final recorded step, the next `ctrl.Step()` is a trailing playback step that releases actions still held at the end of the recording (firing `JustReleased` once); the step after it returns to live input and calls `OnReplayStop`. +## Performance readouts + +Pass your [`debug.Overlay`](debug.md) via `Config.Overlay` to expose the exact same frame timings, draw statistics (`debug.Options.DrawStats` or `Overlay.SetDrawStats`), GC/allocation counters (`debug.GCMonitor`), asset memory (`debug.MemoryTracker`) and timing scopes (`debug.Profiler`) shown by the on-screen debug HUD. + +- `Config.Profiler`, `Config.GC`, `Config.Memory` and `Config.DrawStatsFunc` override (or work standalone without) `Config.Overlay`. +- `Config.RenderStatsFunc` attaches detailed 3D culling, batching, state-switch and GPU memory metrics from [`render3d.RenderStats`](render3d.md) under `render3d`, and populates top-level `draw_calls`, `batches`, `triangles` and `vertices` automatically when no 2D draw-stats provider is set. +- `game_perf_readout` always includes a `sources` object indicating which telemetry providers are active (`overlay`, `profiler`, `gc`, `memory`, `draw_stats`, `render3d`). + ## Stable entity references Every live entity receives a generational reference formatted as `"entity::"` (such as `"entity:0:1"`), produced by `FormatEntityRef` and parsed by `ParseEntityRef`: diff --git a/docs/zh/mcp.md b/docs/zh/mcp.md index 9f327eb8..31951892 100644 --- a/docs/zh/mcp.md +++ b/docs/zh/mcp.md @@ -14,20 +14,22 @@ import "github.com/nsgo-dev/game/packages/game/mcp" ```go bridge, err := mcp.Attach(cx, mcp.Config{ - Scenes: g.scenes, - SceneName: func(c *scene.Controller) string { return g.sceneNames[c] }, - SceneFunc: func() *scene.Scene { return g.activeScene }, - NamedScenes: map[string]*scene.Scene{"title": g.titleScene}, - WorldFunc: func() *entities.World { return g.world }, - EntityName: func(e entities.Entity) string { return g.names[e] }, - EntityTags: func(e entities.Entity) []string { return g.tags[e] }, - EntityLayer: func(e entities.Entity) string { return g.layers[e] }, - Loop: g.loop, - RandomStreams: g.rng, - Actions: g.actions, - Viewport: &g.viewport, - ViewSizeFunc: g.currentViewSize, - Console: g.console, + Scenes: g.scenes, + SceneName: func(c *scene.Controller) string { return g.sceneNames[c] }, + SceneFunc: func() *scene.Scene { return g.activeScene }, + NamedScenes: map[string]*scene.Scene{"title": g.titleScene}, + WorldFunc: func() *entities.World { return g.world }, + EntityName: func(e entities.Entity) string { return g.names[e] }, + EntityTags: func(e entities.Entity) []string { return g.tags[e] }, + EntityLayer: func(e entities.Entity) string { return g.layers[e] }, + Loop: g.loop, + RandomStreams: g.rng, + Actions: g.actions, + Viewport: &g.viewport, + ViewSizeFunc: g.currentViewSize, + Console: g.console, + Overlay: g.debugOverlay, + RenderStatsFunc: func() render3d.RenderStats { return g.lastRenderStats }, }) if err != nil { return err @@ -117,6 +119,9 @@ if err := bridge.RegisterScenePrefab("turret", turretDoc); err != nil { | `game_replay_play` | `name` 或 `yaml`(二选一)、`run_to_end`(默认 `false`)、`steps`(`1..3600`)、`reset`(配置了 `ResetFunc` 或种子目标时默认 `true`) | 按录制的种子重置,然后通过 `replay.Player` 开始确定性回放,并可选通过 `StepFunc` 或游戏循环的 `StepNow` 同步推进全部帧(`run_to_end`,录制不超过 `3600` 步)或 `steps` 帧。`rate` 与游戏固定步频不同的录制会被拒绝。 | | `game_replay_stop` | `{}` | 安全停止当前正在进行的回放,并报告已回放的帧数。 | | `game_replay_list` | `{}` | 按名称排序列出已存储的录制及其 `frames`、`seed`、`step_rate`、`events`、`actions`、`axes` 与 `metadata`。 | +| `game_perf_readout` | `include_history`(可选,默认 `false`)、`history_limit`(可选)、`include_zones`(可选,默认 `false`)、`zones_limit`(可选) | 与调试浮层数值一致的实时性能读数:`fps`、滑动平均与最近一帧的 `frame_ms`/`update_ms`/`draw_ms`、最小/最大及 p50/p95/p99 帧时间、绘制统计(`draw_calls`、`sprites`、`batches`、`triangles`、`vertices`)、每帧堆分配(`allocs_per_frame`、`alloc_bytes_per_frame`、`last_frame_allocs`、`last_frame_alloc_bytes`)、`heap_bytes`、`gc_count`、GC 停顿与卡顿统计、可选的 `render3d` 与 `asset_memory` 明细,以及可选的时间序 `history` 与分析器 `zones`。 | +| `game_perf_zones` | `limit`(可选) | 按最近帧耗时降序排列的 `debug.Profiler` 命名计时区间列表(`name`、`last_ms`、`avg_ms`、`max_ms`、`calls`),以及 `recording`、`recorded_frames` 和 `total`。 | +| `game_perf_reset` | `{}` | 重置累积的 `debug.Overlay` 帧耗时与推送绘制统计、`debug.Profiler` 区间以及 `debug.GCMonitor` 历史记录。 | 所有工具都会拒绝未知的参数字段。 @@ -187,6 +192,14 @@ bridge, err := mcp.Attach(cx, mcp.Config{ - `game_replay_play` 支持按已存 `name` 或内联 `yaml` 文本回放,可同步回放(`run_to_end: true` 或 `steps: N`),也可随游戏循环逐帧回放。未设置 `StepFunc` 时,同步回放通过 `Loop.StepNow` 推进桥接器的游戏循环,因此 `game_loop_status` 会计入回放的步数与游戏时间。与 `game_loop_step` 相同,单次调用最多推进 `MaxLoopSteps`(`3600`)步。 - 最后一个录制步之后,下一次 `ctrl.Step()` 是一个收尾回放步,会释放录制结束时仍按住的动作(触发一次 `JustReleased`);再下一步才恢复实时输入并调用 `OnReplayStop`。 +## 性能读数 + +通过 `Config.Overlay` 传入 [`debug.Overlay`](debug.md),即可把调试 HUD 显示的帧耗时、绘制统计(`debug.Options.DrawStats` 或 `Overlay.SetDrawStats`)、GC 与每帧分配计数(`debug.GCMonitor`)、资源内存(`debug.MemoryTracker`)以及命名计时区间(`debug.Profiler`)以完全一致的数值暴露给智能体。 + +- `Config.Profiler`、`Config.GC`、`Config.Memory` 与 `Config.DrawStatsFunc` 既可覆盖 `Config.Overlay` 上的对应组件,也可在不启用浮层时单独使用。 +- `Config.RenderStatsFunc` 会在 `render3d` 字段下附加来自 [`render3d.RenderStats`](render3d.md) 的 3D 裁剪、合批、状态切换与 GPU 内存明细;在未配置 2D 绘制统计来源时,还会自动填充顶层的 `draw_calls`、`batches`、`triangles` 与 `vertices`。 +- `game_perf_readout` 始终返回 `sources` 对象,标明哪些遥测来源已启用(`overlay`、`profiler`、`gc`、`memory`、`draw_stats`、`render3d`)。 + ## 稳定的实体引用 每个存活实体都会获得一个格式为 `"entity::"`(例如 `"entity:0:1"`)的代数引用,由 `FormatEntityRef` 格式化并由 `ParseEntityRef` 解析: diff --git a/packages/game/debug/debug_release_test.go b/packages/game/debug/debug_release_test.go index 8e60700c..12e2fcd1 100644 --- a/packages/game/debug/debug_release_test.go +++ b/packages/game/debug/debug_release_test.go @@ -113,6 +113,11 @@ func TestReleaseBuildIsDisabledZeroCostStub(t *testing.T) { } dbg.RecordFrame(16*time.Millisecond, 4*time.Millisecond, 3*time.Millisecond) + dbg.SetDrawStats(debug.DrawStats{DrawCalls: 5, Sprites: 10}) + if dbg.HasDrawStats() || dbg.DrawStats() != (debug.DrawStats{}) { + t.Fatal("Overlay recorded DrawStats in release build") + } + dbg.ResetStats() dbg.SetScenes([]debug.SceneSnapshot{{Name: "world"}}) dbg.RefreshScenes() @@ -181,6 +186,7 @@ func TestReleaseBuildIsDisabledZeroCostStub(t *testing.T) { if p.Recording() || p.RecordedFrames() != 0 || len(p.TopScopes(5)) != 0 { t.Fatal("Profiler recorded data in release build") } + p.Reset() var traceBuf bytes.Buffer if err := p.WriteChromeTrace(&traceBuf); err != nil || traceBuf.Len() != 0 { t.Fatalf("WriteChromeTrace in release = (len=%d, err=%v), want (0, nil)", traceBuf.Len(), err) @@ -211,9 +217,10 @@ func TestReleaseBuildIsDisabledZeroCostStub(t *testing.T) { if sample := gc.SampleFrame(16 * time.Millisecond); sample != (debug.GCFrameSample{}) { t.Fatalf("GCMonitor.SampleFrame in release = %+v, want zero", sample) } - if gc.TotalCycles() != 0 || gc.MaxPause() != 0 || gc.LastPause() != 0 || gc.RecentHitches() != 0 || gc.HeapObjectsBytes() != 0 || gc.Len() != 0 || gc.At(0) != (debug.GCFrameSample{}) || gc.Latest() != (debug.GCFrameSample{}) { + if gc.TotalCycles() != 0 || gc.MaxPause() != 0 || gc.LastPause() != 0 || gc.RecentHitches() != 0 || gc.HeapObjectsBytes() != 0 || gc.AllocsPerFrame() != 0 || gc.AllocBytesPerFrame() != 0 || gc.Len() != 0 || gc.At(0) != (debug.GCFrameSample{}) || gc.Latest() != (debug.GCFrameSample{}) { t.Fatal("GCMonitor returned non-zero metrics in release build") } + gc.Reset() if got := debug.MeasureAllocs(10, func() { _ = make([]byte, 64) }); got != 0 { t.Fatalf("MeasureAllocs in release = %v, want 0", got) } diff --git a/packages/game/debug/debug_test.go b/packages/game/debug/debug_test.go index 45608c28..1c034bd1 100644 --- a/packages/game/debug/debug_test.go +++ b/packages/game/debug/debug_test.go @@ -255,6 +255,53 @@ func TestFrameGraphDrawsStackedBarsAndReferenceLine(t *testing.T) { } } +func TestOverlayDrawStatsAndResetStats(t *testing.T) { + dbg := debug.New(debug.Options{Visible: true}) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return core.View{ + Style: core.Style{Width: core.Pt(400), Height: core.Pt(300)}, + Children: []core.Node{dbg.View(cx)}, + } + }) + + if dbg.HasDrawStats() || app.Exists("debug-draw-stats") { + t.Fatal("draw stats should be absent before SetDrawStats") + } + + want := debug.DrawStats{DrawCalls: 7, Sprites: 42, Batches: 2, Triangles: 84, Vertices: 168} + app.Post(func() { + dbg.RecordFrame(16*time.Millisecond, 3*time.Millisecond, 2*time.Millisecond) + dbg.SetDrawStats(want) + }) + app.Settle() + + if !dbg.HasDrawStats() || dbg.DrawStats() != want { + t.Fatalf("DrawStats() = %+v (has=%v), want %+v", dbg.DrawStats(), dbg.HasDrawStats(), want) + } + if !app.Exists("debug-draw-stats") { + t.Fatal("debug-draw-stats section not mounted after SetDrawStats") + } + foundDraw := false + for _, txt := range app.Texts() { + if strings.Contains(txt, "7 calls") && strings.Contains(txt, "42 sprites") && strings.Contains(txt, "84 tris") { + foundDraw = true + break + } + } + if !foundDraw { + t.Fatalf("overlay texts %v missing draw stats summary", app.Texts()) + } + + app.Post(dbg.ResetStats) + app.Settle() + if dbg.Stats().Len() != 0 || dbg.HasDrawStats() || dbg.DrawStats() != (debug.DrawStats{}) { + t.Fatalf("ResetStats did not clear frame/draw stats: len=%d has=%v ds=%+v", dbg.Stats().Len(), dbg.HasDrawStats(), dbg.DrawStats()) + } + if app.Exists("debug-draw-stats") { + t.Fatal("debug-draw-stats still mounted after ResetStats") + } +} + func TestShapesAlignAcrossCameraZoomsAndRotations(t *testing.T) { green := core.RGB(0x22C55E) cyan := core.RGB(0x38BDF8) diff --git a/packages/game/debug/gc.go b/packages/game/debug/gc.go index 5e08c55d..4c77f44c 100644 --- a/packages/game/debug/gc.go +++ b/packages/game/debug/gc.go @@ -9,19 +9,23 @@ import ( "time" ) -// GCMonitor samples Go runtime/metrics GC counters and pause histograms once per frame with zero steady-state allocations, flagging frames hitched by garbage collection. +// GCMonitor samples Go runtime/metrics GC counters, heap allocations and pause histograms once per frame with zero steady-state allocations, flagging frames hitched by garbage collection. type GCMonitor struct { - history []GCFrameSample - head int - count int - recentHitches int - samples [3]metrics.Sample - prevPauseCounts []uint64 - prevCycles uint64 - totalCycles uint64 - heapBytes uint64 - lastPause time.Duration - maxPause time.Duration + history []GCFrameSample + head int + count int + recentHitches int + recentAllocs uint64 + recentAllocBytes uint64 + samples [5]metrics.Sample + prevPauseCounts []uint64 + prevCycles uint64 + totalCycles uint64 + prevAllocsObjects uint64 + prevAllocsBytes uint64 + heapBytes uint64 + lastPause time.Duration + maxPause time.Duration } // NewGCMonitor returns a GCMonitor retaining up to historyLen recent frame samples (defaulting to FrameHistory when <= 0). @@ -31,10 +35,12 @@ func NewGCMonitor(historyLen int) *GCMonitor { } m := &GCMonitor{ history: make([]GCFrameSample, historyLen), - samples: [3]metrics.Sample{ + samples: [5]metrics.Sample{ {Name: "/gc/pauses:seconds"}, {Name: "/gc/cycles/total:gc-cycles"}, {Name: "/memory/classes/heap/objects:bytes"}, + {Name: "/gc/heap/allocs:objects"}, + {Name: "/gc/heap/allocs:bytes"}, }, } metrics.Read(m.samples[:]) @@ -52,6 +58,12 @@ func NewGCMonitor(historyLen int) *GCMonitor { if m.samples[2].Value.Kind() == metrics.KindUint64 { m.heapBytes = m.samples[2].Value.Uint64() } + if m.samples[3].Value.Kind() == metrics.KindUint64 { + m.prevAllocsObjects = m.samples[3].Value.Uint64() + } + if m.samples[4].Value.Kind() == metrics.KindUint64 { + m.prevAllocsBytes = m.samples[4].Value.Uint64() + } return m } @@ -99,6 +111,24 @@ func (m *GCMonitor) SampleFrame(frameDur time.Duration) GCFrameSample { m.heapBytes = heapBytes } + var allocsDelta uint64 + if m.samples[3].Value.Kind() == metrics.KindUint64 { + cur := m.samples[3].Value.Uint64() + if cur > m.prevAllocsObjects { + allocsDelta = cur - m.prevAllocsObjects + } + m.prevAllocsObjects = cur + } + + var allocBytesDelta uint64 + if m.samples[4].Value.Kind() == metrics.KindUint64 { + cur := m.samples[4].Value.Uint64() + if cur > m.prevAllocsBytes { + allocBytesDelta = cur - m.prevAllocsBytes + } + m.prevAllocsBytes = cur + } + pause := time.Duration(pauseSec * float64(time.Second)) if pause < 0 { pause = 0 @@ -116,17 +146,26 @@ func (m *GCMonitor) SampleFrame(frameDur time.Duration) GCFrameSample { CyclesDelta: cyclesDelta, Pause: pause, HeapObjectsBytes: heapBytes, + AllocsDelta: allocsDelta, + AllocBytesDelta: allocBytesDelta, Hitched: hitched, } if len(m.history) > 0 { - if m.count == len(m.history) && m.history[m.head].Hitched { - m.recentHitches-- + if m.count == len(m.history) { + old := m.history[m.head] + if old.Hitched { + m.recentHitches-- + } + m.recentAllocs -= old.AllocsDelta + m.recentAllocBytes -= old.AllocBytesDelta } m.history[m.head] = sample if sample.Hitched { m.recentHitches++ } + m.recentAllocs += sample.AllocsDelta + m.recentAllocBytes += sample.AllocBytesDelta m.head = (m.head + 1) % len(m.history) if m.count < len(m.history) { m.count++ @@ -176,6 +215,57 @@ func (m *GCMonitor) HeapObjectsBytes() uint64 { return m.heapBytes } +// AllocsPerFrame returns the average number of heap objects allocated per frame across the retained history window, or 0 when empty. +func (m *GCMonitor) AllocsPerFrame() float64 { + if m == nil || m.count == 0 { + return 0 + } + return float64(m.recentAllocs) / float64(m.count) +} + +// AllocBytesPerFrame returns the average number of heap bytes allocated per frame across the retained history window, or 0 when empty. +func (m *GCMonitor) AllocBytesPerFrame() float64 { + if m == nil || m.count == 0 { + return 0 + } + return float64(m.recentAllocBytes) / float64(m.count) +} + +// Reset clears retained GC frame history, hitch counts and peak pause timings, and re-baselines runtime/metrics counters to the current point in time. +func (m *GCMonitor) Reset() { + if m == nil { + return + } + m.head = 0 + m.count = 0 + m.recentHitches = 0 + m.recentAllocs = 0 + m.recentAllocBytes = 0 + m.lastPause = 0 + m.maxPause = 0 + + metrics.Read(m.samples[:]) + if m.samples[0].Value.Kind() == metrics.KindFloat64Histogram { + if h := m.samples[0].Value.Float64Histogram(); h != nil && len(h.Counts) == len(m.prevPauseCounts) { + copy(m.prevPauseCounts, h.Counts) + } + } + if m.samples[1].Value.Kind() == metrics.KindUint64 { + c := m.samples[1].Value.Uint64() + m.prevCycles = c + m.totalCycles = c + } + if m.samples[2].Value.Kind() == metrics.KindUint64 { + m.heapBytes = m.samples[2].Value.Uint64() + } + if m.samples[3].Value.Kind() == metrics.KindUint64 { + m.prevAllocsObjects = m.samples[3].Value.Uint64() + } + if m.samples[4].Value.Kind() == metrics.KindUint64 { + m.prevAllocsBytes = m.samples[4].Value.Uint64() + } +} + // Len returns how many frame samples are currently retained in history. func (m *GCMonitor) Len() int { if m == nil { diff --git a/packages/game/debug/gc_release.go b/packages/game/debug/gc_release.go index 0728fcbf..41b7083f 100644 --- a/packages/game/debug/gc_release.go +++ b/packages/game/debug/gc_release.go @@ -33,6 +33,15 @@ func (*GCMonitor) RecentHitches() int { return 0 } // HeapObjectsBytes always returns 0 in release builds. func (*GCMonitor) HeapObjectsBytes() uint64 { return 0 } +// AllocsPerFrame always returns 0 in release builds. +func (*GCMonitor) AllocsPerFrame() float64 { return 0 } + +// AllocBytesPerFrame always returns 0 in release builds. +func (*GCMonitor) AllocBytesPerFrame() float64 { return 0 } + +// Reset is a no-op in release builds. +func (*GCMonitor) Reset() {} + // Len always returns 0 in release builds. func (*GCMonitor) Len() int { return 0 } diff --git a/packages/game/debug/gc_test.go b/packages/game/debug/gc_test.go index 06720aed..349c4c27 100644 --- a/packages/game/debug/gc_test.go +++ b/packages/game/debug/gc_test.go @@ -13,6 +13,8 @@ import ( "github.com/nsgo-dev/nsgo/nsgotest" ) +var gcTestAllocSink []byte + func TestGCMonitorSamplesAndDetectsHitch(t *testing.T) { m := debug.NewGCMonitor(8) beforeCycles := m.TotalCycles() @@ -46,6 +48,23 @@ func TestGCMonitorSamplesAndDetectsHitch(t *testing.T) { if m.Len() != 8 { t.Fatalf("Len() = %d after 13 samples with historyLen=8, want 8", m.Len()) } + + // Deliberate heap allocations are reflected in per-frame alloc averages and cleared by Reset. + gcTestAllocSink = make([]byte, 64<<10) + gcTestAllocSink[0] = 42 + allocSample := m.SampleFrame(16 * time.Millisecond) + gcTestAllocSink = nil + if allocSample.AllocsDelta == 0 || allocSample.AllocBytesDelta == 0 { + t.Fatalf("expected non-zero AllocsDelta/AllocBytesDelta after heap allocation, got %+v", allocSample) + } + if m.AllocsPerFrame() <= 0 || m.AllocBytesPerFrame() <= 0 { + t.Fatalf("AllocsPerFrame=%v AllocBytesPerFrame=%v, want > 0", m.AllocsPerFrame(), m.AllocBytesPerFrame()) + } + + m.Reset() + if m.Len() != 0 || m.RecentHitches() != 0 || m.LastPause() != 0 || m.MaxPause() != 0 || m.AllocsPerFrame() != 0 || m.AllocBytesPerFrame() != 0 { + t.Fatalf("GCMonitor not cleared after Reset: len=%d hitches=%d allocs=%v", m.Len(), m.RecentHitches(), m.AllocsPerFrame()) + } } func TestGCMonitorZeroAllocsSteadyState(t *testing.T) { diff --git a/packages/game/debug/overlay.go b/packages/game/debug/overlay.go index 2986efe9..76cd4590 100644 --- a/packages/game/debug/overlay.go +++ b/packages/game/debug/overlay.go @@ -22,11 +22,13 @@ type Overlay struct { stats FrameStats shapes ShapeOverlay - visible bool - frameTick uint64 - scenesTick uint64 - scenes []SceneSnapshot - lastScenes []SceneSnapshot + visible bool + frameTick uint64 + scenesTick uint64 + scenes []SceneSnapshot + lastScenes []SceneSnapshot + drawStats DrawStats + hasDrawStats bool attached *core.Scope visSig *core.Signal[bool] @@ -213,6 +215,56 @@ func (o *Overlay) GC() *GCMonitor { return o.opts.GC } +// SetDrawStats updates the overlay's pushed per-frame draw statistics and refreshes the visible overlay. It is used when Options.DrawStats is nil. +func (o *Overlay) SetDrawStats(s DrawStats) { + if o == nil { + return + } + o.drawStats = s + o.hasDrawStats = true + if o.visible { + o.frameTick++ + if o.frameSig != nil { + o.frameSig.Set(o.frameTick) + } + } +} + +// DrawStats returns the current per-frame draw statistics from Options.DrawStats if configured, or the most recent SetDrawStats value. +func (o *Overlay) DrawStats() DrawStats { + if o == nil { + return DrawStats{} + } + if o.opts.DrawStats != nil { + return o.opts.DrawStats() + } + return o.drawStats +} + +// HasDrawStats reports whether draw statistics have been configured via Options.DrawStats or pushed via SetDrawStats. +func (o *Overlay) HasDrawStats() bool { + if o == nil { + return false + } + return o.opts.DrawStats != nil || o.hasDrawStats +} + +// ResetStats clears the overlay's recorded frame timings and pushed draw statistics and refreshes the visible overlay. +func (o *Overlay) ResetStats() { + if o == nil { + return + } + o.stats.Reset() + o.drawStats = DrawStats{} + o.hasDrawStats = false + if o.visible { + o.frameTick++ + if o.frameSig != nil { + o.frameSig.Set(o.frameTick) + } + } +} + // SetScenes updates the scene inspector's snapshot list and immediately refreshes the inspector view. It is used when Options.Scenes is nil. func (o *Overlay) SetScenes(scenes []SceneSnapshot) { if o == nil { @@ -383,6 +435,7 @@ func (o *Overlay) View(cx *core.Scope) core.Node { if o.opts.GC != nil { children = append(children, o.gcSummaryView()) } + children = append(children, o.drawStatsView()) if o.opts.Profiler != nil { children = append(children, o.profilerScopesView()) } @@ -455,6 +508,7 @@ func (o *Overlay) gcSummaryView() core.Node { hitches := gc.RecentHitches() header := fmt.Sprintf("GC (%d cycles · %s heap)", gc.TotalCycles(), formatBytes(int64(gc.HeapObjectsBytes()))) line := fmt.Sprintf("last %.2fms · max %.2fms · hitches %d", ms(gc.LastPause()), ms(gc.MaxPause()), hitches) + allocLine := fmt.Sprintf("allocs %.1f/f (%s/f)", gc.AllocsPerFrame(), formatBytes(int64(gc.AllocBytesPerFrame()))) lineStyle := layerLabelStyle if hitches > 0 { lineStyle = gcHitchTextStyle @@ -462,12 +516,43 @@ func (o *Overlay) gcSummaryView() core.Node { return core.Group([]core.Node{ core.Text{Content: header, Style: sectionHeaderStyle}, core.Text{Content: line, Style: lineStyle}, + core.Text{Content: allocLine, Style: layerLabelStyle}, }) }), }, } } +func (o *Overlay) drawStatsView() core.Node { + return core.Show{ + When: func() bool { + if o.frameSig != nil { + _ = o.frameSig.Get() + } + return o.HasDrawStats() + }, + Then: func(cx *core.Scope) core.Node { + return core.View{ + TestID: "debug-draw-stats", + Style: sectionDividerStyle, + Children: []core.Node{ + core.Dynamic(func(cx *core.Scope) core.Node { + if o.frameSig != nil { + _ = o.frameSig.Get() + } + ds := o.DrawStats() + line := fmt.Sprintf("Draw: %d calls · %d sprites · %d batches", ds.DrawCalls, ds.Sprites, ds.Batches) + if ds.Triangles > 0 || ds.Vertices > 0 { + line += fmt.Sprintf(" · %d tris · %d verts", ds.Triangles, ds.Vertices) + } + return core.Text{Content: line, Style: layerLabelStyle} + }), + }, + } + }, + } +} + func (o *Overlay) profilerScopesView() core.Node { return core.View{ TestID: "debug-profiler", diff --git a/packages/game/debug/profiler.go b/packages/game/debug/profiler.go index 1ecc9398..aab8efc5 100644 --- a/packages/game/debug/profiler.go +++ b/packages/game/debug/profiler.go @@ -305,6 +305,24 @@ func (p *Profiler) RecordedFrames() int { return n } +// Reset clears all recorded scope timings, ring buffers and trace events. +func (p *Profiler) Reset() { + if p == nil { + return + } + p.mu.Lock() + clear(p.scopeIndex) + p.scopes = p.scopes[:0] + p.inFrame = false + p.completedFrames = 0 + p.depth = 0 + p.recording = false + p.recordTarget = 0 + p.recordedFrames = 0 + p.events = p.events[:0] + p.mu.Unlock() +} + // TopScopes returns up to limit scope summaries sorted descending by per-frame Total duration (then Avg, then Name). If limit <= 0, all scopes are returned. func (p *Profiler) TopScopes(limit int) []ScopeSummary { if p == nil { diff --git a/packages/game/debug/profiler_release.go b/packages/game/debug/profiler_release.go index 2ea619cd..0913d5df 100644 --- a/packages/game/debug/profiler_release.go +++ b/packages/game/debug/profiler_release.go @@ -55,6 +55,9 @@ func (*Profiler) Recording() bool { return false } // RecordedFrames always returns 0 in release builds. func (*Profiler) RecordedFrames() int { return 0 } +// Reset is a no-op in release builds. +func (*Profiler) Reset() {} + // TopScopes always returns nil in release builds. func (*Profiler) TopScopes(int) []ScopeSummary { return nil } diff --git a/packages/game/debug/profiler_test.go b/packages/game/debug/profiler_test.go index 7e114ee7..87908eae 100644 --- a/packages/game/debug/profiler_test.go +++ b/packages/game/debug/profiler_test.go @@ -60,6 +60,11 @@ func TestProfilerNestedScopesAndTopScopes(t *testing.T) { if len(all) != 3 || all[2].Name != "render" || all[2].Total != 4*time.Millisecond || all[2].Avg != 3*time.Millisecond { t.Fatalf("TopScopes(0) = %+v, want 3 scopes with render last", all) } + + p.Reset() + if got := p.TopScopes(0); len(got) != 0 { + t.Fatalf("TopScopes(0) after Reset = %+v, want empty", got) + } } func TestProfilerChromeTrace300Frames(t *testing.T) { diff --git a/packages/game/debug/release.go b/packages/game/debug/release.go index 786cbce4..62a93cc9 100644 --- a/packages/game/debug/release.go +++ b/packages/game/debug/release.go @@ -58,6 +58,18 @@ func (*Overlay) Memory() *MemoryTracker { return &releaseMemoryTracker } // GC returns a no-op GCMonitor in release builds. func (*Overlay) GC() *GCMonitor { return &releaseGCMonitor } +// SetDrawStats is a no-op in release builds. +func (*Overlay) SetDrawStats(DrawStats) {} + +// DrawStats always returns the zero DrawStats in release builds. +func (*Overlay) DrawStats() DrawStats { return DrawStats{} } + +// HasDrawStats always returns false in release builds. +func (*Overlay) HasDrawStats() bool { return false } + +// ResetStats is a no-op in release builds. +func (*Overlay) ResetStats() {} + // SetScenes is a no-op in release builds. func (*Overlay) SetScenes([]SceneSnapshot) {} diff --git a/packages/game/debug/types.go b/packages/game/debug/types.go index f7967448..8cc4136f 100644 --- a/packages/game/debug/types.go +++ b/packages/game/debug/types.go @@ -27,6 +27,22 @@ type Options struct { Memory *MemoryTracker // GC, when set, samples GC pauses each frame and highlights GC-hitched frames in the overlay. GC *GCMonitor + // DrawStats, when set, supplies live per-frame draw statistics displayed in the overlay and exposed to MCP performance readouts. + DrawStats func() DrawStats +} + +// DrawStats captures per-frame draw submission counts for overlay display and MCP performance readouts. +type DrawStats struct { + // DrawCalls is the number of draw calls submitted in the frame. + DrawCalls int + // Sprites is the number of sprites drawn in the frame. + Sprites int + // Batches is the number of sprite or instanced draw batches submitted in the frame. + Batches int + // Triangles is the number of triangles submitted in the frame. + Triangles uint64 + // Vertices is the number of vertices submitted in the frame. + Vertices uint64 } // FrameSample holds the measured durations of one rendered frame. @@ -189,6 +205,10 @@ type GCFrameSample struct { Pause time.Duration // HeapObjectsBytes is the live heap object bytes reported by /memory/classes/heap/objects:bytes. HeapObjectsBytes uint64 + // AllocsDelta is the number of heap objects allocated during this frame (/gc/heap/allocs:objects). + AllocsDelta uint64 + // AllocBytesDelta is the number of heap bytes allocated during this frame (/gc/heap/allocs:bytes). + AllocBytesDelta uint64 // Hitched reports whether a GC pause occurred during this frame. Hitched bool } diff --git a/packages/game/mcp/doc.go b/packages/game/mcp/doc.go index 8bdf9ce0..51d150a0 100644 --- a/packages/game/mcp/doc.go +++ b/packages/game/mcp/doc.go @@ -33,6 +33,9 @@ // - game_replay_play: replay a stored or inline YAML recording deterministically, optionally resetting and running to completion. // - game_replay_stop: stop an active replay playback cleanly. // - game_replay_list: list stored recordings with frame counts, seeds, step rates and metadata. +// - game_perf_readout: read live frame timing (FPS, frame/update/draw costs and percentiles), draw statistics, allocations per frame, heap/GC counters, asset memory, and optional frame history or profiler zones matching the debug overlay. +// - game_perf_zones: list named profiler timing zones sorted by recent per-frame cost. +// - game_perf_reset: reset accumulated debug overlay frame timings, pushed draw statistics, profiler zones and GC monitor history. // // Components registered on an [entities.World] with [entities.RegisterCodec] are readable and editable automatically. Transient or non-saved components can also be exposed with [RegisterComponent], [RegisterComponentFunc], [RegisterMutableComponent] or [RegisterComponentEditor], and built-in [entities.Transform2D], [entities.WorldTransform2D] and [sceneformat.ObjectRef] components are surfaced automatically when present and not already registered under another name. Prefabs can be registered via [Config.Prefabs], [Bridge.RegisterPrefab], [Bridge.RegisterEntityPrefab] or [Bridge.RegisterScenePrefab]. // diff --git a/packages/game/mcp/example_test.go b/packages/game/mcp/example_test.go index 206bdba5..2adcf0c3 100644 --- a/packages/game/mcp/example_test.go +++ b/packages/game/mcp/example_test.go @@ -66,4 +66,7 @@ func ExampleNew() { // game_replay_play // game_replay_stop // game_replay_list + // game_perf_readout + // game_perf_zones + // game_perf_reset } diff --git a/packages/game/mcp/mcp.go b/packages/game/mcp/mcp.go index a3d1cec8..910b8930 100644 --- a/packages/game/mcp/mcp.go +++ b/packages/game/mcp/mcp.go @@ -18,6 +18,7 @@ import ( "github.com/nsgo-dev/game/packages/game/entities" "github.com/nsgo-dev/game/packages/game/input" "github.com/nsgo-dev/game/packages/game/random" + "github.com/nsgo-dev/game/packages/game/render3d" "github.com/nsgo-dev/game/packages/game/scene" "github.com/nsgo-dev/game/packages/game/screen" "github.com/nsgo-dev/nsgo/automation" @@ -126,6 +127,24 @@ type Config struct { // Replay configures input recording and deterministic playback tools. Replay *ReplayController + + // Overlay is the game's development debug overlay for frame timing, draw statistics, GC/allocation and asset memory readouts. + Overlay *debug.Overlay + + // Profiler is a named-scope timing profiler. When nil, performance tools fall back to Overlay.Profiler(). + Profiler *debug.Profiler + + // GC is a per-frame GC and allocation monitor. When nil, performance tools fall back to Overlay.GC(). + GC *debug.GCMonitor + + // Memory is an asset memory tracker. When nil, performance tools fall back to Overlay.Memory(). + Memory *debug.MemoryTracker + + // DrawStatsFunc dynamically supplies per-frame draw statistics (draw calls, sprites, batches, triangles, vertices). When nil, performance tools fall back to Overlay.DrawStats() or RenderStatsFunc. + DrawStatsFunc func() debug.DrawStats + + // RenderStatsFunc dynamically supplies 3D per-frame render statistics (culling, batching, state switches, geometry and GPU memory). + RenderStatsFunc func() render3d.RenderStats } type compTypeKey any @@ -299,6 +318,7 @@ func (b *Bridge) Tools() []automation.Tool { out = append(out, b.consoleTools()...) out = append(out, b.editTools()...) out = append(out, b.replayTools()...) + out = append(out, b.perfTools()...) return out } diff --git a/packages/game/mcp/perf.go b/packages/game/mcp/perf.go new file mode 100644 index 00000000..a88b38c8 --- /dev/null +++ b/packages/game/mcp/perf.go @@ -0,0 +1,534 @@ +package mcp + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "slices" + "time" + + "github.com/nsgo-dev/game/packages/game/debug" + "github.com/nsgo-dev/game/packages/game/render3d" + "github.com/nsgo-dev/nsgo/automation" +) + +// Performance readout tool names registered by Bridge with github.com/nsgo-dev/nsgo/automation. +const ( + // ToolPerfReadout reads live frame timing, draw statistics, allocation/GC telemetry, and optional frame history or profiler zones. + ToolPerfReadout = "game_perf_readout" + // ToolPerfZones lists named profiler timing zones sorted by recent cost. + ToolPerfZones = "game_perf_zones" + // ToolPerfReset resets accumulated overlay frame stats, profiler zones, and GC monitor history. + ToolPerfReset = "game_perf_reset" +) + +// PerfSources reports which telemetry providers contributed to a performance readout. +type PerfSources struct { + Overlay bool `json:"overlay"` + Profiler bool `json:"profiler"` + GC bool `json:"gc"` + Memory bool `json:"memory"` + DrawStats bool `json:"draw_stats"` + Render3D bool `json:"render3d"` +} + +// PerfFrameSample is one chronological frame timing entry from the debug overlay's ring buffer. +type PerfFrameSample struct { + FrameMs float64 `json:"frame_ms"` + UpdateMs float64 `json:"update_ms"` + DrawMs float64 `json:"draw_ms"` + GCHitch bool `json:"gc_hitch,omitempty"` +} + +// PerfZoneInfo summarizes one named timing scope from debug.Profiler. +type PerfZoneInfo struct { + Name string `json:"name"` + LastMs float64 `json:"last_ms"` + AvgMs float64 `json:"avg_ms"` + MaxMs float64 `json:"max_ms"` + Calls int `json:"calls"` +} + +// PerfRender3DStats mirrors render3d.RenderStats in snake_case JSON form. +type PerfRender3DStats struct { + TotalItems int `json:"total_items"` + CulledItems int `json:"culled_items"` + Occluded int `json:"occluded"` + VisibleItems int `json:"visible_items"` + OpaqueDraws int `json:"opaque_draws"` + TransparentDraws int `json:"transparent_draws"` + InstancedBatches int `json:"instanced_batches"` + TotalDrawCalls int `json:"total_draw_calls"` + Triangles uint64 `json:"triangles"` + Vertices uint64 `json:"vertices"` + MaterialSwitches int `json:"material_switches"` + PipelineSwitches int `json:"pipeline_switches"` + TextureBytes uint64 `json:"texture_bytes"` + BufferBytes uint64 `json:"buffer_bytes"` +} + +// PerfMemoryGroup summarizes tracked asset memory for one debug.MemoryTracker group. +type PerfMemoryGroup struct { + Group string `json:"group"` + TotalBytes int64 `json:"total_bytes"` + Budget int64 `json:"budget,omitempty"` + OverBudget bool `json:"over_budget,omitempty"` + Count int `json:"count"` + ByKind map[string]int64 `json:"by_kind,omitempty"` +} + +// PerfMemorySummary summarizes tracked asset memory from a debug.MemoryTracker. +type PerfMemorySummary struct { + TotalBytes int64 `json:"total_bytes"` + TotalBudget int64 `json:"total_budget,omitempty"` + OverBudget bool `json:"over_budget,omitempty"` + Groups []PerfMemoryGroup `json:"groups"` +} + +// PerfReadoutResult is the JSON result of game_perf_readout. +type PerfReadoutResult struct { + FPS float64 `json:"fps"` + FrameMs float64 `json:"frame_ms"` + UpdateMs float64 `json:"update_ms"` + DrawMs float64 `json:"draw_ms"` + SampleCount int `json:"sample_count"` + LatestFrameMs float64 `json:"latest_frame_ms"` + LatestUpdateMs float64 `json:"latest_update_ms"` + LatestDrawMs float64 `json:"latest_draw_ms"` + MinFrameMs float64 `json:"min_frame_ms"` + MaxFrameMs float64 `json:"max_frame_ms"` + P50FrameMs float64 `json:"p50_frame_ms"` + P95FrameMs float64 `json:"p95_frame_ms"` + P99FrameMs float64 `json:"p99_frame_ms"` + + DrawCalls int `json:"draw_calls"` + Sprites int `json:"sprites"` + Batches int `json:"batches"` + Triangles uint64 `json:"triangles"` + Vertices uint64 `json:"vertices"` + + AllocsPerFrame float64 `json:"allocs_per_frame"` + AllocBytesPerFrame float64 `json:"alloc_bytes_per_frame"` + LastFrameAllocs uint64 `json:"last_frame_allocs"` + LastFrameAllocBytes uint64 `json:"last_frame_alloc_bytes"` + HeapBytes uint64 `json:"heap_bytes"` + GCCount uint64 `json:"gc_count"` + GCLastPauseMs float64 `json:"gc_last_pause_ms"` + GCMaxPauseMs float64 `json:"gc_max_pause_ms"` + GCRecentHitches int `json:"gc_recent_hitches"` + + Render3D *PerfRender3DStats `json:"render3d,omitempty"` + AssetMemory *PerfMemorySummary `json:"asset_memory,omitempty"` + History []PerfFrameSample `json:"history,omitempty"` + Zones []PerfZoneInfo `json:"zones,omitempty"` + Sources PerfSources `json:"sources"` +} + +// PerfZonesResult is the JSON result of game_perf_zones. +type PerfZonesResult struct { + Recording bool `json:"recording"` + RecordedFrames int `json:"recorded_frames"` + Total int `json:"total"` + Zones []PerfZoneInfo `json:"zones"` +} + +// PerfResetResult is the JSON result of game_perf_reset. +type PerfResetResult struct { + ResetFrameStats bool `json:"reset_frame_stats"` + ResetProfiler bool `json:"reset_profiler"` + ResetGC bool `json:"reset_gc"` + ResetDrawStats bool `json:"reset_draw_stats"` +} + +var ( + schemaPerfReadout = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "properties": { + "include_history": { + "type": "boolean", + "description": "Include chronological per-frame timing samples from the debug overlay ring buffer (default false)." + }, + "history_limit": { + "type": "integer", + "minimum": 0, + "description": "Maximum number of most recent frame samples to return when include_history is true (omit or 0 for all retained samples)." + }, + "include_zones": { + "type": "boolean", + "description": "Include per-zone timing summaries from the debug profiler if configured (default false)." + }, + "zones_limit": { + "type": "integer", + "minimum": 0, + "description": "Maximum number of top timing zones to return when include_zones is true (omit or 0 for all zones)." + } + } + }`) + + schemaPerfZones = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "properties": { + "limit": { + "type": "integer", + "minimum": 0, + "description": "Maximum number of top zones to return, sorted by recent frame cost (omit or 0 for all zones)." + } + } + }`) + + schemaPerfReset = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "properties": {} + }`) +) + +func (b *Bridge) perfTools() []automation.Tool { + return []automation.Tool{ + { + Name: ToolPerfReadout, + Description: "Read live performance metrics matching the debug overlay: FPS, frame/update/draw durations and percentiles, draw statistics, allocations per frame, heap/GC counters, asset memory, and optional frame history or profiler zones.", + InputSchema: schemaPerfReadout, + Handler: b.handlePerfReadout, + }, + { + Name: ToolPerfZones, + Description: "List named profiler timing zones sorted by recent per-frame cost (last, rolling average, peak milliseconds and call count).", + InputSchema: schemaPerfZones, + Handler: b.handlePerfZones, + }, + { + Name: ToolPerfReset, + Description: "Reset accumulated debug overlay frame timings, pushed draw statistics, profiler zones and GC monitor history.", + InputSchema: schemaPerfReset, + Handler: b.handlePerfReset, + }, + } +} + +func (b *Bridge) activeProfiler() *debug.Profiler { + if b == nil { + return nil + } + if b.cfg.Profiler != nil { + return b.cfg.Profiler + } + if b.cfg.Overlay != nil { + return b.cfg.Overlay.Profiler() + } + return nil +} + +func (b *Bridge) activeGC() *debug.GCMonitor { + if b == nil { + return nil + } + if b.cfg.GC != nil { + return b.cfg.GC + } + if b.cfg.Overlay != nil { + return b.cfg.Overlay.GC() + } + return nil +} + +func (b *Bridge) activeMemory() *debug.MemoryTracker { + if b == nil { + return nil + } + if b.cfg.Memory != nil { + return b.cfg.Memory + } + if b.cfg.Overlay != nil { + return b.cfg.Overlay.Memory() + } + return nil +} + +func (b *Bridge) hasPerfSource() bool { + if b == nil { + return false + } + return b.cfg.Overlay != nil || + b.cfg.Profiler != nil || + b.cfg.GC != nil || + b.cfg.Memory != nil || + b.cfg.DrawStatsFunc != nil || + b.cfg.RenderStatsFunc != nil +} + +type perfReadoutArgs struct { + IncludeHistory bool `json:"include_history"` + HistoryLimit int `json:"history_limit"` + IncludeZones bool `json:"include_zones"` + ZonesLimit int `json:"zones_limit"` +} + +func (b *Bridge) handlePerfReadout(_ context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[perfReadoutArgs](raw) + if err != nil { + return nil, err + } + if args.HistoryLimit < 0 { + return nil, fmt.Errorf("mcp: history_limit must be >= 0 (got %d)", args.HistoryLimit) + } + if args.ZonesLimit < 0 { + return nil, fmt.Errorf("mcp: zones_limit must be >= 0 (got %d)", args.ZonesLimit) + } + if !b.hasPerfSource() { + return nil, errors.New("mcp: no performance telemetry configured") + } + + var res PerfReadoutResult + + if ov := b.cfg.Overlay; ov != nil { + res.Sources.Overlay = true + stats := ov.Stats() + if stats != nil { + n := stats.Len() + res.SampleCount = n + res.FPS = stats.FPS() + avg := stats.Average() + res.FrameMs = durationMs(avg.Total) + res.UpdateMs = durationMs(avg.Update) + res.DrawMs = durationMs(avg.Draw) + + latest := stats.Latest() + res.LatestFrameMs = durationMs(latest.Total) + res.LatestUpdateMs = durationMs(latest.Update) + res.LatestDrawMs = durationMs(latest.Draw) + + if n > 0 { + samples := stats.Samples(make([]debug.FrameSample, 0, n)) + totals := make([]time.Duration, len(samples)) + for i, s := range samples { + totals[i] = s.Total + } + slices.Sort(totals) + res.MinFrameMs = durationMs(totals[0]) + res.MaxFrameMs = durationMs(totals[len(totals)-1]) + res.P50FrameMs = durationMs(percentileDuration(totals, 50)) + res.P95FrameMs = durationMs(percentileDuration(totals, 95)) + res.P99FrameMs = durationMs(percentileDuration(totals, 99)) + + if args.IncludeHistory { + start := 0 + if args.HistoryLimit > 0 && args.HistoryLimit < len(samples) { + start = len(samples) - args.HistoryLimit + } + hist := make([]PerfFrameSample, 0, len(samples)-start) + for _, s := range samples[start:] { + hist = append(hist, PerfFrameSample{ + FrameMs: durationMs(s.Total), + UpdateMs: durationMs(s.Update), + DrawMs: durationMs(s.Draw), + GCHitch: s.GCHitch, + }) + } + res.History = hist + } + } + } + } + + if b.cfg.DrawStatsFunc != nil { + ds := b.cfg.DrawStatsFunc() + res.Sources.DrawStats = true + res.DrawCalls = ds.DrawCalls + res.Sprites = ds.Sprites + res.Batches = ds.Batches + res.Triangles = ds.Triangles + res.Vertices = ds.Vertices + } else if b.cfg.Overlay != nil && b.cfg.Overlay.HasDrawStats() { + ds := b.cfg.Overlay.DrawStats() + res.Sources.DrawStats = true + res.DrawCalls = ds.DrawCalls + res.Sprites = ds.Sprites + res.Batches = ds.Batches + res.Triangles = ds.Triangles + res.Vertices = ds.Vertices + } + + if b.cfg.RenderStatsFunc != nil { + rs := b.cfg.RenderStatsFunc() + res.Sources.Render3D = true + res.Render3D = render3DStatsFrom(rs) + if !res.Sources.DrawStats { + res.DrawCalls = rs.TotalDrawCalls + res.Batches = rs.InstancedBatches + res.Triangles = rs.Triangles + res.Vertices = rs.Vertices + } + } + + if gc := b.activeGC(); gc != nil { + res.Sources.GC = true + res.AllocsPerFrame = gc.AllocsPerFrame() + res.AllocBytesPerFrame = gc.AllocBytesPerFrame() + latestGC := gc.Latest() + res.LastFrameAllocs = latestGC.AllocsDelta + res.LastFrameAllocBytes = latestGC.AllocBytesDelta + res.HeapBytes = gc.HeapObjectsBytes() + res.GCCount = gc.TotalCycles() + res.GCLastPauseMs = durationMs(gc.LastPause()) + res.GCMaxPauseMs = durationMs(gc.MaxPause()) + res.GCRecentHitches = gc.RecentHitches() + } + + if mem := b.activeMemory(); mem != nil { + res.Sources.Memory = true + res.AssetMemory = memorySummaryFrom(mem) + } + + if p := b.activeProfiler(); p != nil { + res.Sources.Profiler = true + if args.IncludeZones { + res.Zones, _ = collectZones(p, args.ZonesLimit) + } + } + + return res, nil +} + +type perfZonesArgs struct { + Limit int `json:"limit"` +} + +func (b *Bridge) handlePerfZones(_ context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[perfZonesArgs](raw) + if err != nil { + return nil, err + } + if args.Limit < 0 { + return nil, fmt.Errorf("mcp: limit must be >= 0 (got %d)", args.Limit) + } + p := b.activeProfiler() + if p == nil { + return nil, errors.New("mcp: no profiler configured") + } + zones, total := collectZones(p, args.Limit) + return PerfZonesResult{ + Recording: p.Recording(), + RecordedFrames: p.RecordedFrames(), + Total: total, + Zones: zones, + }, nil +} + +func (b *Bridge) handlePerfReset(_ context.Context, raw json.RawMessage) (any, error) { + if _, err := decodeArgs[struct{}](raw); err != nil { + return nil, err + } + if !b.hasPerfSource() { + return nil, errors.New("mcp: no performance telemetry configured") + } + + var res PerfResetResult + if ov := b.cfg.Overlay; ov != nil { + hadDraw := ov.HasDrawStats() + ov.ResetStats() + res.ResetFrameStats = true + if hadDraw && !ov.HasDrawStats() { + res.ResetDrawStats = true + } + } + if p := b.activeProfiler(); p != nil { + p.Reset() + res.ResetProfiler = true + } + if gc := b.activeGC(); gc != nil { + gc.Reset() + res.ResetGC = true + } + return res, nil +} + +func collectZones(p *debug.Profiler, limit int) ([]PerfZoneInfo, int) { + all := p.TopScopes(0) + total := len(all) + if limit > 0 && len(all) > limit { + all = all[:limit] + } + zones := make([]PerfZoneInfo, 0, len(all)) + for _, sc := range all { + zones = append(zones, PerfZoneInfo{ + Name: sc.Name, + LastMs: durationMs(sc.Total), + AvgMs: durationMs(sc.Avg), + MaxMs: durationMs(sc.Max), + Calls: sc.Calls, + }) + } + return zones, total +} + +func render3DStatsFrom(rs render3d.RenderStats) *PerfRender3DStats { + return &PerfRender3DStats{ + TotalItems: rs.TotalItems, + CulledItems: rs.CulledItems, + Occluded: rs.Occluded, + VisibleItems: rs.VisibleItems, + OpaqueDraws: rs.OpaqueDraws, + TransparentDraws: rs.TransparentDraws, + InstancedBatches: rs.InstancedBatches, + TotalDrawCalls: rs.TotalDrawCalls, + Triangles: rs.Triangles, + Vertices: rs.Vertices, + MaterialSwitches: rs.MaterialSwitches, + PipelineSwitches: rs.PipelineSwitches, + TextureBytes: rs.TextureBytes, + BufferBytes: rs.BufferBytes, + } +} + +func memorySummaryFrom(mem *debug.MemoryTracker) *PerfMemorySummary { + total := mem.TotalBytes() + budget := mem.TotalBudget() + rawGroups := mem.Groups() + groups := make([]PerfMemoryGroup, 0, len(rawGroups)) + for _, g := range rawGroups { + var byKind map[string]int64 + if len(g.ByKind) > 0 { + byKind = make(map[string]int64, len(g.ByKind)) + for kind, bytes := range g.ByKind { + byKind[kind.String()] = bytes + } + } + groups = append(groups, PerfMemoryGroup{ + Group: g.Group, + TotalBytes: g.TotalBytes, + Budget: g.Budget, + OverBudget: g.OverBudget, + Count: g.Count, + ByKind: byKind, + }) + } + return &PerfMemorySummary{ + TotalBytes: total, + TotalBudget: budget, + OverBudget: budget > 0 && total > budget, + Groups: groups, + } +} + +func durationMs(d time.Duration) float64 { + return float64(d) / float64(time.Millisecond) +} + +func percentileDuration(sorted []time.Duration, pct int) time.Duration { + n := len(sorted) + if n == 0 { + return 0 + } + idx := (pct*(n-1) + 99) / 100 + if idx < 0 { + idx = 0 + } + if idx >= n { + idx = n - 1 + } + return sorted[idx] +} diff --git a/packages/game/mcp/perf_test.go b/packages/game/mcp/perf_test.go new file mode 100644 index 00000000..6d129bda --- /dev/null +++ b/packages/game/mcp/perf_test.go @@ -0,0 +1,487 @@ +package mcp_test + +import ( + "encoding/json" + "fmt" + "math" + "runtime" + "strings" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/debug" + "github.com/nsgo-dev/game/packages/game/mcp" + "github.com/nsgo-dev/game/packages/game/render3d" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func ms(d time.Duration) float64 { + return float64(d) / float64(time.Millisecond) +} + +func approxEqual(a, b, tol float64) bool { + return math.Abs(a-b) <= tol +} + +// TestPerfReadoutMatchesDebugOverlay verifies that game_perf_readout returns +// values matching debug.Overlay's frame timing, draw statistics, GC/allocation +// counters, asset memory, and profiler scopes, including the rendered overlay HUD. +func TestPerfReadoutMatchesDebugOverlay(t *testing.T) { + now := time.Unix(5000, 0) + prof := debug.NewProfiler(60) + prof.SetNow(func() time.Time { return now }) + + gcMon := debug.NewGCMonitor(debug.FrameHistory) + mem := debug.NewMemoryTracker() + mem.SetTotalBudget(2 << 20) + mem.SetBudget("level1", 1<<20) + mem.Track("level1", "tiles.png", debug.AssetImage, 256<<10) + mem.Track("level1", "sprites.atlas", debug.AssetAtlas, 128<<10) + mem.Track("audio", "bgm.pcm", debug.AssetAudio, 512<<10) + + drawStats := debug.DrawStats{ + DrawCalls: 14, + Sprites: 320, + Batches: 4, + Triangles: 640, + Vertices: 1280, + } + + overlay := debug.New(debug.Options{ + Visible: true, + Profiler: prof, + GC: gcMon, + Memory: mem, + DrawStats: func() debug.DrawStats { return drawStats }, + }) + + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{ + Overlay: overlay, + }); err != nil { + t.Fatal(err) + } + return core.View{ + Style: core.Style{Width: core.Pt(400), Height: core.Pt(300)}, + Children: []core.Node{overlay.View(cx)}, + } + }) + + type frameInput struct { + total, update, draw time.Duration + phys, render, ai time.Duration + allocBytes int + triggerGC bool + } + frames := []frameInput{ + {total: 10 * time.Millisecond, update: 3 * time.Millisecond, draw: 2 * time.Millisecond, phys: 2 * time.Millisecond, render: 2 * time.Millisecond, ai: 1 * time.Millisecond}, + {total: 15 * time.Millisecond, update: 4 * time.Millisecond, draw: 3 * time.Millisecond, phys: 3 * time.Millisecond, render: 3 * time.Millisecond, ai: 1 * time.Millisecond, allocBytes: 4096}, + {total: 20 * time.Millisecond, update: 5 * time.Millisecond, draw: 4 * time.Millisecond, phys: 4 * time.Millisecond, render: 4 * time.Millisecond, ai: 1 * time.Millisecond}, + {total: 25 * time.Millisecond, update: 6 * time.Millisecond, draw: 5 * time.Millisecond, phys: 5 * time.Millisecond, render: 4 * time.Millisecond, ai: 2 * time.Millisecond, triggerGC: true}, + {total: 30 * time.Millisecond, update: 7 * time.Millisecond, draw: 6 * time.Millisecond, phys: 6 * time.Millisecond, render: 5 * time.Millisecond, ai: 2 * time.Millisecond, allocBytes: 8192}, + } + + var escapeSink [][]byte + app.Post(func() { + for _, f := range frames { + prof.BeginFrame() + tPhys := prof.Begin("physics") + now = now.Add(f.phys) + prof.End(tPhys) + + tRender := prof.Begin("render") + now = now.Add(f.render) + prof.End(tRender) + + tAI := prof.Begin("ai") + now = now.Add(f.ai) + prof.End(tAI) + prof.EndFrame() + + if f.allocBytes > 0 { + buf := make([]byte, f.allocBytes) + buf[0] = 1 + escapeSink = append(escapeSink, buf) + } + if f.triggerGC { + runtime.GC() + } + overlay.RecordFrame(f.total, f.update, f.draw) + } + }) + app.Settle() + runtime.KeepAlive(escapeSink) + + // Read default readout (without history or zones). + res := callTool[mcp.PerfReadoutResult](t, app, cx, mcp.ToolPerfReadout, nil) + + stats := overlay.Stats() + avg := stats.Average() + latest := stats.Latest() + + if !res.Sources.Overlay || !res.Sources.Profiler || !res.Sources.GC || !res.Sources.Memory || !res.Sources.DrawStats || res.Sources.Render3D { + t.Fatalf("sources = %+v, want overlay/profiler/gc/memory/draw_stats=true render3d=false", res.Sources) + } + if res.SampleCount != stats.Len() || res.SampleCount != 5 { + t.Fatalf("sample_count = %d, want %d", res.SampleCount, stats.Len()) + } + if res.FPS != stats.FPS() { + t.Fatalf("fps = %v, want overlay %v", res.FPS, stats.FPS()) + } + if res.FrameMs != ms(avg.Total) || res.UpdateMs != ms(avg.Update) || res.DrawMs != ms(avg.Draw) { + t.Fatalf("avg = (%.4f, %.4f, %.4f), want (%.4f, %.4f, %.4f)", + res.FrameMs, res.UpdateMs, res.DrawMs, ms(avg.Total), ms(avg.Update), ms(avg.Draw)) + } + if res.LatestFrameMs != ms(latest.Total) || res.LatestUpdateMs != ms(latest.Update) || res.LatestDrawMs != ms(latest.Draw) { + t.Fatalf("latest = (%.4f, %.4f, %.4f), want (%.4f, %.4f, %.4f)", + res.LatestFrameMs, res.LatestUpdateMs, res.LatestDrawMs, ms(latest.Total), ms(latest.Update), ms(latest.Draw)) + } + // Sorted totals: [10, 15, 20, 25, 30] ms -> min=10, p50=20, p95=30, p99=30, max=30. + if res.MinFrameMs != 10 || res.MaxFrameMs != ms(stats.MaxTotal()) || res.P50FrameMs != 20 || res.P95FrameMs != 30 || res.P99FrameMs != 30 { + t.Fatalf("percentiles = min:%v p50:%v p95:%v p99:%v max:%v, want 10/20/30/30/30", + res.MinFrameMs, res.P50FrameMs, res.P95FrameMs, res.P99FrameMs, res.MaxFrameMs) + } + + // Verify the rendered debug overlay HUD text matches the MCP readout verbatim. + wantHUD := fmt.Sprintf("%.1f fps · %.2f ms (upd %.2f / drw %.2f)", res.FPS, res.FrameMs, res.UpdateMs, res.DrawMs) + if gotHUD := app.Find("debug-frame-stats").Text; gotHUD != wantHUD { + t.Fatalf("overlay HUD text = %q, MCP formatted = %q", gotHUD, wantHUD) + } + + // Draw statistics match debug.Overlay.DrawStats(). + wantDraw := overlay.DrawStats() + if res.DrawCalls != wantDraw.DrawCalls || res.Sprites != wantDraw.Sprites || res.Batches != wantDraw.Batches || res.Triangles != wantDraw.Triangles || res.Vertices != wantDraw.Vertices { + t.Fatalf("draw stats = (%d,%d,%d,%d,%d), want %+v", + res.DrawCalls, res.Sprites, res.Batches, res.Triangles, res.Vertices, wantDraw) + } + if !app.Exists("debug-draw-stats") { + t.Fatal("expected debug-draw-stats section in visible overlay") + } + + // GC & allocation readouts match debug.GCMonitor exactly. + if res.AllocsPerFrame != gcMon.AllocsPerFrame() || res.AllocBytesPerFrame != gcMon.AllocBytesPerFrame() { + t.Fatalf("allocs/frame = (%v, %v), want (%v, %v)", + res.AllocsPerFrame, res.AllocBytesPerFrame, gcMon.AllocsPerFrame(), gcMon.AllocBytesPerFrame()) + } + if res.AllocsPerFrame <= 0 || res.AllocBytesPerFrame <= 0 { + t.Fatalf("expected positive allocations per frame after deliberate heap allocs, got (%v, %v)", + res.AllocsPerFrame, res.AllocBytesPerFrame) + } + if res.LastFrameAllocs != gcMon.Latest().AllocsDelta || res.LastFrameAllocBytes != gcMon.Latest().AllocBytesDelta { + t.Fatalf("last frame allocs = (%d, %d), want (%d, %d)", + res.LastFrameAllocs, res.LastFrameAllocBytes, gcMon.Latest().AllocsDelta, gcMon.Latest().AllocBytesDelta) + } + if res.HeapBytes != gcMon.HeapObjectsBytes() || res.HeapBytes == 0 { + t.Fatalf("heap_bytes = %d, want overlay %d (>0)", res.HeapBytes, gcMon.HeapObjectsBytes()) + } + if res.GCCount != gcMon.TotalCycles() || res.GCCount == 0 { + t.Fatalf("gc_count = %d, want overlay %d (>0)", res.GCCount, gcMon.TotalCycles()) + } + if res.GCLastPauseMs != ms(gcMon.LastPause()) || res.GCMaxPauseMs != ms(gcMon.MaxPause()) || res.GCRecentHitches != gcMon.RecentHitches() || res.GCRecentHitches < 1 { + t.Fatalf("gc pauses/hitches = (last=%v max=%v hitches=%d), want (%v, %v, %d)", + res.GCLastPauseMs, res.GCMaxPauseMs, res.GCRecentHitches, ms(gcMon.LastPause()), ms(gcMon.MaxPause()), gcMon.RecentHitches()) + } + + // Asset memory matches debug.MemoryTracker exactly. + if res.AssetMemory == nil || res.AssetMemory.TotalBytes != mem.TotalBytes() || res.AssetMemory.TotalBudget != mem.TotalBudget() || res.AssetMemory.OverBudget { + t.Fatalf("asset_memory = %+v, want total=%d budget=%d", res.AssetMemory, mem.TotalBytes(), mem.TotalBudget()) + } + if len(res.AssetMemory.Groups) != 2 || res.AssetMemory.Groups[0].Group != "audio" || res.AssetMemory.Groups[1].Group != "level1" { + t.Fatalf("asset_memory.groups = %+v", res.AssetMemory.Groups) + } + if res.AssetMemory.Groups[1].ByKind["image"] != 256<<10 || res.AssetMemory.Groups[1].ByKind["atlas"] != 128<<10 { + t.Fatalf("level1 by_kind = %+v", res.AssetMemory.Groups[1].ByKind) + } + + // Default readout omits history and zones. + if len(res.History) != 0 || len(res.Zones) != 0 { + t.Fatalf("expected history and zones omitted by default, got len(history)=%d len(zones)=%d", len(res.History), len(res.Zones)) + } + + // Request with include_history + history_limit and include_zones + zones_limit. + detailed := callTool[mcp.PerfReadoutResult](t, app, cx, mcp.ToolPerfReadout, map[string]any{ + "include_history": true, + "history_limit": 3, + "include_zones": true, + "zones_limit": 2, + }) + if len(detailed.History) != 3 { + t.Fatalf("len(history) = %d, want 3", len(detailed.History)) + } + // Last 3 frames are frames[2], frames[3] (GC hitch), frames[4]. + if detailed.History[0].FrameMs != 20 || detailed.History[1].FrameMs != 25 || !detailed.History[1].GCHitch || detailed.History[2].FrameMs != 30 { + t.Fatalf("history tail = %+v, want [20ms, 25ms+hitch, 30ms]", detailed.History) + } + if len(detailed.Zones) != 2 { + t.Fatalf("len(zones) = %d, want 2", len(detailed.Zones)) + } + wantTop := prof.TopScopes(2) + for i, want := range wantTop { + got := detailed.Zones[i] + if got.Name != want.Name || got.LastMs != ms(want.Total) || got.AvgMs != ms(want.Avg) || got.MaxMs != ms(want.Max) || got.Calls != want.Calls { + t.Fatalf("zone[%d] = %+v, want %+v", i, got, want) + } + } +} + +func TestPerfZonesAndReset(t *testing.T) { + now := time.Unix(6000, 0) + prof := debug.NewProfiler(30) + prof.SetNow(func() time.Time { return now }) + gcMon := debug.NewGCMonitor(16) + overlay := debug.New(debug.Options{ + Visible: true, + Profiler: prof, + GC: gcMon, + }) + + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{Overlay: overlay}); err != nil { + t.Fatal(err) + } + return core.View{ + Style: core.Style{Width: core.Pt(400), Height: core.Pt(300)}, + Children: []core.Node{overlay.View(cx)}, + } + }) + + app.Post(func() { + prof.StartRecording(10) + for _, physMs := range []time.Duration{2 * time.Millisecond, 6 * time.Millisecond} { + prof.BeginFrame() + t1 := prof.Begin("physics") + now = now.Add(physMs) + prof.End(t1) + t2 := prof.Begin("render") + now = now.Add(3 * time.Millisecond) + prof.End(t2) + t3 := prof.Begin("audio") + now = now.Add(1 * time.Millisecond) + prof.End(t3) + prof.EndFrame() + overlay.RecordFrame(16*time.Millisecond, physMs, 3*time.Millisecond) + } + overlay.SetDrawStats(debug.DrawStats{DrawCalls: 9, Sprites: 50, Batches: 2}) + }) + app.Settle() + + // All zones. + zonesAll := callTool[mcp.PerfZonesResult](t, app, cx, mcp.ToolPerfZones, nil) + if !zonesAll.Recording || zonesAll.RecordedFrames != 2 || zonesAll.Total != 3 || len(zonesAll.Zones) != 3 { + t.Fatalf("zonesAll = %+v, want recording=true recorded=2 total=3 len=3", zonesAll) + } + if zonesAll.Zones[0].Name != "physics" || !approxEqual(zonesAll.Zones[0].LastMs, 6, 1e-6) || !approxEqual(zonesAll.Zones[0].AvgMs, 4, 1e-6) || !approxEqual(zonesAll.Zones[0].MaxMs, 6, 1e-6) || zonesAll.Zones[0].Calls != 1 { + t.Fatalf("zonesAll[0] = %+v, want physics last=6 avg=4 max=6 calls=1", zonesAll.Zones[0]) + } + + // Limited zones still reports Total == 3. + zonesTop1 := callTool[mcp.PerfZonesResult](t, app, cx, mcp.ToolPerfZones, map[string]any{"limit": 1}) + if zonesTop1.Total != 3 || len(zonesTop1.Zones) != 1 || zonesTop1.Zones[0].Name != "physics" { + t.Fatalf("zonesTop1 = %+v", zonesTop1) + } + + // Reset clears overlay frame stats, pushed draw stats, profiler zones and GC history. + resetRes := callTool[mcp.PerfResetResult](t, app, cx, mcp.ToolPerfReset, nil) + if !resetRes.ResetFrameStats || !resetRes.ResetProfiler || !resetRes.ResetGC || !resetRes.ResetDrawStats { + t.Fatalf("resetRes = %+v, want all true", resetRes) + } + + after := callTool[mcp.PerfReadoutResult](t, app, cx, mcp.ToolPerfReadout, map[string]any{ + "include_history": true, + "include_zones": true, + }) + if after.SampleCount != 0 || after.FPS != 0 || after.FrameMs != 0 || after.DrawCalls != 0 || after.AllocsPerFrame != 0 || after.GCRecentHitches != 0 { + t.Fatalf("after reset readout = %+v, want zeroed metrics", after) + } + if after.Sources.DrawStats { + t.Fatalf("expected sources.draw_stats=false after resetting pushed draw stats") + } + if gotHUD := app.Find("debug-frame-stats").Text; gotHUD != "0.0 fps · 0.00 ms" { + t.Fatalf("overlay HUD after reset = %q, want %q", gotHUD, "0.0 fps · 0.00 ms") + } + + // Zones after reset returns empty JSON array (not null). + rawZones, err := callToolRaw(t, app, cx, mcp.ToolPerfZones, nil) + if err != nil { + t.Fatalf("game_perf_zones after reset failed: %v", err) + } + if !strings.Contains(string(rawZones), `"zones":[]`) { + t.Fatalf("expected empty JSON array for zones after reset, got %s", rawZones) + } +} + +func TestPerfRender3DAndStandaloneProviders(t *testing.T) { + r3d := render3d.RenderStats{ + TotalItems: 120, + CulledItems: 35, + Occluded: 15, + VisibleItems: 70, + OpaqueDraws: 12, + TransparentDraws: 4, + InstancedBatches: 6, + TotalDrawCalls: 16, + Triangles: 48_000, + Vertices: 96_000, + MaterialSwitches: 9, + PipelineSwitches: 3, + TextureBytes: 16 << 20, + BufferBytes: 4 << 20, + } + + t.Run("RenderStatsFuncOnly", func(t *testing.T) { + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{ + RenderStatsFunc: func() render3d.RenderStats { return r3d }, + }); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + res := callTool[mcp.PerfReadoutResult](t, app, cx, mcp.ToolPerfReadout, nil) + if !res.Sources.Render3D || res.Sources.Overlay || res.Sources.DrawStats { + t.Fatalf("sources = %+v, want only render3d=true", res.Sources) + } + // Top-level draw counts inherit from RenderStatsFunc when no 2D DrawStats is set. + if res.DrawCalls != 16 || res.Batches != 6 || res.Triangles != 48_000 || res.Vertices != 96_000 { + t.Fatalf("top-level draw counts = (%d,%d,%d,%d), want (16,6,48000,96000)", + res.DrawCalls, res.Batches, res.Triangles, res.Vertices) + } + if res.Render3D == nil || res.Render3D.CulledItems != 35 || res.Render3D.Occluded != 15 || res.Render3D.MaterialSwitches != 9 || res.Render3D.TextureBytes != 16<<20 || res.Render3D.BufferBytes != 4<<20 { + t.Fatalf("render3d = %+v, want exact match with %+v", res.Render3D, r3d) + } + }) + + t.Run("DrawStatsFuncOverridesTopLevelAlongsideRender3D", func(t *testing.T) { + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{ + DrawStatsFunc: func() debug.DrawStats { + return debug.DrawStats{DrawCalls: 5, Sprites: 80, Batches: 2, Triangles: 160, Vertices: 320} + }, + RenderStatsFunc: func() render3d.RenderStats { return r3d }, + }); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + res := callTool[mcp.PerfReadoutResult](t, app, cx, mcp.ToolPerfReadout, nil) + if !res.Sources.DrawStats || !res.Sources.Render3D { + t.Fatalf("sources = %+v, want draw_stats and render3d", res.Sources) + } + if res.DrawCalls != 5 || res.Sprites != 80 || res.Batches != 2 || res.Triangles != 160 || res.Vertices != 320 { + t.Fatalf("top-level draw stats = (%d,%d,%d,%d,%d), want DrawStatsFunc values", + res.DrawCalls, res.Sprites, res.Batches, res.Triangles, res.Vertices) + } + if res.Render3D == nil || res.Render3D.TotalDrawCalls != 16 || res.Render3D.Triangles != 48_000 { + t.Fatalf("render3d = %+v, want full 3D breakdown", res.Render3D) + } + }) + + t.Run("StandaloneProfilerWithoutOverlay", func(t *testing.T) { + now := time.Unix(7000, 0) + prof := debug.NewProfiler(10) + prof.SetNow(func() time.Time { return now }) + prof.BeginFrame() + tok := prof.Begin("sim") + now = now.Add(2500 * time.Microsecond) + prof.End(tok) + prof.EndFrame() + + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{Profiler: prof}); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + res := callTool[mcp.PerfReadoutResult](t, app, cx, mcp.ToolPerfReadout, map[string]any{"include_zones": true}) + if !res.Sources.Profiler || res.Sources.Overlay { + t.Fatalf("sources = %+v, want profiler=true overlay=false", res.Sources) + } + if len(res.Zones) != 1 || res.Zones[0].Name != "sim" || !approxEqual(res.Zones[0].LastMs, 2.5, 1e-6) { + t.Fatalf("zones = %+v, want [sim 2.5ms]", res.Zones) + } + }) +} + +func TestPerfErrorsAndStrictArguments(t *testing.T) { + t.Run("NoTelemetryConfigured", func(t *testing.T) { + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{}); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + if _, err := callToolRaw(t, app, cx, mcp.ToolPerfReadout, nil); err == nil || !strings.Contains(err.Error(), "no performance telemetry") { + t.Fatalf("readout unconfigured = %v, want no performance telemetry error", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolPerfZones, nil); err == nil || !strings.Contains(err.Error(), "no profiler configured") { + t.Fatalf("zones unconfigured = %v, want no profiler configured error", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolPerfReset, nil); err == nil || !strings.Contains(err.Error(), "no performance telemetry") { + t.Fatalf("reset unconfigured = %v, want no performance telemetry error", err) + } + + // Unknown fields rejected on every perf tool. + for _, tool := range []string{mcp.ToolPerfReadout, mcp.ToolPerfZones, mcp.ToolPerfReset} { + if _, err := callToolRaw(t, app, cx, tool, `{"bogus":1}`); err == nil || !strings.Contains(err.Error(), "unknown field") { + t.Fatalf("%s unknown field = %v, want unknown field error", tool, err) + } + } + + // Negative limits rejected. + if _, err := callToolRaw(t, app, cx, mcp.ToolPerfReadout, map[string]any{"history_limit": -1}); err == nil || !strings.Contains(err.Error(), "history_limit") { + t.Fatalf("negative history_limit = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolPerfReadout, map[string]any{"zones_limit": -1}); err == nil || !strings.Contains(err.Error(), "zones_limit") { + t.Fatalf("negative zones_limit = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolPerfZones, map[string]any{"limit": -3}); err == nil || !strings.Contains(err.Error(), "limit") { + t.Fatalf("negative zones limit = %v", err) + } + }) + + t.Run("OverlayWithoutProfilerGraceful", func(t *testing.T) { + overlay := debug.New(debug.Options{}) + overlay.RecordFrame(16*time.Millisecond, 3*time.Millisecond, 2*time.Millisecond) + + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{Overlay: overlay}); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + raw, err := callToolRaw(t, app, cx, mcp.ToolPerfReadout, map[string]any{"include_zones": true, "include_history": true}) + if err != nil { + t.Fatalf("readout with overlay-only failed: %v", err) + } + var res mcp.PerfReadoutResult + if err := json.Unmarshal(raw, &res); err != nil { + t.Fatal(err) + } + if !res.Sources.Overlay || res.Sources.Profiler || res.SampleCount != 1 || len(res.History) != 1 || len(res.Zones) != 0 { + t.Fatalf("overlay-only readout = %+v", res) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolPerfZones, nil); err == nil || !strings.Contains(err.Error(), "no profiler configured") { + t.Fatalf("zones without profiler = %v, want error", err) + } + }) +} From 76b4570eec101862ba5026b01cfca4e3091834e6 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 04:26:01 +0900 Subject: [PATCH 2/5] fix(debug): keep scope IDs and trace recording across Profiler.Reset Profiler.Reset cleared the scope index and stopped any active trace recording, so game_perf_reset silently discarded a Chrome trace started from the dev console, and a scope token spanning the reset was charged to whichever new scope reused its ID. Reset now only zeroes each scope's accumulators and history. --- docs/en/mcp.md | 2 +- docs/zh/mcp.md | 2 +- packages/game/debug/profiler.go | 14 ++++--------- packages/game/debug/profiler_test.go | 31 ++++++++++++++++++++++++++++ packages/game/mcp/perf.go | 2 +- 5 files changed, 38 insertions(+), 13 deletions(-) diff --git a/docs/en/mcp.md b/docs/en/mcp.md index a8038b98..8fc7fba1 100644 --- a/docs/en/mcp.md +++ b/docs/en/mcp.md @@ -121,7 +121,7 @@ If `game_entity_spawn` fails while applying `parent` or `components`, or while r | `game_replay_list` | `{}` | Lists stored recordings in sorted name order with `frames`, `seed`, `step_rate`, `events`, `actions`, `axes` and `metadata`. | | `game_perf_readout` | `include_history` (optional, default `false`), `history_limit` (optional), `include_zones` (optional, default `false`), `zones_limit` (optional) | Live performance readout matching the debug overlay: `fps`, rolling average and latest `frame_ms`/`update_ms`/`draw_ms`, min/max/p50/p95/p99 frame times, draw stats (`draw_calls`, `sprites`, `batches`, `triangles`, `vertices`), per-frame heap allocations (`allocs_per_frame`, `alloc_bytes_per_frame`, `last_frame_allocs`, `last_frame_alloc_bytes`), `heap_bytes`, `gc_count`, GC pause/hitch metrics, optional `render3d` and `asset_memory` breakdowns, and optional chronological `history` and profiler `zones`. | | `game_perf_zones` | `limit` (optional) | Named timing zones from `debug.Profiler` sorted by recent frame cost (`name`, `last_ms`, `avg_ms`, `max_ms`, `calls`), plus `recording`, `recorded_frames` and `total`. | -| `game_perf_reset` | `{}` | Resets accumulated `debug.Overlay` frame timings and pushed draw stats, `debug.Profiler` zones, and `debug.GCMonitor` history. | +| `game_perf_reset` | `{}` | Resets accumulated `debug.Overlay` frame timings and pushed draw stats, `debug.Profiler` zone timings, and `debug.GCMonitor` history. A profiler trace recording started with `StartRecording` keeps running and keeps its events. | All tools reject unknown argument fields. diff --git a/docs/zh/mcp.md b/docs/zh/mcp.md index 31951892..c0034333 100644 --- a/docs/zh/mcp.md +++ b/docs/zh/mcp.md @@ -121,7 +121,7 @@ if err := bridge.RegisterScenePrefab("turret", turretDoc); err != nil { | `game_replay_list` | `{}` | 按名称排序列出已存储的录制及其 `frames`、`seed`、`step_rate`、`events`、`actions`、`axes` 与 `metadata`。 | | `game_perf_readout` | `include_history`(可选,默认 `false`)、`history_limit`(可选)、`include_zones`(可选,默认 `false`)、`zones_limit`(可选) | 与调试浮层数值一致的实时性能读数:`fps`、滑动平均与最近一帧的 `frame_ms`/`update_ms`/`draw_ms`、最小/最大及 p50/p95/p99 帧时间、绘制统计(`draw_calls`、`sprites`、`batches`、`triangles`、`vertices`)、每帧堆分配(`allocs_per_frame`、`alloc_bytes_per_frame`、`last_frame_allocs`、`last_frame_alloc_bytes`)、`heap_bytes`、`gc_count`、GC 停顿与卡顿统计、可选的 `render3d` 与 `asset_memory` 明细,以及可选的时间序 `history` 与分析器 `zones`。 | | `game_perf_zones` | `limit`(可选) | 按最近帧耗时降序排列的 `debug.Profiler` 命名计时区间列表(`name`、`last_ms`、`avg_ms`、`max_ms`、`calls`),以及 `recording`、`recorded_frames` 和 `total`。 | -| `game_perf_reset` | `{}` | 重置累积的 `debug.Overlay` 帧耗时与推送绘制统计、`debug.Profiler` 区间以及 `debug.GCMonitor` 历史记录。 | +| `game_perf_reset` | `{}` | 重置累积的 `debug.Overlay` 帧耗时与推送绘制统计、`debug.Profiler` 区间耗时以及 `debug.GCMonitor` 历史记录。通过 `StartRecording` 开始的分析器追踪录制会继续进行,已录制的事件也会保留。 | 所有工具都会拒绝未知的参数字段。 diff --git a/packages/game/debug/profiler.go b/packages/game/debug/profiler.go index aab8efc5..2c5fa2ed 100644 --- a/packages/game/debug/profiler.go +++ b/packages/game/debug/profiler.go @@ -305,21 +305,15 @@ func (p *Profiler) RecordedFrames() int { return n } -// Reset clears all recorded scope timings, ring buffers and trace events. +// Reset clears every scope's accumulated timings and frame history, so TopScopes reports nothing until scopes run again. Scope names keep their IDs, so a ScopeToken opened before Reset and ended after it is still charged to its own scope, and an active or finished trace recording (StartRecording, WriteChromeTrace) is left as it is. func (p *Profiler) Reset() { if p == nil { return } p.mu.Lock() - clear(p.scopeIndex) - p.scopes = p.scopes[:0] - p.inFrame = false - p.completedFrames = 0 - p.depth = 0 - p.recording = false - p.recordTarget = 0 - p.recordedFrames = 0 - p.events = p.events[:0] + for i := range p.scopes { + p.scopes[i] = scopeRecord{name: p.scopes[i].name} + } p.mu.Unlock() } diff --git a/packages/game/debug/profiler_test.go b/packages/game/debug/profiler_test.go index 87908eae..98cec934 100644 --- a/packages/game/debug/profiler_test.go +++ b/packages/game/debug/profiler_test.go @@ -67,6 +67,37 @@ func TestProfilerNestedScopesAndTopScopes(t *testing.T) { } } +func TestProfilerResetKeepsOpenScopesAndRecording(t *testing.T) { + now := time.Unix(1000, 0) + p := debug.NewProfiler(60) + p.SetNow(func() time.Time { return now }) + + p.BeginFrame() + p.End(p.Begin("physics")) + p.End(p.Begin("render")) + p.EndFrame() + + p.StartRecording(10) + p.BeginFrame() + open := p.Begin("physics") + now = now.Add(3 * time.Millisecond) + p.Reset() + if !p.Recording() { + t.Fatal("Reset stopped an active trace recording") + } + p.Begin("render").End() + p.End(open) + p.EndFrame() + + top := p.TopScopes(0) + if len(top) != 2 || top[0].Name != "physics" || top[0].Total != 3*time.Millisecond || top[1].Name != "render" || top[1].Total != 0 { + t.Fatalf("TopScopes(0) after Reset = %+v, want physics=3ms and render=0", top) + } + if got := p.RecordedFrames(); got != 1 { + t.Fatalf("RecordedFrames() = %d, want 1", got) + } +} + func TestProfilerChromeTrace300Frames(t *testing.T) { now := time.Unix(2000, 0) p := debug.NewProfiler(300) diff --git a/packages/game/mcp/perf.go b/packages/game/mcp/perf.go index a88b38c8..6d7cbd92 100644 --- a/packages/game/mcp/perf.go +++ b/packages/game/mcp/perf.go @@ -202,7 +202,7 @@ func (b *Bridge) perfTools() []automation.Tool { }, { Name: ToolPerfReset, - Description: "Reset accumulated debug overlay frame timings, pushed draw statistics, profiler zones and GC monitor history.", + Description: "Reset accumulated debug overlay frame timings, pushed draw statistics, profiler zone timings and GC monitor history. An active profiler trace recording keeps running.", InputSchema: schemaPerfReset, Handler: b.handlePerfReset, }, From 5a6cf20a7204fcba93c66cac8f8849bc6b48c519 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 04:26:49 +0900 Subject: [PATCH 3/5] fix(mcp): supply 3D render stats without importing game/render3d Config.RenderStatsFunc returned render3d.RenderStats, so game/mcp imported game/render3d and every 2D game attaching the bridge linked nsgo/gpu, scene3d, particles and ktx2. It now returns mcp.PerfRender3DStats, which has the same fields as render3d.RenderStats, so a game converts with mcp.PerfRender3DStats(stats). --- .../2026-11-24-mcp-performance-readouts.md | 8 +++---- docs/en/mcp.md | 4 ++-- docs/zh/mcp.md | 4 ++-- packages/game/mcp/mcp.go | 5 ++-- packages/game/mcp/perf.go | 24 ++----------------- packages/game/mcp/perf_test.go | 4 ++-- 6 files changed, 14 insertions(+), 35 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-11-24-mcp-performance-readouts.md b/.agents/notes/implemented/feature/2026-11-24-mcp-performance-readouts.md index ae4568b9..1b3c14b2 100644 --- a/.agents/notes/implemented/feature/2026-11-24-mcp-performance-readouts.md +++ b/.agents/notes/implemented/feature/2026-11-24-mcp-performance-readouts.md @@ -8,16 +8,16 @@ Coding agents driving or inspecting a running NSGo game over `nsgo mcp` (see [MC ## Decision -Add a dedicated `perf` tool group (`packages/game/mcp/perf.go`) exposing `game_perf_readout`, `game_perf_zones`, and `game_perf_reset` via `Bridge.Tools()`, reading directly from `debug.Overlay`, `debug.Profiler`, `debug.GCMonitor`, `debug.MemoryTracker`, `debug.DrawStats`, and `render3d.RenderStats`. Extend `packages/game/debug` minimally so `GCMonitor` also samples per-frame heap allocations with zero steady-state allocations, `Overlay` supports optional `DrawStats`, and `Overlay`/`Profiler`/`GCMonitor` expose clean reset helpers shared by both the HUD and MCP. +Add a dedicated `perf` tool group (`packages/game/mcp/perf.go`) exposing `game_perf_readout`, `game_perf_zones`, and `game_perf_reset` via `Bridge.Tools()`, reading directly from `debug.Overlay`, `debug.Profiler`, `debug.GCMonitor`, `debug.MemoryTracker` and `debug.DrawStats`, plus 3D statistics a game supplies as `mcp.PerfRender3DStats`. Extend `packages/game/debug` minimally so `GCMonitor` also samples per-frame heap allocations with zero steady-state allocations, `Overlay` supports optional `DrawStats`, and `Overlay`/`Profiler`/`GCMonitor` expose clean reset helpers shared by both the HUD and MCP. ## Architecture and contract - **Single source of truth with `debug.Overlay`**: `game_perf_readout` reads `FPS()`, `Average()`, `Latest()`, `Samples()`, `DrawStats()`, `Profiler()`, `GC()`, and `Memory()` directly from `Config.Overlay` (using the same `float64(d) / float64(time.Millisecond)` conversion as `debug/overlay.go`). Values returned by MCP match the on-screen debug overlay bit-for-bit, and `game_perf_reset` refreshes the visible overlay HUD via `Overlay.ResetStats()`. - **Zero-alloc per-frame allocation tracking in `debug.GCMonitor`**: `GCMonitor` extends its pre-allocated `runtime/metrics` sample buffer from 3 to 5 entries to read `/gc/heap/allocs:objects` and `/gc/heap/allocs:bytes` alongside `/gc/pauses:seconds`, `/gc/cycles/total:gc-cycles`, and `/memory/classes/heap/objects:bytes`. Running window totals (`recentAllocs`, `recentAllocBytes`) are updated in O(1) as the ring buffer advances, preserving `debug.AssertZeroAllocs` in steady state while exposing `AllocsPerFrame()` and `AllocBytesPerFrame()` to both the overlay and MCP. -- **2D and 3D draw statistics**: `debug.DrawStats` (`DrawCalls`, `Sprites`, `Batches`, `Triangles`, `Vertices`) can be supplied via `debug.Options.DrawStats`, pushed with `Overlay.SetDrawStats`, or overridden via `mcp.Config.DrawStatsFunc`. Optional `mcp.Config.RenderStatsFunc` attaches full `render3d.RenderStats` telemetry under `render3d` and populates top-level `draw_calls`, `batches`, `triangles`, and `vertices` automatically when no 2D draw-stats source is configured. +- **2D and 3D draw statistics**: `debug.DrawStats` (`DrawCalls`, `Sprites`, `Batches`, `Triangles`, `Vertices`) can be supplied via `debug.Options.DrawStats`, pushed with `Overlay.SetDrawStats`, or overridden via `mcp.Config.DrawStatsFunc`. Optional `mcp.Config.RenderStatsFunc` attaches full 3D telemetry under `render3d` as `mcp.PerfRender3DStats`, a struct with the same fields as `render3d.RenderStats` so a game converts with `mcp.PerfRender3DStats(stats)` while `game/mcp` never imports `game/render3d` (which would link `nsgo/gpu`, `scene3d`, `particles` and `ktx2` into every 2D game that attaches the bridge), and populates top-level `draw_calls`, `batches`, `triangles`, and `vertices` automatically when no 2D draw-stats source is configured. - **Strict schemas and graceful degradation**: Every perf tool decodes arguments with `json.Decoder.DisallowUnknownFields()` and rejects negative limits. Calling `game_perf_readout` or `game_perf_reset` with no configured perf telemetry returns an explicit error rather than misleading zeros; configuring any subset of providers succeeds and reports active providers in `sources`. Calling `game_perf_zones` without a profiler returns an explicit error, while `game_perf_readout` with `include_zones: true` degrades cleanly when only an overlay is configured. - **Release-build parity**: Every new method added to `packages/game/debug` (`DrawStats`, `SetDrawStats`, `HasDrawStats`, `ResetStats`, `Profiler.Reset`, `GCMonitor.AllocsPerFrame`, `GCMonitor.AllocBytesPerFrame`, `GCMonitor.Reset`) has a matching zero-cost no-op stub in the `//go:build release` files so `-tags release` builds remain unaffected. -- **Minimal merge footprint**: All tool schemas, response structs, and handlers live in `packages/game/mcp/perf.go`, with only additive `Config` fields and `b.perfTools()` hookup in `packages/game/mcp/mcp.go` so parallel MCP PRs (#462–#469) rebase cleanly. +- **Minimal merge footprint**: All tool schemas, response structs, and handlers live in `packages/game/mcp/perf.go`, with only additive `Config` fields and `b.perfTools()` hookup in `packages/game/mcp/mcp.go` so it conflicts with the other MCP tool groups (#462–#469) only where each appends to `Config`, `Tools()` and the tool lists. ## Alternatives considered @@ -36,7 +36,7 @@ Returning a zeroed `PerfReadoutResult` on an empty `mcp.Config{}` avoids errors ## Consequences - **Benefits**: Agents can inspect live FPS, average/latest/percentile frame timings, update/draw splits, 2D and 3D draw counts, per-frame heap allocations, GC pauses/hitches, asset memory budgets, chronological frame history, and profiler zones with guaranteed parity against `debug.Overlay`. Resetting metrics via MCP keeps the visible HUD synchronized. -- **Costs**: `packages/game/debug` gains a small additive API surface (`DrawStats`, `GCMonitor` allocation averages, and `Reset` methods) that must remain mirrored in its `release` build stubs. `packages/game/mcp` now imports `packages/game/debug` and `packages/game/render3d` (all three are Experimental packages, so Stable packages remain unaffected). +- **Costs**: `packages/game/debug` gains a small additive API surface (`DrawStats`, `GCMonitor` allocation averages, and `Reset` methods) that must remain mirrored in its `release` build stubs. `packages/game/mcp` now imports `packages/game/debug` (both are Experimental packages, so Stable packages remain unaffected); it does not import `packages/game/render3d`. ## Verification diff --git a/docs/en/mcp.md b/docs/en/mcp.md index 8fc7fba1..b7984291 100644 --- a/docs/en/mcp.md +++ b/docs/en/mcp.md @@ -29,7 +29,7 @@ bridge, err := mcp.Attach(cx, mcp.Config{ ViewSizeFunc: g.currentViewSize, Console: g.console, Overlay: g.debugOverlay, - RenderStatsFunc: func() render3d.RenderStats { return g.lastRenderStats }, + RenderStatsFunc: func() mcp.PerfRender3DStats { return mcp.PerfRender3DStats(g.lastRenderStats) }, }) if err != nil { return err @@ -197,7 +197,7 @@ bridge, err := mcp.Attach(cx, mcp.Config{ Pass your [`debug.Overlay`](debug.md) via `Config.Overlay` to expose the exact same frame timings, draw statistics (`debug.Options.DrawStats` or `Overlay.SetDrawStats`), GC/allocation counters (`debug.GCMonitor`), asset memory (`debug.MemoryTracker`) and timing scopes (`debug.Profiler`) shown by the on-screen debug HUD. - `Config.Profiler`, `Config.GC`, `Config.Memory` and `Config.DrawStatsFunc` override (or work standalone without) `Config.Overlay`. -- `Config.RenderStatsFunc` attaches detailed 3D culling, batching, state-switch and GPU memory metrics from [`render3d.RenderStats`](render3d.md) under `render3d`, and populates top-level `draw_calls`, `batches`, `triangles` and `vertices` automatically when no 2D draw-stats provider is set. +- `Config.RenderStatsFunc` attaches detailed 3D culling, batching, state-switch and GPU memory metrics from [`render3d.RenderStats`](render3d.md) under `render3d`, and populates top-level `draw_calls`, `batches`, `triangles` and `vertices` automatically when no 2D draw-stats provider is set. `mcp.PerfRender3DStats` has the same fields as `render3d.RenderStats`, so `mcp.PerfRender3DStats(stats)` converts one; `game/mcp` does not import `game/render3d`, so a 2D game that attaches the bridge does not link the 3D renderer. - `game_perf_readout` always includes a `sources` object indicating which telemetry providers are active (`overlay`, `profiler`, `gc`, `memory`, `draw_stats`, `render3d`). ## Stable entity references diff --git a/docs/zh/mcp.md b/docs/zh/mcp.md index c0034333..2194abc0 100644 --- a/docs/zh/mcp.md +++ b/docs/zh/mcp.md @@ -29,7 +29,7 @@ bridge, err := mcp.Attach(cx, mcp.Config{ ViewSizeFunc: g.currentViewSize, Console: g.console, Overlay: g.debugOverlay, - RenderStatsFunc: func() render3d.RenderStats { return g.lastRenderStats }, + RenderStatsFunc: func() mcp.PerfRender3DStats { return mcp.PerfRender3DStats(g.lastRenderStats) }, }) if err != nil { return err @@ -197,7 +197,7 @@ bridge, err := mcp.Attach(cx, mcp.Config{ 通过 `Config.Overlay` 传入 [`debug.Overlay`](debug.md),即可把调试 HUD 显示的帧耗时、绘制统计(`debug.Options.DrawStats` 或 `Overlay.SetDrawStats`)、GC 与每帧分配计数(`debug.GCMonitor`)、资源内存(`debug.MemoryTracker`)以及命名计时区间(`debug.Profiler`)以完全一致的数值暴露给智能体。 - `Config.Profiler`、`Config.GC`、`Config.Memory` 与 `Config.DrawStatsFunc` 既可覆盖 `Config.Overlay` 上的对应组件,也可在不启用浮层时单独使用。 -- `Config.RenderStatsFunc` 会在 `render3d` 字段下附加来自 [`render3d.RenderStats`](render3d.md) 的 3D 裁剪、合批、状态切换与 GPU 内存明细;在未配置 2D 绘制统计来源时,还会自动填充顶层的 `draw_calls`、`batches`、`triangles` 与 `vertices`。 +- `Config.RenderStatsFunc` 会在 `render3d` 字段下附加来自 [`render3d.RenderStats`](render3d.md) 的 3D 裁剪、合批、状态切换与 GPU 内存明细;在未配置 2D 绘制统计来源时,还会自动填充顶层的 `draw_calls`、`batches`、`triangles` 与 `vertices`。`mcp.PerfRender3DStats` 与 `render3d.RenderStats` 字段相同,可直接用 `mcp.PerfRender3DStats(stats)` 转换;`game/mcp` 不导入 `game/render3d`,因此挂接桥接器的 2D 游戏不会链接 3D 渲染器。 - `game_perf_readout` 始终返回 `sources` 对象,标明哪些遥测来源已启用(`overlay`、`profiler`、`gc`、`memory`、`draw_stats`、`render3d`)。 ## 稳定的实体引用 diff --git a/packages/game/mcp/mcp.go b/packages/game/mcp/mcp.go index 910b8930..e8862000 100644 --- a/packages/game/mcp/mcp.go +++ b/packages/game/mcp/mcp.go @@ -18,7 +18,6 @@ import ( "github.com/nsgo-dev/game/packages/game/entities" "github.com/nsgo-dev/game/packages/game/input" "github.com/nsgo-dev/game/packages/game/random" - "github.com/nsgo-dev/game/packages/game/render3d" "github.com/nsgo-dev/game/packages/game/scene" "github.com/nsgo-dev/game/packages/game/screen" "github.com/nsgo-dev/nsgo/automation" @@ -143,8 +142,8 @@ type Config struct { // DrawStatsFunc dynamically supplies per-frame draw statistics (draw calls, sprites, batches, triangles, vertices). When nil, performance tools fall back to Overlay.DrawStats() or RenderStatsFunc. DrawStatsFunc func() debug.DrawStats - // RenderStatsFunc dynamically supplies 3D per-frame render statistics (culling, batching, state switches, geometry and GPU memory). - RenderStatsFunc func() render3d.RenderStats + // RenderStatsFunc supplies 3D per-frame render statistics (culling, batching, state switches, geometry and GPU memory). A game using game/render3d returns mcp.PerfRender3DStats(stats) for its latest render3d.RenderStats. + RenderStatsFunc func() PerfRender3DStats } type compTypeKey any diff --git a/packages/game/mcp/perf.go b/packages/game/mcp/perf.go index 6d7cbd92..2741a392 100644 --- a/packages/game/mcp/perf.go +++ b/packages/game/mcp/perf.go @@ -9,7 +9,6 @@ import ( "time" "github.com/nsgo-dev/game/packages/game/debug" - "github.com/nsgo-dev/game/packages/game/render3d" "github.com/nsgo-dev/nsgo/automation" ) @@ -50,7 +49,7 @@ type PerfZoneInfo struct { Calls int `json:"calls"` } -// PerfRender3DStats mirrors render3d.RenderStats in snake_case JSON form. +// PerfRender3DStats is a 3D renderer's per-frame statistics in snake_case JSON form. It has the same fields in the same order as render3d.RenderStats, so a game converts one with mcp.PerfRender3DStats(stats) and game/mcp does not link the 3D renderer. type PerfRender3DStats struct { TotalItems int `json:"total_items"` CulledItems int `json:"culled_items"` @@ -355,7 +354,7 @@ func (b *Bridge) handlePerfReadout(_ context.Context, raw json.RawMessage) (any, if b.cfg.RenderStatsFunc != nil { rs := b.cfg.RenderStatsFunc() res.Sources.Render3D = true - res.Render3D = render3DStatsFrom(rs) + res.Render3D = &rs if !res.Sources.DrawStats { res.DrawCalls = rs.TotalDrawCalls res.Batches = rs.InstancedBatches @@ -465,25 +464,6 @@ func collectZones(p *debug.Profiler, limit int) ([]PerfZoneInfo, int) { return zones, total } -func render3DStatsFrom(rs render3d.RenderStats) *PerfRender3DStats { - return &PerfRender3DStats{ - TotalItems: rs.TotalItems, - CulledItems: rs.CulledItems, - Occluded: rs.Occluded, - VisibleItems: rs.VisibleItems, - OpaqueDraws: rs.OpaqueDraws, - TransparentDraws: rs.TransparentDraws, - InstancedBatches: rs.InstancedBatches, - TotalDrawCalls: rs.TotalDrawCalls, - Triangles: rs.Triangles, - Vertices: rs.Vertices, - MaterialSwitches: rs.MaterialSwitches, - PipelineSwitches: rs.PipelineSwitches, - TextureBytes: rs.TextureBytes, - BufferBytes: rs.BufferBytes, - } -} - func memorySummaryFrom(mem *debug.MemoryTracker) *PerfMemorySummary { total := mem.TotalBytes() budget := mem.TotalBudget() diff --git a/packages/game/mcp/perf_test.go b/packages/game/mcp/perf_test.go index 6d129bda..e7c2ec22 100644 --- a/packages/game/mcp/perf_test.go +++ b/packages/game/mcp/perf_test.go @@ -338,7 +338,7 @@ func TestPerfRender3DAndStandaloneProviders(t *testing.T) { app := nsgotest.Start(t, func(scope *core.Scope) core.Node { cx = scope if _, err := mcp.Attach(cx, mcp.Config{ - RenderStatsFunc: func() render3d.RenderStats { return r3d }, + RenderStatsFunc: func() mcp.PerfRender3DStats { return mcp.PerfRender3DStats(r3d) }, }); err != nil { t.Fatal(err) } @@ -367,7 +367,7 @@ func TestPerfRender3DAndStandaloneProviders(t *testing.T) { DrawStatsFunc: func() debug.DrawStats { return debug.DrawStats{DrawCalls: 5, Sprites: 80, Batches: 2, Triangles: 160, Vertices: 320} }, - RenderStatsFunc: func() render3d.RenderStats { return r3d }, + RenderStatsFunc: func() mcp.PerfRender3DStats { return mcp.PerfRender3DStats(r3d) }, }); err != nil { t.Fatal(err) } From e8bdcefd41048a40f4c10549ebc90b03f229799f Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 04:26:49 +0900 Subject: [PATCH 4/5] style(mcp): join the hard-wrapped perf test comment into one line --- packages/game/mcp/perf_test.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/game/mcp/perf_test.go b/packages/game/mcp/perf_test.go index e7c2ec22..ba37798a 100644 --- a/packages/game/mcp/perf_test.go +++ b/packages/game/mcp/perf_test.go @@ -24,9 +24,7 @@ func approxEqual(a, b, tol float64) bool { return math.Abs(a-b) <= tol } -// TestPerfReadoutMatchesDebugOverlay verifies that game_perf_readout returns -// values matching debug.Overlay's frame timing, draw statistics, GC/allocation -// counters, asset memory, and profiler scopes, including the rendered overlay HUD. +// TestPerfReadoutMatchesDebugOverlay verifies that game_perf_readout returns values matching debug.Overlay's frame timing, draw statistics, GC/allocation counters, asset memory, and profiler scopes, including the rendered overlay HUD. func TestPerfReadoutMatchesDebugOverlay(t *testing.T) { now := time.Unix(5000, 0) prof := debug.NewProfiler(60) From c234fb79db5195f8c32f85eaf8447ef861bcccd0 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 04:27:38 +0900 Subject: [PATCH 5/5] docs(debug): document draw stats, readout resets and per-frame allocation averages --- docs/en/debug.md | 25 +++++++++++++++++++++++++ docs/en/gc-and-allocations.md | 4 +++- docs/zh/debug.md | 25 +++++++++++++++++++++++++ docs/zh/gc-and-allocations.md | 4 +++- 4 files changed, 56 insertions(+), 2 deletions(-) diff --git a/docs/en/debug.md b/docs/en/debug.md index 9f2dbd92..e09328a9 100644 --- a/docs/en/debug.md +++ b/docs/en/debug.md @@ -71,6 +71,31 @@ Convenience shortcuts `overlay.DrawBox`, `overlay.DrawCircle`, `overlay.DrawSpri overlay.DrawFighterBoxes(d, p1, core.RGB(0x38bdf8), core.RGB(0xef4444)) ``` +## Draw statistics + +Report each frame's draw submissions in either of two ways, and the overlay shows them as a `Draw: N calls · N sprites · N batches` line, followed by `· N tris · N verts` once either count is non-zero: + +1. **Pull via `Options.DrawStats`**: a `func() debug.DrawStats` called whenever the overlay refreshes. +2. **Push via `overlay.SetDrawStats(stats)`**: used when `Options.DrawStats` is nil; call it once per frame after drawing. + +```go +overlay := debug.New(debug.Options{ + DrawStats: func() debug.DrawStats { + return debug.DrawStats{DrawCalls: r.drawCalls, Sprites: len(actorsBatch.Sprites), Batches: r.batches} + }, +}) +``` + +`overlay.DrawStats()` returns the current values and `overlay.HasDrawStats()` reports whether either source is set; the line stays hidden until one is. [`game/mcp`](mcp.md)'s `game_perf_readout` reports the same values. + +## Resetting the readouts + +- `overlay.ResetStats()` clears the frame-time ring buffer and any pushed draw statistics and refreshes the HUD. An `Options.DrawStats` callback keeps reporting. +- `GCMonitor.Reset()` clears the GC frame history, hitch count, pause peaks and per-frame allocation averages, and re-reads the runtime counters so the next frame is measured from that point (see [GC and frame allocations](gc-and-allocations.md)). +- `Profiler.Reset()` clears every timing scope's accumulated timings and history. Scope names keep their IDs, so a scope still open across the reset is charged to its own name, and a trace recording started with `StartRecording` keeps running and keeps its events. + +[`game/mcp`](mcp.md)'s `game_perf_reset` calls all three. + ## Scene inspector Supply live scene structure in either of two ways: diff --git a/docs/en/gc-and-allocations.md b/docs/en/gc-and-allocations.md index adfe8f9b..7b3b4456 100644 --- a/docs/en/gc-and-allocations.md +++ b/docs/en/gc-and-allocations.md @@ -38,7 +38,7 @@ Keep `Loop.Update`, `Loop.Draw`, and `Canvas.Draw` callbacks free of steady-stat ### Runtime Overlay (`GCMonitor`) -Wire `debug.NewGCMonitor` into `debug.Options.GC` to sample `runtime/metrics` (`/gc/pauses:seconds`, `/gc/cycles/total:gc-cycles`, `/memory/classes/heap/objects:bytes`) once per frame with zero steady-state allocations: +Wire `debug.NewGCMonitor` into `debug.Options.GC` to sample `runtime/metrics` (`/gc/pauses:seconds`, `/gc/cycles/total:gc-cycles`, `/memory/classes/heap/objects:bytes`, `/gc/heap/allocs:objects`, `/gc/heap/allocs:bytes`) once per frame with zero steady-state allocations: ```go gcMon := debug.NewGCMonitor(debug.FrameHistory) @@ -49,6 +49,8 @@ overlay := debug.New(debug.Options{ Frames where a GC cycle or pause occurred are flagged (`GCFrameSample.Hitched == true`) and marked directly on the overlay's frame-time graph, alongside cycle count, last/max pause, live heap bytes, and recent hitch count. +Each `GCFrameSample` also carries the heap objects and bytes allocated during that frame (`AllocsDelta`, `AllocBytesDelta`). `gcMon.AllocsPerFrame()` and `gcMon.AllocBytesPerFrame()` average them over the retained history, and the overlay shows them under the GC summary as `allocs 12.0/f (1.5 KB/f)`. A value that stays above zero in steady gameplay means a hot path allocates every frame. Call `gcMon.Reset()` after a loading screen or level change to drop the history and measure from that point. + ### CI Regression Checks (`AssertZeroAllocs`) Use `debug.AssertZeroAllocs` (wrapping `testing.AllocsPerRun`) in unit tests to guard hot paths from accidental allocations in pull requests: diff --git a/docs/zh/debug.md b/docs/zh/debug.md index 20ea2123..3dbf8880 100644 --- a/docs/zh/debug.md +++ b/docs/zh/debug.md @@ -71,6 +71,31 @@ d.Restore() overlay.DrawFighterBoxes(d, p1, core.RGB(0x38bdf8), core.RGB(0xef4444)) ``` +## 绘制统计 + +可以用以下两种方式提供每帧的绘制提交数,浮层会显示一行 `Draw: N calls · N sprites · N batches`,三角形数或顶点数不为零时再追加 `· N tris · N verts`: + +1. **通过 `Options.DrawStats` 拉取**:一个 `func() debug.DrawStats`,浮层每次刷新时调用。 +2. **通过 `overlay.SetDrawStats(stats)` 推送**:在 `Options.DrawStats` 为 nil 时使用,每帧绘制完成后调用一次。 + +```go +overlay := debug.New(debug.Options{ + DrawStats: func() debug.DrawStats { + return debug.DrawStats{DrawCalls: r.drawCalls, Sprites: len(actorsBatch.Sprites), Batches: r.batches} + }, +}) +``` + +`overlay.DrawStats()` 返回当前数值,`overlay.HasDrawStats()` 表示两种来源是否设置了其一;都未设置时不显示这一行。[`game/mcp`](mcp.md) 的 `game_perf_readout` 报告的是同一组数值。 + +## 重置读数 + +- `overlay.ResetStats()` 清空帧耗时环形缓冲区和已推送的绘制统计,并刷新 HUD。`Options.DrawStats` 回调会继续提供数值。 +- `GCMonitor.Reset()` 清空 GC 帧历史、卡顿计数、停顿峰值和每帧分配均值,并重新读取运行时计数器,下一帧从此刻开始计量(见 [GC 与帧分配预算](gc-and-allocations.md))。 +- `Profiler.Reset()` 清空每个计时区间累积的耗时和历史。区间名保留原有 ID,因此跨越重置仍未结束的区间会计入它自己的名字;通过 `StartRecording` 开始的追踪录制会继续进行,已录制的事件也会保留。 + +[`game/mcp`](mcp.md) 的 `game_perf_reset` 会依次调用这三者。 + ## 场景检查器 提供实时场景结构有两种方式: diff --git a/docs/zh/gc-and-allocations.md b/docs/zh/gc-and-allocations.md index a57df8e9..c4a7e483 100644 --- a/docs/zh/gc-and-allocations.md +++ b/docs/zh/gc-and-allocations.md @@ -38,7 +38,7 @@ func configureGC() { ### 运行时覆盖层(`GCMonitor`) -将 `debug.NewGCMonitor` 传入 `debug.Options.GC`,每帧以零稳态分配采样 `runtime/metrics`(`/gc/pauses:seconds`、`/gc/cycles/total:gc-cycles`、`/memory/classes/heap/objects:bytes`): +将 `debug.NewGCMonitor` 传入 `debug.Options.GC`,每帧以零稳态分配采样 `runtime/metrics`(`/gc/pauses:seconds`、`/gc/cycles/total:gc-cycles`、`/memory/classes/heap/objects:bytes`、`/gc/heap/allocs:objects`、`/gc/heap/allocs:bytes`): ```go gcMon := debug.NewGCMonitor(debug.FrameHistory) @@ -49,6 +49,8 @@ overlay := debug.New(debug.Options{ 当某帧内发生 GC 周期或停顿时,该帧会被标记为 `GCFrameSample.Hitched == true`,并直接在调试覆盖层的帧耗时柱状图上高亮标出,同时显示累计周期数、最近/最大停顿、存活堆大小以及近期卡顿帧数。 +每个 `GCFrameSample` 还记录该帧内分配的堆对象数与字节数(`AllocsDelta`、`AllocBytesDelta`)。`gcMon.AllocsPerFrame()` 与 `gcMon.AllocBytesPerFrame()` 给出它们在保留历史内的平均值,浮层在 GC 摘要下以 `allocs 12.0/f (1.5 KB/f)` 的形式显示。稳定游玩时这个值始终大于零,说明某条热路径每帧都在分配。在加载画面或切换关卡之后调用 `gcMon.Reset()`,即可丢弃历史,从此刻重新计量。 + ### CI 分配回归检查(`AssertZeroAllocs`) 在单元测试中使用 `debug.AssertZeroAllocs`(封装 `testing.AllocsPerRun`),防止后续改动在热路径引入意外的堆分配: