debug

package
v0.2.2 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: 26 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 debug holds development-only tooling and overlays for NSGo games: a frame-time graph, collision and sprite-bounds wireframes, a live scene inspector, a behavior tree and state machine inspector with steering guides, an interactive dev console with typed tunables, named timing scopes with Chrome/Perfetto trace export, an asset memory tracker with budgets, and a GC/allocation monitor.

In default builds every feature is compiled in and Enabled reports true. Building with -tags release swaps the implementation for empty no-ops where Enabled reports false and Overlay.View returns nil, so release binaries link none of the overlay UI, graph, AI inspector, steering guides, console, profiler, memory tracker, GC monitor, or wireframe code.

Index

Examples

Constants

View Source
const FrameHistory = 120

FrameHistory is the number of frames retained in a FrameStats ring buffer.

Variables

This section is empty.

Functions

func AssertZeroAllocs

func AssertZeroAllocs(t testing.TB, runs int, fn func())

AssertZeroAllocs fails t if fn allocates on the heap during runs iterations, for use in CI hot-path regression tests.

func ConsoleView

func ConsoleView(cx *core.Scope, c *Console) core.View

ConsoleView returns a native NSGo view bound to c, composable inside Overlay or any game view tree.

func Enabled

func Enabled() bool

Enabled reports whether debug overlays are compiled into this build. It is true in default builds and false with -tags release.

func EstimateImageBytes

func EstimateImageBytes(w, h int) int64

EstimateImageBytes returns the uncompressed RGBA8 memory footprint (w * h * 4) for an image of size w by h, or 0 if either dimension is non-positive.

func EstimatePCMBytes

func EstimatePCMBytes(samples, channels, bytesPerSample int) int64

EstimatePCMBytes returns the uncompressed PCM memory footprint (samples * channels * bytesPerSample), or 0 if any parameter is non-positive.

func MeasureAllocs

func MeasureAllocs(runs int, fn func()) float64

MeasureAllocs wraps testing.AllocsPerRun and returns the average heap allocations per execution of fn over runs iterations (defaulting to 100 when runs <= 0).

Types

type AISnapshot

type AISnapshot struct {
	// Agent identifies the inspected agent (for example, "guard-1" or "boss").
	Agent string
	// Tree holds the behavior tree's pre-order node traces (for example, from ai.BTInspector.Walk or WalkInto).
	Tree []ai.BTNodeTrace
	// Machine holds a flow.Machine's current state and bounded transition history (for example, from m.Inspect()).
	Machine *flow.MachineInspection
}

AISnapshot describes a chosen agent's live AI state for the debug overlay panel. Set Tree to inspect a behavior tree, Machine to inspect a flow.Machine, or both.

func BehaviorTreeSnapshot

func BehaviorTreeSnapshot(agent string, ins *ai.BTInspector) AISnapshot

BehaviorTreeSnapshot builds an AISnapshot for agent by walking ins. Under -tags release, BehaviorTreeSnapshot returns a zero AISnapshot without walking ins.

func StateMachineSnapshot

func StateMachineSnapshot(agent string, m flow.MachineInspector) AISnapshot

StateMachineSnapshot builds an AISnapshot for agent from m's current state and transition history. Under -tags release, StateMachineSnapshot returns a zero AISnapshot without snapshotting m.

type AssetKind

type AssetKind uint8

AssetKind classifies tracked asset memory in a MemoryTracker.

const (
	// AssetImage identifies standalone decoded images and textures.
	AssetImage AssetKind = iota
	// AssetAtlas identifies sprite atlases and sheets.
	AssetAtlas
	// AssetAudio identifies decoded audio buffers and sound banks.
	AssetAudio
	// AssetOther identifies any other asset category.
	AssetOther
)

func (AssetKind) String

func (k AssetKind) String() string

String returns a lowercase label for k.

type CommandInfo

type CommandInfo struct {
	// Name is the command name as typed on the console.
	Name string
	// Help is the command's usage or description text.
	Help string
	// Builtin reports whether the command is built into Console.
	Builtin bool
}

CommandInfo describes one command available on a Console.

type Console

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

Console is an interactive development console supporting custom commands, range-checked typed tunables, history navigation, tab completion, and Storage persistence.

Example

A Console runs commands typed by the developer and tunes registered variables within their ranges.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/debug"
)

func main() {
	c := debug.NewConsole()
	gravity := 9.8
	c.RegisterFloat("gravity", 0, 50, &gravity)
	c.RegisterCommand("spawn", "spawn <kind>: add an enemy", func(args []string) (string, error) {
		return "spawned " + args[0], nil
	})

	out, err := c.Exec("set gravity 24.5")
	fmt.Println(out, err, gravity)
	out, err = c.Exec("spawn slime")
	fmt.Println(out, err)
	_, err = c.Exec("set gravity 99")
	fmt.Println(err != nil, gravity)
	fmt.Println(c.Complete("sp"))
}
Output:
gravity = 24.5 <nil> 24.5
spawned slime <nil>
true 24.5
[spawn]

func NewConsole

func NewConsole() *Console

NewConsole returns an empty development Console with built-in commands enabled.

func (*Console) Commands

func (c *Console) Commands() []CommandInfo

Commands returns all built-in and registered console commands sorted by name.

func (*Console) Complete

func (c *Console) Complete(prefix string) []string

Complete returns sorted completion candidates for prefix, completing command names and tunable names for get/set/help.

