devstate

package
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package devstate saves and restores the running game scene, fixed-step loop clock, and serialized state across Go rebuilds during development.

In release builds (-tags release), the package compiles to zero-cost no-op stubs so production binaries link none of the reflection, serialization, or file I/O logic.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ComputeSchemaHash

func ComputeSchemaHash(sample any) string

ComputeSchemaHash reflects the deterministic structural schema of sample (field names, tags, and types recursively) and returns its SHA-256 hex digest.

Top-level pointer indirection is unwrapped so ComputeSchemaHash(T{}) and ComputeSchemaHash(&T{}) yield the exact same hash. Any added, removed, renamed, reordered, or retyped field changes the digest.

Types

type Hook

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

Hook binds a Snapshotter to a core.Scope so state is saved automatically on exit, scope disposal, or an optional periodic interval.

func Attach

func Attach(cx *core.Scope, store *Store, target Snapshotter, opts HookOptions) *Hook

Attach wires target into cx so that session snapshots are saved automatically when cx exits or is disposed, and periodically when opts.SaveInterval > 0.

func (*Hook) RestoreInto

func (h *Hook) RestoreInto(state any) (RestoreResult, error)

RestoreInto loads a saved snapshot into state (a non-nil pointer) and, when successfully restored, forwards it to the attached Snapshotter's Restore method.

func (*Hook) SaveNow

func (h *Hook) SaveNow() error

SaveNow captures a snapshot from the attached Snapshotter and persists it immediately.

func (*Hook) Stop

func (h *Hook) Stop()

Stop halts periodic checkpointing and prevents automatic save on scope cleanup.

type HookOptions

type HookOptions struct {
	// SceneID returns the identifier of the currently active scene.
	// If nil, "default" is recorded.
	SceneID func() string
	// LoopTick returns the current fixed-step simulation tick count.
	LoopTick func() uint64
	// LoopElapsed returns the total elapsed simulation time.
	LoopElapsed func() time.Duration
	// SaveInterval periodically checkpoints state while running when > 0.
	SaveInterval time.Duration
	// Logf receives diagnostic messages such as schema mismatch notifications.
	// When nil, the store's logger is used.
	Logf func(format string, args ...any)
}

HookOptions configures how Attach captures scene metadata and checkpoints state.

type RestoreResult

type RestoreResult struct {
	Restored    bool
	SceneID     string
	LoopTick    uint64
	LoopElapsed time.Duration
	SkipReason  string
}

RestoreResult describes the outcome of Store.Restore.

When a saved snapshot cannot be applied because its state struct schema changed across a rebuild, Restored is false, SkipReason explains why, and Restore returns a nil error so the game starts fresh cleanly.

type SessionSnapshot

type SessionSnapshot struct {
	SceneID     string        `json:"scene_id"`
	SchemaHash  string        `json:"schema_hash"`
	LoopTick    uint64        `json:"loop_tick"`
	LoopElapsed time.Duration `json:"loop_elapsed"`
	Payload     []byte        `json:"payload"`
	SavedAt     time.Time     `json:"saved_at"`
}

SessionSnapshot is the persisted state of a running development session.

type Snapshotter

type Snapshotter interface {
	Snapshot() (any, error)
	Restore(state any) error
}

Snapshotter is implemented by scenes or game controllers that participate in automatic dev-session capture and restore via Hook.

type Store

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

Store persists and restores SessionSnapshots either on disk or in core.Storage.

Example

A Store keeps the running scene's state across a rebuild during development; Restore brings it back only when the state's shape has not changed since it was saved.

//go:build !release

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/tooling/devstate"
	"github.com/nsgo-dev/nsgo/core"
)

type levelState struct {
	PlayerX, PlayerY float32
	Coins            int
}

// A Store keeps the running scene's state across a rebuild during development; Restore brings it back only when the state's shape has not changed since it was saved.
func main() {
	root := core.NewRoot(core.RootOptions{})
	defer root.Dispose()

	store := devstate.NewStorageStore(root.Storage(), "devstate")
	store.SetLogger(func(string, ...any) {})
	if err := store.Save("level-2", 900, 15*time.Second, levelState{PlayerX: 120, PlayerY: 48, Coins: 7}); err != nil {
		fmt.Println(err)
		return
	}

	// After the rebuild:
	var st levelState
	res, err := store.Restore(&st)
	fmt.Println(err, res.Restored, res.SceneID, res.LoopTick, res.LoopElapsed, st)

	// A changed state type is skipped rather than half restored.
	var other struct{ Lives int }
	res, _ = store.Restore(&other)
	fmt.Println(res.Restored, res.SkipReason != "")
}
Output:
<nil> true level-2 900 15s {120 48 7}
false true

func NewStorageStore

func NewStorageStore(st core.Storage, key string) *Store

NewStorageStore creates a core.Storage-backed dev session store under key.

func NewStore

func NewStore(path string) *Store

NewStore creates a file-backed dev session store at path.

func (*Store) Clear

func (s *Store) Clear() error

Clear removes any persisted session snapshot.

func (*Store) LoadSnapshot

func (s *Store) LoadSnapshot() (snap SessionSnapshot, ok bool, err error)

LoadSnapshot reads the stored SessionSnapshot without decoding its payload. If no snapshot exists, ok is false and err is nil. A snapshot that does not decode returns a *loaderr.Error that names the snapshot's file (or storage key) and line.

func (*Store) Restore

func (s *Store) Restore(state any) (RestoreResult, error)

Restore loads the saved session snapshot into state (which must be a non-nil pointer).

If no snapshot exists, or if the saved schema hash does not match state's current schema, Restore logs a diagnostic notice and returns Restored: false with a clear SkipReason and a nil error so the app starts fresh without crashing.

func (*Store) Save

func (s *Store) Save(sceneID string, loopTick uint64, elapsed time.Duration, state any) error

Save marshals state together with its schema hash and loop clock, writing the snapshot atomically.

func (*Store) SetLogger

func (s *Store) SetLogger(logf func(format string, args ...any))

SetLogger sets the logger used for non-fatal restore notices such as schema mismatches. Passing nil restores the default log.Printf behavior.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL