GitHubНачать

Справочник API собран из Go doc-комментариев в исходном коде и написан на английском языке.

package save

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

Обзор

Package save stores a game's save slots as versioned JSON in either the app's key-value storage (core.Storage) or files in a directory such as cx.DataDir.

Each slot holds a {"version": N, "data": ...} envelope, with optional "header" and "seal" fields; an envelope with any other field, or with a field given twice, is corrupt. When a Store loads a save written by an older version, it runs its registered migrations one version at a time (v to v+1) before unmarshaling into the caller's value; a save from a newer version is refused with ErrFutureVersion rather than read into an older shape.

Writes keep the previous valid save as a backup before replacing the primary copy (with a write, sync and rename on disk, or a backup key in core.Storage), so a failed write leaves the last good save intact and a corrupted primary falls back to the backup on Load.

Player settings (audio, bindings, display, locale, accessibility and custom preferences) are persisted separately via SettingsStore and DefaultSettingsStore outside the save-slot namespace, so deleting or clearing save slots never touches player settings, and LoadAndApply wires loaded settings to game subsystems on startup.

Указатель

Константы

const (

	// MinCaptionScale is the minimum allowed AccessibilitySettings.CaptionScale multiplier.
	MinCaptionScale = 0.5
	// MaxCaptionScale is the maximum allowed AccessibilitySettings.CaptionScale multiplier.
	MaxCaptionScale = 3.0
	// MinGameSpeed is the slowest allowed AccessibilitySettings.GameSpeed multiplier.
	MinGameSpeed = 0.25
	// MaxGameSpeed is the fastest allowed AccessibilitySettings.GameSpeed multiplier.
	MaxGameSpeed = 2.0
	// MaxMinPressMs is the maximum allowed InputAssistSettings.MinPressMs in milliseconds.
	MaxMinPressMs = 2000
	// MaxAcceptDelayMs is the maximum allowed InputAssistSettings.AcceptDelayMs in milliseconds.
	MaxAcceptDelayMs = 2000

	// DefaultCaptionBackgroundOpacity is the default caption pill backdrop opacity (90%).
	DefaultCaptionBackgroundOpacity = 0.9

	// Canonical caption background color presets accepted by NormalizeCaptionBackground.
	CaptionBackgroundBlack = "black"
	CaptionBackgroundGray  = "gray"
	CaptionBackgroundBlue  = "blue"
	CaptionBackgroundWhite = "white"

	// Canonical caption text color presets accepted by NormalizeCaptionTextColor.
	CaptionTextWhite  = "white"
	CaptionTextYellow = "yellow"
	CaptionTextCyan   = "cyan"
	CaptionTextGreen  = "green"
	CaptionTextBlack  = "black"

	// Canonical caption size presets accepted by NormalizeCaptionSize.
	CaptionSizeSmall  = "small"
	CaptionSizeMedium = "medium"
	CaptionSizeLarge  = "large"
	CaptionSizeXLarge = "xlarge"
)
const (
	MinLookSensitivity = 0.1
	MaxLookSensitivity = 5
	MaxStickDeadZone   = 0.95
	MinFieldOfView     = 40
	MaxFieldOfView     = 120
)

Ranges of ControlSettings and CameraSettings values, which Validate clamps to and gameui.SettingsMenu's sliders span.

Переменные

var (
	// ErrNotFound reports that no save exists in the named slot.
	ErrNotFound = errors.New("save: slot not found")
	// ErrInvalidSlot reports that a slot name is empty or unsafe for storage keys or file paths.
	ErrInvalidSlot = errors.New("save: invalid slot name")
	// ErrFutureVersion reports that a save was written by a newer schema version than the store supports.
	ErrFutureVersion = errors.New("save: version newer than supported")
	// ErrMissingMigration reports that a store lacks a migration step needed to bring a save up to its current version.
	ErrMissingMigration = errors.New("save: missing migration")
	// ErrCorrupt reports invalid save contents, including a malformed envelope or data of the wrong JSON type.
	ErrCorrupt = errors.New("save: corrupt data")
	// ErrStorageFull reports that the backend could not persist the save because storage is full.
	ErrStorageFull = errors.New("save: storage full")
	// ErrTampered reports a configured seal that does not match the envelope. It also wraps ErrCorrupt.
	ErrTampered = errors.New("save: tampered data")
)

Функции

func Apply(s Settings, targets SettingsTargets) error

Apply validates a copy of s and dispatches its sections to every non-nil target in targets. All non-nil targets are invoked even if an earlier target returns an error; errors are combined with errors.Join.

func CaptionSizeScale(size string) float64

CaptionSizeScale returns the text size multiplier for a caption size preset ("small" = 0.75, "medium" = 1.0, "large" = 1.25, "xlarge" = 1.5).

func EncodeParts(parts map[string]PartEntry) (json.RawMessage, error)

EncodeParts encodes parts into the JSON object layout Game.Save writes and Game.Load reads ({"parts": {"<name>": {"version": N, "data": ...}}}). Use it in a Store-level Migration when upgrading a legacy flat save struct to a Game registry.

func EnvelopeVersion(payload []byte) (int, bool)

EnvelopeVersion returns the schema version recorded in a save envelope payload, or (0, false) when payload does not carry a positive integer "version" field.

Like Store.Load, it reads a JSON object carrying unknown fields so a save written by a newer build with extra envelope fields still reports its version.

func EqualJSON(a, b json.RawMessage) bool

EqualJSON reports whether a and b represent the same JSON value, ignoring whitespace and object key ordering differences.

func NormalizeCaptionBackground(s string) string

NormalizeCaptionBackground returns the canonical background color name or lowercase "#rrggbb" hex string, defaulting unrecognized/empty inputs to "black".

func NormalizeCaptionSize(s string) string

NormalizeCaptionSize returns the canonical caption size preset ("small", "medium", "large", or "xlarge"), defaulting unrecognized/empty inputs to "medium".

func NormalizeCaptionTextColor(s string) string

NormalizeCaptionTextColor returns the canonical text color name or lowercase "#rrggbb" hex string, defaulting unrecognized/empty inputs to "white".

func NormalizeColorBlindMode(mode string) string

NormalizeColorBlindMode returns the canonical color-vision mode name for mode, accepting both "none" and "normal" (and empty string) as "none", and normalizing "high-contrast", "highcontrast", and "high_contrast" to "high-contrast". Known names are lowercased; unknown non-empty names are trimmed and preserved.

func ValidateSlot(slot string) error

ValidateSlot reports whether slot is a name a Store accepts, returning an error wrapping ErrInvalidSlot when it is not. Code that takes slot names from outside the game, such as a cloud listing, checks them with it before handing them to a Backend.

Типы