func (*Console) Entries

func (c *Console) Entries() []ConsoleEntry

Entries returns a copy of the current console output log.

func (*Console) Exec

func (c *Console) Exec(line string) (string, error)

Exec parses and executes one command line, updating history and output entries.

func (*Console) History

func (c *Console) History() []string

History returns a copy of executed command lines, oldest first.

func (*Console) HistoryNext

func (c *Console) HistoryNext() string

HistoryNext steps forward through command history, returning "" once past the most recent entry.

func (*Console) HistoryPrev

func (c *Console) HistoryPrev() string

HistoryPrev steps backward through command history and returns the selected command line.

func (*Console) LoadTunables

func (c *Console) LoadTunables(st core.Storage, key string) error

LoadTunables restores registered tunables from st under key. Missing entries are a no-op; unknown keys are ignored; out-of-range values return an error without mutating the tunable.

Its errors are *loaderr.Error values that name key as the file, with the line of the tunable at fault and how to fix it.

func (*Console) RegisterBool

func (c *Console) RegisterBool(name string, ptr *bool)

RegisterBool registers a bool tunable bound to ptr.

func (*Console) RegisterCommand

func (c *Console) RegisterCommand(name, help string, fn func(args []string) (string, error))

RegisterCommand registers a named console command and its help text.

func (*Console) RegisterFloat

func (c *Console) RegisterFloat(name string, minVal, maxVal float64, ptr *float64)

RegisterFloat registers a range-checked float64 tunable bound to ptr.

func (*Console) RegisterInt

func (c *Console) RegisterInt(name string, minVal, maxVal int, ptr *int)

RegisterInt registers a range-checked int tunable bound to ptr.

func (*Console) RegisterString

func (c *Console) RegisterString(name string, ptr *string)

RegisterString registers a string tunable bound to ptr.

func (*Console) SaveTunables

func (c *Console) SaveTunables(st core.Storage, key string) error

SaveTunables persists all registered tunables into st under key as JSON.

func (*Console) SetTunable

func (c *Console) SetTunable(name string, value any, clamp bool) (TunableChange, error)

SetTunable updates the named tunable to value after checking its type and numeric range, and returns the previous value with a snapshot of the tunable after the change, both taken under the same lock as the write. A float tunable takes any Go integer or float; an int tunable takes any Go integer. With clamp, a number outside the tunable's range, including an integer beyond int's range, is stored as the nearest bound and TunableChange.Clamped is set; without clamp it is refused. On error the tunable is left unchanged.

func (*Console) Tunable

func (c *Console) Tunable(name string) (TunableInfo, bool)

Tunable returns a snapshot of the named tunable and reports whether it is registered.

func (*Console) Tunables

func (c *Console) Tunables() []TunableInfo

Tunables returns a snapshot of all registered tunables sorted by name.

type ConsoleEntry

type ConsoleEntry struct {
	// Input is the raw command line that was executed.
	Input string
	// Output is the returned text or error message.
	Output string
	// IsError reports whether the command returned an error.
	IsError bool
}

ConsoleEntry is one recorded command execution in a dev Console log.

type DrawStats

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
}

DrawStats captures per-frame draw submission counts for overlay display and MCP performance readouts.

type FrameSample

type FrameSample struct {
	// Total is the elapsed time of the frame.
	Total time.Duration
	// Update is the time spent in fixed-step updates during the frame.
	Update time.Duration
	// Draw is the time spent drawing the frame.
	Draw time.Duration
	// GCHitch reports whether a GC pause occurred during this frame.
	GCHitch bool
	// Cause is an optional short explanation of a frame-time spike (such as shader compilation or asset streaming) when known by the game.
	Cause string
}

FrameSample holds the measured durations of one rendered frame.

type FrameStats

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

FrameStats keeps the last FrameHistory frame timings in a fixed-size ring buffer without per-frame heap allocations.

func (*FrameStats) At

func (s *FrameStats) At(i int) FrameSample

At returns sample i in chronological order, where 0 is the oldest retained frame and Len()-1 is the newest. Out-of-range indices return the zero FrameSample.

func (*FrameStats) Average

func (s *FrameStats) Average() FrameSample

Average returns the mean Total, Update and Draw durations across the retained samples.

func (*FrameStats) DrawGraph

func (s *FrameStats) DrawGraph(d *core.Drawing, size core.Size, targetFPS float64)

DrawGraph records a stacked update+draw bar graph of the retained frame samples into d, filling size, with a reference line at targetFPS (60 when 0 or less).

func (*FrameStats) FPS

func (s *FrameStats) FPS() float64

FPS returns the average frame rate in frames per second across the retained samples, or 0 when empty.

func (*FrameStats) Latest

func (s *FrameStats) Latest() FrameSample

Latest returns the most recently recorded sample, or the zero FrameSample when empty.

func (*FrameStats) Len

func (s *FrameStats) Len() int

Len returns how many samples are currently stored, up to FrameHistory.

func (*FrameStats) MaxTotal

func (s *FrameStats) MaxTotal() time.Duration

MaxTotal returns the longest Total frame duration among the retained samples.

func (*FrameStats) Record

func (s *FrameStats) Record(total, update, draw time.Duration)

Record appends one frame's timings to the ring buffer, overwriting the oldest sample once full.

Negative durations are clamped to zero. When total is zero and update or draw is positive, total defaults to update+draw.

