GitHubはじめる

API リファレンスはソースコード内の Go ドキュメントコメントから生成されており、英語で記述されています。

package gameui

import "github.com/nsgo-dev/game/pkg/gameui"

概要

Package gameui provides stylized in-canvas menus, spatial focus navigation, virtual-resolution scaling, and world-anchored native NSGo overlays.

Build a widget tree from containers (Panel, VBox, HBox) and widgets (Label, Button, Toggle, Slider, List, ProgressBar, Spacer), wrap it in a Root, and drive layout, input, and drawing from your game's Canvas:

  • Call Root.Layout(bounds) to compute exact non-overlapping widget rectangles with padding, spacing, fixed/flex sizing, and alignment.
  • Configure Root.Viewport (or Viewport.Draw / Viewport.WindowToVirtual) for virtual-resolution Fit/Letterbox/Fill/Stretch/Integer scaling and accurate pointer/touch hit-testing.
  • Route pointer/touch events via OnPointerMove, OnPointerDown, OnPointerUp, or OnPress, and keyboard/gamepad navigation via SpatialNavigator (2D spatial lookup, explicit NavOverrides, StepActions, OnConfirm/OnBack, and customizable FocusRingStyle) or Root.OnKeyDown.
  • Call Root.Draw(d, bounds) inside Canvas.Draw; all operations run inside Save/Restore using Path fills and strokes so caller drawing state is never mutated.
  • Customize visuals with Theme (starting from DefaultTheme), NineSlice / FrameDrawer hooks, and custom TextDrawer / TextMeasurer hooks for bitmap fonts.
  • Drop in SettingsMenu for a ready-to-use Audio, Video, Controls (rebinding), Language, and Accessibility screen persisted through save.DefaultSettingsStore and playable with mouse, touch, keyboard, and gamepad alone.
  • Mount AnchorOverlay over your game Canvas and call Sync(proj) each frame to pin native NSGo views (name tags, speech bubbles, text inputs) to 2D world positions with automatic off-screen hiding.

目次

定数

const (
	// MinTouchTargetSize is the minimum touch target diameter in points required on phones and tablets.
	MinTouchTargetSize float32 = 44
	// MinTextContrastRatio is the minimum WCAG 2.1 contrast ratio required for screen text against its fill.
	MinTextContrastRatio float64 = 4.5
)
const (
	// SettingsCustomResolution is the key inside save.Settings.Custom storing the selected resolution ID.
	SettingsCustomResolution = "resolution"
	// SettingsCustomReduceFlashes is the key inside save.Settings.Custom storing the flash-reduction toggle.
	SettingsCustomReduceFlashes = "reduce_flashes"
)
const DefaultScreenFontSize float32 = 12

DefaultScreenFontSize is the default virtual font size in points used for screen files when a node omits fontSize.

const ScreenFormatVersion = 1

ScreenFormatVersion is the *.screen.yaml schema version this package reads and writes.

const ScreenSchemaComment = "# yaml-language-server: $schema=" + ScreenSchemaURL

ScreenSchemaComment is the first line EncodeScreen writes: a YAML comment pointing a YAML language server at ScreenSchemaURL. ParseScreen ignores it like any other comment.

const ScreenSchemaURL = "https://game.nsgo.dev/schemas/screen.v1.json"

ScreenSchemaURL is where the JSON Schema of version 1 screen documents is published. EncodeScreen writes it in a yaml-language-server comment on the first line so editors and AI tools validate and complete screen files as they are written.

関数

func ApplyBindingsToActions(a *input.Actions, bindings map[string][]string, preserveRegions bool)

ApplyBindingsToActions updates a's action bindings from save.Settings.Bindings. When preserveRegions is true, existing TouchRegion and MouseRegion inputs on each action are preserved alongside the rebound keyboard, mouse-button, and gamepad bindings.

func DrawFocusRing(d *core.Drawing, bounds core.Bounds, radius float32, style *FocusRingStyle, theme *Theme)

DrawFocusRing renders a customizable focus ring around bounds using style and theme defaults.

func EncodeScreen(doc *ScreenDoc) ([]byte, error)

EncodeScreen validates doc and writes it as deterministic 2-space YAML prefixed with ScreenSchemaComment. A document EncodeScreen writes loads with ParseScreen and saves back byte-for-byte unchanged.

func FormatBindingLabel(token string) string

FormatBindingLabel returns a concise human-readable label for a binding token (for example "Space", "A", "Pad A/South", or "Mouse Left").

func FormatBindingToken(in input.Input) string

FormatBindingToken encodes an input.Input into a portable string token suitable for save.Settings.Bindings. Returns "" for region inputs or zero inputs.

func GamepadButtonToken(b gamepad.Button) string

GamepadButtonToken returns the canonical binding token stored in save.Settings.Bindings for b (such as "gamepad:south" or "gamepad:dpad_left"), or "" if b is out of range.

func MeasureScreenText(text string, fontSize float32) (width, height float32)

MeasureScreenText estimates single-line text width and height in virtual points for screen layout and overflow checks. Full-width CJK and East Asian glyphs measure at 1.0× fontSize, spaces at 0.25× fontSize, and other glyphs at 0.5× fontSize. When fontSize <= 0, DefaultScreenFontSize (12) is used.

func ParseBindingToken(token string) (input.Input, bool)

ParseBindingToken decodes a binding token from save.Settings.Bindings into an input.Input. Supported forms are "key:<name>", "keycode:<code>", "gamepad:<button>", "mouse:<button>", and bare key names (such as "space" or "Escape") treated as keyboard keys.

func SetSettingsReduceFlashes(s *save.Settings, reduce bool)

SetSettingsReduceFlashes writes reduce into s.Custom["reduce_flashes"].

func SetSettingsResolution(s *save.Settings, id string)

SetSettingsResolution writes id into s.Custom["resolution"].

func SettingsReduceFlashesFrom(s save.Settings) bool

SettingsReduceFlashesFrom reads the flash-reduction flag from s.Custom["reduce_flashes"].

func SettingsResolutionFrom(s save.Settings) string

SettingsResolutionFrom reads the persisted resolution ID from s.Custom["resolution"], or "" if unset.

func ValidateScreen(doc *ScreenDoc) error

ValidateScreen validates doc against the version 1 *.screen.yaml schema and invariants.

型

type Align uint8

Align controls cross-axis placement in VBox and HBox, and child placement inside Panel.

const (
	// AlignDefault inherits the container's Align, or stretches when unset on a container.
	AlignDefault Align = iota
	// AlignStretch expands the child to fill the available cross-axis size unless it sets a fixed size.
	AlignStretch
	// AlignStart aligns the child to the start (left in VBox, top in HBox).
	AlignStart
	// AlignCenter centers the child along the cross axis.
	AlignCenter
	// AlignEnd aligns the child to the end (right in VBox, bottom in HBox).
	AlignEnd
)
type AnchorOverlay struct {
	// TestID optionally sets the TestID on the overlay container view.
	TestID string
	// contains filtered or unexported fields
}

AnchorOverlay renders native NSGo views anchored to 2D world positions inside a non-blocking overlay (PointerEventsNone on the overlay container, PointerEventsOn on each anchored view). Call Sync(proj) each frame to update screen coordinates in the same commit and automatically hide off-screen anchors.

func NewAnchorOverlay(cx *core.Scope) *AnchorOverlay

NewAnchorOverlay creates a signal-driven AnchorOverlay bound to cx.

func (o *AnchorOverlay) Add(anchor *WorldAnchor)

Add registers or replaces anchor by its ID. If Sync has already been called, the new anchor is immediately projected with the last WorldProjection.

func (o *AnchorOverlay) Get(id string) *WorldAnchor

Get returns the registered WorldAnchor with id, or nil if not found.

func (o *AnchorOverlay) Remove(id string) bool

Remove deletes the anchor with id from the overlay. Returns true if it existed.

func (o *AnchorOverlay) ScreenPosition(id string) (core.Point, bool)

ScreenPosition returns the last synced screen position (including OffsetX/OffsetY) and on-screen visibility for id.

func (o *AnchorOverlay) SetVisible(id string, visible bool) bool

SetVisible updates an anchor's logical visibility flag. Call Sync to apply.

func (o *AnchorOverlay) SetWorldPosition(id string, worldX, worldY float32) bool

SetWorldPosition updates an anchor's world coordinates. Call Sync to project and commit updated screen positions.

func (o *AnchorOverlay) Sync(proj WorldProjection)

Sync projects all registered anchors through proj and atomically updates their screen positions and visibility signals in a single batch so anchored views stay aligned within the same frame and off-screen anchors are hidden immediately.

func (o *AnchorOverlay) View(_ *core.Scope) core.View

View returns the non-blocking absolute overlay core.View rendering all currently visible world anchors. The container uses PointerEventsNone so clicks pass through to the game canvas underneath, while each anchored wrapper re-enables interaction with PointerEventsOn.

