profiler

package
v0.3.0-rc.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 23 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package profiler is the editor's live profiler: the MCP clients that read a running game's game_perf_* tools, the recorded frame timeline and zone table, Chrome/Perfetto trace export, and the Play-mode strip and docked Profiler panel views. It never imports the editor; the editor builds a Host of callbacks and forwards its public Profiler methods to a State.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotConnected is returned by Poll when no running game profiler client is connected.
	ErrNotConnected = errors.New("editor: profiler is not connected to a running game")
	// ErrNoFrames is returned by ExportTrace when no frames have been recorded yet.
	ErrNoFrames = errors.New("editor: no profiler frames recorded to export")
)

Functions

func PanelView

func PanelView(cx *core.Scope, st *State, rev *core.Signal[uint64]) core.Node

PanelView renders the full docked Profiler panel below the viewport while st.Open reports true. It charts frame, update and draw time, FPS, allocations per frame, GC and asset memory over time, lists profiler zones from game_perf_zones sorted by cost, and provides Reset (game_perf_reset) and Chrome/Perfetto trace export through gamedebug.Profiler.WriteChromeTrace.

func StripView

func StripView(cx *core.Scope, st *State, rev *core.Signal[uint64]) core.Node

StripView renders the Play-mode "FRAME TIME · LAST 60 S" strip directly below the game view while Play mode is active or a running game is connected to the profiler, matching design/editor/PlayMode.dc.html. Pressing the strip's Profiler button opens the full Profiler panel.

Types

type Client

type Client interface {
	CallTool(ctx context.Context, name string, args json.RawMessage) (json.RawMessage, error)
	Close() error
}

Client invokes a running game's MCP performance tools (game_perf_readout, game_perf_zones, game_perf_reset). Implementations must be safe to Close more than once.

func ConnectCommand

func ConnectCommand(ctx context.Context, dir string, args ...string) (Client, error)

ConnectCommand connects to the running game in dir by launching `go tool nsgo mcp` (or custom args when provided) over an MCP stdio CommandTransport.

func ConnectMCP

func ConnectMCP(ctx context.Context, transport sdkmcp.Transport) (Client, error)

ConnectMCP connects to a running game's MCP server over transport using the official MCP Go SDK. Use it with &sdkmcp.CommandTransport{Command: ...}, &sdkmcp.IOTransport{...}, or sdkmcp.NewInMemoryTransports().

func ConnectScope

func ConnectScope(cx *core.Scope) Client

ConnectScope returns a Client that calls game_perf_* tools registered on cx via github.com/nsgo-dev/nsgo/automation. Call Poll on cx's graph goroutine when invoking manually; background polling dispatches automatically onto cx.

func NewBridgeClient

func NewBridgeClient(b *mcp.Bridge) Client

NewBridgeClient returns a Client backed directly by b's tool handlers without registering tools on a core.Scope.

type Frame

type Frame struct {
	Timestamp          time.Time
	FrameMs            float64
	UpdateMs           float64
	DrawMs             float64
	FPS                float64
	AllocsPerFrame     float64
	AllocBytesPerFrame float64
	HeapBytes          uint64
	GCCount            uint64
	GCLastPauseMs      float64
	GCMaxPauseMs       float64
	GCRecentHitches    int
	GCHitch            bool
	AssetMemoryBytes   int64
	AssetMemoryBudget  int64
	AssetOverBudget    bool
	Cause              string
	Zones              []mcp.PerfZoneInfo
}

Frame is one chronological sample recorded by the editor's profiler from game_perf_readout and game_perf_zones.

type Host

type Host struct {
	// Notify refreshes the editor UI after a profiler change; it runs on the UI goroutine.
	Notify func()
	// Report shows err in the status bar and the Output panel; nil is ignored.
	Report func(err error)
	// ReportStatusError shows msg as an error in the status bar and the Output panel.
	ReportStatusError func(msg string)
	// SetStatus sets the status bar text without notifying; callers call Notify afterwards.
	SetStatus func(status string)
	// Playing reports whether Play mode is running in the editor.
	Playing func() bool
	// MarkFrames returns the simulation frame of each Play mark, in mark order.
	MarkFrames func() []int
	// CurrentPlayFrameAndRate returns the current simulation frame and the fixed step rate of the game in Play mode or the connected running game.
	CurrentPlayFrameAndRate func() (frame int, rate int)
	// ReplayWindowSeconds is the length in seconds of the rolling replay window the strip's mark pins are placed in.
	ReplayWindowSeconds int
	// ProjectName returns the open project's name, or "" when no project is open.
	ProjectName func() string
	// Palette returns the editor's current design tokens for cx.
	Palette func(cx *core.Scope) theme.Palette
	// DockedStyle returns fallback adjusted to fill its dock slot when cx renders inside the editor's dock area.
	DockedStyle func(cx *core.Scope, fallback core.Style) core.Style
	// OnExportTrace returns the callback the Export Trace button hands the trace JSON to, or nil to open a Save File dialog. It is read on every export.
	OnExportTrace func() func(data []byte) error
	// T translates key into the editor's current language, filling in args, as Editor.T does.
	T func(key string, args ...l10n.Arg) string
	// PollInterval returns how often to poll a connected running game; zero or less means 250 ms. It is read each time polling starts.
	PollInterval func() time.Duration
}

Host is what the profiler needs from the editor that owns it. Every func must be set; New does not fill in defaults.

type Metric

type Metric int

Metric selects which time-series chart is shown in the full Profiler panel.