func (*FrameStats) Reset

func (s *FrameStats) Reset()

Reset clears all recorded samples.

func (*FrameStats) Samples

func (s *FrameStats) Samples(dst []FrameSample) []FrameSample

Samples appends the retained samples in chronological order to dst and returns the resulting slice.

type GCFrameSample

type GCFrameSample struct {
	// FrameDuration is the frame duration passed to SampleFrame.
	FrameDuration time.Duration
	// CyclesDelta is the number of GC cycles completed since the previous sample.
	CyclesDelta uint64
	// Pause is the estimated total GC pause time observed during this frame.
	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
}

GCFrameSample records GC metrics sampled for one frame by a GCMonitor.

type GCMonitor

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

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.

func NewGCMonitor

func NewGCMonitor(historyLen int) *GCMonitor

NewGCMonitor returns a GCMonitor retaining up to historyLen recent frame samples (defaulting to FrameHistory when <= 0).

func (*GCMonitor) AllocBytesPerFrame

func (m *GCMonitor) AllocBytesPerFrame() float64

AllocBytesPerFrame returns the average number of heap bytes allocated per frame across the retained history window, or 0 when empty.

func (*GCMonitor) AllocsPerFrame

func (m *GCMonitor) AllocsPerFrame() float64

AllocsPerFrame returns the average number of heap objects allocated per frame across the retained history window, or 0 when empty.

func (*GCMonitor) At

func (m *GCMonitor) At(i int) GCFrameSample

At returns sample i in chronological order (0 is oldest, Len()-1 is newest).

func (*GCMonitor) HeapObjectsBytes

func (m *GCMonitor) HeapObjectsBytes() uint64

HeapObjectsBytes returns the most recently sampled /memory/classes/heap/objects:bytes value.

func (*GCMonitor) LastPause

func (m *GCMonitor) LastPause() time.Duration

LastPause returns the most recent non-zero GC pause observed by this monitor.

func (*GCMonitor) Latest

func (m *GCMonitor) Latest() GCFrameSample

Latest returns the most recently sampled GCFrameSample, or the zero value when empty.

func (*GCMonitor) Len

func (m *GCMonitor) Len() int

Len returns how many frame samples are currently retained in history.

func (*GCMonitor) MaxPause

func (m *GCMonitor) MaxPause() time.Duration

MaxPause returns the longest per-frame GC pause observed by this monitor.

func (*GCMonitor) RecentHitches

func (m *GCMonitor) RecentHitches() int

RecentHitches returns how many frames in the retained history ring buffer experienced a GC pause.

func (*GCMonitor) Reset

func (m *GCMonitor) Reset()

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 (*GCMonitor) SampleFrame

func (m *GCMonitor) SampleFrame(frameDur time.Duration) GCFrameSample

SampleFrame reads runtime/metrics for the completed frame and returns its GCFrameSample without heap allocations in steady state.

func (*GCMonitor) TotalCycles

func (m *GCMonitor) TotalCycles() uint64

TotalCycles returns the cumulative GC cycle count reported by /gc/cycles/total:gc-cycles.

type GroupMemory

type GroupMemory struct {
	// Group is the asset group name, such as "level1" or "ui".
	Group string
	// TotalBytes is the total tracked bytes across all assets in the group.
	TotalBytes int64
	// Budget is the configured byte budget for the group, or 0 when unbounded.
	Budget int64
	// OverBudget reports whether Budget > 0 and TotalBytes > Budget.
	OverBudget bool
	// Count is the number of tracked assets currently in the group.
	Count int
	// ByKind maps each AssetKind present in the group to its tracked byte total.
	ByKind map[AssetKind]int64
}

GroupMemory reports the tracked memory for one asset group.

type LayerSnapshot

type LayerSnapshot struct {
	// Name identifies the layer, such as "terrain", "actors" or "hud".
	Name string
	// Space is the coordinate space the layer draws in, such as "world" or "screen".
	Space string
	// Objects is the number of live objects on the layer.
	Objects int
}

LayerSnapshot describes one layer within a SceneSnapshot.

type MemoryTracker

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

MemoryTracker accounts for decoded asset memory grouped by owner (such as level or scene) and validates per-group and total byte budgets.

Example

A MemoryTracker adds up decoded asset sizes per group and checks them against budgets.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/debug"
)

func main() {
	m := debug.NewMemoryTracker()
	m.SetBudget("level-1", 8<<20)
	m.Track("level-1", "tiles.png", debug.AssetImage, debug.EstimateImageBytes(1024, 1024))
	m.Track("level-1", "boss.png", debug.AssetImage, debug.EstimateImageBytes(1024, 1024))
	fmt.Println(m.GroupBytes("level-1"), m.CheckBudget("level-1") == nil)

	m.Track("level-1", "music.pcm", debug.AssetAudio, debug.EstimatePCMBytes(48000*60, 2, 2))
	fmt.Println(m.CheckBudget("level-1") == nil)
	m.ReleaseGroup("level-1")
	fmt.Println(m.TotalBytes())
}
Output:
8388608 true
false
0

func NewMemoryTracker

func NewMemoryTracker() *MemoryTracker

NewMemoryTracker returns an empty asset MemoryTracker.

func (*MemoryTracker) CheckAllBudgets

func (m *MemoryTracker) CheckAllBudgets() error

CheckAllBudgets validates the total budget and every configured per-group budget, returning a joined error if any are exceeded.

