GitHubLoslegen

Diese Seite ist noch nicht auf Deutsch übersetzt und wird daher auf Englisch angezeigt.

2D-Kern

save

game/save stores game save slots as versioned JSON envelopes in core.Storage or on disk (such as cx.DataDir()), with sequential schema migrations and atomic backup recovery.

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

Choosing a store

Pick a store based on your targets:

  • NewStorageStore(cx.Storage(), prefix, opts...): stores each slot in core.Storage under <prefix>.slot.<slot> and <prefix>.bak.<slot>. Works on every target, including the web.
  • NewFileStore(cx.DataDir(), opts...): stores each slot as <slot>.json and <slot>.json.bak in a directory. Ideal for larger saves on desktop and mobile (on the web, cx.DataDir() is empty, so fall back to NewStorageStore).
  • NewStore(backend, opts...): accepts any custom Backend implementation (such as cloud sync).
type Progress struct {
	Level int    `json:"level"`
	Coins int    `json:"coins"`
	Name  string `json:"name"`
}

store := save.NewStorageStore(cx.Storage(), "mygame", save.WithVersion(1))

if err := store.Save("slot1", Progress{Level: 3, Coins: 120, Name: "Hero"}); err != nil {
	return err
}

var p Progress
if err := store.Load("slot1", &p); errors.Is(err, save.ErrNotFound) {
	p = Progress{Level: 1}
} else if err != nil {
	return err
}

Inspect and manage slots with store.Exists(slot), store.Slots() (sorted slice of slot names), and store.Delete(slot) (removes the backup and then the primary, so an interrupted delete never leaves a backup that Load would resurrect; deleting an absent slot returns nil). save.ValidateSlot(name) checks a slot name from outside the game, such as a cloud listing, against the same rules before it reaches a Backend. A Backend that wraps another, such as liveops.CloudSyncer.Backend(), can expose it with an Unwrap() Backend method; a settings store built on the wrapper then keeps settings exactly where it would on the wrapped backend.

Versioned envelopes and migrations

Every slot is written inside a {"version": N, "data": ...} envelope. When your save schema evolves, bump WithVersion(N) and register one-step Migration functions (v -> v+1) with WithMigration, WithMigrations, or RegisterMigration:

store := save.NewFileStore(cx.DataDir(),
	save.WithVersion(2),
	save.WithMigration(1, func(raw json.RawMessage) (json.RawMessage, error) {
		var v1 struct {
			Level int `json:"level"`
			Gold  int `json:"gold"`
		}
		if err := json.Unmarshal(raw, &v1); err != nil {
			return nil, err
		}
		return json.Marshal(Progress{
			Level: v1.Level,
			Coins: v1.Gold, // renamed field
			Name:  "Adventurer",
		})
	}),
)

When Load reads an older version, it upgrades the JSON one version at a time (1 -> 2 -> 3 ...) before unmarshaling into dst. Load does not write the migrated save back, so migrations run again on every Load until the slot is saved: each one must be a pure function of its input that gives the same result every time.

An envelope with any field besides version, data and the optional header object (see Slot headers), or with a field given twice, is ErrCorrupt. save.EnvelopeVersion(payload) reads a payload's schema version without decoding its body (including envelopes written by a newer build that carry extra fields).

When syncing slots across devices with liveops.CloudSyncer, pass the store's Version as CloudSyncOptions.SaveVersion. Before writing a cloud copy locally, the syncer checks save.EnvelopeVersion; if the cloud copy is newer, it keeps the local slot intact and reports liveops.OutcomeNeedsUpdate with LocalVersion and CloudVersion so the game can ask the player to update instead of writing a future-version envelope that Load would refuse with ErrFutureVersion and risking a fresh save overwriting the cloud copy. See cloudsave.

Sentinel errors to check with errors.Is:

Error Meaning
ErrNotFound No primary or backup save exists for that slot.
ErrInvalidSlot Slot name is empty or unsafe for keys/file paths.
ErrFutureVersion Save was written by a newer schema version than Store.Version.
ErrMissingMigration Store lacks a migration step needed to reach Store.Version.
ErrCorrupt Stored contents are invalid, for example a malformed envelope or data of the wrong JSON type.

