Справочник API собран из Go doc-комментариев в исходном коде и написан на английском языке.
package gameui
import "github.com/nsgo-dev/game/pkg/gameui"Обзор
Package gameui is experimental: its API and documented formats may change in a minor release. See the API stability policy. 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, ImageProgress, 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 ControllerReconnectPanel as a focusable alert while the game's controller-loss policy waits for input to recover.
- 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.
Указатель
- Константы
- func ApplyBindingsToActions(a *input.Actions, bindings map[string][]string, preserveRegions bool)
- func ApplyInputAssistsToActions(a *input.Actions, s save.Settings)
- func ApplySettingsResolution(v *screen.Video, s save.Settings, resolutions ...SettingsResolution)
- func ControllerReconnectPanel(cfg ControllerReconnectConfig) core.Node
- func DrawFocusRing(d *core.Drawing, bounds core.Bounds, radius float32, style *FocusRingStyle, theme *Theme)
- func EncodeScreen(doc *ScreenDoc) ([]byte, error)
- func FirstLaunchComplete(settings save.Settings) bool
- func FormatBindingLabel(token string) string
- func FormatBindingLabelForDevice(cx *core.Scope, token string, device input.DeviceKind) string
- func FormatBindingToken(in input.Input) string
- func GamepadButtonToken(b gamepad.Button) string
- func GridRects(count, columns int, bounds core.Bounds, spacing float32) []core.Bounds
- func GuardQuit(cx *core.Scope, opts QuitGuardOptions)
- func InputAssistsFromSettings(s save.Settings, toggleable ...string) input.Assists
- func MeasureScreenText(text string, fontSize float32) (width, height float32)
- func NormalizeTextInput(text string, options TextInputOptions) string
- func ParseBindingToken(token string) (input.Input, bool)
- func ParseSettingsResolution(id string) (width, height int, ok bool)
- func SetFirstLaunchComplete(settings *save.Settings, complete bool)
- func SetSettingsReduceFlashes(s *save.Settings, reduce bool)
- func SetSettingsResolution(s *save.Settings, id string)
- func SettingsReduceFlashesFrom(s save.Settings) bool
- func SettingsResolutionFrom(s save.Settings) string
- func ValidateScreen(doc *ScreenDoc) error
- type AccessibleNode
- type AccessibleRole
- type Align
- type AnchorOverlay
- func NewAnchorOverlay(cx *core.Scope) *AnchorOverlay
- func (o *AnchorOverlay) Add(anchor *WorldAnchor)
- func (o *AnchorOverlay) Get(id string) *WorldAnchor
- func (o *AnchorOverlay) Remove(id string) bool
- func (o *AnchorOverlay) ScreenPosition(id string) (core.Point, bool)
- func (o *AnchorOverlay) SetVisible(id string, visible bool) bool
- func (o *AnchorOverlay) SetWorldPosition(id string, worldX, worldY float32) bool
- func (o *AnchorOverlay) Sync(proj WorldProjection)
- func (o *AnchorOverlay) View(_ *core.Scope) core.View
- type AnchoredItem
- type BuiltScreen
- func BuildScreen(doc *ScreenDoc, opts ScreenBuildOptions) (*BuiltScreen, error)
- func (s *BuiltScreen) ApplyCatalog(cat *l10n.Catalog, locale string)
- func (s *BuiltScreen) Draw(d *core.Drawing, bounds core.Bounds)
- func (s *BuiltScreen) Layout(bounds core.Bounds)
- func (s *BuiltScreen) SetDeviceClass(class DeviceClass)
- func (s *BuiltScreen) SetSafeArea(insets core.Edges)
- func (s *BuiltScreen) SetTextLookup(fn func(key string) string)
- func (s *BuiltScreen) Widget(id string) Widget
- type Button
- type CaptionPreviewLine
- type CaptionPreviewState
- type ColorRect
- type Container
- type ControllerReconnectConfig
- type CreditEntry
- type Credits
- type Custom
- type CustomWidget
- type DeviceClass
- type DeviceProfile
- type FillMode
- type FirstLaunchSettings
- func NewFirstLaunchSettings(cfg FirstLaunchSettingsConfig) *FirstLaunchSettings
- func (f *FirstLaunchSettings) Complete() error
- func (f *FirstLaunchSettings) Err() error
- func (f *FirstLaunchSettings) Required() bool
- func (f *FirstLaunchSettings) Settings() save.Settings
- func (f *FirstLaunchSettings) View(cx *core.Scope) core.Node
- type FirstLaunchSettingsConfig
- type FirstLaunchSettingsText
- type FocusManager
- type FocusRingStyle
- type FrameDrawer
- type HBox
- type ImageProgress
- type Justify
- type KeyboardKind
- type Label
- type List
- type MeasureContext
- type Menu
- type MenuItem
- type MenuPlacement
- type NavAction
- type NavOverrides
- type NineSlice
- type Panel
- type PointerFilter
- type PointerResult
- type ProgressBar
- type QuitConfirmation
- type QuitGuardOptions
- type RichLabel
- type Root
- func NewRoot(child Widget) *Root
- func (r *Root) Activate() bool
- func (r *Root) Adjust(delta float32) bool
- func (r *Root) Bounds() core.Bounds
- func (r *Root) ClearFocus()
- func (r *Root) Draw(d *core.Drawing, bounds core.Bounds)
- func (r *Root) DrawWithViewport(d *core.Drawing, vp Viewport)
- func (r *Root) FocusIndex() int
- func (r *Root) FocusNext() bool
- func (r *Root) FocusPrev() bool
- func (r *Root) Focused() Widget
- func (r *Root) HitTest(p core.Point) Widget
- func (r *Root) Hovered() Widget
- func (r *Root) Layout(bounds core.Bounds)
- func (r *Root) MoveFocus(dx, dy int) bool
- func (r *Root) OnKeyDown(ev core.KeyEvent) bool
- func (r *Root) OnPointerDown(p core.Point) bool
- func (r *Root) OnPointerMove(p core.Point) bool
- func (r *Root) OnPointerUp(p core.Point) bool
- func (r *Root) OnPress(ev core.PressEvent) bool
- func (r *Root) Pressed() Widget
- func (r *Root) SetFocus(w Widget) bool
- func (r *Root) SetFocusIndex(index int) bool
- func (r *Root) SetTextScale(scale float32) float32
- func (r *Root) StateOf(w Widget) WidgetState
- type ScaleMode
- type ScanOptions
- type ScreenAnchor
- type ScreenBuildOptions
- type ScreenCanvas
- type ScreenCheckOptions
- type ScreenDoc
- type ScreenIssue
- type ScreenIssueCode
- type ScreenNodeDoc
- type ScreenNodeType
- type ScreenOffsetDoc
- type ScreenPaddingDoc
- type ScreenReconnectOptions
- type ScreenScaleMode
- type SettingsAction
- type SettingsAudioBus
- type SettingsConflictPolicy
- type SettingsLocale
- type SettingsMenu
- func NewSettingsMenu(cfg SettingsMenuConfig) *SettingsMenu
- func (m *SettingsMenu) Apply() error
- func (m *SettingsMenu) Back()
- func (m *SettingsMenu) BeginCapture(actionName string) bool
- func (m *SettingsMenu) CancelCapture()
- func (m *SettingsMenu) CaptionPreviewPanel() *Panel
- func (m *SettingsMenu) CaptionPreviewState() CaptionPreviewState
- func (m *SettingsMenu) CaptureBinding(token string) bool
- func (m *SettingsMenu) CapturingAction() string
- func (m *SettingsMenu) Dirty() bool
- func (m *SettingsMenu) Draw(d *core.Drawing, bounds core.Bounds)
- func (m *SettingsMenu) Err() error
- func (m *SettingsMenu) FooterButtons() (apply, saveBtn, reset, back *Button)
- func (m *SettingsMenu) HandleAction(action NavAction) bool
- func (m *SettingsMenu) Layout(bounds core.Bounds)
- func (m *SettingsMenu) Navigator() *SpatialNavigator
- func (m *SettingsMenu) NextTab()
- func (m *SettingsMenu) OnGamepadButton(btn gamepad.Button) bool
- func (m *SettingsMenu) OnKeyDown(ev core.KeyEvent) bool
- func (m *SettingsMenu) OnPointerDown(p core.Point) bool
- func (m *SettingsMenu) OnPointerMove(p core.Point) bool
- func (m *SettingsMenu) OnPointerUp(p core.Point) bool
- func (m *SettingsMenu) OnPress(ev core.PressEvent) bool
- func (m *SettingsMenu) OnTouch(ev core.TouchEvent) bool
- func (m *SettingsMenu) PrevTab()
- func (m *SettingsMenu) Reset()
- func (m *SettingsMenu) ResetControls()
- func (m *SettingsMenu) Root() *Root
- func (m *SettingsMenu) Save() error
- func (m *SettingsMenu) SetSettings(s save.Settings)
- func (m *SettingsMenu) SetTab(tab SettingsTab)
- func (m *SettingsMenu) SetText(text SettingsText)
- func (m *SettingsMenu) Settings() save.Settings
- func (m *SettingsMenu) StepActions(pressed func(NavAction) bool) bool
- func (m *SettingsMenu) StepGamepad(pads []gamepad.Pad) bool
- func (m *SettingsMenu) SyncGamepad(pads []gamepad.Pad)
- func (m *SettingsMenu) Tab() SettingsTab
- func (m *SettingsMenu) TabButton(tab SettingsTab) *Button
- func (m *SettingsMenu) TabControls(tab SettingsTab) []Widget
- type SettingsMenuConfig
- type SettingsOptionItem
- type SettingsResolution
- type SettingsTab
- type SettingsText
- type SizeMode
- type Slider
- type Spacer
- type SpatialNavigator
- func NewSpatialNavigator(root *Root) *SpatialNavigator
- func (n *SpatialNavigator) Back() bool
- func (n *SpatialNavigator) ClearFocus()
- func (n *SpatialNavigator) ClearOverrides(w Widget)
- func (n *SpatialNavigator) Confirm() bool
- func (n *SpatialNavigator) DrawFocusRing(d *core.Drawing)
- func (n *SpatialNavigator) Focused() Widget
- func (n *SpatialNavigator) HandleAction(action NavAction) bool
- func (n *SpatialNavigator) Move(dir NavAction) bool
- func (n *SpatialNavigator) Overrides(w Widget) NavOverrides
- func (n *SpatialNavigator) ScanSelect() bool
- func (n *SpatialNavigator) SetFocus(w Widget) bool
- func (n *SpatialNavigator) SetOverrides(w Widget, ov NavOverrides)
- func (n *SpatialNavigator) SetScanOptions(opts ScanOptions)
- func (n *SpatialNavigator) Step(dt time.Duration) bool
- func (n *SpatialNavigator) StepActions(pressed func(NavAction) bool) bool
- type SpriteRow
- type TextDrawParams
- type TextDrawer
- type TextInputOptions
- type TextMeasurer
- type Theme
- type Toggle
- type ToggleStyle
- type TouchButton
- type TouchStick
- type VBox
- type Viewport
- func NewViewport(virtualW, virtualH float32, mode ScaleMode) Viewport
- func (v Viewport) Apply(d *core.Drawing)
- func (v Viewport) Draw(d *core.Drawing, drawFn func(d *core.Drawing, virtualBounds core.Bounds))
- func (v Viewport) DrawLetterbox(d *core.Drawing)
- func (v Viewport) LetterboxBars() []core.Bounds
- func (v Viewport) Rect() core.Bounds
- func (v Viewport) Scale() float32
- func (v Viewport) ScaleXY() (sx, sy float32)
- func (v *Viewport) SetWindowSize(size core.Size)
- func (v Viewport) VirtualBounds() core.Bounds
- func (v Viewport) VirtualToWindow(p core.Point) core.Point
- func (v Viewport) VisibleBounds() core.Bounds
- func (v Viewport) WindowToVirtual(p core.Point) (core.Point, bool)
- func (v Viewport) WithWindowSize(w, h float32) Viewport
- type VirtualViewport
- type Widget
- type WidgetState
- type WorldAnchor
- type WorldProjection
- func NewCameraViewportProjection(camX, camY, zoom, viewW, viewH float32, vp Viewport) WorldProjection
- func NewWorldProjection(worldToScreen func(worldX, worldY float32) (screenX, screenY float32), screenBounds core.Bounds) WorldProjection
- func (p WorldProjection) Project(worldX, worldY float32) (pt core.Point, onScreen bool)
Константы
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 legacy key inside save.Settings.Custom that stored the flash-reduction toggle before save.AccessibilitySettings.ReduceFlashes existed.
//
// Deprecated: Use save.AccessibilitySettings.ReduceFlashes directly.
SettingsCustomReduceFlashes = "reduce_flashes"
)const (
MinTextScale float32 = 1
MaxTextScale float32 = 2
)MinTextScale and MaxTextScale bound Theme.TextScale, Root.TextScale and ScreenCheckOptions.TextScale.
const DefaultScreenFontSize float32 = 12DefaultScreenFontSize is the default virtual font size in points used for screen files when a node omits fontSize.
const FirstLaunchSettingsKey = "first_launch_accessibility_complete"FirstLaunchSettingsKey is the settings custom-field used by FirstLaunchSettings to record that the first-launch accessibility prompt has been completed.
const ScreenFormatVersion = 1ScreenFormatVersion is the *.screen.yaml schema version this package reads and writes.
const ScreenSchemaComment = "# yaml-language-server: $schema=" + ScreenSchemaURLScreenSchemaComment 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://nsgo.games/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 ApplyInputAssistsToActions(a *input.Actions, s save.Settings)ApplyInputAssistsToActions applies s.InputAssists and s.Accessibility.HoldToToggle (expanding a.ToggleableActions() when HoldToToggle is true) onto a.
func ApplySettingsResolution(v *screen.Video, s save.Settings, resolutions ...SettingsResolution)ApplySettingsResolution reads the persisted resolution ID from s.Custom["resolution"], resolves its dimensions against resolutions (falling back to ParseSettingsResolution), and applies it to v via v.ApplyResolution. A nil v is a no-op.
func ControllerReconnectPanel(cfg ControllerReconnectConfig) core.NodeControllerReconnectPanel shows a focusable alert over the game view. Mount it after the game canvas and drive Visible from the game's recovery state. The game continues to sample input and decides when to hide the panel.
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 FirstLaunchComplete(settings save.Settings) boolFirstLaunchComplete reports whether a settings value contains the completion marker.
func FormatBindingLabel(token string) stringFormatBindingLabel returns a concise human-readable label for a binding token using generic gamepad names and readable key-code fallbacks.
func FormatBindingLabelForDevice(cx *core.Scope, token string, device input.DeviceKind) stringFormatBindingLabelForDevice returns a binding label using device's controller family. When cx is non-nil, physical key codes use the active keyboard layout; otherwise readable names such as "W" and "Left" are used.
func FormatBindingToken(in input.Input) stringFormatBindingToken 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) stringGamepadButtonToken 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 GridRects(count, columns int, bounds core.Bounds, spacing float32) []core.BoundsGridRects returns deterministic cell rectangles for count children in a fixed-column grid. Columns below one become one, negative spacing becomes zero, and a cell never gets a negative size when the spacing does not fit.
func GuardQuit(cx *core.Scope, opts QuitGuardOptions)GuardQuit registers handlers for application quit and for the window that owns cx. Ordinary requests wait for confirmation when the guard asks. Forced requests proceed after any best-effort save. The handlers live as long as the scope.
func InputAssistsFromSettings(s save.Settings, toggleable ...string) input.AssistsInputAssistsFromSettings converts s.InputAssists (and s.Accessibility.HoldToToggle, expanding toggleable actions when enabled) into an input.Assists value.
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 NormalizeTextInput(text string, options TextInputOptions) stringNormalizeTextInput replaces invalid UTF-8 with U+FFFD, removes control characters when PrintableOnly is set, and truncates the text to MaxLength runes.
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 ParseSettingsResolution(id string) (width, height int, ok bool)ParseSettingsResolution parses a persisted resolution ID (such as "1280x720", "1280×720", "native", or "") into target dimensions in points. "native" and "" return (0, 0, true).
func SetFirstLaunchComplete(settings *save.Settings, complete bool)SetFirstLaunchComplete updates the completion marker while preserving other custom settings.
func SetSettingsReduceFlashes(s *save.Settings, reduce bool)SetSettingsReduceFlashes sets s.Accessibility.ReduceFlashes and clears any legacy s.Custom["reduce_flashes"] entry.
Deprecated: Set save.AccessibilitySettings.ReduceFlashes directly.
func SetSettingsResolution(s *save.Settings, id string)SetSettingsResolution writes id into s.Custom["resolution"].
func SettingsReduceFlashesFrom(s save.Settings) boolSettingsReduceFlashesFrom reports whether flash reduction is enabled in s, reading s.Accessibility.ReduceFlashes and falling back to legacy s.Custom["reduce_flashes"].
Deprecated: Read save.AccessibilitySettings.ReduceFlashes directly.
func SettingsResolutionFrom(s save.Settings) stringSettingsResolutionFrom reads the persisted resolution ID from s.Custom["resolution"], or "" if unset.
func ValidateScreen(doc *ScreenDoc) errorValidateScreen validates doc against the version 1 *.screen.yaml schema and invariants.
Типы
type AccessibleNode struct {
Role AccessibleRole
Name, Description, Value string
Checked, Selected, Hidden bool
}AccessibleNode is the screen-reader description of one widget: its role, its name, description and value, and its checked, selected and hidden states.
func (n AccessibleNode) Accessible() boolAccessible reports whether a screen reader can present the node: it is not hidden, and it is a label or a group or has a name.
func (n AccessibleNode) RequiresName() boolRequiresName reports whether the node is a visible control, not a label or a group, without the name a screen reader needs to announce it. It is true exactly when a visible node is not Accessible.
type AccessibleRole uint8AccessibleRole is the kind of control an AccessibleNode exposes to a screen reader.
const (
// AccessibleGroup groups related nodes; a name is optional.
AccessibleGroup AccessibleRole = iota
// AccessibleLabel is static text announced by its content; a name is optional.
AccessibleLabel
// AccessibleButton is a control that runs an action when activated.
AccessibleButton
// AccessibleCheckbox is a control with a checked state.
AccessibleCheckbox
// AccessibleSlider is a control with an adjustable value.
AccessibleSlider
// AccessibleListItem is one entry of a list, with a selected state.
AccessibleListItem
)type Align uint8Align 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) *AnchorOverlayNewAnchorOverlay 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) *WorldAnchorGet returns the registered WorldAnchor with id, or nil if not found.
func (o *AnchorOverlay) Remove(id string) boolRemove 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) boolSetVisible updates an anchor's logical visibility flag. Call Sync to apply.
func (o *AnchorOverlay) SetWorldPosition(id string, worldX, worldY float32) boolSetWorldPosition 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.ViewView 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.
// 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 canvas node IDs to their built widgets. Mount the native reconnect
// overlay separately with Doc.ControllerReconnectPanel.
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 non-disjoint 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) WidgetWidget 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
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.BoundsBounds returns the button's laid-out rectangle.
func (b *Button) HitBounds() core.BoundsHitBounds returns the button's interactive hit area, expanded to TouchHitSize when larger than Bounds.
type CaptionPreviewLine struct {
Kind a11y.CaptionKind
Speaker string
Prefix string
SpeakerPart string
Rest string
FullText string
SpeakerColor core.Color
TextColor core.Color
}CaptionPreviewLine describes one wrapped caption line rendered inside the SettingsMenu Accessibility tab's live preview swatch.
type CaptionPreviewState struct {
Enabled bool
HighContrast bool
Background core.Color
BackgroundOpacity float64
TextColor core.Color
SpeakerColors bool
FontSize core.Points
Lines []CaptionPreviewLine
}CaptionPreviewState is a snapshot of the live caption preview currently rendered over the light and dark swatches in SettingsMenu's Accessibility tab.
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.BoundsBounds 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 ControllerReconnectConfig struct {
// Visible follows the game's controller-loss state. A nil function shows
// the panel whenever it is mounted.
Visible func() bool
// Title and Message read localized strings. Nil functions use English copy
// that asks the player to reconnect the original controller.
Title func() string
Message func() string
// Prompt supplies an optional glyph from the game's input prompt table.
Prompt func() input.Prompt
// Theme styles the panel. Nil uses DefaultTheme.
Theme *Theme
}ControllerReconnectConfig configures a native controller-reconnect panel.
type CreditEntry struct{ Name, Author, License, URL string }CreditEntry is one credited asset or third-party notice.
type Credits struct {
// Title is the displayed game title.
Title string
// Version is the displayed app version.
Version string
// Build is an optional build identifier.
Build string
// Entries contains third-party acknowledgements.
Entries []CreditEntry
}Credits groups app version/build metadata and acknowledgements.
func (c Credits) Sorted() []CreditEntrySorted returns a copy of the entries sorted by name; entries with the same name keep their order.
func (c Credits) Valid() boolValid reports whether the credits have the required title and version.
type Custom struct {
// Impl supplies measurement and drawing for the widget.
Impl CustomWidget
// Width and Height override the measured size when positive.
Width, Height float32
// MinWidth and MinHeight constrain the measured size.
MinWidth, MinHeight float32
// Flex receives extra space in its parent box layout.
Flex float32
// Align controls cross-axis placement in its parent box layout.
Align Align
// Hidden excludes the widget from layout, drawing, focus, and hit testing.
Hidden bool
// FocusOrder controls explicit keyboard/gamepad focus ordering.
FocusOrder int
// contains filtered or unexported fields
}Custom adapts a game-owned CustomWidget into the gameui layout and focus tree.
func (c *Custom) Bounds() core.BoundsBounds returns the rectangle assigned by the last layout pass.
type CustomWidget interface {
// Measure returns the preferred size using the current theme.
Measure(MeasureContext) core.Size
// Draw renders the widget inside bounds with its current interaction state.
Draw(*core.Drawing, core.Bounds, WidgetState, *Theme)
}CustomWidget is the drawing and measurement contract implemented by a game-owned widget.
type DeviceClass stringDeviceClass 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() []DeviceProfileReferenceDevices 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) []DeviceProfileReferenceDevicesFor 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 FillMode uint8FillMode picks how an ImageProgress reveals its progress image as the value grows.
const (
// FillLeftToRight reveals the progress image from the left edge to the right (the default).
FillLeftToRight FillMode = iota
// FillRightToLeft reveals the progress image from the right edge to the left.
FillRightToLeft
// FillTopToBottom reveals the progress image from the top edge to the bottom.
FillTopToBottom
// FillBottomToTop reveals the progress image from the bottom edge to the top.
FillBottomToTop
// FillCenterHorizontal reveals the progress image from the horizontal center outward to both sides.
FillCenterHorizontal
// FillCenterVertical reveals the progress image from the vertical center outward to both edges.
FillCenterVertical
// FillClockwise reveals the progress image along a clockwise pie sweep from StartAngle.
FillClockwise
// FillCounterClockwise reveals the progress image along a counter-clockwise pie sweep from StartAngle.
FillCounterClockwise
)func ParseFillMode(s string) (FillMode, bool)ParseFillMode maps a screen-file fill name (such as "clockwise") to its FillMode, reporting whether s was recognized.
func (m FillMode) String() stringString returns the screen-file name of m (such as "clockwise"), or "left_to_right" for an unknown mode.
type FirstLaunchSettings struct {
// contains filtered or unexported fields
}FirstLaunchSettings is a small, reusable first-launch gate for templates. It enables captions by default, preserves a player's existing text and motion preferences, and disappears permanently after Continue succeeds.
func NewFirstLaunchSettings(cfg FirstLaunchSettingsConfig) *FirstLaunchSettingsNewFirstLaunchSettings creates a prompt from persisted settings or defaults.
func (f *FirstLaunchSettings) Complete() errorComplete enables captions, persists the completion marker, and closes the prompt.
func (f *FirstLaunchSettings) Err() errorErr returns the last load or save error.
func (f *FirstLaunchSettings) Required() boolRequired reports whether the prompt should block the first game screen.
func (f *FirstLaunchSettings) Settings() save.SettingsSettings returns a validated copy of the settings currently held by the prompt.
func (f *FirstLaunchSettings) View(cx *core.Scope) core.NodeView renders the prompt as a native NSGo overlay. Mount it before the first sound is played; it removes itself once Complete succeeds and renders nothing when the prompt was already completed.
type FirstLaunchSettingsConfig struct {
// Store persists the completion marker and the initial accessibility values.
Store *save.DefaultSettingsStore
// Initial supplies settings when Store is nil or has no saved value.
Initial *save.Settings
// Text localizes the prompt. Empty fields use DefaultFirstLaunchSettingsText.
Text FirstLaunchSettingsText
// OnMoreOptions opens the full SettingsMenu's Accessibility tab.
OnMoreOptions func()
// OnComplete runs after the marker and settings have been saved.
OnComplete func(save.Settings) error
}FirstLaunchSettingsConfig configures the first-launch accessibility prompt.
type FirstLaunchSettingsText struct {
Title string
Body string
Captions string
TextSize string
ReducedMotion string
MoreOptions string
Continue string
}FirstLaunchSettingsText contains the copy shown before a game plays its first sound. Applications can localize the prompt without replacing its layout.
func DefaultFirstLaunchSettingsText() FirstLaunchSettingsTextDefaultFirstLaunchSettingsText returns the English first-launch copy.
type FocusManager = SpatialNavigatorFocusManager 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) FrameDrawerNineSliceStateFrame 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.BoundsBounds returns the HBox's laid-out rectangle.
func (b *HBox) ChildWidgets() []WidgetChildWidgets returns the HBox's direct children.
type ImageProgress struct {
Value float32
Min float32
Max float32
Under *NineSlice
Progress *NineSlice
Over *NineSlice
Fill FillMode
StartAngle float32 // degrees, 0 = right, positive clockwise; radial fills only
Span float32 // degrees, 0 defaults to 360; radial fills only
FillColor core.Color
TrackColor core.Color
Width float32
Height float32
MinWidth float32
MinHeight float32
Flex float32
Align Align
Hidden bool
// contains filtered or unexported fields
}ImageProgress displays a read-only progress meter in [Min, Max] (or [0, 1] when both Min and Max are 0) built from up to three layered images: Under drawn in full first, Progress revealed by the value along Fill, and Over drawn in full last (such as an ornate frame over a boss bar).
Each layer is a NineSlice: a plain image when its insets are zero, or a nine-patch that keeps its cap sizes when the widget is wider or taller than the source. Linear fills clip the progress layer to the revealed rectangle, so a nine-slice progress image keeps its caps at any value; radial fills (FillClockwise and FillCounterClockwise) clip it to a pie from StartAngle degrees (0 points right, positive is clockwise) sweeping Span degrees (0 defaults to 360). When a layer is nil the widget falls back to a flat fill: TrackColor (or Theme.Track) for Under and FillColor (or Theme.Accent) for Progress.
func (p *ImageProgress) Bounds() core.BoundsBounds returns the image progress's laid-out rectangle.
func (p *ImageProgress) Fraction() float32Fraction returns Value normalized into [0, 1].
type Justify uint8Justify 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 KeyboardKind uint8KeyboardKind hints at the native keyboard requested by a text field.
const (
// KeyboardText requests the platform's default text keyboard.
KeyboardText KeyboardKind = iota
// KeyboardNumber requests a numeric keypad.
KeyboardNumber
// KeyboardEmail requests a keyboard laid out for email addresses.
KeyboardEmail
// KeyboardURL requests a keyboard laid out for URLs.
KeyboardURL
// KeyboardASCII requests a keyboard limited to ASCII characters.
KeyboardASCII
)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.BoundsBounds 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
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.BoundsBounds returns the list's laid-out rectangle.
func (l *List) ItemAt(p core.Point) intItemAt returns the 0-based index of the item containing p, or -1 if none.
func (l *List) ItemBounds(index int) core.BoundsItemBounds returns the laid-out rectangle for item at index, or zero Bounds if out of range.
func (l *List) Select(index int) boolSelect updates Selected to index (clamped into [0, len(Items)-1]) and invokes OnSelect. Returns false when the list is disabled or empty.
type MeasureContext struct {
// Theme is the active game UI theme.
Theme *Theme
}MeasureContext describes theme information available while measuring a custom widget.
type Menu struct{ Items []MenuItem }Menu is a deterministic ordered popup menu model.
func (m Menu) NextEnabled(index, step int) intNextEnabled returns the next item Selectable accepts, moving one item forward for a positive step and one back for a negative one, wrapping around and skipping separators, disabled items and items without an ID. It returns -1 when no item is selectable. An index outside the items, such as -1 for no selection, starts from the matching end.
func (m Menu) Selectable(index int) boolSelectable reports whether index can be activated.
type MenuItem struct {
ID string
Text string
Disabled bool
Separator bool
Checked bool
}MenuItem is an actionable or separator row in a popup menu.
type MenuPlacement struct {
Bounds core.Bounds
Sheet bool
}MenuPlacement describes a popup rectangle constrained to a safe area.
func PlaceMenu(owner, safe core.Bounds, width, height core.Points) MenuPlacementPlaceMenu places a popup below owner, flipping above or clamping inside safe.
type NavAction uint8NavAction identifies a logical UI navigation action from keyboard, gamepad, or virtual controls.
const (
// NavNone is the zero value representing no action.
// NavUp moves focus upward.
// NavDown moves focus downward.
// NavLeft moves focus left (or decrements a focused Slider when SliderSteps is enabled).
// NavRight moves focus right (or increments a focused Slider when SliderSteps is enabled).
// NavConfirm activates the currently focused widget and invokes OnConfirm.
// NavBack invokes OnBack (e.g. closing a submenu or canceling an action).
)func (a NavAction) String() stringString returns a human-readable name for a.
type NavOverrides struct {
}NavOverrides specifies explicit per-widget directional neighbors that take precedence over automatic 2D spatial lookup.
func (o NavOverrides) For(dir NavAction) WidgetFor 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() FrameDrawerFrameDrawer 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.BoundsBounds returns the panel's laid-out rectangle.
func (p *Panel) ChildWidgets() []WidgetChildWidgets returns the panel's child if non-nil.
type PointerFilter uint8PointerFilter controls whether a widget consumes a pointer press.
const (
// PointerStop reports a hit and stops it from reaching the widget's parents and the world.
PointerStop PointerFilter = iota
// PointerPass reports a hit and lets it continue to the widget's parents and the world.
PointerPass
// PointerIgnore does not report a hit at all.
PointerIgnore
)func (f PointerFilter) ShouldConsume() boolShouldConsume reports whether a hit should stop propagation to the world, which only PointerStop does, matching ResolvePointerFilter.
type PointerResult struct {
Hit bool
Consumed bool
}PointerResult describes a widget hit and whether it should continue to its parent.
func ResolvePointerFilter(filter PointerFilter, hit bool) PointerResultResolvePointerFilter applies a widget filter to a hit. Ignore does not claim the pointer, Pass reports the hit without consuming it, and Stop consumes it.
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.BoundsBounds returns the progress bar's laid-out rectangle.
func (p *ProgressBar) Fraction() float32Fraction returns Value normalized into [0, 1].
type QuitConfirmation struct {
Open func() bool
// OnAnswer receives true to proceed and false to cancel. Close the dialog
// by making Open return false on either answer.
OnAnswer func(proceed bool)
// Save is optional. A failed save leaves the dialog open for retry.
Save func() error
// CanSave limits when Save and quit is shown. Nil allows it whenever Save is set.
CanSave func() bool
// Report receives a failed save for game-specific logging or feedback.
Report func(error)
// The captions can be localized or adapted for Restart and Quit to title.
// Empty captions use English quit copy.
Title, Description, CancelText, QuitText, SaveText, SaveFailedText string
}QuitConfirmation is an alert dialog for actions that would discard progress. It starts with Cancel focused. For controller navigation, enable gamepad.EnableFocusNavigation on the window and release gameplay input capture while the dialog is open.
func (q QuitConfirmation) Render(cx *core.Scope) core.NodeRender implements core.Node.
type QuitGuardOptions struct {
// Guard decides which requests may proceed and when to try saving.
Guard save.QuitGuard
// Ask presents a confirmation and calls answer on the scope's goroutine.
// Passing true allows the request. When Ask is nil the request is canceled.
Ask func(answer func(quit bool))
// Pause receives true while a confirmation is open and false when it is answered.
Pause func(bool)
// Report receives an error from an attempted save.
Report func(error)
}QuitGuardOptions connects a game's unsaved progress to desktop close and quit requests.
type RichLabel struct {
Markup string
OnLink func(string)
Links []text.RichLink
}RichLabel is a lightweight rich-markup model with clickable link spans.
func (r *RichLabel) Activate(index int)Activate invokes OnLink for a link index.
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
// TextScale multiplies every widget font size under this Root, including explicit per-widget and screen-file sizes; it is clamped to [MinTextScale, MaxTextScale], and 0 uses Theme.TextScale.
TextScale float32
// 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) *RootNewRoot returns a Root wrapping child with the default theme.
func (r *Root) Activate() boolActivate triggers the currently focused widget (clicks a Button or flips a Toggle).
func (r *Root) Adjust(delta float32) boolAdjust 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.BoundsBounds 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() intFocusIndex 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() boolFocusNext moves focus to the next enabled, focusable widget, wrapping from the end to the beginning.
func (r *Root) FocusPrev() boolFocusPrev moves focus to the previous enabled, focusable widget, wrapping from the beginning to the end.
func (r *Root) Focused() WidgetFocused returns the currently focused widget, or nil if none is focused.
func (r *Root) HitTest(p core.Point) WidgetHitTest 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() WidgetHovered 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) boolMoveFocus 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) boolOnKeyDown handles keyboard navigation, activation, and slider adjustment. Returns true if the event was consumed by the UI.
func (r *Root) OnPointerDown(p core.Point) boolOnPointerDown 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) boolOnPointerMove 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) boolOnPointerUp 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) boolOnPress 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() WidgetPressed returns the currently pressed interactive widget, or nil.
func (r *Root) SetFocus(w Widget) boolSetFocus focuses w if it is visible and focusable in this tree.
func (r *Root) SetFocusIndex(index int) boolSetFocusIndex focuses the focusable widget at index, or clears focus when index < 0.
func (r *Root) SetTextScale(scale float32) float32SetTextScale sets the root text scale and returns the normalized value.
func (r *Root) StateOf(w Widget) WidgetStateStateOf returns the current hover, pressed, focused, and disabled state of w.
type ScaleMode uint8ScaleMode 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 ScanOptions struct {
Enabled bool
Interval time.Duration
Loops int
Select NavAction
}ScanOptions configures one-switch focus scanning. Interval is the time between focus changes. Loops limits completed passes when positive, while a zero value scans continuously. Select is the action StepActions treats as the switch that activates the highlighted widget.
type ScreenAnchor stringScreenAnchor 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.BoundsBounds returns the canvas's laid-out rectangle.
func (c *ScreenCanvas) ChildWidgets() []WidgetChildWidgets returns the direct child widgets in render order.
type ScreenCheckOptions struct {
// TextScale is the largest text scale the game supports. When it is above the theme's own scale, text overflow is checked at both scales, and an overflow that only appears at the larger one names that scale in its message. It is clamped to [MinTextScale, MaxTextScale]; 0 checks the theme's scale only.
TextScale float32
// 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. Canvas widgets render 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, fields unsupported by a node's type, disjoint nested deviceClasses, 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() *ScreenDocClone returns a deep copy of doc.
func (d *ScreenDoc) ControllerReconnectPanel(opts ScreenReconnectOptions) core.NodeControllerReconnectPanel returns the native overlay declared by the screen, or nil if there is no controller_reconnect node. Mount it after the canvas in the view it should cover. A screen node without a titleKey or messageKey uses the corresponding default text.
func (doc *ScreenDoc) EffectiveScaleMode() ScaleModeEffectiveScaleMode 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) []ScreenIssueCheckScreen 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);
- localization keys missing from any project locale;
- text under 4.5:1 WCAG contrast against its own fill.
type ScreenIssueCode stringScreenIssueCode 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 localization key 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|image_progress|controller_reconnect"`
// 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") on label and button nodes.
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 (vbox, hbox, label, button).
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") for label, button, and touch_button nodes. Screen files store localization keys rather than literal text.
TextKey string `yaml:"textKey,omitempty"`
// TitleKey names an optional localization string for the controller_reconnect title.
TitleKey string `yaml:"titleKey,omitempty"`
// MessageKey names an optional localization string for controller_reconnect recovery instructions.
MessageKey string `yaml:"messageKey,omitempty"`
// PromptAction selects an optional prompt-table action for the controller_reconnect glyph.
PromptAction string `yaml:"promptAction,omitempty"`
// FocusOrder sets the explicit keyboard/gamepad focus traversal order (1-based; 0 means not explicitly ordered) on button and touch_button nodes.
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; nested nodes must overlap their parent's allowed classes.
DeviceClasses []DeviceClass `yaml:"deviceClasses,omitempty"`
// Sprite is a project-relative path to a sprite image or atlas file (for example "art/ui/heart.png") for sprite_row nodes, 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 on a sprite_row node.
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"`
// Under is a project-relative path to the image_progress background layer image, drawn in full first.
Under string `yaml:"under,omitempty"`
// Progress is a project-relative path to the image_progress fill layer image, revealed by the value along Fill.
Progress string `yaml:"progress,omitempty"`
// Over is a project-relative path to the image_progress foreground layer image, drawn in full last.
Over string `yaml:"over,omitempty"`
// Fill picks how an image_progress reveals its progress image: left_to_right (the default), right_to_left, top_to_bottom, bottom_to_top, center_h, center_v, clockwise, or counter_clockwise.
Fill string `yaml:"fill,omitempty" schema:"enum=left_to_right|right_to_left|top_to_bottom|bottom_to_top|center_h|center_v|clockwise|counter_clockwise"`
// StartAngle is the image_progress radial fill's starting angle in degrees (0 points right, positive is clockwise).
StartAngle float32 `yaml:"startAngle,omitempty"`
// Span is the image_progress radial fill's full sweep in degrees (0 defaults to 360).
Span float32 `yaml:"span,omitempty" schema:"minimum=0,maximum=360"`
// Min is the image_progress range's lower bound (defaults to 0).
Min float32 `yaml:"min,omitempty"`
// Max is the image_progress range's upper bound (defaults to 1 when both min and max are 0).
Max float32 `yaml:"max,omitempty"`
// Value is the image_progress node's initial value; game code updates the widget's Value at runtime.
Value float32 `yaml:"value,omitempty"`
// FontSize overrides the text font size in virtual points for label, button, and touch_button nodes.
FontSize float32 `yaml:"fontSize,omitempty" schema:"minimum=0"`
// TextColor is an optional CSS color string parsed with core.ParseColor for text (label, button, touch_button) or the thumbstick knob (touch_stick).
TextColor string `yaml:"textColor,omitempty"`
// Background is an optional CSS color string parsed with core.ParseColor for canvas nodes other than image_progress. It tints fallback sprite_row icons and the touch_stick ring.
Background string `yaml:"background,omitempty"`
// CornerRadius is an optional corner radius in virtual points (vbox, hbox, container, label, button, color_rect).
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() ScreenAnchorEffectiveAnchor returns n.Anchor, defaulting to AnchorTopLeft when empty.
func (n *ScreenNodeDoc) KeepInSafeArea() boolKeepInSafeArea 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 stringScreenNodeType 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"
// NodeImageProgress displays a read-only progress meter built from layered under/progress/over images with a directional or radial fill.
NodeImageProgress ScreenNodeType = "image_progress"
// NodeControllerReconnect declares the screen's native controller-reconnect overlay.
NodeControllerReconnect ScreenNodeType = "controller_reconnect"
)func (t ScreenNodeType) IsContainer() boolIsContainer 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.EdgesEdges converts p into core.Edges (returning zero edges when p is nil).
type ScreenReconnectOptions struct {
// Visible follows the game's controller-loss state. Nil shows the panel whenever mounted.
Visible func() bool
// Text resolves the titleKey and messageKey. It may read a locale signal.
// Nil shows the keys themselves.
Text func(key string) string
// Prompt resolves promptAction to the current device's prompt. Nil omits the glyph.
Prompt func(action string) input.Prompt
// Theme styles the panel. Nil uses DefaultTheme.
Theme *Theme
}ScreenReconnectOptions binds a screen's controller_reconnect node to the game.
type ScreenScaleMode stringScreenScaleMode 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
// Group identifies actions that may not share a binding. Different groups may share bindings.
Group string
// Defaults lists default binding tokens (for example "key:space", "gamepad:south") restored on Reset.
Defaults []string
// AllowToggle reports whether the Controls tab offers a per-action Hold to Toggle assist switch for this action.
AllowToggle bool
// AllowMash reports whether the Controls tab offers a per-action Hold to Mash assist switch for this action.
AllowMash bool
}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 SettingsConflictPolicy uint8SettingsConflictPolicy controls how CaptureBinding resolves a binding used by another action in the same group.
const (
// ConflictSwap, the default, binds the token to the capturing action and gives the other action the binding of the same device class the capturing action had, or clears the token from the other action when it had none.
ConflictSwap SettingsConflictPolicy = iota
// ConflictClear binds the token to the capturing action and removes it from the other action.
ConflictClear
// ConflictRefuse leaves every binding unchanged, keeps capturing, and shows SettingsText.ConflictStatus.
ConflictRefuse
)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) *SettingsMenuNewSettingsMenu constructs a SettingsMenu wired to cfg and ready to draw and receive input.
func (m *SettingsMenu) Apply() errorApply validates the working settings and dispatches them to Targets, Video (for resolution), and OnApply.
func (m *SettingsMenu) Back()Back cancels capture if active; otherwise invokes OnBack.
func (m *SettingsMenu) BeginCapture(actionName string) boolBeginCapture enters control-rebinding capture mode for actionName.
func (m *SettingsMenu) CancelCapture()CancelCapture exits control-rebinding capture mode without modifying bindings.
func (m *SettingsMenu) CaptionPreviewPanel() *PanelCaptionPreviewPanel returns the non-focusable live caption preview panel inside the Accessibility tab.
func (m *SettingsMenu) CaptionPreviewState() CaptionPreviewStateCaptionPreviewState computes the live preview styling and sample caption lines from the menu's current working Accessibility settings.
func (m *SettingsMenu) CaptureBinding(token string) boolCaptureBinding 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() stringCapturingAction returns the action name currently awaiting a key or gamepad button press, or "".
func (m *SettingsMenu) Dirty() boolDirty 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() errorErr 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) boolHandleAction 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() *SpatialNavigatorNavigator 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) boolOnGamepadButton 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) boolOnKeyDown handles keyboard navigation, slider/option stepping, and control rebinding capture.
func (m *SettingsMenu) OnPointerDown(p core.Point) boolOnPointerDown focuses and presses the control under p.
func (m *SettingsMenu) OnPointerMove(p core.Point) boolOnPointerMove updates hover state and drags any active slider.
func (m *SettingsMenu) OnPointerUp(p core.Point) boolOnPointerUp finishes any press or slider drag, activating controls released inside their bounds.
func (m *SettingsMenu) OnPress(ev core.PressEvent) boolOnPress handles a completed core.PressEvent directly.
func (m *SettingsMenu) OnTouch(ev core.TouchEvent) boolOnTouch 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, motor assists, and control and camera preferences to their default values.
func (m *SettingsMenu) Root() *RootRoot returns the menu's underlying gameui Root.
func (m *SettingsMenu) Save() errorSave validates the working settings, persists them through Store (when configured), applies them to Targets/Video/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.SettingsSettings returns a deep copy of the menu's current working player settings.
func (m *SettingsMenu) StepActions(pressed func(NavAction) bool) boolStepActions polls logical UI navigation actions (such as from input.Actions.JustPressed) and dispatches them in deterministic order.
func (m *SettingsMenu) StepGamepad(pads []gamepad.Pad) boolStepGamepad 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() SettingsTabTab returns the currently active SettingsTab.
func (m *SettingsMenu) TabButton(tab SettingsTab) *ButtonTabButton returns the tab-bar Button for tab.
func (m *SettingsMenu) TabControls(tab SettingsTab) []WidgetTabControls 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
// Video optionally receives the selected windowed resolution via ApplySettingsResolution whenever Apply or Save runs.
Video *screen.Video
// Env optionally supplies the platform environment so the Video tab hides controls that cannot apply on the current platform (hiding Window Mode where screen.CanFullScreen is false and hiding Resolution where screen.SupportsWindowResolution is false) and keeps Window Mode synchronized with Env.FullScreen. When nil, desktop capabilities are assumed unless HideResolution is set.
Env *core.Env
// Scope optionally resolves physical key codes to labels in the active layout.
Scope *core.Scope
// 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
// HideResolution omits the Resolution row from the Video tab even on desktop or when Env is nil.
HideResolution bool
// ShowVSync includes the VSync toggle in the Video tab. False by default because NSGo v0.3.4 does not yet expose swap-interval control; enable only when wiring save.DisplaySettings.VSync to a real backend control.
ShowVSync bool
// ShowCameraSettings includes the field of view, camera bob, camera sway and motion blur rows (save.CameraSettings) in the Controls tab. Enable it for games with a 3D camera that applies them through SettingsTargets.ApplyCamera.
ShowCameraSettings bool
// 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
// OnConflict selects how CaptureBinding resolves a binding used by another action in the same group.
OnConflict SettingsConflictPolicy
// DeviceTracker optionally supplies the active controller family for labels.
DeviceTracker *input.DeviceTracker
// Locales configures selectable languages in the Language tab.
Locales []SettingsLocale
// ColorBlindModes configures color-blind palette modes in the Accessibility tab.
ColorBlindModes []SettingsOptionItem
// CaptionSizes configures caption size presets in the Accessibility tab (defaults to small, medium, large, xlarge).
CaptionSizes []SettingsOptionItem
// CaptionBackgrounds configures caption backdrop colors in the Accessibility tab (defaults to black, gray, blue, white).
CaptionBackgrounds []SettingsOptionItem
// CaptionTextColors configures caption text colors in the Accessibility tab (defaults to white, yellow, cyan, green, black).
CaptionTextColors []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 uint8SettingsTab identifies one of the five built-in sections of a SettingsMenu.
const (
// SettingsTabAudio edits mute, master volume, audio bus volumes, mono audio, and left/right balance.
SettingsTabAudio SettingsTab = iota
// SettingsTabVideo edits window mode, resolution (on desktop), scale mode, integer scale, quality preset, frame cap, and (when enabled via ShowVSync) VSync.
SettingsTabVideo
// SettingsTabControls edits keyboard and gamepad action bindings with capture and reset.
SettingsTabControls
// SettingsTabLanguage selects the active locale.
SettingsTabLanguage
// SettingsTabAccessibility edits captions, SFX captions, text scale, high contrast, reduced motion, screen shake, flash reduction, color-blind mode, game speed, invincibility, auto-aim, and hold-to-toggle.
SettingsTabAccessibility
)func (t SettingsTab) String() stringString 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
MonoAudio string
MonoOn string
MonoOff string
Balance string
BalanceLeft string
BalanceCenter string
BalanceRight 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
ConflictStatus string
Unbound string
ResetControls string
ActionToggle string
ActionMash string
MinPressTime string
AcceptDelay string
AssistOff string
MouseSensitivity string
StickSensitivity string
TouchSensitivity string
GyroSensitivity string
InvertX string
InvertY string
StickDeadZone string
TriggerThreshold string
Vibration string
FieldOfView string
CameraBob string
CameraSway string
MotionBlur string
LanguageHint string
SystemDefault string
CaptionsSection string
AssistSection string
Subtitles string
DialogueCaptions string
ChatterCaptions string
SFXCaptions string
CaptionSize string
CaptionBackground string
CaptionOpacity string
CaptionTextColor string
SpeakerColors string
CaptionsOffPreview string
PreviewLight string
PreviewDark string
PreviewSpeaker string
PreviewQualifier string
PreviewDialogue string
PreviewChatterSpeaker string
PreviewChatter string
PreviewSFX string
TextScale string
HighContrast string
ReduceMotion string
ScreenShake string
ReduceFlashes string
ColorBlind string
ColorBlindSeverity string
GameSpeed string
Invincibility string
AutoAim string
HoldToToggle 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() SettingsTextDefaultSettingsText returns the English strings used by SettingsMenu.
type SizeMode stringSizeMode 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
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.BoundsBounds returns the slider's laid-out rectangle.
func (s *Slider) Fraction() float32Fraction returns the slider's current Value normalized into [0, 1].
func (s *Slider) SetValue(v float32) boolSetValue clamps v into [Min, Max], updates Value, and invokes OnChange if Value changed.
func (s *Slider) TrackBounds() core.BoundsTrackBounds 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.BoundsBounds returns the spacer's laid-out rectangle.
type SpatialNavigator struct {
// Root is the UI root whose focusable widgets are navigated.
// WrapAround enables edge wrap-around when no widget exists further in the requested direction.
// 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.
// OnConfirm is invoked after NavConfirm activates the focused widget (or when Confirm is called).
// OnBack is invoked when NavBack is triggered.
// OnFocusChange is invoked whenever navigation moves focus from prev to next.
// FocusRing customizes the focus ring drawn by DrawFocusRing (or attached to Root).
// Scan configures optional one-switch scanning. Use SetScanOptions to reset the scan clock after changing it.
// 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) *SpatialNavigatorNewSpatialNavigator returns a SpatialNavigator attached to root with wrap-around and slider stepping enabled.
func (n *SpatialNavigator) Back() boolBack 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() boolConfirm 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() WidgetFocused returns the currently focused widget in Root, or nil.
func (n *SpatialNavigator) HandleAction(action NavAction) boolHandleAction executes a single NavAction (directional move, slider step, confirm, or back).
func (n *SpatialNavigator) Move(dir NavAction) boolMove 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) NavOverridesOverrides returns the navigator-level overrides registered for w (or zero value if none).
func (n *SpatialNavigator) ScanSelect() boolScanSelect activates the currently highlighted widget when scanning is enabled. It is suitable for a single switch or eye-tracker action.
func (n *SpatialNavigator) SetFocus(w Widget) boolSetFocus 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) SetScanOptions(opts ScanOptions)SetScanOptions enables or disables one-switch scanning and resets its clock.
func (n *SpatialNavigator) Step(dt time.Duration) boolStep advances the scanner by fixed simulation time, moving focus through the root's focus order (wrapping from the last widget to the first) rather than by spatial direction, so rows, grids and columns all scan every widget. It returns true when focus moved.
func (n *SpatialNavigator) StepActions(pressed func(NavAction) bool) boolStepActions 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.BoundsBounds 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 TextInputOptions struct {
// MaxLength limits the text to this many runes; zero or less means no limit.
MaxLength int
// PrintableOnly removes control characters (Unicode category Cc, which includes C0, DEL and C1).
PrintableOnly bool
// Secret asks the native field to hide the text, as for a password.
Secret bool
// Keyboard is the native keyboard hint.
Keyboard KeyboardKind
}TextInputOptions describes portable validation before a native input bridge applies text.
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 {
// TextScale multiplies every widget font size, the default Font and per-widget overrides alike, during layout and draw; it is clamped to [MinTextScale, MaxTextScale], and 0 means 1. Root.TextScale, when set, replaces it.
TextScale float32
// 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() ThemeDefaultTheme returns a high-contrast dark theme suited for in-game overlays and menus.
func HighContrastTheme() ThemeHighContrastTheme 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
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.BoundsBounds returns the toggle's laid-out rectangle.
type ToggleStyle uint8ToggleStyle 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
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.BoundsBounds returns the touch button's visual bounds.
func (b *TouchButton) HitBounds() core.BoundsHitBounds 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.BoundsBounds returns the stick's visual bounds.
func (t *TouchStick) HitBounds() core.BoundsHitBounds 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.BoundsBounds returns the VBox's laid-out rectangle.
func (b *VBox) ChildWidgets() []WidgetChildWidgets 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) ViewportNewViewport 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.BoundsLetterboxBars returns the non-empty, non-overlapping bar rectangles inside the window outside Rect().
func (v Viewport) Rect() core.BoundsRect 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() float32Scale 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.BoundsVirtualBounds returns the layout rectangle in virtual coordinates: (0, 0, VirtualWidth, VirtualHeight).
func (v Viewport) VirtualToWindow(p core.Point) core.PointVirtualToWindow maps a point in virtual coordinates into physical window coordinates.
func (v Viewport) VisibleBounds() core.BoundsVisibleBounds 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) ViewportWithWindowSize returns a copy of v with WindowWidth and WindowHeight set to w and h.
type VirtualViewport = ViewportVirtualViewport 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) *WorldAnchorNewWorldAnchor 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) WorldProjectionNewCameraViewportProjection 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) WorldProjectionNewWorldProjection 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.