type AccessibilitySettings struct {
	Captions bool `json:"captions"`
	// CaptionsSet reports whether Captions was chosen explicitly (including false) rather than following a platform caption preference.
	CaptionsSet bool `json:"captions_set,omitempty"`
	// SFXCaptions enables captions for non-speech sound effects (footsteps, explosions, directional cues).
	SFXCaptions bool `json:"sfx_captions,omitempty"`
	// Caption holds player-chosen caption presentation (background, opacity, text color, speaker colors, size) and per-kind toggles (dialogue, chatter, sounds).
	Caption CaptionSettings `json:"caption"`
	// CaptionScale is the subtitle/UI text scale factor in [MinCaptionScale, MaxCaptionScale] (1.0 by default).
	// When CaptionScaleSet is false and CaptionScale is 0 or 1.0, EffectiveCaptionScale follows core.Env.FontScale.
	CaptionScale float64 `json:"caption_scale"`
	// CaptionScaleSet reports whether CaptionScale was chosen explicitly (including 1.0) rather than following core.Env.FontScale.
	CaptionScaleSet bool `json:"caption_scale_set,omitempty"`
	// ColorBlindMode is the canonical color-vision mode ("none", "protanopia", "deuteranopia", "tritanopia", or "high-contrast").
	// "normal" is accepted on load and normalized to "none".
	ColorBlindMode string `json:"color_blind_mode,omitempty"`
	// ColorBlindSeverity scales the color-vision frame filter intensity in [0, 1] (1.0 by default).
	// When ColorBlindSeveritySet is false and ColorBlindSeverity is 0, EffectiveColorBlindSeverity returns 1.0.
	ColorBlindSeverity float64 `json:"color_blind_severity"`
	// ColorBlindSeveritySet reports whether ColorBlindSeverity was set explicitly (including 0.0).
	ColorBlindSeveritySet bool `json:"color_blind_severity_set,omitempty"`
	ReduceMotion          bool `json:"reduce_motion"`
	// ReduceMotionSet reports whether ReduceMotion was chosen explicitly (including false) rather than following core.Env.ReduceMotion.
	ReduceMotionSet bool `json:"reduce_motion_set,omitempty"`
	HighContrast    bool `json:"high_contrast"`
	// HighContrastSet reports whether HighContrast was chosen explicitly (including false) rather than following core.Env.IncreaseContrast.
	HighContrastSet bool `json:"high_contrast_set,omitempty"`
	// ReduceFlashes disables full-screen flash effects independently of ReduceMotion.
	ReduceFlashes bool `json:"reduce_flashes,omitempty"`
	// ScreenShake is the camera shake intensity in [0, 1] (1.0 by default, 0 disables shake).
	ScreenShake float64 `json:"screen_shake"`
	// GameSpeed is the gameplay speed multiplier in [MinGameSpeed, MaxGameSpeed] (1.0 by default).
	GameSpeed float64 `json:"game_speed"`
	// Invincibility disables player damage when supported by the game.
	Invincibility bool `json:"invincibility,omitempty"`
	// AutoAim enables aim assistance when supported by the game.
	AutoAim bool `json:"auto_aim,omitempty"`
	// HoldToToggle turns held inputs into toggles when supported by the game.
	HoldToToggle bool `json:"hold_to_toggle,omitempty"`
}

AccessibilitySettings holds player accessibility and gameplay-assist preferences.

func (a *AccessibilitySettings) ClearCaptionScale()

ClearCaptionScale clears the explicit scale override so EffectiveCaptionScale follows core.Env.FontScale again.

func (a *AccessibilitySettings) ClearCaptions()

ClearCaptions clears the explicit captions override so EffectiveCaptions follows the platform caption preference when supported.

func (a *AccessibilitySettings) ClearColorBlindSeverity()

ClearColorBlindSeverity clears the explicit severity flag and restores the default 1.0.

func (a *AccessibilitySettings) ClearHighContrast()

ClearHighContrast clears the explicit high-contrast override so EffectiveHighContrast follows the platform setting again.

func (a *AccessibilitySettings) ClearReduceMotion()

ClearReduceMotion clears the explicit reduced-motion override so EffectiveReduceMotion follows the platform setting again.

func (a AccessibilitySettings) EffectiveCaptionScale(env *core.Env) float64

EffectiveCaptionScale returns the active text/caption scale factor in [MinCaptionScale, MaxCaptionScale]. When CaptionScaleSet is false and CaptionScale is 0 or 1.0, it adopts env.FontScale (clamped to the valid range) when env is non-nil and reports a positive scale.

func (a AccessibilitySettings) EffectiveCaptions(env *core.Env) bool

EffectiveCaptions reports whether captions are enabled, using the player's explicit choice when Captions or CaptionsSet is true and otherwise checking the platform caption preference when exposed by env (nsgo-dev/nsgo#2677).

func (a AccessibilitySettings) EffectiveColorBlindSeverity() float64

EffectiveColorBlindSeverity returns the color-vision filter strength in [0, 1]. When ColorBlindSeveritySet is false and ColorBlindSeverity is 0, it defaults to 1.0 so structs that set only ColorBlindMode get a full-strength filter.

func (a AccessibilitySettings) EffectiveHighContrast(env *core.Env) bool

EffectiveHighContrast reports whether high contrast is active, using the player's explicit choice when HighContrast or HighContrastSet is true and otherwise falling back to env.IncreaseContrast when env is non-nil.

func (a AccessibilitySettings) EffectiveReduceMotion(env *core.Env) bool

EffectiveReduceMotion reports whether reduced motion is active, using the player's explicit choice when ReduceMotion or ReduceMotionSet is true and otherwise falling back to env.ReduceMotion when env is non-nil.

func (a AccessibilitySettings) EffectiveSoundCaptions() bool

EffectiveSoundCaptions reports whether non-speech sound and music captions are enabled, respecting an explicit Caption.SetSounds call and otherwise honoring either SFXCaptions or Caption.Sounds.

func (a *AccessibilitySettings) SetCaptionScale(v float64)

SetCaptionScale clamps v into [MinCaptionScale, MaxCaptionScale] (defaulting NaN/Inf/0 to 1.0) and marks CaptionScaleSet so it overrides core.Env.FontScale even when set to 1.0.

func (a *AccessibilitySettings) SetCaptions(v bool)

SetCaptions records an explicit captions preference so it overrides any platform caption preference even when v is false.

func (a *AccessibilitySettings) SetColorBlindSeverity(v float64)

SetColorBlindSeverity clamps v into [0, 1] (defaulting NaN to 1.0) and marks ColorBlindSeveritySet so explicit 0.0 is preserved instead of defaulting to 1.0.

func (a *AccessibilitySettings) SetHighContrast(v bool)

SetHighContrast records an explicit high-contrast preference so it overrides the platform setting even when v is false.

func (a *AccessibilitySettings) SetReduceMotion(v bool)

SetReduceMotion records an explicit reduced-motion preference so it overrides the platform setting even when v is false.

func (a *AccessibilitySettings) SetSoundCaptions(v bool)

SetSoundCaptions updates both SFXCaptions and Caption.Sounds together so legacy and structured sound-caption toggles stay synchronized.

