Esta página ainda não foi traduzida para português, por isso a versão em inglês é exibida abaixo.
Núcleo 2Dassets
game/pkg/assetsExperimentalgame/pkg/tooling/assetsExperimentalgame/pkg/tooling/dlcExperimentalgame/pkg/tooling/spriteframesExperimentalgame/pkg/tooling/texseamExperimental
For the trade-offs between resources/, embedded startup files and first-load groups, see Small downloads and fast starts.
game/assets loads sprite atlases, sounds, images, raw bytes, and custom game data asynchronously off the engine goroutine, organizes them into per-scene groups with reactive progress signals, releases them cleanly when a scene ends, and provides a ready-made LoadingScreen component.
import "github.com/nsgo-dev/game/pkg/assets"
All Manager and Group methods run on the engine goroutine; file reading and parsing run in background goroutines and post results back via core.Scope.Post so animations and game.Loop never hitch.
Creating a Manager and defining groups
Create a Manager bound to a *core.Scope (typically your root game component's scope). With no options, "asset:" URIs resolve the same app resources/ files that images (core.Src("asset:...")) and sounds (audio.Source{URI: "asset:..."}) resolve on every target, through core.Scope.ReadAsset (fetched on demand on the web without embedding them in the binary):
mgr := assets.NewManager(cx)
// Register a scene's assets as a named group (all loaded from resources/)
level1 := mgr.Group("level1").
AddAtlas("hero", "asset:hero.json", core.Src("asset:hero.png")).
AddSound("jump", audio.Source{URI: "asset:sounds/jump.wav"}).
AddImage("bg", core.Src("asset:bg.png")).
AddCustom("map", "asset:maps/level1.tmj", parseMap, nil)
Pass assets.WithFS(fsys) to override "asset:" byte reads with an embed.FS or os.DirFS (for example small startup assets embedded in the binary, or os.DirFS(hotreload.DevAssetsDir()) under game dev), or assets.WithReadAsset(fn) for custom storage.
Chainable builders on *Group:
| Method | What it loads |
|---|---|
AddAtlas(name, jsonURI, img) |
Reads & parses sprite.LoadAtlas off-thread, and prefetches img when URI-backed. |
AddSound(name, src) |
Decodes a short sound via audio.LoadSound. |
AddImage(name, src) |
Prefetches a URI-backed core.ImageSource through core.Scope's image loader. |
AddBytes(name, uri) |
Reads raw bytes from uri off-thread. |
AddCustom(name, uri, parse, release) |
Reads uri and parses it off-thread; invokes release(val) on group release or cancellation. |
AddCustomLoader(name, uri, load, release) |
Same as AddCustom, passing a cancellable context.Context to load. |
AddCustomSized(name, uri, parse, release) |
Same as AddCustom, with parse also returning the decoded value's memory size in bytes for WithMemoryTracker. |
For one-off loads outside a group, Manager also exposes LoadAtlas, LoadSound, LoadBytes, and LoadCustom.
Loading, reactive progress, and reading assets
Start a group with mgr.LoadGroup("level1", onDone) or level1.Load(onDone). Loading is idempotent: calling Load on an already-loaded group runs onDone(nil) immediately, and calling it while loading queues onDone onto the active load.
Every status method on *Group is backed by a core.Signal, so reading them inside an NSGo view subscribes automatically:
g.Progress()(float64in[0, 1])g.Loaded()andg.Total()(int)g.Loading(),g.Done()(bool), andg.Err()(error)
Once loaded, retrieve typed assets from the group or from Manager (which searches the most recently registered group holding name):
heroAtlas, ok := mgr.Atlas("hero")
jumpSound, ok := mgr.Sound("jump")
bgImage, ok := mgr.Image("bg")
rawLevel, ok := mgr.Get("map")
Releasing groups
Release a scene's assets when leaving the scene with mgr.ReleaseGroup("level1") (or level1.Release(), or mgr.ReleaseAll()):
mgr.ReleaseGroup("level1")
Releasing closes every loaded *audio.Sound, calls custom release hooks, drops atlas/image/byte references for garbage collection, cancels any in-flight load, and resets progress to 0 so the group can be loaded again later. Disposing Manager's cx scope releases all groups automatically and discards late completions without leaking.
Keeping decoded atlas images pinned outside NSGo's 64-source canvas cache is tracked in nsgo#1127.
Tracking decoded asset memory
Pass a gamedebug.MemoryTracker to the manager to account for every successfully loaded group asset automatically, and optionally set an OnBudget callback:
mem := debug.NewMemoryTracker()
mem.SetBudget("level1", 64<<20)
mem.SetTotalBudget(256 << 20)
mgr := assets.NewManager(cx,
assets.WithMemoryTracker(mem),
assets.WithOnBudget(func(group string, err error) {
if group == "" {
log.Printf("total asset memory budget: %v", err)
return
}
log.Printf("%s asset memory budget: %v", group, err)
}),
)
Atlases and images are tracked as decoded RGBA pixels (width × height × 4), using the atlas's meta.size (PageWidth and PageHeight) or the image header read during loading. Sounds use the decoded PCM estimate exposed by the current NSGo API (duration at 44.1 kHz, 16-bit stereo). Raw bytes use their exact length. Ordinary custom assets use MemoryBytes() int64 when implemented, byte or string length when applicable, and otherwise the source length; use AddCustomSized when the parser knows the decoded size. Negative custom sizes are clamped to zero.
Repeated loads replace same-name entries rather than adding them again. Reload, ReloadAsset, and ReloadGroup update sizes after successful replacements. Failed group loads remove partial accounting; failed reloads preserve the previous assets and their accounting. Release, Reset, manager disposal, and failed group loads untrack their assets. Calling SetFS with a different file system also untracks the group's currently loaded assets, while setting the one already mounted changes nothing; call Release and Load to load and account for assets from the new file system.
The budget callback fires once when a load or reload crosses a group budget or the total budget, and fires again only after usage returns within that budget and crosses it again. An empty group argument identifies the total budget. Crossing a budget never refuses a load; the debug overlay highlights the over-budget group and total. Tracking and callbacks compile to no-ops under -tags release.
LoadingScreen
Drop assets.LoadingScreen (or assets.LoadingView(cx, props)) directly into your component tree to start loading a group on mount, render a reactive progress bar, and transition once ready:
return assets.LoadingScreen{
Manager: mgr,
Group: "level1",
Title: "Loading Cavern",
OnReady: func() {
stage.Set("play")
},
OnError: func(err error) {
loadErr.Set(err)
},
}
Set View: func(progress float64, err error) core.Node on LoadingScreen (or Render on LoadingScreenProps) to replace the default progress UI with your own branded loading view.
Reloading on save
Run the game with go tool game dev and start a watcher on the asset directory it names, and every atlas, image and raw-bytes asset the manager has loaded changes in the running game within a second of its file being saved:
var opts []assets.Option
if dir := hotreload.DevAssetsDir(); dir != "" {
// Under game dev, read "asset:" URIs from the directory the watcher watches.
opts = append(opts, assets.WithFS(os.DirFS(dir)))
}
mgr := assets.NewManager(cx, opts...)
w := hotreload.NewDevWatcher(cx) // nil outside game dev and in release builds
w.WatchAssets(mgr, func(path string, names []string, err error) {
if err != nil {
log.Printf("reload %s: %v", path, err)
}
})
The watcher and the manager must see the same files: a Manager without WithFS reads "asset:" URIs from the app's packaged resources/ through core.Scope.ReadAsset, so under game dev pass assets.WithFS(os.DirFS(hotreload.DevAssetsDir())), the absolute path of the directory game dev watches, as above (this also lets ReloadAsset and ReloadGroup re-read edited files synchronously). WatchAssets passes each changed file under the directory to Manager.Reload as "asset:<path>" on the engine goroutine. An atlas whose JSON changed is parsed again, and one whose image changed draws the file's new bytes with the same frames; the *sprite.Atlas the group holds is updated in place, so code that kept the pointer draws the edit. JSON that no longer parses keeps the previous frames and reports the error. Images show the new bytes and raw bytes are replaced; sounds and custom assets load again only when their group does. An image that ships in several densities (Scales) reloads from the file the screen shows, such as hero@2x.png on a 2x screen; saving another density changes nothing until the screen shows it. A group mounted on a DLC pack with SetFS keeps the pack's copy of a file the pack has, so saving the base file does not change it. Manager.Revision counts the reloads that replaced something, so a core.Canvas that reads it in Draw draws again after each one; a game drawn every frame by game.Loop needs nothing more.
For an atlas the game loads itself, such as one embedded with go:embed, w.WatchAtlasFiles("sprites.json", "sprites.png", img, onReload) delivers the atlas parsed from the saved files. For WGSL/Kage shaders and 3D shader materials, attach hotreload.ShaderReloader and hotreload.MaterialReloader with w.WatchShaders and w.WatchMaterials; see Hot-reloading shaders and materials. NewDevWatcher returns nil when the game is not running under game dev, and a nil watcher's methods do nothing, so the calls can stay in the game; in release builds (-tags release) they compile to nothing.
Downloadable packs (DLC)
Build a pack from the encoded asset directory with a versioned definition. The builder sorts paths and fixes ZIP timestamps, so repeated builds are byte-identical. Set GAME_PACK_KEY to an Ed25519 private key in hex or base64 to sign the archive digest. game dlc verify checks the local archives, hashes and signatures before upload.
version: 1
id: forest
group: forest
packVersion: 1.2.0
minBuild: 42
include: [levels/forest/**, music/forest/**]
exclude: ["**/*.psd"]
go tool game dlc build packs/forest.pack.yaml -root resources -out dist/packs -url https://cdn.example.com/packs/
go tool game dlc verify dist/packs/manifest.json -key "$GAME_PACK_PUBLIC_KEY"
assets.NewDLCManager(assets.DLCOptions{...}) downloads ZIP packs described by a PackSpec (usually parsed from a manifest with ParsePackManifest), resumes interrupted downloads with HTTP Range requests, verifies size, SHA-256 and an Ed25519 signature, and caches them in a PackCache. Fetch returns the verified pack as an fs.FS; FetchGroup also mounts it into a Group and loads it.
dlc := assets.NewDLCManager(assets.DLCOptions{
AppBuild: 42,
PublicKey: packPublicKey,
Cache: assets.NewDirPackCache(cacheDir),
Limits: assets.PackLimits{MaxTotalBytes: 256 << 20},
})
group, err := dlc.FetchGroup(ctx, mgr, spec, registerAssets, onProgress)
- Without a
PublicKey, every pack is refused withErrInvalidSignature, because whoever supplies thePackSpec(URL, size and hash) would otherwise choose what is mounted. SetAllowUnsignedto accept unsigned packs during development or when the specs ship inside the app. - A cached pack is verified again on the same reader that is mounted.
DirPackCachereads a mounted pack through one open file, so replacing or deleting the cache file afterwards does not change what the mount serves (on Windows, deleting a mounted pack fails until it is released). - The
fs.FSthatFetchreturns is also anio.Closer. Close it when the pack is no longer used; one never closed is released when it is garbage collected.FetchGrouphands its pack to the group, which releases it onGroup.Reset,Group.SetFS, the nextFetchGroupinto the same group, or when the asset manager's scope is disposed.Removeof a pack that is still mounted deletes its partial download at once and the cached pack when the last mount is released, so it never pulls the bytes from under a loaded group; aFetchof the pack before then keeps it. Limitscaps the number of entries, the size of one file, the total unpacked size and the archive itself (zero fields useDefaultPackLimits(): 32768 entries, 256 MiB, 1 GiB and 1088 MiB). A pack over a limit is refused before mounting. A download stops withErrPackTooLargeonce it would passMaxPackBytes, which bounds the.partfile of aPackSpecwithout aSize. A mounted pack reads each file as it decompresses, growing its buffer with the bytes that arrive rather than allocating the size the header claims, and fails withErrPackTooLargepastMaxFileBytes.- A spec that could never verify (a malformed
sha256orsignature, or a negativesize) is refused before the cache is touched, so it cannot delete a good cached pack. A cached pack is deleted only when its bytes do not match the spec's size or hash; one whose bytes match but whose signature or contents are refused stays, since downloading it again would fetch the same bytes. - A resumed download that gets
206 Partial Contentwithout aContent-Rangeheader starts over from the first byte rather than appending a body whose range it cannot check. ParsePackManifestrefuses fields it does not define, such as a misspeltsha265, a key given twice in one object, and anything after the manifest, with the line and a fix.
Sprite frame processing
Frames from a renderer, a video model or a capture usually need cleanup before they make a usable sheet: a keyed background, a loop seam that jumps, and a subject that drifts by a few pixels inside the canvas. go tool game sprite frames -in frames -out build/sprites -name hero reads a directory of PNG frames in name order, or an animated GIF composited the way a player shows it, and writes hero.png and hero.json (an atlas that sprite.LoadAtlas reads, with frames hero_000, hero_001 and so on) and hero.animation.yaml (a flipbook clip built with animclip.FromFrames). The same steps are pure functions in pkg/tooling/spriteframes for callers that hold the frames in memory. Video decoding is out of scope: export the video as PNG frames first.
-key '#00ff00'makes the key colour transparent. A pixel within-tolerance(RGB distance, default 32) of it is cleared, one within the following-softness(default 16) keeps part of its alpha, and each pixel is judged on its own, so key-coloured holes enclosed by the subject are cleared too.-despill 1pulls the key's dominant channel down to the larger of the other two on edge pixels, removing the coloured fringe; values between 0 and 1 remove part of it.-seamkeeps only the run of frames whose end best matches its start, comparing luminance thumbnails at most 96 pixels on a side, and drops the end frame, so a sequence rendered one frame too long loses its duplicate.-min-framesand-max-framesbound the loop.-anchor bottom-center(the default) or-anchor centercrops each frame to its visible pixels and places it at the same point of a cell as large as the largest frame, and writes that point as each atlas frame's pivot.-widthand-heightscale every frame with nearest-neighbor sampling, which keeps hard edges for pixel art; scaling runs after keying and before the anchor.
| Symptom | Cause | Fix |
|---|---|---|
| The character jitters in place | The subject drifts inside the source canvas | -anchor bottom-center (on by default) |
| The loop stalls on one frame | The last frame repeats the first | -seam |
| The loop jumps back | The sequence does not end where it starts | -seam, or render a longer take for it to choose from |
| A coloured halo around the subject | Key colour blended into the edge pixels | -despill 1, a larger -softness |
| Background speckles remain | Compression noise moved pixels away from the key | A larger -tolerance |
| Holes appear in the subject | -tolerance reaches colours of the subject |
A smaller -tolerance, or a key colour the subject does not use |
| Pixel art shimmers | Frames were scaled with filtering | -width and -height, which sample nearest-neighbor |
Image collision and named points
An atlas source PNG may carry a *.import.yaml sidecar configuring baked 2D collision shapes (image.collision) and named image points (image.points, with optional per-cell overrides in image.cellPoints for sliced sheets):
version: 1
image:
slice: {width: 16, height: 16}
collision:
mode: alpha # alpha, box, ellipse, polygon, or none
tolerance: 0 # alpha cutoff [0..255]; pixels with alpha > tolerance are solid
maxVertices: 8 # max vertices per convex polygon (3..8, default 8)
cells:
- cell: 1
mode: box
points:
muzzle: [14, 6]
feet: [8, 16]
cellPoints:
- cell: 1
points:
muzzle: [15, 5]
When go tool game assets or go tool game pack builds the atlas, it traces pixel alpha silhouettes with marching squares, simplifies contours, splits concave outlines into convex polygons of at most maxVertices vertices, and writes shapes and points into each frame of the packed JSON. Sidecars refuse unknown fields and validate against import.v1.json. In the editor, selecting the image in the file browser overlays the traced collision outline and named points over the sprite and lets you drag points directly on the preview canvas.
Remote assets
For loose files hosted on a CDN (such as music tracks or per-level art kept out of mini-game or web bundles), configure assets.remote in game.yaml so go tool game assets copies them to content-hashed paths (<name>.<hash8>.<ext>) and writes a sorted, versioned remote.yaml manifest, then pass assets.WithRemote when creating the Manager:
manifest, err := assets.ParseRemoteManifest(remoteManifestYAML)
if err != nil {
return err
}
cache := assets.NewDirRemoteCache(cacheDir) // default 200 MiB quota
mgr := assets.NewManager(cx, assets.WithRemote(assets.RemoteOptions{
Manifest: manifest,
Cache: cache,
}))
- Any URI listed in
Manifest(bytes, custom assets, images, atlas JSON/images, and sounds) is fetched fromBase(defaulting toManifest.Base) using its content-hashed path, checked against exact byte size and SHA-256 (ErrSizeMismatch/ErrHashMismatch), and stored inCache. URIs not inManifestfall through to local sources (WithReadAsset,WithFS, or packagedresources/). - A cached file whose bytes still match the manifest's size and SHA-256 is served without a network request, allowing offline startups once cached. A corrupted or truncated cache entry is removed and re-fetched automatically.
- Concurrent loads for the same content digest share a single in-flight request; cancelling one waiter leaves sibling waiters running, and cancelling the last waiter aborts the underlying fetch.
RemoteOptions.Fetch(func(ctx context.Context, url string) (io.ReadCloser, int64, error)) is the transport seam, defaulting tonet/http. Targets withoutnet/http(such as mini-program runtimes) can plug in their host request API directly.DirRemoteCacheenforcesQuota(200 MiB by default, matching mini-game filesystem caps) with least-recently-used eviction that never removes files pinned by a loaded or loadingGroup, writes files atomically via temporary files, persists access times in a smallindex.yamltext index, and exposesUsage()(Bytes,Quota,Files,PinnedBytes) andClear()for a settings screen. UseMemoryRemoteCacheon targets without local disk storage (such as the web).
Memory budgets
Manager.SetBudget(totalBytes, perGroupBytes) enforces decoded asset memory at load time in every build. A load that would exceed either limit fails with *assets.MemoryBudgetError. Call Manager.Over() to inspect current usage, mark groups with group.SetEvictable(true), and call Manager.MemoryPressure() to release evictable loaded groups during simulated or platform memory pressure.
Delivery per export preset
An export preset in game.yaml can say where each asset group ships: delivery.main lists the groups in the main package, delivery.subpackages maps each subpackage name to its groups, and delivery.remote lists the groups served from the remote origin. delivery.caps sets the largest size of the main package (main) and of all packages together (total) in bytes. A group may appear in only one of these places, and a subpackage name has no spaces; see Asset delivery for the format. game.yaml records and checks this placement only: game release does not yet lay files out per package or enforce the caps, and Manager.LoadGroup does not yet load a subpackage through the host.
tooling/refs.ParseLFSPointer recognizes Git LFS pointers and exposes the underlying SHA-256 and declared size so index and loader tooling can report unfetched content clearly.
Group.ByteProgress() returns the decoded bytes of the group's loaded assets and the estimated total for byte-oriented progress displays. Sizes are known only once an asset has loaded, so the total grows during the load and is 0 until the first asset finishes; fall back to Progress() while it is 0. Loading views retry failed groups when remounted.
Seamless tiles and derived maps
github.com/nsgo-dev/game/pkg/tooling/texseam provides deterministic image tooling for tiles and lit sprites. texseam.Check compares each wrap edge with interior neighbor differences and reports a pass when both ratios are at most 1.3; texseam.Fix feathers opposite edges toward a matching seam. texseam.Merge limits an edited tile to a feathered center cross, preserving the original outside that band.
Use texseam.Height to derive grayscale height from blurred luminance, texseam.Normal to make an RGBA8 tangent-space map, and texseam.Roughness to make an inverted contrast-stretched grayscale map. Height and Normal take texseam.Wrap for repeating textures, so the derived maps stay seamless, or texseam.Clamp for sprites. A flat area encodes as (128, 128, 255); pass texseam.GreenUp for a render3d material's normal texture (glTF, +Y up) and texseam.GreenDown for lights2d.ShadeNormalMap (screen y down).
The game tex command exposes the same deterministic operations. -seamless-check prints both ratios and exits non-zero when a tile fails, -seamless-fix writes a repaired PNG, and -normal or -roughness writes a derived PNG beside the source or at -out.
Export package delivery and caps (#1735)
pkg/tooling/assets.Layout produces a deterministic package report from measured asset groups and an export preset's delivery mapping. Unmentioned groups stay in main; named subpackages and remote groups are reported separately. AssetCaps.Main and AssetCaps.Total fail the layout with a report listing the exceeded byte limits, before a release is published. Files are sorted by path within each package, and subpackages by name, for stable CI output. A subpackage named main is refused, since its groups would otherwise be merged into the main package.