GitHub快速开始

API 参考取自源码中的 Go 文档注释,以英文书写。

package assets

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

概述

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.PrefetchImage and dropped for GC when their group is released.

索引

常量

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.

变量

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")
)

函数

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 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 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.

类型

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 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) 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) 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) 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) 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 local files under "assets/".
	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 local "assets" directory on disk.

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) 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) 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, the Manager's FS or the local assets/ directory). 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) 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) Sound(name string) (*audio.Sound, bool)

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

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 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.

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.

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.