func (a *AccessibilitySettings) Validate()

Validate clamps out-of-range numeric fields and normalizes ColorBlindMode and Caption in place.

type AudioSettings struct {
	// Master is the overall volume in [0, 1] (1.0 by default).
	Master float64 `json:"master"`
	// Groups maps audio group names (such as "music", "sfx", "ui") to volumes in [0, 1].
	Groups map[string]float64 `json:"groups,omitempty"`
	// Muted silences all audio without discarding the stored Master level.
	Muted bool `json:"muted"`
	// Mono forces positional voices to play centered at pan 0. Nil (the default) follows the
	// platform's mono audio switch (nsgo-dev/nsgo#2677); a non-nil pointer overrides it explicitly.
	Mono *bool `json:"mono,omitempty"`
	// Balance shifts stereo voice panning in [-1, 1] (-1 full left, 0 centered, +1 full right)
	// when mono audio is off.
	Balance float64 `json:"balance,omitempty"`
}

AudioSettings holds player audio preferences stored independently of save slots.

func (a AudioSettings) ResolveMono(systemMono bool) bool

ResolveMono returns the effective mono setting given the platform's mono audio switch: *a.Mono when explicitly set, and systemMono when a.Mono is nil.

func (a *AudioSettings) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes AudioSettings while preserving defaults for omitted fields and replacing Groups cleanly when "groups" is explicitly present in JSON.

type Backend interface {
	// Read returns the primary payload for slot, or an error wrapping ErrNotFound if absent.
	Read(slot string) ([]byte, error)
	// ReadBackup returns the previous valid payload kept as a backup for slot, or an error wrapping ErrNotFound if absent.
	ReadBackup(slot string) ([]byte, error)
	// Write saves data as the primary payload for slot, preserving any existing valid primary as the backup first.
	Write(slot string, data []byte) error
	// Delete removes both primary and backup payloads for slot, the backup first so an interrupted Delete never leaves a backup that resurrects the slot. Deleting an absent slot returns nil.
	Delete(slot string) error
	// Exists reports whether a primary or backup payload exists for slot.
	Exists(slot string) bool
	// Slots returns the sorted names of all slots that have a primary or backup payload.
	Slots() ([]string, error)
}

Backend stores and retrieves raw save payloads and their backup copies by validated slot name.

A Backend that wraps another, such as one that records each write, can expose it with an Unwrap() Backend method. A SettingsStore built on the wrapper then keeps settings exactly where it would on the wrapped backend, without passing them through the wrapper.

A Backend can provide ReadBackupWithTime(string) ([]byte, time.Time, error) to return the backup's modification time along with its contents for LoadInfo. Backends that quarantine damaged saves can expose their copies to Store with Damaged() ([]string, error) and DiscardDamaged(string) error.

func FileBackend(dir string) Backend

FileBackend returns a Backend that keeps each slot as <slot>.json and its backup as <slot>.json.bak inside dir (such as cx.DataDir()).

Writes stage data into a synced temporary file in dir, preserve any existing valid primary in <slot>.json.bak, atomically rename the temporary file into place and sync the directory, reporting a failed directory sync as a write error. The first Write removes .save-*.tmp files that an interrupted write left more than an hour ago. On the web, where Scope.DataDir is empty, use StorageBackend instead.

func StorageBackend(store core.Storage, prefix string) Backend

StorageBackend returns a Backend that keeps saves in store under keys starting with prefix.

Each slot uses a primary key (<prefix>.slot.<slot>) and a backup key (<prefix>.bak.<slot>), so backup keys never collide with slot names and a failed SetItem (such as *core.StorageFullError) leaves the previous save intact.

type CameraSettings struct {
	FieldOfView float64 `json:"field_of_view"`
	CameraBob   float64 `json:"camera_bob"`
	CameraSway  float64 `json:"camera_sway"`
	MotionBlur  bool    `json:"motion_blur"`
}

CameraSettings holds player preferences used by first- and third-person cameras. FieldOfView is the vertical field of view in degrees, in [MinFieldOfView, MaxFieldOfView] (0 reads as 90). CameraBob and CameraSway are strengths in [0, 1].

func (c *CameraSettings) Validate()

Validate clamps every value to its documented range, replacing NaN and a zero field of view with the defaults.

type CaptionSettings struct {
	// Background is a canonical backdrop color name ("black", "gray", "blue", "white")
	// or a 6-digit hex color ("#rrggbb"). Empty defaults to "black".
	Background string `json:"background,omitempty"`
	// BackgroundOpacity is the backdrop opacity in [0, 1] (0.9 by default; 0 is transparent).
	// Use SetBackgroundOpacity(0) to distinguish an explicit transparent backdrop from a zero-value struct.
	BackgroundOpacity float64 `json:"background_opacity"`
	// BackgroundOpacitySet reports whether BackgroundOpacity was set explicitly (including 0).
	BackgroundOpacitySet bool `json:"background_opacity_set,omitempty"`
	// TextColor is a canonical text color name ("white", "yellow", "cyan", "green", "black")
	// or a 6-digit hex color ("#rrggbb"). Empty defaults to "white".
	TextColor string `json:"text_color,omitempty"`
	// SpeakerColors tints speaker names with distinct per-speaker colors (true by default).
	// Use SetSpeakerColors(false) to distinguish an explicit off choice from a zero-value struct.
	SpeakerColors bool `json:"speaker_colors"`
	// SpeakerColorsSet reports whether SpeakerColors was set explicitly (including false).
	SpeakerColorsSet bool `json:"speaker_colors_set,omitempty"`
	// Dialogue enables main spoken dialogue captions when Captions is enabled (true by default).
	// Use SetDialogue(false) to distinguish an explicit off choice from a zero-value struct.
	Dialogue bool `json:"dialogue"`
	// DialogueSet reports whether Dialogue was set explicitly (including false).
	DialogueSet bool `json:"dialogue_set,omitempty"`
	// Chatter enables ambient / background NPC chatter captions when Captions is enabled.
	Chatter bool `json:"chatter,omitempty"`
	// Sounds enables non-speech sound-effect and music captions (paired with AccessibilitySettings.SFXCaptions).
	Sounds bool `json:"sounds,omitempty"`
	// SoundsSet reports whether Sounds was set explicitly (including false).
	SoundsSet bool `json:"sounds_set,omitempty"`
	// Size selects a caption text size preset ("small", "medium", "large", "xlarge"; default "medium").
	Size string `json:"size,omitempty"`
}

CaptionSettings holds player-customizable presentation and per-kind filtering preferences for live captions.

func DefaultCaptionSettings() CaptionSettings

DefaultCaptionSettings returns a CaptionSettings populated with readable defaults.

func (c CaptionSettings) EffectiveBackgroundOpacity() float64

EffectiveBackgroundOpacity returns the active caption backdrop opacity in [0, 1].

func (c CaptionSettings) EffectiveDialogue() bool

EffectiveDialogue reports whether main spoken dialogue captions are enabled.