func (*MemoryTracker) CheckBudget

func (m *MemoryTracker) CheckBudget(group string) error

CheckBudget returns an error if group has a configured budget and its tracked bytes exceed that budget.

func (*MemoryTracker) GroupBytes

func (m *MemoryTracker) GroupBytes(group string) int64

GroupBytes returns the total tracked bytes currently held by group.

func (*MemoryTracker) Groups

func (m *MemoryTracker) Groups() []GroupMemory

Groups returns a sorted snapshot of all groups with tracked assets and their per-kind byte breakdowns.

func (*MemoryTracker) ReleaseGroup

func (m *MemoryTracker) ReleaseGroup(group string)

ReleaseGroup drops all tracked assets and bytes belonging to group. Any configured budget for group is retained.

func (*MemoryTracker) SetBudget

func (m *MemoryTracker) SetBudget(group string, maxBytes int64)

SetBudget sets the maximum allowed bytes for group. Passing maxBytes <= 0 removes the budget for group.

func (*MemoryTracker) SetTotalBudget

func (m *MemoryTracker) SetTotalBudget(maxBytes int64)

SetTotalBudget sets the maximum allowed total bytes across all groups. Passing maxBytes <= 0 removes the total budget.

func (*MemoryTracker) TotalBudget

func (m *MemoryTracker) TotalBudget() int64

TotalBudget returns the configured total byte budget, or 0 when none is set.

func (*MemoryTracker) TotalBytes

func (m *MemoryTracker) TotalBytes() int64

TotalBytes returns the total tracked bytes across all asset groups.

func (*MemoryTracker) Track

func (m *MemoryTracker) Track(group, name string, kind AssetKind, bytes int64)

Track records or updates an asset named name in group with its AssetKind and size in bytes. Negative byte counts are clamped to 0.

func (*MemoryTracker) Untrack

func (m *MemoryTracker) Untrack(group, name string)

Untrack removes a previously tracked asset from group.

type NetChannelStats

type NetChannelStats struct {
	// Channel is the transport delivery channel (ChannelReliableOrdered or ChannelUnreliable).
	Channel netplay.Channel
	// BytesPerSec is the combined send and receive byte rate on this channel.
	BytesPerSec float64
	// PacketsPerSec is the combined send and receive packet rate on this channel.
	PacketsPerSec float64
	// SendBytesPerSec is the outbound byte rate on this channel.
	SendBytesPerSec float64
	// RecvBytesPerSec is the inbound byte rate on this channel.
	RecvBytesPerSec float64
	// SendPacketsPerSec is the outbound packet rate on this channel.
	SendPacketsPerSec float64
	// RecvPacketsPerSec is the inbound packet rate on this channel.
	RecvPacketsPerSec float64
}

NetChannelStats reports live throughput rates for one netplay.Channel.

type NetMessageEvent

type NetMessageEvent struct {
	// Dir is netplay.CaptureSend ("send") or netplay.CaptureRecv ("recv").
	Dir netplay.CaptureDirection
	// Peer is the remote peer ID.
	Peer netplay.PeerID
	// Channel is the transport delivery channel.
	Channel netplay.Channel
	// Type is the decoded wire message type (such as "replication.delta", "rollback.single_input", "relay.members", or "raw").
	Type string
	// Bytes is the payload size in bytes.
	Bytes int
}

NetMessageEvent records one recently sent or received packet's decoded wire message type.

type NetMonitor

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

NetMonitor tracks per-channel and per-peer throughput rates, Transport InboxStats, and recent decoded wire message types using reused buffers so per-frame updates perform zero heap allocations in steady state.

func NewNetMonitor

func NewNetMonitor(recentLimit int) *NetMonitor

NewNetMonitor creates a NetMonitor retaining up to recentLimit recent message types (defaulting to 12 when <= 0).

func (*NetMonitor) ObserveRecv

func (m *NetMonitor) ObserveRecv(pkt netplay.Packet)

ObserveRecv records one inbound packet and decodes its wire message type into reused buffers without steady-state allocations.

func (*NetMonitor) ObserveSend

func (m *NetMonitor) ObserveSend(to netplay.PeerID, ch netplay.Channel, payload []byte)

ObserveSend records one outbound packet and decodes its wire message type into reused buffers without steady-state allocations.

func (*NetMonitor) Reset

func (m *NetMonitor) Reset()

Reset clears all accumulated traffic counters, peer trackers, and recent message history while keeping allocated slice capacities.

func (*NetMonitor) SampleFrame

func (m *NetMonitor) SampleFrame(dt time.Duration)

SampleFrame commits the current frame's packet/byte counts into the sliding rate window, polls InboxStats from any wrapped InboxReporter, and refreshes the cached NetSnapshot without steady-state heap allocations.

func (*NetMonitor) Snapshot

func (m *NetMonitor) Snapshot() NetSnapshot

Snapshot returns the most recent NetSnapshot built by SampleFrame, backed by m's reused buffers so calling it in Options.Net allocates zero bytes.

func (*NetMonitor) Wrap

func (m *NetMonitor) Wrap(inner netplay.Transport) netplay.Transport

Wrap wraps inner so every successful Send and every Recv packet is observed by m with zero steady-state heap allocations. If inner implements netplay.InboxReporter, SampleFrame polls its InboxStats automatically and the wrapper forwards InboxReporter calls.

type NetPeerStats