type AnchoredItem struct {
	ID          string
	Widget      Widget
	Anchor      ScreenAnchor
	Offset      ScreenOffsetDoc
	SafeArea    bool
	SizeMode    SizeMode
	FixedWidth  float32
	FixedHeight float32
	// PassThrough marks an unsized container whose children anchor directly against the parent's full bounds and safe area.
	PassThrough bool
}

AnchoredItem pairs a child Widget with its anchor, offset, safe-area inset preference, and sizing mode inside a ScreenCanvas.

type BuiltScreen struct {
	// Root is the interactive gameui.Root configured with the screen's Viewport and theme.
	Root *Root
	// Navigator is a SpatialNavigator attached to Root with explicit focus-order overrides wired.
	Navigator *SpatialNavigator
	// Doc is a clone of the ScreenDoc this screen was built from.
	Doc *ScreenDoc
	// Canvas is the root ScreenCanvas child of Root.
	Canvas *ScreenCanvas
	// Nodes maps every node ID in the screen to its built Widget.
	Nodes map[string]Widget
	// FocusOrder lists focusable widgets that declared an explicit focusOrder, sorted ascending.
	FocusOrder []Widget
	// contains filtered or unexported fields
}

BuiltScreen is the runtime UI tree constructed from a *.screen.yaml document.

func BuildScreen(doc *ScreenDoc, opts ScreenBuildOptions) (*BuiltScreen, error)

BuildScreen constructs a runtime BuiltScreen (including a configured gameui.Root, Viewport, safe-area anchoring, localized text, device-class visibility, and focus-order navigation) from doc.

func (s *BuiltScreen) ApplyCatalog(cat *l10n.Catalog, locale string)