func (c CaptionSettings) EffectiveSpeakerColors() bool

EffectiveSpeakerColors reports whether distinct per-speaker colors are enabled.

func (c *CaptionSettings) SetBackgroundOpacity(v float64)

SetBackgroundOpacity clamps v into [0, 1] and marks BackgroundOpacitySet so an explicit 0 (transparent background) is preserved across Validate and JSON saves.

func (c *CaptionSettings) SetDialogue(v bool)

SetDialogue records an explicit main-dialogue caption toggle (including false).

func (c *CaptionSettings) SetSounds(v bool)

SetSounds records an explicit sound-effects/music caption toggle (including false).

func (c *CaptionSettings) SetSpeakerColors(v bool)

SetSpeakerColors records an explicit speaker-color preference (including false).

func (c *CaptionSettings) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes CaptionSettings while preserving defaults for omitted fields and recording explicit false/0 overrides when present in JSON.

func (c *CaptionSettings) Validate()

Validate normalizes preset names and clamps BackgroundOpacity into [0, 1] in place.

type CloseDecision uint8

CloseDecision describes the action for a dirty save state.

Deprecated: Use QuitDecision, which QuitGuard.Decide returns.

const (
	// CloseAllow closes at once: there is no unsaved progress.
	CloseAllow CloseDecision = iota
	// ClosePrompt asks the player before closing: there is unsaved progress and no way to save it now.
	ClosePrompt
	// CloseSave saves before closing: there is unsaved progress and the game can save it now.
	CloseSave
)
type ControlSettings struct {
	MouseSensitivity float64 `json:"mouse_sensitivity"`
	StickSensitivity float64 `json:"stick_sensitivity"`
	TouchSensitivity float64 `json:"touch_sensitivity"`
	GyroSensitivity  float64 `json:"gyro_sensitivity"`
	InvertX          bool    `json:"invert_x"`
	InvertY          bool    `json:"invert_y"`
	StickDeadZone    float64 `json:"stick_dead_zone"`
	TriggerThreshold float64 `json:"trigger_threshold"`
	Vibration        float64 `json:"vibration"`
}

ControlSettings holds player preferences that affect camera look input and controller feedback. Sensitivity values are multipliers in [MinLookSensitivity, MaxLookSensitivity] on the game's declared binding sensitivity, where 1 keeps it (0 reads as 1). StickDeadZone is in [0, MaxStickDeadZone], where 0 turns the dead zone off. TriggerThreshold and Vibration are in [0, 1]; TriggerThreshold is stored for games that read analog triggers themselves.

func (c *ControlSettings) Validate()

Validate clamps every value to its documented range, replacing NaN and zero sensitivities with the defaults.

type DefaultSettingsStore struct {
	*SettingsStore[Settings]
}

DefaultSettingsStore is a convenience SettingsStore for the standard Settings struct with startup Apply support.

func NewDefaultSettingsStore(backend Backend, opts ...SettingsOption) *DefaultSettingsStore

NewDefaultSettingsStore returns a DefaultSettingsStore backed by backend.

func NewFileSettingsStore(dir string, opts ...SettingsOption) *DefaultSettingsStore

NewFileSettingsStore returns a DefaultSettingsStore backed by settings.json (and settings.json.bak) inside dir.

func NewStorageSettingsStore(store core.Storage, prefix string, opts ...SettingsOption) *DefaultSettingsStore

NewStorageSettingsStore returns a DefaultSettingsStore backed by store under <prefix>.settings (outside the slot namespace).

func (s *DefaultSettingsStore) LoadAndApply(targets SettingsTargets) (Settings, error)

LoadAndApply loads settings (returning DefaultSettings when absent) and applies them to targets. If Load fails, targets are not called. If Apply fails, the loaded settings are still returned alongside the error.

type DirtyState struct {
	// Dirty reports progress made since the last save.
	Dirty bool
}

DirtyState tracks unsaved progress and provides a close decision contract.

Deprecated: Use QuitGuard, which also covers forced shutdown: QuitGuard{Unsaved, CanSave, Save}.Decide(false) returns QuitAllow, QuitAsk or QuitSave where Decide(saveAvailable) returns CloseAllow, ClosePrompt or CloseSave.

func (s DirtyState) Decide(saveAvailable bool) CloseDecision

Decide chooses whether closing should be allowed, prompted, or saved.

Deprecated: Use QuitGuard.Decide.

type DisplaySettings struct {
	// Fullscreen puts the window in full screen on the chosen display, as the platform provides it (on macOS, native full screen in its own Space; on the web, the browser's full screen, granted only during a user gesture); false keeps it windowed.
	Fullscreen bool `json:"fullscreen"`
	// DisplayID is the ID, from core.Env.Displays, of the display full screen uses. It names a display the same way across launches and display changes, so a UI that offers displays sets it; when it is empty or the display is not connected, DisplayIndex chooses instead.
	DisplayID string `json:"display_id,omitempty"`
	// DisplayIndex is the position in core.Env.Displays of the display full screen uses when DisplayID is empty or not connected; out of range keeps the window's current display.
	DisplayIndex int    `json:"display_index"`
	ScaleMode    string `json:"scale_mode,omitempty"`
	IntegerScale bool   `json:"integer_scale"`
	// FrameCap is the most frames drawn a second, uncapped when 0.
	FrameCap int `json:"frame_cap"`
	// VSync requests vertical sync. NSGo v0.3.4 does not yet expose swap-interval control, so screen.Video does not apply this field and gameui.SettingsMenu hides the toggle by default.
	VSync bool `json:"vsync"`
	// AutoDropLowPower lowers the frame cap while the system is in low-power mode or under serious thermal pressure, and restores it once the condition clears.
	AutoDropLowPower bool `json:"auto_drop_low_power"`
	// Quality is the player's quality setting as quality.NormalizeSetting writes it: "auto" (the default) lets quality.Selector choose from the device and its frame times, and "low", "medium" or "high" holds that preset.
	Quality string `json:"quality,omitempty"`
}

DisplaySettings holds player display and presentation preferences.

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

Game holds an ordered registry of named saveable parts so a game can save and load all of its subsystems in one call, with per-part schema versions, per-part migrations and all-or-nothing loads.

The zero value of Game is ready to use.

func NewGame() *Game

NewGame returns an empty Game save registry.

func (g *Game) Load(s *Store, slot string) error

Load reads slot from s, validates and migrates every registered part before mutating any of them, and then applies all parts in registration order.

If any part fails validation, migration or loading, none of the registered parts are changed. When a registered part is missing from an older slot, it is initialized from WithPartDefault when configured, reset via Resetter when implemented, or left unchanged otherwise. Unregistered parts present in the slot are ignored.

Because Load runs through Store.LoadChecked, a primary copy that fails decoding or part validation automatically falls back to the slot's backup copy, while a future part version (ErrFutureVersion) or missing part migration (ErrMissingMigration) is returned directly without downgrading to backup.