type NetPeerStats struct {
	// Peer identifies the remote peer (or netplay.PeerBroadcast for broadcast sends).
	Peer netplay.PeerID
	// BytesPerSec is the combined send and receive byte rate with this peer.
	BytesPerSec float64
	// PacketsPerSec is the combined send and receive packet rate with this peer.
	PacketsPerSec float64
	// SendBytesPerSec is the outbound byte rate to this peer.
	SendBytesPerSec float64
	// RecvBytesPerSec is the inbound byte rate from this peer.
	RecvBytesPerSec float64
	// SendPacketsPerSec is the outbound packet rate to this peer.
	SendPacketsPerSec float64
	// RecvPacketsPerSec is the inbound packet rate from this peer.
	RecvPacketsPerSec float64
}

NetPeerStats reports live throughput rates for one remote peer.

type NetSnapshot

type NetSnapshot struct {
	// Inbox holds the transport's InboxStats counters.
	Inbox netplay.InboxStats
	// Channels holds per-channel throughput rates.
	Channels []NetChannelStats
	// Peers holds per-peer throughput rates.
	Peers []NetPeerStats
	// Recent holds the most recent N decoded message events, oldest to newest.
	Recent []NetMessageEvent
}

NetSnapshot describes live network traffic rates, inbox counters, and recent message types for the debug overlay panel.

type Options

type Options struct {
	// ToggleKey is the key binding that shows and hides the overlay; "F3" when empty.
	ToggleKey string
	// Visible sets whether the overlay starts shown.
	Visible bool
	// TargetFPS is the reference frame rate drawn on the frame-time graph; 60 when 0 or less.
	TargetFPS float64
	// LineWidth is the base stroke width, in screen points, for collision and bounds wireframes; 1 when 0 or less.
	LineWidth float32
	// Scenes, when set, supplies the active scenes and layers shown by the scene inspector. If it reads NSGo signals, the inspector updates as those signals change; otherwise it refreshes on recorded frames and RefreshScenes.
	Scenes func() []SceneSnapshot
	// Now is the clock WrapLoop uses to measure Update and Draw durations; time.Now when nil.
	Now func() time.Time
	// Console, when set, renders an interactive dev console alongside the overlay.
	Console *Console
	// Profiler, when set, displays top named timing scopes inside the overlay.
	Profiler *Profiler
	// Memory, when set, displays asset memory usage and budget status inside the overlay.
	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
	// AI, when set, supplies the chosen agent's behavior tree or state machine snapshot shown in the AI inspector panel.
	// If it reads NSGo signals, the panel updates reactively; otherwise it refreshes on recorded frames and RefreshAI.
	AI func() AISnapshot
	// Net, when set, supplies live network traffic rates, InboxStats counters, and recent decoded message types shown in the network inspector panel.
	// Callers can build NetSnapshot without per-frame allocations using NetMonitor.
	Net func() NetSnapshot
}

Options configures an Overlay. Every field is optional and takes a sensible default when zero.

type Overlay

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

Overlay coordinates the development debug HUD: a key-toggled panel with a frame-time graph and scene inspector, plus world-space collision and sprite-bounds wireframes.

Example

An Overlay's FrameStats keeps recent frame timings for its graph; RecordFrame adds one, as WrapLoop does for each frame of a game.Loop.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/debug"
)

func main() {
	o := debug.New(debug.Options{ToggleKey: "F3"})
	for _, ms := range []time.Duration{16, 17, 18} {
		o.RecordFrame(ms*time.Millisecond, 4*time.Millisecond, 8*time.Millisecond)
	}
	stats := o.Stats()
	fmt.Println(stats.Len(), stats.Average().Total, stats.MaxTotal())
	fmt.Println(o.Visible())
	o.Toggle()
	fmt.Println(o.Visible())
}
Output:
3 17ms 18ms
false
true

func New

func New(opts Options) *Overlay

New returns a configured debug overlay.

func (*Overlay) AISnapshot

func (o *Overlay) AISnapshot() AISnapshot

AISnapshot returns the currently displayed AI snapshot from Options.AI if configured, or the most recent SetAI value.

func (*Overlay) Attach

func (o *Overlay) Attach(cx *core.Scope)

Attach wires the overlay's reactive signals and toggle key onto cx. Calling Attach more than once on the same scope is a no-op; View calls Attach automatically.

func (*Overlay) ClearAI

func (o *Overlay) ClearAI()

ClearAI clears the pushed AI snapshot and hides the AI inspector panel when Options.AI is nil.

func (*Overlay) ClearNet

func (o *Overlay) ClearNet()

ClearNet clears the pushed network snapshot and hides the network inspector panel when Options.Net is nil.

func (*Overlay) Console

func (o *Overlay) Console() *Console

Console returns the Console attached to the overlay via Options.Console, or nil.

func (*Overlay) DrawBatchBounds

func (o *Overlay) DrawBatchBounds(d *core.Drawing, batch *sprite.Batch, col core.Color)

DrawBatchBounds draws the untrimmed bounding wireframes of all sprites in batch under d's active transform while the overlay is visible.

func (*Overlay) DrawBox

func (o *Overlay) DrawBox(d *core.Drawing, b core.Bounds, col core.Color)

DrawBox draws a wireframe box under d's active transform while the overlay is visible.

func (*Overlay) DrawCircle

func (o *Overlay) DrawCircle(d *core.Drawing, x, y, r float32, col core.Color)

