GitHubCommencer

La référence API provient des commentaires de documentation Go du code source et est rédigée en anglais.

package assets

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

Vue d’ensemble

Package assets is experimental: its API and documented formats may change in a minor release. See the API stability policy. 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

Constantes

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 (
	StateUnloaded = "unloaded"
	StateLoading  = "loading"
	StateLoaded   = "loaded"
	StateFailed   = "failed"
)

Group lifecycle state names reported by GroupStats.State.

const DefaultDLCChunkSize = 32 * 1024

DefaultDLCChunkSize is the default streaming read buffer size (32 KiB) used by DLCManager when DLCOptions.ChunkSize is zero or negative.

const DefaultRemoteCacheQuota int64 = 200 << 20

DefaultRemoteCacheQuota is the default byte budget (200 MiB) for DirRemoteCache and MemoryRemoteCache, matching the local file system cap of mini-game runtimes such as WeChat.

const DefaultRemoteRetryBackoff = 100 * time.Millisecond

DefaultRemoteRetryBackoff is the initial wait before the first retry when RemoteOptions.Retries > 0 and RemoteOptions.RetryBackoff <= 0.

const RemoteManifestFile = "remote.yaml"

RemoteManifestFile is the canonical filename written beside content-hashed remote assets by `game assets`.

const RemoteManifestVersion = 1

RemoteManifestVersion is the schema version of remote.yaml.

Variables

var (
	// ErrIncompatibleBuild reports that a pack's MinBuild/MaxBuild range does
	// not include the running application's AppBuild.
	ErrIncompatibleBuild = errors.New("assets: pack incompatible with app build")
	// ErrHashMismatch reports that a pack's SHA-256 digest does not match
	// PackSpec.SHA256.
	ErrHashMismatch = errors.New("assets: pack sha256 mismatch")
	// ErrInvalidSignature reports that a pack's Ed25519 signature failed
	// verification against DLCOptions.PublicKey.
	ErrInvalidSignature = errors.New("assets: pack signature invalid")
	// ErrCorruptPack reports that a pack archive is unreadable or not a valid
	// ZIP archive.
	ErrCorruptPack = errors.New("assets: pack archive corrupt")
	// ErrSizeMismatch reports that a pack's byte length does not match
	// PackSpec.Size.
	ErrSizeMismatch = errors.New("assets: pack size mismatch")
	// ErrPackTooLarge reports that a pack archive, or a file read from a mounted pack, would exceed PackLimits: a download without a PackSpec.Size that grows past MaxPackBytes, or an entry that decompresses past MaxFileBytes.
	ErrPackTooLarge = errors.New("assets: pack exceeds its size limit")
)

Fonctions

func EncodeRemoteManifest(m *RemoteManifest) ([]byte, error)

EncodeRemoteManifest encodes m as canonical 2-space YAML with Files sorted by URI so a round trip through ParseRemoteManifest and EncodeRemoteManifest changes nothing.

func EstimateAtlasBytes(a *sprite.Atlas, rawJSONBytes int64) int64

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 HashedPath(relPath, sha256Hex string) string

HashedPath inserts the first 8 lowercase hex characters of sha256Hex before the extension of relPath, producing "<name>.<hash8>.<ext>" (or "<name>.<hash8>" when relPath has no extension).

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.

The once is per mount: a Render runs once under its scope, so OnReady fires again only when the view is mounted again, for example by a parent Dynamic that rebuilds it, and then immediately if the group is already loaded. Mounting the view for a group whose last load failed retries that load. Keep the view out of reactive branches that rebuild it, or make OnReady idempotent.

func RemoteURL(base, relPath string) (string, error)

RemoteURL joins an HTTP(S) base URL with a clean relative slash-separated asset path, escaping each path segment and refusing path traversal.

func SignPack(priv ed25519.PrivateKey, data []byte) (sha256Hex, signatureHex string)