func (g *Game) PartSnapshots() (map[string]json.RawMessage, error)

PartSnapshots captures every registered part's current state as compacted JSON, keyed by part name. Parts are snapshotted in registration order.

func (g *Game) PartVersion(name string) (int, bool)

PartVersion returns the registered schema version for name and whether name is registered.

func (g *Game) Parts() []string

Parts returns the registered part names in registration order.

func (g *Game) PeekPart(s *Store, slot, name string, dst any) error

PeekPart reads and migrates one named part from slot in s and decodes it into dst without modifying any live part registered on g. It is intended for load-menu summaries and inspection.

When name is not present in the slot, PeekPart returns ErrNotFound.

func (g *Game) Register(name string, version int, p Part, opts ...PartOption)

Register adds p to g under name with schema version version (versions below 1 are treated as 1).

Parts are saved and applied in registration order. Register panics if name is empty, p is nil, or name is already registered.

func (g *Game) RegisterMigration(part string, from int, fn Migration)

RegisterMigration registers fn to upgrade the named part's raw JSON from version from to from+1. It may be called before or after Register for part.

func (g *Game) ResetParts()

ResetParts calls ResetState on every registered part that implements Resetter, in registration order.

func (g *Game) Save(s *Store, slot string) error

Save snapshots every registered part in registration order and writes them atomically to slot in s. If any part fails to snapshot or marshal, s is not touched and any previous save in slot stays intact.

type InputAssistSettings struct {
	// Toggle lists action names that latch on the first accepted press and release on the next.
	Toggle []string `json:"toggle,omitempty"`
	// MashToHold lists action names whose rapid-press mechanics count a single hold as repeated presses.
	MashToHold []string `json:"mash_to_hold,omitempty"`
	// MinPressMs is the minimum hold duration in milliseconds before a press counts (slow keys); 0 disables it.
	MinPressMs int `json:"min_press_ms,omitempty"`
	// AcceptDelayMs is the post-acceptance cooldown in milliseconds during which further presses of the same action are ignored (bounce keys); 0 disables it.
	AcceptDelayMs int `json:"accept_delay_ms,omitempty"`
}

InputAssistSettings holds player-chosen motor accessibility assists persisted alongside Bindings.

func (a InputAssistSettings) AcceptDelay() time.Duration

AcceptDelay returns AcceptDelayMs as a time.Duration (0 when non-positive).

func (a InputAssistSettings) IsZero() bool

IsZero reports whether a enables no input motor assists.

func (a InputAssistSettings) MinPress() time.Duration

MinPress returns MinPressMs as a time.Duration (0 when non-positive).

func (a *InputAssistSettings) SetAcceptDelay(d time.Duration)

SetAcceptDelay stores d in AcceptDelayMs, clamped to [0, MaxAcceptDelayMs].

func (a *InputAssistSettings) SetMinPress(d time.Duration)

SetMinPress stores d in MinPressMs, clamped to [0, MaxMinPressMs].

func (a *InputAssistSettings) Validate()

Validate normalizes action name lists (trimmed, unique, sorted) and clamps millisecond timings in place.

type LoadDiagnostic struct {
	// Slot is the slot the outcome is about.
	Slot string
	// Code is the outcome's stable code: "ok", "not_found", "storage_full", "future_version", "missing_migration", "tampered", "corrupt" or "unknown".
	Code string
	// Message is the error's text for a details view, or "save loaded" for "ok"; it is not meant as the headline shown to the player.
	Message string
	// Recoverable reports whether the player can go on saving: false for a save from a newer version and for a missing migration, which only another build of the game can read.
	Recoverable bool
}

LoadDiagnostic explains a save/load outcome for user-facing template UI.

func DiagnosticError(slot string, err error) LoadDiagnostic

DiagnosticError converts a save error into a stable diagnostic code. An error matching several of the package's errors gets the most specific code: ErrTampered before ErrCorrupt, which it also matches.

type LoadResult struct {
	// FromBackup reports whether LoadInfo used the slot's backup copy.
	FromBackup bool
	// PrimaryErr explains why LoadInfo could not use the primary copy.
	PrimaryErr error
	// BackupTime is the backup copy's modification time, or zero when unavailable.
	BackupTime time.Time
}

LoadResult describes a successfully loaded save.

type Migration func(data json.RawMessage) (json.RawMessage, error)

Migration converts a save's raw JSON data from one schema version to the next (v to v+1).

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

MigrationRegistry is a validated set of adjacent save migrations.

func NewMigrationRegistry(m map[int]Migration) (*MigrationRegistry, error)

NewMigrationRegistry builds a registry from migrations keyed by their source version.

func (r *MigrationRegistry) Apply(data json.RawMessage, from, to int) (json.RawMessage, error)

Apply runs the planned adjacent migrations in ascending version order.

func (r *MigrationRegistry) Plan(from, to int) ([]int, error)

Plan returns the source versions needed to move from from to to.

func (r *MigrationRegistry) Versions() []int

Versions returns registered source versions in ascending order.

type ObjectState struct {
	// Destroyed records that the object was removed (picked up, defeated, broken)
	// and should be omitted when the scene is built or spawned again.
	Destroyed bool `json:"destroyed,omitempty"`
	// X, Y and PosZ override the object's local position when set.
	X    *float32 `json:"x,omitempty"`
	Y    *float32 `json:"y,omitempty"`
	PosZ *float32 `json:"posZ,omitempty"`
	// Rotation overrides the object's 2D clockwise rotation in radians when set.
	Rotation *float32 `json:"rotation,omitempty"`
	// Components holds persisted component field overrides keyed by component name, then field name.
	Components map[string]map[string]any `json:"components,omitempty"`
	// Switches holds per-object boolean flags (self switches, such as "A" or "opened").
	Switches map[string]bool `json:"switches,omitempty"`
	// Vars holds arbitrary JSON-encodable per-object variables.
	Vars map[string]any `json:"vars,omitempty"`
}

ObjectState holds persisted changes for one object inside a scene. Nil pointer fields mean the object kept the transform from its scene file.

type Option func(*Store)

Option configures a Store returned by NewStore, NewStorageStore or NewFileStore.

func WithMigration(from int, fn Migration) Option

WithMigration registers fn to migrate a save's JSON data from version from to from+1.

func WithMigrations(m map[int]Migration) Option

WithMigrations registers each migration in m, keyed by its starting version (from to from+1).

func WithPayloadValidator(validate PayloadValidator) Option

WithPayloadValidator checks new and loaded data with validate. The built-in backends also use it before rotating the primary or preserving a damaged copy, so data refused by the game cannot replace a usable backup.

func WithSeal(opts SealOptions) Option

WithSeal enables tamper-evident envelopes: Save adds a "seal" field to each envelope and Load checks it, as opts describes.

func WithVersion(v int) Option

WithVersion sets the store's current save schema version. Versions below 1 are treated as 1.