DrawCircle draws a wireframe circle under d's active transform while the overlay is visible.

func (*Overlay) DrawFighterBoxes

func (o *Overlay) DrawFighterBoxes(d *core.Drawing, f *framedata.Fighter, hurt, hit core.Color)

DrawFighterBoxes draws f's active hurtboxes and hitboxes as wireframes under d's active transform while the overlay is visible.

func (*Overlay) DrawPath

func (o *Overlay) DrawPath(d *core.Drawing, path []core.Point, col core.Color)

DrawPath draws a waypoint polyline under d's active transform while the overlay is visible.

func (*Overlay) DrawShapes

func (o *Overlay) DrawShapes(d *core.Drawing, fn func(*ShapeOverlay))

DrawShapes calls fn with the overlay's ShapeOverlay only while the overlay is visible. When called inside a core.Canvas.Draw callback, toggling the overlay automatically redraws the canvas.

func (*Overlay) DrawSpriteBounds

func (o *Overlay) DrawSpriteBounds(d *core.Drawing, s *sprite.Sprite, col core.Color)

DrawSpriteBounds draws the untrimmed bounding wireframe of s under d's active transform while the overlay is visible.

func (*Overlay) DrawStats

func (o *Overlay) DrawStats() DrawStats

DrawStats returns the current per-frame draw statistics from Options.DrawStats if configured, or the most recent SetDrawStats value.

func (*Overlay) DrawSteering

func (o *Overlay) DrawSteering(d *core.Drawing, info SteeringDebug)

DrawSteering draws steering agent guides (velocity, desired velocity, target, path) under d's active transform while the overlay is visible.

func (*Overlay) DrawTarget

func (o *Overlay) DrawTarget(d *core.Drawing, target core.Point, col core.Color)

DrawTarget draws a target reticle under d's active transform while the overlay is visible.

func (*Overlay) DrawVector

func (o *Overlay) DrawVector(d *core.Drawing, origin, vec core.Point, col core.Color)

DrawVector draws a directional vector arrow under d's active transform while the overlay is visible.

func (*Overlay) GC

func (o *Overlay) GC() *GCMonitor

GC returns the GCMonitor attached to the overlay via Options.GC, or nil.

func (*Overlay) HasDrawStats

func (o *Overlay) HasDrawStats() bool

HasDrawStats reports whether draw statistics have been configured via Options.DrawStats or pushed via SetDrawStats.

func (*Overlay) Memory

func (o *Overlay) Memory() *MemoryTracker

Memory returns the MemoryTracker attached to the overlay via Options.Memory, or nil.

func (*Overlay) NetSnapshot

func (o *Overlay) NetSnapshot() NetSnapshot

NetSnapshot returns the currently displayed network snapshot from Options.Net if configured, or the most recent SetNet value.

func (*Overlay) NoteFrameCause

func (o *Overlay) NoteFrameCause(cause string)

NoteFrameCause attaches a short explanation (for example "first use of torch_glow compiled its shader") to the next frame recorded by RecordFrame. Calling it with an empty string is a no-op; calling it again before RecordFrame replaces the pending cause.

func (*Overlay) Profiler

func (o *Overlay) Profiler() *Profiler

Profiler returns the Profiler attached to the overlay via Options.Profiler, or nil.

func (*Overlay) RecordFrame

func (o *Overlay) RecordFrame(total, update, draw time.Duration)

RecordFrame records one frame's total, update and draw durations into the ring buffer, samples the attached GCMonitor (if any), and refreshes the visible overlay graph.

func (*Overlay) RefreshAI

func (o *Overlay) RefreshAI()

RefreshAI tells the AI inspector panel to re-read Options.AI immediately.

func (*Overlay) RefreshNet

func (o *Overlay) RefreshNet()

RefreshNet tells the network inspector panel to re-read Options.Net immediately.

func (*Overlay) RefreshScenes

func (o *Overlay) RefreshScenes()

RefreshScenes tells the scene inspector to re-read Options.Scenes immediately.

func (*Overlay) ResetStats

func (o *Overlay) ResetStats()

ResetStats clears the overlay's recorded frame timings and pushed draw statistics and refreshes the visible overlay.

func (*Overlay) SetAI

func (o *Overlay) SetAI(snap AISnapshot)

SetAI updates the AI inspector panel's pushed snapshot and immediately refreshes the panel. It is used when Options.AI is nil.

func (*Overlay) SetDrawStats

func (o *Overlay) SetDrawStats(s DrawStats)

SetDrawStats updates the overlay's pushed per-frame draw statistics and refreshes the visible overlay. It is used when Options.DrawStats is nil.

func (*Overlay) SetNet

func (o *Overlay) SetNet(snap NetSnapshot)

SetNet updates the network inspector panel's pushed snapshot and immediately refreshes the panel. It is used when Options.Net is nil.

func (*Overlay) SetScenes

func (o *Overlay) SetScenes(scenes []SceneSnapshot)

SetScenes updates the scene inspector's snapshot list and immediately refreshes the inspector view. It is used when Options.Scenes is nil.

func (*Overlay) SetVisible

func (o *Overlay) SetVisible(v bool)

SetVisible shows or hides the overlay and its world-space wireframes.

func (*Overlay) Stats

func (o *Overlay) Stats() *FrameStats

Stats returns the overlay's frame-time ring buffer.

func (*Overlay) Toggle

func (o *Overlay) Toggle()

Toggle flips the overlay's visibility.

func (*Overlay) View

func (o *Overlay) View(cx *core.Scope) core.Node

View attaches the overlay to cx and returns a non-intrusive native NSGo overlay node positioned over the game view.

func (*Overlay) Visible

func (o *Overlay) Visible() bool

Visible reports whether the overlay is currently shown. Read inside a reactive NSGo view or drawing, it subscribes to visibility toggles.

func (*Overlay) WrapLoop

func (o *Overlay) WrapLoop(l *game.Loop)

WrapLoop wraps l.Update and l.Draw so every frame automatically times Update and Draw and calls RecordFrame.

type Profiler

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

Profiler records named timing scopes per frame with zero steady-state allocations, produces top-scope summaries for Overlay, emits optional runtime/trace regions, and exports Chrome/Perfetto Trace Event Format JSON.

Example

A Profiler times named scopes per frame and reports the costliest ones; SetNow gives it a clock, here one that advances by hand.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/debug"
)

func main() {
	now := time.Unix(0, 0)
	p := debug.NewProfiler(0)
	p.SetNow(func() time.Time { return now })

	p.BeginFrame()
	physics := p.Begin("physics")
	now = now.Add(3 * time.Millisecond)
	p.End(physics)
	for range 2 {
		ai := p.Begin("ai")
		now = now.Add(time.Millisecond)
		p.End(ai)
	}
	p.EndFrame()

	for _, s := range p.TopScopes(2) {
		fmt.Println(s.Name, s.Total, s.Calls)
	}
}
Output:
physics 3ms 1
ai 2ms 2

func NewProfiler

func NewProfiler(maxRecordedFrames int) *Profiler

NewProfiler returns a Profiler capable of recording up to maxRecordedFrames frames (defaulting to 300 when <= 0).

func (*Profiler) Begin

func (p *Profiler) Begin(name string) ScopeToken

Begin opens a named timing scope and returns a ScopeToken to pass to End.

func (*Profiler) BeginFrame

func (p *Profiler) BeginFrame()

BeginFrame resets per-frame scope accumulators for the next frame.

func (*Profiler) End

func (p *Profiler) End(tok ScopeToken)

End closes a timing scope started by Begin or Scope.

func (*Profiler) EndFrame

func (p *Profiler) EndFrame()

EndFrame finalizes the current frame's scope timings and advances active recording if enabled.

func (*Profiler) RecordedFrames

func (p *Profiler) RecordedFrames() int

RecordedFrames returns the number of completed frames captured in the current or most recent recording.

func (*Profiler) Recording

func (p *Profiler) Recording() bool

Recording reports whether trace recording is currently active.

func (*Profiler) Reset

func (p *Profiler) Reset()

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 (*Profiler) Scope

func (p *Profiler) Scope(name string) ScopeToken

Scope opens a named timing scope for use with defer: `defer p.Scope("physics").End()`.

func (*Profiler) SetNow

func (p *Profiler) SetNow(fn func() time.Time)

SetNow overrides the clock used to timestamp scopes, primarily for deterministic tests. Passing nil restores time.Now.

func (*Profiler) SetTraceContext

func (p *Profiler) SetTraceContext(ctx context.Context)

SetTraceContext sets the context passed to runtime/trace.StartRegion when Go execution tracing is active.

func (*Profiler) StartRecording

func (p *Profiler) StartRecording(frames int)

StartRecording begins recording scope events for up to frames frames (capped by maxRecordedFrames).

func (*Profiler) StopRecording

func (p *Profiler) StopRecording()

StopRecording ends an active trace recording early, keeping already recorded frames.

func (*Profiler) TopScopes

func (p *Profiler) TopScopes(limit int) []ScopeSummary

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 (*Profiler) WriteChromeTrace

func (p *Profiler) WriteChromeTrace(w io.Writer) error

WriteChromeTrace writes recorded scope events in Chrome/Perfetto Trace Event Format JSON to w. Each distinct scope name is assigned its own tid track and thread_name metadata event so Perfetto displays one track per scope.

type SceneSnapshot

type SceneSnapshot struct {
	// Name identifies the scene, such as "title" or "world".
	Name string
	// Layers are the scene's layers in draw order.
	Layers []LayerSnapshot
}

SceneSnapshot describes one active scene for the scene inspector.

type ScopeSummary

type ScopeSummary struct {
	// Name is the scope identifier passed to Begin or Scope.
	Name string
	// Total is the total duration spent in this scope during the most recent frame.
	Total time.Duration
	// Avg is the rolling average per-frame duration across recent frames.
	Avg time.Duration
	// Max is the longest per-frame duration observed across recent frames.
	Max time.Duration
	// Calls is the number of times this scope ran during the most recent frame.
	Calls int
}

ScopeSummary summarizes a named timing scope's cost for overlay display.

type ScopeToken

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

ScopeToken is returned by Profiler.Begin or Profiler.Scope and passed to End to close a timing scope without heap allocations.

func (ScopeToken) End

func (t ScopeToken) End()

End closes the timing scope associated with t. It is safe to call on a zero ScopeToken.

type ShapeOverlay

type ShapeOverlay struct {
	// LineWidth is the desired stroke width in screen points; 1 when 0 or less.
	LineWidth float32
}

ShapeOverlay draws collision shapes and sprite bounds as wireframes into a core.Drawing under whatever camera or viewport transform is already active on it.