Use save.WithPayloadValidator when your game can diagnose damage from the JSON data itself. The validator receives the original schema version and raw data, before migration, and returns an error for invalid contents. A refused primary can fall back to the backup. On built-in backends, the validator also checks the previous copies before saving so a game-invalid primary cannot replace a usable backup. If both copies fail, the next save keeps the damaged primary aside before writing the new copy. Register the same validator when reopening the store. The validator must be safe to call concurrently and must leave its input unchanged.

The Spark Slide template starts with empty stars on ErrNotFound. For any other load failure, it preserves the progress slot for the session and awards new stars in memory. A newer schema prompts the player to update. A failed write offers a retry that saves the stars earned so far.

Slot headers

A load screen shows a chapter, a location or a play time for each slot. SaveWithHeader(slot, header, value) writes a small game-defined header in the same envelope as the data, {"version": N, "header": {...}, "data": ...}, and Headers() returns every slot's header as raw JSON keyed by slot name, without unmarshaling any slot's data into a Go value:

type SlotSummary struct {
	Chapter string `json:"chapter"`
	PlayMin int    `json:"playMin"`
}

if err := store.SaveWithHeader("slot1", SlotSummary{Chapter: "Harbor", PlayMin: 42}, progress); err != nil {
	return err
}

headers, err := store.Headers()
if err != nil {
	return err
}
for slot, raw := range headers {
	var sum SlotSummary
	if json.Unmarshal(raw, &sum) == nil {
		fmt.Println(slot, sum.Chapter, sum.PlayMin)
	}
}

The header must encode to a JSON object. Because the header and the data are one write, they cannot disagree, and the backup copy keeps the previous header with the previous data: when the primary copy is torn, Headers reads the header from the copy Load falls back to. Load ignores the header. A slot written with Save, or by a build that predates headers, has no header and is not in the map (Slots still lists it), and neither is a slot with no valid copy. Headers reads each slot's whole envelope, so keep the header small, and put a thumbnail or other image data elsewhere rather than in the header.

A build older than headers reads an envelope with a header as ErrCorrupt and falls back to the backup, so a game that may be downgraded should not start writing headers in the same schema version.

Atomic writes and backup recovery

Save marshals the payload completely before touching the backend, so marshaling errors leave existing saves untouched. Before replacing a slot's primary copy, both built-in backends preserve the previous valid primary as a backup:

  • FileBackend: writes to a temporary file in the same directory, syncs it to disk, backs up the existing <slot>.json to <slot>.json.bak, atomically renames the temp file into place, and syncs the directory; a failed directory sync is returned as a write error, except on file systems that cannot sync a directory at all (EINVAL or ENOTSUP, as some network and FUSE mounts report), where the sync is skipped. The first write through a backend removes .save-*.tmp files an interrupted write left more than an hour ago.
  • StorageBackend: writes the backup key before updating the primary key, so a *core.StorageFullError leaves the last good save intact.

On Load, if the primary copy is missing, unreadable, or corrupt, Store automatically falls back to the backup copy. It rewrites the primary from the 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, such as a permission or I/O error, or that is a JSON object Load cannot use, is left in place, since it may be newer than the backup. If the primary carries a version newer than Store.Version, even with envelope fields this build does not know, Load returns ErrFutureVersion without silently downgrading to an older backup.

store.LoadInfo(slot, &progress, check) runs the same load and optional check as LoadChecked. On a successful recovery, LoadResult.FromBackup is true and PrimaryErr holds the reason the primary could not be used. BackupTime is the backup file's modification time on disk, or the zero time when the backend has no timestamp.

Before a save replaces a malformed primary envelope whose backup is missing or also malformed, the built-in backends preserve the primary byte for byte. The file backend uses <slot>.json.damaged and the storage backend uses <prefix>.damaged.<escaped slot> (or damaged.<escaped slot> with no prefix). Quarantine checks the envelope structure. A game-specific payload or seal can fail to load even if its envelope is structurally valid.

store.Damaged() lists the sorted slot names with quarantined copies. Each slot keeps its most recent quarantined copy until another damaged primary replaces it or store.DiscardDamaged(slot) removes it. Quarantined copies are separate from Slots, Exists, Delete, and DeleteAll. If preserving the damaged copy fails, the save returns an error and keeps the primary.

Use these messages for player-facing slot errors:

  • If LoadInfo succeeds with FromBackup, show “We restored an earlier save. Some recent progress may be missing.”
  • If a damaged save was kept aside, as confirmed by Damaged after a successful save, show “Your save was damaged. We kept a copy in case it can be recovered.”
  • If saving returns ErrStorageFull, show “Storage is full. Free up some space and try again.”