type Part interface {
	// SaveState returns a JSON-encodable snapshot of the part's current state.
	SaveState() (any, error)
	// LoadState replaces the part's state from raw JSON previously written by SaveState (after any per-part migrations).
	LoadState(raw json.RawMessage) error
}

Part is one named subsystem of a game that can be saved into and restored from a save slot.

func FuncPart[T any](saveFn func() (T, error), loadFn func(T) error, resetFn ...func()) Part

FuncPart adapts a typed save/load callback pair into a Part. JSON decoding happens before loadFn runs, and Game.Load snapshots and rolls back automatically if a later part fails. When resetFn is provided, the part also implements Resetter.

type PartEntry struct {
	// Version is the part's schema version; values below 1 are treated as 1.
	Version int
	// Data is the JSON-encodable state of the part.
	Data any
}

PartEntry pairs a part schema version with a JSON-encodable value for EncodeParts.

type PartOption func(*partConfig)

PartOption configures a part registered with Game.Register.

func WithPartDefault(v any) PartOption

WithPartDefault sets the JSON-encodable default value applied to a part when loading an older save slot that does not contain that part.

func WithPartMigration(from int, fn Migration) PartOption

WithPartMigration registers fn to upgrade a part's raw JSON from version from to from+1.

func WithPartMigrations(m map[int]Migration) PartOption

WithPartMigrations registers each migration in m for a part, keyed by starting version (from to from+1).

type PayloadValidator func(version int, data json.RawMessage) error

PayloadValidator checks the original JSON data of a supported save version. It must inspect only its arguments and must not modify data. Saves and loads can run validation concurrently and on workers when using the async methods.

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

Persistence tracks per-scene object state across scene reloads, room transitions and save slots, keyed by scene path (such as "scenes/cave.scene.yaml") and object ID.

It implements Part, StagedPart and Resetter so a game can register it directly on a save.Game. The zero value of Persistence is ready to use.

func NewPersistence() *Persistence

NewPersistence returns an empty Persistence store.

func (p *Persistence) Clear()

Clear removes all persisted state across every scene.

func (p *Persistence) ClearObject(scene, id string)

ClearObject removes all persisted state for object id in scene.

func (p *Persistence) ClearScene(scene string)

ClearScene removes all persisted state for scene.

func (p *Persistence) ComponentField(scene, id, component, field string) (any, bool)

ComponentField returns the persisted override for component.field on object id in scene.

func (p *Persistence) IsDestroyed(scene, id string) bool

IsDestroyed reports whether object id in scene has been marked destroyed.

func (p *Persistence) LoadState(raw json.RawMessage) error

LoadState implements Part.

func (p *Persistence) MarkDestroyed(scene, id string)

MarkDestroyed records that object id in scene was destroyed (picked up, defeated, broken).

func (p *Persistence) Object(scene, id string) (ObjectState, bool)

Object returns a deep copy of the persisted state for object id in scene and whether any exists.

func (p *Persistence) Position(scene, id string) (x, y float32, ok bool)

Position returns the persisted 2D position override for object id in scene and whether one is set.

func (p *Persistence) PrepareLoad(raw json.RawMessage) (func(), error)

PrepareLoad implements StagedPart. Integer JSON numbers inside Components and Vars are preserved as Go int values so scene component fields typed as FieldInt round-trip cleanly.

func (p *Persistence) ResetState()

ResetState implements Resetter.

func (p *Persistence) Restore(snap PersistenceSnapshot) error

Restore validates snap and atomically replaces p's state. On error p is unchanged.

func (p *Persistence) SaveState() (any, error)

SaveState implements Part.

func (p *Persistence) Scene(scene string) map[string]ObjectState

Scene returns a deep copy of every persisted object state in scene, or nil when none exist.

func (p *Persistence) Scenes() []string

Scenes returns the sorted scene paths that currently hold persisted state.

func (p *Persistence) SetComponentField(scene, id, component, field string, value any)

SetComponentField records a persisted override for component.field on object id in scene.

func (p *Persistence) SetObject(scene, id string, st ObjectState)

SetObject replaces the persisted state for object id in scene with a deep copy of st. An empty ObjectState clears the entry.

func (p *Persistence) SetPosition(scene, id string, x, y float32)

SetPosition records a persisted 2D position override for object id in scene.

func (p *Persistence) SetPosition3D(scene, id string, x, y, z float32)

SetPosition3D records a persisted 3D position override for object id in scene.

func (p *Persistence) SetRotation(scene, id string, rad float32)

SetRotation records a persisted 2D rotation override (in radians) for object id in scene.

func (p *Persistence) SetSwitch(scene, id, key string, value bool)

SetSwitch sets a per-object boolean self switch on object id in scene. Setting a switch to false removes it so default false values do not bloat the save.

func (p *Persistence) SetVar(scene, id, key string, value any)

SetVar stores a per-object variable under key on object id in scene. Passing nil deletes the variable.

func (p *Persistence) Snapshot() PersistenceSnapshot

Snapshot returns a deep, deterministic copy of p's state.

func (p *Persistence) Switch(scene, id, key string) bool

Switch returns the boolean value of self switch key on object id in scene (false when unset).

func (p *Persistence) Var(scene, id, key string) (any, bool)

Var returns the per-object variable stored under key on object id in scene.

type PersistenceSnapshot struct {
	// Scenes maps cleaned scene paths to object states keyed by object ID.
	Scenes map[string]map[string]ObjectState `json:"scenes,omitempty"`
}

PersistenceSnapshot is the deterministic JSON form of a Persistence store.

type QuitDecision uint8

QuitDecision is what a close or quit request does with unsaved progress.

const (
	// QuitAllow closes at once: there is no unsaved progress, or a forced request has no Save to call.
	QuitAllow QuitDecision = iota
	// QuitAsk asks the player before closing: an ordinary request has unsaved progress the game cannot save now.
	QuitAsk
	// QuitSaveAndAllow saves best effort, then closes: a forced request (the platform is terminating the app and cannot wait for a dialog) has unsaved progress. The caller calls SaveForced and closes whatever it returns.
	QuitSaveAndAllow
	// QuitSave saves before closing: an ordinary request has unsaved progress the game can save now. The caller calls Save and closes when it succeeds; when it fails, the caller asks the player as for QuitAsk, so a failed save never loses progress silently.
	QuitSave
)
type QuitGuard struct {
	// Unsaved reports whether the game has progress a quit would lose; nil means it never does.
	Unsaved func() bool
	// CanSave reports whether an ordinary request may save that progress now without asking the player (false mid-battle, in a cutscene, or for a game that always asks); nil means it never may. It does not affect forced requests.
	CanSave func() bool
	// Save writes that progress for QuitSave and SaveForced; nil means the game cannot save on quit, so Decide never returns QuitSave or QuitSaveAndAllow.
	Save func() error
}

QuitGuard decides what a window close, quit or forced shutdown does with unsaved progress. It keeps platform wiring out of game logic so desktop, mobile and template adapters share the same fail-safe policy and can test it without platform bindings.