const (
	// MetricFrame charts total frame, update, and draw times in milliseconds.
	MetricFrame Metric = iota
	// MetricFPS charts frames per second over time.
	MetricFPS
	// MetricAllocsGC charts allocations per frame, live heap bytes, and GC hitches over time.
	MetricAllocsGC
	// MetricMemory charts tracked asset memory against budgets over time.
	MetricMemory
)

func (Metric) String

func (m Metric) String() string

String returns the human-readable label for m.

type Snapshot

type Snapshot struct {
	Connected      bool
	InEditorPlay   bool
	SourceLabel    string
	Open           bool
	Metric         Metric
	HasReadout     bool
	Readout        mcp.PerfReadoutResult
	Zones          []mcp.PerfZoneInfo
	Recording      bool
	RecordedFrames int
	Frames         []Frame
	Spike          *Spike
	LastError      string
}

Snapshot is an immutable snapshot of the editor's profiler state for UI rendering and tests.

type Spike

type Spike struct {
	// FrameIndex is the index into Snapshot.Frames.
	FrameIndex int
	// BarIndex is the index within the visible strip bars (0 .. stripBars-1).
	BarIndex int
	// PositionFrac is the horizontal fraction [0, 1] of the spike bar across the strip chart.
	PositionFrac float64
	// FrameMs is the spike frame duration in milliseconds.
	FrameMs float64
	// Cause is the game-supplied spike explanation or "GC pause" when known, or empty.
	Cause string
	// Label is the formatted callout pill text, such as "18.2 ms · first use of torch_glow compiled its shader".
	Label string
}

Spike describes the most prominent frame-time spike in the 60 s strip window.

type State

type State struct {
	// contains filtered or unexported fields
}

State is the profiler's connection, recorded frame timeline, zone table and panel visibility. Its methods are safe on a nil *State, which acts as a disconnected profiler that records nothing.

func New

func New(host Host) *State

New returns a disconnected profiler that calls back into host.

func (*State) Attach

func (s *State) Attach(client Client, inEditorPlay bool, label string)

Attach connects client under the source label label, clearing the recorded frames. inEditorPlay marks the editor's own Play-mode session, which the editor polls from its game loop instead of a background poller.

func (*State) Connect

func (s *State) Connect(client Client)

Connect connects the editor's profiler to client, polling game_perf_readout and game_perf_zones while connected. Any previously connected profiler client is closed first. Passing nil disconnects the profiler.

func (*State) Connected

func (s *State) Connected() bool

Connected reports whether the editor's profiler is currently connected to a running game (remote MCP client or active Play-in-editor session).

func (*State) DetachPlay

func (s *State) DetachPlay()

DetachPlay disconnects the profiler when it is attached to the editor's Play-mode session and leaves a remote connection alone.

func (*State) Disconnect

func (s *State) Disconnect() error

Disconnect stops live polling and closes the connected profiler client, preserving recorded frames so the user can inspect or export them.

func (*State) ExportTrace

func (s *State) ExportTrace(w io.Writer) error

ExportTrace exports all recorded frames (and their zones) as Chrome/Perfetto Trace Event Format JSON through gamedebug.Profiler.WriteChromeTrace.

func (*State) ExportTraceFile

func (s *State) ExportTraceFile(path string) error

ExportTraceFile writes the recorded profiler frames as Chrome/Perfetto Trace Event Format JSON to path.

func (*State) ExportTraceFromUI

func (s *State) ExportTraceFromUI()

ExportTraceFromUI exports the recorded frames for the panel's Export Trace button: to Host.OnExportTrace when it returns a callback, otherwise through a Save File dialog on the bound scope.

func (*State) Metric

func (s *State) Metric() Metric

Metric returns the currently active chart metric in the full Profiler panel.

func (*State) Open

func (s *State) Open() bool

Open reports whether the full Profiler panel is currently visible below the viewport.

func (*State) PlayActive

func (s *State) PlayActive() bool

PlayActive reports whether the profiler is attached to the editor's own Play-mode session.

func (*State) Poll

func (s *State) Poll(ctx context.Context) error

Poll queries game_perf_readout (including frame history) and game_perf_zones from the connected game, updates the recorded frame history and zone table, and refreshes the UI.

func (*State) Reset

func (s *State) Reset(ctx context.Context) error

Reset resets accumulated performance counters in the connected game via game_perf_reset (when connected) and clears the editor's recorded profiler timeline and zone table.

func (*State) ResetFromUI

func (s *State) ResetFromUI()

ResetFromUI resets the profiler for the panel's Reset button, off the UI goroutine when the client is a remote game, and reports a failure in the status bar.

func (*State) Seq

func (s *State) Seq() uint64

Seq returns a counter that changes whenever the profiler's state does, for views to memoize on.

func (*State) SetMetric

func (s *State) SetMetric(metric Metric)

SetMetric selects the active time-series chart in the full Profiler panel.

func (*State) SetOpen

func (s *State) SetOpen(open bool)

SetOpen opens or closes the full Profiler panel below the viewport.

func (*State) SetScope

func (s *State) SetScope(cx *core.Scope)

SetScope binds the editor's UI scope, onto which background polls post their UI refreshes and from which the Save File dialog of a trace export opens.

func (*State) Snapshot

func (s *State) Snapshot() Snapshot

Snapshot returns an immutable snapshot of the editor's current profiler readout, recorded frames, sorted zones, and highlighted spike. It is safe to call from any goroutine.

func (*State) StartPoller

func (s *State) StartPoller()

StartPoller starts polling a connected remote game in the background, unless polling already runs or the profiler is attached to Play mode.

func (*State) StopPoller

func (s *State) StopPoller()

StopPoller stops background polling and waits for an in-flight poll to finish.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL