Documentation
¶
Overview ¶
Package asset is a handle-based asset system: typed stores, background loading, scopes with reference counts and dependency tracking.
It uses the standard library only and knows no graphics or audio API, so it is testable with fstest.MapFS and fake loaders, without a GPU. Asset types that need a GPU or a decoder (textures, sprites, fonts, sounds) live in your own packages and plug in through Loader.
Model ¶
Components hold a Handle, an 8-byte generational index into a Store of one asset type. Load returns a handle immediately and queues the work; the asset becomes ready later. Store.Get never returns nil: handles that are zero, not ready, failed or stale resolve to the type's placeholder.
A Loader has two phases. Decode (file bytes to a plain value) runs on worker goroutines and must not touch stores. Finish (create GPU objects, resolve dependencies, publish sub-assets) runs on the game goroutine inside Server.Update, optionally under a time budget.
Lifetime is by Scope: a scope holds the assets it loaded, and assets nobody holds are unloaded by the next Server.Update. Handles inside components are non-owning.
Goroutines ¶
Everything except Decode runs on one goroutine, the game goroutine: Load, Update, Get, scopes, Close. Decode may run on several workers at once, so a Loader's Decode must be safe for concurrent use.
Panics and errors ¶
Programmer errors panic with an "asset: " prefix (unregistered type, bad key, Load after Close, strict-mode stale handle). Bad files and failing loaders are not programmer errors: they put the asset in state Failed, are reported through Options.OnError and never panic.
Example ¶
package main
import (
"fmt"
"strings"
"testing/fstest"
"github.com/weakpixel/asset"
)
// Greeting is a stand-in for an asset type. A real one would hold a
// GPU texture or similar, created in Finish.
type Greeting struct{ Text string }
// greetingLoader decodes a file into upper-case text. Decode is the part that
// would run on a worker; Finish builds the final value on the game goroutine.
type greetingLoader struct{}
func (greetingLoader) Decode(_ *asset.DecodeContext, data []byte) (string, error) {
return strings.ToUpper(string(data)), nil
}
func (greetingLoader) Finish(_ *asset.FinishContext, s string) (Greeting, error) {
return Greeting{Text: s}, nil
}
func (greetingLoader) Unload(*Greeting) {}
func main() {
srv := asset.NewServer(asset.Options{
FS: fstest.MapFS{"hello.txt": {Data: []byte("hello")}},
// Workers: runtime.GOMAXPROCS(0) - 1 would decode in the background;
// 0 decodes inside Update, which keeps this example deterministic.
Workers: 0,
})
defer srv.Close()
greetings := asset.Register(srv, greetingLoader{}, Greeting{Text: "(loading)"})
// Load returns at once. The handle is what components store.
level := srv.NewScope("level-1")
hello := asset.Load[Greeting](level, "hello.txt")
fmt.Println("before Update:", greetings.Get(hello).Text)
// Update runs first in every tick: it decodes, commits and unloads.
for ev := range srv.Update().All() {
fmt.Println("event:", ev.Key, ev.Kind == asset.EventLoaded)
}
fmt.Println("after Update:", greetings.Get(hello).Text)
// Releasing the scope unloads what nothing else holds. The old handle is
// not dangling: it resolves to the placeholder.
level.Release()
srv.Update()
fmt.Println("after Release:", greetings.Get(hello).Text)
}
Output: before Update: (loading) event: hello.txt true after Update: HELLO after Release: (loading)
Index ¶
- Constants
- func Hold[T any](sc *Scope, h Handle[T])
- func RegisterChild[P, C any](s *Server)
- type BuiltinLoader
- type DecodeContext
- type DepRef
- type Event
- type EventKind
- type Events
- type FinishContext
- type Handle
- type ID
- type Key
- type Loader
- type Options
- type Ref
- type Scope
- type Server
- type State
- type Stats
- type Store
- func (s *Store[T]) All() iter.Seq2[Handle[T], *T]
- func (s *Store[T]) Err(h Handle[T]) error
- func (s *Store[T]) Get(h Handle[T]) *T
- func (s *Store[T]) ID(h Handle[T]) ID
- func (s *Store[T]) Key(h Handle[T]) Key
- func (s *Store[T]) Len() int
- func (s *Store[T]) Lookup(h Handle[T]) (*T, State)
- func (s *Store[T]) Ready(h Handle[T]) bool
- func (s *Store[T]) Version(h Handle[T]) uint32
- type TypeID
- type TypeStats
Examples ¶
Constants ¶
const StateCount = int(Failed) + 1
StateCount is the number of States, for arrays indexed by State.
Variables ¶
This section is empty.
Functions ¶
func Hold ¶
Hold adds sc as an owner of an existing handle: an entity spawned at runtime that should keep its art alive after the level that loaded it is released. The zero handle is ignored.
Holding a stale handle is a programmer error: it panics with "asset: stale handle" in strict mode and is ignored (and counted) otherwise.
func RegisterChild ¶
RegisterChild says that "path#sub" keys for C are sub-assets of the P at "path" (a Sprite of an Atlas, a Clip of a ClipSet). Loading such a key loads the parent, reserves the child's slot right away, and the parent's Finish fills it with AddChild. Both types must be registered first.
A C key without a '#sub' is an ordinary top-level asset of C.
It panics with "asset: type not registered" for an unregistered type and with "asset: child type already registered" if C already has a parent.
Types ¶
type BuiltinLoader ¶
BuiltinLoader is an optional method of a Loader: Builtin reports whether key names a value built into the loader (a starter voice by its name), not a file. For such a key the server reads nothing and calls Decode with nil data; hot reload never sees it change. Builtin runs on worker goroutines, so it must be safe for concurrent use, and must answer the same for a key every time.
type DecodeContext ¶
type DecodeContext struct {
// Key is the key being loaded.
Key Key
// contains filtered or unexported fields
}
DecodeContext is handed to Decode. It is the only way a loader declares dependencies (atlas -> texture, tile map -> tileset, animation -> atlas). It is valid only during the Decode call.
type DepRef ¶
type DepRef[T any] struct { // contains filtered or unexported fields } // 1-based index into the declared deps
DepRef names a dependency declared in Decode. Hand it to Resolve in Finish. The zero DepRef is invalid.
func Dep ¶
func Dep[T any](ctx *DecodeContext, path string) DepRef[T]
Dep declares that the asset being decoded needs a T at path. A relative path resolves against the directory of ctx.Key.Path ("hero.png" next to "chars/hero.json" is "chars/hero.png"); it may carry a "#sub" suffix.
The server loads it with a hold owned by the parent and delays the parent's Finish until it is Ready. If it fails, the parent fails too, without Finish. A dependency cycle fails the asset that closes it (see Server.Update).
T must be registered by the time the result is applied, or Update panics with "asset: type not registered".
type EventKind ¶
type EventKind uint8
EventKind says what happened to an asset.
const ( // EventLoaded: the asset was committed and is Ready. EventLoaded EventKind = iota // EventFailed: the asset failed; Event.Err says why. EventFailed // EventModified: hot reload replaced the value. The handle is the same; // Store.Version went up. Systems that derived data from the asset (a // collision grid, cached images) rebuild it. EventModified // EventUnloaded: the asset was unloaded and its handles are now stale. EventUnloaded )
type Events ¶
type Events struct {
// contains filtered or unexported fields
}
Events is the list for one Server.Update. The same Events value (and its backing storage) is reused, so it is valid until the next Update.
type FinishContext ¶
type FinishContext struct {
// Key is the key being finished.
Key Key
// contains filtered or unexported fields
}
FinishContext is handed to Finish. It is valid only during the Finish call.
type Handle ¶
type Handle[T any] struct { // contains filtered or unexported fields }
Handle refers to one asset of type T in one Server. It is 8 bytes, comparable and pointer-free, so it can live in components, draw items and map keys.
The zero Handle means "none" and resolves to the store's placeholder. A handle never changes for the life of the asset. The generation changes only when the slot is freed, which makes older handles stale.
Handles are only meaningful inside the Server that issued them.
func AddChild ¶
func AddChild[C any](ctx *FinishContext, sub string, v C) Handle[C]
AddChild publishes the sub-asset "path#sub" of the asset being finished and returns its handle. The child type C must be registered with RegisterChild for the parent's type.
If a handle for that key was handed out earlier (Load of "path#sub" before the parent was ready), the same slot is filled, so existing handles stay valid. A child lives as long as its parent and is unloaded with it.
During a hot reload the child's existing slot gets the new value (same handle, Version + 1) once the parent's Finish succeeds; children the new version does not add switch to Failed.
It panics with "asset: AddChild" if C is not a registered child of the asset being finished, if sub is empty, or if the sub-asset was already added.
func HandleOf ¶
HandleOf returns r as a Handle[T]. It is the inverse of Handle.Ref and does not check that r came from a Handle[T]: a Ref of another type resolves to an unrelated slot or a stale handle. Use it only inside a store facade that owns the concrete handle type for T, never at game call sites.
func Load ¶
Load returns the handle for key and adds a hold for sc. It never blocks: a new key gets a slot in state Queued and a job; a known key returns the existing handle in whatever state it is in. It is idempotent per (T, key) and per scope, and it does not retry an asset that already Failed.
Load is a map lookup on a string: call it at spawn time or in Init, keep the handle, and never call it per entity per tick. Don't call it from Draw.
If T is registered as a child type and key has a "#sub", the parent is loaded too and the child's slot is reserved in state Waiting until the parent's Finish adds it (see RegisterChild).
It panics with "asset: bad key" for a malformed key (see ParseKey), with "asset: type not registered" for an unregistered T, and with "asset: server closed" after Close.
func LoadSync ¶
LoadSync is Load followed by driving the server until the asset (and its dependencies) is Ready or Failed, ignoring CommitBudget. It returns the handle and the asset's error, if it failed.
It blocks the game loop. Use it for boot screens, tests and tools, never in a running level. Events produced meanwhile are delivered by the next Update.
Example ¶
package main
import (
"fmt"
"strings"
"testing/fstest"
"github.com/weakpixel/asset"
)
// Greeting is a stand-in for an asset type. A real one would hold a
// GPU texture or similar, created in Finish.
type Greeting struct{ Text string }
// greetingLoader decodes a file into upper-case text. Decode is the part that
// would run on a worker; Finish builds the final value on the game goroutine.
type greetingLoader struct{}
func (greetingLoader) Decode(_ *asset.DecodeContext, data []byte) (string, error) {
return strings.ToUpper(string(data)), nil
}
func (greetingLoader) Finish(_ *asset.FinishContext, s string) (Greeting, error) {
return Greeting{Text: s}, nil
}
func (greetingLoader) Unload(*Greeting) {}
func main() {
srv := asset.NewServer(asset.Options{FS: fstest.MapFS{"boot.txt": {Data: []byte("boot")}}})
defer srv.Close()
greetings := asset.Register(srv, greetingLoader{}, Greeting{Text: "(loading)"})
// Blocks until the asset is Ready or Failed. For boot screens and tools.
h, err := asset.LoadSync[Greeting](srv.Global(), "boot.txt")
fmt.Println(greetings.Get(h).Text, err)
}
Output: BOOT <nil>
func Resolve ¶
func Resolve[T any](ctx *FinishContext, d DepRef[T]) Handle[T]
Resolve turns a DepRef from Decode into a Ready handle. The parent keeps its hold on the dependency until the parent is unloaded, so the handle stays valid as long as the asset being finished does.
It panics with "asset: Resolve" if d is the zero DepRef or its type does not match the dependency.
func (Handle[T]) Index ¶
Index returns the handle's slot index in its store. It is meant for sort keys (handles to the same asset share an index) and debugging; it is not an identity, because it ignores the generation. The zero handle returns 0.
type ID ¶
ID is the untyped form of a Handle: the store it belongs to plus index and generation. It is comparable, so it works as a map key in events and debug tools. Get one with Store.ID.
type Key ¶
Key names an asset: a clean, slash-separated path inside the Server's fs.FS, plus an optional sub-asset name after '#': "chars/hero.json#run_0". Together with the asset type it is the cache key, so loading the same key twice returns the same handle.
type Loader ¶
type Loader[T, D any] interface { Decode(ctx *DecodeContext, data []byte) (D, error) Finish(ctx *FinishContext, d D) (T, error) Unload(v *T) }
Loader turns file bytes into a T in two phases. D is the intermediate value Decode hands to Finish.
Decode runs on a worker goroutine, possibly several at once, so it must be safe for concurrent use: CPU work only (image/png, encoding/json, audio decoders, font parsing). It must not make GPU calls and must not touch stores or the Server.
Finish runs on the game goroutine inside Server.Update, after every dependency declared in Decode is Ready: create images, cache sub-images, compile shaders, resolve dependency handles, publish sub-assets. Keep it short; heavy CPU work belongs in Decode.
With hot reload on (Options.WatchInterval), Finish can run again with the same D when a dependency changes, so it must not modify d. Its result replaces the old value only if it succeeds.
Unload releases what Finish created. It runs on the game goroutine when the asset is unloaded, for every Ready value at Server.Close, and for the old value after a hot reload replaced it.
type Options ¶
type Options struct {
// FS is the file system assets are read from: embed.FS in release builds,
// os.DirFS("assets") in development. Workers read from it concurrently.
FS fs.FS
// Workers is the number of decode goroutines. 0 decodes inline inside
// Update: deterministic, for tests and tools.
Workers int
// CommitBudget caps the time Update spends in Finish calls. At least one
// Finish runs per Update, so loading always progresses. 0 means no cap.
// [LoadSync] ignores the cap. Unloads are not capped.
CommitBudget time.Duration
// StrictHandles makes a stale handle panic with "asset: stale handle: ..."
// instead of resolving to the placeholder. Meant for debug builds, to find
// entities that outlive the scope that loaded their assets. The zero handle
// and handles of assets that are not ready yet are never stale.
StrictHandles bool
// OnError receives load failures, from Update on the game goroutine. The
// default logs with the standard logger.
OnError func(err error)
// WatchInterval turns on hot reload, for development builds. Update stats
// the file of every loaded asset at most once per interval (wall-clock
// time). A different modtime or size reloads it: the file is decoded and
// finished again into a candidate, which replaces the value in the same
// slot (same handle, [Store.Version] + 1, [EventModified]) only if both
// steps succeed. A failed reload keeps the old value and is reported
// through OnError once per file version ("asset: reload failed, keeping
// previous version: ..."). Assets that depend on a replaced asset are
// finished again; its sub-assets keep their handles, and the ones the new
// version no longer has switch to Failed. A Failed asset is loaded again
// when its file changes. A file that cannot be stat'ed counts as
// unchanged, and an embed.FS never changes.
//
// 0 turns it off: no file-system calls besides loading.
WatchInterval time.Duration
// KeepAlive is the byte budget of released assets that stay loaded. When
// a scope is released, assets that lose their last hold are parked
// instead of unloaded; loading the same key again revives the asset with
// the same handle and without decoding. Once the idle bytes (parked
// assets and the dependencies only they hold) exceed the budget, the
// least recently released are unloaded. Sizes come from the loader's
// optional Size method, else from the file length (see [Stats]). 0 turns
// keep-alive off: released assets unload at the next Update.
//
// A parked asset's handles stay valid, so with keep-alive on a stale
// handle is noticed later, or never. Use 0 when hunting them with
// StrictHandles.
KeepAlive int64
}
Options configures a Server.
type Ref ¶
type Ref struct {
// contains filtered or unexported fields
}
Ref is the untyped payload of a handle: slot index and generation, without the asset type. It is 8 bytes, comparable and pointer-free.
Ref exists so packages can give an asset kind its own concrete handle type (a SpriteHandle defined as struct{ asset.Ref }) instead of exposing Handle[T] to game code. Such a package converts with Handle.Ref and HandleOf in one place, its store facade; game code never converts by hand.
The zero Ref means "none", like the zero Handle.
func (Ref) Index ¶
Index returns the slot index, with the same meaning as Handle.Index.
type Scope ¶
type Scope struct {
// contains filtered or unexported fields
}
Scope owns asset holds: Global, a level, a UI screen, a cutscene. Loading through a scope adds a hold; releasing the scope drops all its holds, and assets without any remaining hold are unloaded by the next Update.
Every asset has a reference count: the scopes that hold it, plus the parent assets that depend on it, plus one while any of its sub-assets is held. The count changes on load, release and dependency edges, never per entity.
func (*Scope) Done ¶
Done reports whether every asset the scope needs is Ready or Failed. An empty scope is Done.
func (*Scope) Err ¶
Err joins the errors of every Failed asset the scope needs, or returns nil. A parent that failed because of a dependency appears together with the dependency's own error.
func (*Scope) Progress ¶
Progress counts the assets sc needs, dependencies and parents included: how many are Ready and how many there are. Failed assets count in total only, so use Done to tell "finished with errors" from "still loading".
func (*Scope) Release ¶
func (sc *Scope) Release()
Release drops every hold of sc. Assets with no remaining hold, from any scope or parent asset, are unloaded at the next Update, or parked when Options.KeepAlive is set. The scope can be reused afterwards. Handles of unloaded assets become stale.
Release a level's scope only after the next level's scope is Done, so shared assets are not unloaded and reloaded.
It panics with "asset: cannot release the global scope" for Server.Global. After Server.Close it does nothing.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server owns the stores, the loaders, the scopes and the worker goroutines. All methods except the workers' Decode calls run on the game goroutine.
func NewServer ¶
NewServer creates a server and starts opts.Workers decode goroutines. Call Server.Close to stop them.
func (*Server) Changed ¶
Changed reports that the files at paths changed, for hosts that learn about changes themselves (an editor's file watcher) instead of polling. The next Update reloads every loaded top-level asset whose key has one of these paths, exactly as polling does when a file's stamp changes: a Ready asset is decoded again and swapped in place (EventModified; on failure the old value stays), a Failed one is loaded again. It works whether or not Options.WatchInterval is set, and never stats the file.
A path whose asset is still loading or already reloading stays recorded until an Update can act on it, so a change is never lost. A path no loaded asset uses is dropped. Sub-assets are not reloaded directly: their parent republishes them. Call it on the game goroutine.
func (*Server) Close ¶
func (s *Server) Close()
Close stops the workers, waits for them, and unloads every asset (calling each loader's Unload on Ready values). All handles are stale afterwards. Load after Close panics with "asset: server closed"; Update, Release and a second Close are harmless no-ops. Pending decode work is dropped.
func (*Server) Global ¶
Global returns the scope that is never released. Fonts, the UI atlas and other assets that live as long as the game belong here.
func (*Server) Stats ¶
Stats returns the current counts. It allocates; use it for overlays and tests, not per entity.
func (*Server) Update ¶
Update runs once per tick on the game goroutine, before any system that reads assets. In order it:
- hands queued jobs to the workers (or decodes them inline when Workers is 0) and applies finished decode results, loading declared dependencies;
- runs Finish for every decoded asset whose dependencies are Ready, FIFO, until Options.CommitBudget is spent (at least one per call). An asset whose dependency failed fails without Finish;
- unloads assets whose reference count is 0, calling the loader's Unload, bumping the slot generation and dropping their dependency holds. With Options.KeepAlive they are parked instead, and only the least recently released ones beyond the byte budget are unloaded;
- returns the tick's events.
With Options.WatchInterval set it first polls loaded files for changes and queues hot reloads; reloads go through the same steps 1 and 2 (see Options.WatchInterval). Paths reported with Server.Changed are reloaded the same way, with or without polling.
The returned Events is reused: it is valid until the next Update. Pointers from Store.Get are valid until the next Update as well.
It panics with "asset: type not registered" if a loader declared a dependency of an unregistered type. After Close it returns no events.
type State ¶
type State uint8
State is where an asset is in its load pipeline.
const ( // Missing is a zero or stale handle, or a slot that was never loaded. Missing State = iota // Queued waits for a worker (or for the next Update when Workers is 0). Queued // Decoding means Decode is running, or its result is not applied yet. Decoding // Waiting is decoded and waits for its dependencies or the commit budget. // A reserved sub-asset also waits here until its parent is finished. Waiting // Ready means the value is committed; Get returns it. Ready // Failed means Decode or Finish failed, or a dependency or the parent // failed. Get returns the placeholder; [Store.Err] says why. Failed )
type Stats ¶
type Stats struct {
// States counts assets per State across all types (placeholders excluded).
States [StateCount]int
// Types is the same per type, in registration order.
Types []TypeStats
// Queued is the number of jobs not yet handed to a worker or decoded;
// InFlight the number handed to workers whose result is not applied yet.
Queued, InFlight int
// StaleHits counts Store lookups with a stale handle (also in strict mode,
// right before the panic).
StaleHits uint64
// Bytes is the approximate size of all Ready values; IdleBytes the part
// that no live scope needs: parked assets and the dependencies only they
// hold. Parked counts the assets kept alive by [Options.KeepAlive].
Bytes, IdleBytes int64
Parked int
}
Stats is a debug snapshot of the server.
type Store ¶
type Store[T any] struct { // contains filtered or unexported fields }
Store holds every asset of one type. It is read and written on the game goroutine only; workers never touch it, so Get needs no lock.
Create stores with Register; the zero Store is not usable.
func Register ¶
Register adds the store and loader for T and returns the store. placeholder is what Get returns for missing, loading, failed and stale handles (a magenta checker sprite, a silent sound).
It panics with "asset: type already registered: <T>" if T is registered. Register before the first Load of T.
func (*Store[T]) All ¶
All yields every Ready asset, for debug tools and editors. Pointers follow the validity rule of Store.Get. Don't load or release while iterating.
func (*Store[T]) Err ¶
Err returns why the asset failed, or nil if it did not fail (including handles that are zero or stale).
func (*Store[T]) Get ¶
Get returns the asset, or the placeholder if h is zero, stale, not ready or failed. It never returns nil and does not allocate.
The pointer is valid until the next Server.Update (a commit may grow the slot slice) and must not be stored in components or closures; store the handle instead.
A stale handle (its slot was freed or reused) counts in Stats and returns the placeholder, or panics with "asset: stale handle" when Options.StrictHandles is set.
func (*Store[T]) Key ¶
Key returns the key the asset was loaded from, or the zero Key for a zero or stale handle. For debugging and save files.
func (*Store[T]) Lookup ¶
Lookup is Get plus the state, for code that must tell the placeholder from a real asset. For a zero handle the state is Missing, for a stale handle too (subject to the strict-mode panic described at Store.Get).
func (*Store[T]) Version ¶
Version is 0 until the asset is committed, 1 after the first commit, and goes up by one with every hot reload that replaced the value (see Options.WatchInterval). Caches of data derived from an asset compare it to notice changes.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package httpfs is a read-only fs.FS over HTTP, for games that load their assets from a web server instead of embedding them: a browser build (js/wasm, where net/http uses fetch) or an editor webview reading the workspace.
|
Package httpfs is a read-only fs.FS over HTTP, for games that load their assets from a web server instead of embedding them: a browser build (js/wasm, where net/http uses fetch) or an editor webview reading the workspace. |