The roguelike2d template shows which slot recovered from a backup. It protects each unrecoverable slot independently. The first replacement write after backup recovery uses the game's validator to keep the rejected primary from replacing the readable backup.

Load errors and checks

An error about a copy's contents is a *loaderr.Error (see Errors) that names the copy, the line in the stored JSON, the field, such as data.items[1], and a fix. A FileBackend copy is named by its file, such as saves/slot1.json or saves/slot1.json.bak for the backup, and a StorageBackend copy by its storage key; a custom Backend's copy by its slot, slot1 (backup) for the backup. The sentinels above still match it with errors.Is.

LoadChecked is Load with a check of the decoded value. A copy the check refuses is treated as corrupt, so the backup is tried, decoded into the value dst held before the call rather than over what the refused copy left; when every copy fails, dst keeps that value; when the check returns a *loaderr.Error about a field of the value, the error gives that field's line in the stored copy, under data. entities.LoadWorld checks a world snapshot this way:

var snap Progress
err := store.LoadChecked("slot1", &snap, func() error {
	if snap.Level < 1 {
		return loaderr.Errorf("level", "start levels at 1", "level %d is below 1", snap.Level)
	}
	return nil
})

save.DiagnosticError converts load and save outcomes into stable codes for template UI: ok, not_found, storage_full, future_version, missing_migration, tampered, corrupt and unknown. Recoverable is false for future_version and missing_migration, which only another build of the game can read; Message is the raw error for a details view, not a headline.

The cards2d template shows a localized notice when either slot returns ErrFutureVersion. Play can continue for the session. Both slots are protected from writes, and Save details keeps the slot diagnostic and core.App() version and build available to copy.

For a failed write, Retry save retries the current progress for each affected slot. If storage is full, the notice tells the player to free up space first. A finished deal's last playable table remains on disk until its result is saved.

Pulse Lanes keeps the record slot intact when startup cannot read it. New best clears are available for the session. If a write fails, Retry save saves the best clears earned so far. The notice appears on the menu and results, leaving the playfield available for the chart.

Tap2D preserves a newer or unreadable best-score slot for the session. Its startup check treats a negative score as damaged, so the store can try the backup. Failed writes display a retry for the latest in-memory best score.

Player settings (SettingsStore & AccessibilitySettings)

NewDefaultSettingsStore (NewFileSettingsStore / NewStorageSettingsStore) persists Settings (Audio, Bindings, Display, Controls, Camera, Locale, Accessibility, Custom) outside save slots with the same versioned envelope and backup recovery. Call store.Subscribe(fn) to react whenever Save, Reset, or Delete succeeds (used by a11y.NewAssistFromSettings to keep captions, menus, and effects synchronized with gameui.SettingsMenu).

Controls stores per-device look sensitivity (multipliers in [MinLookSensitivity, MaxLookSensitivity], default 1), axis inversion, stick dead zone ([0, MaxStickDeadZone], default 0.15, 0 turns it off), trigger threshold (default 0.5, for games that read analog triggers themselves), and vibration strength ([0, 1], default 1). Camera stores the vertical field of view in degrees ([MinFieldOfView, MaxFieldOfView], default 90), camera bob and sway strength ([0, 1], default 1), and motion blur. Both sections validate on load, a settings file written before they existed loads their defaults, and they are dispatched through SettingsTargets.ApplyControls and SettingsTargets.ApplyCamera.

AccessibilitySettings is the single model for accessibility and gameplay-assist preferences:

  • Ranges & canonical names: CaptionScale clamps to [MinCaptionScale, MaxCaptionScale] (0.5–3.0), GameSpeed to [MinGameSpeed, MaxGameSpeed] (0.25–2.0), and ScreenShake to [0, 1]. NormalizeColorBlindMode accepts both "none" and "normal" (normalizing both to "none"), "protanopia", "deuteranopia", "tritanopia", and "high-contrast" (including "highcontrast" / "high_contrast").
  • Assist fields & migration: holds Captions, SFXCaptions, Caption (CaptionSettings), ReduceFlashes, Invincibility, AutoAim, and HoldToToggle as typed fields; loading an older file with Custom["reduce_flashes"] migrates it into Accessibility.ReduceFlashes automatically.
  • Caption styling & per-kind toggles (CaptionSettings): configures Background (black, gray, blue, white, or #rrggbb), BackgroundOpacity (0–1, default 0.9; use SetBackgroundOpacity(0) for an explicit transparent backdrop), TextColor (white, yellow, cyan, green, black, or #rrggbb), SpeakerColors (default true), Dialogue (default true), Chatter, Sounds (synchronized with SFXCaptions via SetSoundCaptions / EffectiveSoundCaptions), and Size (small, medium, large, xlarge).
  • Follow-platform defaults: EffectiveCaptions(env), EffectiveReduceMotion(env), EffectiveHighContrast(env), and EffectiveCaptionScale(env) fall back to the platform environment while unset; call SetCaptions, SetReduceMotion, SetHighContrast, or SetCaptionScale to record an explicit override (including false or 1.0), and Clear* to follow the platform again.

Whole-game save registry (save.Game)

Instead of maintaining one hand-written struct and a manual snapshot/restore pair for every subsystem, register each saveable subsystem once on a save.Game and save or load the whole game in one call:

saver := save.NewGame()
saver.Register("bag", 1, bag.SavePart())
saver.Register("gear", 1, gear.SavePart())
saver.Register("quests", 1, quests.SavePart())
saver.Register("dialogue", 1, dialogueRunner.SavePart())
saver.Register("persistence", 1, persistence)
saver.Register("player", 1, save.ValuePart(&player))

if err := saver.Save(store, "slot1"); err != nil {
	return err
}
if err := saver.Load(store, "slot1"); err != nil {
	return err
}
  • Slot layout: Game.Save writes {"parts": {"<name>": {"version": N, "data": ...}}} inside the Store envelope, with part keys in deterministic order.
  • Built-in SavePart() adapters: inventory.Container, inventory.Equipment, quest.Log, stats.Sheet, ability.Caster, flow.Machine[S], dialogue.Runner, and entities.World each expose SavePart() save.Part. save.Persistence implements save.Part, save.StagedPart, and save.Resetter directly.
  • Custom parts: wrap a pointer with save.ValuePart(&state), a save/load pair with save.FuncPart(saveFn, loadFn, resetFn...), or a two-phase validate-then-apply pair with save.StagedFuncPart(saveFn, prepareFn, resetFn...).
  • All-or-nothing loads: Game.Load runs through Store.LoadChecked, validates and migrates every part before mutating live state, and applies all parts in registration order. Every built-in adapter implements save.StagedPart (PrepareLoad), so a failure never touches any subsystem; plain save.Part implementations are snapshotted before commit and rolled back on failure. If the primary copy fails part validation, Store.LoadChecked automatically tries the backup copy.
  • Per-part versions, migrations, and newly added parts: bump an individual part's version and pass save.WithPartMigration(from, fn) (or saver.RegisterMigration(name, from, fn)). When an older slot omits a part added in a newer build, Game.Load initializes it from save.WithPartDefault(v) if given, calls ResetState() if the part implements save.Resetter (as all built-in adapters do), or leaves it untouched. A part with a newer version than registered returns ErrFutureVersion, and a missing step returns ErrMissingMigration, both without downgrading to an older backup.
  • Migrating legacy flat slots & load-menu summaries: use save.EncodeParts inside a Store-level save.Migration to upgrade a legacy flat struct into a Game parts slot, and saver.PeekPart(store, slot, "player", &summary) to read one part (with migrations applied) without mutating the running game.

Persistent per-scene object state (save.Persistence)

save.Persistence tracks per-scene object state keyed by cleaned scene path and object ID—destroyed objects (MarkDestroyed / IsDestroyed), moved 2D/3D positions and rotations (SetPosition / SetPosition3D / SetRotation), component field overrides (SetComponentField / ComponentField), per-object boolean self switches (SetSwitch / Switch), and per-object variables (SetVar / Var).

Register it on save.Game alongside your other parts, and connect it to sceneformat when entering and leaving scenes:

// On entering a scene:
spawned, err := sceneformat.SpawnEntitiesWith(doc, world, sceneformat.SpawnOptions{
	Components:  reg,
	Persistence: persistence,
	ScenePath:   "scenes/cave.scene.yaml",
})

// Before leaving the scene:
sceneformat.CapturePersistence(doc, world, spawned, persistence, "scenes/cave.scene.yaml")

Pass CapturePersistence the scene as parsed from its file: it compares each object against the file's position and rotation, records the ones that differ, and clears an earlier override once an object is back where the file places it.

sceneformat.ApplyPersistence and sceneformat.BuildWithPersistence apply the same overrides to a cloned SceneDoc (omitting destroyed objects and pruning connections that reference them) without mutating the original parsed scene document. Integer values inside Components and Vars round-trip through JSON as Go int so sceneformat.FieldInt validation continues to pass after reload.

Round-trip testing (pkg/save/savetest)

Use savetest.RoundTrip in tests to catch forgotten fields or broken restore paths early:

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

func TestSaveRoundTrip(t *testing.T) {
	g := newTestGame(t)
	// ... play the game so every subsystem moves away from defaults ...
	savetest.RoundTrip(t, g.saver, func() *save.Game {
		return newTestGame(t).saver
	})
}

Passing a fresh factory saves g to a temporary store, loads it into the fresh *save.Game, verifies both register the same parts and versions, and compares every part's JSON before and after the load. Calling savetest.RoundTrip(t, g) without a factory resets any save.Resetter parts on g before reloading back into g.

Tamper-evident slots

Pass save.WithSeal(save.SealOptions{Key: key, Bind: accountID}) when creating a store to add a seal field to each envelope: hmac-sha256: over the version, the data and Bind, while the rest of the JSON stays readable and diffable. The header is not sealed. Keep the key in a platform keychain or secret store, not beside the JSON file. Bind makes a save copied between accounts fail verification. A mismatch, including a copy without a seal, returns ErrTampered (which also matches ErrCorrupt) and follows the normal backup recovery path. Set OnMismatch: save.SealReport and Report when a game wants to load a mismatched copy for support telemetry.

When an update turns sealing on for saves written without it, set AcceptUnsealed: true so those saves still load; the next Save seals them. Turn it off again once players have saved with sealing, because while it is on, deleting the seal field is all an edit needs to load.

The seal makes casual editing and copying detectable; it is not a defense against someone who reads the key out of the device or the game. Keep anything bought with money on a server.

Storage full

Use errors.Is(err, save.ErrStorageFull) to show one “free space and try again” message across storage backends: Save and SettingsStore.Save wrap a *core.StorageFullError from StorageBackend and a full disk (ENOSPC, or ERROR_DISK_FULL on Windows) from FileBackend in it.

Unsaved progress on close

QuitGuard decides what a window close, quit or forced shutdown does with unsaved progress, so desktop, mobile and template adapters share one policy. Set Unsaved to report progress a quit would lose, Save to write it, and CanSave to report whether an ordinary request may save it now without asking (leave it nil for a game that always asks, such as one where quitting may mean discarding a run). Decide(forced) returns:

  • QuitAllow when there is no unsaved progress, or for a forced request without Save: close at once.
  • QuitSave for an ordinary request when Save is set and CanSave reports true: call Save and close; if it fails, ask the player as for QuitAsk.
  • QuitAsk for an ordinary request otherwise: ask the player to save, discard or cancel.
  • QuitSaveAndAllow for a forced request (the platform is terminating the app and cannot wait for a dialog) with Save set: call SaveForced for a best-effort save, then close even when it fails.

DirtyState and its CloseDecision are deprecated: QuitGuard{Unsaved: ..., CanSave: ..., Save: ...}.Decide(false) returns QuitAllow, QuitAsk and QuitSave where DirtyState.Decide(saveAvailable) returned CloseAllow, ClosePrompt and CloseSave.

Migration registries

MigrationRegistry validates adjacent schema steps, plans a complete version range, and applies migrations in order while checking each result as valid JSON. Register content or save-shape migrations explicitly and keep the strict missing-step refusal.

Asynchronous saves and slot headers

SaveWithHeader stores a small JSON object beside the data and Headers reads those envelopes without decoding the game value, so a load screen can list metadata before loading a slot.

SaveAsync marshals the value on the caller's goroutine. With NewFileStore, a worker handles the queued saves and loads in order for each slot and invokes the completion callbacks. Call Flush while backgrounding or shutting down to wait for those operations.

Call SaveAsync and LoadAsync for NewStorageStore on the scope that owns its core.Storage. Both methods perform the storage operation and invoke the callback before returning. This also applies to StorageBackend passed to NewStore, including wrappers that expose it through Unwrap() Backend.

Diese Seite bearbeiten