Stroke widths are automatically divided by the drawing's active scale so wireframes keep a steady thickness at any camera zoom.

func (*ShapeOverlay) DrawBatchBounds

func (s *ShapeOverlay) DrawBatchBounds(d *core.Drawing, batch *sprite.Batch, col core.Color)

DrawBatchBounds strokes the untrimmed bounding box of every visible sprite in batch in col under d's active transform.

func (*ShapeOverlay) DrawBox

func (s *ShapeOverlay) DrawBox(d *core.Drawing, b core.Bounds, col core.Color)

DrawBox strokes the axis-aligned rectangle b in col under d's active transform, leaving d's state unchanged.

func (*ShapeOverlay) DrawCircle

func (s *ShapeOverlay) DrawCircle(d *core.Drawing, x, y, r float32, col core.Color)

DrawCircle strokes a circle centered at (x, y) with radius r in col under d's active transform, leaving d's state unchanged.

func (*ShapeOverlay) DrawFighterBoxes

func (s *ShapeOverlay) DrawFighterBoxes(d *core.Drawing, f *framedata.Fighter, hurt, hit core.Color)

DrawFighterBoxes strokes the boxes f's current move has active on its current frame under d's active transform: hurtboxes in hurt, then hitboxes in hit on top, mirrored as the fighter faces.

func (*ShapeOverlay) DrawPath

func (s *ShapeOverlay) DrawPath(d *core.Drawing, path []core.Point, col core.Color)

DrawPath strokes a waypoint polyline and small waypoint markers in col under d's active transform.

func (*ShapeOverlay) DrawSpriteBounds

func (s *ShapeOverlay) DrawSpriteBounds(d *core.Drawing, sp *sprite.Sprite, col core.Color)

DrawSpriteBounds strokes the untrimmed bounding box of sp in col, respecting its origin, scale, flip and rotation, under d's active transform.

func (*ShapeOverlay) DrawSteering

func (s *ShapeOverlay) DrawSteering(d *core.Drawing, info SteeringDebug)

DrawSteering draws world-space debug guides for a 2D steering agent under d's active transform: its waypoint path, target reticle and sightline, body radius, desired velocity arrow, and current velocity arrow.

func (*ShapeOverlay) DrawTarget

func (s *ShapeOverlay) DrawTarget(d *core.Drawing, target core.Point, col core.Color)

DrawTarget strokes a crosshair reticle at target in col under d's active transform.

func (*ShapeOverlay) DrawVector

func (s *ShapeOverlay) DrawVector(d *core.Drawing, origin, vec core.Point, col core.Color)

DrawVector strokes a directional arrow from origin to origin+vec in col under d's active transform, keeping line width and arrowhead size steady in screen points across camera zooms.

type SteeringColors

type SteeringColors struct {
	// Agent colors the agent's collision-radius wireframe (default: 0xE2E8F0).
	Agent core.Color
	// Velocity colors the current velocity vector arrow (default: 0x22C55E).
	Velocity core.Color
	// Desired colors the desired velocity vector arrow (default: 0x38BDF8).
	Desired core.Color
	// Target colors the target reticle and sightline (default: 0xF59E0B).
	Target core.Color
	// Path colors the waypoint polyline and waypoint markers (default: 0xA78BFA).
	Path core.Color
}

SteeringColors customizes the colors used by DrawSteering. Zero fields take high-contrast defaults.

type SteeringDebug

type SteeringDebug struct {
	// Agent is the steering agent whose position, radius, and current velocity are drawn.
	Agent ai.Agent
	// DesiredVelocity is the agent's desired velocity vector (drawn when non-zero).
	DesiredVelocity core.Point
	// Target is the agent's current target position (drawn when HasTarget is true).
	Target core.Point
	// HasTarget reports whether Target should be drawn, allowing (0, 0) as a valid target.
	HasTarget bool
	// Path is an optional sequence of world-space waypoints being followed.
	Path []core.Point
	// WaypointIndex highlights Path[WaypointIndex] as the active waypoint when in [0, len(Path)); set negative to omit active highlighting.
	WaypointIndex int
	// VelocityScale scales Velocity and DesiredVelocity into world drawing units (1 when 0 or less).
	VelocityScale float32
	// Colors overrides default colors for any non-zero color field.
	Colors SteeringColors
}

SteeringDebug holds the debug visualization inputs for one 2D steering agent.

type TunableChange

type TunableChange struct {
	// Old is the tunable's value before the change.
	Old any
	// Tunable describes the tunable after the change; its Value is the value stored.
	Tunable TunableInfo
	// Clamped reports whether the requested value lay outside the tunable's range and was stored as the nearest bound.
	Clamped bool
}

TunableChange is the result of Console.SetTunable.

type TunableInfo

type TunableInfo struct {
	// Name is the tunable's registered name.
	Name string
	// Type is "float", "int", "bool" or "string".
	Type string
	// Value is the tunable's current value (float64, int, bool or string).
	Value any
	// Default is the value captured when the tunable was registered.
	Default any
	// Min is the inclusive lower bound for numeric tunables ("float" or "int"), or nil for other types.
	Min any
	// Max is the inclusive upper bound for numeric tunables ("float" or "int"), or nil for other types.
	Max any
}

TunableInfo describes one registered tunable variable on a Console.

Jump to

Keyboard shortcuts

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