func (g QuitGuard) Decide(forced bool) QuitDecision

Decide returns the decision for a close or quit request. forced reports a request the platform will not wait for, such as a system shutdown or the OS terminating a backgrounded app: it never returns QuitAsk for one. In order: no unsaved progress allows; a forced request saves best effort and allows (QuitSaveAndAllow, or QuitAllow without Save); an ordinary request saves first when CanSave and Save allow it (QuitSave) and asks otherwise (QuitAsk).

func (g QuitGuard) SaveForced() error

SaveForced performs the best-effort save for QuitSaveAndAllow and returns Save's error for logging; the caller closes even when it fails. It does nothing without Save.

type Resetter interface {
	ResetState()
}

Resetter is an optional interface a Part may implement to reset its state to its defaults when loading an older save slot that does not contain the part.

type SealOptions struct {
	// Key returns the secret the seal is computed with: a stable per-install secret kept outside the save, such as in the platform keychain. An error or an empty key fails Save, and fails Load's check as a mismatch.
	Key func() ([]byte, error)
	// Bind is mixed into the seal, such as the player's account ID, so a save copied to another account does not match.
	Bind string
	// OnMismatch is what Load does with a copy whose seal does not match; SealRefuse when zero.
	OnMismatch SealPolicy
	// Report, when set, is called with every mismatch Load finds, whatever OnMismatch is.
	Report func(error)
	// AcceptUnsealed loads a copy that has no seal field, as a build from before sealing wrote it, instead of treating it as a mismatch; the next Save seals it. Removing the field is otherwise all an edit needs to pass, so turn it on only for the releases that upgrade unsealed saves.
	AcceptUnsealed bool
}

SealOptions configures an HMAC-SHA256 seal over each envelope's version, data and Bind.

type SealPolicy int

SealPolicy controls what Load does when a configured seal does not match.

const (
	// SealRefuse refuses a copy whose seal does not match with an error matching ErrTampered and ErrCorrupt, so Load falls back to the backup. It is the default.
	SealRefuse SealPolicy = iota
	// SealReport loads a copy whose seal does not match and passes the mismatch to SealOptions.Report.
	SealReport
)
type Settings struct {
	Audio         AudioSettings              `json:"audio"`
	Bindings      map[string][]string        `json:"bindings,omitempty"`
	InputAssists  InputAssistSettings        `json:"input_assists,omitzero"`
	Display       DisplaySettings            `json:"display"`
	Controls      ControlSettings            `json:"controls"`
	Camera        CameraSettings             `json:"camera"`
	Locale        string                     `json:"locale,omitempty"`
	Accessibility AccessibilitySettings      `json:"accessibility"`
	Custom        map[string]json.RawMessage `json:"custom,omitempty"`
}

Settings holds typed, versioned player preferences kept completely separate from save slots.

func DefaultSettings() Settings

DefaultSettings returns a Settings populated with sane defaults.

func (s *Settings) Validate()

Validate clamps out-of-range numeric fields and normalizes empty/whitespace strings in place.

type SettingsOption func(*settingsConfig)

SettingsOption configures a SettingsStore or DefaultSettingsStore.

func WithSettingsMigration(from int, fn Migration) SettingsOption

WithSettingsMigration registers fn to migrate settings JSON data from version from to from+1.

func WithSettingsMigrations(m map[int]Migration) SettingsOption

WithSettingsMigrations registers each migration in m, keyed by its starting version (from to from+1).

func WithSettingsSchema(schema SettingsSchema) SettingsOption

WithSettingsSchema applies schema's Version and Migrations to a settings store.

func WithSettingsVersion(v int) SettingsOption

WithSettingsVersion sets the settings store's current schema version. Versions below 1 are treated as 1.

type SettingsSchema struct {
	// Version is the current settings schema version written by Save and expected by Load; 1 when 0 or negative.
	Version int
	// Migrations maps a version v to the Migration that upgrades settings JSON data from v to v+1.
	Migrations map[int]Migration
}

SettingsSchema describes the version and step-by-step migrations for a SettingsStore.

type SettingsStore[T any] struct {
	// Version is the current settings schema version written by Save and expected by Load; 1 when 0 or negative.
	Version int
	// Migrations maps a version v to the Migration that upgrades settings JSON data from v to v+1.
	Migrations map[int]Migration
	// contains filtered or unexported fields
}

SettingsStore persists a versioned settings value of type T in a dedicated settings file or storage key, completely separate from save slots.

func NewSettingsStore[T any](backend Backend, defaults func() T, opts ...SettingsOption) *SettingsStore[T]

NewSettingsStore returns a SettingsStore for T backed by backend.

defaults supplies the baseline value returned when no settings exist yet, used as the base when unmarshaling partial JSON, and written on Reset. When defaults is nil, DefaultSettings() is used if T is Settings, otherwise the zero value of T.

func (s *SettingsStore[T]) Delete() error

Delete removes the stored settings and its backup copy. Deleting absent settings returns nil.

func (s *SettingsStore[T]) Exists() bool

Exists reports whether a primary or backup settings payload exists.

func (s *SettingsStore[T]) Load() (T, error)

Load reads settings, migrating older versions up to s.Version one step at a time and validating the result.

If no settings have been saved yet, Load returns the store's default value and a nil error. If the primary copy is missing, unreadable or corrupted, Load recovers from the backup copy. Settings from a newer schema version return ErrFutureVersion without falling back to an older backup.

func (s *SettingsStore[T]) RegisterMigration(from int, fn Migration)

RegisterMigration registers fn to upgrade settings JSON data from version from to from+1.

func (s *SettingsStore[T]) Reset() error

Reset restores and saves the store's default settings.

func (s *SettingsStore[T]) Save(value T) error

Save validates value (if T implements Validate()), encodes it into a versioned JSON envelope, and writes it atomically while keeping the previous valid copy as a backup.

func (s *SettingsStore[T]) Subscribe(fn func()) func()

Subscribe registers fn to run whenever Save, Reset, or Delete succeeds on s. Call the returned function to remove the subscription. A nil fn is a no-op.

type SettingsTargets struct {
	// Sound receives master volume, group volumes, mono mode, and left/right balance from Settings.Audio.
	// When Settings.Audio.Muted is true, the mixer's master volume is set to 0.
	Sound *sound.Mixer

	// SetMasterVolume receives the effective master volume (0 when Muted is true) in [0, 1].
	SetMasterVolume func(volume float64)

	// SetGroupVolume receives each audio group name and volume from Settings.Audio.Groups in sorted key order.
	SetGroupVolume func(group string, volume float64)

	// ApplyAudio receives the validated AudioSettings.
	ApplyAudio func(AudioSettings) error

	// ApplyBindings receives a cloned map of action bindings.
	ApplyBindings func(map[string][]string) error

	// ApplyInputAssists receives the validated InputAssistSettings.
	ApplyInputAssists func(InputAssistSettings) error

	// ApplyDisplay receives the validated DisplaySettings.
	ApplyDisplay func(DisplaySettings) error

	// ApplyControls receives validated look and controller feedback preferences.
	ApplyControls func(ControlSettings) error

	// ApplyCamera receives validated camera preferences.
	ApplyCamera func(CameraSettings) error

	// ApplyLocale receives the validated Locale string.
	ApplyLocale func(locale string) error

	// ApplyAccessibility receives the validated AccessibilitySettings.
	ApplyAccessibility func(AccessibilitySettings) error
}

