Documentation
¶
Overview ¶
Package assets is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package assets loads a game's atlases, sounds, images and custom data asynchronously without blocking display frames, organizes them into named per-scene groups with reactive progress, releases them when a scene ends, and provides a loading screen component.
Asset files are read and parsed off the engine goroutine and delivered back through core.Scope.Post so animations and game loops keep ticking while assets load. Manager and Group methods are called on the engine's goroutine, as core and audio services are.
Keeping decoded atlas images pinned outside NSGo's 64-source canvas cache waits on nsgo-dev/nsgo#1127; today, image assets are warmed through core.Scope's image loader and dropped for GC when their group is released.
Index ¶
- Constants
- Variables
- func EstimateAtlasBytes(a *sprite.Atlas, rawJSONBytes int64) int64
- func GroupResource[T resource.Resource](g *Group, name string) (T, bool)
- func LoadingView(cx *core.Scope, props LoadingScreenProps) core.Node
- func NewOverlayFS(files map[string][]byte) (fs.FS, error)
- func ReadOverlayFile(overlay fs.FS, name string, fallback []byte) ([]byte, bool)
- func ReportWebOverlay(app string, applied []string, loadErr error)
- func WebOverlay(app string) fs.FS
- type AssetStats
- type CustomLoader
- type Group
- func (g *Group) AddAtlas(name, jsonURI string, img core.ImageSource) *Group
- func (g *Group) AddBytes(name, uri string) *Group
- func (g *Group) AddCustom(name, uri string, parse func([]byte) (any, error), release func(any)) *Group
- func (g *Group) AddCustomLoader(name, uri string, load CustomLoader, release func(any)) *Group
- func (g *Group) AddCustomSized(name, uri string, parse func([]byte) (any, int64, error), release func(any)) *Group
- func (g *Group) AddImage(name string, src core.ImageSource) *Group
- func (g *Group) AddResource(name, path string, lib *resource.Library) *Group
- func (g *Group) AddScene(name, path string, scenes sceneformat.SceneResolver) *Group
- func (g *Group) AddSound(name string, src audio.Source) *Group
- func (g *Group) AddStepped(name, uri string, load SteppedLoader, release func(any)) *Group
- func (g *Group) Atlas(name string) (*sprite.Atlas, bool)
- func (g *Group) ByteProgress() (loaded, total int64)
- func (g *Group) Bytes(name string) ([]byte, bool)
- func (g *Group) BytesLoaded() int64
- func (g *Group) BytesTotal() int64
- func (g *Group) Done() bool
- func (g *Group) Err() error
- func (g *Group) Evictable() bool
- func (g *Group) FS() fs.FS
- func (g *Group) Get(name string) (any, bool)
- func (g *Group) Image(name string) (core.ImageSource, bool)
- func (g *Group) Load(onDone func(error))
- func (g *Group) LoadDuration() time.Duration
- func (g *Group) Loaded() int
- func (g *Group) Loading() bool
- func (g *Group) MountFS(fsys fs.FS) *Group
- func (g *Group) Name() string
- func (g *Group) Progress() float64
- func (g *Group) Release()
- func (g *Group) Reset()
- func (g *Group) Scene(name string) (*sceneformat.BuiltScene, bool)
- func (g *Group) SetEvictable(evictable bool) *Group
- func (g *Group) SetFS(fsys fs.FS) *Group
- func (g *Group) Sound(name string) (*audio.Sound, bool)
- func (g *Group) Stats() GroupStats
- func (g *Group) Total() int
- type GroupStats
- type Handle
- type LoadingScreen
- type LoadingScreenProps
- type LoadingText
- type LocaleCatalog
- type Manager
- func (m *Manager) AcquireAtlas(jsonURI string, img core.ImageSource, done func(*sprite.Atlas, error)) *Handle[*sprite.Atlas]
- func (m *Manager) AcquireBytes(uri string, done func([]byte, error)) *Handle[[]byte]
- func (m *Manager) AcquireSound(src audio.Source, done func(*audio.Sound, error)) *Handle[*audio.Sound]
- func (m *Manager) Atlas(name string) (*sprite.Atlas, bool)
- func (m *Manager) Budget() (total, perGroup int64)
- func (m *Manager) Bytes(name string) ([]byte, bool)
- func (m *Manager) Context() context.Context
- func (m *Manager) Disposed() bool
- func (m *Manager) Get(name string) (any, bool)
- func (m *Manager) Group(name string) *Group
- func (m *Manager) GroupNames() []string
- func (m *Manager) GroupStats() []GroupStats
- func (m *Manager) Image(name string) (core.ImageSource, bool)
- func (m *Manager) LoadAtlas(jsonURI string, img core.ImageSource, done func(*sprite.Atlas, error))
- func (m *Manager) LoadBytes(uri string, done func([]byte, error))
- func (m *Manager) LoadCustom(uri string, load CustomLoader, closeFn func(any), done func(any, error))
- func (m *Manager) LoadGroup(name string, onDone func(error))
- func (m *Manager) LoadSound(src audio.Source, done func(*audio.Sound, error))
- func (m *Manager) LookupGroup(name string) (*Group, bool)
- func (m *Manager) MemoryPressure() int
- func (m *Manager) Over() bool
- func (m *Manager) Post(fn func(), onDisposed func())
- func (m *Manager) Prefetch(group string)
- func (m *Manager) ReleaseAll()
- func (m *Manager) ReleaseGroup(name string)
- func (m *Manager) Reload(uri string, data []byte) ([]string, error)
- func (m *Manager) ReloadAsset(ctx context.Context, groupName, key string) ([]ReloadedAsset, error)
- func (m *Manager) ReloadGroup(ctx context.Context, groupName string) ([]ReloadedAsset, error)
- func (m *Manager) RemoteLoader() RemoteLoader
- func (m *Manager) Revision() int
- func (m *Manager) Scene(name string) (*sceneformat.BuiltScene, bool)
- func (m *Manager) SetAtlasScale(scale float32)
- func (m *Manager) SetBudget(total, perGroup int64)
- func (m *Manager) Sound(name string) (*audio.Sound, bool)
- func (m *Manager) SubpackageForGroup(group string) (string, bool)
- type MemoryBudgetError
- type MemoryTracker
- type Option
- func WithAtlasScale(fn func() float32) Option
- func WithFS(fsys fs.FS) Option
- func WithLocaleCatalog(catalog LocaleCatalog) Option
- func WithLocaleResolver(fn func(name string) (string, bool)) Option
- func WithMemoryTracker(tracker MemoryTracker) Option
- func WithOnBudget(fn func(group string, err error)) Option
- func WithOverlay(fsys fs.FS) Option
- func WithReadAsset(fn func(ctx context.Context, uri string) ([]byte, error)) Option
- func WithRemoteLoader(loader RemoteLoader) Option
- func WithRetry(retries int, backoff time.Duration) Option
- func WithSizes(sizes map[string]int64) Option
- func WithStepBudget(budget time.Duration) Option
- func WithSubpackages(opts SubpackageOptions) Option
- type ReloadedAsset
- type RemoteLoader
- type SteppedLoader
- type Stepper
- type SubpackageHost
- type SubpackageOptions
- type SubpackageProgress
Examples ¶
Constants ¶
const ( // DefaultLoadingShowDelay is how long the default loading view waits before // appearing, so fast loads complete without flashing a loading screen. DefaultLoadingShowDelay = 300 * time.Millisecond // DefaultLoadingMinDisplay is the minimum time the default loading view // stays visible once shown before invoking OnReady. DefaultLoadingMinDisplay = 300 * time.Millisecond // DefaultLoadingStallAfter is how long without progress before the default // loading view displays the "Still loading…" message. DefaultLoadingStallAfter = 5 * time.Second )
const ( // SkippedSound marks a sound: sounds decode asynchronously on the platform, so they are not replaced in place. SkippedSound = "sounds are not reloaded in place" // SkippedNoFile marks an image with no file behind it, such as one registered with in-memory pixels, or, in ReloadGroup, one whose URI the group's reader cannot find. SkippedNoFile = "no file to reload from" // SkippedDensity marks an image file at a density the screen does not show, so replacing it would change nothing on screen. SkippedDensity = "file is at a density the screen does not show" )
Reasons ReloadAsset and ReloadGroup give in ReloadedAsset.Skipped.
const ( // DefaultItemRetries is the default number of additional attempts for a // network-backed asset item that fails with a transient error during a // group load. DefaultItemRetries = 2 // DefaultItemRetryBackoff is the initial wait before the first per-item // retry; each subsequent attempt doubles the wait. DefaultItemRetryBackoff = 200 * time.Millisecond )
const ( StateUnloaded = "unloaded" StateLoading = "loading" StateLoaded = "loaded" StateFailed = "failed" )
Group lifecycle state names reported by GroupStats.State.
const DefaultStepBudget = 4 * time.Millisecond
DefaultStepBudget is the per-step time budget Group.AddStepped gives each incremental loader before yielding back to the event loop.
const DefaultSubpackageProgressWeight = 0.5
DefaultSubpackageProgressWeight is the default fraction of a group's loading progress reserved for downloading its platform subpackage before individual assets inside the group begin loading.
Variables ¶
var ErrManagerDisposed = errors.New("assets: manager disposed")
ErrManagerDisposed is the error a Handle reports when it was acquired from a Manager whose scope had already been disposed.
Functions ¶
func EstimateAtlasBytes ¶
EstimateAtlasBytes estimates the memory an atlas holds: rawJSONBytes (or a per-frame estimate when it is 0) plus the image bytes, which come from the image's pixels, data or size, or from the packed frame extents at 4 bytes per pixel when the image has only a URI. game/mcp uses it for atlases registered outside a Manager.
func GroupResource ¶
GroupResource returns the loaded resource named name from g as T, reporting false when the group is nil, the asset is not loaded, or it holds another resource type.
func LoadingView ¶
func LoadingView(cx *core.Scope, props LoadingScreenProps) core.Node
LoadingView mounts a loading screen for props.Group on cx. It starts loading the named group on mount, displays reactive progress (0%..100% with a progress bar, or props.Render when set), and invokes props.OnReady or props.OnError once loading finishes while cx is still mounted.
In the default view, the UI waits ShowDelay before appearing so fast loads do not flash, stays visible at least MinDisplay once shown, displays Text.StillLoading after StallAfter without progress, and on failure shows a localized player message with Retry and Details buttons. Retry calls Group.Load again while keeping items that already loaded.
OnReady fires at most once per mount; OnError fires on each failed attempt so Retry can recover and still invoke OnReady once the group succeeds.
func NewOverlayFS ¶
NewOverlayFS builds an immutable in-memory fs.FS from relative file paths and contents, suitable for passing to WithOverlay or ReadOverlayFile. Paths must be valid relative fs.FS paths (no leading slash, no "..", no backslashes or NUL bytes) and respect the overlay file-count and size limits.
func ReadOverlayFile ¶
ReadOverlayFile reads name from overlay when overlay is non-nil and holds that file, returning (data, true). Otherwise it returns (fallback, false).
func ReportWebOverlay ¶
ReportWebOverlay notifies a same-origin host page of the overlay files that app applied and any structured load error (such as a *loaderr.Error) raised while parsing them. On non-web targets it is a no-op.
func WebOverlay ¶
WebOverlay returns an in-memory fs.FS containing edited files provided by a same-origin host page (such as the website playground) before the web build starts. On non-web targets, or when no valid overlay was provided for app, it returns nil.
Types ¶
type AssetStats ¶
type AssetStats struct {
Name string
Kind string // "atlas", "sound", "image", "bytes", "custom"
URI string
ImageURI string // atlas image URI when Kind == "atlas"
Loaded bool
Bytes int64
Frames int // atlas frame count when loaded and Kind == "atlas"
}
AssetStats describes one registered asset inside a Group and its estimated in-memory size.
type CustomLoader ¶
CustomLoader parses raw asset bytes off the engine goroutine into a domain value such as a tilemap, bitmap font or JSON table.
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group is a named collection of assets loaded and released together, typically one per scene. Its progress and status methods are backed by core.Signal so NSGo views and effects update automatically as assets load or are released.
Example ¶
A Group loads a scene's assets together off the engine goroutine and reports progress as they arrive. Here a channel stands in for the host's Post, so the example runs each posted callback itself.
package main
import (
"fmt"
"strings"
"testing/fstest"
"github.com/nsgo-dev/game/pkg/assets"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
posted := make(chan func(), 16)
root := core.NewRoot(core.RootOptions{Post: func(fn func()) { posted <- fn }})
defer root.Dispose()
files := fstest.MapFS{
"levels/1.txt": {Data: []byte("wall wall door")},
"credits.txt": {Data: []byte("Made with NSGo")},
}
m := assets.NewManager(root, assets.WithFS(files))
g := m.Group("level-1").
AddBytes("credits", "asset:credits.txt").
AddCustom("layout", "asset:levels/1.txt", func(b []byte) (any, error) { return strings.Fields(string(b)), nil }, nil)
done := false
g.Load(func(err error) {
done = true
fmt.Println("loaded:", err)
})
for !done {
(<-posted)()
}
credits, _ := g.Bytes("credits")
layout, _ := g.Get("layout")
fmt.Printf("%d/%d %.0f%%\n", g.Loaded(), g.Total(), g.Progress()*100)
fmt.Println(string(credits), layout)
m.ReleaseGroup("level-1")
_, ok := g.Get("layout")
fmt.Println("after release:", ok)
}
Output: loaded: <nil> 2/2 100% Made with NSGo [wall wall door] after release: false
func (*Group) AddAtlas ¶
func (g *Group) AddAtlas(name, jsonURI string, img core.ImageSource) *Group
AddAtlas adds a sprite atlas whose JSON is read from jsonURI and parsed with sprite.LoadAtlas for img. When img names a URI without inline Data or Pixels, Load also prefetches img via core.Scope.PrefetchImage (in nsgotest, register the URI in App.ImageSizes).
func (*Group) AddCustom ¶
func (g *Group) AddCustom(name, uri string, parse func([]byte) (any, error), release func(any)) *Group
AddCustom adds an arbitrary asset read from uri and parsed off the engine goroutine by parse, such as a tilemap, bitmap font or JSON table. When release is non-nil, it is invoked when the group is released or when a late load is discarded after release or scope disposal.
func (*Group) AddCustomLoader ¶
func (g *Group) AddCustomLoader(name, uri string, load CustomLoader, release func(any)) *Group
AddCustomLoader is like AddCustom, passing the load's cancellable context to load so long parses can stop promptly on Release or scope disposal.
func (*Group) AddCustomSized ¶
func (g *Group) AddCustomSized(name, uri string, parse func([]byte) (any, int64, error), release func(any)) *Group
AddCustomSized is like AddCustom, but parse also returns the decoded value's memory size in bytes for a Manager configured with WithMemoryTracker. A negative size is tracked as 0.
func (*Group) AddImage ¶
func (g *Group) AddImage(name string, src core.ImageSource) *Group
AddImage adds an image source. When src names a URI without inline Data or Pixels, Load prefetches it via core.Scope.PrefetchImage (in nsgotest, register the URI in App.ImageSizes).
Keeping decoded images pinned outside NSGo's 64-source canvas cache waits on nsgo-dev/nsgo#1127.
func (*Group) AddResource ¶
AddResource registers a YAML resource file (built-in or plugin-registered via resource.RegisterKind) to be read and parsed off the engine goroutine as part of the group.
When lib is non-nil, Load stores the parsed value in lib on the engine goroutine (or reuses the value already cached there) and retains it; Group.Release releases it so lib drops the path once no group retains it and no direct Library.Load holds it. When lib is nil, the parsed resource is kept on the group alone until Release.
func (*Group) AddScene ¶
func (g *Group) AddScene(name, path string, scenes sceneformat.SceneResolver) *Group
AddScene registers a YAML scene file to be parsed, resolved, and built as part of the group.
During Load, the scene file and any scenes it instances or inherits are read and resolved off the engine goroutine, every resource the scene depends on (atlases, images, tilemaps, tilesets, materials, particles, models, sounds, and skeletal rigs) is added to the group so progress counts it and loaded off the engine goroutine, and sceneformat.Build runs on the engine goroutine once all dependencies are ready without reading any file synchronously.
scenes may be nil to read scene files through the group's file system or Manager.ReadAsset; when non-nil it resolves instanced and inherited scenes (and, if it also implements sceneformat.FileResolver, AssetResolver, MaterialResolver, or LDtkOptionsResolver, supplies fallback lookups for them).
func (*Group) AddStepped ¶
func (g *Group) AddStepped(name, uri string, load SteppedLoader, release func(any)) *Group
AddStepped adds an asset read from uri whose parsing or transcoding runs incrementally across frames through load's Stepper, yielding back to the event loop between time-budgeted steps so single-threaded targets such as js/wasm keep painting loading UI. The loaded value is retrieved with Group.Get (or Manager.Get) and released with release when the group is released.
func (*Group) ByteProgress ¶
ByteProgress returns the currently loaded bytes and registered bytes for a group. The total is an estimate from loaded assets and is zero until at least one asset is loaded.
func (*Group) BytesLoaded ¶
BytesLoaded returns how many known asset bytes in the group have loaded so far. Read in a reactive computation, it subscribes to updates.
func (*Group) BytesTotal ¶
BytesTotal returns the total expected byte size of sized assets in the group (from WithSizes or a RemoteLoader such as remote.Manifest), or 0 when no expected sizes are known. Read in a reactive computation, it subscribes to updates.
func (*Group) Done ¶
Done reports whether every asset in the group finished loading without error. Read in a reactive computation, it subscribes to updates.
func (*Group) Err ¶
Err returns the error that stopped the group's last load, or nil. Read in a reactive computation, it subscribes to updates.
func (*Group) Get ¶
Get returns any loaded asset named name (custom, scene, atlas, sound, image or raw bytes), if present in the group.
func (*Group) Image ¶
func (g *Group) Image(name string) (core.ImageSource, bool)
Image returns the loaded image source named name, if present in the group.
func (*Group) Load ¶
Load starts loading every unloaded asset in the group asynchronously and invokes onDone on the engine goroutine once finished.
Load is idempotent: if the group is already loaded, onDone(nil) runs immediately; if it is currently loading, onDone is queued onto the active load. If a previous load failed, Load keeps items that already loaded and retries only the missing ones. An empty group completes immediately with progress 1.
func (*Group) LoadDuration ¶
LoadDuration returns how long the group's most recent completed load took, or 0 while the group is unloaded, loading, or failed.
func (*Group) Loaded ¶
Loaded returns how many assets in the group have finished loading. Read in a reactive computation, it subscribes to updates.
func (*Group) Loading ¶
Loading reports whether the group is currently loading. Read in a reactive computation, it subscribes to updates.
func (*Group) MountFS ¶
MountFS mounts fsys on this group like SetFS and takes ownership of closing it (when fsys implements io.Closer) on Reset, SetFS with a different file system, a later MountFS, or Manager disposal. pkg/assets/remote's DLCManager.FetchGroup uses MountFS so a mounted pack stays open across Release/Load cycles and is released once replaced or disposed.
func (*Group) Progress ¶
Progress returns loading progress in [0, 1], weighted by expected byte sizes when available (from WithSizes or a RemoteLoader such as remote.Manifest) and falling back to item counts for items without a known size. Read in a reactive computation, it subscribes to progress updates.
func (*Group) Release ¶
func (g *Group) Release()
Release closes every loaded *audio.Sound in the group (ignoring already-closed sounds), invokes custom release hooks, drops all atlas, image and byte references for GC, cancels any in-flight load, and resets progress to 0 so the group can be loaded again later. It keeps the group's specs and mounted file system, so a DLC pack stays mounted for the next Load.
Keeping decoded atlas images pinned outside NSGo's 64-source canvas cache waits on nsgo-dev/nsgo#1127.
func (*Group) Reset ¶
func (g *Group) Reset()
Reset drops the group's asset specs and loaded resources, cancels any in-flight load, and leaves the group idle so a new asset set (such as a freshly mounted DLC pack) can be registered into it. It also unmounts the group's file system, releasing a pack DLCManager.FetchGroup mounted. Concurrent mounts of the same group must be serialized by the caller.
func (*Group) Scene ¶
func (g *Group) Scene(name string) (*sceneformat.BuiltScene, bool)
Scene returns the built scene named name, if present in the group.
func (*Group) SetEvictable ¶
SetEvictable marks the group as eligible for MemoryPressure eviction.
func (*Group) SetFS ¶
SetFS mounts fsys as the primary file system for this group's file-backed assets, such as a downloaded DLC zip archive. When set, asset URIs in this group are read from fsys first and fall back to the Manager's asset reader if a file is not present in fsys.
Replacing a file system mounted via MountFS (such as a DLC pack) closes that previous file system, as Reset does; setting the same file system again keeps it.
func (*Group) Stats ¶
func (g *Group) Stats() GroupStats
Stats returns a read-only snapshot of g's load state, registered assets, and estimated memory usage in bytes. Calling Stats does not subscribe the caller to reactive signals.
type GroupStats ¶
type GroupStats struct {
Name string
State string // StateUnloaded, StateLoading, StateLoaded, or StateFailed
Loaded int
Total int
Bytes int64
LoadDuration time.Duration
Error string
Assets []AssetStats
}
GroupStats describes a Group's current load state, load duration, assets and estimated memory footprint.
type Handle ¶
type Handle[T any] struct { // contains filtered or unexported fields }
Handle is one reference to an asset in a Manager's cache. Every Acquire call for the same asset shares a single load and a single loaded value, and the value is closed (a sound's Close, a custom asset's release) once the last handle holding it is released or the Manager's scope is disposed.
Done and Err are backed by core.Signal, so reading them in a reactive computation subscribes to the load finishing. Handle methods run on the engine goroutine, as Manager's do.
func AcquireCustom ¶
func AcquireCustom[T any](m *Manager, uri string, load func(ctx context.Context, data []byte) (T, error), release func(T), done func(T, error)) *Handle[T]
AcquireCustom returns a handle to the value load parses uri into, loading it as Manager.LoadCustom does unless m already holds it. Custom assets are shared by their resolved URI and T: every Acquire of the same file into the same type gets the value the first one parsed, whichever load it passed. release, when non-nil, runs on the value once the last handle is released, the Manager's scope is disposed, or a load finishes after every handle was released. done, when non-nil, runs on the engine goroutine after AcquireCustom returns, once the value is ready or failed, unless the handle is released first.
func (*Handle[T]) Done ¶
Done reports whether the asset loaded without error and the handle still holds it. Read in a reactive computation, it subscribes to updates.
func (*Handle[T]) Err ¶
Err returns the error that stopped the asset's load, ErrManagerDisposed for a handle acquired from a disposed Manager, or nil. Read in a reactive computation, it subscribes to updates.
type LoadingScreen ¶
type LoadingScreen struct {
Manager *Manager
Group string
Title string
Text LoadingText
ShowDelay time.Duration
MinDisplay time.Duration
StallAfter time.Duration
OnReady func()
OnError func(error)
// View replaces the default loading view when non-nil, re-rendering
// reactively as progress or error changes.
View func(progress float64, err error) core.Node
Style core.Style
TestID string
}
LoadingScreen is a core.Node component that starts loading a named asset group on mount, shows reactive loading progress, and calls OnReady or OnError once loading finishes. Set View to replace the default progress UI.
type LoadingScreenProps ¶
type LoadingScreenProps struct {
// Manager holds the asset group to load.
Manager *Manager
// Group is the name of the asset group to load on mount.
Group string
// Title is shown above the progress bar in the default view; overrides
// Text.Title when non-empty.
Title string
// Text localizes every user-visible string in the default view. Empty fields
// inherit from DefaultLoadingText.
Text LoadingText
// ShowDelay delays showing the default view so fast loads do not flash.
// Zero uses DefaultLoadingShowDelay; a negative value shows immediately.
ShowDelay time.Duration
// MinDisplay keeps the default view on screen at least this long once shown
// before calling OnReady. Zero uses DefaultLoadingMinDisplay; a negative
// value disables the minimum display time.
MinDisplay time.Duration
// StallAfter is how long without progress before the default view shows
// Text.StillLoading. Zero uses DefaultLoadingStallAfter; a negative value
// disables the stall message.
StallAfter time.Duration
// OnReady runs on the engine goroutine once the group finishes loading
// without error.
OnReady func()
// OnError runs on the engine goroutine if loading the group fails.
OnError func(error)
// Render replaces the default loading view when non-nil. It re-renders
// reactively as the group's progress or error changes.
Render func(progress float64, err error) core.Node
// Style merges onto the default outer container view.
Style core.Style
// TestID sets the default outer container's TestID.
TestID string
}
LoadingScreenProps configures LoadingScreen and LoadingView.
type LoadingText ¶
type LoadingText struct {
// Title is shown above the progress bar or error message (default "Loading").
// LoadingScreenProps.Title overrides Title when set.
Title string
// StillLoading is shown below the progress indicator when loading makes no
// progress past StallAfter (default "Still loading…").
StillLoading string
// ErrorOffline is shown when loading fails due to a network or offline error.
ErrorOffline string
// ErrorNotFound is shown when a required asset file cannot be found.
ErrorNotFound string
// ErrorOther is shown for any other load error.
ErrorOther string
// Retry is the label of the retry button shown on failure (default "Retry").
Retry string
// Details is the label of the button that reveals technical error details
// (default "Details").
Details string
// HideDetails is the label of the details button while details are open
// (default "Hide details").
HideDetails string
}
LoadingText holds every user-visible string shown by the default LoadingScreen / LoadingView so games can localize it. Any empty field inherits its English default from DefaultLoadingText.
func DefaultLoadingText ¶
func DefaultLoadingText() LoadingText
DefaultLoadingText returns the default English copy used by LoadingScreen and LoadingView when LoadingText fields are empty.
type LocaleCatalog ¶
type LocaleCatalog interface {
ResolvePath(name string) (string, bool)
OnReload(fn func(groups []string, locale string)) (stop func())
}
LocaleCatalog resolves logical asset names to concrete paths for the active locale and notifies listeners when a locale switch affects one or more asset groups. *l10n.AssetCatalog implements LocaleCatalog directly.
type Manager ¶
type Manager struct {
// ReadAsset reads raw bytes for uri off the engine goroutine. When nil,
// Manager falls back to WithFS or the app's resources via core.Scope.ReadAsset.
ReadAsset func(ctx context.Context, uri string) ([]byte, error)
// contains filtered or unexported fields
}
Manager loads game assets asynchronously under a scope, groups them by scene with reactive progress, and releases them when a group or the scope ends.
ReadAsset may be replaced before loading starts; when nil, Manager reads "asset:" URIs from the FS given to WithFS, or from the app's resources through core.Scope.ReadAsset (the same resources/ files images and sounds resolve on every target, fetched on demand on the web).
func NewManager ¶
NewManager returns an asset manager owned by cx. When cx is disposed, any in-flight loads are cancelled, late completions release their resources instead of calling callbacks, and every loaded group is released.
func (*Manager) AcquireAtlas ¶
func (m *Manager) AcquireAtlas(jsonURI string, img core.ImageSource, done func(*sprite.Atlas, error)) *Handle[*sprite.Atlas]
AcquireAtlas returns a handle to the atlas jsonURI describes over img, loading it as LoadAtlas does unless the Manager already holds it. Atlases are shared by their resolved JSON and image URIs and the atlas scale in effect; an image with inline Data, Pixels or Offscreen content is never shared. done, when non-nil, runs on the engine goroutine after AcquireAtlas returns, once the atlas is ready or failed, unless the handle is released first.
func (*Manager) AcquireBytes ¶
AcquireBytes returns a handle to the bytes uri reads to, loading them as LoadBytes does unless the Manager already holds them. Every holder shares one slice, which must not be modified. done, when non-nil, runs on the engine goroutine after AcquireBytes returns, once the bytes are read or failed, unless the handle is released first.
func (*Manager) AcquireSound ¶
func (m *Manager) AcquireSound(src audio.Source, done func(*audio.Sound, error)) *Handle[*audio.Sound]
AcquireSound returns a handle to the sound src decodes to, loading it as LoadSound does unless the Manager already holds it. Sounds are shared by their resolved URI; a source with inline Data is never shared. The sound is closed once the last handle is released, so holders must not Close it themselves. done, when non-nil, runs on the engine goroutine after AcquireSound returns, once the sound is ready or failed, unless the handle is released first.
func (*Manager) Atlas ¶
Atlas returns the loaded atlas named name from the most recently registered group that holds it.
func (*Manager) Bytes ¶
Bytes returns the loaded raw bytes named name from the most recently registered group that holds it.
func (*Manager) Context ¶
Context returns a context that is cancelled when the Manager's scope is disposed.
func (*Manager) Get ¶
Get returns the loaded asset named name (custom, scene, atlas, sound, image or raw bytes) from the most recently registered group that holds it.
func (*Manager) Group ¶
Group returns the named asset group, creating it under the manager's scope if it does not yet exist.
func (*Manager) GroupNames ¶
GroupNames returns the names of all registered groups in registration order.
func (*Manager) GroupStats ¶
func (m *Manager) GroupStats() []GroupStats
GroupStats returns a read-only stats snapshot for every registered group in registration order. Reading GroupStats does not subscribe the caller to reactive signals.
func (*Manager) Image ¶
func (m *Manager) Image(name string) (core.ImageSource, bool)
Image returns the loaded image source named name from the most recently registered group that holds it.
func (*Manager) LoadAtlas ¶
LoadAtlas reads jsonURI and parses it with sprite.LoadAtlas off the engine goroutine, and prefetches img through core.Scope.PrefetchImage when img names a URI without inline Data or Pixels (in nsgotest, register the URI in App.ImageSizes). It calls done on the engine goroutine once ready.
func (*Manager) LoadBytes ¶
LoadBytes reads uri off the engine goroutine and calls done on the engine goroutine with its bytes or error. Nothing runs if the manager's scope is disposed before completion.
func (*Manager) LoadCustom ¶
func (m *Manager) LoadCustom(uri string, load CustomLoader, closeFn func(any), done func(any, error))
LoadCustom reads uri and parses it with load off the engine goroutine, then calls done on the engine goroutine. If the manager's scope is disposed before done runs (or done is nil), closeFn is called on the loaded value so nothing leaks.
func (*Manager) LoadGroup ¶
LoadGroup starts loading the named group asynchronously and calls onDone on the engine goroutine when loading finishes. Calling LoadGroup on a group that is already loaded calls onDone(nil) immediately; calling it while the group is loading attaches onDone to the in-flight load. An empty group completes immediately with progress 1.
func (*Manager) LoadSound ¶
LoadSound loads src through audio.LoadSound under the manager's scope and calls done on the engine goroutine. If the scope is disposed before loading completes, any loaded sound is closed and done is not called.
func (*Manager) LookupGroup ¶
LookupGroup returns the existing group named name without creating one when absent.
func (*Manager) MemoryPressure ¶
MemoryPressure releases loaded groups marked evictable until the manager is within its configured budget. It returns the number of groups released.
func (*Manager) Post ¶
func (m *Manager) Post(fn func(), onDisposed func())
Post schedules fn to run on the engine goroutine under the Manager's scope. If the Manager is already disposed, or is disposed before fn runs, onDisposed (when non-nil) is invoked instead so callers can release resources without leaking.
func (*Manager) Prefetch ¶
Prefetch asks the configured SubpackageHost to pre-download the subpackage containing group in the background (for example wx.preDownloadSubpackage). It returns immediately without blocking the engine goroutine and is a no-op when group is in the main package, when the subpackage is already loaded or being pre-downloaded, or on targets without a SubpackageHost.
func (*Manager) ReleaseAll ¶
func (m *Manager) ReleaseAll()
ReleaseAll releases every group registered on the manager.
func (*Manager) ReleaseGroup ¶
ReleaseGroup releases every loaded asset in the named group: closes every loaded *audio.Sound, invokes custom release hooks, drops atlas, image and byte references for GC, cancels any in-flight load for the group, and resets progress to 0 so the group can be loaded again later.
Keeping decoded atlas images pinned outside NSGo's 64-source canvas cache waits on nsgo-dev/nsgo#1127.
func (*Manager) Reload ¶
Reload replaces the loaded assets that were read from uri with data, the file's new contents, and returns the names of the assets it replaced, in the order of their groups and of the assets in each; hot reload (tooling/hotreload's Watcher.WatchAssets) calls it when a file changes on disk. It runs on the engine goroutine, as the Manager's other methods do.
An atlas whose JSON is uri is parsed again with sprite.LoadAtlas, and one whose image is uri draws data from then on, its frames unchanged; either way the *sprite.Atlas the group holds is updated in place, so code that kept the pointer sees the edit. An image whose source is uri shows data, and raw bytes read from uri become data. For an image, an atlas's too, that ships in several densities (core.ImageSource.Scales), uri is the file the screen's pixel ratio picks, such as "asset:hero@2x.png" on a 2x screen, and the image keeps that file's name and so its density; saving a density the screen does not show changes nothing. Sounds and custom assets are not replaced. Assets a group has not loaded are skipped, as are an atlas's JSON and raw bytes that a group reads from the file system SetFS mounted on it, such as a DLC pack overriding the base file at uri, and an atlas whose new JSON does not parse keeps its previous frames and adds its error to the one returned.
When it replaces anything, Reload increments Revision, so a core.Canvas or core.Effect that reads Revision draws or runs again.
func (*Manager) ReloadAsset ¶
ReloadAsset reloads the loaded assets that match key by asset name, URI or relative path, reading fresh bytes through each group's reader (the group's FS, Manager.ReadAsset, or the Manager's FS). When groupName is non-empty, only that group is searched. It returns an empty slice and a nil error when no loaded asset matches key, and an error when groupName names no group.
The reads, atlas parses and custom loaders run off the engine goroutine, as they do in Group.Load, while ReloadAsset waits for them, so a reader or loader must not wait on the engine goroutine. When ctx is done first, ReloadAsset returns ctx's error and changes nothing. The results are applied on the engine goroutine: an atlas is updated in place (*cur = *next), so the *sprite.Atlas pointers the game holds stay valid, and a failed read or parse leaves the previous asset in place and is reported both in the item's Err and in the joined error. Sounds, images with no file behind them and files at a density the screen does not show are reported in Skipped and left unchanged. Revision goes up by one when at least one asset was replaced.
Call ReloadAsset on the engine goroutine.
func (*Manager) ReloadGroup ¶
ReloadGroup reloads every loaded asset in the named group in place, as ReloadAsset does for one key. Images whose file the group's reader cannot find are reported as skipped rather than failed, so a group that mixes files with generated textures reloads cleanly.
Call ReloadGroup on the engine goroutine.
func (*Manager) RemoteLoader ¶
func (m *Manager) RemoteLoader() RemoteLoader
RemoteLoader returns the RemoteLoader attached to m, or nil if none is configured.
func (*Manager) Revision ¶
Revision counts the Reload, ReloadAsset and ReloadGroup calls that replaced at least one asset; each such call adds one. Reading it inside a core.Canvas Draw callback or a core.Effect subscribes to later reloads.
func (*Manager) Scene ¶
func (m *Manager) Scene(name string) (*sceneformat.BuiltScene, bool)
Scene returns the loaded built scene named name from the most recently registered group that holds it.
func (*Manager) SetAtlasScale ¶
SetAtlasScale sets a fixed atlas scale in (0, 1] for future atlas loads, overriding any callback configured with WithAtlasScale. Values <= 0, >= 1, or non-finite load the full atlas. Changing the scale takes effect on the next group load; already-loaded atlases are not hot-swapped.
func (*Manager) SetBudget ¶
SetBudget sets the total and per-group decoded asset memory budgets in bytes. A non-positive value disables the corresponding limit. Groups that would exceed either limit fail their load with *MemoryBudgetError.
type MemoryBudgetError ¶
type MemoryBudgetError struct {
Group string
GroupBytes int64
TotalBytes int64
GroupBudget int64
TotalBudget int64
}
MemoryBudgetError reports a group load rejected because decoded asset memory would exceed the manager's total or per-group budget.
func (*MemoryBudgetError) Error ¶
func (e *MemoryBudgetError) Error() string
Error describes the group, the memory it would use and the budget it exceeds.
type MemoryTracker ¶
type MemoryTracker interface {
TrackAsset(group, name, kind string, bytes int64)
ReleaseGroup(group string)
CheckBudget(group string) error
CheckAllBudgets() error
TotalBudget() int64
TotalBytes() int64
}
MemoryTracker receives decoded asset memory accounting and budget checks from a Manager. *gamedebug.MemoryTracker implements MemoryTracker directly.
type Option ¶
type Option func(*Manager)
Option configures a Manager created by NewManager.
func WithAtlasScale ¶
WithAtlasScale configures Manager to consult fn when loading atlases and resolve reduced-scale variants (such as "actors@0.5x.json" and "actors@0.5x.png") whenever fn returns a scale in (0, 1). If the variant is not present (fs.ErrNotExist, core.ErrAssetNotFound, or HTTP 404), Manager falls back to the full atlas. A nil fn, or values <= 0, >= 1, or non-finite load the full atlas. Changing the scale returned by fn takes effect on the next group load; already-loaded atlases are not hot-swapped.
func WithFS ¶
WithFS sets the file system that the default ReadAsset reads "asset:" URIs from, such as an embed.FS or os.DirFS, overriding the app's resources.
func WithLocaleCatalog ¶
func WithLocaleCatalog(catalog LocaleCatalog) Option
WithLocaleCatalog connects Manager to a localized asset catalog (such as *l10n.AssetCatalog). Every group or one-off load resolves logical asset names through catalog.ResolvePath for the active locale (preserving an "asset:" prefix when the logical URI carries one), and whenever catalog notifies OnReload for a locale switch, Manager reloads ONLY the affected groups that are currently loaded or loading. The subscription is removed automatically when the manager's scope is disposed.
func WithLocaleResolver ¶
WithLocaleResolver configures Manager to resolve logical asset names through fn before loading. Unlike WithLocaleCatalog, it does not subscribe to automatic group reloads on locale changes.
func WithMemoryTracker ¶
func WithMemoryTracker(tracker MemoryTracker) Option
WithMemoryTracker reports each successfully loaded group asset's decoded size to tracker (such as a *gamedebug.MemoryTracker). Tracking and budget callbacks are compiled out in release builds.
func WithOnBudget ¶
WithOnBudget sets the callback invoked when a load or reload crosses a group's budget or the total budget. The group argument is empty for the total budget. Loading continues, and a callback fires again only after usage returns within its budget and crosses it again. It is compiled out in release builds.
func WithOverlay ¶
WithOverlay layers fsys ahead of the manager's base asset source (remote, ReadAsset, WithFS, or core.Scope.ReadAsset). When a requested asset is not present in fsys, Manager falls through to the base source.
func WithReadAsset ¶
WithReadAsset sets how Manager reads raw bytes for asset URIs off the engine goroutine.
func WithRemoteLoader ¶
func WithRemoteLoader(loader RemoteLoader) Option
WithRemoteLoader attaches a RemoteLoader to a Manager. Most games should import github.com/nsgo-dev/game/pkg/assets/remote and pass remote.With(remote.Options{...}) instead.
func WithRetry ¶
WithRetry configures per-item retries with exponential backoff for transient network errors during group loads. Passing retries <= 0 disables per-item retries; backoff <= 0 uses DefaultItemRetryBackoff. When WithRetry is not passed, Manager uses DefaultItemRetries and DefaultItemRetryBackoff.
func WithSizes ¶
WithSizes provides expected byte sizes keyed by asset URI (such as the Sizes map written by `game assets` / `pkg/tooling/manifest`). Group.Progress weights sized items by their expected byte size and falls back to item counts for items without a size, and Group.BytesLoaded / Group.BytesTotal expose byte counts reactively for custom loading views.
func WithStepBudget ¶
WithStepBudget sets the per-step time budget passed to Stepper.Step for assets registered with Group.AddStepped. Passing budget <= 0 passes 0 to Step (one work chunk per step). When WithStepBudget is not passed, Manager uses DefaultStepBudget.
func WithSubpackages ¶
func WithSubpackages(opts SubpackageOptions) Option
WithSubpackages configures Manager to load named subpackages through opts.Host before loading any asset group assigned to them, folding subpackage download progress into Group.Progress, and to forward Manager.Prefetch to opts.Host.PreDownloadSubpackage.
When opts.Host is nil, the mapping collapses to the main package so one project serves web, native, and mini-program presets unchanged.
type ReloadedAsset ¶
type ReloadedAsset struct {
Group string
Name string
Kind string
URI string
Bytes int64
Frames int
Skipped string
Err error
}
ReloadedAsset describes one loaded asset that ReloadAsset or ReloadGroup matched. Err holds a read or parse failure, after which the previous asset stays in place. Skipped says why an asset was left unchanged without an error.
type RemoteLoader ¶
type RemoteLoader interface {
// InitErr returns any configuration error detected when constructing the
// loader (such as an invalid manifest or base URL), or nil.
InitErr() error
// Has reports whether uri is managed by this remote loader.
Has(uri string) bool
// Entry returns the expected byte size and pin key (such as a SHA-256
// digest) for uri, if uri is managed by this remote loader.
Entry(uri string) (size int64, pinKey string, ok bool)
// ResolveImageURI picks the remote URI and pin key for img at display
// pixel ratio, checking density-selected variants when img.Scales is set.
ResolveImageURI(img core.ImageSource, ratio float32) (uri string, pinKey string, ok bool)
// Fetch retrieves verified bytes for uri. When onProgress is non-nil, it
// receives monotonically increasing downloaded byte counts during transfer.
Fetch(ctx context.Context, uri string, onProgress func(loaded int64)) ([]byte, error)
// RetriesConfigured reports whether the loader already performs its own
// per-URI retries so Group does not double-retry transient failures.
RetriesConfigured() bool
// Pin increments the eviction-protection pin count for pinKey.
Pin(pinKey string)
// Unpin decrements the eviction-protection pin count for pinKey.
Unpin(pinKey string)
// Flush persists any buffered cache metadata when the Manager is disposed.
Flush()
}
RemoteLoader resolves, fetches, pins, and caches remote asset URIs for a Manager. Most games attach one via pkg/assets/remote's With option rather than implementing RemoteLoader directly.
type SteppedLoader ¶
SteppedLoader constructs an incremental Stepper from the raw bytes read for an asset URI. It is called on the engine goroutine so loaders that create GPU resources (such as render3d.StartLoadKTX2) can run safely without extra synchronization.
type Stepper ¶
Stepper advances an incremental asset parse or transcode for up to budget per step so single-threaded targets such as js/wasm keep painting while loading (for example, ktx2.Transcoder or render3d.KTX2Loader). Step returns true once the work has finished or failed, after which Result returns the loaded value and any error.
A Stepper may optionally also implement Progress() float64 (returning a fraction in [0, 1]) to update Group.Progress smoothly while stepping, and Close() error to release partial state if loading is cancelled.
type SubpackageHost ¶
type SubpackageHost interface {
// LoadSubpackage downloads and activates the named subpackage, calling
// onProgress as bytes arrive and returning nil once its assets can be read.
// It must respect ctx cancellation.
LoadSubpackage(ctx context.Context, name string, onProgress func(SubpackageProgress)) error
// PreDownloadSubpackage warms the named subpackage in the background
// without blocking gameplay (for example wx.preDownloadSubpackage).
PreDownloadSubpackage(ctx context.Context, name string) error
}
SubpackageHost loads and pre-downloads platform subpackages (such as WeChat wx.loadSubpackage and wx.preDownloadSubpackage) off the engine goroutine.
Implementations may invoke onProgress from any goroutine; Manager marshals progress updates back onto its core.Scope. When no SubpackageHost is configured (the default on desktop, mobile, and web targets), subpackage mappings collapse to the main package so the same game code runs everywhere.
type SubpackageOptions ¶
type SubpackageOptions struct {
// Host loads and pre-downloads named subpackages. When nil (on targets
// without subpackages), all subpackage mappings collapse to the main
// package: LoadGroup loads assets directly and Prefetch is a no-op.
Host SubpackageHost
// Subpackages maps each subpackage name to the asset groups it ships,
// matching game.yaml's export.presets[].delivery.subpackages.
Subpackages map[string][]string
// ProgressWeight is the share of a group's progress bar in (0, 1)
// reserved for loading its subpackage before its individual assets load.
// When <= 0 or >= 1, DefaultSubpackageProgressWeight (0.5) is used.
ProgressWeight float64
}
SubpackageOptions configures mapping named asset groups to platform subpackages loaded through Host.
type SubpackageProgress ¶
type SubpackageProgress struct {
// Progress is a fraction in [0, 1], used when TotalBytes <= 0.
Progress float64
// LoadedBytes is the number of bytes downloaded so far when reported by
// the host.
LoadedBytes int64
// TotalBytes is the total byte size of the subpackage when known.
TotalBytes int64
}
SubpackageProgress reports incremental download progress for a platform subpackage load (such as WeChat's wx.loadSubpackage onProgressUpdate).
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package remote is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
|
Package remote is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/. |