このページはまだ日本語訳がないため、英語の原文を表示しています。
2D コアdebug
game/debug provides development-only diagnostics for NSGo games: a key-toggled frame-time graph, a live scene/layer inspector, and world-space collision and sprite-bounds wireframes — all stripped to zero-cost no-ops with -tags release.
import "github.com/nsgo-dev/game/pkg/debug"
Wiring the overlay and frame-time graph
Create an *Overlay with debug.New, wrap your game.Loop with WrapLoop, and mount overlay.View(cx) alongside your game canvas:
overlay := debug.New(debug.Options{
ToggleKey: "F3", // default when empty
TargetFPS: 60, // reference line on the frame graph
LineWidth: 1,
Scenes: func() []debug.SceneSnapshot {
return []debug.SceneSnapshot{
{
Name: "world",
Layers: []debug.LayerSnapshot{
{Name: "terrain", Space: "world", Objects: 1},
{Name: "actors", Space: "world", Objects: len(actorsBatch.Sprites)},
{Name: "hud", Space: "screen", Objects: 3},
},
},
}
},
})
overlay.WrapLoop(loop)
loop.Run(cx)
return core.View{
Style: core.Style{FlexGrow: 1, FlexShrink: 1},
Children: []core.Node{
gameCanvas,
overlay.View(cx), // returns nil under -tags release
},
}
WrapLoop(l)wrapsl.Updateandl.Drawto time each frame and callRecordFrame(total, update, draw)into the fixed-sizeFrameStatsring buffer (FrameHistory = 120samples, zero per-frame heap allocations).overlay.Stats()exposesFPS(),Average(),Latest(),MaxTotal(),Len(),At(i),Samples(dst),Reset(), andDrawGraph(d, size, targetFPS)if you want to embed metrics elsewhere.- Toggling: press
ToggleKey(default"F3") or calloverlay.Toggle()/overlay.SetVisible(true). Readingoverlay.Visible()inside a reactive view orCanvas.Drawsubscribes automatically.
Drawing collision and sprite-bounds wireframes
Draw world-space debug wireframes inside core.Canvas.Draw while your camera/viewport transform is active. ShapeOverlay automatically divides LineWidth by the drawing's active scale so wireframes stay crisp at any camera zoom:
d.Save()
cam.Apply(d)
worldScene.Draw(d)
// Only executes when the overlay is visible; subscribes the canvas to toggles
overlay.DrawShapes(d, func(s *debug.ShapeOverlay) {
s.DrawBox(d, playerBounds, core.RGB(0x22c55e))
s.DrawCircle(d, aggroX, aggroY, aggroRadius, core.RGB(0xf59e0b))
s.DrawBatchBounds(d, actorsBatch, core.RGB(0x38bdf8))
})
d.Restore()
Convenience shortcuts overlay.DrawBox, overlay.DrawCircle, overlay.DrawSpriteBounds, and overlay.DrawBatchBounds are also available directly on *Overlay.
DrawFighterBoxes(d, fighter, hurt, hit) strokes the hurtboxes and hitboxes a framedata Fighter has active on its current frame, hitboxes on top, mirrored as the fighter faces:
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:
- Pull via
Options.DrawStats: afunc() debug.DrawStatscalled whenever the overlay refreshes. - Push via
overlay.SetDrawStats(stats): used whenOptions.DrawStatsis nil; call it once per frame after drawing.
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'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. AnOptions.DrawStatscallback 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).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 withStartRecordingkeeps running and keeps its events.
game/mcp's game_perf_reset calls all three.
Scene inspector
Supply live scene structure in either of two ways:
- Pull via
Options.Scenes: if the callback reads NSGo signals, the inspector updates reactively; otherwise it refreshes on recorded frames and whenever you calloverlay.RefreshScenes(). - Push via
overlay.SetScenes(snapshots): updates the inspector immediately whenOptions.Scenesis nil.
AI inspector and steering guides
Inspect a chosen agent's game/ai behavior tree (with the running path highlighted) or game/flow Machine state and bounded transition history inside the overlay panel:
overlay := debug.New(debug.Options{
AI: func() debug.AISnapshot {
return debug.BehaviorTreeSnapshot("guard-1", guardInspector)
},
})
// Or push a snapshot on demand (behavior tree, state machine, or both):
overlay.SetAI(debug.StateMachineSnapshot("boss", bossFSM))
- Pull (
Options.AI) or push (SetAI/ClearAI/RefreshAI): works just likeScenes, refreshing on recorded frames or reactively whenOptions.AIreads NSGo signals. - Steering guides: inside
core.Canvas.Drawwhile your camera transform is active, draw a 2D steering agent's body radius, velocity, desired velocity, target reticle, and waypoint path withoverlay.DrawSteering(orShapeOverlay.DrawSteering,DrawVector,DrawPath,DrawTarget):
overlay.DrawSteering(d, debug.SteeringDebug{
Agent: agent,
DesiredVelocity: desiredVel,
Target: targetPos,
HasTarget: true,
Path: waypoints,
WaypointIndex: followState.Index,
VelocityScale: 0.5,
})
All AI panel views and steering draw helpers compile to zero-cost no-ops under -tags release, so none of the inspection UI or drawing code is linked into release binaries.
Stripping debug code in release builds
Build release binaries with -tags release:
go build -tags release ./...
Under -tags release, debug.Enabled() returns false, Overlay.View(cx) returns nil, and every Overlay, FrameStats, and ShapeOverlay method compiles to an empty no-op — so none of the overlay UI, frame graph, or wireframe drawing code is linked into your shipping binary.