SettingsTargets wires subsystems to receive loaded player settings at startup or when settings change. Every field is optional; nil targets are skipped.

type StagedPart interface {
	Part
	PrepareLoad(raw json.RawMessage) (apply func(), err error)
}

StagedPart is an optional interface a Part may implement so Game.Load can validate and decode raw JSON into staging state without mutating live state. Game.Load calls PrepareLoad on every StagedPart before applying any part; once every part succeeds, it calls each returned apply function in registration order.

func StagedFuncPart[T any](saveFn func() (T, error), prepareFn func(T) (func(), error), resetFn ...func()) StagedPart

StagedFuncPart adapts a typed save/prepare callback pair into a StagedPart. prepareFn validates the decoded T without mutating live state and returns an apply function invoked only after every part in Game.Load has passed validation. When resetFn is provided, the returned part also implements Resetter.

func ValuePart[T any](ptr *T) StagedPart

ValuePart returns a StagedPart (and Resetter) that saves and loads the JSON-encodable value at ptr. Loading unmarshals into a fresh T before writing *ptr, and ResetState zeroes *ptr when an older save slot omits the part.

type Store struct {
	// Version is the current save schema version written by Save and expected by Load; 1 when 0 or negative.
	Version int
	// Migrations maps a version v to the Migration that upgrades a save's JSON data from v to v+1.
	Migrations map[int]Migration
	// contains filtered or unexported fields
}

Store saves and loads versioned JSON game state across named slots backed by a Backend.

func NewFileStore(dir string, opts ...Option) *Store

NewFileStore returns a Store backed by JSON files inside dir (such as cx.DataDir()).

func NewStorageStore(store core.Storage, prefix string, opts ...Option) *Store

NewStorageStore returns a Store backed by store under keys starting with prefix.

func NewStore(backend Backend, opts ...Option) *Store

NewStore returns a Store backed by backend, defaulting to Version 1 before applying opts.

func (s *Store) Damaged() ([]string, error)

Damaged returns the sorted names of slots whose damaged primaries were kept aside during a save. Backends without quarantine support return an empty list.

func (s *Store) Delete(slot string) error

Delete removes slot and its backup copy. Deleting a slot that does not exist returns nil. The backup goes first, so an interrupted Delete leaves either the whole slot or nothing that Load could resurrect.

func (s *Store) DeleteAll() error

DeleteAll removes every save slot and its backup copy. Player settings stored alongside save slots are never touched.

func (s *Store) DiscardDamaged(slot string) error

DiscardDamaged removes the quarantined copy for slot, if any.

func (s *Store) Exists(slot string) bool

Exists reports whether slot has a stored save or backup copy.

func (s *Store) Flush()

Flush waits for all queued asynchronous save and load operations.

func (s *Store) Headers() (map[string]json.RawMessage, error)

Headers returns the header of every slot saved with SaveWithHeader, keyed by slot name, without unmarshaling any slot's data into a Go value. A slot saved with Save, or by a build that predates headers, has no header and is left out; Slots still lists it.

Each header comes from the copy Load would read: the primary, or the backup when the primary is missing or is not a valid envelope. A slot neither of whose copies is a valid envelope is left out too, and Load reports what is wrong with it.

func (s *Store) Load(slot string, dst any) error

Load reads slot, migrates older save versions up to s.Version one step at a time, and unmarshals the data into dst.

If the primary copy is missing, unreadable or corrupted, Load automatically recovers from the slot's backup copy. It rewrites the primary from that backup only when the primary is missing or is not a JSON object at all (empty, truncated or garbage); a primary that failed to read for another reason, or that is a JSON object Load cannot use, is left as it is, because it may be newer than the backup. A save whose version exceeds s.Version returns an error wrapping ErrFutureVersion without falling back to an older backup, even when its envelope has fields this build does not know.

Load never writes a migrated save back: migrations run in memory on every Load until the slot is saved again, so each Migration must be a pure function of its input that gives the same result every time it runs.

An error about a copy's contents is a *loaderr.Error that names the copy, the line in the stored JSON and a fix. FileBackend names it by its file path (<dir>/<slot>.json, or <dir>/<slot>.json.bak for the backup) and StorageBackend by its storage key; another Backend by the slot, with " (backup)" for its backup copy.

func (s *Store) LoadAsync(slot string, dst any, done func(error)) error

LoadAsync loads a slot and calls done when complete. With a StorageBackend, call it on the storage's owning scope: the load and done run before LoadAsync returns. Other backends load on a worker, so read dst from done or after Flush returns.

func (s *Store) LoadChecked(slot string, dst any, check func() error) error

LoadChecked is Load with a check of the decoded value: after a copy decodes into dst, LoadChecked calls check, and a copy check refuses is treated as corrupted, so the backup is tried as it would be for one that does not decode.

Before the backup is decoded, and when LoadChecked returns an error, dst is put back to the value it had when LoadChecked was called, so nothing of a refused copy is left in it.

When check returns a *loaderr.Error whose Field is a path in dst's JSON, the error LoadChecked returns gives that field's line in the stored copy, under "data". A nil check checks nothing.

func (s *Store) LoadInfo(slot string, dst any, check func() error) (LoadResult, error)

LoadInfo loads and checks a save like LoadChecked and reports whether it recovered from the backup.

func (s *Store) RegisterMigration(from int, fn Migration)

RegisterMigration registers fn to upgrade a save's JSON data from version from to from+1.

func (s *Store) Save(slot string, value any) error

Save encodes value into a versioned JSON envelope and writes it to slot.

Marshaling happens before the backend is touched, so an encoding error leaves any previous save in slot untouched.

func (s *Store) SaveAsync(slot string, value any, done func(error)) error

SaveAsync marshals value on the caller's goroutine. With a StorageBackend, call it on the storage's owning scope: the write and done run before SaveAsync returns. Other backends write on a worker in per-slot queue order. If done is set, it receives the write result once, including ErrStorageFull for a full backend.

func (s *Store) SaveWithHeader(slot string, header, value any) error

SaveWithHeader is Save with a header: header, which must encode to a JSON object, is written in the same envelope as value, as {"version": N, "header": {...}, "data": ...}, so the header and the data it describes are replaced together by one write and cannot disagree. Headers lists it without unmarshaling the data. Load ignores the header.

Keep the header small (a chapter, a location, play time, a date): Headers reads every slot's envelope to list them.

func (s *Store) Slots() ([]string, error)

Slots returns the sorted names of all slots stored in the backend.