SignPack hashes data with SHA-256, signs the raw 32-byte digest with priv, and returns the hex-encoded SHA-256 digest and hex-encoded Ed25519 signature.

func SignPackDigest(priv ed25519.PrivateKey, sha256Hex string) (string, error)

SignPackDigest signs a hex-encoded SHA-256 digest with priv and returns the hex-encoded Ed25519 signature.

Types

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 func(ctx context.Context, data []byte) (any, error)

CustomLoader parses raw asset bytes off the engine goroutine into a domain value such as a tilemap, bitmap font or JSON table.

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

DLCManager downloads, resumes, verifies, caches, and mounts DLC pack ZIP archives as fs.FS instances and assets.Groups.

func NewDLCManager(opts DLCOptions) *DLCManager

NewDLCManager returns a DLCManager configured with opts.

func (d *DLCManager) Cache() PackCache

Cache returns the PackCache used by this DLCManager.

func (d *DLCManager) Fetch(ctx context.Context, spec PackSpec, onProgress func(downloaded, total int64)) (fsys fs.FS, err error)

Fetch ensures spec is compatible with AppBuild, checks and re-verifies any cached pack, downloads missing or resumed bytes via HTTP Range requests into a .part staging entry, strictly verifies size, SHA-256, Ed25519 signature, and ZIP structure, commits atomically to the cache, and returns the mounted ZIP archive as an fs.FS.

The returned fs.FS also implements io.Closer and fs.ReadFileFS. It reads through the one cache reader it was verified on, and each file as it decompresses, bounded by PackLimits. Close it when the pack is no longer used: that releases the cache entry for Remove; one that is never closed is released when it is garbage collected. FetchGroup closes the pack it mounts when the group is reset or mounted again.

On network or context interruption, the .part entry is preserved so a subsequent Fetch resumes via HTTP Range ("bytes=<offset>-"). A spec that could never verify (a missing ID, a negative Size, a malformed SHA256 or Signature) is refused before the cache is touched. A cached pack whose bytes do not match the spec's size or SHA-256, and a download that fails verification, are removed from the cache; a cached pack whose bytes match but whose signature or contents are refused is kept, because downloading it again would fetch the same bytes.

func (d *DLCManager) FetchGroup(
	ctx context.Context,
	loader *Manager,
	spec PackSpec,
	registerFn func(g *Group, packFS fs.FS) error,
	onProgress func(downloaded, total int64),
) (*Group, error)

FetchGroup fetches and verifies spec, mounts the resulting ZIP fs.FS onto loader.Group(spec.Group) (or spec.ID when spec.Group is empty), invokes registerFn on the engine goroutine to register assets in the group, and loads the group to completion.