ApplyCatalog refreshes all localized text nodes from cat for locale (or cat's fallback locale when locale is empty).

func (s *BuiltScreen) Draw(d *core.Drawing, bounds core.Bounds)

Draw delegates to s.Root.Draw(d, bounds).

func (s *BuiltScreen) Layout(bounds core.Bounds)

Layout delegates to s.Root.Layout(bounds).

func (s *BuiltScreen) SetDeviceClass(class DeviceClass)

SetDeviceClass updates conditional visibility for all nodes carrying deviceClasses restrictions. Passing an empty DeviceClass makes all nodes visible.

func (s *BuiltScreen) SetSafeArea(insets core.Edges)

SetSafeArea updates the safe-area insets used by subsequent Layout and Draw calls.

func (s *BuiltScreen) SetTextLookup(fn func(key string) string)

SetTextLookup refreshes all localized text nodes using fn (or the raw textKey when fn is nil).

func (s *BuiltScreen) Widget(id string) Widget

Widget returns the built Widget with id, or nil if no node has that ID.

type Button struct {
	Text           string
	OnClick        func()
	Disabled       bool
	Font           core.Font
	TextColor      core.Color
	Background     core.Color
	CornerRadius   float32
	Padding        core.Edges
	FocusOrder     int
	TouchHitSize   float32
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Nav            NavOverrides
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	// contains filtered or unexported fields
}

Button is a clickable and focusable action trigger.

func (b *Button) Bounds() core.Bounds

Bounds returns the button's laid-out rectangle.

func (b *Button) HitBounds() core.Bounds

HitBounds returns the button's interactive hit area, expanded to TouchHitSize when larger than Bounds.

type ColorRect struct {
	Color        core.Color
	CornerRadius float32
	Width        float32
	Height       float32
	MinWidth     float32
	MinHeight    float32
	Flex         float32
	Align        Align
	Hidden       bool
	// contains filtered or unexported fields
}

ColorRect draws a solid or translucent filled rectangle (such as a modal backdrop or HUD plate).

func (c *ColorRect) Bounds() core.Bounds

Bounds returns the rectangle's laid-out bounds.

type Container interface {
	Widget
	// ChildWidgets returns the container's direct children in layout order.
	ChildWidgets() []Widget
}

Container is a Widget that lays out child widgets. Panel, VBox, and HBox implement Container.

type DeviceClass string

DeviceClass identifies a target device form factor for conditional visibility and reference layout checks.

const (
	DevicePhone     DeviceClass = "phone"
	DeviceTablet    DeviceClass = "tablet"
	DeviceDesktop   DeviceClass = "desktop"
	DeviceUltrawide DeviceClass = "ultrawide"
)
type DeviceProfile struct {
	// ID is the machine identifier (for example "phone", "tablet", "desktop", "ultrawide").
	ID string
	// Name is the human-readable profile name (for example "Phone 19.5:9 (notch)").
	Name string
	// Class is the device class matched against ScreenNodeDoc.DeviceClasses.
	Class DeviceClass
	// Width and Height are the virtual canvas dimensions in points at this aspect ratio.
	Width  float32
	Height float32
	// SafeArea specifies the notch, rounded-corner, and home-indicator insets in virtual points.
	SafeArea core.Edges
	// Touch reports whether this device uses touch input (and enforces minimum touch target size).
	Touch bool
}

DeviceProfile describes a reference display size, safe-area insets, and device class used to preview and validate screens.

func ReferenceDevices() []DeviceProfile

ReferenceDevices returns the four standard reference profiles for a 640×360 design canvas: Phone 19.5:9 with a notch (780×360), Tablet 4:3 (640×480), Desktop 16:9 (640×360), and Ultrawide 21:9 (840×360).

func ReferenceDevicesFor(designW, designH float32) []DeviceProfile

ReferenceDevicesFor returns the four standard reference profiles scaled to match a screen's design size: Phone 19.5:9 with a notch, Tablet 4:3, Desktop 16:9, and Ultrawide 21:9.

type FocusManager = SpatialNavigator

FocusManager is an alias for SpatialNavigator.

type FocusRingStyle struct {
	// Color overrides Theme.FocusedBorder when non-zero. Set core.Transparent to disable the default stroke.
	Color core.Color
	// Width overrides Theme.FocusWidth when > 0.
	Width float32
	// Outset expands the ring outward from the widget bounds by Outset points (negative insets it).
	Outset float32
	// CornerRadius overrides the corner radius (0 uses widget/theme default; < 0 uses square corners).
	CornerRadius float32
	// Dash sets an optional line dash pattern for the focus ring stroke.
	Dash []float32
	// Draw replaces the default stroke when non-nil, running inside Save/Restore.
	Draw func(d *core.Drawing, bounds core.Bounds, theme *Theme)
}

FocusRingStyle customizes the focus indicator drawn around the currently focused widget.

type FrameDrawer func(d *core.Drawing, bounds core.Bounds, state WidgetState)

FrameDrawer draws a stylized background frame (such as a nine-slice sprite or custom skin) for a widget in its current interaction state.

func NineSliceStateFrame(normal, hover, pressed, disabled *NineSlice) FrameDrawer

NineSliceStateFrame returns a state-aware FrameDrawer that selects the matching NineSlice for Disabled, Pressed, Hovered, or Normal state, falling back to normal when a state slice is nil.

type HBox struct {
	Children       []Widget
	Spacing        float32
	Padding        core.Edges
	Align          Align
	Justify        Justify
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Hidden         bool
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	// contains filtered or unexported fields
}

HBox arranges Children horizontally from left to right with Spacing and Padding.

func (b *HBox) Bounds() core.Bounds

Bounds returns the HBox's laid-out rectangle.

func (b *HBox) ChildWidgets() []Widget

ChildWidgets returns the HBox's direct children.

type Justify uint8

Justify controls main-axis distribution in VBox and HBox when extra space remains and no child has Flex > 0.

const (
	// JustifyStart packs children at the start of the main axis.
	JustifyStart Justify = iota
	// JustifyCenter centers children as a group along the main axis.
	JustifyCenter
	// JustifyEnd packs children at the end of the main axis.
	JustifyEnd
	// JustifySpaceBetween spreads remaining space evenly between adjacent children.
	JustifySpaceBetween
)
type Label struct {
	Text           string
	Color          core.Color
	Background     core.Color
	CornerRadius   float32
	Padding        core.Edges
	Font           core.Font
	TextAlign      core.TextAlign
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	// contains filtered or unexported fields
}

Label displays non-interactive text. Focus navigation skips labels automatically.

func (l *Label) Bounds() core.Bounds

Bounds returns the label's laid-out rectangle.

type List struct {
	Items          []string
	Selected       int
	ItemHeight     float32
	Spacing        float32
	OnSelect       func(index int, item string)
	Disabled       bool
	Font           core.Font
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Nav            NavOverrides
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	// contains filtered or unexported fields
}

List is a focusable vertical list of selectable items supporting pointer and keyboard/gamepad selection.

func (l *List) Bounds() core.Bounds

Bounds returns the list's laid-out rectangle.

func (l *List) ItemAt(p core.Point) int

ItemAt returns the 0-based index of the item containing p, or -1 if none.

func (l *List) ItemBounds(index int) core.Bounds

ItemBounds returns the laid-out rectangle for item at index, or zero Bounds if out of range.

func (l *List) Select(index int) bool

Select updates Selected to index (clamped into [0, len(Items)-1]) and invokes OnSelect. Returns false when the list is disabled or empty.

type NavAction uint8

NavAction identifies a logical UI navigation action from keyboard, gamepad, or virtual controls.

const (
	// NavNone is the zero value representing no action.
	NavNone NavAction = iota
	// NavUp moves focus upward.
	NavUp
	// NavDown moves focus downward.
	NavDown
	// NavLeft moves focus left (or decrements a focused Slider when SliderSteps is enabled).
	NavLeft
	// NavRight moves focus right (or increments a focused Slider when SliderSteps is enabled).
	NavRight
	// NavConfirm activates the currently focused widget and invokes OnConfirm.
	NavConfirm
	// NavBack invokes OnBack (e.g. closing a submenu or canceling an action).
	NavBack
)
func (a NavAction) String() string

String returns a human-readable name for a.

type NavOverrides struct {
	Up    Widget
	Down  Widget
	Left  Widget
	Right Widget
}

NavOverrides specifies explicit per-widget directional neighbors that take precedence over automatic 2D spatial lookup.

func (o NavOverrides) For(dir NavAction) Widget

For returns the explicit neighbor configured for dir, or nil if unset or non-directional.

type NineSlice struct {
	Image  core.ImageSource
	Src    core.Bounds
	Left   float32
	Top    float32
	Right  float32
	Bottom float32
}

NineSlice describes a 9-patch sprite frame with fixed corner margins (Left, Top, Right, Bottom) inside Src of Image. Corners stay unstretched while edges and center scale to fill destination bounds.

func (ns NineSlice) Draw(d *core.Drawing, dst core.Bounds)

Draw renders the 9-patch image stretched into dst. Corner insets clamp proportionally if dst is smaller than Left+Right or Top+Bottom.

func (ns NineSlice) FrameDrawer() FrameDrawer

FrameDrawer adapts a single NineSlice into a FrameDrawer callback.

type Panel struct {
	Child          Widget
	Padding        core.Edges
	Align          Align
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Hidden         bool
	Background     core.Color
	Border         core.Color
	CornerRadius   float32 // 0 uses Theme.CornerRadius; < 0 uses square corners.
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	// contains filtered or unexported fields
}

Panel frames a single optional Child with padding, background fill, and border.

func (p *Panel) Bounds() core.Bounds

Bounds returns the panel's laid-out rectangle.

func (p *Panel) ChildWidgets() []Widget

ChildWidgets returns the panel's child if non-nil.

type ProgressBar struct {
	Value          float32
	Min            float32
	Max            float32
	Label          string
	FillColor      core.Color
	TrackColor     core.Color
	Font           core.Font
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	// contains filtered or unexported fields
}

ProgressBar displays a read-only progress meter in [Min, Max] (or [0, 1] when both Min and Max are 0).

func (p *ProgressBar) Bounds() core.Bounds

Bounds returns the progress bar's laid-out rectangle.

func (p *ProgressBar) Fraction() float32

Fraction returns Value normalized into [0, 1].

type Root struct {
	// Child is the root widget of the UI tree (typically a Panel, VBox, or HBox).
	Child Widget
	// Theme styles all widgets under this Root; nil uses DefaultTheme.
	Theme *Theme
	// Viewport optionally maps a fixed virtual resolution onto the physical window bounds,
	// applying scaling and letterboxing in Draw and mapping window pointer/touch input into virtual coordinates.
	Viewport *Viewport
	// FocusRing optionally overrides the focus ring style drawn around the focused widget.
	FocusRing *FocusRingStyle
	// contains filtered or unexported fields
}

Root manages layout, focus navigation, pointer/touch interaction, and rendering for a game UI widget tree.

func NewRoot(child Widget) *Root

NewRoot returns a Root wrapping child with the default theme.

func (r *Root) Activate() bool

Activate triggers the currently focused widget (clicks a Button or flips a Toggle).

func (r *Root) Adjust(delta float32) bool

Adjust steps the currently focused adjustable widget by delta steps (e.g. -1 or +1). For a Slider, Value moves by delta * step within [Min, Max]. For a Toggle, delta > 0 checks it and delta < 0 unchecks it. For a List, Selected steps by delta clamped to the available items.

func (r *Root) Bounds() core.Bounds

Bounds returns the bounds from the last Layout or Draw call.

func (r *Root) ClearFocus()

ClearFocus removes keyboard/gamepad focus from the active widget.

func (r *Root) Draw(d *core.Drawing, bounds core.Bounds)

Draw lays out the tree into bounds and draws every visible widget into d. When Viewport is set, Draw renders letterbox bars and transforms d into the virtual resolution. Caller drawing state (transform, colors, stroke settings, alpha, text align/baseline, and current path) is preserved.

func (r *Root) DrawWithViewport(d *core.Drawing, vp Viewport)

DrawWithViewport renders the UI tree using vp without permanently replacing r.Viewport.

func (r *Root) FocusIndex() int

FocusIndex returns the index of the focused widget in the current list of enabled, visible focusable widgets, or -1 if none is focused.

func (r *Root) FocusNext() bool

FocusNext moves focus to the next enabled, focusable widget, wrapping from the end to the beginning.

func (r *Root) FocusPrev() bool

FocusPrev moves focus to the previous enabled, focusable widget, wrapping from the beginning to the end.

func (r *Root) Focused() Widget

Focused returns the currently focused widget, or nil if none is focused.

func (r *Root) HitTest(p core.Point) Widget

HitTest returns the topmost enabled, focusable widget containing p, or nil. When Viewport is set, p is mapped from window coordinates into virtual coordinates and points inside letterbox bars return nil.

func (r *Root) Hovered() Widget

Hovered returns the currently hovered interactive widget, or nil.

func (r *Root) Layout(bounds core.Bounds)

Layout computes exact rectangles for every widget in the tree inside bounds and refreshes the focusable widget list. When Viewport is set, bounds specifies the physical window rectangle and the widget tree is laid out in virtual coordinates.

func (r *Root) MoveFocus(dx, dy int) bool

MoveFocus moves focus geometrically in direction (dx, dy) (for arrow keys and gamepad D-pad/stick), checking explicit per-widget NavOverrides first, wrapping along the axis when reaching an edge, and falling back to linear order if layout has not run.

func (r *Root) OnKeyDown(ev core.KeyEvent) bool

OnKeyDown handles keyboard navigation, activation, and slider adjustment. Returns true if the event was consumed by the UI.

func (r *Root) OnPointerDown(p core.Point) bool

OnPointerDown focuses and presses the interactive widget under p, beginning a drag if it is a Slider. Returns true if an interactive widget was hit.

func (r *Root) OnPointerMove(p core.Point) bool

OnPointerMove updates hover state and smoothly drags any active Slider. Returns true if the pointer is over an interactive widget or dragging a Slider.

func (r *Root) OnPointerUp(p core.Point) bool

OnPointerUp finishes any active press or Slider drag, activating a Button, Toggle, or List item when released inside it. Returns true if a press or drag was handled.

func (r *Root) OnPress(ev core.PressEvent) bool

OnPress handles a core.Canvas PressEvent directly (tapping/clicking a Button, Toggle, Slider, or List, or activating the focused widget on keyboard press).

func (r *Root) Pressed() Widget

Pressed returns the currently pressed interactive widget, or nil.

func (r *Root) SetFocus(w Widget) bool

SetFocus focuses w if it is visible and focusable in this tree.

func (r *Root) SetFocusIndex(index int) bool

SetFocusIndex focuses the focusable widget at index, or clears focus when index < 0.

func (r *Root) StateOf(w Widget) WidgetState

StateOf returns the current hover, pressed, focused, and disabled state of w.

type ScaleMode uint8

ScaleMode controls how a Viewport maps a virtual resolution into a physical window size.

const (
	// ScaleFit uniformly scales the virtual canvas to fit inside the window, adding letterbox or pillarbox bars as needed.
	ScaleFit ScaleMode = iota
	// ScaleFill uniformly scales the virtual canvas to cover the entire window, cropping any overflow symmetrically.
	ScaleFill
	// ScaleStretch scales X and Y independently to fill the window without preserving aspect ratio.
	ScaleStretch
	// ScaleInteger uniformly scales by the largest integer factor >= 1 that fits inside the window,
	// falling back to ScaleFit when the window is smaller than the virtual resolution.
	ScaleInteger

	// ScaleLetterbox is an alias for ScaleFit.
	ScaleLetterbox = ScaleFit
	// IntegerScale is an alias for ScaleInteger.
	IntegerScale = ScaleInteger
)
type ScreenAnchor string

ScreenAnchor positions a node against one of nine reference points or fills its parent bounds.

const (
	AnchorTopLeft      ScreenAnchor = "top_left"
	AnchorTopCenter    ScreenAnchor = "top_center"
	AnchorTopRight     ScreenAnchor = "top_right"
	AnchorCenterLeft   ScreenAnchor = "center_left"
	AnchorCenter       ScreenAnchor = "center"
	AnchorCenterRight  ScreenAnchor = "center_right"
	AnchorBottomLeft   ScreenAnchor = "bottom_left"
	AnchorBottomCenter ScreenAnchor = "bottom_center"
	AnchorBottomRight  ScreenAnchor = "bottom_right"
	AnchorFill         ScreenAnchor = "fill"
)
type ScreenBuildOptions struct {
	// SafeArea specifies the display safe-area insets in virtual points (for notches, rounded corners, and home indicators).
	SafeArea core.Edges
	// DeviceClass selects which conditional nodes (ScreenNodeDoc.DeviceClasses) are visible.
	// When empty, no device-class filtering is applied and all nodes remain visible.
	DeviceClass DeviceClass
	// ViewportWidth and ViewportHeight optionally override the Viewport's virtual dimensions (for example 780×360 for a 19.5:9 phone).
	// When zero, the document's DesignWidth and DesignHeight are used.
	ViewportWidth  float32
	ViewportHeight float32
	// Text resolves localization textKey values. When nil and Catalog is set, Catalog.T(Locale, key) is used; when both are nil, the key itself is displayed.
	Text func(key string) string
	// Catalog optionally resolves textKey values when Text is nil.
	Catalog *l10n.Catalog
	// Locale optionally selects the locale in Catalog (empty uses Catalog's active locale).
	Locale string
	// Theme optionally overrides the built Root's theme; nil uses DefaultTheme tuned for DefaultScreenFontSize and screen text measurement.
	Theme *Theme
	// OnClick optionally binds click callbacks by node ID for button and touch_button nodes.
	OnClick map[string]func()
	// Sprites optionally resolves a node's Sprite path (and optional SpriteFrame) into a core.ImageSource and source rectangle.
	Sprites func(path, frame string) (core.ImageSource, core.Bounds, bool)
}

ScreenBuildOptions configures BuildScreen.

type ScreenCanvas struct {
	SafeArea     core.Edges
	Items        []AnchoredItem
	Background   core.Color
	CornerRadius float32
	Width        float32
	Height       float32
	MinWidth     float32
	MinHeight    float32
	Flex         float32
	Align        Align
	Hidden       bool
	// contains filtered or unexported fields
}

ScreenCanvas lays out children using nine-point anchors or fill, optional safe-area insets, and offsets. It implements Container and Widget.

func (c *ScreenCanvas) Bounds() core.Bounds

Bounds returns the canvas's laid-out rectangle.

func (c *ScreenCanvas) ChildWidgets() []Widget

ChildWidgets returns the direct child widgets in render order.

type ScreenCheckOptions struct {
	// Locales maps normalized locale tags to their message string maps (for example from l10n.StringTable.Strings).
	Locales map[string]map[string]string
	// Plurals optionally maps normalized locale tags to their CLDR plural entries (for example from l10n.StringTable.Plurals).
	Plurals map[string]map[string]l10n.PluralForms
	// Devices optionally overrides the reference device profiles; empty uses ReferenceDevicesFor(doc.DesignWidth, doc.DesignHeight).
	Devices []DeviceProfile
	// Theme optionally overrides the theme used for default text/button colors and text measurement.
	Theme *Theme
	// FallbackBackdrop is the backdrop color used to composite translucent fills when no opaque ancestor fill exists (defaults to #101216).
	FallbackBackdrop core.Color
}

ScreenCheckOptions configures CheckScreen.

type ScreenDoc struct {
	// Version is the schema version; it must equal ScreenFormatVersion (1).
	Version int `yaml:"version" schema:"required"`
	// UID is an optional stable ID for the screen file, kept across renames by game index and game mv.
	UID string `yaml:"uid,omitempty"`
	// Name is the screen's human-readable name (for example "hud" or "pause").
	Name string `yaml:"name,omitempty"`
	// DesignWidth is the authored reference canvas width in virtual points (for example 640).
	DesignWidth float32 `yaml:"designWidth" schema:"required,exclusiveMinimum=0"`
	// DesignHeight is the authored reference canvas height in virtual points (for example 360).
	DesignHeight float32 `yaml:"designHeight" schema:"required,exclusiveMinimum=0"`
	// ScaleMode controls how the screen scales to different window sizes: fit (default), fill, stretch, or integer.
	ScaleMode ScreenScaleMode `yaml:"scaleMode,omitempty" schema:"enum=fit|fill|stretch|integer"`
	// Nodes are the top-level UI nodes of the screen, rendered in slice order.
	Nodes []ScreenNodeDoc `yaml:"nodes,omitempty"`
}

ScreenDoc is the root of a versioned *.screen.yaml HUD or menu screen definition.

func LoadScreenFS(fsys fs.FS, name string) (*ScreenDoc, error)

LoadScreenFS reads and parses a *.screen.yaml file from fsys, attaching name to any returned error.

func ParseScreen(data []byte) (*ScreenDoc, error)

ParseScreen decodes and validates a versioned *.screen.yaml document. Unknown fields, trailing YAML documents, YAML anchors/aliases/merge keys, missing or unsupported versions, duplicate node IDs, duplicate focus orders, invalid enums or colors, and non-finite numbers are refused.

Errors are *loaderr.Error values carrying line, column, field path, and fix guidance; callers that read from a file can attach the file path with loaderr.WithFile.

func (doc *ScreenDoc) Clone() *ScreenDoc

Clone returns a deep copy of doc.

func (doc *ScreenDoc) EffectiveScaleMode() ScaleMode

EffectiveScaleMode maps doc.ScaleMode to a gameui.ScaleMode, defaulting to ScaleFit.

type ScreenIssue struct {
	// Code classifies the issue.
	Code ScreenIssueCode
	// NodeID is the ScreenNodeDoc.ID at fault.
	NodeID string
	// NodePath holds the YAML path steps from the document root to the offending node or field (for example ["nodes", "3", "textKey"]).
	NodePath []string
	// Locale is the BCP-47 locale tag involved, when the issue is locale-specific.
	Locale string
	// Devices names the reference device profiles involved, when the issue is device-specific.
	Devices []string
	// Message describes the issue for diagnostics and UI panels.
	Message string
}

ScreenIssue is one problem CheckScreen finds in a ScreenDoc.

func CheckScreen(doc *ScreenDoc, opts ScreenCheckOptions) []ScreenIssue

CheckScreen checks doc against the HUD/menu screen quality rules:

  • touch areas under 44 pt on phones and tablets;
  • localized text overflowing its box at any reference device size (Phone 19.5:9 with notch, Tablet 4:3, Desktop 16:9, Ultrawide 21:9);
  • textKey entries missing from any project locale;
  • text under 4.5:1 WCAG contrast against its own fill.
type ScreenIssueCode string

ScreenIssueCode identifies the category of a screen check diagnostic.

const (
	// IssueTouchAreaTooSmall flags a touch control whose hit area is below MinTouchTargetSize (44 pt) on phones or tablets.
	IssueTouchAreaTooSmall ScreenIssueCode = "touch_area_too_small"
	// IssueTextOverflow flags a text node whose localized string exceeds its laid-out box width at one or more reference sizes.
	IssueTextOverflow ScreenIssueCode = "text_overflow"
	// IssueMissingTextKey flags a textKey absent from a project locale table.
	IssueMissingTextKey ScreenIssueCode = "missing_text_key"
	// IssueLowContrast flags text whose contrast ratio against its fill is under 4.5:1.
	IssueLowContrast ScreenIssueCode = "low_contrast"
)
type ScreenNodeDoc struct {
	// ID uniquely identifies this node within the screen.
	ID string `yaml:"id" schema:"required,minLength=1"`
	// Type selects the widget or container kind.
	Type ScreenNodeType `yaml:"type" schema:"required,enum=vbox|hbox|label|button|sprite_row|color_rect|touch_stick|touch_button|container"`
	// Anchor positions the node relative to the screen or safe area: one of the nine anchor points or fill.
	Anchor ScreenAnchor `yaml:"anchor,omitempty" schema:"enum=top_left|top_center|top_right|center_left|center|center_right|bottom_left|bottom_center|bottom_right|fill"`
	// Offset shifts the node from its anchor in virtual points. For right and bottom anchors, positive values inset inward from that edge.
	Offset *ScreenOffsetDoc `yaml:"offset,omitempty"`
	// SafeArea keeps the node inside the display safe area (away from notches and home indicators). Nil defaults to true for non-fill anchors and false for fill.
	SafeArea *bool `yaml:"safeArea,omitempty"`
	// SizeMode selects whether width is fixed ("fixed", the default) or sizes to fit localized text ("fit_text").
	SizeMode SizeMode `yaml:"sizeMode,omitempty" schema:"enum=fixed|fit_text"`
	// Width is the node's fixed width in virtual points (0 uses intrinsic or container-determined width).
	Width float32 `yaml:"width,omitempty" schema:"minimum=0"`
	// Height is the node's fixed height in virtual points (0 uses intrinsic or container-determined height).
	Height float32 `yaml:"height,omitempty" schema:"minimum=0"`
	// Padding is the node's inner padding in virtual points.
	Padding *ScreenPaddingDoc `yaml:"padding,omitempty"`
	// Spacing is the gap between children of a vbox, hbox, or sprite_row in virtual points.
	Spacing float32 `yaml:"spacing,omitempty" schema:"minimum=0"`
	// TextKey names a localized string in the project's l10n tables (such as "hud.hint.lever"). Screen files store localization keys rather than literal text.
	TextKey string `yaml:"textKey,omitempty"`
	// FocusOrder sets the explicit keyboard/gamepad focus traversal order (1-based; 0 means not explicitly ordered).
	FocusOrder int `yaml:"focusOrder,omitempty" schema:"minimum=0"`
	// TouchHitSize is the touch target diameter in virtual points for touch_stick, touch_button, or touch-interactive buttons.
	TouchHitSize float32 `yaml:"touchHitSize,omitempty" schema:"minimum=0"`
	// DeviceClasses optionally restricts the node and its subtree to the listed device classes (for example [phone, tablet]). Empty shows on all devices.
	DeviceClasses []DeviceClass `yaml:"deviceClasses,omitempty"`
	// Sprite is a project-relative path to a sprite image or atlas file (for example "art/ui/heart.png"), followed by refs and game mv.
	Sprite string `yaml:"sprite,omitempty"`
	// SpriteFrame optionally names a frame inside a sprite atlas when Sprite points to an atlas JSON file.
	SpriteFrame string `yaml:"spriteFrame,omitempty"`
	// SpriteCount is the number of repeated icons in a sprite_row (defaults to 1 when Sprite is set).
	SpriteCount int `yaml:"spriteCount,omitempty" schema:"minimum=0"`
	// FontSize overrides the text font size in virtual points for text-bearing nodes.
	FontSize float32 `yaml:"fontSize,omitempty" schema:"minimum=0"`
	// TextColor is an optional CSS color string parsed with core.ParseColor for text.
	TextColor string `yaml:"textColor,omitempty"`
	// Background is an optional CSS color string parsed with core.ParseColor for the node's fill.
	Background string `yaml:"background,omitempty"`
	// CornerRadius is an optional corner radius in virtual points.
	CornerRadius float32 `yaml:"cornerRadius,omitempty" schema:"minimum=0"`
	// Children are nested child nodes for container types (vbox, hbox, container).
	Children []ScreenNodeDoc `yaml:"children,omitempty"`
}

ScreenNodeDoc is one node in a *.screen.yaml tree.

func (n *ScreenNodeDoc) EffectiveAnchor() ScreenAnchor

EffectiveAnchor returns n.Anchor, defaulting to AnchorTopLeft when empty.

func (n *ScreenNodeDoc) KeepInSafeArea() bool

KeepInSafeArea reports whether the node stays inside the display safe area. When SafeArea is nil, non-fill anchors default to true and AnchorFill defaults to false.

type ScreenNodeType string

ScreenNodeType identifies the widget or container kind of a ScreenNodeDoc.

const (
	// NodeVBox stacks children vertically.
	NodeVBox ScreenNodeType = "vbox"
	// NodeHBox arranges children horizontally.
	NodeHBox ScreenNodeType = "hbox"
	// NodeLabel displays localized non-interactive text.
	NodeLabel ScreenNodeType = "label"
	// NodeButton displays a focusable, clickable button.
	NodeButton ScreenNodeType = "button"
	// NodeSpriteRow displays a horizontal row of repeated sprite icons (such as health hearts).
	NodeSpriteRow ScreenNodeType = "sprite_row"
	// NodeColorRect draws a filled rectangle (such as a modal dim backdrop or HUD plate).
	NodeColorRect ScreenNodeType = "color_rect"
	// NodeTouchStick displays an on-screen virtual thumbstick for touch devices.
	NodeTouchStick ScreenNodeType = "touch_stick"
	// NodeTouchButton displays an on-screen circular/rounded touch action button.
	NodeTouchButton ScreenNodeType = "touch_button"
	// NodeContainer groups child nodes with optional device-class filtering or anchored sub-bounds.
	NodeContainer ScreenNodeType = "container"
)
func (t ScreenNodeType) IsContainer() bool

IsContainer reports whether t can hold child nodes.

type ScreenOffsetDoc struct {
	// X is the horizontal offset in virtual points.
	X float32 `yaml:"x,omitempty"`
	// Y is the vertical offset in virtual points.
	Y float32 `yaml:"y,omitempty"`
}

ScreenOffsetDoc is an offset from a node's anchor point in virtual points. For right and bottom anchors, positive X and Y values move inward away from that edge.

type ScreenPaddingDoc struct {
	// Top is the top inner padding in virtual points.
	Top float32 `yaml:"top,omitempty" schema:"minimum=0"`
	// Right is the right inner padding in virtual points.
	Right float32 `yaml:"right,omitempty" schema:"minimum=0"`
	// Bottom is the bottom inner padding in virtual points.
	Bottom float32 `yaml:"bottom,omitempty" schema:"minimum=0"`
	// Left is the left inner padding in virtual points.
	Left float32 `yaml:"left,omitempty" schema:"minimum=0"`
}

ScreenPaddingDoc holds inner padding in virtual points.

func (p *ScreenPaddingDoc) Edges() core.Edges

Edges converts p into core.Edges (returning zero edges when p is nil).

type ScreenScaleMode string

ScreenScaleMode selects the Viewport scaling behavior for a screen file.

const (
	// ScreenScaleFit uniformly scales the design canvas to fit inside the window (default).
	ScreenScaleFit ScreenScaleMode = "fit"
	// ScreenScaleFill uniformly scales the design canvas to cover the window.
	ScreenScaleFill ScreenScaleMode = "fill"
	// ScreenScaleStretch scales X and Y independently to fill the window.
	ScreenScaleStretch ScreenScaleMode = "stretch"
	// ScreenScaleInteger uniformly scales by the largest integer factor >= 1 that fits.
	ScreenScaleInteger ScreenScaleMode = "integer"
)
type SettingsAction struct {
	// Name is the action key stored in save.Settings.Bindings (for example "jump", "left", "pause").
	Name string
	// Label is displayed in the Controls tab; defaults to Name when empty.
	Label string
	// Defaults lists default binding tokens (for example "key:space", "gamepad:south") restored on Reset.
	Defaults []string
}

SettingsAction describes a rebindable input action shown in the Controls tab.

type SettingsAudioBus struct {
	// Name is the key inside save.AudioSettings.Groups (for example "music", "sfx", "ui").
	Name string
	// Label is shown next to the slider; defaults to Name when empty.
	Label string
}

SettingsAudioBus describes an audio group slider shown in the Audio tab.

type SettingsLocale struct {
	// Tag is the BCP-47 locale tag stored in save.Settings.Locale ("" selects the system default).
	Tag string
	// Label is displayed in the Language tab; defaults to Tag or SystemDefault.
	Label string
}

SettingsLocale describes a selectable language entry in the Language tab.

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

SettingsMenu is a ready-to-use, gameui-based settings screen covering Audio, Video, Controls (rebinding), Language, and Accessibility, persisted via save.DefaultSettingsStore and operable with mouse, touch, keyboard, and gamepad alone.

func NewSettingsMenu(cfg SettingsMenuConfig) *SettingsMenu

NewSettingsMenu constructs a SettingsMenu wired to cfg and ready to draw and receive input.

func (m *SettingsMenu) Apply() error

Apply validates the working settings and dispatches them to Targets and OnApply.

func (m *SettingsMenu) Back()

Back cancels capture if active; otherwise invokes OnBack.

func (m *SettingsMenu) BeginCapture(actionName string) bool

BeginCapture enters control-rebinding capture mode for actionName.

func (m *SettingsMenu) CancelCapture()

CancelCapture exits control-rebinding capture mode without modifying bindings.

func (m *SettingsMenu) CaptureBinding(token string) bool

CaptureBinding assigns token to the currently capturing action, replacing the existing binding of the same input device class (keyboard vs gamepad vs mouse) while keeping other classes intact.

func (m *SettingsMenu) CapturingAction() string

CapturingAction returns the action name currently awaiting a key or gamepad button press, or "".

func (m *SettingsMenu) Dirty() bool

Dirty reports whether the working settings have unsaved changes.

func (m *SettingsMenu) Draw(d *core.Drawing, bounds core.Bounds)

Draw lays out and renders the settings menu into d within bounds.

func (m *SettingsMenu) Err() error

Err returns the last error produced by Load, Apply, or Save.

func (m *SettingsMenu) FooterButtons() (apply, saveBtn, reset, back *Button)

FooterButtons returns the Apply, Save, Reset, and Back buttons in order.

func (m *SettingsMenu) HandleAction(action NavAction) bool

HandleAction dispatches a logical NavAction through the menu, supporting slider adjustment, toggle switching, cycle-option stepping on NavLeft/NavRight, and capture cancellation on NavBack.

func (m *SettingsMenu) Layout(bounds core.Bounds)

Layout lays out the menu inside bounds.

func (m *SettingsMenu) Navigator() *SpatialNavigator

Navigator returns the menu's SpatialNavigator.

func (m *SettingsMenu) NextTab()

NextTab switches to the next settings tab, wrapping from Accessibility back to Audio.

func (m *SettingsMenu) OnGamepadButton(btn gamepad.Button) bool

OnGamepadButton processes a single gamepad button press (rising edge). While capturing a control rebind, any valid button is captured; otherwise D-pad, South (confirm), East (back), and LB/RB (previous/next tab) drive the menu.

func (m *SettingsMenu) OnKeyDown(ev core.KeyEvent) bool

OnKeyDown handles keyboard navigation, slider/option stepping, and control rebinding capture.

func (m *SettingsMenu) OnPointerDown(p core.Point) bool

OnPointerDown focuses and presses the control under p.

func (m *SettingsMenu) OnPointerMove(p core.Point) bool

OnPointerMove updates hover state and drags any active slider.

func (m *SettingsMenu) OnPointerUp(p core.Point) bool

OnPointerUp finishes any press or slider drag, activating controls released inside their bounds.

func (m *SettingsMenu) OnPress(ev core.PressEvent) bool

OnPress handles a completed core.PressEvent directly.

func (m *SettingsMenu) OnTouch(ev core.TouchEvent) bool

OnTouch routes touch start, move, end, and cancel events to sliders, toggles, and buttons.

func (m *SettingsMenu) PrevTab()

PrevTab switches to the previous settings tab, wrapping from Audio to Accessibility.

func (m *SettingsMenu) Reset()

Reset restores all settings to their configured defaults and refreshes the UI.

func (m *SettingsMenu) ResetControls()

ResetControls restores all configured actions' bindings to their default values.

func (m *SettingsMenu) Root() *Root

Root returns the menu's underlying gameui Root.

func (m *SettingsMenu) Save() error

Save validates the working settings, persists them through Store (when configured), applies them to Targets/OnApply, and invokes OnSave.

func (m *SettingsMenu) SetSettings(s save.Settings)

SetSettings replaces the menu's working settings and refreshes all controls.

func (m *SettingsMenu) SetTab(tab SettingsTab)

SetTab switches the active settings tab, cancelling any in-progress control capture and updating focus and directional navigation cleanly.

func (m *SettingsMenu) SetText(text SettingsText)

SetText updates the menu's user-visible strings (for example after changing locale).

func (m *SettingsMenu) Settings() save.Settings

Settings returns a deep copy of the menu's current working player settings.

func (m *SettingsMenu) StepActions(pressed func(NavAction) bool) bool

StepActions polls logical UI navigation actions (such as from input.Actions.JustPressed) and dispatches them in deterministic order.

func (m *SettingsMenu) StepGamepad(pads []gamepad.Pad) bool

StepGamepad polls connected gamepads once per frame, driving navigation, tab switching, value adjustment, and control-rebinding capture on button and left-stick rising edges.

func (m *SettingsMenu) SyncGamepad(pads []gamepad.Pad)

SyncGamepad records the currently held buttons and left-stick position on pads as the baseline without triggering any actions. Call it when opening the menu so buttons held to open the screen do not immediately fire inside it.

func (m *SettingsMenu) Tab() SettingsTab

Tab returns the currently active SettingsTab.

func (m *SettingsMenu) TabButton(tab SettingsTab) *Button

TabButton returns the tab-bar Button for tab.

func (m *SettingsMenu) TabControls(tab SettingsTab) []Widget

TabControls returns the ordered focusable widgets inside tab.

type SettingsMenuConfig struct {
	// Store optionally loads initial player settings and persists changes when Save is called.
	Store *save.DefaultSettingsStore
	// Targets optionally receives validated settings via save.Apply when Apply or Save is called.
	Targets save.SettingsTargets
	// Initial supplies starting settings when Store is nil (or if Store.Load fails).
	Initial *save.Settings
	// Defaults supplies baseline settings restored by Reset.
	Defaults *save.Settings

	// AudioBuses configures group volume sliders in the Audio tab (defaults to music, sfx, ui).
	AudioBuses []SettingsAudioBus
	// Resolutions configures selectable resolutions in the Video tab (defaults to Native, 960x540, 1280x720, 1920x1080).
	Resolutions []SettingsResolution
	// ScaleModes configures scale mode options in the Video tab (defaults to fit, fill, stretch, expand).
	ScaleModes []SettingsOptionItem
	// QualityPresets configures quality preset options in the Video tab (defaults to auto, low, medium, high).
	QualityPresets []SettingsOptionItem
	// FrameCaps configures selectable FPS caps in the Video tab; 0 means uncapped (defaults to 0, 30, 60, 120).
	FrameCaps []int
	// Actions configures rebindable input actions in the Controls tab.
	Actions []SettingsAction
	// Locales configures selectable languages in the Language tab.
	Locales []SettingsLocale
	// ColorBlindModes configures color-blind palette modes in the Accessibility tab.
	ColorBlindModes []SettingsOptionItem

	// Text customizes displayed labels; unset fields inherit DefaultSettingsText.
	Text SettingsText
	// Theme optionally overrides the Theme used by the menu's Root.
	// When nil, DefaultTheme is used and switches automatically to HighContrastTheme while Accessibility.HighContrast is true.
	Theme *Theme
	// Viewport optionally attaches virtual-resolution scaling to the menu's Root.
	Viewport *Viewport

	// AutoApply dispatches Targets and OnApply immediately whenever any control changes.
	AutoApply bool
	// AutoSave persists changes to Store immediately whenever any control changes.
	AutoSave bool

	// OnChange runs whenever any setting changes in the working copy.
	OnChange func(save.Settings)
	// OnApply runs when Apply or Save applies settings.
	OnApply func(save.Settings) error
	// OnSave runs after Save succeeds.
	OnSave func(save.Settings) error
	// OnReset runs after Reset restores defaults.
	OnReset func(save.Settings)
	// OnBack runs when Back or NavBack is triggered outside capture mode.
	OnBack func()
	// OnResolutionChange runs when the selected resolution changes.
	OnResolutionChange func(SettingsResolution)
}

SettingsMenuConfig configures a ready-to-use SettingsMenu. Every field is optional.

type SettingsOptionItem struct {
	Value string
	Label string
}

SettingsOptionItem pairs a persisted setting value with a user-visible display label.

type SettingsResolution struct {
	// ID is persisted in save.Settings.Custom["resolution"] (for example "native" or "1280x720").
	ID string
	// Label is displayed in the Video tab; defaults to ID when empty.
	Label string
	// Width and Height optionally carry the target dimensions in points/pixels (0 for native/auto).
	Width  int
	Height int
}

SettingsResolution describes a selectable resolution entry in the Video tab.

type SettingsTab uint8

SettingsTab identifies one of the five built-in sections of a SettingsMenu.

const (
	// SettingsTabAudio edits mute, master volume, and audio bus volumes.
	SettingsTabAudio SettingsTab = iota
	// SettingsTabVideo edits window mode, resolution, scale mode, integer scale, quality preset, VSync, and frame cap.
	SettingsTabVideo
	// SettingsTabControls edits keyboard and gamepad action bindings with capture and reset.
	SettingsTabControls
	// SettingsTabLanguage selects the active locale.
	SettingsTabLanguage
	// SettingsTabAccessibility edits captions, text scale, high contrast, reduced motion, screen shake, flash reduction, color-blind mode, and game speed.
	SettingsTabAccessibility
)
func (t SettingsTab) String() string

String returns the canonical lowercase name of tab.

type SettingsText struct {
	Title string

	TabAudio         string
	TabVideo         string
	TabControls      string
	TabLanguage      string
	TabAccessibility string

	MuteAll      string
	MasterVolume string

	WindowMode    string
	Windowed      string
	Fullscreen    string
	Resolution    string
	ScaleMode     string
	IntegerScale  string
	QualityPreset string
	VSync         string
	FrameCap      string
	Uncapped      string

	ControlsHint  string
	CapturePrompt string
	Unbound       string
	ResetControls string

	LanguageHint  string
	SystemDefault string

	Subtitles     string
	TextScale     string
	HighContrast  string
	ReduceMotion  string
	ScreenShake   string
	ReduceFlashes string
	ColorBlind    string
	GameSpeed     string

	Apply string
	Save  string
	Reset string
	Back  string

	SavedStatus   string
	AppliedStatus string
	ResetStatus   string
}

SettingsText holds every user-visible string displayed by SettingsMenu, so a game can localize it. Partial structs passed via SettingsMenuConfig.Text inherit unset fields from DefaultSettingsText.

func DefaultSettingsText() SettingsText

DefaultSettingsText returns the English strings used by SettingsMenu.

type SizeMode string

SizeMode controls whether a node uses a fixed width or sizes horizontally to fit localized text.

const (
	// SizeFixed keeps the node's declared Width (the default when omitted).
	SizeFixed SizeMode = "fixed"
	// SizeFitText expands or contracts width to fit the node's localized text plus horizontal padding.
	SizeFitText SizeMode = "fit_text"
)
type Slider struct {
	Label          string
	Min            float32
	Max            float32
	Value          float32
	Step           float32
	OnChange       func(value float32)
	Disabled       bool
	Font           core.Font
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Nav            NavOverrides
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	// contains filtered or unexported fields
}

Slider is a horizontal draggable and left/right steppable value control in [Min, Max]. When Min and Max are both 0, the range defaults to [0, 1]. When Step <= 0, keyboard and Adjust steps default to (Max - Min) / 10.

func (s *Slider) Bounds() core.Bounds

Bounds returns the slider's laid-out rectangle.

func (s *Slider) Fraction() float32

Fraction returns the slider's current Value normalized into [0, 1].

func (s *Slider) SetValue(v float32) bool

SetValue clamps v into [Min, Max], updates Value, and invokes OnChange if Value changed.

func (s *Slider) TrackBounds() core.Bounds

TrackBounds returns the slider's interactive track rectangle from the last Layout pass.

type Spacer struct {
	Width     float32
	Height    float32
	MinWidth  float32
	MinHeight float32
	Flex      float32
	Hidden    bool
	// contains filtered or unexported fields
}

Spacer reserves empty space inside a VBox or HBox. A zero-value Spacer defaults to Flex: 1 so it expands to push siblings apart; setting Width or Height without Flex creates a fixed gap.

func (s *Spacer) Bounds() core.Bounds

Bounds returns the spacer's laid-out rectangle.

type SpatialNavigator struct {
	// Root is the UI root whose focusable widgets are navigated.
	Root *Root
	// WrapAround enables edge wrap-around when no widget exists further in the requested direction.
	WrapAround bool
	// SliderSteps causes NavLeft and NavRight to adjust a focused Slider by -1/+1 step
	// unless an explicit Left/Right neighbor override is configured for that Slider.
	SliderSteps bool
	// OnConfirm is invoked after NavConfirm activates the focused widget (or when Confirm is called).
	OnConfirm func(focused Widget)
	// OnBack is invoked when NavBack is triggered.
	OnBack func()
	// OnFocusChange is invoked whenever navigation moves focus from prev to next.
	OnFocusChange func(prev, next Widget)
	// FocusRing customizes the focus ring drawn by DrawFocusRing (or attached to Root).
	FocusRing *FocusRingStyle
	// contains filtered or unexported fields
}

SpatialNavigator drives 2D spatial focus navigation, explicit neighbor overrides, action-based keyboard/gamepad input, and customizable focus ring rendering over a Root.

func NewSpatialNavigator(root *Root) *SpatialNavigator

NewSpatialNavigator returns a SpatialNavigator attached to root with wrap-around and slider stepping enabled.

func (n *SpatialNavigator) Back() bool

Back triggers the OnBack callback if configured.

func (n *SpatialNavigator) ClearFocus()

ClearFocus clears focus on Root.

func (n *SpatialNavigator) ClearOverrides(w Widget)

ClearOverrides removes any navigator-level overrides registered for w.

func (n *SpatialNavigator) Confirm() bool

Confirm activates the currently focused widget and calls OnConfirm if configured.

func (n *SpatialNavigator) DrawFocusRing(d *core.Drawing)

DrawFocusRing draws a customizable focus ring around the currently focused widget in Root.

func (n *SpatialNavigator) Focused() Widget

Focused returns the currently focused widget in Root, or nil.

func (n *SpatialNavigator) HandleAction(action NavAction) bool

HandleAction executes a single NavAction (directional move, slider step, confirm, or back).

func (n *SpatialNavigator) Move(dir NavAction) bool

Move navigates focus in the directional NavAction (NavUp, NavDown, NavLeft, NavRight). It checks explicit per-widget overrides first, then falls back to 2D spatial navigation.

func (n *SpatialNavigator) Overrides(w Widget) NavOverrides

Overrides returns the navigator-level overrides registered for w (or zero value if none).

func (n *SpatialNavigator) SetFocus(w Widget) bool

SetFocus focuses w if it is visible and focusable in Root.

func (n *SpatialNavigator) SetOverrides(w Widget, ov NavOverrides)

SetOverrides registers explicit directional neighbor overrides for w on this navigator. Navigator overrides take precedence over widget-level Nav fields and automatic spatial search.

func (n *SpatialNavigator) StepActions(pressed func(NavAction) bool) bool

StepActions polls logical UI navigation actions using pressed (for example, wrapping input.Actions.JustPressed) and dispatches any triggered actions in deterministic order. Returns true if any action was handled.

type SpriteRow struct {
	SpritePath  string
	SpriteFrame string
	Image       core.ImageSource
	Src         core.Bounds
	HasImage    bool
	Count       int
	Spacing     float32
	Color       core.Color
	Width       float32
	Height      float32
	MinWidth    float32
	MinHeight   float32
	Flex        float32
	Align       Align
	Hidden      bool
	// contains filtered or unexported fields
}

SpriteRow displays a horizontal row of repeated sprite icons (such as health hearts or ammo pips).

func (s *SpriteRow) Bounds() core.Bounds

Bounds returns the sprite row's laid-out bounds.

type TextDrawParams struct {
	Text     string
	X, Y     float32
	Font     core.Font
	Color    core.Color
	Align    core.TextAlign
	Baseline core.TextBaseline
	Bounds   core.Bounds
}

TextDrawParams carries the text string, anchor position, font, color, alignment, baseline, and widget bounds passed to a custom TextDrawer hook.

type TextDrawer func(d *core.Drawing, params TextDrawParams)

TextDrawer renders widget text into d, allowing custom bitmap or stylized font renderers without circular imports.

type TextMeasurer func(text string, font core.Font) (width, height float32)

TextMeasurer measures text width and height for layout when using a custom TextDrawer.

type Theme struct {
	// PanelBackground and PanelBorder style Panel containers.
	PanelBackground core.Color
	PanelBorder     core.Color

	// Background, Hover, Active, Disabled, Border, and FocusedBorder style interactive controls.
	Background    core.Color
	Hover         core.Color
	Active        core.Color
	FocusedBorder core.Color
	Disabled      core.Color
	Border        core.Color

	// Text, DisabledText, MutedText, Accent, AccentHover, AccentActive, and Track style labels, toggles, sliders, and progress bars.
	Text         core.Color
	DisabledText core.Color
	MutedText    core.Color
	Accent       core.Color
	AccentHover  core.Color
	AccentActive core.Color
	Track        core.Color

	// Padding is the default inner padding used for widget intrinsic sizing and spacing.
	Padding float32
	// CornerRadius is the default corner radius for rounded widget surfaces.
	CornerRadius float32
	// BorderWidth is the stroke width for widget borders.
	BorderWidth float32
	// FocusWidth is the stroke width for the focused outline.
	FocusWidth float32
	// Font is the default font used by text-bearing widgets.
	Font core.Font

	// PanelFrame optionally draws stylized or nine-slice frames for Panel widgets.
	PanelFrame FrameDrawer
	// ButtonFrame optionally draws stylized or nine-slice frames for Button widgets.
	ButtonFrame FrameDrawer
	// FrameDrawer optionally draws stylized or nine-slice frames when a widget has no specific frame drawer.
	FrameDrawer FrameDrawer
	// TextDrawer optionally replaces default Canvas FillText rendering (for example, with a bitmap font renderer).
	TextDrawer TextDrawer
	// TextMeasurer optionally provides text dimensions for layout when using a custom TextDrawer.
	TextMeasurer TextMeasurer
	// FocusRing optionally customizes the focus ring drawn around focused widgets.
	FocusRing *FocusRingStyle
}

Theme holds the colors, spacing, corner radius, borders, and default font used to lay out and draw a game UI.

func DefaultTheme() Theme

DefaultTheme returns a high-contrast dark theme suited for in-game overlays and menus.

func HighContrastTheme() Theme

HighContrastTheme returns a high-contrast dark gameui Theme suitable when Accessibility.HighContrast is enabled.

type Toggle struct {
	Label          string
	Checked        bool
	Style          ToggleStyle
	OnChange       func(checked bool)
	Disabled       bool
	Font           core.Font
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Nav            NavOverrides
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	// contains filtered or unexported fields
}

Toggle is a focusable boolean checkbox or switch control.

func (t *Toggle) Bounds() core.Bounds

Bounds returns the toggle's laid-out rectangle.

type ToggleStyle uint8

ToggleStyle picks the visual presentation of a Toggle widget.

const (
	// ToggleCheckbox draws a square checkbox with a checkmark when checked.
	ToggleCheckbox ToggleStyle = iota
	// ToggleSwitch draws a sliding pill switch.
	ToggleSwitch
)
type TouchButton struct {
	Text       string
	HitSize    float32
	OnClick    func()
	Disabled   bool
	Font       core.Font
	TextColor  core.Color
	Background core.Color
	FocusOrder int
	Nav        NavOverrides
	Width      float32
	Height     float32
	MinWidth   float32
	MinHeight  float32
	Flex       float32
	Align      Align
	Hidden     bool
	TextDrawer TextDrawer
	// contains filtered or unexported fields
}

TouchButton is an on-screen circular touch action button with an expanded touch hit target.

func (b *TouchButton) Bounds() core.Bounds

Bounds returns the touch button's visual bounds.

func (b *TouchButton) HitBounds() core.Bounds

HitBounds returns the touch button's interactive hit area, expanded to HitSize when larger than Bounds.

type TouchStick struct {
	HitSize   float32
	BaseColor core.Color
	KnobColor core.Color
	ValueX    float32
	ValueY    float32
	OnMove    func(x, y float32)
	Disabled  bool
	Width     float32
	Height    float32
	MinWidth  float32
	MinHeight float32
	Flex      float32
	Align     Align
	Hidden    bool
	// contains filtered or unexported fields
}

TouchStick is an on-screen virtual thumbstick with an optional expanded circular touch hit area.

func (t *TouchStick) Bounds() core.Bounds

Bounds returns the stick's visual bounds.

func (t *TouchStick) HitBounds() core.Bounds

HitBounds returns the stick's interactive touch target bounds, expanded to HitSize when larger than Bounds.

type VBox struct {
	Children       []Widget
	Spacing        float32
	Padding        core.Edges
	Align          Align
	Justify        Justify
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Hidden         bool
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	// contains filtered or unexported fields
}

VBox arranges Children vertically from top to bottom with Spacing and Padding.

func (b *VBox) Bounds() core.Bounds

Bounds returns the VBox's laid-out rectangle.

func (b *VBox) ChildWidgets() []Widget

ChildWidgets returns the VBox's direct children.

type Viewport struct {
	VirtualWidth  float32
	VirtualHeight float32
	WindowWidth   float32
	WindowHeight  float32
	ScaleMode     ScaleMode
	// LetterboxColor fills letterbox/pillarbox bars in Draw and DrawLetterbox.
	// Zero defaults to opaque black; set core.Transparent to skip drawing bars.
	LetterboxColor core.Color
}

Viewport maps a fixed virtual UI resolution onto a physical window size with scaling, letterboxing, drawing transform setup, and window-to-virtual coordinate conversion.

func NewViewport(virtualW, virtualH float32, mode ScaleMode) Viewport

NewViewport returns a Viewport configured for virtualW x virtualH using mode.

func (v Viewport) Apply(d *core.Drawing)

Apply clips d to VisibleBounds and applies the viewport's translation and scale transform. Callers should wrap Apply in d.Save() / d.Restore().

func (v Viewport) Draw(d *core.Drawing, drawFn func(d *core.Drawing, virtualBounds core.Bounds))

Draw renders letterbox bars, sets up the viewport clip and transform inside Save/Restore, and invokes drawFn with the virtual canvas bounds.

func (v Viewport) DrawLetterbox(d *core.Drawing)

DrawLetterbox fills any active letterbox/pillarbox bars into d unless LetterboxColor is core.Transparent.

func (v Viewport) LetterboxBars() []core.Bounds

LetterboxBars returns the non-empty, non-overlapping bar rectangles inside the window outside Rect().

func (v Viewport) Rect() core.Bounds

Rect returns the projected virtual canvas rectangle in physical window coordinates. For ScaleFill, Rect may extend outside [0, WindowWidth] x [0, WindowHeight].

func (v Viewport) Scale() float32

Scale returns the uniform scale factor (or min(sx, sy) for ScaleStretch).

func (v Viewport) ScaleXY() (sx, sy float32)

ScaleXY returns the horizontal and vertical scale factors from virtual coordinates to window coordinates.

func (v *Viewport) SetWindowSize(size core.Size)

SetWindowSize updates the viewport's physical window dimensions.

func (v Viewport) VirtualBounds() core.Bounds

VirtualBounds returns the layout rectangle in virtual coordinates: (0, 0, VirtualWidth, VirtualHeight).

func (v Viewport) VirtualToWindow(p core.Point) core.Point

VirtualToWindow maps a point in virtual coordinates into physical window coordinates.

func (v Viewport) VisibleBounds() core.Bounds

VisibleBounds returns the intersection of Rect() with the window bounds [0, WindowWidth] x [0, WindowHeight]. For ScaleFit and ScaleInteger this equals Rect(); for ScaleFill it equals the full window bounds.

func (v Viewport) WindowToVirtual(p core.Point) (core.Point, bool)

WindowToVirtual maps a physical window point into virtual coordinates. ok is false when p falls outside the active viewport (for example, inside letterbox/pillarbox bars or outside the window).

func (v Viewport) WithWindowSize(w, h float32) Viewport

WithWindowSize returns a copy of v with WindowWidth and WindowHeight set to w and h.

type VirtualViewport = Viewport

VirtualViewport is an alias for Viewport.

type Widget interface {
	// Bounds returns the widget's rectangle from the last Layout pass.
	Bounds() core.Bounds
	// contains filtered or unexported methods
}

Widget is a node in a game UI layout and focus tree.

type WidgetState struct {
	Hovered  bool
	Pressed  bool
	Focused  bool
	Disabled bool
}

WidgetState describes the current interaction state of a widget during Draw or StateOf queries.

type WorldAnchor struct {
	// ID uniquely identifies this anchor inside an AnchorOverlay.
	ID string
	// WorldX and WorldY are the anchor's coordinates in 2D game world space.
	WorldX, WorldY float32
	// OffsetX and OffsetY shift the anchored view in screen points after world projection.
	OffsetX, OffsetY float32
	// AnchorX and AnchorY position the view relative to the projected point as fractions of the view's own size:
	// (0, 0) = top-left at point, (0.5, 0.5) = centered on point, (0.5, 1.0) = centered directly above point.
	AnchorX, AnchorY float32
	// Visible toggles whether this anchor is shown when on-screen.
	Visible bool
	// View builds the native NSGo view mounted at this anchor's screen position.
	View func(*core.Scope) core.View
	// TestID optionally assigns a TestID to the positioned anchor wrapper view.
	TestID string
}

WorldAnchor binds a native NSGo View (such as a name tag, speech bubble, or text input) to a 2D world position with optional screen-space pixel offset and normalized anchor pivot.

func NewWorldAnchor(id string, worldX, worldY float32, view func(*core.Scope) core.View) *WorldAnchor

NewWorldAnchor returns a visible WorldAnchor at (worldX, worldY) rendering view.

type WorldProjection struct {
	// WorldToScreen converts a world position (worldX, worldY) to screen/window coordinates (screenX, screenY).
	WorldToScreen func(worldX, worldY float32) (screenX, screenY float32)
	// ScreenBounds is the visible screen rectangle in window coordinates.
	// When non-zero, projected positions outside ScreenBounds are treated as off-screen and hidden.
	ScreenBounds core.Bounds
}

WorldProjection maps 2D game world coordinates into screen/window coordinates and defines the visible screen bounds used to automatically hide off-screen world anchors.

func NewCameraViewportProjection(camX, camY, zoom, viewW, viewH float32, vp Viewport) WorldProjection

NewCameraViewportProjection creates a WorldProjection combining a 2D camera centered at (camX, camY) with zoom and view dimensions (viewW, viewH) with a virtual-resolution Viewport (including scaling and letterboxing). Points projecting into letterbox bars or outside the window fall outside ScreenBounds.

func NewWorldProjection(worldToScreen func(worldX, worldY float32) (screenX, screenY float32), screenBounds core.Bounds) WorldProjection

NewWorldProjection constructs a WorldProjection from a custom projection function and visible screen bounds.

func (p WorldProjection) Project(worldX, worldY float32) (pt core.Point, onScreen bool)

Project maps (worldX, worldY) to screen coordinates and reports whether the projected point is on-screen.