FetchGroup blocks until download and group loading finish or ctx (or loader's scope) is cancelled, so it should be called off the engine goroutine.

The group owns the mounted pack: Group.Reset, Group.SetFS, a later FetchGroup into the same group and disposing loader's scope release it, and with it the cache entry for Remove.

func (d *DLCManager) Remove(spec PackSpec) error

Remove deletes both the cached pack and any partial download for spec.

A pack that Fetch or FetchGroup mounted and that is still in use is not pulled from under its readers: its partial download goes at once, and the cached pack when the last mount is released, by closing the fs.FS Fetch returned or by resetting or re-mounting the group FetchGroup loaded (#546). A Fetch of the same pack before then keeps it.

type DLCOptions struct {
	// AppBuild is the running application's build number, checked against each
	// PackSpec's MinBuild and MaxBuild range.
	AppBuild int
	// PublicKey is the Ed25519 public key used to verify pack signatures over
	// each pack's 32-byte SHA-256 digest. Without it every pack is refused with ErrInvalidSignature unless AllowUnsigned is set.
	PublicKey ed25519.PublicKey
	// AllowUnsigned accepts packs without a signature when PublicKey is empty, checking only their size and SHA-256 from the PackSpec. Whoever supplies the PackSpec then chooses what is mounted, so set it only for development or when the specs ship inside the app (#546).
	AllowUnsigned bool
	// Cache stores completed packs and resumable .part downloads. When nil, a
	// new MemoryPackCache is used.
	Cache PackCache
	// HTTPClient performs pack downloads. When nil, http.DefaultClient is used.
	HTTPClient *http.Client
	// ChunkSize sets the buffer size for streaming reads and progress updates.
	// When <= 0, DefaultDLCChunkSize (32 KiB) is used.
	ChunkSize int
	// Limits caps how large a pack may be and what it may contain; zero fields use DefaultPackLimits. A pack over any limit is refused before it is mounted, a download stops as soon as it would pass MaxPackBytes, and a mounted pack reads each file as it decompresses, failing with ErrPackTooLarge past MaxFileBytes, so the caps also bound what reading an asset can allocate.
	Limits PackLimits
}

DLCOptions configures a DLCManager created by NewDLCManager.

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

DirPackCache stores DLC packs on the local filesystem using ".pack.part" staging files and atomic os.Rename commits into ".pack" files.

func NewDirPackCache(dir string) *DirPackCache

NewDirPackCache returns a filesystem-backed PackCache rooted at dir. Directories are created lazily on first write.

func (c *DirPackCache) CommitPart(key string) error

CommitPart implements PackCache via atomic os.Rename.

func (c *DirPackCache) Dir() string

Dir returns the root directory of the cache.

func (c *DirPackCache) Has(key string) bool

Has reports whether a completed pack exists for key.

func (c *DirPackCache) HasPart(key string) bool

HasPart reports whether a partial ".part" file exists for key.

func (c *DirPackCache) Open(key string) (io.ReaderAt, int64, error)

Open implements PackCache.

func (c *DirPackCache) OpenPartReader(key string) (io.ReaderAt, int64, error)

OpenPartReader implements PackCache.

func (c *DirPackCache) OpenPartWriter(key string, appendMode bool) (io.WriteCloser, error)

OpenPartWriter implements PackCache.

func (c *DirPackCache) PartSize(key string) (int64, error)

PartSize implements PackCache.

func (c *DirPackCache) Remove(key string) error

Remove implements PackCache.

func (c *DirPackCache) RemovePart(key string) error

RemovePart implements PackCache.

type DirRemoteCache struct {
	// Quota is the maximum total size of cached files in bytes. When <= 0,
	// DefaultRemoteCacheQuota (200 MiB) is used.
	Quota int64
	// FlushInterval controls how frequently Get access-time updates are written
	// to index.yaml. Zero writes immediately on every access; Put and Remove
	// always persist the index immediately.
	FlushInterval time.Duration
	// contains filtered or unexported fields
}

DirRemoteCache stores remote loose asset files on disk under a directory, held to Quota (DefaultRemoteCacheQuota, 200 MiB, when <= 0) via least-recently-used eviction that never removes a file pinned by a loaded group, with access times persisted in a small YAML index (index.yaml).

func NewDirRemoteCache(dir string, quota ...int64) *DirRemoteCache

NewDirRemoteCache returns a filesystem-backed RemoteCache rooted at dir. If quota is given and positive, it sets Quota; otherwise DefaultRemoteCacheQuota (200 MiB) is used. Directories are created lazily on first write.

func (c *DirRemoteCache) Clear() error

Clear removes every unpinned file from the cache, sparing files currently pinned by loaded groups.

func (c *DirRemoteCache) Close() error

Close flushes any pending index updates to disk.

func (c *DirRemoteCache) Dir() string

Dir returns the cache root directory.

func (c *DirRemoteCache) Flush() error

Flush persists any buffered access-time updates to index.yaml on disk.

func (c *DirRemoteCache) Get(sha256Hex string) ([]byte, error)

Get implements RemoteCache.

func (c *DirRemoteCache) Has(sha256Hex string) bool

Has reports whether sha256Hex is currently present in the cache.

func (c *DirRemoteCache) Pin(sha256Hex string)

Pin implements RemoteCache.

func (c *DirRemoteCache) Put(sha256Hex string, data []byte) error

Put implements RemoteCache using atomic temp-file writes and LRU eviction of unpinned entries to stay within Quota.

func (c *DirRemoteCache) Remove(sha256Hex string) error

Remove implements RemoteCache.

func (c *DirRemoteCache) Unpin(sha256Hex string)

Unpin implements RemoteCache.

func (c *DirRemoteCache) Usage() RemoteCacheUsage

Usage implements RemoteCache.

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.

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 (g *Group) AddBytes(name, uri string) *Group

AddBytes adds a raw byte asset read from uri off the engine goroutine.

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 (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 (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 (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 (g *Group) AddSound(name string, src audio.Source) *Group

AddSound adds a short sound decoded through audio.LoadSound.

func (g *Group) Atlas(name string) (*sprite.Atlas, bool)

Atlas returns the loaded atlas named name, if present in the group.

func (g *Group) ByteProgress() (loaded, total int64)

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 (g *Group) Bytes(name string) ([]byte, bool)

Bytes returns the loaded raw bytes named name, if present in the group.

func (g *Group) Done() bool

Done reports whether every asset in the group finished loading without error. Read in a reactive computation, it subscribes to updates.

func (g *Group) Err() error

Err returns the error that stopped the group's last load, or nil. Read in a reactive computation, it subscribes to updates.

func (g *Group) Evictable() bool

Evictable reports whether MemoryPressure may release this group.

func (g *Group) FS() fs.FS

FS returns the file system mounted on this group via SetFS, or nil.

func (g *Group) Get(name string) (any, bool)

Get returns any loaded asset named name (custom, atlas, sound, image or raw bytes), if present in the group.

func (g *Group) Image(name string) (core.ImageSource, bool)

Image returns the loaded image source named name, if present in the group.

func (g *Group) Load(onDone func(error))

Load starts loading every 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. An empty group completes immediately with progress 1.

func (g *Group) Loaded() int

Loaded returns how many assets in the group have finished loading. Read in a reactive computation, it subscribes to updates.

func (g *Group) Loading() bool

Loading reports whether the group is currently loading. Read in a reactive computation, it subscribes to updates.

func (g *Group) Name() string

Name returns the group's name.

func (g *Group) Progress() float64

Progress returns loading progress in [0, 1]. Read in a reactive computation, it subscribes to progress updates.

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 (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 (g *Group) SetEvictable(evictable bool) *Group

SetEvictable marks the group as eligible for MemoryPressure eviction.

func (g *Group) SetFS(fsys fs.FS) *Group

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 the pack DLCManager.FetchGroup mounted on the group releases that pack, as Reset does; setting that same pack again keeps it.

func (g *Group) Sound(name string) (*audio.Sound, bool)

Sound returns the loaded sound named name, if present in the group.

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.

func (g *Group) Total() int

Total returns the number of assets in the group. Read in a reactive computation, it subscribes to updates.

type GroupStats struct {
	Name   string
	State  string // StateUnloaded, StateLoading, StateLoaded, or StateFailed
	Loaded int
	Total  int
	Bytes  int64
	Error  string
	Assets []AssetStats
}

GroupStats describes a Group's current load state, assets and estimated memory footprint.

type LoadingScreen struct {
	Manager *Manager
	Group   string
	Title   string
	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.

func (s LoadingScreen) Render(cx *core.Scope) core.Node

Render implements core.Node.

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; "Loading" when
	// empty.
	Title string
	// 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 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(cx *core.Scope, opts ...Option) *Manager

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 (m *Manager) Atlas(name string) (*sprite.Atlas, bool)

Atlas returns the loaded atlas named name from the most recently registered group that holds it.

func (m *Manager) Budget() (total, perGroup int64)

Budget returns the configured total and per-group limits in bytes.

func (m *Manager) Bytes(name string) ([]byte, bool)

Bytes returns the loaded raw bytes named name from the most recently registered group that holds it.

func (m *Manager) Disposed() bool

Disposed reports whether the manager's owning scope has been disposed.

func (m *Manager) Get(name string) (any, bool)

Get returns the loaded asset named name (custom, atlas, sound, image or raw bytes) from the most recently registered group that holds it.

func (m *Manager) Group(name string) *Group

Group returns the named asset group, creating it under the manager's scope if it does not yet exist.

func (m *Manager) GroupNames() []string

GroupNames returns the names of all registered groups in registration order.

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 (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 (m *Manager) LoadAtlas(jsonURI string, img core.ImageSource, done func(*sprite.Atlas, error))

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 (m *Manager) LoadBytes(uri string, done func([]byte, error))

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 (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 (m *Manager) LoadGroup(name string, onDone func(error))

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 (m *Manager) LoadSound(src audio.Source, done func(*audio.Sound, error))

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 (m *Manager) LookupGroup(name string) (*Group, bool)

LookupGroup returns the existing group named name without creating one when absent.

func (m *Manager) MemoryPressure() int

MemoryPressure releases loaded groups marked evictable until the manager is within its configured budget. It returns the number of groups released.

func (m *Manager) Over() bool

Over reports whether the currently loaded groups exceed a configured budget.

func (m *Manager) ReleaseAll()

ReleaseAll releases every group registered on the manager.

func (m *Manager) ReleaseGroup(name string)

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 (m *Manager) Reload(uri string, data []byte) ([]string, error)

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 (m *Manager) ReloadAsset(ctx context.Context, groupName, key string) ([]ReloadedAsset, error)

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 (m *Manager) ReloadGroup(ctx context.Context, groupName string) ([]ReloadedAsset, error)

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 (m *Manager) RemoteCache() RemoteCache

RemoteCache returns the RemoteCache configured via WithRemote, or nil if no remote origin is configured. Callers can read Usage() for a settings screen.

func (m *Manager) Revision() int

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 (m *Manager) SetBudget(total, perGroup int64)

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.

func (m *Manager) Sound(name string) (*audio.Sound, bool)

Sound returns the loaded sound named name from the most recently registered group that holds it.

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 (e *MemoryBudgetError) Error() string

Error describes the group, the memory it would use and the budget it exceeds.

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

MemoryPackCache is an in-memory PackCache that works on every target including Web/WASM and unit tests.

A pack is held once: readers share the stored bytes, which are never written after they are stored, and CommitPart moves the partial download into place instead of copying it (#546).

func NewMemoryPackCache() *MemoryPackCache

NewMemoryPackCache returns an empty in-memory PackCache.

func (c *MemoryPackCache) CommitPart(key string) error

CommitPart implements PackCache.

func (c *MemoryPackCache) Has(key string) bool

Has reports whether a completed pack exists for key.

func (c *MemoryPackCache) HasPart(key string) bool

HasPart reports whether a partial download exists for key.

func (c *MemoryPackCache) Open(key string) (io.ReaderAt, int64, error)

Open implements PackCache.

func (c *MemoryPackCache) OpenPartReader(key string) (io.ReaderAt, int64, error)

OpenPartReader implements PackCache.

func (c *MemoryPackCache) OpenPartWriter(key string, appendMode bool) (io.WriteCloser, error)

OpenPartWriter implements PackCache.

func (c *MemoryPackCache) PartSize(key string) (int64, error)

PartSize implements PackCache.

func (c *MemoryPackCache) Remove(key string) error

Remove implements PackCache.

func (c *MemoryPackCache) RemovePart(key string) error

RemovePart implements PackCache.

type MemoryRemoteCache struct {
	// Quota is the maximum total size of cached files in bytes. When <= 0,
	// DefaultRemoteCacheQuota (200 MiB) is used.
	Quota int64
	// contains filtered or unexported fields
}

MemoryRemoteCache is an in-memory RemoteCache enforcing Quota, LRU eviction, and loaded-group pinning on every target including Web/WASM and unit tests.

func NewMemoryRemoteCache(quota ...int64) *MemoryRemoteCache

NewMemoryRemoteCache returns an empty in-memory RemoteCache. If quota is given and positive, it sets Quota; otherwise DefaultRemoteCacheQuota is used.

func (c *MemoryRemoteCache) Clear()

Clear removes all unpinned cached entries.

func (c *MemoryRemoteCache) Get(sha256Hex string) ([]byte, error)

Get implements RemoteCache.

func (c *MemoryRemoteCache) Has(sha256Hex string) bool

Has reports whether sha256Hex is currently cached.

func (c *MemoryRemoteCache) Pin(sha256Hex string)

Pin implements RemoteCache.

func (c *MemoryRemoteCache) Put(sha256Hex string, data []byte) error

Put implements RemoteCache.

func (c *MemoryRemoteCache) Remove(sha256Hex string) error

Remove implements RemoteCache.

func (c *MemoryRemoteCache) Unpin(sha256Hex string)

Unpin implements RemoteCache.

func (c *MemoryRemoteCache) Usage() RemoteCacheUsage

Usage implements RemoteCache.

type Option func(*Manager)

Option configures a Manager created by NewManager.

func WithFS(fsys fs.FS) Option

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 WithMemoryTracker(tracker *gamedebug.MemoryTracker) Option

WithMemoryTracker reports each successfully loaded group asset's decoded size to tracker. Tracking and budget callbacks are compiled out in release builds.

func WithOnBudget(fn func(group string, err error)) Option

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 WithReadAsset(fn func(ctx context.Context, uri string) ([]byte, error)) Option

WithReadAsset sets how Manager reads raw bytes for asset URIs off the engine goroutine.

func WithRemote(opts RemoteOptions) Option

WithRemote configures Manager to load any asset URI listed in opts.Manifest from a remote origin by its content-hashed URL, verifying exact size and SHA-256 and storing verified files in opts.Cache. URIs not present in opts.Manifest continue to load from the Manager's local source (WithReadAsset, WithFS, or packaged app resources).

type PackCache interface {
	// Open returns a random-access reader and byte size for a completed pack,
	// or fs.ErrNotExist if key is not cached. The returned io.ReaderAt must be
	// safe for concurrent ReadAt calls and must not leak resources without a
	// Close call.
	Open(key string) (io.ReaderAt, int64, error)
	// PartSize returns the byte size of an in-progress partial download for
	// key, or (0, nil) if no partial download exists.
	PartSize(key string) (int64, error)
	// OpenPartWriter opens the partial download entry for key. When appendMode
	// is true, writes append to existing partial bytes; when false, existing
	// partial bytes are truncated.
	OpenPartWriter(key string, appendMode bool) (io.WriteCloser, error)
	// OpenPartReader returns a random-access reader and byte size for an
	// in-progress partial download so it can be verified before CommitPart, or
	// fs.ErrNotExist if no partial download exists.
	OpenPartReader(key string) (io.ReaderAt, int64, error)
	// CommitPart atomically promotes the partial download for key into the
	// completed pack entry.
	CommitPart(key string) error
	// RemovePart deletes any partial download for key, returning nil if absent.
	RemovePart(key string) error
	// Remove deletes any completed pack for key, returning nil if absent.
	Remove(key string) error
}

PackCache persists downloaded DLC packs and in-progress resumable partial downloads. Implementations must be safe for concurrent use.

type PackLimits struct {
	// MaxEntries is the largest number of files a pack may hold.
	MaxEntries int
	// MaxFileBytes is the largest uncompressed size of one file, checked against the archive's headers before mounting and against the bytes themselves as a mounted pack reads them.
	MaxFileBytes uint64
	// MaxTotalBytes is the largest uncompressed size of all files together.
	MaxTotalBytes uint64
	// MaxPackBytes is the largest archive a DLCManager downloads or opens. It bounds the .part file of a PackSpec without a Size, which would otherwise grow as long as the server sends bytes, and a PackSpec whose Size is larger is refused before anything is downloaded.
	MaxPackBytes int64
}

PackLimits bounds the size and structure of a DLC pack ZIP.

func DefaultPackLimits() PackLimits

DefaultPackLimits returns the limits a DLCManager uses for zero PackLimits fields: 32768 entries, 256 MiB per file, 1 GiB in total and a 1088 MiB (1 GiB + 64 MiB) archive.

type PackManifest struct {
	// Packs lists the packs the catalog offers.
	Packs []PackSpec `json:"packs"`
}

PackManifest is a JSON catalog of downloadable content packs.

type PackSpec struct {
	// ID uniquely identifies the pack (for example "chapter-2").
	ID string `json:"id"`
	// Group names the assets.Group populated by FetchGroup. When empty, ID is
	// used as the group name.
	Group string `json:"group,omitempty"`
	// URL is the HTTP(S) endpoint serving the pack ZIP archive.
	URL string `json:"url"`
	// Version identifies the pack revision (for example "1.0.0").
	Version string `json:"version"`
	// MinBuild is the minimum inclusive application build compatible with this
	// pack. Zero means no lower bound.
	MinBuild int `json:"min_build,omitempty"`
	// MaxBuild is the maximum inclusive application build compatible with this
	// pack. Zero means no upper bound.
	MaxBuild int `json:"max_build,omitempty"`
	// Size is the expected pack size in bytes. When positive, downloads and
	// cached packs must match Size exactly.
	Size int64 `json:"size,omitempty"`
	// SHA256 is the expected hex-encoded SHA-256 digest of the pack archive.
	SHA256 string `json:"sha256"`
	// Signature is the Ed25519 signature over the raw 32-byte SHA-256 digest of
	// the pack, encoded as hex or base64. Required when DLCOptions.PublicKey is
	// set.
	Signature string `json:"signature,omitempty"`
}

PackSpec describes a downloadable content (DLC) pack archive.

func ParsePackManifest(data []byte) ([]PackSpec, error)

ParsePackManifest decodes a JSON pack manifest containing either a PackManifest object ({"packs": [...]}) or a bare JSON array of PackSpec.

A field the manifest does not define, such as a misspelt "sha265", is refused rather than ignored, as are a key given twice in one object and bytes after the manifest, so a typo cannot silently drop a check and a reader cannot be shown one value while another is used (#546).

Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile.

func (s PackSpec) CacheKey() string

CacheKey returns the stable cache key for this pack based on its ID and Version.

func (s PackSpec) Compatible(appBuild int) bool

Compatible reports whether appBuild falls within the pack's inclusive [MinBuild, MaxBuild] bounds. Zero bounds are treated as unbounded.

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 RemoteCache interface {
	// Get returns the cached bytes for sha256Hex and updates its last-access
	// time, or returns fs.ErrNotExist if not cached.
	Get(sha256Hex string) ([]byte, error)
	// Put stores verified bytes for sha256Hex, updates its last-access time,
	// and evicts least-recently-used unpinned entries to stay within Quota.
	Put(sha256Hex string, data []byte) error
	// Remove deletes the cached entry for sha256Hex, returning nil if absent.
	Remove(sha256Hex string) error
	// Pin marks sha256Hex as in use by a loaded or loading group so eviction
	// spares it. Calls are reference-counted and paired with Unpin.
	Pin(sha256Hex string)
	// Unpin releases one Pin reference on sha256Hex.
	Unpin(sha256Hex string)
	// Usage returns the cache's current byte usage, quota, file count, and
	// pinned byte count.
	Usage() RemoteCacheUsage
}

RemoteCache stores verified remote asset files keyed by their lowercase hex SHA-256 digest and enforces a byte quota with least-recently-used eviction. Implementations must be safe for concurrent use.

type RemoteCacheUsage struct {
	// Bytes is the total size in bytes of all cached files.
	Bytes int64
	// Quota is the configured maximum cache size in bytes.
	Quota int64
	// Files is the number of cached files.
	Files int
	// PinnedBytes is the total size in bytes of cached files currently pinned by loaded groups.
	PinnedBytes int64
}

RemoteCacheUsage summarizes the footprint of a RemoteCache, suitable for displaying in a game's settings or storage management screen.

type RemoteEntry struct {
	// URI is the logical asset URI (for example "asset:music/theme.m4a").
	URI string `yaml:"uri"`
	// Path is the content-hashed relative path under Base (for example "music/theme.9f86d081.m4a").
	Path string `yaml:"path"`
	// Size is the exact expected file size in bytes.
	Size int64 `yaml:"size"`
	// SHA256 is the lowercase 64-character hex-encoded SHA-256 digest of the file.
	SHA256 string `yaml:"sha256"`
}

RemoteEntry describes one loose asset file served from a remote origin.

type RemoteManifest struct {
	// Version is the schema version; must equal RemoteManifestVersion (1).
	Version int `yaml:"version"`
	// Base is the default origin URL prefix (for example "https://cdn.example.com/game/")
	// joined with each entry's Path when RemoteOptions.Base is empty.
	Base string `yaml:"base,omitempty"`
	// Files lists the remotely delivered assets, sorted by URI in canonical output.
	Files []RemoteEntry `yaml:"files,omitempty"`
}

RemoteManifest maps logical asset URIs (such as "asset:music/theme.m4a") to content-hashed paths on a remote origin, with each file's exact byte size and SHA-256 digest.

func ParseRemoteManifest(data []byte) (*RemoteManifest, error)

ParseRemoteManifest decodes a remote.yaml manifest, refusing unknown fields, trailing YAML documents, unsupported versions, duplicate URIs, invalid paths, negative sizes, and malformed SHA-256 digests.

func (m *RemoteManifest) Lookup(uri string) (RemoteEntry, bool)

Lookup returns the manifest entry for uri (normalizing "asset:" paths), if present.

type RemoteOptions struct {
	// Manifest maps logical asset URIs to content-hashed paths, exact byte
	// sizes and SHA-256 digests. URIs not listed in Manifest fall through to
	// the Manager's local reader.
	Manifest *RemoteManifest
	// Base is the remote origin URL prefix (for example "https://cdn.example.com/game/").
	// When empty, Manifest.Base is used.
	Base string
	// Fetch retrieves url and returns its response body and expected content
	// length (-1 if unknown). The caller closes the returned io.ReadCloser.
	// When nil, net/http with http.DefaultClient is used.
	Fetch func(ctx context.Context, url string) (io.ReadCloser, int64, error)
	// Cache stores verified remote files keyed by SHA-256 and enforces a byte
	// quota with LRU eviction. When nil, a MemoryRemoteCache with
	// DefaultRemoteCacheQuota is used.
	Cache RemoteCache
	// Retries is the number of additional attempts after a transient fetch
	// error (network failure, HTTP 429 or 5xx). Integrity mismatches and 4xx
	// responses are never retried. Zero disables retries.
	Retries int
	// RetryBackoff is the initial delay before the first retry (doubled on
	// each subsequent attempt). When <= 0, DefaultRemoteRetryBackoff is used.
	RetryBackoff time.Duration
}

RemoteOptions configures loading loose asset files from a remote origin by content-hashed URL, verified against size and SHA-256 and cached under a byte quota.