# NSGo Game documentation --- Source: http://nsgo.games/docs/ # Overview For download size, loading groups and web caching, see [Small downloads and fast starts](http://nsgo.games/docs/small-downloads/). game is a pure-Go 2D and 3D game layer for [NSGo](https://nsgo.dev) apps. A game draws into one NSGo view—a `Canvas`, a pixel buffer, a shader or a GPU view—while its HUD and menus stay ordinary native NSGo views on top. It uses only NSGo's public API (`core`, `audio`, `gamepad`, and GPU views), so an app that does not import it links none of it. > NSGo Game requires Go 1.27+ and a compatible NSGo release. [API Stability](http://nsgo.games/docs/stability/) says which packages are stable and which are experimental. Start with [Getting Started](http://nsgo.games/docs/getting-started/) to build and run a game, pick one of the [starter templates](http://nsgo.games/docs/templates/), follow the [tutorial](http://nsgo.games/docs/tutorial/), use the [Teaching and game jams](http://nsgo.games/docs/teaching-and-jams/) checklist, or browse the [genre guide](http://nsgo.games/docs/genres/) to map a game idea to packages and examples. > These docs follow `main` and may describe unreleased APIs. To use them, add `github.com/nsgo-dev/game@main` to your game module. Published releases may differ. ## 2D and 3D 1. **2D**: a fixed-step loop, input actions, sprites, tilemaps, scenes, physics, lighting, particles, UI and sound, drawn at 60 fps or the display's rate. 2. **3D**: meshes, cameras, PBR lighting, skeletal animation, 3D physics, terrain, voxels and glTF models drawn with depth on NSGo's GPU view. See [3D Models from Blender](http://nsgo.games/docs/3d-models-blender/) for coordinate conventions, Blender 4.x export settings, FBX/OBJ conversion and sample glTF assets, and [Lantern 3D](https://github.com/nsgo-dev/game/tree/main/examples/lantern3d) for an interactive glTF 3D scene example with orbit camera, dynamic lighting, a native HUD, and 2D ↔ 3D scene switching with shared input and sound. The loop, input actions, sound, assets and scene switching are shared by both 2D and 3D, so you can combine 2D and 3D scenes in one game without rewriting its structure. Every author-facing file—scenes, prefabs, materials, animations, tables and project settings—is plain-text versioned YAML ([File Formats](http://nsgo.games/docs/formats/)), editable by hand, with coding agents, or in the visual [Scene Editor](http://nsgo.games/docs/editor/). ## Packages | Package | Import path | Guide | What it holds | | --- | --- | --- | --- | | `game` | `github.com/nsgo-dev/game` | [Loop](http://nsgo.games/docs/loop/) | `Loop`, the fixed-step loop every package shares | | `sprite` | `github.com/nsgo-dev/game/pkg/sprite` | [sprite](http://nsgo.games/docs/sprite/) | Atlases, frames, animations, sprites and batches drawn into a `Canvas` | | `sound` | `github.com/nsgo-dev/game/pkg/sound` | [sound](http://nsgo.games/docs/sound/) | The `Mixer`, its effects and music | | `input` | `github.com/nsgo-dev/game/pkg/input` | [input](http://nsgo.games/docs/input/) | Named actions and axes from touch regions, mouse buttons, keyboard keys, pointer-lock mouselook and game controllers, persisted in `core.Storage` | | `tilemap` | `github.com/nsgo-dev/game/pkg/tilemap` | [tilemap](http://nsgo.games/docs/tilemap/) | 2D `Camera`, culled tilemaps, Tiled `.tmj` loader, animated tiles and raycasts | | `scene` | `github.com/nsgo-dev/game/pkg/scene` | [scene](http://nsgo.games/docs/scene/) | World/screen layers, hit testing, scene stacks and animated transitions | | `sceneformat` | `github.com/nsgo-dev/game/pkg/sceneformat` | [Scene format](http://nsgo.games/docs/formats/#scene) | Versioned YAML scene documents: strict parsing and validation, deterministic encoding and building into sprite batches ready to draw | | `editor` | `github.com/nsgo-dev/game/pkg/editor` | [Scene Editor](http://nsgo.games/docs/editor/) | The NSGo Scene Editor over `sceneformat`: undoable scene, tilemap, layer and property editing, play-in-editor, asset browser, plugins and project panels | | `editor/theme` | `github.com/nsgo-dev/game/pkg/editor/theme` | [Design tokens](http://nsgo.games/docs/editor/#design-tokens-1002) | The editor's design tokens: the embedded YAML theme, the dark and light palettes, type, spacing, shape and motion constants, and the WCAG 2.2 contrast table every palette meets | | `editor/keychain` | `github.com/nsgo-dev/game/pkg/editor/keychain` | [Build and release screen](http://nsgo.games/docs/editor/#build-and-release-screen-1048-1050) | The editor's OS secret storage: macOS Keychain, Linux Secret Service and Windows Credential Manager behind one `Store`, with an in-memory `Memory` for tests | | `motion` | `github.com/nsgo-dev/game/pkg/motion` | [scene](http://nsgo.games/docs/scene/#motion-behaviors-in-scene-files) | Deterministic, rate-independent 2D motion helpers (`Bullet`, `Sine`, `Rotate`, `Orbit`, `MoveTo`, `Wrap`, `Bound`, `DestroyOutside`, `Fade`, `Flash`) backing scene behaviors | | `physics` | `github.com/nsgo-dev/game/pkg/physics` | [physics](http://nsgo.games/docs/physics/) | `Box`/`Circle` overlaps, `MoveAndSlide` tile resolution and `World` queries | | `physics3d` | `github.com/nsgo-dev/game/pkg/physics3d` | [physics3d](http://nsgo.games/docs/physics3d/) | Deterministic 3D collision detection, raycasts, rigid-body dynamics and a kinematic character controller | | `platformer` | `github.com/nsgo-dev/game/pkg/platformer` | [platformer](http://nsgo.games/docs/platformer/) | Platformer `Controller` on `CharacterBody`: coyote time, jump buffer, variable jump height, wall slide and wall jump from a YAML config | | `screen` | `github.com/nsgo-dev/game/pkg/screen` | [screen](http://nsgo.games/docs/screen/) | Virtual resolution `Viewport` scaling, pixel snapping, safe-area rectangles and video settings | | `project` | `github.com/nsgo-dev/game/pkg/project` | [Project File](http://nsgo.games/docs/project/) | `game.yaml`, the one project file: window, virtual resolution, input map, audio buses, autoloads and export presets, kept in step with `nsgo.yaml` | | `tooling/refs` | `github.com/nsgo-dev/game/pkg/tooling/refs` | [Stable references](http://nsgo.games/docs/project/#stable-references) | Stable file IDs, the project index and moves that rewrite every reference to a file, behind `game mv`, `game index` and `game check` | | `assets` | `github.com/nsgo-dev/game/pkg/assets` | [assets](http://nsgo.games/docs/assets/) | Async per-scene asset groups, reactive progress and `LoadingScreen` | | `resource` | `github.com/nsgo-dev/game/pkg/resource` | [resource](http://nsgo.games/docs/resources/) | Shared YAML resource files (materials, curves, gradients, animation clips, UI themes, bus layouts, physics materials) and a `Library` that shares and reloads them | | `importsettings` | `github.com/nsgo-dev/game/pkg/importsettings` | [Import settings sidecar](http://nsgo.games/docs/formats/#import-settings-sidecar) | `.import.yaml` sidecars beside an image, sound, font or model that say how `game assets` imports it, overriding the target's settings | | `ktx2` | `github.com/nsgo-dev/game/pkg/ktx2` | [tex](http://nsgo.games/docs/cli/#tex) | KTX2 texture container encoding and decoding, mipmap chains, Basis Universal ETC1S and UASTC codecs and transcoding to BC, ETC2 and ASTC blocks | | `loaderr` | `github.com/nsgo-dev/game/pkg/loaderr` | [Errors](http://nsgo.games/docs/errors/) | The error every loader returns for a file it cannot use: file, line, column, field, what was expected and how to fix it | | `text` | `github.com/nsgo-dev/game/pkg/text` | [text](http://nsgo.games/docs/text/) | AngelCode BMFont bitmap fonts, signed-distance-field fonts in 2D and 3D world space, and platform text via `DrawPlatform` | | `placeholder` | `github.com/nsgo-dev/game/pkg/placeholder` | [Placeholder Assets](http://nsgo.games/docs/placeholder/) | A CC0 pack of sprite sheets, a tileset and level, a pixel font, sounds and glTF models, with their import settings sidecars, to prototype with | | `particles` | `github.com/nsgo-dev/game/pkg/particles` | [particles](http://nsgo.games/docs/particles/) | Seeded deterministic 2D `Emitter`, spawn shapes, bursts and lifetime curves | | `pixelfx` | `github.com/nsgo-dev/game/pkg/pixelfx` | [pixelfx](http://nsgo.games/docs/pixelfx/) | A Go port of pixelfx's pixel art effects: the painter, simulation and acting system, effects by category (`pixelfx/fire`, `pixelfx/explosions`, ...), recoloring, mirroring and sprite sheet export | | `bullets` | `github.com/nsgo-dev/game/pkg/bullets` | [bullets](http://nsgo.games/docs/bullets/) | Shooter bullet patterns (rings, spirals, aimed bursts) from YAML, pooled and drawn through a sprite batch | | `save` | `github.com/nsgo-dev/game/pkg/save` | [save](http://nsgo.games/docs/save/) | Versioned JSON save slots, schema migrations and atomic backup recovery | | `achievements` | `github.com/nsgo-dev/game/pkg/online/achievements` | [achievements](http://nsgo.games/docs/achievements/) | Achievements declared in versioned YAML, monotonic progress persisted in `core.Storage`, and reporting to Game Center and Play Games | | `datatable` | `github.com/nsgo-dev/game/pkg/datatable` | [datatable](http://nsgo.games/docs/datatable/) | Typed data tables in versioned YAML (and CSV/JSON) with cell-level errors, deterministic saves and hot reload | | `tooling/gamedebug` | `github.com/nsgo-dev/game/pkg/tooling/gamedebug` | [gamedebug](http://nsgo.games/docs/gamedebug/) | Frame-time graph, wireframe shapes, scene inspector and `-tags release` stripping | | `mcp` | `github.com/nsgo-dev/game/pkg/mcp` | [mcp](http://nsgo.games/docs/mcp/) | MCP tools registered through `nsgo/automation` to inspect running scenes, layers, entities and components | | `flow` | `github.com/nsgo-dev/game/pkg/flow` | [flow](http://nsgo.games/docs/flow/) | Game-clock `Timers`, `Machine[S]`, `Seq`/`Parallel`/`Race` and typed event `Bus` | | `dialogue` | `github.com/nsgo-dev/game/pkg/dialogue` | [dialogue](http://nsgo.games/docs/dialogue/) | Yarn Spinner scripts run line by line and choice by choice, with variables, conditions, game commands and saved `State` | | `entities` | `github.com/nsgo-dev/game/pkg/entities` | [entities](http://nsgo.games/docs/entities/) | Zero-reflection ECS: generational entities, typed sparse-set components, allocation-free queries, ordered systems, prefabs and JSON snapshots | | `stats` | `github.com/nsgo-dev/game/pkg/stats` | [stats](http://nsgo.games/docs/stats/) | Base stats with add/mul/override modifiers from sources, recomputed on change, timed modifiers on the fixed step and a YAML stats file | | `tags` | `github.com/nsgo-dev/game/pkg/tags` | [tags](http://nsgo.games/docs/tags/) | Gameplay tags: a strict versioned YAML registry of dotted hierarchical names, reference-counted containers that match parents and children, and all/any/none queries | | `tween` | `github.com/nsgo-dev/game/pkg/tween` | [tween](http://nsgo.games/docs/tween/) | Fixed-step `Tween`, `Timeline` and camera choreography helpers | | `animclip` | `github.com/nsgo-dev/game/pkg/animclip` | [animclip](http://nsgo.games/docs/animclip/) | Animation clips that key any registered property, played on scene objects through `tween.Timeline` | | `skeletal` | `github.com/nsgo-dev/game/pkg/skeletal` | [skeletal](http://nsgo.games/docs/skeletal/) | 2D skeletal rigs in versioned YAML, loaded, saved, animated and drawn through `sprite.Batch` | | `cards` | `github.com/nsgo-dev/game/pkg/cards` | [cards](http://nsgo.games/docs/cards/) | Drag and drop between board slots with snap and return, fanned hands, decks, piles and grids, and YAML board files | | `rooms` | `github.com/nsgo-dev/game/pkg/rooms` | [rooms](http://nsgo.games/docs/rooms/) | Room maps with per-room camera bounds and cut, slide or fade transitions between them | | `ai` | `github.com/nsgo-dev/game/pkg/ai` | [ai](http://nsgo.games/docs/ai/) | Steering behaviors, ORCA avoidance, behavior trees, utility AI, GOAP, tactical queries and perception | | `ai/perception3d` | `github.com/nsgo-dev/game/pkg/ai/perception3d` | [ai](http://nsgo.games/docs/ai/#3d) | `ai` perception for 3D agents on `math3d.Vec3`, with `physics3d` line of sight | | `ai/cover3d` | `github.com/nsgo-dev/game/pkg/ai/cover3d` | [ai](http://nsgo.games/docs/ai/#cover-points-and-generators) | `ai` cover points generated from the colliders of a `physics3d` world on the XZ plane | | `pathfind` | `github.com/nsgo-dev/game/pkg/pathfind` | [pathfind](http://nsgo.games/docs/pathfind/) | Grid `AStar`, HPA*, JPS, graph and waypoint search, 2D `NavMesh` with `NavAgent`, tiled meshes and budgeted path queues | | `pathfind/navbake` | `github.com/nsgo-dev/game/pkg/pathfind/navbake` | [navbake](http://nsgo.games/docs/navbake/) | Bakes `pathfind.NavMesh` polygons from concave obstacles or a tilemap's solid cells for each agent radius, saved as versioned YAML, with a debug overlay | | `rts` | `github.com/nsgo-dev/game/pkg/rts` | [rts](http://nsgo.games/docs/rts/) | Flow fields, a `Crowd` of many units with separation, YAML formations, box/click selection and control groups | | `procgen` | `github.com/nsgo-dev/game/pkg/procgen` | [procgen](http://nsgo.games/docs/procgen/) | Seeded BSP rooms, cellular-automata caves and wave function collapse from YAML rules, with connectivity checks and tilemap painting | | `replay` | `github.com/nsgo-dev/game/pkg/replay` | [replay](http://nsgo.games/docs/replay/) | Input `Recorder`/`Player` with editable YAML recordings and deterministic test assertions | | `statedump` | `github.com/nsgo-dev/game/pkg/statedump` | [statedump](http://nsgo.games/docs/statedump/) | Headless runs dumped as deterministic YAML (entities, components, scene stack, values) and a line `Diff` between runs | | `gametest` | `github.com/nsgo-dev/game/pkg/gametest` | [gametest](http://nsgo.games/docs/gametest/) | Deterministic software rasterizer for `core.DrawOp`, golden PNG assertions with persistent failure diffs, and `ImageDraws` structural checks | | `tooling/playtest` | `github.com/nsgo-dev/game/pkg/tooling/playtest` | [playtest](http://nsgo.games/docs/playtest/) | `playtest.yaml` bots, seeded headless runs with replay recordings, metrics against goals and deterministic YAML reports | | `cutscene` | `github.com/nsgo-dev/game/pkg/cutscene` | [cutscene](http://nsgo.games/docs/cutscene/) | Skippable video cutscenes over the game's view, in a scene or between scenes, from YAML files | | `rhythm` | `github.com/nsgo-dev/game/pkg/rhythm` | [rhythm](http://nsgo.games/docs/rhythm/) | YAML beat maps with tempo and meter changes, a music clock on the audio clock, and per-device audio/video latency calibration | | `undo` | `github.com/nsgo-dev/game/pkg/undo` | [undo](http://nsgo.games/docs/undo/) | Reversible moves with unlimited undo, redo and `Seek`, saved as a YAML `Log` | | `fighting` | `github.com/nsgo-dev/game/pkg/fighting` | [fighting](http://nsgo.games/docs/fighting/) | Per-step input buffer, numpad motion inputs, charges, double taps, chords and combos from YAML move sets | | `math2d` | `github.com/nsgo-dev/game/pkg/math2d` | [math2d](http://nsgo.games/docs/math2d/) | Shared 2D `Vec2`, `Rect`, `Circle` and `Affine` types with lossless `core` conversions | | `random` | `github.com/nsgo-dev/game/pkg/random` | [Determinism](http://nsgo.games/docs/determinism/#2-use-seeded-randomstream-per-purpose) | Seeded cross-platform `Stream` (Xoshiro256**), procedural noise and helpers that verify a simulation is deterministic | | `gameui` | `github.com/nsgo-dev/game/pkg/gameui` | [gameui](http://nsgo.games/docs/gameui/) | In-canvas box-layout menus, virtual-resolution scaling, spatial focus nav and world-anchored views | | `lights2d` | `github.com/nsgo-dev/game/pkg/lights2d` | [lights2d](http://nsgo.games/docs/lights2d/) | 2D ambient darkness, point/cone lights, visibility-polygon shadows and normal-mapped sprites | | `tilemap/tileshape` | `github.com/nsgo-dev/game/pkg/tilemap/tileshape` | [tileshape](http://nsgo.games/docs/tileshape/) | Tilemap collision and lighting geometry: a physics `TileGrid` view, slopes from per-tile shapes, merged outlines and `lights2d` occluders | | `postfx` | `github.com/nsgo-dev/game/pkg/postfx` | [postfx](http://nsgo.games/docs/postfx/) | Kage shader passes chained over the game's frame in one draw, uniforms on the frame clock and CPU reference pictures | | `worldmap` | `github.com/nsgo-dev/game/pkg/worldmap` | [worldmap](http://nsgo.games/docs/worldmap/) | YAML room maps, saved room discovery and markers, a minimap of the current area and a world map | | `fog` | `github.com/nsgo-dev/game/pkg/fog` | [fog](http://nsgo.games/docs/fog/) | Per-team fog of war: shadowcast vision sources, explored versus visible cells, map overlay and JSON saves | | `quality` | `github.com/nsgo-dev/game/pkg/quality` | [quality](http://nsgo.games/docs/quality/) | Low, medium and high presets picked from the device class and measured frame times, overridable in settings | | `sessionstats` | `github.com/nsgo-dev/game/pkg/sessionstats` | [sessionstats](http://nsgo.games/docs/sessionstats/) | Release-safe session metrics: frame-time percentiles, frames over twice the interval, peak heap, runtime memory and GC pauses, as a versioned JSON or YAML summary | | `a11y` | `github.com/nsgo-dev/game/pkg/a11y` | [a11y](http://nsgo.games/docs/a11y/) | Live captions, color-blind palettes and CVD simulation, persisted assist options and accessible menus | | `l10n` | `github.com/nsgo-dev/game/pkg/l10n` | [l10n](http://nsgo.games/docs/l10n/) | JSON string tables with CLDR plurals, script `FontSet`, RTL visual ordering and per-language asset catalogs | | `mempool` | `github.com/nsgo-dev/game/pkg/mempool` | [mempool](http://nsgo.games/docs/mempool/) | Zero-alloc object pools: `Pool`, `Arena` with generational `Handle`s and `SlicePool` | | `spatial` | `github.com/nsgo-dev/game/pkg/spatial` | [spatial](http://nsgo.games/docs/spatial/) | 2D broad phase with `Hash` and `Quadtree`, and viewport culling with `Cull` and `CullBatch` | | `idle` | `github.com/nsgo-dev/game/pkg/idle` | [idle](http://nsgo.games/docs/idle/) | `Number` past float64's range, capped offline progress and short/scientific/locale formatting of large numbers | | `netplay` | `github.com/nsgo-dev/game/pkg/online/netplay` | [netplay](http://nsgo.games/docs/netplay/) | Cross-target WebSocket/UDP/loopback transports, delta replication and lockstep/rollback netcode | | `wsclient` | `github.com/nsgo-dev/game/pkg/online/wsclient` | [wsclient](http://nsgo.games/docs/wsclient/) | Plain WebSocket client for third-party servers, with the same API on native and web targets | | `gameserver` | `github.com/nsgo-dev/game/pkg/online/gameserver` | [gameserver](http://nsgo.games/docs/gameserver/) | Headless fixed-step `Runner` for dedicated servers: several matches at their own rates, overrun reports and bounded signal shutdown | | `audit` | `github.com/nsgo-dev/game/pkg/online/audit` | [gameserver](http://nsgo.games/docs/gameserver/) | Append-only JSON Lines audit log of a server's administrative events: one file per UTC day, a non-blocking queue with a drop counter, retention | | `servicehealth` | `github.com/nsgo-dev/game/pkg/online/servicehealth` | [backend-deploy](http://nsgo.games/docs/backend-deploy/) | Deployment endpoints of online services: `/healthz`, `/readyz` with a database ping and Prometheus `/metrics`, requests by route and status with latency | | `admin` | `github.com/nsgo-dev/game/pkg/online/admin` | [admin](http://nsgo.games/docs/admin/) | Operator access for the self-hosted services: operators.yaml with roles and argon2id passwords, TOTP, session cookies with CSRF checks and admin bearer tokens, and an audit record of every operator call | | `backend` | `github.com/nsgo-dev/game/pkg/online/backend` | [backend](http://nsgo.games/docs/backend/) | One embeddable `http.Handler` that mounts the online services under their prefixes and serves authenticated, compiled game RPCs at `POST /v1/rpc/{name}` | | `accounts` | `github.com/nsgo-dev/game/pkg/online/accounts` | [accounts](http://nsgo.games/docs/accounts/) | Self-hosted player accounts: guests upgraded to email or a linked platform/OAuth identity, argon2id passwords, SQLite/Postgres stores and Ed25519 tokens game servers verify offline | | `cloudsave` | `github.com/nsgo-dev/game/pkg/online/cloudsave` | [cloudsave](http://nsgo.games/docs/cloudsave/) | Self-hosted cloud saves behind `liveops.CloudSync`: per-account slots over HTTPS, conditional writes that turn concurrent saves into conflicts, size limits, kept versions with restore, SQLite (`cloudsave/sqlitestore`) and Postgres (`cloudsave/pgstore`) stores | | `leaderboard` | `github.com/nsgo-dev/game/pkg/online/leaderboard` | [leaderboard](http://nsgo.games/docs/leaderboard/) | Boards declared once in YAML, scores submitted and native boards shown through Game Center or Play Games | | `leaderboard/selfhost` | `github.com/nsgo-dev/game/pkg/online/leaderboard/selfhost` | [leaderboard/selfhost](http://nsgo.games/docs/leaderboard-selfhost/) | Self-hosted cross-platform leaderboards: all-time, daily and weekly boards with kept past periods, scores authenticated by account tokens and optionally signed by the game server, top-N, around-me and friends queries | | `eos` | `github.com/nsgo-dev/game/pkg/online/eos` | [eos](http://nsgo.games/docs/epic/) | Epic Online Services boundary: exchange-code login, achievements, leaderboards and rich presence over an injected asynchronous driver, results on the engine goroutine | | `presence` | `github.com/nsgo-dev/game/pkg/online/presence` | [presence](http://nsgo.games/docs/presence/) | Rich presence on Steam (`ISteamFriends` via purego) and Discord (pure Go local IPC v1) behind a provider-neutral `Activity` and `Manager` | | `steam` | `github.com/nsgo-dev/game/pkg/online/steam` | [steam](http://nsgo.games/docs/steam-stats/) | Injectable Steamworks boundary for achievements, stats, leaderboard scores and rich presence; games supply the native `Driver` | | `steamworks` | `github.com/nsgo-dev/game/pkg/online/steamworks` | [steamworks](http://nsgo.games/docs/steamworks/) | One process-wide Steamworks client (purego): init, the per-frame manual-dispatch callback pump, overlay, join and lobby events, `+connect` launch joins, Web API auth tickets and Steam Deck text input, shared by `presence` and `modding` | | `liveops` | `github.com/nsgo-dev/game/pkg/online/liveops` | [liveops](http://nsgo.games/docs/liveops/) | Provider-agnostic crash reports, consent-gated analytics, the `CloudSync` interface and in-app purchases credited into the save | | `economy` | `github.com/nsgo-dev/game/pkg/online/economy` | [economy](http://nsgo.games/docs/economy/) | Server-owned wallets: currencies with balance caps declared in a versioned config, and grants, spends and exchanges applied once per idempotency key | | `records` | `github.com/nsgo-dev/game/pkg/online/records` | [records](http://nsgo.games/docs/records/) | Server-authoritative JSON records per owner, collection and key: optimistic versions, read permissions and all-or-nothing transactions | | `social` | `github.com/nsgo-dev/game/pkg/online/social` | [social](http://nsgo.games/docs/social/) | Server-side social cores: friend and block graph, groups with roles, parties with leader handover, and chat channels with moderation and retention | | `realtime` | `github.com/nsgo-dev/game/pkg/online/realtime` | [social](http://nsgo.games/docs/social/#realtime-notifications) | Notifications to accounts: live delivery to online subscribers and persistent history kept while offline | | `lan` | `github.com/nsgo-dev/game/pkg/online/lan` | [netplay](http://nsgo.games/docs/netplay/) | LAN game advertisements with validated player counts and deterministic TXT metadata for discovery | | `portmap` | `github.com/nsgo-dev/game/pkg/online/portmap` | [portmap](http://nsgo.games/docs/portmap/) | Gateway port-mapping contract for player-hosted servers, with providers for UPnP, NAT-PMP or PCP plugged in per target | | `antiaddiction` | `github.com/nsgo-dev/game/pkg/online/antiaddiction` | [shipping in China](http://nsgo.games/docs/shipping-china/) | Mainland China minor play windows and spending caps by age band, on the server's clock and holiday calendar | | `inventory` | `github.com/nsgo-dev/game/pkg/inventory` | [inventory](http://nsgo.games/docs/inventory/) | Item definitions in YAML, stacking slot containers, typed equipment slots and save snapshots | | `ability` | `github.com/nsgo-dev/game/pkg/ability` | [ability](http://nsgo.games/docs/ability/) | YAML ability sets and a per-step `Caster`: costs, cooldowns, charges, cast and channel times and conditions driven by input actions | | `cues` | `github.com/nsgo-dev/game/pkg/cues` | [cues](http://nsgo.games/docs/cues/) | YAML cue mappings from gameplay tags to particles, sounds, camera shake, sprite flashes and animations, and a client `Player` that suppresses replayed one-shots and reconciles while-active cues after rollback | | `quest` | `github.com/nsgo-dev/game/pkg/quest` | [quest](http://nsgo.games/docs/quest/) | YAML quest books with collect/reach/defeat/talk objectives, prerequisites and rewards, advanced by bus events and saved as snapshots | | `loot` | `github.com/nsgo-dev/game/pkg/loot` | [loot](http://nsgo.games/docs/loot/) | Nested weighted drop tables in YAML with guaranteed drops and hard/soft pity counters on seeded streams | | `rpgdata` | `github.com/nsgo-dev/game/pkg/rpgdata` | [rpgdata](http://nsgo.games/docs/rpgdata/) | RPG database in YAML: classes with level curves and learned skills, actors, skills, enemies and troops, with references checked on load and a linear experience progression | | `battle` | `github.com/nsgo-dev/game/pkg/battle` | [battle](http://nsgo.games/docs/battle/) | Deterministic turn-based battles between a party and a troop: agility order, scoped actions with MP costs, hit and critical rolls on seeded streams, presentation-independent events and snapshots | | `vn` | `github.com/nsgo-dev/game/pkg/vn` | [vn](http://nsgo.games/docs/vn/) | Visual novel presenter: YAML cast of portraits and expressions, name plates, typewriter text box, choices, backlog, auto/skip modes and voice lines | | `modding` | `github.com/nsgo-dev/game/pkg/modding` | [modding](http://nsgo.games/docs/modding/) | Capability-sandboxed TSX `"game"` modding API and `mod.yaml` dependency/lifecycle manager | | `gameplugin` | `github.com/nsgo-dev/game/pkg/gameplugin` | [Plugins](http://nsgo.games/docs/plugins/) | Runtime plugin contract and deterministic installer: API version check, conflict detection, and ordered registration of components, systems, effects, data tables and console commands | | `gameplugin/manifest` | `github.com/nsgo-dev/game/pkg/gameplugin/manifest` | [Plugins](http://nsgo.games/docs/plugins/) | Strict parser, validator and deterministic YAML encoder for Go plugin `plugin.yaml` manifests | | `math3d` | `github.com/nsgo-dev/game/pkg/math3d` | [math3d](http://nsgo.games/docs/math3d/) | 3D vectors, matrices, quaternions, transforms, bounds, rays, frustums and conventions | | `scene3d` | `github.com/nsgo-dev/game/pkg/scene3d` | [scene3d](http://nsgo.games/docs/scene3d/) | 3D node tree, sockets/attachments, dynamic fat-AABB/SAH BVH, Orbit/FPS/ThirdPerson cameras and picking | | `anim3d` | `github.com/nsgo-dev/game/pkg/anim3d` | [anim3d](http://nsgo.games/docs/anim3d/) | 3D pose state machines, 1D/2D blend spaces, bone-masked/additive layers, clip events, IK and root motion | | `world3d` | `github.com/nsgo-dev/game/pkg/world3d` | [world3d](http://nsgo.games/docs/world3d/) | Heightmap terrain, 3D `GridMap`, scattered foliage and floating-origin chunk streaming | | `pathfind3d` | `github.com/nsgo-dev/game/pkg/pathfind3d` | [pathfind3d](http://nsgo.games/docs/pathfind3d/) | Multi-level 3D `NavMesh` with areas, off-mesh links and reusable queries, `NavAgent` groups, and tiled meshes with dynamic obstacles that stream with `world3d` chunks | | `pathfind3d/navbake3d` | `github.com/nsgo-dev/game/pkg/pathfind3d/navbake3d` | [navbake3d](http://nsgo.games/docs/navbake3d/) | Navigation meshes baked from glTF, terrain, `GridMap` and physics level geometry per agent type, saved as YAML a scene names, with debug drawing and `game navmesh` | | `voxel` | `github.com/nsgo-dev/game/pkg/voxel` | [voxel](http://nsgo.games/docs/voxel/) | Chunked 3D voxel worlds with greedy meshing, cross-chunk culling and AO, dirty-chunk editing, DDA raycasting and YAML saves | | `render3d` | `github.com/nsgo-dev/game/pkg/render3d` | [render3d](http://nsgo.games/docs/render3d/) | GPU mesh buffers, textures and samplers, camera uniforms, CPU frustum culling, draw sorting, 0-alloc instancing, LOD hysteresis, debug draw/gizmos, billboards, 3D ribbon trails and GPU budgets | | `scenemodel` | `github.com/nsgo-dev/game/pkg/scenemodel` | [scenemodel](http://nsgo.games/docs/scenemodel/) | Scene file objects drawn in 3D: built-in primitives and glTF models with material overrides, built into a `scene3d` tree with bounds and drawn by a lit, textured renderer | | `gltf` | `github.com/nsgo-dev/game/pkg/gltf` | [3D Models from Blender](http://nsgo.games/docs/3d-models-blender/) | Pure-Go glTF 2.0 and GLB loader: typed accessors, node hierarchy, PBR materials, skins, morph targets, animations and Draco/meshopt compression | | `jsonschema` | `github.com/nsgo-dev/game/pkg/jsonschema` | [Schemas for YAML files](http://nsgo.games/docs/schemas/) | JSON Schemas built from Go types for editors and AI tools, the published scene schema and validation with JSON Pointer paths | | `tooling/library` | `github.com/nsgo-dev/game/pkg/tooling/library` | [Asset and Plugin Library](http://nsgo.games/docs/library/) | A YAML index of shared asset, editor plugin and template packs, checked by digest and installed into a project with their files and `game.yaml` references recorded | | `framedata` | `github.com/nsgo-dev/game/pkg/framedata` | [framedata](http://nsgo.games/docs/framedata/) | Fighting game hitboxes, hurtboxes, hitstun and cancel windows per frame in YAML, resolved deterministically each step | | `vehicle3d` | `github.com/nsgo-dev/game/pkg/vehicle3d` | [vehicle3d](http://nsgo.games/docs/vehicle3d/) | Raycast cars on `physics3d`: wheel suspension, tire friction and a car controller, race checkpoints and laps, and YAML car files and lap ghosts | For a single-page summary of the core APIs, see [Packages](http://nsgo.games/docs/packages/). [Working as a team](http://nsgo.games/docs/teams/) covers version-control setup, scene merges, review gates, CI and release branches. Every loader reports a file it cannot use with the file, line, field and a fix; see [Errors](http://nsgo.games/docs/errors/). [File Formats](http://nsgo.games/docs/formats/) lists every file a game reads or writes, with its version and an example. | `deck` | `github.com/nsgo-dev/game/pkg/cards/deck` | [cards](http://nsgo.games/docs/cards/) | Cards deck and pile helpers | | `farming` | `github.com/nsgo-dev/game/pkg/farming` | [farming](http://nsgo.games/docs/farming/) | Deterministic farming calendar and crop rules | | `gametime` | `github.com/nsgo-dev/game/pkg/gametime` | [gametime](http://nsgo.games/docs/gametime/) | Deterministic game-time calendar clock | | `hostbridge` | `github.com/nsgo-dev/game/pkg/hostbridge` | [shipping](http://nsgo.games/docs/shipping/) | Web host embedding bridge | | `match3` | `github.com/nsgo-dev/game/pkg/match3` | [match3](http://nsgo.games/docs/match3/) | Deterministic match-3 board and level rules | | `mergegame` | `github.com/nsgo-dev/game/pkg/mergegame` | [formats](http://nsgo.games/docs/formats/) | Versioned merge-game chain format | | `placement` | `github.com/nsgo-dev/game/pkg/placement` | [placement](http://nsgo.games/docs/placement/) | Rotated footprint placement grid | | `progression` | `github.com/nsgo-dev/game/pkg/progression` | [progression](http://nsgo.games/docs/progression/) | Deterministic progression packs and unlocks | | `spawn` | `github.com/nsgo-dev/game/pkg/spawn` | [spawn](http://nsgo.games/docs/spawn/) | Deterministic spawn director schedules | For a single-page summary of the core APIs, see [Core packages](http://nsgo.games/docs/packages/). The [API Stability](http://nsgo.games/docs/stability/) table links the rest of the package catalog to its guide. Every loader reports a file it cannot use with the file, line, field and a fix; see [Errors](http://nsgo.games/docs/errors/). [File Formats](http://nsgo.games/docs/formats/) lists every file a game reads or writes, with its version and an example. ## Coming from another engine Each guide maps that engine's scenes, nodes, resources, signals, input maps, physics and export to the packages above: [Godot](http://nsgo.games/docs/from-godot/), [Ebitengine](http://nsgo.games/docs/from-ebitengine/), [Unity](http://nsgo.games/docs/from-unity/) and [Unreal Engine](http://nsgo.games/docs/from-unreal/). For 2D tools, [GameMaker](http://nsgo.games/docs/from-gamemaker/), [Construct](http://nsgo.games/docs/from-construct/) and [RPG Maker](http://nsgo.games/docs/from-rpgmaker/) map rooms, layouts, event sheets, behaviors and the RPG Maker database the same way. ## Install The module needs Go 1.27 and NSGo `v0.4.0` or later: ```sh go get github.com/nsgo-dev/game ``` ## How a frame runs A game is an NSGo component. It starts a `game.Loop` on its scope, which runs on NSGo's `RequestAnimationFrame`: 1. Each display frame adds the time since the last one and runs `Update` once for each whole fixed step it holds, zero or more times. 2. `Update` moves the game's state by the fixed `dt`, advancing animations and timers. 3. `Draw` runs once, with how far the frame falls into the next step, and sets a signal the game's `Canvas` reads, so the canvas draws again without a commit of the view tree. While the window is in the background, the loop runs no updates and the mixer plays nothing; both resume from where they were. ## Targets NSGo Game has six primary build targets—macOS, iOS, Windows, Linux, Android and the web—while HarmonyOS, mini programs, watchOS and tvOS remain experimental targets outside the first stage. Feature availability and CI test coverage differ across targets; see [Platform support](http://nsgo.games/docs/platforms/) for the per-feature matrix and the upstream issues tracking each gap. Consoles (Nintendo Switch, PlayStation and Xbox) are out of scope: their SDKs are under NDA and need C toolchains, and NSGo and this repository are Go only, with no hand-written C. See [Building and Shipping](http://nsgo.games/docs/shipping/) for icons, signing, notarization, store packaging and `nsgo check` across all six build targets, [Release Checklist](http://nsgo.games/docs/releasing/) for package stability and release steps, [Accessibility Guide](http://nsgo.games/docs/accessibility-guide/) for wiring player accessibility settings, GAG/XAG guidelines, pre-release checks and App Store accessibility labels, and [Command Line](http://nsgo.games/docs/cli/) for `go tool game`, which packs atlases, converts audio, generates asset manifests, encodes textures, opens the scene editor, and builds all of a game's assets from `game.yaml`, rebuilding only what changed. ### VR and AR The game layer does not support VR or AR for now ([#495](https://github.com/nsgo-dev/game/issues/495)). Every package draws into one flat NSGo view, a `Canvas` or a GPU view, and reads touch, mouse, keyboard, gamepads and device motion. NSGo currently has no XR runtime on any of its targets, and this repository uses only NSGo's public API and holds no platform code, so it cannot add one itself. XR work here can start once NSGo provides, on at least one runtime (OpenXR on desktop and Android headsets, visionOS, ARKit, ARCore or WebXR): - **An XR session**: starting it, pausing when the headset is taken off or the app loses focus, and ending it. - **Poses**: the head's and each controller's pose every frame, predicted for when the frame is shown, and the runtime's controller and hand input. - **Stereo rendering**: a render target per eye with its own view and projection, drawn by the GPU view at the headset's rate and handed to the runtime's compositor. - **For AR**: the camera's passthrough behind the drawing, detected planes, hit tests against the real world and anchors that stay in place. OpenXR is the runtime to target first, since one API covers headsets on Windows, Linux and Android, three of NSGo's targets; visionOS, ARKit, ARCore and WebXR can follow. The session, poses and stereo rendering come first and are enough for VR; the AR items come after them. With those, this repository would add an XR camera rig to `scene3d` and XR actions to `input`, reusing `math3d`'s transforms for poses. Until then a 3D game runs on a flat screen. ## For language models The site publishes the English docs for language models and coding agents, as [nsgo.dev](https://nsgo.dev/llms.txt) does: [llms.txt](https://nsgo.games/llms.txt) lists every page with a line about it, and [llms-full.txt](https://nsgo.games/llms-full.txt) holds every page's Markdown in one file. Both are built from `docs/en` with the site, so they always match these pages. For coding agents that support Agent Skills, install the game-layer skill with `bunx skills add nsgo-dev/game`; see [Agent Skill](http://nsgo.games/docs/agent-skill/). For setup, build and runtime first-run failures, see [Troubleshooting](http://nsgo.games/docs/troubleshooting/). --- Source: http://nsgo.games/docs/getting-started/ # Getting Started Create an NSGo game, run it on desktop, web, iOS and Android, draw an animated sprite on a fixed-step loop, handle touch and mouse input, and play sound. Coming from another 2D tool? Use the [GameMaker](http://nsgo.games/docs/from-gamemaker/), [Construct](http://nsgo.games/docs/from-construct/), or [RPG Maker](http://nsgo.games/docs/from-rpgmaker/) migration guide to map familiar concepts to the templates, editor, packages, and current feature gaps. For setup failures, see [Troubleshooting](http://nsgo.games/docs/troubleshooting/). ## Requirements - **Go 1.27** or later. - **NSGo `v0.4.0`** or later, which a new project requires and runs as `go tool nsgo` ([Command Line](http://nsgo.games/docs/cli/#install)). - For iOS builds: macOS with Xcode. - For running on Android devices or emulators: `adb` (Android SDK Platform-Tools). Building an `android_arm64` APK needs only Go. Run `go tool nsgo doctor` inside a project to check what toolchains this machine has. ## Create a project Create the project with the `game` command's `new` subcommand ([Command Line](http://nsgo.games/docs/cli/#install)). It writes the starter into a new directory and has Go add the game layer and the `game` tool to its `go.mod`, beside the `nsgo` tool the starter already has: ```sh go run github.com/nsgo-dev/game/cmd/game@latest new mygame cd mygame go tool nsgo dev ``` Inside the created project, `go tool game ` runs the module's pinned `game` tool (for example `go tool game check` or `go tool game generate`). Run `go tool game doctor` to check the project before you build or release it. The starter includes an animated sprite, tap-to-score input, and tests. Its settings live in `game.yaml`, the [project file](http://nsgo.games/docs/project/), which `nsgo.yaml` mirrors. `new` names the game after its directory in both files' `name` and `id` and in the module path; `-name` and `-module` choose others, such as `-module example.com/mygame`. [Command Line](http://nsgo.games/docs/cli/#new) describes every flag, and `-template` starts from another of the [templates](http://nsgo.games/docs/templates/), which `new -list` lists. Change the identifier to your own before you ship the game: edit the game's name and identifier in `game.yaml`, then run `go run github.com/nsgo-dev/game/cmd/game project sync` to write them into `nsgo.yaml`. NSGo's own command writes the same starter from the template module, without the `game` tool: `nsgo init -template github.com/nsgo-dev/game/template -module example.com/mygame mygame`, with an NSGo command that supports [Go module templates](https://nsgo.dev/docs/getting-started/#templates-from-go-modules), such as the installed `nsgo` of v0.4.0 or later. Its `game.yaml` and `nsgo.yaml` name the game `Starter Game` until you edit them. From a checkout of this repository, `go run ./cmd/game new ../mygame` creates a project from the starter in `template/template/`; a command built from a checkout has no version of its own, so the project requires the game layer on the `main` branch, which is never older than the templates in the checkout, unless `-version` names another. From the checkout itself, run the original starter with `go tool nsgo dev ./template/template`. Add `resources/` for files your game loads at runtime and `assets/` for files the tool uses to build the app, such as app icons: ```text mygame/ ├─ go.mod ├─ game.yaml ├─ nsgo.yaml ├─ main.go ├─ project.go ├─ game.go ├─ game_test.go ├─ resources/ │ ├─ hero.png │ ├─ hero.json │ ├─ jump.wav │ └─ theme.m4a └─ assets/ └─ Icon.png ``` Anything under `resources/` is packaged with the app on every target and resolved by `"asset:"` (for example `"asset:hero.png"` or `"asset:sounds/jump.wav"`). Atlas JSON files can be embedded directly into the Go binary with `//go:embed`. ## Run on every target `nsgo dev` builds the app, launches it, and hot-reloads on save. Desktop (this machine's native backend, the default in `nsgo.yaml`): ```sh go tool nsgo dev ``` Web (starts a local dev server on port 8080 and opens the browser): ```sh go tool nsgo dev -target web ``` iOS (simulator, or a connected iPhone signed with `-team` or Xcode's last team): ```sh go tool nsgo dev -target ios_simulator go tool nsgo dev -target ios ``` Android (a connected device or running emulator; pass `-device` when several are attached): ```sh go tool nsgo dev -target android ``` Add `-fps` to any `nsgo dev` command to show NSGo's performance monitor over the running game. To also reload atlases, images and data files in the running game when you save them under `resources/`, run it with `go tool game dev` (after `go get -tool github.com/nsgo-dev/game/cmd/game`) and start a watcher on them with `hotreload.NewDevWatcher`, as [Reloading on save](http://nsgo.games/docs/assets/#reloading-on-save) shows. ## Draw a sprite on a fixed-step loop A game is an NSGo component. It starts a `game.Loop` on its scope, updates state in `Update` at a fixed rate (60 updates a second by default), and triggers a `core.Canvas` redraw from `Draw` through a `core.Signal` without re-committing the view tree. Pack a sprite sheet with TexturePacker or Aseprite (with rotation off), put the PNG in `resources/hero.png`, and embed its JSON with `//go:embed`. If you do not have a sheet yet, you can construct a `*sprite.Atlas` literal directly as shown in the [sprite guide](http://nsgo.games/docs/sprite/). ```go package main import ( _ "embed" "math" "time" "github.com/nsgo-dev/game" "github.com/nsgo-dev/game/pkg/sprite" "github.com/nsgo-dev/nsgo" "github.com/nsgo-dev/nsgo/core" ) //go:embed resources/hero.json var heroJSON []byte func Game(cx *core.Scope) core.Node { atlas, err := sprite.LoadAtlas(core.Src("asset:hero.png"), heroJSON) if err != nil { panic(err) } walk := atlas.Animations["walk"] hero := sprite.NewSprite(walk.Frame()) hero.OriginX = hero.Frame.Width / 2 hero.OriginY = hero.Frame.Height / 2 hero.X, hero.Y = 160, 120 batch := &sprite.Batch{ Atlas: atlas, Sprites: []*sprite.Sprite{&hero}, } x, y := hero.X, hero.Y lastX, lastY := x, y targetX, targetY := x, y alpha := core.NewSignal(cx, 0.0) loop := &game.Loop{ Rate: 60, Update: func(dt time.Duration) { lastX, lastY = x, y dx, dy := targetX-x, targetY-y if dist := float32(math.Hypot(float64(dx), float64(dy))); dist > 1 { step := min(dist, 180*float32(dt.Seconds())) x += dx / dist * step y += dy / dist * step hero.FlipX = dx < 0 walk.Update(dt) hero.Frame = walk.Frame() } }, Draw: func(a float64) { alpha.Set(a) }, } loop.Run(cx) return core.Canvas{ Style: core.Style{FlexGrow: 1, FlexShrink: 1, Background: core.RGB(0x181c24)}, OnPress: func(e core.PressEvent) { targetX = float32(e.Position.X) targetY = float32(e.Position.Y) }, Draw: func(d *core.Drawing, _ core.Size) { a := float32(alpha.Get()) hero.X = lastX + (x-lastX)*a hero.Y = lastY + (y-lastY)*a batch.Draw(d) }, } } func main() { nsgo.Run(Game) } ``` Because `Draw` reads `alpha.Get()`, NSGo redraws only the `Canvas` on each display frame. Interpolating between `(lastX, lastY)` and `(x, y)` keeps movement smooth on 60 Hz, 120 Hz and variable-refresh displays while the simulation stays locked to 60 Hz. ## Handle touch and mouse input `core.Canvas.OnPress` handles taps on phones and clicks on desktops and the web, delivering `e.Position` in the canvas's own points. For continuous pointer tracking, drags or multi-touch, wrap the `Canvas` in a `core.View` that listens to NSGo's pointer and touch handlers (`OnPressDown`, `OnPressUp`, `OnMouseMove`, `OnTouch`, `OnPan`) and layer native HUD views on top with `core.Absolute`: ```go return core.View{ Style: core.Style{FlexGrow: 1, FlexShrink: 1}, OnMouseMove: func(e core.MouseEvent) { if e.PressedButton == core.MouseButtonLeft { targetX, targetY = float32(e.Position.X), float32(e.Position.Y) } }, OnTouch: func(e core.TouchEvent) { if len(e.Touches) > 0 { targetX = float32(e.Touches[0].Position.X) targetY = float32(e.Touches[0].Position.Y) } }, Children: []core.Node{ canvas, core.View{ Style: core.Style{ Position: core.Absolute, Top: core.Pt(12), Left: core.Pt(12), PaddingEnv: core.EnvAll(core.EnvSafeArea), }, Children: []core.Node{ core.Text{Content: "Score: 0", Style: core.Style{Color: core.RGB(0xffffff)}}, }, }, }, } ``` ## Keyboard, controllers and on-screen controls `input.Actions` binds keyboard keys, controller buttons and touch regions to the same named action. `Key` follows the keyboard layout, while `KeyCode` identifies a physical key position: ```go func bindGettingStartedActions(actions *input.Actions) { actions.Bind("jump", input.Key("space"), input.KeyCode("Space"), input.GamepadButton(gamepad.ButtonSouth), input.TouchRegion(core.Bounds{Origin: core.Point{X: 248, Y: 104}, Size: core.Size{Width: 64, Height: 64}}), ) } ``` Call `actions.WatchKeys(cx)` and `actions.WatchGamepads(cx)` once, attach the actions to the game view, and call `actions.Step()` at the start of each fixed update. Combine opposing actions into an axis with `actions.BindAxis("move_x", "left", "right")`. See [input](http://nsgo.games/docs/input/) for event attachment, controller sticks and rebinding. For phone controls, `input.TouchControls` builds buttons, d-pads and sticks from a YAML `TouchLayout` and drives the same actions. Call `BindActions`, attach it after `Actions.Attach`, call `Update(dt)` after `Step`, and resize and draw it with the game canvas. See [on-screen touch controls](http://nsgo.games/docs/input/#on-screen-touch-controls) and the [touch control layout format](http://nsgo.games/docs/formats/#touch-control-layout). ## Play sound with sound.Mixer Create one `sound.Mixer` on the component's scope. It persists master and group volumes in `core.Storage`, mutes automatically when the app moves to the background, and manages both short sound effects (`Effect`) and streaming music (`Music`). Ship audio as WAV, AAC (`.m4a`) or MP3 under `resources/`: ```go mixer := sound.NewMixer(cx, "sound") music := mixer.Music("music") music.Loop = true var jump *sound.Effect audio.LoadSound(cx, audio.Source{URI: "asset:jump.wav"}, func(s *audio.Sound, err error) { if err != nil { return } jump = mixer.Effect(s, "effects", 4) }) ``` Trigger the effect and start music on a user press (on the web, browsers block audio until the first user gesture): ```go started := false // Inside OnPress: if !started { started = true music.Play(audio.Source{URI: "asset:theme.m4a"}, 2*time.Second) } if jump != nil { jump.Play(audio.Voice{Volume: 0.8}) } ``` ## Next steps - Follow the [tutorial](http://nsgo.games/docs/tutorial/), which builds a whole game, Star Catcher, from an empty project to release builds in nine chapters. - Read the package guides for [Loop](http://nsgo.games/docs/loop/), [sprite](http://nsgo.games/docs/sprite/) and [sound](http://nsgo.games/docs/sound/), or the [Core packages](http://nsgo.games/docs/packages/) summary and the package guides linked from [API Stability](http://nsgo.games/docs/stability/). - If more than one person will edit the project, read [Working as a team](http://nsgo.games/docs/teams/) before the first clone or scene merge. - Play and read [Cave Run](https://github.com/nsgo-dev/game/tree/main/examples/caverun), the sample platformer: the loop, input actions on the keyboard, game controllers and on-screen touch controls, a sprite batch, a Tiled map with a camera, scenes, sound groups and a native HUD and pause menu, with a 1000-sprite stress mode and headless tests that play its level to the end. - Explore [Lantern 3D](https://github.com/nsgo-dev/game/tree/main/examples/lantern3d), the 3D glTF scene example: an embedded binary glTF 2.0 diorama loaded with `game/gltf`, uploaded with `render3d.UploadMesh` and `render3d.UploadTexture`, lit through a `render3d.LightRig` (a directional key light, an orbiting warm point light, the shrine's glow and ambient) with render3d's metallic-roughness PBR shading on NSGo's `gpu.View`, with a `scene3d.OrbitController` camera and a native `scene.HUD3D` overlay. - When you are ready to verify all targets and produce release builds for macOS, Windows, Linux, the web, iOS and Android, read [Building and Shipping](http://nsgo.games/docs/shipping/). --- Source: http://nsgo.games/docs/playground/ # Playground The playground starts each built example in an iframe. Its reload contract is deterministic: the first Run uses run 1, Restart increments the run key so the iframe is recreated, and a source-file fragment such as `#game.go` selects that tab. The page keeps the fragment in a shareable URL without changing browser history. Editing an example still happens through the local `go tool nsgo dev -target web` workflow described below. The [playground](https://nsgo.games/playground/) runs this repository's examples in the browser, built for NSGo's web target, with each example's source beside it. To change an example, run it on your machine with the dev server, which rebuilds and reloads it each time you save. ## In the browser Each example has a page of its own, such as `/playground/caverun/`, so its address is the link to share. The page shows: - **The game**, which loads when you press **Run**: its WebAssembly is about 15 MB, so nothing is downloaded before then. Click the game to give it the keyboard. **Restart** loads it again from the start, and **Open in a new tab** runs the build on a page of its own. - **The source**, a tab per file: the example's main package without its tests, then its `nsgo.yaml`. The tab shown is the address's fragment, so `/playground/caverun/#level.go` opens on `level.go`. Each file links to it on GitHub. ### On a phone On touch screens (`pointer: coarse`), the stage shows **Play fullscreen** and a touch hint instead of the keyboard hint: - **Fullscreen and overlay**: Pressing **Play fullscreen** requests native element fullscreen on the stage (Android Chrome and other supporting browsers) and locks the screen orientation to the example's preferred orientation when allowed. Where element fullscreen is unavailable, such as iPhone Safari, the stage opens as a fixed full-viewport (`100dvh`) overlay with an **Exit** button. - **No accidental scrolling**: While mobile play mode is active, page scroll is locked (`overflow: hidden` and `overscroll-behavior: none`) and the stage sets `touch-action: none` so thumb drags on virtual controls or the board neither scroll the page nor cancel the touch. - **Orientation prompt**: Each playground entry declares its preferred orientation (`landscape`, `portrait`, or `any`) in `website/src/content/playground.ts`. When the screen does not match and orientation lock is unavailable, a prompt asks you to rotate your phone (with an option to continue anyway). The site is static, hosted on GitHub Pages, so it compiles nothing: a page runs the build the site was deployed with, from the same commit as the source it shows. ## Edit on your machine With Go 1.27 or later, clone the repository and start an example with the dev server for the web target: ```sh git clone https://github.com/nsgo-dev/game.git cd game/examples/caverun go tool nsgo dev -target web ``` It opens the game in your browser, Chrome and Safari alike, and rebuilds and reloads it each time you save a file of the example or of the root module (`pkg/`), which the examples use through the checkout's `go.work`. A failed build shows its errors over the game until the next save builds. Without `-target web` the example runs as a native app, which reloads in the same way. ## How the builds are made `bun run playground`, from the repository's root, builds each example with `go tool nsgo build -target web` into the example's `dist/playground/`, then copies the site it writes into `website/public/play//`, which Git ignores. The website serves that directory at `/play//` and each example's page shows it in a frame. `bun run playground caverun` builds one example. The website's workflow sets up Go and runs it before building the site, on every push to `main` and every pull request that touches the site, the examples, `pkg/`, `cmd/`, or root `.go` files. In CI a missing build fails the site's build, so a deploy never publishes a page with no game; a local `bun run build` without the builds warns, and the example's page shows the command that makes its build. ## Add an example 1. Put the example under `examples//` with an `nsgo.yaml`, a main package that builds for the web target, and an entry for it in `go.work`. 2. Add `` to `PLAYGROUND_IDS` and its preferred phone `orientation` to `PLAYGROUND_ENTRIES` in `website/src/content/playground.ts`. 3. Give it an entry in `website/src/content/showcase.ts`, whose title and description the playground shows, in English and Chinese. --- Source: http://nsgo.games/docs/packages/ # Core packages This page summarizes the core packages and how their parts behave, from package doc comments. The [API reference](https://nsgo.games/docs/api/) covers every package, and [API Stability](http://nsgo.games/docs/stability/) maps every package to its guide. Every file format the packages read and write is in [File Formats](http://nsgo.games/docs/formats/). ## API reference The [API reference](https://nsgo.games/docs/api/) has a page for each package of `github.com/nsgo-dev/game`, rendered from the doc comments in its source at every build of the site, as `go doc` shows them: the package's doc, an index, then its constants, variables, functions and types, each type with its values, constructors and methods. Every exported identifier has an anchor named as pkg.go.dev names it, `Name` for a constant, variable, function or type and `Type.Name` for a method, a struct field or an interface method, so `https://nsgo.games/docs/api/game/#Loop.Update` is `Loop.Update`. A declaration that only some targets build lists them. Search the site for a declaration such as `NewStore` or a qualified field such as `Loop.Update`. Select the matching symbol below the package result to jump to its definition. Select **API reference** in the search filters to limit results to the reference. Agents read the same reference as JSON at [`/api.json`](https://nsgo.games/api.json): every package with its synopsis and doc, and every declaration with its anchor, its gofmt-formatted source, its doc comment, its file and line below the repository root, and the targets that build it when not all of them do. Its `version` field is 1 and changes when a field is removed or changes meaning. To write it from a checkout, run at the repository root: ```sh go run ./tools/gameapi -out api.json ``` `-html` adds each doc comment rendered as HTML, as the site's pages show it. The reference is read from the files the linux, macos, windows, android, ios and web targets build in a development build; packages main, `internal` directories and `testdata` are left out. Library packages expose runnable examples for their main entry points: `Example` functions in its `example_test.go` that show the main use of its types. They appear with the package's Go doc (on pkg.go.dev, for instance), and `go tool nsgo test` runs each one and checks what it prints against its `// Output:` comment, so an example that no longer matches the code fails the tests. Commands (`package main`, such as those under `cmd/`) have none, as they export no API to show, and neither do internal packages, which only the module itself imports. Examples that need an outside service, such as `online/accounts/pgstore`'s Postgres database, or a running test, such as `online/accounts/storetest`, have no `// Output:` comment, so they are compiled but not run. `TestEveryPackageHasExamples` in `internal/repocheck` fails for a library package with no example, apart from the packages its exemption list names with a reason and a follow-up issue. ## Loop ```go import "github.com/nsgo-dev/game" ``` `Loop` runs a game's updates at a fixed rate on a scope's display frames, and draws once a frame in between. ```go type Loop struct { Rate int // updates a second, 60 when 0 MaxSteps int // most updates one frame runs, Rate/10 and at least 1 when 0 Update func(dt time.Duration) // moves the game on by dt, always 1/Rate seconds Draw func(alpha float64) // draws the frame, alpha in [0, 1) } func (l *Loop) Run(cx *core.Scope) (stop func()) ``` - Each frame adds the time since the last one and runs `Update` once for each whole step of `1/Rate` seconds it holds, then `Draw` once with how far the time left over reaches into the next step. A game moves its state in `Update` by the fixed `dt`, so it plays alike at any display rate, and `Draw` places what moves between the last two states by `alpha`, so it moves smoothly. - A frame that would run more than `MaxSteps` updates drops the whole steps past it, so an `Update` slower than its step, or a long hitch, slows the game rather than making each frame run more updates than the last. - `Run` starts the loop until the scope is disposed or `stop` is called. It reads the fields on each frame, so a game may change them while the loop runs. - The loop pauses while the scope's window is in the background (`core.Env.Lifecycle`) and resumes from the time it shows again, so the time away runs no updates. - A frame's time is the display's frame time where the platform stamps one, and the graph clock's otherwise; the loop adds it as it is. ## sprite ```go import "github.com/nsgo-dev/game/pkg/sprite" ``` Atlases, frames, animations, sprites and batches drawn into a `Canvas`. ### Atlas and Frame An `Atlas` is an image that packs many pictures (`Image`), the frames that say where each one is (`Frames`, by name), and its animations (`Animations`, by name). `LoadAtlas(img, data)` reads the JSON atlas data that TexturePacker ("JSON (Hash)" and "JSON (Array)") or Aseprite (json-hash and json-array) exports for the image it packed: - Rectangles are in the image's pixels, divided by the export's `meta.scale`, so the image measures its points as a 1x image does. - Aseprite's frame tags become `Animations`, each frame for the duration the export gives it, in the tag's direction, looping unless the tag has a repeat count. - Frames a packer rotated are refused: export with rotation off. A game can also write the table by hand as an `Atlas` literal. A `Frame` is one picture: the part of the image it draws (`X`, `Y`, `W`, `H`), where that part sits in the untrimmed picture (`OffsetX`, `OffsetY`), and the untrimmed size (`Width`, `Height`). ### Animation An `Animation` plays frames one after another, each for its own duration, moved on by `Update` with a `Loop`'s fixed steps. It is a value that keeps where it is in its frames, so each sprite plays its own copy: copy one from an atlas's `Animations`, or write one by hand. - `Update(dt)` moves it on past as many frames as `dt` covers. - `Frame()` is the frame showing now, `Index()` its index, and `Done()` reports whether an animation that does not loop has shown its last frame for that frame's duration. - `Reset()` starts it over. ### Sprite and Batch A `Sprite` is a frame placed in a drawing: moved (`X`, `Y`), turned (`Rotation`, in radians, clockwise), scaled (`ScaleX`, `ScaleY`; negative mirrors), flipped inside its untrimmed frame (`FlipX`, `FlipY`), faded (`Alpha`), tinted (`Tint`) and styled per sprite (`Effect`: solid-color flash and silhouette, alpha outline, dissolve, palette swap or custom pixel hook) about its origin (`OriginX`, `OriginY`). `Z` orders the sprites of a batch. Its zero value draws nothing; `NewSprite(f)` returns one at full size and opacity. `Tint` and `Effect` modify only the sprite's own pixels, leaving neighboring sprites and what is drawn under it unchanged. A `Batch` draws sprites of one atlas into a `core.Drawing`, lowest `Z` first and in the batch's order for the same `Z`. Consecutive sprites that are only moved, rotated and scaled evenly draw with one NSGo `DrawAtlas`; a sprite that is mirrored, scaled unevenly, tinted, blended, masked or has an active `Effect` draws on its own (`DrawImageFrom`, `DrawTintedImageFrom`, or a reused per-slot effect buffer). `EffectProgram` and `EffectShader` also run the built-in per-sprite effects on the GPU via `core.Shader`. It leaves the drawing's state as it found it. ```go walk := atlas.Animations["walk"] hero := sprite.NewSprite(walk.Frame()) batch := &sprite.Batch{Atlas: atlas, Sprites: []*sprite.Sprite{&hero}} loop := &game.Loop{ Update: func(dt time.Duration) { walk.Update(dt) hero.Frame = walk.Frame() }, } // In a core.Canvas's Draw: batch.Draw(d) ``` ## sound ```go import "github.com/nsgo-dev/game/pkg/sound" ``` The `Mixer`, its effects and music, on top of NSGo's `audio` package. Its methods are called on the engine's goroutine, as `audio`'s are. ### Mixer A `Mixer` sets how loud a game's sounds and music play: a master volume and a volume for each group the app names, such as `"effects"`, `"music"` and `"ui"`, each from 0 to 1 and 1 until set. - `NewMixer(cx, key)` keeps the volumes in the app's storage (`core.Storage`) under keys starting with `key`, so they hold across launches. - `Master`, `SetMaster`, `Volume(group)` and `SetVolume(group, v)` read and set them. Read in a computation, a volume subscribes it to changes; a set fails with a `*core.StorageFullError` when the storage is full. - `SetDefaultMaster` and `SetDefaultVolume(group, v)` set the volumes a mixer has until the player sets one, such as a project file's, without keeping them in storage. - An effect plays at its own voice's volume times its group's and the master volume, and music at its group's and the master volume. - A volume change applies at once to the effects playing and to music as it plays. An effect whose group or master volume reaches 0 plays on in silence and is heard again as the volume comes back. - While the window is in the background, the mixer silences the effects playing and pauses the music; when the window shows again, it restores the effects still playing and plays the music on from there. `Suspend()` does the same until the `resume` it returns is called, as a cutscene does while it plays ([cutscene](http://nsgo.games/docs/cutscene/)). ### Effect `mixer.Effect(s, group, limit)` plays an `*audio.Sound` through the mixer in a group, at most `limit` playbacks at once (0 for no limit of its own, under the platform's 32 for all sounds), so a burst of one sound does not take every voice. `Play(voice)` starts a playback and reports whether it did. It plays nothing while the volume is 0, for a voice with `Muted` set, or while the app is in the background. With `Limit` playbacks still playing, it stops the oldest to make room. `Stop()` stops every playback of the sound. ### Music `mixer.Music(group)` plays long tracks through the mixer, one at a time, each through an `audio.Player`. - `Play(src, fade)` fades the new track in over `fade` as the tracks playing fade out, by the display's frames, closing them as they reach silence; it switches at once when `fade` is 0. - `Stop(fade)` fades the music out. ```go mixer := sound.NewMixer(cx, "sound") music := mixer.Music("music") music.Play(audio.Source{URI: "asset:theme.m4a"}, 2*time.Second) ``` --- Source: http://nsgo.games/docs/stability/ # API Stability Every package of the module is either stable or experimental. The status says how a package may change from one release to the next, how its changes are announced, and how long an app has to move off what it deprecates. ## Statuses **Stable** packages change only in ways an app can plan for: - From v1.0.0, a stable package keeps its exported API compatible within a major version, as [Semantic Versioning](https://semver.org/spec/v2.0.0.html) and Go's own [compatibility promise](https://go.dev/doc/go1compat) describe: no identifier is removed or renamed, no signature changes, and documented behavior holds. Adding methods, fields, functions and types is compatible when it does not change an existing interface's method set. Adding a method to an exported interface is a breaking change because existing implementations may no longer compile. - Before v1.0.0, where Semantic Versioning allows any change, a stable package breaks its API only in a minor release (v0.x.0, never a patch release), and only after deprecating what it removes or changes for at least one minor release, as [Deprecation](http://nsgo.games/docs/stability/#deprecation) describes. - A stable package imports no experimental package of this module, so a change to an experimental package never breaks it. **Experimental** packages are still finding their shape, usually because they wait on an NSGo primitive, a format decision or more use in the sample games: - An experimental package may change or remove any part of its API in any minor release, without a deprecation period. Patch releases still only fix bugs. - Every change to its API is listed in `CHANGELOG.md` under the release that makes it, so an upgrade is never a surprise. - An app may use experimental packages; it should pin the module's version and read the changelog before it upgrades. ## What the promise covers - The exported Go API of a package: its identifiers, signatures, and the behavior its doc comments document. - The text formats a package defines, such as its YAML files. Each has a `version` field; a stable package keeps loading every version of its formats it has written since it became stable, and migrates them on load. - The formats of other tools a package reads, such as Tiled's and LDtk's maps and Aseprite's and TexturePacker's atlases. A stable package keeps reading every version of those exports it has read since it became stable. - For a command (a `cmd` directory), its flags, arguments, exit codes and the formats of its output files. It does not cover: - Packages under `internal/`, which no other module can import. - Behavior a doc comment calls unspecified, and anything that depends on a bug: a fix to a bug is not a breaking change. - Performance, allocation counts and binary size, which are tracked by [budgets](http://nsgo.games/docs/package-size-budgets/) rather than promised. - The minimum Go and NSGo versions, which a minor release may raise; the README's compatibility table lists them for each release. ## Package moves and NSGo types Moving an experimental package to a new import path is allowed in a minor release. The release changelog names the old and new paths and the package's guide links to the migration. A stable package keeps its old import path for at least one minor release as a forwarding package of aliases and wrappers, with a `Deprecated:` package comment that names the replacement. Removing that forwarding path follows the same deprecation period as any other stable API removal. NSGo types in a stable signature are part of that package's compatibility contract. If an NSGo change makes a stable signature incompatible, the game release raises its minimum NSGo version and lists every affected package and identifier under `### Changed`. Where Go permits aliases or wrappers, the old signature remains available for the deprecation period. Experimental packages may follow a newer NSGo signature in a minor release when the change is listed in the changelog. Every experimental package starts its package documentation with a sentence that says it is experimental and links this policy. `TestStabilityTable` checks that sentence alongside the status table, so `go doc` and pkg.go.dev show the same status as the website. ## Deprecation The `check` workflow compares deterministic `apidiff` export artifacts from the pull request base and head. Stable incompatible changes fail CI. Experimental incompatible changes require a bullet under `### Changed` or `### Removed` in a `changelog.d` fragment that names the package in backticks, such as `` `editor` `` or `` `game/editor` ``. Release checks run the same comparison against the previous tag and put the report in the release notes. Package moves are recorded in `internal/repocheck/api-moves.yaml`. When a stable package replaces or removes part of its API: 1. The release that deprecates it adds a paragraph starting `Deprecated:` to the identifier's doc comment, naming what to use instead, as Go's [deprecation convention](https://go.dev/wiki/Deprecated) describes, so gopls, staticcheck and pkg.go.dev flag its uses: ```go // DrawAll draws every sprite of the batch. // // Deprecated: Use Batch.Draw, which also orders the sprites by Z. func (b *Batch) DrawAll(d core.Drawing) ``` 2. The same release lists it under `### Deprecated` in `CHANGELOG.md`, with the issue that tracks it. 3. The deprecated identifier keeps working, unchanged, for at least one whole minor release after the one that deprecates it: deprecated in v0.4.0, it is removed in v0.6.0 at the earliest. 4. The release that removes it lists it under `### Removed` in `CHANGELOG.md`. From v1.0.0 nothing is removed from a stable package before the next major version. The releases themselves, their tags, changelog sections and the NSGo version each one needs, are described in [#39](https://github.com/nsgo-dev/game/issues/39). ## Changing a status - A package becomes stable in a minor release through a pull request that changes its row below, says so in the changelog, and has the package's guide in place. It should be used by at least one sample game in `examples` and depend only on stable packages. - A stable package never goes back to experimental. A design it outgrows is replaced by a new package or, from v1.0.0, a new major version. - A new package starts experimental. ## Packages Paths are relative to `github.com/nsgo-dev`. The table is checked by a test in the module, so every package has exactly one row. Every package starts experimental. An experimental row means its exported API, documented behavior, and package-defined text formats may still change in a minor release. The row's guide is the place to find the current usage contract, while the release process in [Release Checklist](http://nsgo.games/docs/releasing/) describes how changes are announced and verified. | Package | Status | Guide | | --- | --- | --- | | `game` | Stable | [Loop](http://nsgo.games/docs/loop/) | | `game/cmd/accountsd` | Experimental | [accounts](http://nsgo.games/docs/accounts/) | | `game/cmd/cloudsaved` | Experimental | [cloudsave](http://nsgo.games/docs/cloudsave/) | | `game/cmd/editor` | Experimental | [Scene Editor](http://nsgo.games/docs/editor/) | | `game/cmd/game` | Experimental | [Command Line](http://nsgo.games/docs/cli/) | | `game/cmd/leaderboardd` | Experimental | [leaderboard/selfhost](http://nsgo.games/docs/leaderboard-selfhost/) | | `game/cmd/nsgo-game` | Experimental | [Command Line](http://nsgo.games/docs/cli/) | | `game/pkg/a11y` | Experimental | [a11y](http://nsgo.games/docs/a11y/) | | `game/pkg/ability` | Experimental | [ability](http://nsgo.games/docs/ability/) | | `game/pkg/ai` | Stable | [ai](http://nsgo.games/docs/ai/) | | `game/pkg/ai/cover3d` | Experimental | [ai](http://nsgo.games/docs/ai/) | | `game/pkg/ai/perception3d` | Experimental | [ai](http://nsgo.games/docs/ai/) | | `game/pkg/anim3d` | Experimental | [anim3d](http://nsgo.games/docs/anim3d/) | | `game/pkg/animclip` | Experimental | [animclip](http://nsgo.games/docs/animclip/) | | `game/pkg/assets` | Experimental | [assets](http://nsgo.games/docs/assets/) | | `game/pkg/battle` | Experimental | [battle](http://nsgo.games/docs/battle/) | | `game/pkg/bullets` | Experimental | [bullets](http://nsgo.games/docs/bullets/) | | `game/pkg/cards` | Experimental | [cards](http://nsgo.games/docs/cards/) | | `game/pkg/cards/deck` | Experimental | [cards](http://nsgo.games/docs/cards/) | | `game/pkg/cues` | Experimental | [cues](http://nsgo.games/docs/cues/) | | `game/pkg/cutscene` | Experimental | [cutscene](http://nsgo.games/docs/cutscene/) | | `game/pkg/datatable` | Experimental | [datatable](http://nsgo.games/docs/datatable/) | | `game/pkg/datatable/datatablewatch` | Experimental | [datatable](http://nsgo.games/docs/datatable/) | | `game/pkg/dialogue` | Stable | [dialogue](http://nsgo.games/docs/dialogue/) | | `game/pkg/editor` | Experimental | [editor](http://nsgo.games/docs/editor/) | | `game/pkg/editor/agentdir` | Experimental | [editor](http://nsgo.games/docs/editor/) | | `game/pkg/editor/diaglog` | Experimental | [editor](http://nsgo.games/docs/editor/) | | `game/pkg/editor/editorcmd` | Experimental | [editor](http://nsgo.games/docs/editor/) | | `game/pkg/editor/editormcp` | Experimental | [mcp](http://nsgo.games/docs/mcp/) | | `game/pkg/editor/keychain` | Experimental | [editor](http://nsgo.games/docs/editor/) | | `game/pkg/editor/theme` | Experimental | [editor](http://nsgo.games/docs/editor/) | | `game/pkg/entities` | Experimental | [entities](http://nsgo.games/docs/entities/) | | `game/pkg/farming` | Experimental | [farming](http://nsgo.games/docs/farming/) | | `game/pkg/fighting` | Experimental | [fighting](http://nsgo.games/docs/fighting/) | | `game/pkg/flow` | Stable | [flow](http://nsgo.games/docs/flow/) | | `game/pkg/fog` | Experimental | [fog](http://nsgo.games/docs/fog/) | | `game/pkg/framedata` | Experimental | [framedata](http://nsgo.games/docs/framedata/) | | `game/pkg/gameplugin` | Experimental | [Plugins](http://nsgo.games/docs/plugins/) | | `game/pkg/gameplugin/devplugin` | Experimental | [Plugins](http://nsgo.games/docs/plugins/) | | `game/pkg/gameplugin/manifest` | Experimental | [Plugins](http://nsgo.games/docs/plugins/) | | `game/pkg/gametest` | Experimental | [gametest](http://nsgo.games/docs/gametest/) | | `game/pkg/gametime` | Experimental | [gametime](http://nsgo.games/docs/gametime/) | | `game/pkg/gameui` | Experimental | [gameui](http://nsgo.games/docs/gameui/) | | `game/pkg/gltf` | Experimental | [3D Models from Blender](http://nsgo.games/docs/3d-models-blender/) | | `game/pkg/hostbridge` | Experimental | [shipping](http://nsgo.games/docs/shipping/) | | `game/pkg/idle` | Experimental | [idle](http://nsgo.games/docs/idle/) | | `game/pkg/importsettings` | Experimental | [Command Line](http://nsgo.games/docs/cli/) | | `game/pkg/input` | Stable | [input](http://nsgo.games/docs/input/) | | `game/pkg/inventory` | Experimental | [inventory](http://nsgo.games/docs/inventory/) | | `game/pkg/jsonschema` | Experimental | [Schemas for YAML files](http://nsgo.games/docs/schemas/) | | `game/pkg/ktx2` | Experimental | [render3d](http://nsgo.games/docs/render3d/) | | `game/pkg/l10n` | Experimental | [l10n](http://nsgo.games/docs/l10n/) | | `game/pkg/lights2d` | Experimental | [lights2d](http://nsgo.games/docs/lights2d/) | | `game/pkg/loaderr` | Stable | [Errors](http://nsgo.games/docs/errors/) | | `game/pkg/loot` | Experimental | [loot](http://nsgo.games/docs/loot/) | | `game/pkg/match3` | Experimental | [match3](http://nsgo.games/docs/match3/) | | `game/pkg/math2d` | Stable | [math2d](http://nsgo.games/docs/math2d/) | | `game/pkg/math3d` | Experimental | [math3d](http://nsgo.games/docs/math3d/) | | `game/pkg/mcp` | Experimental | [mcp](http://nsgo.games/docs/mcp/) | | `game/pkg/mcp/mcp3d` | Experimental | [mcp](http://nsgo.games/docs/mcp/) | | `game/pkg/mcp/mcpui` | Experimental | [mcp](http://nsgo.games/docs/mcp/) | | `game/pkg/mempool` | Experimental | [mempool](http://nsgo.games/docs/mempool/) | | `game/pkg/mergegame` | Experimental | [formats](http://nsgo.games/docs/formats/) | | `game/pkg/modding` | Experimental | [modding](http://nsgo.games/docs/modding/) | | `game/pkg/motion` | Experimental | [scene](http://nsgo.games/docs/scene/) | | `game/pkg/online/accounts` | Experimental | [accounts](http://nsgo.games/docs/accounts/) | | `game/pkg/online/accounts/authtoken` | Experimental | [accounts](http://nsgo.games/docs/accounts/) | | `game/pkg/online/accounts/identity` | Experimental | [accounts](http://nsgo.games/docs/accounts/) | | `game/pkg/online/accounts/pgstore` | Experimental | [accounts](http://nsgo.games/docs/accounts/) | | `game/pkg/online/accounts/sqlitestore` | Experimental | [accounts](http://nsgo.games/docs/accounts/) | | `game/pkg/online/accounts/sqlstore` | Experimental | [accounts](http://nsgo.games/docs/accounts/) | | `game/pkg/online/accounts/storetest` | Experimental | [accounts](http://nsgo.games/docs/accounts/) | | `game/pkg/online/achievements` | Experimental | [achievements](http://nsgo.games/docs/achievements/) | | `game/pkg/online/admin` | Experimental | [admin](http://nsgo.games/docs/admin/) | | `game/pkg/online/antiaddiction` | Experimental | [Releasing in Mainland China](http://nsgo.games/docs/shipping-china/) | | `game/pkg/online/audit` | Experimental | [gameserver](http://nsgo.games/docs/gameserver/) | | `game/pkg/online/backend` | Experimental | [backend](http://nsgo.games/docs/backend/) | | `game/pkg/online/cloudsave` | Experimental | [cloudsave](http://nsgo.games/docs/cloudsave/) | | `game/pkg/online/cloudsave/pgstore` | Experimental | [cloudsave](http://nsgo.games/docs/cloudsave/) | | `game/pkg/online/cloudsave/sqlitestore` | Experimental | [cloudsave](http://nsgo.games/docs/cloudsave/) | | `game/pkg/online/cloudsave/sqlstore` | Experimental | [cloudsave](http://nsgo.games/docs/cloudsave/) | | `game/pkg/online/cloudsave/storetest` | Experimental | [cloudsave](http://nsgo.games/docs/cloudsave/) | | `game/pkg/online/economy` | Experimental | [economy](http://nsgo.games/docs/economy/) | | `game/pkg/online/eos` | Experimental | [eos](http://nsgo.games/docs/epic/) | | `game/pkg/online/gameserver` | Experimental | [gameserver](http://nsgo.games/docs/gameserver/) | | `game/pkg/online/lan` | Experimental | [netplay](http://nsgo.games/docs/netplay/) | | `game/pkg/online/leaderboard` | Experimental | [leaderboard](http://nsgo.games/docs/leaderboard/) | | `game/pkg/online/leaderboard/selfhost` | Experimental | [leaderboard/selfhost](http://nsgo.games/docs/leaderboard-selfhost/) | | `game/pkg/online/leaderboard/selfhost/pgstore` | Experimental | [leaderboard/selfhost](http://nsgo.games/docs/leaderboard-selfhost/) | | `game/pkg/online/leaderboard/selfhost/sqlitestore` | Experimental | [leaderboard/selfhost](http://nsgo.games/docs/leaderboard-selfhost/) | | `game/pkg/online/leaderboard/selfhost/sqlstore` | Experimental | [leaderboard/selfhost](http://nsgo.games/docs/leaderboard-selfhost/) | | `game/pkg/online/liveops` | Experimental | [liveops](http://nsgo.games/docs/liveops/) | | `game/pkg/online/liveops/crashreport` | Experimental | [liveops](http://nsgo.games/docs/liveops/) | | `game/pkg/online/netplay` | Experimental | [netplay](http://nsgo.games/docs/netplay/) | | `game/pkg/online/netplay/roomstate` | Experimental | [netplay](http://nsgo.games/docs/netplay/) | | `game/pkg/online/netplay/wire` | Experimental | [netplay/wire](http://nsgo.games/docs/netplay-wire/) | | `game/pkg/online/portmap` | Experimental | [portmap](http://nsgo.games/docs/portmap/) | | `game/pkg/online/presence` | Experimental | [presence](http://nsgo.games/docs/presence/) | | `game/pkg/online/realtime` | Experimental | [social](http://nsgo.games/docs/social/) | | `game/pkg/online/records` | Experimental | [records](http://nsgo.games/docs/records/) | | `game/pkg/online/servicehealth` | Experimental | [Deploying backend services](http://nsgo.games/docs/backend-deploy/) | | `game/pkg/online/social` | Experimental | [social](http://nsgo.games/docs/social/) | | `game/pkg/online/steam` | Experimental | [steam](http://nsgo.games/docs/steam-stats/) | | `game/pkg/online/steamworks` | Experimental | [steamworks](http://nsgo.games/docs/steamworks/) | | `game/pkg/online/storeverify/wechatpay` | Experimental | [liveops](http://nsgo.games/docs/liveops/) | | `game/pkg/online/wsclient` | Experimental | [wsclient](http://nsgo.games/docs/wsclient/) | | `game/pkg/particles` | Experimental | [particles](http://nsgo.games/docs/particles/) | | `game/pkg/pathfind` | Stable | [pathfind](http://nsgo.games/docs/pathfind/) | | `game/pkg/pathfind/navbake` | Experimental | [navbake](http://nsgo.games/docs/navbake/) | | `game/pkg/pathfind3d` | Experimental | [pathfind3d](http://nsgo.games/docs/pathfind3d/) | | `game/pkg/pathfind3d/navbake3d` | Experimental | [navbake3d](http://nsgo.games/docs/navbake3d/) | | `game/pkg/physics` | Stable | [physics](http://nsgo.games/docs/physics/) | | `game/pkg/physics3d` | Experimental | [physics3d](http://nsgo.games/docs/physics3d/) | | `game/pkg/pixelfx` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/arcane` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/critters` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/explosions` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/fire` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/holy` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/ice` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/impacts` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/lightning` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/melee` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/moves` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/nature` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/pickups` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/projectiles` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/scifi` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/shadow` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/spawn` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/status` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/transitions` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/ui` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/water` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/pixelfx/weather` | Experimental | [pixelfx](http://nsgo.games/docs/pixelfx/) | | `game/pkg/placeholder` | Experimental | [Placeholder Assets](http://nsgo.games/docs/placeholder/) | | `game/pkg/placement` | Experimental | [placement](http://nsgo.games/docs/placement/) | | `game/pkg/platformer` | Experimental | [platformer](http://nsgo.games/docs/platformer/) | | `game/pkg/postfx` | Experimental | [postfx](http://nsgo.games/docs/postfx/) | | `game/pkg/procgen` | Experimental | [procgen](http://nsgo.games/docs/procgen/) | | `game/pkg/progression` | Experimental | [progression](http://nsgo.games/docs/progression/) | | `game/pkg/project` | Experimental | [Project File](http://nsgo.games/docs/project/) | | `game/pkg/quality` | Experimental | [quality](http://nsgo.games/docs/quality/) | | `game/pkg/quest` | Experimental | [quest](http://nsgo.games/docs/quest/) | | `game/pkg/random` | Stable | [Determinism](http://nsgo.games/docs/determinism/) | | `game/pkg/render3d` | Experimental | [render3d](http://nsgo.games/docs/render3d/) | | `game/pkg/replay` | Experimental | [replay](http://nsgo.games/docs/replay/) | | `game/pkg/resource` | Experimental | [resources](http://nsgo.games/docs/resources/) | | `game/pkg/rhythm` | Experimental | [rhythm](http://nsgo.games/docs/rhythm/) | | `game/pkg/rooms` | Experimental | [rooms](http://nsgo.games/docs/rooms/) | | `game/pkg/rpgdata` | Experimental | [rpgdata](http://nsgo.games/docs/rpgdata/) | | `game/pkg/rts` | Experimental | [rts](http://nsgo.games/docs/rts/) | | `game/pkg/save` | Stable | [save](http://nsgo.games/docs/save/) | | `game/pkg/save/savetest` | Experimental | [save](http://nsgo.games/docs/save/) | | `game/pkg/scene` | Stable | [scene](http://nsgo.games/docs/scene/) | | `game/pkg/scene3d` | Experimental | [scene3d](http://nsgo.games/docs/scene3d/) | | `game/pkg/sceneformat` | Experimental | [editor](http://nsgo.games/docs/editor/) | | `game/pkg/scenemodel` | Experimental | [scenemodel](http://nsgo.games/docs/scenemodel/) | | `game/pkg/screen` | Stable | [screen](http://nsgo.games/docs/screen/) | | `game/pkg/sessionstats` | Experimental | [sessionstats](http://nsgo.games/docs/sessionstats/) | | `game/pkg/skeletal` | Experimental | [skeletal](http://nsgo.games/docs/skeletal/) | | `game/pkg/sound` | Stable | [sound](http://nsgo.games/docs/sound/) | | `game/pkg/spatial` | Experimental | [spatial](http://nsgo.games/docs/spatial/) | | `game/pkg/spawn` | Experimental | [spawn](http://nsgo.games/docs/spawn/) | | `game/pkg/sprite` | Stable | [sprite](http://nsgo.games/docs/sprite/) | | `game/pkg/statedump` | Experimental | [statedump](http://nsgo.games/docs/statedump/) | | `game/pkg/stats` | Experimental | [stats](http://nsgo.games/docs/stats/) | | `game/pkg/tags` | Experimental | [tags](http://nsgo.games/docs/tags/) | | `game/pkg/text` | Experimental | [text](http://nsgo.games/docs/text/) | | `game/pkg/tilemap` | Stable | [tilemap](http://nsgo.games/docs/tilemap/) | | `game/pkg/tilemap/tileshape` | Experimental | [tileshape](http://nsgo.games/docs/tileshape/) | | `game/pkg/tooling/assetbuild` | Experimental | [Command Line](http://nsgo.games/docs/cli/) | | `game/pkg/tooling/assetcheck` | Experimental | [Command Line](http://nsgo.games/docs/cli/) | | `game/pkg/tooling/assets` | Experimental | [assets](http://nsgo.games/docs/assets/) | | `game/pkg/tooling/atlaspack` | Experimental | [Command Line](http://nsgo.games/docs/cli/) | | `game/pkg/tooling/audioconv` | Experimental | [Command Line](http://nsgo.games/docs/cli/) | | `game/pkg/tooling/bench` | Experimental | [Command Line](http://nsgo.games/docs/cli/) | | `game/pkg/tooling/credits` | Experimental | [Command Line](http://nsgo.games/docs/cli/) | | `game/pkg/tooling/devstate` | Experimental | [File Formats](http://nsgo.games/docs/formats/) | | `game/pkg/tooling/dlc` | Experimental | [assets](http://nsgo.games/docs/assets/) | | `game/pkg/tooling/gamedebug` | Experimental | [gamedebug](http://nsgo.games/docs/gamedebug/) | | `game/pkg/tooling/genjob` | Experimental | [editor](http://nsgo.games/docs/editor/) | | `game/pkg/tooling/genparams` | Experimental | | | `game/pkg/tooling/godebug` | Experimental | [editor](http://nsgo.games/docs/editor/) | | `game/pkg/tooling/hotreload` | Experimental | [Resources](http://nsgo.games/docs/resources/) | | `game/pkg/tooling/library` | Experimental | [Asset and Plugin Library](http://nsgo.games/docs/library/) | | `game/pkg/tooling/manifest` | Experimental | [Command Line](http://nsgo.games/docs/cli/) | | `game/pkg/tooling/playtest` | Experimental | [playtest](http://nsgo.games/docs/playtest/) | | `game/pkg/tooling/refs` | Experimental | [Packages](http://nsgo.games/docs/packages/) | | `game/pkg/tooling/sizecheck` | Experimental | [Package Size Budgets](http://nsgo.games/docs/package-size-budgets/) | | `game/pkg/tooling/spriteframes` | Experimental | [assets](http://nsgo.games/docs/assets/) | | `game/pkg/tooling/storecapture` | Experimental | [Building and Shipping](http://nsgo.games/docs/shipping/) | | `game/pkg/tooling/templatemeta` | Experimental | [Templates](http://nsgo.games/docs/templates/) | | `game/pkg/tooling/texseam` | Experimental | [assets](http://nsgo.games/docs/assets/) | | `game/pkg/tween` | Stable | [tween](http://nsgo.games/docs/tween/) | | `game/pkg/undo` | Experimental | [undo](http://nsgo.games/docs/undo/) | | `game/pkg/vehicle3d` | Experimental | [vehicle3d](http://nsgo.games/docs/vehicle3d/) | | `game/pkg/vn` | Experimental | [vn](http://nsgo.games/docs/vn/) | | `game/pkg/voxel` | Experimental | [voxel](http://nsgo.games/docs/voxel/) | | `game/pkg/world3d` | Experimental | [world3d](http://nsgo.games/docs/world3d/) | | `game/pkg/worldmap` | Experimental | [worldmap](http://nsgo.games/docs/worldmap/) | | `game/skills` | Experimental | [Agent Skill](http://nsgo.games/docs/agent-skill/) | ## Package moves and NSGo types A stable package keeps its old import path for one minor release when it moves, using deprecated aliases or wrappers. Experimental packages may move in a minor release with a changelog entry naming the new path. Changes to NSGo types in stable signatures follow the same compatibility policy and list affected identifiers when aliases are impossible. --- Source: http://nsgo.games/docs/loop/ # Loop `game.Loop` drives fixed-step updates and interpolated frame draws on an NSGo scope's display frames, pausing automatically while the app is in the background. ```go import "github.com/nsgo-dev/game" ``` ## How the fixed step works Displays run at different refresh rates (60 Hz, 90 Hz, 120 Hz, or variable). If a game moves physics by raw frame delta times, jump heights and collisions change with the display rate. `Loop` decouples simulation from rendering: ```go type Loop struct { Rate int // updates a second, 60 when 0 MaxSteps int // most updates one frame runs, max(1, Rate/10) when 0 Paused bool // stops Update from advancing with display time PausedAwake time.Duration // how long to keep the display awake while paused or OnDemand-idle TimeScale float64 // simulated time multiplier, 1 when <= 0 or non-finite DrawRate int // caps Draw calls per second, uncapped when <= 0 MatchDisplayToRate bool // asks the display to use Rate when DrawRate is uncapped OnDemand bool // skips Draw on frames without Update unless MarkDirty was called Idle func() bool // with OnDemand, skips both Update and Draw while returning true Immersive bool // hides phone system bars while unpaused Update func(dt time.Duration) // moves the game on by dt, always 1/Rate seconds Draw func(alpha float64) // draws the frame, alpha in [0, 1) FrameTime func(dt time.Duration) // receives each frame's length before updates OnPause func(paused bool) // runs whenever Paused changes } func (l *Loop) Run(cx *core.Scope) (stop func()) func (l *Loop) SetPaused(paused bool) func (l *Loop) SetTimeScale(scale float64) func (l *Loop) Step(n int) func (l *Loop) StepOnce() func (l *Loop) StepNow(n int) int func (l *Loop) MarkDirty() ``` On each display frame from NSGo's `RequestAnimationFrame`: 1. The loop adds the elapsed time since the previous frame to an accumulator. 2. While the accumulator holds at least one whole step (`time.Second / time.Duration(Rate)`), it subtracts one step and calls `Update(step)`. A single display frame may run zero, one or several updates. 3. Once fewer than one whole step remains, it calls `Draw(alpha)` with `alpha = float64(acc) / float64(step)` in `[0, 1)`. `Run` reads `Rate`, `MaxSteps`, `Update` and `Draw` on every frame, so you can swap handlers or adjust the rate while the loop is running. ## Interpolating with alpha When the display rate does not evenly divide `Rate` (for example, a 60 Hz simulation on a 120 Hz display), drawing the raw state from `Update` produces visible stutter because some frames run zero updates and some run one. Keep the previous and current state in `Update`, pass `alpha` into a `core.Signal[float64]` from `Draw`, and interpolate inside `core.Canvas.Draw`: ```go func Ball(cx *core.Scope) core.Node { var x, last float32 alpha := core.NewSignal(cx, 0.0) loop := &game.Loop{ Rate: 60, Update: func(dt time.Duration) { last = x x += 120 * float32(dt.Seconds()) }, Draw: func(a float64) { alpha.Set(a) }, } loop.Run(cx) return core.Canvas{ Style: core.Style{FlexGrow: 1, FlexShrink: 1}, Draw: func(d *core.Drawing, _ core.Size) { at := last + (x-last)*float32(alpha.Get()) d.SetFillColor(core.RGB(0xff5a1f)).FillRect(at, 40, 16, 16) }, } } ``` Because `alpha` is read only inside `Canvas.Draw`, setting it redraws the canvas without re-evaluating or committing the surrounding view tree. ## Hitch protection and MaxSteps If a single frame takes much longer than usual (a debugger pause, a slow frame, or a device stall), catching up every missed step would cause an even slower next frame — the classic "spiral of death". `MaxSteps` caps how many `Update` calls one display frame may execute: - When `MaxSteps <= 0`, it defaults to `max(1, Rate/10)` — one tenth of a second of simulation (6 steps at 60 Hz, 12 steps at 120 Hz). - When a frame reaches `MaxSteps`, the loop drops the remaining whole steps (`acc %= step`) and moves straight to `Draw`. The game briefly slows down instead of freezing. Set `MaxSteps` explicitly when you need a tighter bound (for example, `MaxSteps: 3` for heavy physics): ```go loop := &game.Loop{ Rate: 60, MaxSteps: 3, Update: stepWorld, Draw: renderWorld, } ``` ## Frame time Each frame adds the time between its timestamp and the previous frame's, exactly as `RequestAnimationFrame` gives it. Where the platform stamps its display frames, that is the display's own frame time, so a frame's length is the display's rather than when the engine got to the frame; elsewhere it is the graph clock's. The first frame after the loop starts or resumes adds the time from then to its timestamp, which may lie a frame ahead where the display stamps a frame with when it will show, so the loop's time is the shown frame's. A frame stamped before the time the loop started or resumed adds nothing, so resuming never moves the accumulator backward, and the next frame adds the time from then. Set `FrameTime` to read each frame's length, the time it adds, ahead of the frame's updates; a frame that adds nothing passes 0. Frame-time statistics, such as [quality](http://nsgo.games/docs/quality/)'s `Selector`, read it. The first frame back from the background measures from the time the window showed again, not the time away, and `FrameTime` may call the `stop` function `Run` returned, which ends the frame before any update. It also fires while `Paused` is set, so a caller that should only measure frames that simulate skips them itself. ```go loop := &game.Loop{ FrameTime: func(dt time.Duration) { selector.Observe(dt) }, Update: stepWorld, Draw: renderWorld, } ``` ## Pausing and syncing subsystems `SetPaused(true)` (or setting `Paused = true`) stops `Update` from advancing while `Draw` keeps running, and unpausing resumes without a catch-up backlog. Set `OnPause` to keep subsystems such as [`sound.Mixer`](http://nsgo.games/docs/sound/#pausing-with-the-game) in sync with the loop's paused state: ```go mixer.SetPauseExempt("ui", true) loop := &game.Loop{ Rate: 60, OnPause: mixer.SetPaused, Update: stepWorld, Draw: renderWorld, } loop.Run(cx) ``` - `SetPaused` calls `OnPause` immediately whenever the paused state changes (repeating the same value does nothing). - Editing `Paused` directly calls `OnPause` on the next frame, or in the same frame when `Update` changes it. - If `Paused` is already `true` when `Run` starts, `Run` calls `OnPause(true)`. - Backgrounding does not call `OnPause`; both `Loop.Run` and `sound.NewMixer` watch `core.Env.Lifecycle` directly so backgrounding pauses and resumes everything in sync without clearing an open pause menu. ## Scaling time (`TimeScale`) `TimeScale` (or `SetTimeScale`) scales simulated time for slow-motion effects or fast-forward without changing the fixed `dt` passed to `Update`: - `0.5` runs half as many `Update` steps per second; `2.0` runs twice as many (still capped by `MaxSteps` per frame). - Values at or below `0` (as well as `NaN` and `±Inf`) default to `1`. ```go loop.SetTimeScale(0.25) // bullet-time slow motion; Update still sees dt == 1/Rate ``` ## Single-stepping while paused (`Step`, `StepOnce`, `StepNow`) While `Paused` is `true`, you can advance the simulation by an exact number of fixed steps without unpausing: - `Step(n)` queues `n` fixed `Update` steps to run on the next display frame, followed by a `Draw(0)` (non-positive values do nothing). - `StepOnce()` is shorthand for `Step(1)`. - `StepNow(n)` runs `n` fixed `Update` steps and a `Draw` synchronously right away (whether `Paused` is `true` or `false`) and returns how many steps ran, which suits deterministic tests and editor replay tools. ## Capping the draw rate (`DrawRate`) Set `DrawRate` to cap how many times `Draw` runs per second while keeping `Update` at `Rate` (for example, 60 Hz physics with 30 fps rendering under low-power mode). Values at or below `0` leave `Draw` uncapped at the display's refresh rate. When `OnDemand` and `DrawRate` are both set, a `MarkDirty` request that arrives before the next draw interval is preserved and drawn once the interval elapses. ## Matching the display rate (`MatchDisplayToRate`) `Loop` asks the host to lower the display refresh rate when it can. A positive `DrawRate` becomes the preferred display rate, so a low-power cap avoids waking the app at the panel's full rate. Set `MatchDisplayToRate: true` when `DrawRate` is uncapped and the display should follow the fixed update rate. Paused loops and idle `OnDemand` loops request a conservative 60 Hz idle rate, which lowers wakeups on high-refresh panels while preserving the usual cadence on 60 Hz displays. The host may choose a different supported rate. ## On-demand drawing and idling (`OnDemand`, `Idle`, `MarkDirty`) Menu-heavy, turn-based and narrative games often sit waiting for the player to tap or press a key. Set `OnDemand: true` together with `Idle` so the loop does zero update and draw work while nothing is animating: - **Without `Idle`**: `OnDemand: true` skips `Draw` on frames where no `Update` ran unless `MarkDirty()` was called (for example, a 30 Hz simulation on a 60 Hz display draws 30 times a second, and a `Paused: true` loop draws only on `Step` or `MarkDirty`). - **With `Idle`**: while `OnDemand` is `true`, `Paused` is `false` and `Idle()` returns `true`, the loop skips both `Update` and `Draw` on display frames without accumulating elapsed time (so waking later produces no catch-up backlog). - **Waking on input (`MarkDirty`)**: calling `MarkDirty()` requests a `Draw` on the next frame; when an unpaused `OnDemand` loop is idle, `MarkDirty()` also queues one fixed `Update` step on that frame so `Update` can sample input and advance state. Multiple `MarkDirty()` calls between frames coalesce into a single wake step. If that `Update` starts ongoing work (so `Idle()` returns `false`), fixed-step updates resume normally until `Idle()` returns `true` again. - **Wiring input**: assign `actions.Wake = loop.MarkDirty` on [`input.Actions`](http://nsgo.games/docs/input/#waking-an-idle-ondemand-loop) (and `TouchControls.OnWake` or `GestureRecognizer.Wake` when used without a bound `Actions`), and call `loop.MarkDirty()` from view callbacks (such as button `OnPress`) that mutate state outside `Update`. ```go loop := &game.Loop{ Rate: 60, OnDemand: true, Idle: func() bool { return fadeLeft == 0 && typewriter.Done() && !autoMode }, Update: func(dt time.Duration) { actions.Step() handleInput() stepAnimations(dt) }, Draw: func(float64) { frame.Update(func(v uint64) uint64 { return v + 1 }) }, } actions.Wake = loop.MarkDirty loop.Run(cx) ``` ## Background pause and stopping `Loop.Run` watches `cx.Env().Lifecycle()`: - **`core.LifecycleBackground`** (minimized, hidden or covered on desktop; app backgrounded on iOS or Android): the loop cancels its pending frame request and runs no updates. - **`core.LifecycleActive` or `core.LifecycleInactive`** (visible, even without focus on desktop): the loop runs normally. When returning from the background, it resets its clock anchor to `cx.Now()`, so time spent away produces zero catch-up steps. - Set `PauseOnLeave: LeaveInactive` to pause once on any focus loss, or `LeaveBackground` to pause only when the app is backgrounded. The pause stays set until `SetPaused(false)` is called. `OnLeave` runs once for every transition away from the active lifecycle and receives whether the transition was backgrounding, which is a suitable place to save progress. The signals it reads do not subscribe the loop, so a change to them never calls it again. - A live run also calls `OnLeave` during scope quit when it has not already handled the current background transition. The stop function returned by `Run` ends that run’s lifecycle and quit callbacks. - The `shmup2d` template pauses a running game on focus loss or backgrounding. The pause menu stays open until the player chooses **Resume**. The loop ends permanently when either: - The `cx` scope is disposed (for example, navigating away or hiding the component with `core.Show`), or - You call the `stop` function returned by `Run`. Calling `stop()` is safe to repeat and safe from inside `Update`: if `Update` stops the loop, no further updates and no `Draw` run for that frame, and returning from the background will not restart it. ```go var stop func() loop := &game.Loop{ Update: func(dt time.Duration) { if gameOver { stop() } }, Draw: func(alpha float64) { frame.Set(alpha) }, } stop = loop.Run(cx) ``` ## Keeping the display awake While the loop runs in the foreground and is active (not `Paused`, and not idle under `OnDemand` and `Idle`), `Loop.Run` holds a display keep-awake lock (`core.Scope.KeepAwake` with `Display: true`) so the device does not dim or auto-lock mid-game: - **Background, `stop`, or scope disposal**: the display hold is released immediately. - **Paused or idle `OnDemand` loops**: once the loop is `Paused` or `OnDemand`-idle (`Idle()` returns `true`, with no pending `Step` updates or `MarkDirty` wake/draw), the hold is released after `PausedAwake`. The default `0` (or any non-positive value) releases the hold immediately so the OS auto-lock timer runs normally on pause, title, waiting-dialogue, and game-over screens. - **Grace period (`PausedAwake`)**: set `PausedAwake` (for example `30 * time.Second`) to keep the display awake briefly after pausing, going idle, or after the last `Step` / `MarkDirty` before releasing the hold. - **Resuming and stepping**: calling `SetPaused(false)` takes the hold again immediately (changing `Paused = false` directly or having `Idle()` return `false` takes it on the next frame). Queuing `Step` updates while paused or calling `MarkDirty` on a paused or idle `OnDemand` loop keeps the hold while those updates or draws run and resets the `PausedAwake` timer. - **Cutscenes**: [`cutscene.Player`](http://nsgo.games/docs/cutscene/) takes its own display hold while a cutscene plays, so pausing the game loop underneath a cutscene does not let the screen sleep. ```go loop := &game.Loop{ Rate: 60, PausedAwake: 30 * time.Second, // optional grace period on pause menus Update: stepWorld, Draw: renderWorld, } loop.Run(cx) ``` ## Immersive mode on phones Set `Immersive` to hide a phone's system bars while the game plays and bring them back in menus. The loop calls NSGo's `mobile.Immersive`: Android hides its status and navigation bars and shows them briefly on an edge swipe, iOS hides the status bar and lets the home indicator fade, and HarmonyOS hides its status bar, navigation bar and navigation indicator. Desktop and web targets ignore it. ```go loop := &game.Loop{ Immersive: true, Update: stepWorld, Draw: renderWorld, } loop.Run(cx) // Opening the pause menu shows the bars on the next frame; closing it hides them again. openMenu := func() { loop.SetPaused(true) } closeMenu := func() { loop.SetPaused(false) } ``` - The bars hide while the loop runs and is not `Paused`, and come back while it is `Paused`, when `stop` is called and when `cx` is disposed, so a menu screen that replaces the game's view brings them back too. - The loop hides them as it starts or returns from the background, applies a change to `Immersive` or `Paused` on its next frame (in the same frame when `Update` pauses), and asks the platform only when the state changes. It leaves the bars as they are while the app is in the background. - Hiding and showing the bars can change the safe-area insets the platform reports (HarmonyOS, for one, keeps only the display cutout while they are hidden), so lay HUDs out with [`screen.Viewport.SafeGameRectForEnv`](http://nsgo.games/docs/screen/#safe-area-for-mobile-huds), which follows the insets as they change. - Loops in the same window share the bars: they stay hidden while any loop with `Immersive` set plays, and come back once the last of them pauses or ends. A scene that starts its own loop while the previous scene's loop is still alive, as under a scene transition, keeps the bars hidden when the old loop is disposed, and a pushed scene's loop keeps them hidden when the scene below pauses its own. A menu shown as an NSGo page or dialog can also set `StatusBar: core.StatusBarSetting{Immersive: core.ToggleOff}`, which overrides the window's setting while it is shown. ## Testing with nsgotest `nsgotest` runs display frames deterministically on a virtual clock (one frame every 16.667 ms, 60 frames a second), so you can test gameplay loops, `MaxSteps` hitches and background pauses without sleeping. ```go package mygame_test import ( "testing" "time" "github.com/nsgo-dev/game" "github.com/nsgo-dev/nsgo/core" "github.com/nsgo-dev/nsgo/nsgotest" ) func TestMain(m *testing.M) { nsgotest.Main(m) } func TestLoopSimulation(t *testing.T) { updates := 0 l := &game.Loop{ Rate: 60, MaxSteps: 4, Update: func(dt time.Duration) { updates++ }, } app := nsgotest.Start(t, func(cx *core.Scope) core.Node { l.Run(cx) return core.View{} }) // Advance steps frame by frame for one full second. app.Advance(time.Second) if updates != 60 { t.Fatalf("got %d updates, want 60", updates) } // FastForward jumps in a single frame, exercising MaxSteps. app.FastForward(500 * time.Millisecond) if updates != 64 { t.Fatalf("got %d updates after hitch, want 64", updates) } // Background pauses the loop with no catch-up on resume. app.SetEnvironment(core.Environment{Lifecycle: core.LifecycleBackground}) app.Advance(time.Second) app.SetEnvironment(core.Environment{Lifecycle: core.LifecycleActive}) if updates != 64 { t.Fatalf("got %d updates while backgrounded, want 64", updates) } } ``` ## Guarding unsaved progress on quit `save.QuitGuard` centralizes the decision used by close and quit adapters: a clean request closes, an ordinary request with unsaved progress saves first when the game can save now (`QuitSave`) and asks the player otherwise (`QuitAsk`), and a forced shutdown saves best effort with `SaveForced` and closes even when saving fails (`QuitSaveAndAllow`). See [Unsaved progress on close](http://nsgo.games/docs/save/#unsaved-progress-on-close). Register `gameui.GuardQuit` once in the game's window scope with a `gameui.QuitGuardOptions`. The adapter handles both system Quit and the window close button, including the close button on macOS. `Ask` opens the game's confirmation UI. Call its answer with `true` to close or `false` to keep playing, on the same scope. Use `Pause` to suspend simulation while the question is open and combine that pause with the game's existing pause state. `Report` can display or log a save error. A failed ordinary save falls back to confirmation and a forced quit proceeds after a best-effort save. Mount `gameui.QuitConfirmation` alongside the game view. Give its `Open` the signal set by `Pause` and forward `OnAnswer` to the reply from `Ask`. The dialog initially focuses Cancel. Set `Save` to offer Save and quit, and optionally `CanSave` to control when the action is available. A failed save keeps the dialog open for retry. To use a controller, call `gamepad.EnableFocusNavigation` on the window scope and release any gameplay input capture while the question is open. For Restart or Quit to title, supply the action's own copy and handle `OnAnswer` directly. `Loop.PauseOnLeave` and `HandleLeave` provide a shared leave-policy hook for pausing and save callbacks when a game loses focus or backgrounds. ### Fixed-step interpolation `tilemap.Camera` keeps its previous fixed-step pose: call `BeginStep` before each `Update` that moves it, `ResetInterpolation` after a teleport or a cut, and `InterpolatedPose(alpha)` in `Draw` for the position and rotation to draw (rotation turns along the shortest arc; `Zoom` is not interpolated). It never changes the camera, so simulation state stays the same. Physics bodies and scene objects keep no previous pose yet; interpolate them by hand as in [Interpolating with alpha](http://nsgo.games/docs/loop/#interpolating-with-alpha). --- Source: http://nsgo.games/docs/sprite/ # sprite `game/sprite` loads packed sprite atlases, plays frame animations on a fixed step, and draws Z-ordered sprite batches into an NSGo `core.Canvas`. ```go import "github.com/nsgo-dev/game/pkg/sprite" ``` ## Atlases from TexturePacker and Aseprite An `Atlas` pairs one packed image (`Image`) with its named frames (`Frames`) and optional named animations (`Animations`). `LoadAtlas(img, data)` reads the JSON exported by: - **TexturePacker**: "JSON (Hash)" and "JSON (Array)" - **Aseprite**: `json-hash` and `json-array` (with frame tags enabled to populate `Animations`) Put the packed PNG in `resources/` so NSGo packages it as `"asset:..."`, and embed the JSON with `//go:embed`: ```go //go:embed resources/hero.json var heroJSON []byte atlas, err := sprite.LoadAtlas(core.Src("asset:hero.png"), heroJSON) if err != nil { return err } ``` ### Export settings and scale - **Turn rotation off**: `LoadAtlas` rejects rotated frames with an error. - **Keep frame names unique**: duplicate frame names return an error. - **High-DPI sheets (`meta.scale`)**: all frame rectangles, offsets and source sizes are divided by `meta.scale` (defaults to `1`). A 2× sheet exported with `"scale": "2"` produces coordinates in 1× points, matching NSGo's point coordinates. ### Hand-written atlases For simple tile sheets, prototypes or tests, build an `Atlas` literal directly without JSON: ```go sheet := &sprite.Atlas{ Image: core.Src("asset:sheet.png"), Frames: map[string]sprite.Frame{ "hero": {Name: "hero", X: 0, Y: 0, W: 16, H: 16, Width: 16, Height: 16}, "coin": {Name: "coin", X: 16, Y: 0, W: 8, H: 10, OffsetX: 4, OffsetY: 3, Width: 16, Height: 16}, }, } ``` ## Trimmed frames Packers often trim transparent borders around each frame to pack more pictures into one image. `Frame` keeps both the trimmed rectangle in the atlas and its untrimmed box: `Frame` also carries optional baked 2D collision polygons (`Shapes`) and named image points (`Points`), both in untrimmed frame points from the top left: ```go type Frame struct { Name string X, Y, W, H float32 // trimmed rectangle in the atlas image, in points OffsetX, OffsetY float32 // position of the trimmed rectangle inside the untrimmed box Width, Height float32 // untrimmed frame size (W, H when untrimmed) PivotX, PivotY float32 // pivot in untrimmed frame points from the top left Shapes [][]math2d.Vec2 // convex collision polygons, wound CW in Y-down space Points map[string]math2d.Vec2 // named image points (muzzle, hand, feet, ...) } ``` `Sprite` always aligns `OriginX`, `OriginY`, `FlipX`, `FlipY`, rotation and scaling to the untrimmed box (`Width`, `Height`). Trimming never shifts a character's feet, named points, or collision polygons as animations change from frame to frame. ## Collision polygons and named image points Configure `image.collision`, `image.points`, and `image.cellPoints` in an image's `.import.yaml` sidecar (see [assets](http://nsgo.games/docs/assets/#image-collision-and-named-points)) so `go tool game assets` and `go tool game pack` trace alpha silhouettes with marching squares, simplify each convex part to at most `maxVertices` (default `8`), split concave outlines into convex polygons, and bake `shapes` and `points` directly into the packed atlas JSON. The runtime never traces images. `LoadAtlas` reads: - Packed `frames..shapes` and `frames..points`, dividing every coordinate by `meta.scale`. - Aseprite `meta.slices` entries whose keys carry a `pivot`, mapping each slice's `bounds + pivot` into `Frame.Points[slice.name]` across the key's frame span (and into `Atlas.Animations`). Use `Sprite.PointWorld(name)` and `Sprite.ShapesWorld()` to read them in world (drawing) coordinates with `FlipX`, `FlipY`, `OriginX`/`OriginY`, `ScaleX`/`ScaleY`, `Rotation`, and `(X, Y)` applied: ```go if muzzle, ok := hero.PointWorld("muzzle"); ok { spawnBullet(muzzle.X, muzzle.Y, hero.FlipX) } ``` When a sprite is mirrored (`FlipX`, `FlipY`, or negative scale), `ShapesWorld()` reverses polygon vertex order so every polygon retains clockwise winding in Y-down space. In scene files, set `collider2d` (or `trigger2d`) `shape: sprite` so 2D physics takes the current frame's `Shapes` and automatically follows frame changes, flips, scale, and rotation on `PhysicsScene.Step` (or `PhysicsScene.SyncSpriteColliders`). ## Animation `Animation` advances through a slice of `AnimationFrame` values, each with its own `Duration`, driven by `Update(dt)` inside `game.Loop.Update`: ```go type Animation struct { Frames []AnimationFrame Loop bool // ... } type AnimationFrame struct { Frame Frame Duration time.Duration } ``` `Animation` is a value that holds its playback state (current frame index, elapsed time, and completion flag). Copy it from `atlas.Animations` so every entity advances independently: ```go walk := atlas.Animations["walk"] attack := atlas.Animations["attack"] ``` Methods on `Animation`: - `Update(dt)`: advances by `dt`, skipping past as many frames (or full loops) as `dt` covers. - `Frame()`: returns the current `Frame` (zero `Frame` if `Frames` is empty). - `Index()`: returns the current index in `Frames`. - `Done()`: reports whether a non-looping animation has finished displaying its final frame for that frame's full duration. - `Reset()`: rewinds back to frame 0 and clears `Done()`. ### Aseprite frame tags When loading an Aseprite export, each entry in `meta.frameTags` becomes an entry in `atlas.Animations`: - Frame durations come from each frame's `duration` in milliseconds (every frame used by a tag must have a positive duration). - Supported tag directions: `"forward"` (default), `"reverse"`, `"pingpong"` and `"pingpong_reverse"`. - A tag with no `repeat` (or `repeat: 0`) sets `Loop: true`. A tag with `repeat: N` expands `N` passes into a non-looping `Animation` (`Loop: false`). Ping-pong tags count each direction pass as one repeat and never show the turning frame twice in a row. ### Hand-written animations For TexturePacker sheets (which carry no frame tags), assemble an `Animation` from `atlas.Frames`: ```go spin := sprite.Animation{ Loop: true, Frames: []sprite.AnimationFrame{ {Frame: atlas.Frames["coin_0.png"], Duration: 100 * time.Millisecond}, {Frame: atlas.Frames["coin_1.png"], Duration: 100 * time.Millisecond}, {Frame: atlas.Frames["coin_2.png"], Duration: 100 * time.Millisecond}, }, } ``` ## Sprite placement and transforms A `Sprite` places one `Frame` in a `core.Drawing`. Its zero value has `ScaleX == 0`, `ScaleY == 0` and `Alpha == 0`, so it draws nothing. Start with `sprite.NewSprite(frame)` to get full scale (`1, 1`) and full opacity (`1`): ```go hero := sprite.NewSprite(walk.Frame()) hero.OriginX = hero.Frame.Width / 2 hero.OriginY = hero.Frame.Height // anchor at the character's feet hero.X, hero.Y = 120, 200 ``` Fields on `Sprite`: | Field | Meaning | | --- | --- | | `Frame` | The `Frame` to draw; a zero frame (`W <= 0` or `H <= 0`) draws nothing. | | `X`, `Y` | Where the sprite's origin sits in the drawing, in points. | | `OriginX`, `OriginY` | Pivot point inside the untrimmed frame, from its top left. | | `Rotation` | Clockwise rotation about the origin, in radians. | | `ScaleX`, `ScaleY` | Scale about the origin; a negative value mirrors about the origin; `0` draws nothing. | | `FlipX`, `FlipY` | Mirrors the frame inside its untrimmed box before placement, keeping the origin in place. | | `Alpha` | Opacity in `[0, 1]`; `<= 0` draws nothing. Replaces the drawing's alpha for this sprite. | | `Tint` | A `core.Color` that multiplies the frame's red, green, blue and alpha before the sprite is composited; the zero value and opaque white draw the frame unchanged, and any other tint with alpha `0` draws nothing. To fade a sprite out, lower `Alpha`: a tint that reaches transparent black is the zero value and draws the frame unchanged. | | `Effect` | Optional `*Effect` applying per-sprite solid-color flash or silhouette, alpha outline, dissolve, palette swap, or a custom pixel hook to this sprite's pixels alone. A `nil` or inactive `Effect` keeps the sprite on `DrawAtlas`. | | `Z` | Draw order inside a `Batch`; higher `Z` draws on top of lower `Z`. | A tinted sprite recolors only its own pixels: it draws with NSGo's `DrawTintedImageFrom`, which multiplies the image's channels by the tint before compositing with the default source-over mode, so transparent pixels leave what is under the sprite unchanged. `Tint` combines with `Alpha`, `Blend` and `Mask` in the same draw: ```go hit := sprite.NewSprite(atlas.Frames["slime.png"]) hit.Tint = core.RGB(0xff6060) // flash red when damaged ghost := hit ghost.Tint = core.RGBA(0x80c0ff, 0.5) // a pale blue at half the sprite's opacity ``` On the web, a cross-origin atlas image must allow anonymous CORS requests for NSGo to tint its pixels. On HarmonyOS, NSGo tints atlases loaded from bytes or the app's resources, but tinting is not yet checked on a device there, and an atlas built from a pixel buffer or an offscreen image draws nothing there yet. ## Per-sprite effects `Sprite.Tint` multiplies existing channels (so dark pixels stay dark under a white tint) and `game/postfx` runs fragment passes over the whole game view. For per-sprite hit flashes, silhouettes, outlines, dissolves and palette swaps that never touch neighboring sprites or the backdrop drawn beneath the sprite, set `Sprite.Effect`: ```go fx := &sprite.Effect{ Flash: sprite.Flash{Color: core.RGB(0xffffff), Strength: 0.8}, // or sprite.Silhouette(core.RGB(0xffffff)) Outline: sprite.Outline{Color: core.RGB(0xffdd00), Thickness: 1}, } hero.Effect = fx // Parameters can change every frame; clearing them returns the sprite to DrawAtlas. fx.Flash.Strength = 0 ``` Stages on `Effect` compose in a fixed order: 1. **`PaletteSwap`**: remaps straight 8-bit sRGB colors matching `Entries` (within `Tolerance`, first match wins) while scaling pixel alpha by `To`'s alpha. 2. **`Sprite.Tint`**: multiplies base sprite color when `Tint` is also set (so hit flashes and outlines are not darkened by the sprite's base tint). 3. **`Dissolve`**: discards pixels whose noise value is below `Threshold` (`[0, 1]`), optionally coloring surviving pixels in `[Threshold, Threshold+EdgeWidth)` with `EdgeColor`. Uses deterministic hash/value noise seeded by `Seed` and cell size `Scale`, or samples a custom grayscale `Noise` image. 4. **`Flash`**: lerps non-transparent RGB toward `Flash.Color` by `Strength` (`[0, 1]`) while preserving each pixel's alpha. `Silhouette(color)` is shorthand for `Strength: 1`. 5. **`Outline`**: draws a rounded solid-color border of `Thickness` source pixels around pixels whose alpha is at least `AlphaThreshold` (default: any non-zero alpha). The sprite buffer expands by `ceil(Thickness)` transparent pixels on every side so tightly cropped frames are never clipped and adjacent frames in the atlas never bleed into the border. 6. **`Custom`**: optional per-pixel hook `func(x, y, w, h int, r, g, b, a float32) (nr, ng, nb, na float32)` over premultiplied RGBA after the built-in stages. ### GPU shader view (`EffectShader`) When a sprite is rendered as its own GPU shader node (for example a boss or portrait animated on the platform's frame clock with `core.AnimatedNode` uniforms, or an `asset:` URI atlas on a GPU-backed target), `EffectProgram`, `Effect.Uniforms` and `EffectShader` run the same built-in stages (palette swap up to `MaxShaderPaletteEntries` = 8 entries, tint, dissolve, flash/silhouette and outline) in a Kage fragment shader (`core.Shader`): ```go sh, err := sprite.EffectShader(atlas, hero) if err != nil { return err } sh.Uniforms["FlashStrength"] = flashNode // animates on the frame clock with no commit per frame ``` `EffectProgram` compiles lazily on first call, so games that only use `Batch.Draw` do not link NSGo's shader compiler. ### Cost per sprite - **Inactive `Effect`**: a `nil` or zero/inactive `*Effect` adds one nil/boolean check and stays on `Batch`'s `DrawAtlas` fast path with zero extra draw calls or pixel work. - **Static active `Effect` in `Batch.Draw`**: each effected sprite occupies one reused scratch slot in `Batch`. When the atlas version, frame, tint and effect parameters are unchanged from the previous frame, `Batch.Draw` skips pixel recomputation and reuses the same `ImageSource.Version`, so NSGo skips copying and uploading the buffer (`~0.21 µs` per 32×32 sprite). - **Changing parameters every frame in `Batch.Draw`**: `Batch` reuses each slot's `*image.RGBA` and alpha scratch slice in place (growing capacity only when dimensions increase and trimming idle tail slots back down), so mutating `Flash.Strength`, `Outline.Thickness`, `Dissolve.Threshold` or `PaletteSwap.Entries` every frame performs zero pixel-buffer allocations and bumps `ImageSource.Version` monotonically. Cost scales linearly with the frame's pixel area (`W × H`, plus `(W+2p) × (H+2p) × πr²` for `Outline` on non-opaque edge pixels). Reference `BenchmarkSpriteEffects` readings on Apple Silicon (`-cpu 1`): | Effect (32×32 sprite, updated every frame) | CPU time / sprite | Heap allocs / frame | | --- | ---: | ---: | | `Flash` (16×16) | 0.84 µs | 1 (`96 B`, `DrawOp` image copy) | | `Flash` (32×32) | 3.3 µs | 1 (`96 B`) | | `Outline` (1 px, 32×32) | 6.2 µs | 1 (`96 B`) | | `Outline` (2 px, 32×32) | 13.1 µs | 1 (`96 B`) | | `Dissolve` + edge glow (32×32) | 7.1 µs | 1 (`96 B`) | | Static `PaletteSwap` (32×32, cached hit) | 0.21 µs | 1 (`96 B`) | - **GPU `EffectShader`**: one `core.Shader` surface per sprite view (no per-frame CPU pixel writes or uploads once the atlas texture is on the GPU; best suited to a small number of hero/boss/UI sprites rather than hundreds of batched entities). ### Per-target behavior and fallbacks `Batch.Draw` applies exact CPU pixel effects whenever the atlas exposes pixels (`Atlas.Image.Pixels != nil`, or `Atlas.Image.Data` decoded lazily via `image.Decode` using any decoder the app imports such as `_ "image/png"`). If an atlas is URI-only (`core.Src("asset:...")` with neither `Pixels` nor `Data`), `Batch.Draw` falls back without touching neighbors or canvas composite state: full dissolve (`Threshold >= 1`) skips drawing, `Flash` falls back to NSGo's per-draw multiply tint (`DrawTintedImageFrom`, exact for darkening flashes and black silhouettes, unable to brighten dark texels toward white), and `Outline`, partial `Dissolve`, `PaletteSwap` and `Custom` draw the sprite unmodified. | Target | `Batch.Draw` (`Pixels` or `Data` atlas) | `Batch.Draw` (URI-only atlas) | `EffectShader` (`core.Shader` GPU) | | --- | --- | --- | --- | | macOS, iOS | Full exact effects via `CGImage` pixel buffer | `DrawTintedImageFrom` flash fallback; full dissolve skipped | Full GPU shader (Metal) | | Windows | Full exact effects via Direct2D premultiplied BGRA bitmap | `DrawTintedImageFrom` flash fallback; full dissolve skipped | Full GPU shader (Direct3D 11) | | Linux | Full exact effects via Cairo ARGB32 surface | `DrawTintedImageFrom` flash fallback; full dissolve skipped | Full GPU shader (OpenGL 3.3 / ES 3.0) | | Android | Full exact effects via `Bitmap` pipe transfer | `DrawTintedImageFrom` flash fallback; full dissolve skipped | Full GPU shader (GLES 3.0) | | Web (Wasm) | Full exact effects via cached offscreen `` | `DrawTintedImageFrom` flash fallback (CORS required cross-origin); full dissolve skipped | Full GPU shader (WebGL 2) | | HarmonyOS | Full exact effects via `PixelMap` pixel buffer (`Tint` folded into pixels) | `DrawTintedImageFrom` flash fallback (not yet device-verified); full dissolve skipped | Unavailable (shader view draws empty; use `Batch.Draw`) | | Mini programs | Full exact effects via offscreen 2D canvas `putImageData` | `DrawTintedImageFrom` flash fallback; full dissolve skipped | Unavailable (`nsgo_noshader`; use `Batch.Draw`) | | Headless (`gametest.RenderOps`) | Full exact pixel output for pixel-comparison tests | Records `DrawTintedImageFrom` / `DrawImageFrom` ops | Models lanes and uniforms in `nsgotest` | ### Color matrices `sprite.ColorMatrix` is a row-major 4x5 matrix over straight (unpremultiplied) RGBA: each output channel is a row's first four entries dotted with the input plus the row's fifth entry. `IdentityColorMatrix`, `Grayscale` (Rec. 709 luminance), `Brightness`, `Invert` and `HueRotate` build one, and `Apply` transforms one color without clamping. Nothing draws with it yet: `Batch.Draw`, `Effect` and the frame effects do not take a color matrix, so apply it to colors you compute, such as a `Tint`. ## Batch and Z ordering A `Batch` draws sprites from a single `Atlas` into a `*core.Drawing`: ```go batch := &sprite.Batch{ Atlas: atlas, Sprites: []*sprite.Sprite{&shadow, &hero, &weapon}, } // Inside core.Canvas.Draw: batch.Draw(d) ``` - **Ordering**: `Draw` stably sorts sprites into an internal scratch slice by ascending `Z` (lowest `Z` drawn first, equal `Z` in the order `Sprites` lists them). `batch.Sprites` itself is never reordered. - **Drawing state**: `Draw` leaves `d`'s transform, alpha, composite and clip exactly as it found them. - **Draw calls**: consecutive sprites, in Z order, that are only moved, rotated and scaled evenly (`ScaleX == ScaleY`, or both flips together) with the default `Blend` and no `Mask` of their own draw with one NSGo `DrawAtlas`. A mirrored, unevenly scaled, blended or masked sprite, and a run of only one sprite, draws with its own `DrawImageFrom`, wrapped in `Save`/`Restore` when it is turned, mirrored, faded, blended or masked. - **Alpha in a run**: a run of sprites at full opacity keeps the drawing's alpha, as a single sprite does. A run of faded sprites draws between `Save` and `Restore` with the alpha set to `1` and each sprite's own `Alpha`, so `Alpha` still replaces the drawing's alpha. A change from opaque to faded sprites starts a new run. - **Depth-sorted scene layers**: a `game/scene` layer sorted by Y (`SortY`) or by a custom key draws its sprites one at a time, so each is a run of one and still draws with its own `DrawImageFrom`. Only layers without per-sprite sorting, and batches drawn directly, get `DrawAtlas`. - **Skipped sprites**: a sprite whose position, origin, rotation, scale or alpha is NaN or infinite draws nothing, as does a batch with no `Atlas`. The picture is the same as one `DrawImageFrom` per sprite: the tests replay both recordings and compare every drawn rectangle, a fuzz test does so for random batches, and `gametest.RenderOps` renders both to identical pixels. ### Recording cost before and after `DrawAtlas` `BenchmarkBatchRecord` records a frame of 1,000 and 5,000 moving sprites, a fifth of them rotated and scaled, with one `DrawImageFrom` each (`per-sprite`) and with `DrawAtlas` (`atlas`). It times only recording on the CPU, not the platform's drawing. `sprites/60Hz` is 16.7 ms divided by the recording time per sprite, an upper bound that no frame reaches, not a measured sprite count at 60 frames per second: ```sh go tool nsgo test ./pkg/sprite -- -run '^$' -bench BatchRecord -benchmem -cpu 1 -benchtime 2s ``` Readings from 2026-11-23 on a shared 24-core x86-64 Linux machine; the times move with the machine's load, the allocations do not: | Sprites | Recording time per frame | Allocations per frame | Sprites recorded per 16.7 ms | | ---: | ---: | ---: | ---: | | 1,000 | 219 µs → 81 µs | 1,000 → 3 | 76,000 → 206,400 | | 5,000 | 926 µs → 586 µs | 5,000 → 3 | 90,000 → 142,300 | Recording is the smaller part of a frame: the platform still draws every sprite. The largest sprite count this repository's `Batch` holds at 60 frames per second on a device, before and after, has not been measured yet ([#28](https://github.com/nsgo-dev/game/issues/28)). NSGo's own [many-sprite comparison](https://github.com/nsgo-dev/nsgo/blob/main/docs/architecture/performance.md#canvas-atlas-batching) of `DrawAtlas` against one `DrawImageFrom` per sprite, with its own fixture of 32 × 32 crops rather than this `Batch`, measured frame rates at a fixed sprite count: 5,000 sprites rose from 29.3 to 39.9 frames per second on a Pixel 3 XL, from 55.5 to 60.0 in headless Chromium and from 6.6 to 7.8 on macOS, with 1,000 sprites already at 60 frames per second on Android and Chromium. On Linux it has no reliable reading yet: in a shared Ubuntu VM the isolated Cairo replay of 5,000 sprites fell from 20.86 to 15.81 ms, but the end-to-end rates, which moved with the host's load, were lower in the first atlas run (25.54 to 10.83 at 1,000 sprites and 10.37 to 1.98 at 5,000), and NSGo calls for a paired run on a dedicated machine. ## Testing with nsgotest Because `Batch.Draw` records ordinary `core.DrawOp` operations on a `core.Canvas`, you can inspect what a batch drew headlessly with `nsgotest`: ```go app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return core.Canvas{ TestID: "stage", Style: core.Style{Width: core.Pt(320), Height: core.Pt(240)}, Draw: func(d *core.Drawing, _ core.Size) { batch.Draw(d) }, } }) ops := app.Find("stage").Ops if len(ops) == 0 { t.Fatal("expected sprite draw operations") } ``` A batch records its sprites in `DrawAtlas` operations as well as `DrawImageFrom` ones, so check what it drew with `gametest.ImageDraws(ops)` rather than by counting `DrawImage` operations. It returns each drawn rectangle of an image, with its source rectangle, its corners on the canvas, its alpha, composite, tint, sampling and clip, however it was recorded. `gametest.AssertSameImages(t, got, want)` compares two recordings that way, images only (fills, strokes and texts are checked separately), such as a batch against hand-written `DrawImageFrom` calls, and `gametest.RenderOps` renders `DrawAtlas` too. ### Optional draw counters `Batch.Stats` accepts an optional `DrawCounter` for development diagnostics. It records atlas submissions, single-sprite submissions and sprite-level break reasons (`tint`, `blend`, `mask`, `effect`, `mirror`, `unevenScale`, `alphaChange` and `lone`) without changing rendering when unset. `AtlasCalls` counts submissions and `AtlasSprites` counts sprites in those submissions. `Draw` only adds to the counts, so call `Reset` once per frame for per-frame figures. --- Source: http://nsgo.games/docs/sound/ # sound `game/sound` layers a persistent volume `Mixer`, voice-limited sound `Effect`s, crossfading `Music`, and automatic background muting on top of NSGo's `audio` package. ```go import ( "github.com/nsgo-dev/game/pkg/sound" "github.com/nsgo-dev/nsgo/audio" ) ``` All `Mixer`, `Effect` and `Music` methods run on the engine's goroutine, just like `audio`'s methods. From any other goroutine, dispatch through `cx.Post`. Ship audio files under `resources/` as **WAV**, **AAC (`.m4a`)** or **MP3**. ## Mixer and persistent volumes A `Mixer` holds one master volume and a volume for every group name your game uses (for example `"effects"`, `"music"` and `"ui"`). Every volume is in `[0, 1]` and defaults to `1`. ```go mixer := sound.NewMixer(cx, "sound") ``` `NewMixer(cx, key)` stores values in `cx.Storage()` (`core.Storage`) under: - `.master` - `.group.` Volumes persist automatically across app launches. Passing values outside `[0, 1]` clamps them (and `NaN` resets to `1`). If storage is full, `SetMaster` and `SetVolume` return `*core.StorageFullError` and keep the previous volume. `SetDefaultMaster` and `SetDefaultVolume(group, v)` set the volume a mixer has until the player sets one, such as a bus volume from the [project file](http://nsgo.games/docs/project/). They keep nothing in storage, so a volume the player set wins; set them before the game reads volumes. ### Reactive settings UI `Master()` and `Volume(group)` read from `core.Storage`, so calling them inside a reactive view function subscribes that view to volume changes automatically: ```go core.Text{ ContentFunc: func() string { return fmt.Sprintf("Music: %.0f%%", mixer.Volume("music")*100) }, } ``` ### How volume changes take effect - **Effects**: each playback uses `voice.Volume * mixer.Volume(group) * mixer.Master()`. Volume changes apply at once to effects already playing, through each playback's `audio.Playback`, and to those started afterwards. A playback whose group or master volume reaches `0` plays on in silence and is heard again when the volume comes back. - **Music**: active tracks update live at `mixer.Volume(group) * mixer.Master()`, pausing when the effective gain reaches `0` and resuming from the same position when raised above `0`. ## Effect and voice limits Short sounds (under 8 MiB encoded and 5 seconds decoded) are decoded into memory once with `audio.LoadSound`, then wrapped in a mixer `Effect`: ```go var hit *sound.Effect audio.LoadSound(cx, audio.Source{URI: "asset:sounds/hit.wav"}, func(s *audio.Sound, err error) { if err != nil { return } hit = mixer.Effect(s, "effects", 4) }) ``` The third argument (`limit`) caps how many overlapping playbacks of that sound may run at once (`0` means no per-effect cap, still bounded by the platform's 32 concurrent sound voices). This prevents rapid bursts — such as coins or footsteps — from starving every other sound. - `Play(v audio.Voice) bool` starts a playback and reports whether it asked for one. It returns `false` when effective gain is `0` (including a voice with `Muted` set) or the app is in the background, and `true` otherwise, even where the playback ends at once because the backend could not start it. When `Limit` playbacks are still playing, it stops the oldest of them to make room, so the newest are heard; playbacks that end on their own free their place without stopping another, and one that never started leaves them playing. A backend that cannot address playbacks plays the voice as it started, outside the limit and later volume changes; every NSGo backend with audio can. - `Stop()` stops every playback of that sound (and any other `*audio.Sound` sharing the same source). - Close the underlying `*audio.Sound` when you no longer need it, or let `cx`'s scope disposal free it. ```go if hit != nil { hit.Play(audio.Voice{Volume: 0.9, Rate: 1.05}) } ``` ## Concurrency groups, priority, retrigger time, and ducking Beyond a single `Effect.Limit`, `Mixer` supports named concurrency groups shared across multiple `Effect`s and `Cue`s, a global voice budget with cross-group priority stealing, minimum retrigger intervals, steal fade-outs, older-voice group ducking, and bus ducking: ```go mixer.SetMaxVoices(28) // default: sound.DefaultMaxVoices (30, below the platform's 32) mixer.SetConcurrencyGroup("impacts", sound.ConcurrencyGroup{ Max: 4, Resolve: sound.ResolveQuietest, // ResolveRefuse (default), ResolveOldest, ResolveFarthest, ResolveQuietest, ResolveLowestPriority Scope: sound.ScopeGlobal, // ScopeGlobal (default) or ScopeOwner Retrigger: 40 * time.Millisecond, StealFade: 30 * time.Millisecond, Duck: sound.DuckEnvelope{Amount: 0.25, Attack: 20 * time.Millisecond, Release: 150 * time.Millisecond}, }) mixer.SetBusDucking(sound.BusDuckRule{ Bus: "music", By: "dialogue", Amount: 0.4, // lowers music by 40% (to 0.6x) while dialogue plays Attack: 100 * time.Millisecond, Release: 500 * time.Millisecond, }) hit.Concurrency = "impacts" hit.Priority = 10 hit.PlayWith(audio.Voice{Volume: 0.9}, sound.PlayOptions{Owner: enemyID}) ``` - **Shared concurrency groups**: set `Effect.Concurrency` (or `CueOptions.Concurrency` / `PlayOptions.Concurrency`) to assign many different sounds to one registered group. When `Max` active voices are already playing in the group, `Resolve` decides what happens: `ResolveRefuse` drops the new sound, `ResolveOldest` stops the oldest active voice, `ResolveFarthest` stops the farthest positional voice (or refuses if the new sound is farther), `ResolveQuietest` stops the quietest audible voice (or refuses if the new sound is quieter), and `ResolveLowestPriority` stops the lowest-priority voice (breaking ties by oldest, or refusing if the new sound has strictly lower priority). - **Owner scope**: with `Scope: sound.ScopeOwner`, `Max`, `Retrigger`, and `Duck` apply independently per `PlayOptions.Owner` (any comparable value such as an entity ID, string, or pointer) through `Effect.PlayWith`, `PlayAtWith`, `PlayAt3DWith`, `Play3DWith`, and the matching `Cue` methods. - **Retrigger time**: `Retrigger` rejects new starts in the group (or owner) arriving sooner than the cooldown after the last accepted start, without stopping voices already playing. - **Steal fade-out**: when `StealFade > 0`, voices stolen by a concurrency group are removed from active voice counts immediately and smoothly ramped to silence over `StealFade` before stopping. - **Group ducking**: `ConcurrencyGroup.Duck` lowers older active voices in the same concurrency scope as newer voices start (scaling each older voice by `(1 - Amount)^newer`), ramping in over `Attack` and recovering over `Release` automatically as newer voices finish. - **Bus ducking**: `SetBusDucking` / `AddBusDucking` lowers `Bus` by `Amount` (in `[0, 1]`, where `0.4` yields `0.6x` gain and `1` silences while keeping `Music` playheads advancing) whenever any `Effect` or `Music` plays on bus `By` (or in concurrency group `By`), with smooth `Attack` and `Release` envelopes. Multiple rules targeting the same bus stack multiplicatively. - **Global voice budget and priority**: `Mixer` caps total active voices at `MaxVoices()` (`DefaultMaxVoices`, `30`, by default) and steals the lowest-priority active voice across all groups (ties broken by oldest), refusing strictly lower-priority sounds so bursts of minor effects never cut important dialogue or player cues. - **Project configuration and validation**: declare `audio.maxVoices`, `audio.concurrency`, and `audio.duck` in [`game.yaml`](http://nsgo.games/docs/project/) and install them with `File.ConfigureMixer(mixer)`. `go tool game check` validates `concurrency:` names referenced by `*.sound.yaml` files against `game.yaml`. - **Debug readout**: call `mixer.DebugSnapshot()` — or pass `Sound: mixer` to [`gamedebug.Options`](http://nsgo.games/docs/gamedebug/) and [`mcp.Config`](http://nsgo.games/docs/mcp/) (`game_sound_readout`) — to inspect active and fading voice counts, global budget, per-group counts and counters (`refused`, `stolen`, `retriggered`), and live bus duck gains. ## Bus effect chains `mixer.SetGroupEffects(group, ...)` gives a group a DSP chain of bus effects, run in order, and `mixer.GroupEffects(group)` reads it back. The list is `sound.LowPass`, `sound.HighPass`, `sound.BandPass`, `sound.Notch`, `sound.PeakingEQ`, `sound.EQ`, `sound.LowShelf`, `sound.HighShelf`, `sound.Delay`, `sound.Reverb`, `sound.Chorus`, `sound.Phaser`, `sound.Distortion`, `sound.PitchShift`, `sound.Panner`, `sound.StereoWidth`, `sound.Compressor`, `sound.Limiter`, `sound.Gain` and `sound.Bitcrush`. A project's `game.yaml` `audio.buses` `effects` install the same chains through [`project.File.ConfigureMixer`](http://nsgo.games/docs/project/). The families split by what they do to a bus: - **Filters** are 2nd-order RBJ biquads: `LowPass` and `HighPass` keep one side, `BandPass` and `Notch` work around one frequency, `PeakingEQ`, `LowShelf` and `HighShelf` change a band by dB, and `EQ` applies a list of peaking bands in order, so one entry shapes several frequencies. `Q` defaults to Butterworth when it is not positive. - **Dynamics** are `Compressor` (threshold, ratio, attack and release) and `Limiter` (a ceiling no sample passes). - **Modulation and drive**: `Chorus` reads a wet copy from a delay sweeping around 20ms by `depthMs` at `rateHz`, `Phaser` sweeps four all-pass stages between 400 Hz and 1600 Hz with feedback and a dry/wet mix, `Distortion` drives a sample by dB and shapes it with `DistortionClip`, `DistortionTanh` or `DistortionFold`, and `PitchShift` retunes by semitones with overlapping 40ms Hann grains, so the duration and the timing of the buffer stay the same. - **Placement**: `Panner` moves a stereo signal between the channels with an equal-power law (`pan` -1 to 1, and a mono stream is unchanged), and `StereoWidth` narrows a stereo signal to mono at 0 and widens it at 2. Every effect follows the same contract as the originals: `ProcessSamples` works in place on interleaved samples, keeps its state inside the call, and returns samples unchanged for a parameter it cannot use, such as a NaN rate. The chain applies where a source is still in memory before it reaches the player: - `Music.Play(src, fade)` (and `PlayLooped`, `PlaySections`, `PlayWithIntro`) runs src through the music's group chain when src holds in-memory 16-bit PCM WAV data, and plays the result. - `mixer.LoadEffect(src, group, limit, done)` loads src through its group chain the same way, then wraps it as `mixer.Effect` does. - `mixer.ProcessSource(group, src)` exposes the same processing on its own; the editor's bus audition uses it. Any other source — a URI, or in-memory MP3, AAC, Ogg or non-PCM WAV data — cannot be processed this way and plays without the chain, with one log line per group saying its effects were skipped for it. `mixer.Effect(s, group, limit)` on an already decoded `*audio.Sound` plays without the chain too: it applies at load time, so load through `LoadEffect` to hear it. Processing whole buffers as they load is the interim pipeline; live effects on every playing voice, covering every format, are a planned follow-up. ## Positional effects in 2D A `Listener2D` hears effects placed in the world from where the 2D camera looks: an effect to the left of the camera plays panned left, one to the right panned right, and both play quieter the further they are. ```go listener := sound.Listener2D{ Position: math2d.V2(cam.X, cam.Y), Rotation: cam.Rotation, Near: 64, // full volume up to 64 world units away Far: 640, // silent from 640 away Rolloff: sound.RolloffInverse, } hit.PlayAt(listener, math2d.V2(enemy.X, enemy.Y), audio.Voice{Volume: 0.9}) ``` - `Position` and `Rotation` follow the camera, such as `tilemap.Camera`'s `X`, `Y` and `Rotation`, so left and right are the view's even when the camera turns. Distances are in world units; the camera's zoom does not change them. - `Gain(pos)` is `1` within `Near`, `0` at `Far` and beyond, and falls between them by `Rolloff`: `RolloffLinear` (the default) in a straight line, `RolloffInverse` as `Near / distance` rescaled to reach `0` at `Far`, and `RolloffExponential` as `(Near / distance)^2` rescaled to reach `0` at `Far`. A `Far` that is not greater than `Near`, infinite or `NaN` turns attenuation off. - `Pan(pos)` is the effect's offset across the view divided by `PanWidth`, clamped to `[-1, 1]`; a `PanWidth` of `0` takes `Far`. An effect straight above or below the camera plays centered. - `PlayAt(l, pos, v)` plays with `v.Volume * l.Gain(pos)`, then the group and master volumes as `Play` does, and `v.Pan` replaced by `l.Pan(pos)`. It returns `false` and plays nothing beyond `Far`, so silent effects never take a voice or count against `Limit`. - `Cue.PlayAt(l, pos)` picks the cue's next variant as `Play` does and plays it through its effect's `PlayAt`, at the variant's volume and pitch, so randomized footsteps and hits can be placed too. - `Voice(pos, v)` returns the voice `PlayAt` would play with, for playing an `audio.Sound` directly. Where the effect is silent it sets `Muted`, since `audio` plays a volume of `0` at full volume. - The camera's rotation only turns the pan; distance ignores it, and an infinite or `NaN` `Rotation` counts as `0`. The pan and volume are fixed when the playback starts, because NSGo's `audio.Playback` cannot change its pan once playing. Suit it to short effects; a long sound that follows a moving source would need to be replayed. ## Positional effects in 3D `Listener3D` hears effects placed in a right-handed Y-up 3D world (`+X` right, `+Y` up, `-Z` forward — matching `math3d` and `scene3d.Camera`). Because `sound.Vec3` shares the exact field layout of `math3d.Vec3`, convert camera vectors directly with `sound.Vec3(...)`: ```go listener := sound.Listener3D{ Position: sound.Vec3(cam.Pos), Forward: sound.Vec3(cam.Forward()), Up: sound.Vec3(cam.Up()), Near: 2, Far: 40, Rolloff: sound.RolloffInverse, } mixer.SetListener3D(listener) // Fire-and-forget 3D effect (mirrors Effect.PlayAt): hit.PlayAt3D(listener, sound.Vec3(enemyPos), audio.Voice{Volume: 0.9}) // Live 3D playback that tracks camera and source motion: engine := loopSFX.Play3D(sound.Vec3(shipPos), audio.Voice{Loop: true}, sound.Spatial3DOptions{}) engine.SetPosition(sound.Vec3(nextShipPos)) ``` - **Distance attenuation**: `Gain(pos)` is `1` within `Near`, `0` at `Far` and beyond, and falls between them by `Rolloff` (`RolloffLinear`, `RolloffInverse`, or `RolloffExponential`, shaped by optional `RolloffFactor`). A `Far` not greater than `Near`, infinite, or `NaN` turns distance attenuation off. - **Rear head-shadow attenuation**: sounds behind the listener (`dot(dir, forward) < 0`) interpolate linearly from `1` at the lateral plane down to `RearGain` directly behind (`DefaultRearGain`, `0.7`, when `RearGain` is zero, negative, or `NaN`; set `RearGain: 1` to disable). An effect behind the camera is therefore quieter than an equidistant effect in front while remaining panned to its left or right side. - **Stereo pan**: `Pan(pos)` projects the unit direction from the listener to the source onto the listener's right axis (`dot(dir, right)`), clamped to `[-1, 1]`. Sounds at the listener, directly ahead, directly behind, directly overhead/underfoot, or with `NaN` coordinates play centered (`0`). Set a positive finite `PanWidth` to use linear lateral-offset panning like `Listener2D`. - **Directional source cones & overrides**: pass `Spatial3DOptions` to `Listener3D.Spatialize`, `Spatialize3D`, `Listener3D.VoiceWithOptions`, `Effect.Play3D`, or `Cue.Play3D` to add a directional emission cone (`SourceForward`, `InnerConeAngle`, `OuterConeAngle`, `OuterGain`) or per-source `Near`/`Far`/`Rolloff`/`RolloffFactor` overrides. - **Live `Playback3D` tracking**: `Mixer.SetListener3D(l)` refreshes every active `Playback3D` started by `Effect.Play3D` or `Cue.Play3D`, and `Playback3D.SetPosition` / `SetOptions` refresh a single source. Live distance, rear, and source-cone attenuation update immediately through `audio.Playback.SetVolume` while honoring master/group volumes, `SetPaused`, `SetPauseExempt`, `Suspend`, and background muting. Because NSGo's `audio.Playback` cannot change stereo pan after starting, `Playback3D.Pan()` tracks the latest computed pan while the backend playback keeps its initial pan. - **Pose helpers & cues**: `Listener3D.SetPose(pos, forward, up)` and `Listener3D.LookAt(target, up)` update orientation without altering attenuation settings. `Cue.PlayAt3D` and `Cue.Play3D` position randomized sound cues in 3D. ## Mono audio and left/right balance Players with hearing in one ear can miss sounds panned to the other side. `Mixer` supports mono voice panning and a stereo left/right balance offset across every effect it plays (`Effect.Play`, `Effect.PlayAt`, `Effect.PlayAt3D`, `Effect.Play3D`, and `Cue` variants): ```go mixer.SetMono(true) // center every voice to pan 0, keeping distance/rear/cone attenuation mixer.FollowSystemMono() // return to following the platform's mono audio switch mixer.SetBalance(-0.3) // shift stereo panning left by 0.3 when mono is off (clamped to [-1, 1]) ``` - **Mono mode**: when `mixer.Mono()` is `true`, every voice the mixer starts (or updates once NSGo exposes live `Playback.SetPan`) uses pan `0` while keeping distance, rear head-shadow, and source-cone attenuation unchanged, so distance cues still work. `Listener2D.Pan`, `Listener3D.Pan`, and `Playback3D.Pan()` still report the listener's geometric direction, so directional captions (`a11y.CaptionTrack.ShowSFXAt`) keep the direction the sound would have had. - **Left/right balance**: `SetBalance(float32)` sets an offset in `[-1, 1]` (`-1` full left, `0` centered, `+1` full right; out-of-range values clamp and `NaN` resets to `0`). When mono is off, each voice adds `Balance()` to its pan and clamps to `[-1, 1]`. While mono is on, every voice plays at pan `0` and the configured balance is retained for when mono is turned off. - **Platform switch and settings**: `NewMixer` follows the platform's mono audio switch until `SetMono` is called, and `FollowSystemMono()` restores follow-system mode. Persist both preferences in `save.AudioSettings` (`Mono *bool`, `nil` to follow system; `Balance float64` in `[-1, 1]`), which `save.Apply` applies to `SettingsTargets.Sound` and `gameui.SettingsMenu`'s Audio tab exposes as **Mono Audio** and **Balance** rows. - **Stereo assets and NSGo follow-ups**: stereo audio files (such as stereo music or ambience tracks) keep their channels until NSGo supports mixing the output down to mono (`nsgo-dev/nsgo#2676`), and following the OS mono audio switch automatically activates once NSGo exposes `Env.MonoAudio` (`nsgo-dev/nsgo#2677`; defaults to `false` on NSGo v0.3.4). ## Music and crossfades `mixer.Music(group)` plays streaming tracks through `audio.Player`, one active track at a time, with smooth crossfades: ```go music := mixer.Music("music") music.Loop = true music.Play(audio.Source{URI: "asset:music/overworld.m4a"}, 2*time.Second) ``` - `Loop`: when `true`, tracks started by subsequent `Play` calls loop at their end. - `Play(src, fade)`: starts the new track at once, muted, and fades it in over `fade` while fading all currently playing tracks out on display frames (`core.Scope.Animate`), closing faded-out players once they reach silence. When `fade <= 0`, it switches immediately. Starting another `Play` mid-crossfade smoothly fades out the incoming track from its current level. - `Stop(fade)`: fades active music out over `fade` and closes its players (`fade <= 0` stops immediately). - A `src` holding in-memory 16-bit PCM WAV data is processed through the group's [bus effect chain](http://nsgo.games/docs/sound/#bus-effect-chains) before playing; any other source plays as it is. ### Intro and loop music Most game music plays an intro once and then loops the main body indefinitely. **Recommended: single file with `PlayLooped`** Keep intro and loop in one audio file and pass the loop point's timestamp to `PlayLooped(src, loopStart, fade)`: ```go music.PlayLooped( audio.Source{URI: "asset:music/boss.m4a"}, 12*time.Second, // intro plays 0s..12s once, then 12s..end repeats time.Second, ) ``` `PlayLooped` creates a single `audio.Player` with `audio.PlayerOptions.LoopStart`, so the loop return runs inside the native player with no handoff gap or click across platforms. It always loops regardless of `music.Loop` (without changing `music.Loop` for later `Play` calls), crossfades and pauses like `Play`, processes in-memory 16-bit PCM WAV sources through the group's bus effect chain, loops the full track when `loopStart <= 0` (or `>= duration`), and stops the music over `fade` if `src` is empty. **Split files with `PlaySections` / `PlayWithIntro`** When intro and loop arrive as two separate files that cannot be combined into one asset, use `PlaySections(intro, loop, fade)` or `PlayWithIntro(sound.SectionedTrack{Intro, Loop}, fade)`: ```go music.PlayWithIntro(sound.SectionedTrack{ Intro: audio.Source{URI: "asset:music/boss_intro.m4a"}, Loop: audio.Source{URI: "asset:music/boss_loop.m4a"}, }, time.Second) ``` - `PlaySections` plays `intro` once without looping, preloads `loop` with looping enabled, and schedules `loop` slightly ahead of `intro`'s reported duration using `OnProgress` (falling back to `OnEnd` when duration is unknown) while letting `intro` finish its remaining samples. - Stopping or starting another track during the intro cancels `loop` so it never plays. - If `intro` is empty, `loop` plays directly with looping enabled; if `loop` is empty, `intro` plays once without looping; if both are empty, `PlaySections` stops the music over `fade`. - Because two-file playback coordinates two separate `audio.Player` instances across engine turns, it may still leave a slight seam or overlap under load or on the web. Prefer a single file with `PlayLooped` whenever you control the asset. ### Web autoplay and gesture unlock On the web, browsers refuse audio playback (`audio.NotAllowed`) until the page has received a user gesture. You can still call `music.Play` (or `PlayLooped` / `PlaySections`) during setup as on native targets: - When a music player fails with `audio.NotAllowed`, the track stays current at position `0` with its group volume, crossfade level, loop settings and any armed intro handoff intact, and `music.Blocked()` reports `true`. Other failures (such as a decode error) still end the track. - Call `mixer.Unblock()` once audio is allowed — assign `actions.Mixer = mixer` on [`input.Actions`](http://nsgo.games/docs/input/) so the first press, touch or key press retries automatically, and call `mixer.Unblock()` from any standalone press handler (such as a HUD button) that does not route through `input.Actions`. - `music.Blocked()` is reactive, so reading it inside a view lets you show a "Tap for sound" hint that disappears as soon as playback unblocks: ```go core.Show{ When: music.Blocked, Then: func(*core.Scope) core.Node { return core.Text{Content: "Tap for sound"} }, } ``` ## Pausing with the game `mixer.SetPaused(true)` pauses gameplay audio when a pause menu opens, and `mixer.SetPaused(false)` resumes it when the menu closes: - **Gameplay groups** (any group not marked exempt): playing `Effect`s are silenced through their `audio.Playback` without stopping, new `Effect.Play` calls return `false`, and `Music` pauses at its current position. On resume, effects still playing return to their volume and music continues from where it paused. Because NSGo v0.3.0's `audio.Playback` provides volume, rate and stop controls without a playhead pause command, short one-shot effects finish silently if the pause lasts longer than their remaining duration, while looping effects and `Music` (`audio.Player`) resume right where they left off. - **Exempt groups**: call `mixer.SetPauseExempt("ui", true)` so pause-menu clicks or menu music keep playing while `mixer.Paused()` is `true`. `mixer.PauseExempt(group)` reports whether a group is exempt, and toggling exemption while paused applies immediately. - **Loop sync**: pair `mixer.SetPaused` with [`game.Loop.OnPause`](http://nsgo.games/docs/loop/#pausing-and-syncing-subsystems) so gameplay sounds pause and resume automatically whenever `loop.SetPaused` or `loop.Paused` changes: ```go mixer.SetPauseExempt("ui", true) loop := &game.Loop{ Rate: 60, OnPause: mixer.SetPaused, Update: stepWorld, Draw: renderWorld, } loop.Run(cx) ``` ## Background muting `NewMixer` watches `cx.Env().Lifecycle()` on the same condition as `game.Loop.Run`, so backgrounding pauses and resumes audio in sync with the loop: - When the app enters **`core.LifecycleBackground`** (minimized, hidden or covered on desktop; backgrounded on iOS or Android), the mixer silences every playing effect (including pause-exempt groups such as `"ui"`), drops new `Effect.Play` calls, and pauses all music. - When the window returns to **`core.LifecycleActive`** or **`core.LifecycleInactive`** (visible, even unfocused on desktop), pause-exempt groups resume at once, while gameplay groups resume only if `mixer.Paused()` is `false` — returning from the background while the pause menu is still open keeps gameplay sounds silenced and gameplay music paused at its position until the menu closes. ## Suspending for a cutscene `mixer.Suspend()` silences the mixer the same way the background does, until the `resume` function it returns is called: effects playing are silenced, new `Effect.Play` calls play nothing, and music pauses and later plays on from where it stopped. Holds nest, so the mixer plays again only once every `Suspend` has been resumed; calling one `resume` twice does nothing. `mixer.Suspended()` reports whether a hold is left. ```go resume := mixer.Suspend() // ... something else has the speakers ... resume() ``` [cutscene](http://nsgo.games/docs/cutscene/)'s `Player` suspends the mixer while a video plays. ## Testing with nsgotest Enable virtual audio in `nsgotest` with `nsgotest.Environment(core.Environment{Audio: true})` and configure decoded durations on `app.AudioDurations` to test voice limits, crossfades, persistence and background muting deterministically: ```go package mygame_test import ( "testing" "time" "github.com/nsgo-dev/game/pkg/sound" "github.com/nsgo-dev/nsgo/audio" "github.com/nsgo-dev/nsgo/core" "github.com/nsgo-dev/nsgo/nsgotest" ) func TestMain(m *testing.M) { nsgotest.Main(m) } func TestMixerCrossfadeAndMute(t *testing.T) { var mixer *sound.Mixer var music *sound.Music app := nsgotest.Start(t, func(cx *core.Scope) core.Node { mixer = sound.NewMixer(cx, "sound") music = mixer.Music("music") music.Loop = true return core.View{} }, nsgotest.Environment(core.Environment{Audio: true}), func(a *nsgotest.App) { a.AudioDurations = map[string]time.Duration{ "asset:a.m4a": time.Minute, "asset:b.m4a": time.Minute, } }, ) mixer.SetVolume("music", 0.5) music.Play(audio.Source{URI: "asset:a.m4a"}, 0) music.Play(audio.Source{URI: "asset:b.m4a"}, time.Second) app.Advance(1100 * time.Millisecond) if !app.Players[0].Closed || !app.Players[1].Playing { t.Fatalf("expected track A closed and track B playing") } app.SetEnvironment(core.Environment{Audio: true, Lifecycle: core.LifecycleBackground}) app.Settle() if app.Players[1].Playing { t.Fatal("expected music paused in background") } } ``` ## Captions for positional sounds `Effect.SetCaption(label, callback)` calls `callback` with `label` and the listener pan each time `PlayAt`, `PlayAt3D`, their `With` forms, or a `Cue` playing the effect at a position starts a playback, so a caption points where the player hears the sound. Plain `Play` has no position and does not call it; a nil callback removes it. Connect it to `a11y.CaptionEmitter.Emit`, which shows the caption on a `CaptionTrack` and drops a label repeated within `MinInterval` (default `a11y.DefaultCaptionMinInterval`, 250 ms, on the track's clock): ```go emitter := a11y.NewCaptionEmitter(captions) door.SetCaption("Door creaks", func(label string, pan float32) { emitter.Emit(label, a11y.CaptionSFX, pan, 0) }) ``` Animation resources can now carry timed `sounds` and nested `clips` keys, while events may include scalar `args` for gameplay callbacks. ### Scene emitters and zones Scene objects can reference a `sound` resource with autoplay, looping, distance culling, far-cutoff filtering and Doppler intent. A `soundZone` record names the bus and fade/reverb-send values for listener transitions. ### Sound resources `resource.Sound` files define bus, voice limit, deterministic variant mode, pitch and volume ranges, weighted source clips and optional 3D attenuation. ### Adaptive music resources `resource.Music` files define BPM, clips, synchronized stems, bar-synced transitions and deterministic playlists. Sources are project-relative paths validated during resource parsing. ### Dynamics effects `sound.Compressor(thresholdDB, ratio, attackMs, releaseMs)` is a feed-forward peak compressor: above the threshold, each channel's level rises only 1/`ratio` dB per input dB, following peaks over `attackMs` and recovering over `releaseMs`. `sound.Limiter(ceilingDB)` clips every sample to the ceiling. Both are `BusEffect`s for `Mixer.SetGroupEffects` and the offline PCM and WAV helpers; bus layouts and `game.yaml` cannot declare them yet ([#1399](https://github.com/nsgo-dev/game/issues/1399)). ### Opt-in software mixer `NewSoftwareMixer` provides a deterministic interleaved-float mixer for stateful effects implementing `StatefulBusEffect`. Each bus owns effect instances so filters and delays retain state across blocks. The existing native mixer remains the default path. --- Source: http://nsgo.games/docs/3d-models-blender/ # 3D Models from Blender Prepare static, skinned, and animated 3D models in Blender 4.x or convert FBX and OBJ assets into glTF 2.0 (`.glb`/`.gltf`) matching NSGo's 3D conventions, verified against two committed round-trip sample models. > NSGo's 3D rendering layer is Stage 2 of the [overview](http://nsgo.games/docs/) ([nsgo#1059](https://github.com/nsgo-dev/nsgo/issues/1059)). The conventions and glTF 2.0 asset contract on this page let you author, convert, and validate 3D assets ahead of time so they load cleanly without re-exporting. ## NSGo 3D conventions NSGo adopts the standard glTF 2.0 coordinate system and physical units across every 3D package: | Property | Convention | Notes | | --- | --- | --- | | Handedness | Right-handed | Matches glTF 2.0 and OpenGL/Metal/Vulkan view math | | Axes | `+X` right, `+Y` up, `-Z` forward | Characters and vehicles face `-Z` in local space | | Units | Meters (`1.0` = 1 m) | Human character ≈ `1.7`–`1.8` units tall; physics and lighting assume meters | | Front-face winding | Counter-clockwise (CCW) | Outward normals satisfy `(v1 - v0) × (v2 - v0) · n > 0` | | Texture UVs | Origin `(0, 0)` at top-left | Standard glTF 2.0 UV layout; Blender's glTF exporter flips V automatically | | PBR workflow | Metallic-Roughness | `Principled BSDF` base color, metallic, roughness, normal, occlusion, emissive | | Runtime format | Binary glTF 2.0 (`.glb`) | Single self-contained file with aligned binary buffers; use `.gltf` for JSON inspection | | Skinning limit | 4 bone influences per vertex | One `JOINTS_0` / `WEIGHTS_0` `VEC4` attribute per vertex, normalized to sum to `1.0` | ### Project layout for 3D assets Keep runtime `.glb` files inside `resources/` so `nsgo build` bundles them on all six targets and your game loads them via `"asset:..."`. Keep heavy authoring files (`.blend`, `.fbx`, `.obj`, `.psd`) outside `resources/` (for example in `art/`) so they never inflate release packages. A `.gltf` export with its `.bin` buffer and texture files can stay in `art/` too: a model target of [`game assets`](http://nsgo.games/docs/cli/#assets) packs it into one `.glb` under `resources/`, scaled and with or without its animations as the model's import settings sidecar says: ```text mygame/ ├─ art/ # authoring sources, not shipped in builds │ ├─ crate.blend │ └─ robot_arm.blend ├─ resources/ # packaged with every target ("asset:...") │ └─ models/ │ ├─ crate.glb │ └─ robot_arm.glb └─ nsgo.yaml ``` See [Building and Shipping](http://nsgo.games/docs/shipping/) for using `mobile.exclude_resources` when desktop and mobile builds ship different LODs or texture sizes. ## Blender 4.x export checklist Blender uses a right-handed **Z-up** viewport (`+X` right, `+Y` into screen, `+Z` up). When you export with **+Y Up** enabled, Blender's glTF 2.0 exporter rotates the scene `-90°` around X so Blender's `+Z` becomes `+Y` and Blender's `-Y` (Front View, Numpad `1`) becomes **`-Z` forward** in glTF. ### Before exporting (every asset) 1. **Set metric units**: in *Scene Properties → Units*, set *Unit System* to `Metric` and *Unit Scale* to `1.0`. Verify the object's dimensions in meters in the *N* sidebar (`Item → Dimensions`). 2. **Face `-Y` in Blender**: orient characters, weapons, and vehicles so their front faces `-Y` (looking toward you in Front Orthographic View, Numpad `1`). After `+Y Up` export, they face `-Z` forward. 3. **Place the pivot cleanly**: put static props and characters with their base or feet resting at `(0, 0, 0)` so spawning at `y = 0` places them flush on the floor. 4. **Apply transforms**: select the mesh (and armature for rigged assets) and press `Ctrl+A → Rotation & Scale` (plus `Location` for origin-anchored props). Never export with negative scale (`-1`), which flips triangle winding inside out. 5. **Check face orientation**: enable *Viewport Overlays → Face Orientation*. Every visible outside surface must be blue. If any faces appear red, enter Edit Mode, select all (`A`), and run `Mesh → Normals → Recalculate Outside` (`Shift+N`). 6. **Use `Principled BSDF`**: wire textures into `Base Color`, `Metallic`, `Roughness`, `Normal` (via a `Normal Map` node), and `Emission`. Bake procedural Blender shader nodes (Noise, Voronoi, ColorRamp) to image textures before exporting; procedural Blender nodes do not exist in glTF. ### Static meshes (`.glb`) Open `File → Export → glTF 2.0 (.glb/.gltf)` and verify these settings: - **Format**: `glTF Binary (.glb)`. - **Include**: enable `Selected Objects` (or `Active Collection`) so cameras, lights, and guide empties stay out of the asset. - **Transform**: check **`+Y Up`**. - **Data → Mesh**: - Check `Apply Modifiers` (bakes Subdivision, Mirror, Bevel, and Weighted Normal modifiers). - Check `UVs` and `Normals`. - Check `Tangents` if the material uses a normal map (avoids tangent-space mismatches across renderers). - Uncheck `Vertex Colors` unless your shader reads them. - **Data → Material**: `Materials: Export`, images as `Automatic` (PNG/JPEG) or `WebP` where supported. - **Data → Compression**: leave **Draco mesh compression unchecked** while iterating, so the file stays easy to inspect; turn it on for shipped assets when download size matters. `game/gltf` decodes Draco in pure Go (see [Compressed geometry](http://nsgo.games/docs/3d-models-blender/#compressed-geometry)). ### Skinned meshes and animations Rigged characters and props need a few extra checks so GPU skinning and animation blending work cleanly: 1. **Single Armature root with unit scale**: apply `Scale = (1, 1, 1)` to both the Armature and the skinned Mesh before exporting. Keep the Armature modifier on the mesh (do **not** apply the Armature modifier). 2. **Enforce the 4-bone influence limit**: - Select the mesh, switch to *Weight Paint* mode, and run `Weights → Limit Total` with **Limit = `4`**. - Immediately run `Weights → Normalize All` (with *Lock Active* unchecked) so every vertex's weights sum strictly to `1.0`. - In the glTF exporter under *Data → Skinning*, check `Skinning` and leave **`Include All Bone Influences` unchecked** so only `JOINTS_0` and `WEIGHTS_0` (4 joints per vertex) are emitted. 3. **Export multiple clips via Actions / NLA**: - Give each clip a clean Action name (`Idle`, `Walk`, `Jump`, `Wave`). - Push each Action down to an NLA strip in the *Non-Linear Animation* editor so Blender preserves every clip in the file. - In the exporter under *Animation*, set *Animation Mode* to **`Actions`** (or `NLA Tracks`), check **`Always Sample Animations`** if the rig uses IK, Copy Rotation, or drivers, and set *Sampling Rate* to `30` or `60` fps (matching your fixed step). - Enable `Optimize Animation Size` to drop redundant flat channels while keeping keyframe curves accurate. 4. **Root motion vs in-place locomotion**: - Structure your rig with a ground-level `Root` bone at `(0, 0, 0)` parenting `Hips`/`Pelvis`. - For **in-place** clips (where Go code moves the entity transform), keep `Root` stationary at `(0, 0, 0)` and strip horizontal `X`/`Z` drift from `Hips`. - For **root-motion** clips (such as dodge rolls or lunge attacks), author horizontal translation and yaw rotation exclusively on the `Root` bone. Runtime playback can then sample per-step root deltas and hand them to your movement controller without double-applying displacement. 5. **Clip events (`extras.events`)**: - NSGo reads per-clip event markers from `animations[i].extras.events`, an array of `{ "time": , "name": "" }` objects: ```json "extras": { "events": [ { "time": 0.0, "name": "wave_start" }, { "time": 0.5, "name": "wave_apex" }, { "time": 1.0, "name": "wave_end" } ] } ``` - In Blender, add **Pose Markers** to an Action in the *Dope Sheet → Action Editor* (`M` to add a marker, `Ctrl+M` to rename it), then copy them onto `action["events"]` before exporting with **`Include → Custom Properties`** enabled: ```python import bpy fps = bpy.context.scene.render.fps / bpy.context.scene.render.fps_base for action in bpy.data.actions: if not action.pose_markers: continue start = action.frame_range[0] events = [ {"time": round((m.frame - start) / fps, 6), "name": m.name} for m in sorted(action.pose_markers, key=lambda item: item.frame) ] action["events"] = events ``` ## Converting FBX and OBJ from other tools Assets from Maya, 3ds Max, ZBrush, Mixamo, or third-party marketplaces frequently arrive as `.fbx` or `.obj`, often in **centimeters** (`100×` too large) or **Z-up** orientation. Convert them to `.glb` during asset preparation instead of parsing FBX or OBJ at runtime. ### Headless Blender CLI conversion You can batch-convert `.fbx` and `.obj` files reproducibly in CI or a local script using Blender's headless CLI (`blender --background`). Save the following helper as `tools/convert_to_glb.py`: ```python import os import sys import bpy argv = sys.argv[sys.argv.index("--") + 1 :] src_path, dst_path = argv[0], argv[1] scale_factor = float(argv[2]) if len(argv) > 2 else 1.0 # pass 0.01 for cm -> m bpy.ops.wm.read_factory_settings(use_empty=True) ext = os.path.splitext(src_path)[1].lower() if ext == ".fbx": bpy.ops.import_scene.fbx( filepath=src_path, use_anim=True, ignore_leaf_bones=True, automatic_bone_orientation=True, ) elif ext == ".obj": bpy.ops.wm.obj_import( filepath=src_path, forward_axis="NEGATIVE_Z", up_axis="Y", ) else: raise SystemExit(f"unsupported input format: {ext}") # Apply centimeter -> meter scale when source tools authored in cm (Maya, Mixamo). if scale_factor != 1.0: bpy.ops.object.select_all(action="SELECT") for obj in bpy.context.selected_objects: if obj.parent is None: obj.scale = tuple(s * scale_factor for s in obj.scale) bpy.ops.object.transform_apply(location=False, rotation=True, scale=True) # Normalize skinning weights to 4 bone influences per vertex on any skinned mesh. for obj in bpy.data.objects: if obj.type == "MESH" and obj.vertex_groups: bpy.context.view_layer.objects.active = obj bpy.ops.object.mode_set(mode="WEIGHT_PAINT") bpy.ops.object.vertex_group_limit_total(limit=4) bpy.ops.object.vertex_group_normalize_all(lock_active=False) bpy.ops.object.mode_set(mode="OBJECT") bpy.ops.export_scene.gltf( filepath=dst_path, export_format="GLB", export_yup=True, export_apply=True, export_texcoords=True, export_normals=True, export_tangents=True, export_skins=True, export_all_influences=False, export_animations=True, export_force_sampling=True, export_extras=True, export_draco_mesh_compression_enable=False, ) ``` Run it from the command line: ```sh # Convert an OBJ prop authored in meters blender --background --python tools/convert_to_glb.py -- art/barrel.obj resources/models/barrel.glb # Convert a Maya / Mixamo FBX authored in centimeters (0.01x -> meters) blender --background --python tools/convert_to_glb.py -- art/character.fbx resources/models/character.glb 0.01 ``` ### Handling common source-tool quirks - **Maya / 3ds Max FBX (`cm` → `m`)**: Blender's FBX importer respects the FBX `UnitScaleFactor` header when present, but many marketplace exports leave `UnitScaleFactor = 1` while modeling `180` units tall. Always verify bounding-box height in meters after conversion and pass `0.01` when needed. - **Z-up OBJ files** (CAD tools, older 3ds Max exports): pass `up_axis="Z"` to `bpy.ops.wm.obj_import(...)` so Blender rotates the mesh upright before exporting with `export_yup=True`. - **Mixamo multi-clip FBX downloads**: download the character mesh once (`With Skin`), then download additional animations `Without Skin`, import their Armature actions into the same `.blend` file, push each Action to the NLA stack, and export a single `.glb` containing all clips. - **Standalone inspection & optimization**: after exporting, you can inspect node trees, accessor bounds, and texture sizes with `gltf-transform inspect model.glb` or validate strict spec compliance with the Khronos `gltf_validator`. ## Compressed geometry `game/gltf` decodes both common glTF geometry compression extensions in pure Go, with no C++ or Wasm decoder, so compressed files load through the same `gltf.Load` and `gltf.LoadFS` calls as plain ones: | Extension | What it compresses | Typical producer | | --- | --- | --- | | `KHR_draco_mesh_compression` | Whole triangle primitives: connectivity plus quantized attributes | Blender's exporter (*Data → Compression*), `gltf-pipeline -d`, `gltf-transform draco` | | `EXT_meshopt_compression`, `KHR_meshopt_compression` | Individual buffer views: vertex attributes, triangle and index lists, animation keyframes | `gltfpack -c`, `gltf-transform meshopt` | | `KHR_mesh_quantization` | Integer positions, normals and texture coordinates, usually paired with meshopt | `gltfpack`, `gltf-transform quantize` | The decoded data is what the readers return: `Primitive.Positions`, `Indices` and the other attributes, `ReadVec3` and friends, animation channels and skins all see uncompressed values. A buffer tagged as a meshopt fallback is never fetched, so a `.glb` that ships its uncompressed fallback as a separate optional `.bin` loads without that file. Choosing between them: - **Draco** gives the smallest files for dense static meshes, but decoding is slower and it may change the order and number of vertices, so tools that compare against the uncompressed file must match by value, not by index. Quantization is lossy: Blender's default 14-bit positions are enough for props; check close-ups of large meshes. - **meshopt** decodes much faster, keeps vertex order, also compresses animation data, and suits skinned characters and scenes with many small meshes. Its filters (octahedral, quaternion, exponential, color) are lossy; plain attribute, triangle and index streams are lossless. Both decoders charge their output and working memory to the same per-load budget as uncompressed data before allocating it, so a small stream that declares huge counts or many wide attributes fails fast, and malformed streams return an error instead of panicking. An `EXT_meshopt_compression` file may use only what that extension defines: version 0 of the attribute codec and no `COLOR` filter. Other required extensions, such as `KHR_texture_basisu`, are still refused at load time. ## Texture transforms and material variants `game/gltf` supports both `KHR_texture_transform` and `KHR_materials_variants` (whether listed in `extensionsUsed` or `extensionsRequired`): - **`KHR_texture_transform`**: parsed on every PBR and material-extension texture slot (`BaseColorTexture`, `MetallicRoughnessTexture`, `NormalTexture`, `OcclusionTexture`, `EmissiveTexture`, `Clearcoat.Texture`, `Clearcoat.RoughnessTexture`, `Clearcoat.NormalTexture`, `Transmission.Texture`) into `TextureRef.Transform` (`*TextureTransform`). - Defaults match the Khronos specification (`offset: [0, 0]`, `rotation: 0`, `scale: [1, 1]`), and transforms apply in exact `T * R * S` order in glTF UV space (`+U` right, `+V` down, positive rotation counter-clockwise) via `TextureTransform.Apply`, `TextureTransform.ApplyUV`, `TextureTransform.Matrix`, or `TextureRef.ApplyUV`. - When `KHR_texture_transform.texCoord` is present, `TextureRef.EffectiveTexCoord()` returns the overridden UV set instead of `TextureRef.TexCoord`. - `Document.PrimitiveTexCoords(prim, set)` returns `TEXCOORD_0`/`TEXCOORD_1` directly and decodes higher sets (`TEXCOORD_2`, …) on demand; `Document.TransformTexCoords(prim, ref, out)` evaluates the final transformed UVs for a primitive and texture slot into a reusable slice. - Malformed transforms (non-object payloads, `offset` or `scale` arrays with length other than 2, non-finite numbers, or negative/non-integer `texCoord`) are rejected at load time with `*loaderr.Error` locations. - **`KHR_materials_variants`**: top-level variant names load into `Document.Variants` (`[]MaterialVariant`), and per-primitive mappings load into `Primitive.VariantMappings` (`map[int]int`). - Look up variants by name with `Document.VariantIndex(name)` and resolve materials without mutating `Primitive.Material` via `Document.MaterialForPrimitive(prim, variantIndex)`, `Document.MaterialForVariant(prim, name)`, `Document.MeshMaterials(meshIndex, variantIndex)`, and `Document.ResolveVariantMaterials(variantIndex)`. Any unmapped primitive or out-of-range/negative variant falls back to `Primitive.Material`. - Spec constraints are enforced at load time: non-empty `variants` and `mappings` arrays, required variant `name`, valid material and variant indices, and at most one mapping per variant on any primitive. ## Material extensions `game/gltf` accepts four material extensions in `extensionsUsed` and `extensionsRequired`: - **`KHR_materials_unlit`**: sets `Material.Unlit`. - **`KHR_materials_emissive_strength`**: `Material.EmissiveStrength()` returns the multiplier for `EmissiveFactor`, 1 when the extension or its `emissiveStrength` is omitted, and an error when the payload is not an object or the value is not a finite number >= 0. - **`KHR_materials_clearcoat`**: populates `Material.Clearcoat` (`*Clearcoat`) with `Factor`, `RoughnessFactor`, `Texture`, `RoughnessTexture`, and `NormalTexture` (including `Scale`, `TexCoord`, and `KHR_texture_transform`), rejecting out-of-range factors or invalid texture references at load time. - **`KHR_materials_transmission`**: populates `Material.Transmission` (`*Transmission`) with `Factor` and `Texture` (including `TexCoord` and `KHR_texture_transform`), rejecting out-of-range factors or invalid texture references at load time. ## Baked lightmaps Bake lighting in Blender (or another baker) into a second UV map, export it as `TEXCOORD_1`, and point the material at the baked texture with `MOZ_lightmap` (what the Hubs Blender add-on writes), `EXT_lightmap`, or an `extras.lightmap` object. Both extensions are accepted in `extensionsUsed` and `extensionsRequired`. - `Document.MaterialLightmap(materialIndex)` returns a `*LightmapRef` (nil when the material has no lightmap) with the texture, `Intensity`, the `Encoding` hint (`linear`, `srgb`, `rgbm`, `rgbd`), `RGBMMaxRange`, and the atlas `UVScale` / `UVOffset`. - `UVScale` / `UVOffset` are the authoritative atlas transform. They come from, in increasing precedence, the lightmap's `KHR_texture_transform` scale and offset, a `scaleOffset` `[sx, sy, ox, oy]` field, and separate `uvScale` / `uvOffset` fields. A rotated lightmap transform is refused. The transform is not left in `LightmapRef.Texture.Transform` (which keeps only a `texCoord` override), so `TransformTexCoords` on it never applies the atlas transform twice. - `Document.LightmapTexCoords(prim, ref)` returns the lightmap UV set, falling back to `TEXCOORD_0` when `TEXCOORD_1` is missing, and fails when the primitive has neither. [render3d](http://nsgo.games/docs/render3d/#baked-lightmaps-lightmapmesh-lightmaprenderer) shows how to draw the result. ## Morph targets `game/gltf` decodes glTF 2.0 morph targets (`POSITION`, `NORMAL`, and `TANGENT` displacement deltas, including sparse accessors), default `mesh.weights` and `node.weights`, and animated `weights` channels (`STEP`, `LINEAR`, and `CUBICSPLINE`). In Blender, author morph targets as **Shape Keys** on the mesh, keyframe their *Value* sliders in an Action, and enable *Data → Shape Keys* (plus *Shape Key Normals* and *Shape Key Tangents* when needed) in the glTF 2.0 exporter. At runtime, evaluate morph targets without per-frame heap allocations by reusing weight and `MorphResult` buffers: ```go weights := gltf.ResolveWeights(doc, nodeIdx) // node.Weights > mesh.Weights > zeros var morphed gltf.MorphResult // Each frame: if sampled, ok := gltf.SampleMorphWeights(doc.Animations[0], nodeIdx, animTime, weights); ok { weights = sampled } gltf.ApplyMorphWeights(prim, weights, &morphed) // morphed.Positions, morphed.Normals (renormalized), morphed.Tangents (XYZ renormalized, W preserved), morphed.Bounds ``` - `ResolveWeights` and `ResolveWeightsInto` apply glTF 2.0 weight precedence (`node.Weights` overrides `mesh.Weights`; missing weights default to zeros matching the primitive's morph target count). - `SampleMorphWeights` unpacks `N` target weights per keyframe (`3 * N` floats per keyframe in `[inTangent, value, outTangent]` order for `CUBICSPLINE`), clamping outside the channel's keyframe time range. - `EvaluateMorphTangents` blends tangent `XYZ` displacements, renormalizes `XYZ`, and preserves `W` handedness unchanged, complementing `EvaluateMorphPositions` and `EvaluateMorphNormals`. - To draw an animated morph mesh in an NSGo `gpu.View`, upload the base primitive and targets into `render3d.GPUMorphMesh` (see [`render3d`](http://nsgo.games/docs/render3d/#morph-target-meshes-morphmesh-gpumorphmesh)). The test suite verifies full animation playback and pixel readback against the Khronos `AnimatedMorphCube` sample model. ## Collision nodes (`-colonly` and `extras.collider`) Author level colliders directly alongside visual geometry in Blender using collider node name suffixes or Custom Properties (`extras.collider`), and keep collider-only nodes out of visual draws: | Name suffix | Collider shape | Drawn visually? | | --- | --- | --- | | `-col` / `-colonly` | Triangle mesh (`ColliderTriMesh`) | Yes / No | | `-boxcol` / `-boxcolonly` | Oriented box (`ColliderBox`) | Yes / No | | `-spherecol` / `-spherecolonly` | Sphere (`ColliderSphere`) | Yes / No | | `-capsulecol` / `-capsulecolonly` | Capsule (`ColliderCapsule`) | Yes / No | | `-convcol` / `-convcolonly` | Convex (`ColliderConvex`, currently built as trimesh) | Yes / No | Suffix matching is case-insensitive and strips Blender's trailing duplicate numbers (such as `Wall-colonly.001`). Nodes can also declare `extras.collider` (as a shape string, `true`/`false`, or an object with `shape`/`type`, `draw`/`only`/`visible`, `trigger`, `tag`, `center`, `halfExtents`/`size`, `radius`, `height`, `friction`, `restitution`, `layer`, and `mask`) — including on meshless Empty nodes. - **Filter visual draws**: call `doc.DrawableNodes()` (or `doc.SceneDrawableNodes(sceneIdx)` / `node.IsDrawable()`) so `-colonly` and `draw: false` nodes are excluded from rendering. - **Inspect or build physics colliders**: call `doc.ColliderNodes()` / `gltf.ParseNodeCollider(node)` for raw metadata, or pass `doc` directly to [`physics3d.World.AddGLTFColliders`](http://nsgo.games/docs/physics3d/#gltf-gridmap-and-heightmap-colliders). ## Round-trip sample models The [placeholder pack](http://nsgo.games/docs/placeholder/) holds three minimal, deterministic glTF 2.0 sample models under [`pkg/placeholder/pack/models/`](https://github.com/nsgo-dev/game/blob/main/pkg/placeholder/pack/models/), generated and round-trip verified in Go by [`pkg/placeholder/internal/samplegltf/`](https://github.com/nsgo-dev/game/blob/main/pkg/placeholder/internal/samplegltf/samplegltf.go). Like the rest of the pack they are dedicated to the public domain under CC0 1.0, and `placeholder.Model` loads them. ### 1. Static binary crate (`crate.glb`) File: [`models/crate.glb`](https://github.com/nsgo-dev/game/blob/main/pkg/placeholder/pack/models/crate.glb) (1,920 bytes, GLB 2.0) - **Geometry**: `1 m × 1 m × 1 m` cube with pivot at bottom center (`X ∈ [-0.5, 0.5]`, `Y ∈ [0, 1]`, `Z ∈ [-0.5, 0.5]`), right-handed `+Y` up, `-Z` forward. - **Mesh data**: 24 vertices (4 per face for crisp hard normals), 12 triangles (36 `UNSIGNED_SHORT` indices), strict CCW outward winding, `POSITION` (with exact `min`/`max`), unit `NORMAL`, and per-face `TEXCOORD_0`. - **Material**: `CrateMaterial` using `pbrMetallicRoughness` (`baseColorFactor: [0.72, 0.52, 0.32, 1]`, `metallicFactor: 0.05`, `roughnessFactor: 0.78`, `doubleSided: false`). - **Container layout**: 12-byte GLB header (`glTF` magic `0x46546C67`, version `2`, 4-byte-aligned total length), space-padded `JSON` chunk (`0x4E4F534A`), and zero-padded `BIN` chunk (`0x004E4942`). ### 2. Skinned & animated 2-bone arm (`robot_arm.gltf`) File: [`models/robot_arm.gltf`](https://github.com/nsgo-dev/game/blob/main/pkg/placeholder/pack/models/robot_arm.gltf) (embedded base64 buffer, human-readable JSON) - **Hierarchy**: ```text ArmRoot (node 0) ├─ ArmMesh (node 1: mesh 0, skin 0) └─ UpperArm (node 2: skeleton root at 0, 0, 0) └─ Forearm (node 3: translation 0, 0.5, 0) ``` - **Geometry & skinning**: `0.25 m × 1.0 m × 0.25 m` segmented arm (`X ∈ [-0.125, 0.125]`, `Y ∈ [0, 1]`, `Z ∈ [-0.125, 0.125]`), 32 vertices, 20 triangles (60 indices). The shared elbow ring at `y = 0.5` blends smoothly across both joints (`JOINTS_0 = [0, 1, 0, 0]`, `WEIGHTS_0 = [0.5, 0.5, 0, 0]`), while base and tip rings bind `1.0` to `UpperArm` and `Forearm` respectively. - **Skin (`ArmSkin`)**: `joints: [2, 3]`, `skeleton: 2`, and `inverseBindMatrices` containing identity `I` for `UpperArm` and translation `T(0, -0.5, 0)` for `Forearm`, satisfying `worldBind × IBM = I`. - **Animation (`Wave`)**: 1.0-second clip (`times = [0, 0.5, 1]`) with two `LINEAR` quaternion rotation channels (`UpperArm` +15° Z, `Forearm` +60° Z) and three `extras.events` markers (`wave_start` at `0.0 s`, `wave_apex` at `0.5 s`, `wave_end` at `1.0 s`). ### 3. Flat-shaded gem (`gem.glb`) File: [`models/gem.glb`](https://github.com/nsgo-dev/game/blob/main/pkg/placeholder/pack/models/gem.glb) (1,924 bytes, GLB 2.0) - **Geometry**: a hexagonal bipyramid `0.8 m` across and `1 m` tall with its pivot at its bottom point (`Y ∈ [0, 1]`), its girdle at `y = 0.6`, right-handed `+Y` up. - **Mesh data**: 36 vertices and 12 triangles, three vertices per face so each face has its own unit `NORMAL`, with CCW outward winding. - **Material**: `GemMaterial` using `pbrMetallicRoughness` (`baseColorFactor: [0.13, 0.77, 0.45, 1]`, `metallicFactor: 0`, `roughnessFactor: 0.2`). - **Reproducibility**: the generator uses only exactly rounded arithmetic, so it writes the same bytes on every architecture. ### Running the round-trip verifier The Go test suite in [`pkg/placeholder/internal/samplegltf/samplegltf_test.go`](https://github.com/nsgo-dev/game/blob/main/pkg/placeholder/internal/samplegltf/samplegltf_test.go) unpacks the committed models and verifies: - GLB magic, version `2`, 4-byte alignment, JSON/BIN chunk bounds, and zero-byte BIN padding - Embedded data URI base64 decoding and exact buffer byte lengths - Accessor alignment, `POSITION` `min`/`max` bounds, unit normals, and CCW outward triangle winding on every triangle - 4-bone `JOINTS_0`/`WEIGHTS_0` bounds and per-vertex weight sums equal to `1.0` - Exact `worldBind × inverseBindMatrix == Identity` for every joint in `skins` - Strictly increasing animation timestamps, unit rotation quaternions, and in-range `extras.events` - Byte-for-byte reproducibility against the deterministic Go generator Run the tests from the repository root: ```sh go tool nsgo test ./pkg/placeholder/internal/samplegltf ``` If you edit the generator, regenerate the committed models and re-verify in one command: ```sh go tool nsgo test ./pkg/placeholder/internal/samplegltf -update ``` ## Troubleshooting | Symptom | Likely cause | Fix | | --- | --- | --- | | Model is 100× too large or tiny | Source authored in centimeters or unapplied Object Scale | Set Blender units to Metric (`1.0`), apply `Ctrl+A → Scale`, or convert FBX with `0.01` scale | | Model lies on its back or faces away from the camera | `+Y Up` disabled on export, or model built facing `+Y` instead of `-Y` | Rotate model so front faces `-Y` in Blender, apply `Ctrl+A → Rotation`, and enable **`+Y Up`** | | Inside-out or missing faces | Inverted normals or negative scale (`-1`) flipped triangle winding | Apply `Ctrl+A → Scale`, check *Face Orientation* overlay, and run `Shift+N` (*Recalculate Outside*) | | Skinned mesh explodes or stretches weirdly | Unapplied Armature/Mesh scale, >4 bone weights, or unnormalized weights | Apply scale to mesh and armature, run `Limit Total (4)` + `Normalize All`, uncheck `Include All Bone Influences` | | Only one animation exports (or none) | Actions are not pushed to NLA tracks, or IK constraints are unbaked | Push every Action to an NLA strip, set *Animation Mode* to `Actions`, and check `Always Sample Animations` | | Material looks flat white, black, or loses textures | Blender-only procedural nodes or unpacked external image paths | Bake procedural nodes into PBR maps wired to `Principled BSDF` and export as `.glb` | | Character snaps back to origin when a walk cycle loops | Root motion baked into a clip meant to loop in place | Zero horizontal translation on `Root`/`Hips` for in-place loops, or consume root deltas in gameplay code | | `extras.events` missing from exported glTF | Custom properties omitted or stored on the Object instead of the Action | Write `action["events"]` on each Blender Action and enable `Include → Custom Properties` on export | | `gltf.Load` refuses the file | The exporter wrote data the spec forbids: an index past the vertex count, attributes or morph targets with different counts, NaN/Inf vertex data, a `JOINTS_0` value past the skin's joint list, unordered sparse indices, a second GLB JSON chunk, or an `asset.minVersion` above 2.0 | Fix the source mesh (or re-export) and check it with the Khronos `gltf_validator`; the error names the mesh, primitive and element | | A node's `Translation`/`Rotation`/`Scale` do not match its `LocalMatrix` | The node's authored `matrix` has shear, which TRS cannot express; `Node.MatrixNotTRS` is set | Use `LocalMatrix`, or apply the transform in Blender so the node exports as plain TRS | ### Basis Universal textures The glTF loader preserves `KHR_texture_basisu` texture entries. Use `Texture.ImageIndex()` to select the extension's KTX2 image, then pass its bytes from `Document.ImageKTX2` to `render3d.LoadKTX2`. Required `KHR_texture_basisu` is accepted by the loader, while malformed source indices are refused. Model sidecars can declare named clip slices, loop preferences, material remaps and skipped helper nodes through `model.clips`, `model.materials` and `model.skipNodes` ([File Formats](http://nsgo.games/docs/formats/#import-settings-sidecar)). They are recorded and checked only for now: `game assets` does not slice the animations or skip the nodes yet, and `scenemodel` does not remap the materials, so set loop flags in Go meanwhile. Keep reviewed `boneMap` YAML beside rigs when sharing animation clips between differently named skeletons. --- Source: http://nsgo.games/docs/platforms/ # Platform support NSGo Game targets six primary build targets (macOS, Windows, Linux, iOS, Android, and Web) and also compiles with NSGo's four experimental targets (HarmonyOS, tvOS, watchOS, and mini programs), though feature availability and CI test coverage differ by target. Every cell below is verified against NSGo `v0.3.4` and this repository's build tags and workflows, with links to the upstream issue tracking each gap. - **Supported**: works in NSGo `v0.3.4` and `nsgo-dev/game` without missing platform plumbing. - **Partial (N)**: works with platform limits or missing pieces explained in [Footnotes](http://nsgo.games/docs/platforms/#footnotes). - **Not available**: returns an unsupported/unavailable error or is excluded at compile time; links the tracking issue. - **Out of scope**: the platform has no native equivalent or the feature does not belong on that target. ## Feature matrix | Feature | macOS | Windows | Linux | iOS | Android | Web | HarmonyOS | tvOS | watchOS | Mini programs | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 2D rendering | Supported | Supported | Supported | Supported | Supported | Supported | Partial (1) | Supported | Partial (2) | Partial (3) | | 3D rendering (GPU view) | Supported | Supported | Supported | Supported | Supported | Supported | Not available ([nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521), [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320)) | Not available ([nsgo#1317](https://github.com/nsgo-dev/nsgo/issues/1317)) | Out of scope ([nsgo#1318](https://github.com/nsgo-dev/nsgo/issues/1318)) | Out of scope ([nsgo#1505](https://github.com/nsgo-dev/nsgo/issues/1505)) | | Audio | Supported | Partial (4) | Supported | Supported | Partial (4) | Partial (5) | Not available ([nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521), [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320)) | Not available ([nsgo#1317](https://github.com/nsgo-dev/nsgo/issues/1317)) | Not available ([nsgo#1318](https://github.com/nsgo-dev/nsgo/issues/1318)) | Not available ([nsgo#1505](https://github.com/nsgo-dev/nsgo/issues/1505)) | | Keyboard and mouse | Supported | Supported | Supported | Partial (6) | Partial (6) | Supported | Partial (6) | Partial (7) | Out of scope | Out of scope | | Gamepad | Supported | Supported | Supported | Supported | Supported | Supported | Not available ([nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521), [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320)) | Supported | Out of scope ([nsgo#1318](https://github.com/nsgo-dev/nsgo/issues/1318)) | Not available ([nsgo#1505](https://github.com/nsgo-dev/nsgo/issues/1505)) | | Touch | Partial (8) | Supported (8) | Supported (8) | Supported | Supported | Supported | Supported | Out of scope | Supported | Supported | | Haptics | Out of scope | Out of scope | Out of scope | Supported | Supported | Partial (9) | Not available ([nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521), [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320)) | Out of scope | Not available ([nsgo#1318](https://github.com/nsgo-dev/nsgo/issues/1318)) | Not available ([nsgo#1505](https://github.com/nsgo-dev/nsgo/issues/1505)) | | Motion sensors | Out of scope | Out of scope | Out of scope | Supported | Supported | Partial (10) | Not available ([nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521), [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320)) | Out of scope | Supported | Not available ([nsgo#1505](https://github.com/nsgo-dev/nsgo/issues/1505)) | | Local saves | Supported | Supported | Supported | Supported | Supported | Partial (11) | Partial (12) | Supported | Supported | Partial (11) | | OS cloud save | Partial (13) | Out of scope | Out of scope | Supported | Partial (14) | Out of scope | Not available ([nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521), [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320)) | Supported | Not available ([nsgo#1318](https://github.com/nsgo-dev/nsgo/issues/1318)) | Out of scope | | Self-hosted cloud save | Supported | Supported | Supported | Supported | Supported | Supported | Partial (15) | Supported | Supported | Not available ([nsgo#1505](https://github.com/nsgo-dev/nsgo/issues/1505)) | | UDP | Supported | Supported | Supported | Supported | Supported | Out of scope | Not available ([nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521), [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320)) | Supported | Supported | Out of scope | | WebSocket | Supported | Supported | Supported | Supported | Supported | Supported (16) | Partial (16) | Supported | Supported | Not available ([nsgo#1505](https://github.com/nsgo-dev/nsgo/issues/1505)) | | Game services | Supported | Out of scope | Out of scope | Supported | Partial (17) | Out of scope | Not available ([nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521), [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320)) | Supported | Not available ([nsgo#1318](https://github.com/nsgo-dev/nsgo/issues/1318)) | Out of scope | | In-app purchases | Supported | Not available ([nsgo#1370](https://github.com/nsgo-dev/nsgo/issues/1370)) | Not available ([nsgo#1370](https://github.com/nsgo-dev/nsgo/issues/1370)) | Supported | Not available ([nsgo#1369](https://github.com/nsgo-dev/nsgo/issues/1369)) | Not available ([nsgo#1370](https://github.com/nsgo-dev/nsgo/issues/1370)) | Not available ([nsgo#1370](https://github.com/nsgo-dev/nsgo/issues/1370), [nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521)) | Supported | Not available ([nsgo#1370](https://github.com/nsgo-dev/nsgo/issues/1370), [nsgo#1318](https://github.com/nsgo-dev/nsgo/issues/1318)) | Not available ([nsgo#1370](https://github.com/nsgo-dev/nsgo/issues/1370), [nsgo#1505](https://github.com/nsgo-dev/nsgo/issues/1505)) | | Local notifications | Supported | Supported | Partial (18) | Supported | Supported | Partial (18) | Not available ([nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521), [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320)) | Out of scope | Supported | Out of scope | | Remote push | Not available ([nsgo#59](https://github.com/nsgo-dev/nsgo/issues/59), [nsgo#1323](https://github.com/nsgo-dev/nsgo/issues/1323)) | Not available ([nsgo#59](https://github.com/nsgo-dev/nsgo/issues/59), [nsgo#1323](https://github.com/nsgo-dev/nsgo/issues/1323)) | Not available ([nsgo#59](https://github.com/nsgo-dev/nsgo/issues/59), [nsgo#1323](https://github.com/nsgo-dev/nsgo/issues/1323)) | Not available ([nsgo#59](https://github.com/nsgo-dev/nsgo/issues/59), [nsgo#1323](https://github.com/nsgo-dev/nsgo/issues/1323)) | Not available ([nsgo#59](https://github.com/nsgo-dev/nsgo/issues/59), [nsgo#1323](https://github.com/nsgo-dev/nsgo/issues/1323)) | Not available ([nsgo#59](https://github.com/nsgo-dev/nsgo/issues/59), [nsgo#1323](https://github.com/nsgo-dev/nsgo/issues/1323)) | Not available ([nsgo#59](https://github.com/nsgo-dev/nsgo/issues/59), [nsgo#1323](https://github.com/nsgo-dev/nsgo/issues/1323)) | Not available ([nsgo#59](https://github.com/nsgo-dev/nsgo/issues/59), [nsgo#1323](https://github.com/nsgo-dev/nsgo/issues/1323)) | Not available ([nsgo#59](https://github.com/nsgo-dev/nsgo/issues/59), [nsgo#1323](https://github.com/nsgo-dev/nsgo/issues/1323)) | Not available ([nsgo#59](https://github.com/nsgo-dev/nsgo/issues/59), [nsgo#1323](https://github.com/nsgo-dev/nsgo/issues/1323)) | | Steam integration | Partial (19) | Partial (19) | Partial (19) | Out of scope | Out of scope | Out of scope | Out of scope | Out of scope | Out of scope | Out of scope | | The editor | Supported | Supported | Supported | Out of scope | Out of scope | Out of scope | Out of scope | Out of scope | Out of scope | Out of scope | | Tested in CI | Supported | Partial (20) | Supported | Partial (21) | Partial (21) | Partial (22) | Not available ([nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521), [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320)) | Not available ([nsgo#1317](https://github.com/nsgo-dev/nsgo/issues/1317)) | Not available ([nsgo#1318](https://github.com/nsgo-dev/nsgo/issues/1318)) | Not available ([nsgo#1505](https://github.com/nsgo-dev/nsgo/issues/1505)) | ## Footnotes 1. **HarmonyOS 2D rendering**: `Canvas` replays onto an ArkUI `Canvas`, but `core.Shader` has no view host on HarmonyOS yet (`docs/architecture/harmonyos.md`; tracked in [nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521) and [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320)). 2. **watchOS 2D rendering**: `Canvas` draws on the SwiftUI host, while `KindShader` renders as an empty box because watchOS has no Metal view (`internal/platform/watchos/watchos.go`; [nsgo#1318](https://github.com/nsgo-dev/nsgo/issues/1318)). 3. **Mini programs 2D rendering**: `Canvas` draws into an offscreen canvas (`canvas2d`), WeChat supports pixel images while QQ, Douyin, and Alipay lack image-view pixel binding, `nsgo_noshader` disables `core.Shader`, and the 2 MB package cap constrains bundled code and assets (`docs/architecture/miniprogram.md`; [nsgo#1505](https://github.com/nsgo-dev/nsgo/issues/1505)). 4. **Windows and Android audio**: `Env.CanPlayAudio()` is true on both (XAudio2 + Media Foundation on Windows; SoundPool + MediaPlayer on Android, with SoundPool's 1 MiB decoded sample cap), while `Env.CanScheduleAudio()` is false (`windows/env.go` and `android/protocol.go` do not set `AudioSchedule`, so timed sample scheduling is unavailable). 5. **Web audio**: Web Audio (`AudioContext`) and `HTMLAudioElement` are supported, but browsers mute output until the first trusted user gesture (`docs/architecture/audio.md`; see [sound](http://nsgo.games/docs/sound/)). 6. **iOS, Android, and HarmonyOS keyboard and mouse**: external hardware keyboards dispatch `EventKeyDown` / `EventKeyUp`, but `Env.CanLockPointer()` and `Env.SupportsCustomCursor()` are false (no desktop pointer lock or custom image cursor). 7. **tvOS keyboard and mouse**: Apple TV uses the Siri Remote for focus navigation (`ios/keycommands.go` skips hardware key commands when `onTV()`); mouse pointers and pointer lock are absent ([nsgo#1317](https://github.com/nsgo-dev/nsgo/issues/1317)). 8. **Desktop touch**: macOS has no touchscreen hardware and maps mouse presses as finger 0 for views that listen to `OnTouch` (`macos/macos.go`). Windows (`WM_POINTER` in `windows/touch.go`) and Linux (GTK touch events in `linux/callback.go`) support multi-touch on touchscreen hardware in addition to pointer input. 9. **Web haptics**: `mobile.PlayHapticPattern` uses `navigator.vibrate` where the browser implements the Vibration API (primarily Android browsers); `mobile.PlayHaptic` is a no-op and Safari/iOS lacks `navigator.vibrate` (`web/env.go`, `web/haptics.go`). 10. **Web motion sensors**: `WatchMotion` reads `DeviceMotionEvent` and `DeviceOrientationEvent` in secure mobile browser contexts only (Safari requires `RequestPermission(PermissionMotion)` from a user gesture); desktop browsers and magnetometers report unavailable (`docs/architecture/location-motion.md`; [nsgo#1208](https://github.com/nsgo-dev/nsgo/issues/1208)). 11. **Web and mini program local saves**: `save.StorageBackend(cx.Storage(), ...)` persists to browser `localStorage` or mini program host storage, but `cx.DataDir()` is empty so `save.FileBackend` does not apply (`pkg/save/backend.go`). 12. **HarmonyOS local saves**: `internal/platform/harmonyos/harmonyos.go` passes no persistent `Storage` store to `engine.Start`, so `cx.Storage()` falls back to an in-memory store (`core.NewStore(nil)`) and `js/wasm` cannot write directly to host paths in `DataDir` ([nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521), [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320)). 13. **macOS OS cloud save**: Apple iCloud ubiquity containers require a provisioning profile with iCloud entitlements, which NSGo embeds only in Mac App Store builds (`sign.macos_profile`); Developer ID and ad hoc builds leave iCloud out and return `ErrCloudUnavailable` (`docs/architecture/cloud.md`). 14. **Android OS cloud save**: Google Play Games Saved Games works via `CloudStorage.java` reflection only when the Play Games Services SDK is packaged with the app/host and the player is signed in; otherwise `Env.CanUseCloudStorage()` is false and `liveops.PlatformCloud` returns `ErrCloudUnavailable` (`docs/architecture/cloud.md`, `android/protocol.go`). 15. **HarmonyOS self-hosted cloud save**: `liveops.CloudClient` runs Go's `net/http` over ArkWeb's `fetch`, requiring network permission and CORS `allowedOrigins`, and is not tested in CI ([nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521), [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320)). 16. **Web and HarmonyOS WebSocket**: `pkg/online/netplay/ws_js.go` wraps the browser `WebSocket` global for client `DialWebSocket` only (`ListenWebSocket` is native-only). On HarmonyOS this runs inside ArkWeb and is not tested in CI ([nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521), [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320)). 17. **Android game services**: the Go wire protocol (`gameservices_android.go`) is implemented, but NSGo `v0.3.4`'s prebuilt `NsgoView.java` does not yet set the Play Games Services capability bit (`more & 64`), so `Env.CanUseGameServices()` is false and `achievements` / `leaderboard` return `ErrUnsupported` until the Java reflection hook lands (`docs/architecture/gameservices.md`). 18. **Linux and Web local notifications**: immediate notifications work, and `Env.CanScheduleNotifications()` is true, but scheduled notifications are held in memory by `driver.NotificationScheduler` and fire only while the app or browser page remains open (`linux/env.go`, `web/env.go`, `docs/architecture/services.md`). 19. **Steam integration**: `pkg/online/presence` (`ISteamFriends` via `purego`), `pkg/modding` (`SteamWorkshop` via `purego`), and `liveops.DirCloud` (Steam Auto-Cloud) build and run on macOS, Windows, and Linux, but running NSGo games under the Steam client, Steam Linux Runtime, Steam Deck / gamescope, Steam Overlay, and Steam Input is still being verified in [nsgo#1228](https://github.com/nsgo-dev/nsgo/issues/1228). 20. **Windows CI**: `.github/workflows/check.yml` cross-compiles and vets `windows` with `go tool nsgo check`, but `.github/workflows/test.yml` does not yet run `go tool nsgo test ./...` on a Windows runner (tracked in [game#1305](https://github.com/nsgo-dev/game/issues/1305)). 21. **iOS and Android CI**: `.github/workflows/check.yml` compiles and vets `ios`, `ios_simulator`, and `android` with `go tool nsgo check`, but runtime tests and example smoke runs on an iOS simulator and Android emulator are not yet in CI (tracked in [game#1306](https://github.com/nsgo-dev/game/issues/1306)). 22. **Web CI**: `.github/workflows/check.yml` cross-compiles and vets `web` with `go tool nsgo check` and `.github/workflows/website.yml` builds the WebAssembly playground examples, but headless browser runtime tests do not run in `nsgo-dev/game`'s CI. ## How each row is decided Reviewers can keep the matrix current by checking these exact runtime guards, build tags, and workflow files: | Feature | Runtime check or build tag | Deciding source | | --- | --- | --- | | 2D rendering | `core.Canvas` (`driver.ItemCanvas`), `core.Pixels`, `core.Shader`, `nsgo_noshader` | NSGo `internal/platform/*/canvas*`, `internal/platform/watchos/watchos.go`, `docs/architecture/harmonyos.md`, `docs/architecture/miniprogram.md` | | 3D rendering (GPU view) | `core.Env.SupportsGPU()` | NSGo `core/env.go` (`SupportsGPU`), `gpu/view.go`, `internal/platform/ios/env.go`, `docs/architecture/gpu.md` | | Audio | `core.Env.CanPlayAudio()`, `core.Env.CanScheduleAudio()` | NSGo `core/env.go` (`CanPlayAudio`, `CanScheduleAudio`), `internal/platform/ios/env.go`, `internal/platform/harmonyos/env.go`, `internal/platform/miniprogram/env.go`, `docs/architecture/audio.md` | | Keyboard and mouse | `driver.EventKeyDown`, `core.Env.CanLockPointer()`, `core.Env.SupportsCustomCursor()` | NSGo `core/env.go` (`CanLockPointer`, `SupportsCustomCursor`), `internal/platform/ios/keycommands.go`, `internal/platform/harmonyos/keyboard.go`; game [`pkg/input`](https://github.com/nsgo-dev/game/blob/main/pkg/input/) | | Gamepad | `core.Env.SupportsGamepads()`, `nsgo/gamepad` build tags | NSGo `core/env.go` (`SupportsGamepads`), `gamepad/gamepad_apple.go`, `gamepad/gamepad_other.go` (`(ios && nsgowatch) \|\| (js && wasm && (nsgominiprogram \|\| nsgoharmony))`) | | Touch | `driver.EventTouch`, `core.Env.Pointer()` | NSGo `core/env.go` (`Pointer`), `internal/platform/macos/macos.go`, `internal/platform/windows/touch.go`, `internal/platform/linux/callback.go`, `internal/platform/ios/touch.go`, `docs/architecture/device-differences.md` | | Haptics | `mobile.PlayHaptic`, `core.Env.CanPlayHapticPattern()` | NSGo `core/env.go` (`CanPlayHapticPattern`), `internal/platform/ios/ios.go`, `internal/platform/android/protocol.go`, `internal/platform/web/haptics.go`, `docs/architecture/services.md` | | Motion sensors | `core.Scope.WatchMotion`, `core.PermissionMotion` | NSGo `internal/platform/apple/sensors.go`, `internal/platform/watchos/watchos.go`, `docs/architecture/location-motion.md` | | Local saves | `core.Scope.Storage()`, `core.Scope.DataDir()` | Game [`pkg/save/backend.go`](https://github.com/nsgo-dev/game/blob/main/pkg/save/backend.go); NSGo `internal/platform/web/web.go`, `internal/platform/harmonyos/harmonyos.go`, `internal/platform/miniprogram/miniprogram.go` | | OS cloud save | `core.Env.CanUseCloudStorage()`, `nsgo/cloud` (`darwin`, `android`, `!darwin && !android`) | Game [`pkg/online/liveops/cloud_platform.go`](https://github.com/nsgo-dev/game/blob/main/pkg/online/liveops/cloud_platform.go) (`CloudProviderFor`, `PlatformCloud`); NSGo `core/env.go` (`CanUseCloudStorage`), `cloud/cloud_apple.go`, `cloud/cloud_android.go`, `cloud/cloud_other.go`, `docs/architecture/cloud.md` | | Self-hosted cloud save | `net/http` client (`liveops.CloudClient`); server SQLite/Postgres `!js && !wasip1` | Game [`pkg/online/liveops/cloudclient.go`](https://github.com/nsgo-dev/game/blob/main/pkg/online/liveops/cloudclient.go), [`pkg/online/cloudsave/doc.go`](https://github.com/nsgo-dev/game/blob/main/pkg/online/cloudsave/doc.go) | | UDP | `//go:build !js` | Game [`pkg/online/netplay/udp_native.go`](https://github.com/nsgo-dev/game/blob/main/pkg/online/netplay/udp_native.go), [`pkg/online/netplay/udp_session_native.go`](https://github.com/nsgo-dev/game/blob/main/pkg/online/netplay/udp_session_native.go) | | WebSocket | `//go:build !js` and `//go:build js && wasm` (`js.Global().Get("WebSocket").Truthy()`) | Game [`pkg/online/netplay/ws_native.go`](https://github.com/nsgo-dev/game/blob/main/pkg/online/netplay/ws_native.go), [`pkg/online/netplay/ws_js.go`](https://github.com/nsgo-dev/game/blob/main/pkg/online/netplay/ws_js.go) | | Game services | `core.Env.CanUseGameServices()`, `nsgo/gameservices` (`darwin && !nsgowatch`, `android`, other) | Game [`pkg/online/achievements/services.go`](https://github.com/nsgo-dev/game/blob/main/pkg/online/achievements/services.go), [`pkg/online/leaderboard`](https://github.com/nsgo-dev/game/blob/main/pkg/online/leaderboard/); NSGo `core/env.go` (`CanUseGameServices`), `gameservices/gameservices.go`, `internal/platform/android/java/dev/oneo/nsgo/NsgoView.java`, `docs/architecture/gameservices.md` | | In-app purchases | `core.Env.CanPurchase()` | Game [`pkg/online/liveops/purchases.go`](https://github.com/nsgo-dev/game/blob/main/pkg/online/liveops/purchases.go) (`Purchases.Available`); NSGo `core/env.go` (`CanPurchase`), `internal/platform/macos/macos.go`, `internal/platform/ios/env.go` | | Local notifications | `core.Scope.ShowNotification`, `core.Env.CanScheduleNotifications()` | NSGo `core/env.go` (`CanScheduleNotifications`), `internal/platform/ios/env.go`, `internal/platform/watchos/watchos.go`, `docs/architecture/services.md` | | Remote push | No public API in NSGo `v0.3.4` | NSGo `docs/architecture/remote-push.md` | | Steam integration | `//go:build (darwin && !ios) \|\| (linux && !android) \|\| windows` | Game [`pkg/online/presence/steam_unix.go`](https://github.com/nsgo-dev/game/blob/main/pkg/online/presence/steam_unix.go), [`pkg/online/presence/steam_windows.go`](https://github.com/nsgo-dev/game/blob/main/pkg/online/presence/steam_windows.go), [`pkg/online/presence/steam_unsupported.go`](https://github.com/nsgo-dev/game/blob/main/pkg/online/presence/steam_unsupported.go), [`pkg/modding/workshop_steam.go`](https://github.com/nsgo-dev/game/blob/main/pkg/modding/workshop_steam.go) | | The editor | `//go:build ios \|\| android \|\| js` (disabled stubs) | Game [`pkg/editor/agent_runner_other.go`](https://github.com/nsgo-dev/game/blob/main/pkg/editor/agent_runner_other.go), [`pkg/editor/run_game_unsupported.go`](https://github.com/nsgo-dev/game/blob/main/pkg/editor/run_game_unsupported.go), [`pkg/editor/build_device_other.go`](https://github.com/nsgo-dev/game/blob/main/pkg/editor/build_device_other.go) | | Tested in CI | CI workflow matrices and `nsgo check` target lists | Game [`.github/workflows/test.yml`](https://github.com/nsgo-dev/game/blob/main/.github/workflows/test.yml), [`.github/workflows/check.yml`](https://github.com/nsgo-dev/game/blob/main/.github/workflows/check.yml) | ## Experimental targets HarmonyOS, tvOS, watchOS, and mini programs are outside the first stage of NSGo Game and are not built or vetted by this repository's CI. In NSGo `v0.3.4`, all four disable `Env.SupportsGPU()` and `Env.CanPlayAudio()`, so a 3D game renders an empty fallback view and any game using `pkg/sound` runs silent: - **HarmonyOS**: preview ArkWeb + ArkUI target; lacks GPU views, audio, gamepads, haptics, motion sensors, persistent `core.Storage`, native notifications, UDP, and game services ([nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521), [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320)). - **tvOS**: shares the iOS backend with gamepads, Game Center, StoreKit, and iCloud, but `ios/env.go` disables audio and GPU views until tvOS verification finishes ([nsgo#1317](https://github.com/nsgo-dev/nsgo/issues/1317)). - **watchOS**: SwiftUI host with 2D `Canvas`, touch, motion sensors, local saves, and local notifications, but no Metal/GPU view, no audio, no gamepads, no haptics, no iCloud, and no Game Center ([nsgo#1318](https://github.com/nsgo-dev/nsgo/issues/1318)). - **Mini programs** (WeChat, QQ, Alipay, Douyin): logic-layer `js/wasm` with `nsgo_noshader` and a 2 MB package cap; no GPU view, no audio, no gamepads, no haptics, no motion sensors, and no standard browser `fetch` or `WebSocket` globals ([nsgo#1505](https://github.com/nsgo-dev/nsgo/issues/1505)). ## Upstream gaps Every "Not available" or runtime-blocked cell in the matrix points to an open tracking issue: | Issue | Scope | | --- | --- | | [nsgo#1369](https://github.com/nsgo-dev/nsgo/issues/1369) | In-app purchases on Android (Google Play Billing) | | [nsgo#1370](https://github.com/nsgo-dev/nsgo/issues/1370) | In-app purchases on Windows, Linux, Web, and other targets | | [nsgo#59](https://github.com/nsgo-dev/nsgo/issues/59) | Remote push notifications (APNs and FCM) | | [nsgo#1323](https://github.com/nsgo-dev/nsgo/issues/1323) | Remote push open design decisions and provider adapters | | [nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521) | HarmonyOS platform parity | | [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320) | HarmonyOS preview target gaps | | [nsgo#1317](https://github.com/nsgo-dev/nsgo/issues/1317) | Apple TV (tvOS) remaining gaps (audio, GPU view) | | [nsgo#1318](https://github.com/nsgo-dev/nsgo/issues/1318) | Apple Watch (watchOS) remaining gaps | | [nsgo#1505](https://github.com/nsgo-dev/nsgo/issues/1505) | Mini programs larger apps and 2 MB package constraints | | [nsgo#1208](https://github.com/nsgo-dev/nsgo/issues/1208) | Web motion sensors (`WatchMotion`) | | [nsgo#1228](https://github.com/nsgo-dev/nsgo/issues/1228) | Steam client, Steam Linux Runtime, Steam Deck, overlay, and Steam Input verification | | [game#1305](https://github.com/nsgo-dev/game/issues/1305) | Running the `nsgo-dev/game` test suite on Windows in CI | | [game#1306](https://github.com/nsgo-dev/game/issues/1306) | Smoke-running examples on an iOS simulator and Android emulator in CI | ## Out of scope - **Game consoles** (Nintendo Switch, PlayStation, Xbox): console SDKs are under NDA and require C toolchains, whereas NSGo and NSGo Game are pure Go with no hand-written C. - **VR and AR**: currently out of scope until NSGo exposes an XR runtime ([#495](https://github.com/nsgo-dev/game/issues/495); see [VR and AR](http://nsgo.games/docs/#vr-and-ar)). - **Target-specific exclusions**: desktop operating systems have no OS-wide cloud save daemon (use `liveops.DirCloud` with Steam Auto-Cloud or `liveops.CloudClient` over [cloudsave](http://nsgo.games/docs/cloudsave/)), desktop targets have no mobile haptic or Core Motion APIs, browsers cannot open raw UDP sockets, Steamworks is desktop-only, and the visual [Scene Editor](http://nsgo.games/docs/editor/) is a desktop tool. See [Building and Shipping](http://nsgo.games/docs/shipping/) for packaging, signing, notarization, store channels, and `nsgo check` commands across the six primary build targets. --- Source: http://nsgo.games/docs/shipping/ # Building and Shipping For a first-load plan that connects resources, loading progress, web caching and size budgets, see [Small downloads and fast starts](http://nsgo.games/docs/small-downloads/). ## Web portal uploads Build one self-contained web folder and connect its page adapter to `liveops.Portal`. Test loading, gameplay start and stop, commercial breaks, rewarded success and rewarded errors with each portal's local SDK mode. Keep the game paused and muted until the SDK callback, and grant opt-in rewards only after a successful result. Verify your game across every target with `nsgo check`, configure its identity and export presets in `game.yaml`, keep icons and signing in `nsgo.yaml`, and build release packages for macOS, Windows, Linux, the web, iOS and Android with `nsgo build`. ## Name, identifier and version In a project made with `game new`, `game.yaml` owns the name, identifier, player-facing version, appearance and export settings. Replace the generated `dev.nsgo.` identifier with a reverse-DNS name of a domain you own before the first store upload, and keep it stable across releases: the App Store, Google Play and Microsoft Store identify the app by it. ```yaml version: 1 name: My Game id: com.example.mygame appVersion: 1.0.0 window: width: 1280 height: 720 export: output: dist presets: - platform: macos targets: [macos_arm64, macos_x64] - platform: windows targets: [windows_x64, windows_arm64] - platform: linux targets: [linux_x64, linux_arm64] - platform: web - platform: ios - platform: android targets: [android_arm64] ``` After editing `game.yaml`, synchronize the fields NSGo reads instead of editing them in `nsgo.yaml` yourself: ```sh go tool game project sync go tool game project check ``` `sync` keeps the other `nsgo.yaml` settings and comments. `build_number` is not part of `game.yaml`: leave it in `nsgo.yaml` and increment it for every store upload. `nsgo build` reads the synchronized files; its `-name`, `-id`, `-version`, `-build-number`, `-output`, `-target` and `-channel` flags override the corresponding values for one build without rewriting either file. ```yaml name: My Game id: com.example.mygame version: 1.0.0 build_number: 1 copyright: "© 2026 Example Studio" icon: apple: assets/AppIcon.icon # Icon Composer .icon (macOS/iOS) or .icns (macOS) png: assets/Icon.png # square PNG (1024x1024 recommended) build: output: dist installers: true targets: - macos_arm64 - macos_x64 - windows_x64 - windows_arm64 - linux_x64 - linux_arm64 - web - ios - android_arm64 ``` - **`appVersion` / `version`**: the user-facing semantic version (`CFBundleShortVersionString`, Android `versionName`). - **`build_number`**: a monotonically increasing integer for every store upload (`CFBundleVersion` on Apple platforms, `versionCode` on Android). When omitted, it derives from `version`. - **`resources/` vs `assets/`**: every runtime file loaded as `"asset:..."` — images, sounds, atlas JSON, tilemaps, models, data tables and raw bytes read by `assets.Manager` — lives in `resources/` and ships inside every package (fetched on demand on the web through `core.Scope.ReadAsset`). Build-time inputs such as app icons, or small startup files embedded with `//go:embed`, live in `assets/`. Use `mobile.exclude_resources` in `nsgo.yaml` to omit desktop-only files from iOS and Android packages. Before a release build, `game release` and the editor readiness checks refuse symbolic links, dotfiles and dot-directories, credential names such as `.env`, `.npmrc`, `.ssh`, `*.p12`, `*.pem`, and private-key or service-account contents in files up to 1 MiB under `resources/`, as well as named pipes and other non-regular files. An intentionally shipped dotfile may be listed with `export.allowResources` in `game.yaml`. It remains a warning for a person to review and never prints file contents. Build downloadable packs from the same encoded `resources/` output after `game assets` completes. Keep the pack definition and generated `manifest.json` with the release artifacts, run `game dlc verify` before uploading the ZIP, and keep `GAME_PACK_KEY` in CI secret storage. ## App icons Place default icons in `assets/` and `nsgo build` picks them up automatically without extra configuration: - `assets/AppIcon.icon` (Apple Icon Composer) or `assets/AppIcon.icns` (macOS only) for macOS and iOS. - `assets/Icon.png` (a square PNG, 1024×1024 recommended) for Windows, Linux, Android, the web, and any Apple target without `icon.apple`. To distinguish development builds from releases, add `-dev` variants (`assets/AppIcon-dev.icon`, `assets/Icon-dev.png`) or set `dev.icon`; `nsgo dev` uses them automatically. For desktop installers, you can also set `macos.dmg_icon`, `macos.dmg_background` (PNG with optional `@2x` twin), `windows.installer_icon` and `windows.uninstaller_icon` in `nsgo.yaml`. Android launchers can mask and move an adaptive icon instead of putting the shared PNG on their own background. Configure its foreground and background, and add a monochrome shape for Android 13's themed icons: ```yaml icon: android: foreground: assets/IconForeground.png background: "#1F1F1F" # a color or a square PNG monochrome: assets/IconMonochrome.png ``` Each layer is a 108 dp square, with PNGs scaled to 432 pixels. Keep the logo inside the center 66 dp (264 pixels) and let the background fill the whole square. Only the monochrome shape's alpha matters. `icon.android.png` can still select a plain Android bitmap; without one, NSGo uses `icon.png` or draws it from the adaptive layers. See [NSGo's building guide](https://nsgo.dev/docs/building/) for the fallback rules. ## Launch screen Set `launch_screen` in `nsgo.yaml` to show an opaque background, a centered PNG, or both on iOS and Android 12 or later: ```yaml launch_screen: background: "#F5F1EA" image: assets/Launch.png dark: background: "#201C26" image: assets/LaunchDark.png ``` Image paths are relative to `nsgo.yaml`. The image fits proportionally inside 128 × 128 points or dp; use a transparent PNG whose longest side is at least 512 pixels. The system selects light or dark unless `window.appearance` in `game.yaml` pins the appearance. An omitted dark field reuses its light value; omit the image or background entirely to keep the platform default. ## Apple privacy manifest and export compliance Every Apple bundle NSGo builds contains `PrivacyInfo.xcprivacy`, declaring the required-reason APIs used by NSGo and the Go runtime. Add your game's own declarations with `apple.privacy`; a `PrivacyInfo.xcprivacy` in `resources/` is merged with them rather than replaced. Record the app's answer to Apple's encryption export-compliance question under `apple.info`: ```yaml apple: privacy: accessed_apis: NSPrivacyAccessedAPICategoryDiskSpace: [E174.1] # example only: declare the APIs and reasons your game actually uses tracking: false info: ITSAppUsesNonExemptEncryption: false # example answer; use your app's actual answer # ITSEncryptionExportComplianceCode: "Apple's approval code, if you have one" ``` `accessed_apis` also supports the other Apple required-reason categories, and `privacy` accepts `tracking_domains` and `collected_data`. The export-compliance value must be a YAML boolean and the approval code a string. You can omit both keys and answer the questionnaire at upload instead. See [NSGo's building guide](https://nsgo.dev/docs/building/) and Apple's current App Store Connect guidance for the complete declarations. ## Verify all targets before building Check your host machine's toolchains first: ```sh go tool nsgo doctor ``` Run `nsgo check` to vet your Go code (and any catalogs) across every target before building release packages: ```sh go tool nsgo check -target all ``` Or check the six primary build targets explicitly: ```sh go tool nsgo check -target macos,windows,linux,web,ios,android ``` - Pass `-jobs N` to vet up to `N` targets in parallel. - A bare OS name (`macos`, `windows`, `linux`) expands to both its `arm64` and `x64` architectures; `android` expands to `android_arm64` (`android_x64` requires an Android NDK). - On Linux or Windows hosts, `-target all` skips Apple targets that require macOS and Xcode; naming `ios` explicitly fails if Xcode is absent. Run headless tests with `go tool nsgo test`, or run tests on a real platform with `go tool nsgo test -target macos|windows|linux|web|ios_simulator|android`. ## Build release packages `go tool game release` (and the scene editor's Export / Build and Release screens) runs `nsgo build` with `GOFLAGS=-tags=release`, compiling out development-only packages (`pkg/tooling/gamedebug`, `pkg/tooling/hotreload`, `pkg/tooling/devstate`, and physics/AI debug drawing), verifying built desktop binaries against leaked debug symbols, and writing `CREDITS.md` beside the packages: ```sh # Build every export preset in game.yaml (or all six primary targets by default) go tool game release # Build store-formatted packages instead of direct installers go tool game release -channel store -target macos,windows,linux,ios,android ``` `nsgo build` compiles stripped release binaries and writes one directory per target under `/--`, plus distributable release files. Until NSGo supports release-only tags in `nsgo.yaml` ([nsgo-dev/nsgo#2695](https://github.com/nsgo-dev/nsgo/issues/2695)), pass `GOFLAGS=-tags=release` whenever you invoke `nsgo build` directly (do not add `release` to `nsgo.yaml`'s `build.tags`, which also applies to `nsgo dev` and `nsgo test`): ```sh # Build every target configured in nsgo.yaml GOFLAGS=-tags=release go tool nsgo build # Build all targets Go and Xcode can build on this machine GOFLAGS=-tags=release go tool nsgo build -target all # Build store-formatted packages instead of direct installers GOFLAGS=-tags=release go tool nsgo build -channel store -target macos,windows,linux,ios,android ``` `-channel` chooses how packages are formatted and updated: - **`direct`** (default): direct-download installers and archives (`.dmg`, NSIS `.exe`, `.deb`/Arch/`.AppImage`, `.apk`, `.ipa`, web `.zip`). - **`store`**: store submission packages (Mac App Store `.pkg`, Microsoft Store `.msix`, Flathub `.tar.gz` + Flatpak manifest, Google Play `.aab`, iOS `.ipa`). - **`steam`**: unpacked desktop depot directories for macOS, Windows and Linux (with `steam-launch.sh` and bundled GTK 4 on `linux_x64`), without installers, self-updaters or `steam_appid.txt`. See [Shipping on Steam](http://nsgo.games/docs/steam/) for Steamworks setup, `nsgo-natives.yaml`, SteamPipe uploads, Steam Cloud paths and the Steam Deck checklist. - **`none`**: skips auto-update feeds while keeping direct packaging. Pass `-installers=false` if you only want the raw unpacked app directories on desktop targets. Pass `-run` to launch a built package immediately on this machine, a connected device, or a local web server. ## Credit your assets Most licenses an asset comes under, Creative Commons Attribution and the SIL Open Font License among them, ask for its author and license to be shipped with the game. Record them in the `credit` section of the import settings sidecar beside each asset (`hero.png.import.yaml`); `go tool game release`, which runs `nsgo build` for every platform, then writes `CREDITS.md` beside the packages, for the store or download page, and refuses to build while an asset in `game.yaml`'s `assets` section has no credit. `go tool game credits` checks the credits and prints the file without building; `go tool game credits -out resources/CREDITS.md` before the release puts it in every package too, since `nsgo build` copies the `resources` folder into each one ([Command Line](http://nsgo.games/docs/cli/#credits)). Assets the game loads from outside the `assets` section are not listed, so credit those yourself. ## Targets This table covers build packaging and store formats for the six primary build targets; see [Platform support](http://nsgo.games/docs/platforms/) for which runtime features work on each target, the status of experimental targets (HarmonyOS, tvOS, watchOS and mini programs), and links to upstream gaps. | Platform | Target names | Direct build (`-channel direct`) | Store build (`-channel store`) | Host requirements | | --- | --- | --- | --- | --- | | macOS | `macos_arm64`, `macos_x64` (`macos`) | `.app` + `.dmg` | Sandboxed `.pkg` | macOS for signing/notarization | | Windows | `windows_x64`, `windows_arm64` (`windows`) | `.exe` bundle + NSIS installer | `.msix` | Any host (Go cross-compiles) | | Linux | `linux_x64`, `linux_arm64` (`linux`) | Binary bundle + `.deb`, Arch pkg, `.AppImage` | `.tar.gz` + AppStream + Flatpak manifest | Any host (Go cross-compiles) | | Web | `web` | Static WebAssembly site + `.zip` | Same static site | Any host | | iOS | `ios`, `ios_simulator` | `.ipa` | `.ipa` | macOS + Xcode | | Android | `android_arm64` (`android`), `android_x64` | `.apk` | `.aab` | Any host (`android_x64` needs NDK) | Consoles (Nintendo Switch, PlayStation and Xbox) are not targets: their SDKs are under NDA and need C toolchains, and NSGo is Go only. ### macOS Build Apple Silicon, Intel, or both: ```sh go tool nsgo build -target macos ``` - **Code signing**: without an identity, macOS apps are signed ad hoc (fine for local testing, rejected by Gatekeeper when downloaded). For direct distribution, pass a Developer ID Application certificate via `sign.identity` or `-sign`: ```sh go tool nsgo build -target macos -sign "Developer ID Application: Example Studio (TEAMID)" ``` - **Notarization**: to open on other Macs without Gatekeeper warnings, configure a keychain profile (`xcrun notarytool store-credentials`) in `sign.notarize` or pass `-notarize `. In CI, set the App Store Connect API key environment variables `NSGO_NOTARY_KEY` (path to `.p8`), `NSGO_NOTARY_KEY_ID` and `NSGO_NOTARY_ISSUER`. `nsgo build` submits the `.dmg` (or zipped `.app`), waits for approval, and staples the ticket to both the `.app` and `.dmg`. - **Mac App Store**: set `macos.category` (for example `public.app-category.games`), `sign.macos_profile` (Mac App Store provisioning profile) and optionally `sign.installer` (Mac Installer Distribution identity), then build with `-channel store`: ```sh go tool nsgo build -channel store -target macos ``` `nsgo build` signs the app in the App Sandbox and packages a `.pkg` installer ready for `go tool nsgo publish macos`, as [Publish to the stores](http://nsgo.games/docs/shipping/#publish-to-the-stores) describes. ### Windows Build x64, ARM64, or both: ```sh go tool nsgo build -target windows ``` - **Direct distribution**: produces the application directory and an NSIS setup installer (`-installers=true`, default). Set `windows.publisher` and `copyright` in `nsgo.yaml` to populate executable metadata and uninstall entries. - **Code signing**: sign executables and the installer to prevent SmartScreen warnings. Pass a PKCS#12 `.pfx` certificate with `-certificate` (or `sign.certificate`) and provide its password in `NSGO_CERTIFICATE_PASSWORD`, plus an RFC 3161 timestamp server (`-timestamp-url` / `sign.timestamp_url`, defaults to `http://timestamp.digicert.com`): ```sh NSGO_CERTIFICATE_PASSWORD="$PFX_PASSWORD" \ go tool nsgo build -target windows -certificate certs/win.pfx ``` For hardware tokens or cloud signing services, use `-sign-command` (or `sign.sign_command`) where `%1` stands for each file path. - **Microsoft Store**: set `windows.store.identity`, `windows.store.publisher` (`CN=...`) and `windows.store.publisher_name` from Partner Center, then build with `-channel store` to produce an `.msix` package (left unsigned so the Store signs it on publication): ```sh go tool nsgo build -channel store -target windows ``` ### Linux Build x64, ARM64, or both: ```sh go tool nsgo build -target linux ``` - **Direct distribution**: builds `.deb` (Debian/Ubuntu), Arch packages and `.AppImage` bundles. Configure desktop metadata in `nsgo.yaml`: ```yaml linux: categories: [Game] maintainer: "Example Studio " summary: "A 2D adventure game" license: MIT ``` Add extra runtime dependencies with `linux.depends` and `linux.recommends` if your game ships helper binaries. - **Flathub / Flatpak**: build with `-channel store` to emit `.tar.gz` archives containing `.metainfo.xml` AppStream metadata and a `flatpak/.yml` manifest targeting the GNOME runtime (`linux.flatpak_runtime` overrides the default runtime version). Submit the manifest to Flathub or build locally with `flatpak-builder`. ### The web Build the static WebAssembly bundle: ```sh go tool nsgo build -target web ``` Test the production build locally before deploying: ```sh go tool nsgo build -target web -run ``` `dist/--web/` contains the HTML, JS, WebAssembly binary and `resources/` files, and `nsgo build` also writes a `.zip` archive in the releases directory. Upload the directory contents to any static host (GitHub Pages, Cloudflare Pages, Netlify, itch.io, or S3). Remember that browsers gate audio behind the first user gesture (see [sound](http://nsgo.games/docs/sound/)). #### Hosting and embedding Keep the generated names and headers when you upload the directory. The browser can compile a streaming module only when the `.wasm` response is `Content-Type: application/wasm`; an `application/octet-stream` response still works but buffers the module first. The loader always requests the `.wasm` file, so the `.wasm.br` and `.wasm.gz` copies beside it help only when the host answers that request with a copy's bytes, its `Content-Encoding` and `Vary: Accept-Encoding`; a header rule on the `.wasm.br` path alone never applies. | Host | Recommended setup | | --- | --- | | GitHub Pages | Upload the directory as-is. Pages gzips the `.wasm` response on the fly but never serves the `.wasm.br` or `.wasm.gz` copies, and it has no setting for `Cache-Control`. | | Netlify | Netlify compresses responses itself and does not serve the adjacent copies for a `.wasm` request. Use a `_headers` file to add `Cache-Control: public, max-age=31536000, immutable` to the hashed module, loader and resource names. | | Cloudflare Pages | Use a Pages Function (static redirects cannot match `Accept-Encoding`) to answer a `.wasm` request with `.br`/`.gz` by `Accept-Encoding`, set `Content-Type: application/wasm`, `Content-Encoding` and `Vary`, and cache hashed files for a year. | | S3/CloudFront | Upload the `.wasm.br` and `.wasm.gz` objects with `Content-Type: application/wasm`, their `Content-Encoding` and `Cache-Control` metadata, and add a CloudFront Function that rewrites a `.wasm` request to one of them by `Accept-Encoding`. Include `Accept-Encoding` in the cache key so Brotli and gzip are cached separately. | | nginx | Enable `gzip_static on` and, with the `ngx_brotli` module, `brotli_static on`, keep `types { application/wasm wasm; }`, and send immutable caching for the hashed files. | When embedding the game, give its iframe the permissions it needs: ```html ``` A sandboxed iframe needs `allow-scripts` and `allow-same-origin` in its `sandbox`, plus `allow-pointer-lock` when the game uses pointer-lock mouselook. Without `allow-same-origin`, browser storage and an offline worker use a unique origin and cannot share the game's normal save data. Keep each game on its own origin or namespace its storage keys when a portal hosts several games, because web save storage and quota are shared by origin. Audio and fullscreen still require a user gesture, and iPhone Safari does not provide element fullscreen, so use the page's fullscreen fallback there. ### iOS Requires macOS with Xcode installed. Build for physical devices (`.ipa`) or the simulator: ```sh go tool nsgo build -target ios go tool nsgo build -target ios_simulator ``` - **Signing**: provide an App Store, Ad Hoc or Development provisioning profile matching `id` via `sign.profile` (or `-profile`). `nsgo build` automatically selects the matching signing identity from your keychain, or you can specify it explicitly with `sign.identity` (or `-sign`). - **Store submission**: - Upload the signed store `.ipa` to App Store Connect / TestFlight with `go tool nsgo publish ios`, as [Publish to the stores](http://nsgo.games/docs/shipping/#publish-to-the-stores) describes. - Increment `build_number` (`CFBundleVersion`) for every upload. - Configure iPad multitasking and screen orientations with `apple.requires_full_screen` and `apple.orientations` (`portrait`, `portrait_upside_down`, `landscape_left`, `landscape_right`), and add any required `Info.plist` entries under `apple.info`. `apple.orientations` declares the orientations a full-screen iPad allows, while the runtime request from `cx.RequestOrientation` applies on both the iPhone and the iPad (see [Orientation on phones](http://nsgo.games/docs/screen/#orientation-on-phones)). On an iPad, UIKit allows only the orientations both lists share, so list every orientation the game requests, such as `landscape_left` and `landscape_right` for a landscape game; a request with nothing in common with `apple.orientations` leaves the iPad no valid orientation. ### Android Build ARM64 (needs only Go — `CGO_ENABLED=0`, no Android SDK or NDK required): ```sh go tool nsgo build -target android_arm64 ``` To also build `android_x64` (for x86_64 emulators or Chromebooks), install an Android NDK and pass `-target android_arm64,android_x64`. - **Create an upload key**: use the JDK's `keytool` to create a PKCS#12 upload keystore, answer its identity prompts, and choose strong passwords when prompted. Keep the file and passwords out of version control and back them up securely: ```sh mkdir -p certs keytool -genkeypair -v -keystore certs/upload.p12 -storetype PKCS12 -alias upload -keyalg RSA -keysize 2048 -validity 10000 ``` - **Signing**: configure the PKCS#12 or JKS keystore via `sign.keystore` (or `-keystore`) and `sign.key_alias` (or `-key-alias`). Never commit passwords to `nsgo.yaml`; pass them via environment variables: ```sh NSGO_KEYSTORE_PASSWORD="$STORE_PW" NSGO_KEY_PASSWORD="$KEY_PW" \ go tool nsgo build -channel store -target android_arm64 \ -keystore certs/upload.p12 -key-alias upload ``` Without a keystore, `nsgo build` signs APKs with the project's debug key (for sideloading only, rejected by Google Play). - **Google Play**: build with `-channel store` to produce a signed `.aab` (Android App Bundle), then upload it with `go tool nsgo publish -target android`, as [Publish to the stores](http://nsgo.games/docs/shipping/#publish-to-the-stores) describes. Increment `build_number` (`versionCode`) on every upload, set `android.target_sdk` to Google Play's current required API level (`minSdkVersion` is 28), and declare any extra permissions under `android.permissions`. - **Mainland China stores (no Google Play Services) & HarmonyOS**: for publishing approval (版号/ISBN), MIIT APP filing, first-launch privacy consent, signed `.apk` distribution across Huawei AppGallery, Xiaomi, OPPO, vivo, Honor and TapTap, online-package fallbacks without Google services, and HarmonyOS / mini program preview status, see [Releasing in Mainland China](http://nsgo.games/docs/shipping-china/). - **Orientation**: the manifest does not fix an orientation; the game requests the one it plays in at runtime with `cx.RequestOrientation` (see [Orientation on phones](http://nsgo.games/docs/screen/#orientation-on-phones)). ### WeChat and Douyin mini-game publishing Review uploads on the Build and Release screen has WeChat and Douyin mini program destinations (`PublishDestWeChat`, `PublishDestDouyin`). A `miniprogram` export preset's row uploads to the destination of the first `miniprogram_wechat` or `miniprogram_douyin` target the preset lists; a preset that lists no targets builds every mini program, WeChat first, so it uploads to WeChat. `SetReleaseUploadDestination` points a row at another destination. The mini program's AppID is read from `miniprogram.appid.wechat` or `miniprogram.appid.douyin` in `nsgo.yaml`, the same key NSGo builds the developer tool's project with (see [Releasing in Mainland China](http://nsgo.games/docs/shipping-china/)), and the row shows it or names the missing key. The AppID is not a secret: the AppID typed into the key form's account field, or passed to `SetMiniProgramAppID`, is checked (`wx` or `tt` followed by letters and digits) and written to `nsgo.yaml` with its other keys and comments kept, while the upload key goes only to the system keychain. Before a person-confirmed upload starts, `ValidateMiniProgramPreflight` checks the AppID, a `major.minor.patch` version (such as `1.2.3`) and an upload key of at least 16 bytes, and, when it is given a source IP and an allowlist, that the address falls inside one of the allowlisted prefixes. The upload runs `nsgo publish miniprogram -target -version ` with the key in `NSGO_MINIPROGRAM_UPLOAD_KEY` and the AppID in `NSGO_MINIPROGRAM_APP_ID`. `nsgo publish` has no mini program command yet ([nsgo-dev/nsgo#2723](https://github.com/nsgo-dev/nsgo/issues/2723)), so the upload fails until it does. For the same reason there is no phone preview: the preview QR is an image the vendor's developer tool writes, nothing in the editor can produce it until `nsgo publish` drives that tool's preview, and the row says the preview is not available yet. ## Store listings Keep store metadata in version control as YAML and Markdown under `store/`, or change the directory with `store.dir` in `nsgo.yaml`: ```text store/ listing.yaml # version: 1, default_locale, app_store and google_play settings en-US/ listing.yaml # version: 1, title, subtitle, short_description, keywords and URLs description.md # full description; can instead be the YAML description field release_notes.md # what's new; can instead be the YAML release_notes field promotional_text.md # optional App Store promotional text screenshots/ zh-Hans/ listing.yaml description.md release_notes.md screenshots/ ``` Both levels of `listing.yaml` require `version: 1` and refuse unknown fields. Canonical locale directories map to each store's locale automatically; `app_store.locale` and `google_play.locale` can override the mapping. `app_store.bundle_id`, `app_store.version` and `google_play.package_name` default to the identity synchronized from `game.yaml`. See [NSGo's building guide](https://nsgo.dev/docs/building/#store-listings) for every field, media type and store-specific override. Validate every locale before a release: ```sh go tool nsgo publish -store all -dry-run ``` This checks required fields, locale codes, URL schemes, media files and counts, and each store's character limits without reading credentials or making HTTP requests. The limits include 30 characters for either store's title, 80 for a Google Play short description, 4000 for either full description, and 500 for Google Play release notes. App Store Connect also limits subtitles to 30, keywords to 100, promotional text to 170 and release notes to 4000 characters. To upload the validated metadata, run `go tool nsgo publish -store appstore,play`; add `-track production` with `-store play` to update that track's release notes. App Store Connect reads `NSGO_APP_STORE_KEY`, `NSGO_APP_STORE_KEY_ID` and `NSGO_APP_STORE_ISSUER`, falling back to the corresponding `NSGO_NOTARY_*` variables. Google Play reads `NSGO_PLAY_SERVICE_ACCOUNT`. Credentials come from the environment, never the listing files. ### Store screenshot plan `store/capture.yaml` records which scene, input recording and frame make each store screenshot and cover, and the sizes each store needs, so the set can be rebuilt after an art pass and a diff shows what changed: ```yaml version: 1 shots: - name: title scene: scenes/title.scene.yaml frame: 30 output: title sizes: - preset: itch_cover - preset: minigame_share - name: boss scene: scenes/boss.scene.yaml recording: recordings/boss.replay.yaml time: 2.5 output: play/boss sizes: - preset: google_play - width: 2796 height: 1290 ``` Each shot names a scene and optionally a `.replay.yaml` input recording, both relative to the project, the fixed-step `frame` or `time` in seconds to capture (at most one; neither means the first frame), an `output` name, and its `sizes`, each a `preset` or an explicit `width` and `height`. A shot's image at each size is `-x.png` under the media directory, `store/media` by default. The presets are `app_store_iphone` (1290x2796), `app_store_ipad` (2064x2752), `google_play` (1920x1080), `google_play_feature` (1024x500), `itch_cover` (630x500) and `minigame_share` (1280x720); a landscape App Store screenshot is an explicit size. The plan needs `version: 1`, refuses unknown fields, paths outside the project and two images with the same file, and encodes back to the same bytes. `go tool game capture` checks the plan: every scene and recording exists, and every image exists as a PNG of its target size, reporting each missing or wrongly sized file and exiting with 1; `-shot name` checks one shot. It does not render the images yet: that needs the fixed-step movie mode of [#1438](https://github.com/nsgo-dev/game/issues/1438), so for now capture them with the runtime MCP bridge's `game_screenshot` or by hand. ## Publish to the stores Create the app records in App Store Connect and Google Play Console before uploading. NSGo uploads builds and store metadata, but you still submit the processed build for review in each store. For App Store Connect and TestFlight, sign an iOS `.ipa` with an App Store distribution profile or a macOS store `.pkg` with the team's installer identity. On a Mac with Xcode, set `NSGO_APP_STORE_KEY` to an App Store Connect `.p8` key's path or contents, and set `NSGO_APP_STORE_KEY_ID` and `NSGO_APP_STORE_ISSUER`; give the key access to the app and permission to upload builds. Then pass the signed package to the matching command: ```sh go tool nsgo publish ios path/to/MyGame.ipa go tool nsgo publish macos path/to/MyGame.pkg ``` The command checks the bundle's build number, uploads the package and reports Apple's processing result. Increment `build_number` before the next upload. macOS build numbers increase across all app versions; iOS can restart the sequence for a new version. For Google Play, enable the Google Play Developer API and give a service account permission to release the app to the chosen track. Set `NSGO_PLAY_SERVICE_ACCOUNT` to the service-account JSON key's contents or file path, build a signed App Bundle, and publish it: ```sh GOFLAGS=-tags=release go tool nsgo build -channel store -target android go tool nsgo publish -target android -track internal ``` `publish` finds the current project version's `.aab` in `build.output/releases`. If more than one matches, pass the desired `.aab` path after the flags. The track can be `internal`, `production` or a closed track's ID. NSGo reads the package name and version code from the bundle, requires a version code higher than every release on that track, uploads the bundle and commits the release. ### Publish records Each successful upload from the editor's Build and Release screen (itch.io, Google Play internal testing or TestFlight) is recorded in `.game/publish/.yaml`, under the `.game` folder a project leaves out of version control. The record holds the last upload's version, `build_number` from `nsgo.yaml`, artifact name, SHA-256, size, upload time, result URL and outcome, plus the time of each store-console step a person confirmed. The file is versioned (`version: 1`), refuses unknown fields, is written atomically and never contains a credential. A new upload clears the confirmations for the previous version and keeps the app-level ones, such as the store account. ## Store compliance Use `nsgo.yaml` to track the release questionnaires that remain outside the package: ```yaml compliance: app_store: { age_rating: false } google_play: { data_safety: false } steam: { content_survey: false } ``` Set an entry to `true` after completing its questionnaire. A matching `-channel store` or `-channel steam` build reminds you about entries still set to `false`; omit entries you do not want to track. - Complete the [age rating questionnaire](https://developer.apple.com/help/app-store-connect/manage-app-information/set-an-app-age-rating) and [App Privacy details](https://developer.apple.com/help/app-store-connect/manage-app-information/manage-app-privacy) in App Store Connect. Answer the encryption export-compliance question as [Apple privacy manifest and export compliance](http://nsgo.games/docs/shipping/#apple-privacy-manifest-and-export-compliance) describes. - Complete [Data safety](https://support.google.com/googleplay/android-developer/answer/10787469) in Play Console. Apps distributed exclusively on the internal testing track are exempt. - Complete the [Content Survey](https://partner.steamgames.com/doc/gettingstarted/contentsurvey) in Steamworks before submitting the game for review. ## Web host bridge `pkg/hostbridge.Attach` gives embedding pages stable `pause`, `resume`, `mute`, and `unmute` events. Games can post `loadingProgress` with `{loaded,total}`, then `loaded`, `gameplayStart`, and `gameplayStop` through the returned bridge. --- Source: http://nsgo.games/docs/steam/ # Shipping on Steam Configure Steamworks app and depot IDs, bundle the Steamworks redistributable through `nsgo-natives.yaml`, build desktop depots with `go tool game release -channel steam`, upload builds via SteamPipe to a staging branch, map NSGo's save directories to Steam Auto-Cloud, and verify your game against Steam Deck and Steam review requirements. ## Steamworks setup Create your application in the [Steamworks Partner Portal](https://partner.steamgames.com/) and note its **App ID**. Under **SteamPipe → Depots**, create one depot per desktop operating system you ship: | Platform | NSGo target | Typical Steamworks OS setting | | --- | --- | --- | | macOS (Apple Silicon + Intel) | `macos_universal` | macOS (64-bit) | | Windows (64-bit) | `windows_x64` | Windows (64-bit) | | Linux / SteamOS (64-bit) | `linux_x64` | Linux (64-bit) | Steamworks assigns each depot its own **Depot ID** (commonly sequential after the App ID, such as `AppID + 1`, `AppID + 2`, `AppID + 3`; always copy the exact IDs shown in the portal). ### Local testing with `steam.app_id` When launching a game outside the Steam client during development, Steamworks looks for `steam_appid.txt` in the working directory. Set `steam.app_id` in `nsgo.yaml`: ```yaml steam: app_id: 480 # replace with your Steamworks App ID (480 is Spacewar, Valve's test app) ``` - `go tool nsgo dev` and `go tool game dev` write `steam_appid.txt` into the native build directory and start the app with that directory as its working directory so `SteamAPI_Init` succeeds while the Steam client is open. - `go tool game release -channel steam` (and `nsgo build -channel steam`) never writes `steam_appid.txt` into shipped depots and ignores any `steam_appid.txt` inside `resources/`. Never commit or upload `steam_appid.txt` to a Steam depot. ### Bundling the Steamworks redistributable (`nsgo-natives.yaml`) NSGo games bind Steamworks dynamically via `purego` / `syscall` with zero cgo. Download the Steamworks SDK from the Steamworks Partner Portal and copy the three desktop redistributables (`libsteam_api.dylib`, `steam_api64.dll`, `libsteam_api.so`) and Valve's SDK license file into a Go package inside your project (for example `internal/steamlib/`), then declare them in `internal/steamlib/nsgo-natives.yaml`: ```yaml version: 2 libraries: macos_arm64: - name: libsteam_api.dylib path: lib/macos/libsteam_api.dylib sha256: "<64-hex-sha256-of-libsteam_api.dylib>" licenses: [licenses/STEAMWORKS_LICENSE.txt] macos_x64: - name: libsteam_api.dylib path: lib/macos/libsteam_api.dylib sha256: "<64-hex-sha256-of-libsteam_api.dylib>" licenses: [licenses/STEAMWORKS_LICENSE.txt] windows_x64: - name: steam_api64.dll path: lib/windows-x64/steam_api64.dll sha256: "<64-hex-sha256-of-steam_api64.dll>" licenses: [licenses/STEAMWORKS_LICENSE.txt] windows_arm64: [] linux_x64: - name: libsteam_api.so path: lib/linux-x64/libsteam_api.so sha256: "<64-hex-sha256-of-libsteam_api.so>" licenses: [licenses/STEAMWORKS_LICENSE.txt] linux_arm64: [] ios: [] ios_simulator: [] tvos: [] tvos_simulator: [] ``` - Compute each digest with `shasum -a 256 ` (macOS/Linux) or `Get-FileHash -Algorithm SHA256 ` (Windows). - Valve ships `libsteam_api.dylib` as a universal macOS binary, so the same file can serve both `macos_arm64` and `macos_x64` when building `macos_universal`. - Import the package (for example `_ "example.com/mygame/internal/steamlib"`) in your desktop build so NSGo copies each library into the right location before signing: - **macOS**: `.app/Contents/Frameworks/libsteam_api.dylib` - **Windows**: `steam_api64.dll` beside `.exe` - **Linux**: `libsteam_api.so` beside `` - Because Steamworks redistributables are proprietary, keep them out of public repositories or fetch them in CI from a private artifact store rather than a public URL. - Today, [`pkg/online/presence`](http://nsgo.games/docs/presence/#steam-rich-presence) automatically probes `/../Frameworks/libsteam_api.dylib` on macOS and `` on Windows and Linux, while [`pkg/modding`](http://nsgo.games/docs/modding/#steam-workshop-workshop) loads by library name or `SteamWorkshopOptions.LibraryPath`. [`pkg/online/steamworks`](http://nsgo.games/docs/steamworks/) probes the same locations and is the one shared client that owns `SteamAPI_Init`, the callback pump, overlay pause and join events; pass it to `presence.SteamConfig.Client` and `modding.SteamWorkshopOptions.Client`. ## Building depots Build all three desktop depots in one run with `go tool game release`: ```sh go tool game release -channel steam -target macos_universal,windows_x64,linux_x64 ``` Why pass `-target macos_universal,windows_x64,linux_x64` explicitly: - If `game.yaml` declares `export.presets` that include mobile or web platforms, `game release` uses those presets unless `-target` overrides them, and `-channel steam` refuses non-desktop targets. - Without `export.presets`, `-channel steam` defaults to `macos,windows,linux`, which builds separate `macos_arm64` and `macos_x64` directories; passing `macos_universal` joins both macOS architectures into one universal `.app` bundle, which matches a single macOS Steam depot. - `macos_universal` requires a macOS host. On Linux or Windows hosts, build `-target windows_x64,linux_x64` there and build `macos_universal` on macOS. - If Steam is the project's only distribution channel, you can also set `updates: { channel: steam }` in `nsgo.yaml` so `-channel steam` becomes the default. `go tool game release` runs `nsgo build` with `GOFLAGS=-tags=release` (compiling out `pkg/tooling/gamedebug`, `pkg/tooling/hotreload`, `pkg/tooling/devstate`, and physics/AI debug drawing), verifies the built desktop binaries against leaked debug symbols, checks asset license credits (writing `CREDITS.md` beside the depots; run `go tool game credits -out resources/CREDITS.md` before building to include it inside every depot), and reminds you if `compliance.steam.content_survey` in `nsgo.yaml` is still `false`. Each depot is written to `/--/` with no installers, no self-updater and no `steam_appid.txt`: | Depot directory | Contents | | --- | --- | | `dist/--macos_universal/` | `.app` (signed and notarized when `sign.identity` and `sign.notarize` are configured; holds `Contents/Resources/` and `Contents/Frameworks/`). | | `dist/--windows_x64/` | `.exe`, runtime files from `resources/`, `THIRD_PARTY_NOTICES.txt`, and declared Windows DLLs (such as `steam_api64.dll`). | | `dist/--linux_x64/` | ``, `steam-launch.sh`, `nsgo-gtk/` (GTK 4 runtime and `nsgo-gtk/licenses/`), `.desktop`, runtime files from `resources/`, `THIRD_PARTY_NOTICES.txt`, and declared Linux `.so` libraries (such as `libsteam_api.so`). | Sign and notarize your macOS `.app` (`sign.identity`, `sign.notarize`, or `NSGO_NOTARY_*` in CI) and Authenticode-sign your Windows `.exe` and DLLs (`sign.certificate` + `NSGO_CERTIFICATE_PASSWORD` or `sign.sign_command`) so players do not hit Gatekeeper or SmartScreen warnings when launching through Steam. See [Building and Shipping](http://nsgo.games/docs/shipping/) for signing configuration. ## Launch options and Linux runtime Configure one launch option per operating system in Steamworks under **Installation → General Installation**: | OS | Executable | Working directory | Notes | | --- | --- | --- | --- | | macOS | `.app` | (empty / depot root) | Universal `.app` bundle from `macos_universal`. | | Windows (64-bit) | `.exe` | (empty / depot root) | Executable from `windows_x64`. | | Linux (64-bit) | `steam-launch.sh` | (empty / depot root) | Wrapper script generated by `nsgo build -channel steam` for `linux_x64`. | | Linux (arm64, optional) | `` | (empty / depot root) | Requires GTK 4 in the host runtime (no `nsgo-gtk/` bundle). | Under **Installation → Linux Runtime**, select **Steam Linux Runtime 3.0 (sniper)** (or 4.0 when available). Steam Linux Runtime supplies the display stack but does not ship GTK 4.14+. On `linux_x64`, `nsgo build -channel steam` bundles GTK 4 and its dependencies in `nsgo-gtk/` alongside `steam-launch.sh`: - `steam-launch.sh` checks `ldconfig` for a system `libgtk-4.so.1` of version 4.14 or newer. - Only when the system lacks GTK 4.14+ (as inside Steam Linux Runtime 3.0/4.0) does it prepend `nsgo-gtk/lib` to `LD_LIBRARY_PATH` and `nsgo-gtk/share` to `XDG_DATA_DIRS`, then `exec`s your game binary with all launch arguments intact. - Keep `nsgo-gtk/`—including `nsgo-gtk/licenses/` (`NOTICE`, `build.sh`, and upstream license texts)—in your Linux depot. It provides the LGPL license notices and corresponding source/build instructions for the bundled GLib, Pango and GTK libraries. ## Uploading with SteamPipe `nsgo publish` does not yet upload builds to Steam ([nsgo-dev/nsgo#2691](https://github.com/nsgo-dev/nsgo/issues/2691)). Upload depots with Valve's `steamcmd` and SteamPipe VDF build scripts. Create a `steam/` directory at your project root with one app build script and three depot build scripts. Replace `1000` with your App ID, `1001`–`1003` with your Depot IDs, and `My Game-1.0.0` with your `-` prefix (or copy the three depot directories to fixed paths such as `dist/steam/macos`, `dist/steam/windows`, `dist/steam/linux` in your release script so the VDFs stay unchanged across versions): ```text // steam/app_build.vdf "AppBuild" { "AppID" "1000" "Desc" "1.0.0 release candidate" "BuildOutput" "../build/steam-output" "ContentRoot" "../dist" "SetLive" "staging" "Depots" { "1001" "depot_macos.vdf" "1002" "depot_windows.vdf" "1003" "depot_linux.vdf" } } ``` ```text // steam/depot_macos.vdf "DepotBuild" { "DepotID" "1001" "FileMapping" { "LocalPath" "My Game-1.0.0-macos_universal/*" "DepotPath" "." "recursive" "1" } "FileExclusion" "*.pdb" "FileExclusion" ".DS_Store" "FileExclusion" "steam_appid.txt" } ``` ```text // steam/depot_windows.vdf "DepotBuild" { "DepotID" "1002" "FileMapping" { "LocalPath" "My Game-1.0.0-windows_x64/*" "DepotPath" "." "recursive" "1" } "FileExclusion" "*.pdb" "FileExclusion" "steam_appid.txt" } ``` ```text // steam/depot_linux.vdf "DepotBuild" { "DepotID" "1003" "FileMapping" { "LocalPath" "My Game-1.0.0-linux_x64/*" "DepotPath" "." "recursive" "1" } "FileExclusion" "*.debug" "FileExclusion" "steam_appid.txt" } ``` Run `steamcmd` from the project root (create `build/steam-output` first if it does not exist): ```sh mkdir -p build/steam-output steamcmd +login +run_app_build "$(pwd)/steam/app_build.vdf" +quit ``` ### Branches and promoting builds safely - **Never point `"SetLive"` at `"default"` in a VDF script or CI job.** Always upload to a non-default branch such as `staging` (password-protected in Steamworks under **SteamPipe → Builds**). - Opt a test Steam client into `staging` on macOS, Windows, and Linux / Steam Deck. Verify cold launch, audio, controller input, Steam overlay, and Steam Cloud sync. - Once verified, open **SteamPipe → Builds** in the Steamworks Partner Portal, select the tested BuildID, set it live on `default`, and click **Preview Change → Set Build Live Now**. - Keep a `previous` branch (or note the prior live BuildID) so you can roll back immediately if a regression reaches players. ### Automating uploads in CI 1. **Create a dedicated builder account**: in Steamworks (**Users & Permissions**), add a separate Steam account with only **Edit App Metadata** and **Publish App Changes to Steam** permissions for this app. Never store a personal admin account in CI. 2. **Cache Steam Guard credentials once**: run `steamcmd +login +quit` interactively on a trusted machine to approve Steam Guard, then base64-encode `steamcmd`'s cached `config/config.vdf` (and `ssfn*` if present) into a CI secret such as `STEAM_CONFIG_VDF` alongside `STEAM_USERNAME`. 3. **Build and upload to `staging` only**: build `macos_universal` on a macOS runner (and `windows_x64,linux_x64` on macOS or Linux), assemble all three depots in one `dist/` directory, restore `config.vdf`, and run `steamcmd +login "$STEAM_USERNAME" +run_app_build "$PWD/steam/app_build.vdf" +quit`. Promote the uploaded BuildID to `default` manually in Steamworks after smoke-testing `staging`. ## Steam Cloud NSGo's `cx.DataDir()` resolves to a per-app directory keyed by `id` in `nsgo.yaml` (for example `com.example.mygame`): | OS | NSGo `cx.DataDir()` | Steamworks Auto-Cloud Root | Subdirectory for `DirCloud` | Pattern | | --- | --- | --- | --- | --- | | Windows | `%APPDATA%\` | `WinAppDataRoaming` | `/cloud` | `*.json` | | macOS | `~/Library/Application Support/` | `MacAppSupport` | `/cloud` | `*.json` | | Linux / SteamOS | `$XDG_DATA_HOME/` (default `~/.local/share/`) | `LinuxXdgDataHome` | `/cloud` | `*.json` | Configure Steam Auto-Cloud in Steamworks under **Application → Steam Cloud**: 1. Enable Steam Cloud and set a byte quota and file-count quota per user (for example 100 MB and 100 files). 2. Under **Auto-Cloud Configuration**, add one rule with Root `WinAppDataRoaming`, Subdirectory `/cloud` (for example `com.example.mygame/cloud`), Pattern `*.json`, and **Include Subdirectories** unchecked. 3. Under **Root Overrides**, map `WinAppDataRoaming` to: - **macOS**: Root `MacAppSupport`, Add/Replace Path `/cloud` - **Linux + SteamOS**: Root `LinuxXdgDataHome`, Add/Replace Path `/cloud` In Go, point [`liveops.NewDirCloud`](http://nsgo.games/docs/liveops/#cloud-saves) at `filepath.Join(cx.DataDir(), "cloud")` and pair it with `liveops.NewCloudSyncer`: ```go dirCloud, err := liveops.NewDirCloud(filepath.Join(cx.DataDir(), "cloud")) if err != nil { return err } syncer, err := liveops.NewCloudSyncer(liveops.CloudSyncOptions{ Local: save.StorageBackend(cx.Storage(), "mygame"), Cloud: dirCloud, State: cx.Storage(), Device: deviceID, Policy: liveops.PolicyKeepBoth, }) if err != nil { return err } ``` Why sync `cx.DataDir()/cloud` with `DirCloud` instead of syncing all of `cx.DataDir()`: - **Machine-local settings stay local**: display resolution, fullscreen mode, frame cap, and audio settings kept in `cx.Storage()` (or `save.NewDefaultSettingsStore(syncer.Backend())`) are never synced, so playing on a 1280×800 Steam Deck does not overwrite a desktop PC's display settings. - **Conflict safety**: `DirCloud` implements `ConditionalCloudSync` with atomic temp-file writes and directory sync, and `CloudSyncer` resolves concurrent offline edits across machines without silently dropping progress (see [Live operations](http://nsgo.games/docs/liveops/#resolving-conflicts-539)). - **Direct file alternative**: games that do not use `CloudSyncer` can point Auto-Cloud at `` (`save.FileBackend(cx.DataDir())`, pattern `*.json`), keeping settings in a separate non-`.json` key or `cx.Storage()` so they are not synced. - **Native Linux vs Proton**: if you ship a native `linux_x64` depot, Steam Deck uses the `LinuxXdgDataHome` override. If you ship only a `windows_x64` depot and players run it under Proton on Steam Deck, Steam automatically maps `WinAppDataRoaming` inside the game's Proton prefix (`compatdata//pfx/drive_c/users/steamuser/AppData/Roaming`). ## Steamworks features ### Rich presence localization [`pkg/online/presence`](http://nsgo.games/docs/presence/#steam-rich-presence) writes `status`, `level`, `mode`, `steam_player_group`, `steam_player_group_size`, `connect`, and `steam_display` through `ISteamFriends::SetRichPresence`. Steam only shows localized friend-list strings when `steam_display` names a token uploaded to Steamworks under **Community → Rich Presence Localization**. Save a localization VDF matching the `DisplayToken` passed to `presence.NewSteam` (such as `"#Status_InLevel"`) and upload it in Steamworks: ```text // steam/rich_presence_loc.vdf "lang" { "english" { "tokens" { "#Status_InMenu" "In Menus" "#Status_InLevel" "%mode%: %level%" } } "schinese" { "tokens" { "#Status_InMenu" "在菜单中" "#Status_InLevel" "%mode%:%level%" } } } ``` `presence.NewSteam` automatically populates `%mode%` from `Activity.Mode` and `%level%` from `Activity.Level` (see [presence](http://nsgo.games/docs/presence/#activity)). ### Steam Workshop [`pkg/modding`](http://nsgo.games/docs/modding/#steam-workshop-workshop) binds `ISteamUGC` via `purego` (`modding.NewSteamWorkshop` and `modding.NewWorkshop`) to publish mods with deterministic `workshop.yaml` metadata and sync subscribed items into `modding.Manager`. - Enable Workshop in Steamworks under **Application → Workshop → General**, set the Workshop visibility state, and configure the allowed tags that your game passes in `workshop.yaml` / `PublishOptions.Tags`. - When bundling `libsteam_api.dylib` with `nsgo-natives.yaml` on macOS, NSGo places it in `.app/Contents/Frameworks/libsteam_api.dylib`. A shared [`steamworks.Client`](http://nsgo.games/docs/steamworks/) finds it there; pass the client in `modding.SteamWorkshopOptions.Client`, or, without one, pass that path in `modding.SteamWorkshopOptions.LibraryPath` (resolved from `os.Executable()`). ### Achievements, stats and leaderboards (planned) Today, [`pkg/online/achievements`](http://nsgo.games/docs/achievements/) and [`pkg/online/leaderboard`](http://nsgo.games/docs/leaderboard/) report to Apple Game Center and Google Play Games Services through NSGo's `gameservices` package. Built-in Steam `ISteamUserStats` reporting for achievements, stats and Steam leaderboards is **not implemented yet** and is tracked in [#1764](https://github.com/nsgo-dev/game/issues/1764) (building on [#1763](https://github.com/nsgo-dev/game/issues/1763)). What works on Steam today: - `achievements.Tracker` tracks and persists local unlocks and step progress in `core.Storage` on desktop platforms so your in-game achievement UI works immediately. - Games that want cross-platform leaderboards today can deploy [`pkg/online/leaderboard/selfhost`](http://nsgo.games/docs/leaderboard-selfhost/). ## Steam Deck checklist Use Valve's four **Steam Deck Verified** categories when testing your `linux_x64` depot (or `windows_x64` under Proton) on Steam Deck before submitting for review. Built-in Steam Deck glyphs, automatic Steam on-screen keyboard invocation, a `1280×800` fullscreen default on Deck, and Steam Input action sets from `game.yaml` are planned in [#1765](https://github.com/nsgo-dev/game/issues/1765); the checklist below notes what you can satisfy today and what waits on that issue. ### Input - [ ] Every menu, pause screen, dialog, and gameplay action is playable end-to-end with a gamepad alone using [`input.Actions`](http://nsgo.games/docs/input/#game-controllers) (`GamepadButton`, `BindGamepadAxis`, `WatchGamepads`) and spatial focus navigation in [`gameui`](http://nsgo.games/docs/gameui/). - [ ] Gameplay pauses cleanly or alerts the player if the active controller disconnects (a built-in disconnect dialog is tracked in [#1568](https://github.com/nsgo-dev/game/issues/1568)). - [ ] Controller prompts match gamepad buttons rather than keyboard/mouse icons when playing on a controller (native Deck glyph detection and `game.yaml` Steam Input action sets are planned in [#1765](https://github.com/nsgo-dev/game/issues/1765)). - [ ] No mandatory text entry blocks normal play without a controller-friendly fallback (automatic Steam on-screen keyboard summoning via `ShowFloatingGamepadTextInput` is planned in [#1765](https://github.com/nsgo-dev/game/issues/1765)). ### Display - [ ] The game renders cleanly at `1280×800` (16:10 native Steam Deck) and `1280×720` (16:9) without clipped HUD elements, using [`screen.Viewport`](http://nsgo.games/docs/screen/) (`ModeFit` or `ModeExpand`) and [`screen.Video`](http://nsgo.games/docs/screen/#video-settings) (`Fullscreen: true`). Automatic `1280×800` fullscreen detection on Deck is tracked in [#1765](https://github.com/nsgo-dev/game/issues/1765). - [ ] All UI text, prompts, and subtitles remain legible on a 7-inch 1280×800 screen (avoid tiny sub-9px text). - [ ] Frame rate is steady and battery-friendly: wire `screen.Video`'s `FrameCap` (player-configurable or capped at 60/90 fps) and `AutoDropLowPower`. ### Seamlessness - [ ] Clicking **Play** launches directly into the game with no external launcher, setup wizard, or mouse-only warning dialogs. - [ ] Single-player play works offline without requiring a browser login or persistent network connection. - [ ] Steam Cloud syncs save slots between desktop PC and Steam Deck without overwriting per-device video or audio settings (use `DirCloud` in `cx.DataDir()/cloud` and keep settings in `cx.Storage()`). ### System support - [ ] Ship the `linux_x64` depot built with `-channel steam` under **Steam Linux Runtime 3.0 (sniper)** with `steam-launch.sh` and `nsgo-gtk/` intact, or verify your `windows_x64` depot under Proton. - [ ] Every asset path in `resources/` matches exact filename casing (Linux filesystems are case-sensitive even if your macOS or Windows machine is not); run `go tool game check` before releasing. ## Store review and release 1. **Content survey**: complete the [Steamworks Content Survey](https://partner.steamgames.com/doc/gettingstarted/contentsurvey) for age ratings and mature content disclosures. Track it in `nsgo.yaml`: ```yaml compliance: steam: content_survey: false # change to true after submitting in Steamworks ``` While set to `false`, `go tool game release -channel steam` (and `nsgo build -channel steam`) prints a reminder during the build. 2. **Store page review and "Coming Soon"**: fill out store copy, capsule art, screenshots, trailer, system requirements, and controller support tags, then submit the store page for Valve's review (typically 3–5 business days). Valve requires your store page to be publicly visible as **Coming Soon** for **at least two weeks** before you can release the game. 3. **Build review**: upload your release candidate depots via SteamPipe, configure depots, launch options, Linux runtime, and Steam Cloud paths, then submit the build for Valve's review (typically 3–5 business days; provide test credentials in the review notes if your game uses online accounts). 4. **Final pre-launch check**: - Confirm no `steam_appid.txt` is in any depot. - Confirm `THIRD_PARTY_NOTICES.txt`, `CREDITS.md` (if shipped in `resources/`), and `nsgo-gtk/licenses/` (Linux x64) are present. - Install the `staging` branch cleanly from the Steam client on each supported OS and verify launch, saves, Cloud sync, and Rich Presence / Workshop. - Set the approved BuildID live on `default` before clicking **Release App** in Steamworks. --- Source: http://nsgo.games/docs/shipping-china/ # Releasing in Mainland China Prepare a game built with NSGo Game for players in mainland China: plan regulatory registrations in order, implement first-launch privacy consent and required disclosures, handle Android devices without Google Play Services, and track HarmonyOS and mini program preview status. > This page summarizes engineering checkpoints, store mechanics, and links to official portals. It is not legal advice; rules and store review checklists change frequently, so confirm current requirements with the official portals below, your publisher, or qualified counsel before submitting. ## Order of steps and lead times Publishing in mainland China is gated by regulatory lead times rather than build time. The National Press and Publication Administration (NPPA) approval queue usually sets the release date, while software copyright and app filing must line up before store submission. | Step | Purpose | Asked for by | Typical lead time | | --- | --- | --- | --- | | 1. Legal entity & ICP qualifications | Register a mainland China corporate entity (business license); commercial online game operation also involves an ICP license (value-added telecom permit) or a licensed operator/publisher. | Filing providers, publishers, store accounts | 2–8 weeks | | 2. Software copyright registration (软著) | Register the game's software copyright with the Copyright Protection Center of China (CPCC). | Major Android OEM stores, TapTap, NPPA approval | 1–2 months | | 3. App filing (APP 备案) | File the mobile app with the Ministry of Industry and Information Technology (MIIT) through your mainland hosting/cloud provider (or mini-program host platform), binding your bundle ID and signing certificate fingerprint. | Apple App Store (mainland China), Huawei AppGallery, Android OEM stores, TapTap, HarmonyOS, mini programs | 1–3 weeks | | 4. Publishing approval & ISBN (版号) | Obtain NPPA publishing approval and an ISBN through a licensed publishing unit before paid downloads, in-app purchases, or commercial/monetized operation (separate domestic and imported queues). | Apple App Store (monetized games), Huawei AppGallery, Android OEM stores, TapTap, monetized mini-games | Several months to 1+ year | | 5. Store accounts & channel builds | Verify developer accounts, complete privacy/SDK disclosures, and upload store-specific builds. | Each store separately | 1–2 weeks per store | Lock your reverse-DNS bundle identifier (`id` in `game.yaml` and `nsgo.yaml`) and your Android / HarmonyOS release signing keystore before starting APP filing: the filing records both the package ID and the signing certificate's public-key / MD5 fingerprint, and stores verify that uploaded packages match the filed record. ## Required in-game screens and timing Store reviewers check both static packages and runtime network traffic from the moment the app starts. ### First-launch privacy consent dialog Mainland China app stores reject builds that collect personal information, read device identifiers, transmit telemetry, or initialize third-party SDKs before the player explicitly accepts the privacy policy on first launch. 1. Show a privacy consent dialog before entering gameplay, opening analytics/crash uploads, or initializing any third-party SDK. 2. Include a clear summary of data collection and permissions, a clickable link to the full privacy policy, and explicit **Agree** and **Disagree** buttons. Choosing **Disagree** must exit cleanly or remain in a non-collecting offline/browse mode without reading device identifiers or sending telemetry. 3. Persist the player's choice in `core.Storage` so subsequent launches skip the prompt (while keeping a way in settings to view the policy or withdraw consent). 4. Keep `android.permissions` in `nsgo.yaml` minimal—declare only what the game uses, and avoid unnecessary device-identifier permissions—and maintain the third-party SDK disclosure table (SDK name, provider, purpose, collected fields, privacy policy URL) requested during store submission. `liveops.Analytics` already enforces opt-in consent: it starts in `liveops.ConsentUnknown` and drops every `Track` call (zero events sent or buffered for retroactive replay) until `SetConsent(liveops.ConsentGranted)` is called (see [Live operations](http://nsgo.games/docs/liveops/#analytics)). Gate `liveops.CrashReporter` uploads and any network/SDK initialization behind the same persisted consent flag: ```go store := cx.Storage() analytics := liveops.NewAnalytics(store, "privacy.analytics", myAnalyticsProvider) analytics.SetClock(cx.Now) // Before the player taps Agree, analytics.Track drops events without buffering. // Gate crash report uploads and any third-party SDK init on the same consent state: reporter := liveops.NewCrashReporter(liveops.CrashOptions{ Reporter: func(r liveops.CrashReport) { if analytics.Consent() == liveops.ConsentGranted { uploadCrashReport(r) } }, Now: cx.Now, }) // Called from the first-launch privacy dialog's Agree button: onAgreePrivacy := func() { _ = analytics.SetConsent(liveops.ConsentGranted) initPostConsentServices() } // Called from the Disagree button: onDisagreePrivacy := func() { _ = analytics.SetConsent(liveops.ConsentDenied) // Exit cleanly or stay in offline mode with zero data collection. } ``` ### Health advisory, age rating, and publishing disclosures - **Health game advisory (健康游戏忠告)**: display the standard NPPA advisory text on the splash/login screen (*抵制不良游戏,拒绝盗版游戏。注意自我保护,谨防受骗上当。适度游戏益脑,沉迷游戏伤身。合理安排时间,享受健康生活。*). - **Age-appropriateness notice (适龄提示)**: display the CADPA age badge (such as 8+, 12+, or 16+) on the start screen and store listing pages. - **Publishing & filing information**: display your NPPA approval number (文号), ISBN, publisher (出版单位), copyright holder (著作权人), and APP/ICP filing number (备案号) on the start/login/about screen and enter the matching fields in every store console. ### Real-name verification and minors anti-addiction Commercial online games published in mainland China must verify every player against the NPPA real-name verification system (网络游戏防沉迷实名认证系统), enforce minor play-time windows (under 18: 20:00–21:00 Beijing time on Fridays, Saturdays, Sundays, and statutory holidays), enforce age-tiered spending caps (under 8: no payments; 8–15: max 50 CNY per payment and 200 CNY per month; 16–17: max 100 CNY per payment and 400 CNY per month), and report login/logout behavior from the server rather than trusting the client clock. > **Current status (partial)**: `pkg/online/antiaddiction` provides the server-side minor play-window and spending-cap checks (see [Reusable policy checks](http://nsgo.games/docs/shipping-china/#reusable-policy-checks)). NSGo Game does not yet ship built-in NPPA real-name verification, login/logout reporting, `Purchases` pre-check hooks, or a template advisory splash screen; they are tracked in [#1649](https://github.com/nsgo-dev/game/issues/1649). Until they land, implement verification and reporting on your server or integrate your publisher's / channel's compliance SDK, and call the checks from it. ## Online packages without Google Play Services Android devices sold in mainland China ship without Google Play Services (GMS), Google Play Games Services, Google Play Billing, or Google Play Store, and Firebase Cloud Messaging (FCM) is unreachable. The table below lists every `pkg/online` package in NSGo Game and how it behaves on Google-free Android devices. | Package | Without Google services | Behavior on Google-free Android & fallback | | --- | --- | --- | | `pkg/online/accounts` | Works | Self-hosted HTTPS account service (`cmd/accountsd`, plus `accounts/authtoken`, `sqlitestore`, `pgstore`, `sqlstore`, `storetest`). Works with guest accounts, email/password, or custom `IdentityVerifier` backends (WeChat, Huawei, TapTap, Apple, mini programs) instead of Play Games. NPPA real-name extensions are planned in [#1649](https://github.com/nsgo-dev/game/issues/1649). | | `pkg/online/achievements` | Partial | Local `Tracker` and `Persist` (`core.Storage`) work everywhere without Google services. `ServiceFor(core.OSAndroid)` selects `PlayGames`, so `SignIn` fails with `gameservices.ErrUnsupported` on Google-free Android (and on NSGo `v0.3.4` Android overall; see [Platform support](http://nsgo.games/docs/platforms/)). Render your own in-game UI or attach a custom `Reporter` through `Tracker.Connect`. | | `pkg/online/admin` | Works | Pure server-side operator sign-in, roles and audited admin routes for the self-hosted daemons (`pkg/online/admin`); no client or Google dependency. | | `pkg/online/antiaddiction` | Works | Pure server-side mainland China minor play windows and spending caps by age band (`pkg/online/antiaddiction`), on the server's clock and holiday calendar; no client or Google dependency. Real-name verification and NPPA reporting stay in the publisher's or channel's integration. | | `pkg/online/audit` | Works | Pure server-side append-only JSON Lines audit log (`pkg/online/audit`); no client or Google dependency. | | `pkg/online/backend` | Works | Pure server-side HTTP mux for the self-hosted services and game RPCs (`pkg/online/backend`); no client or Google dependency. | | `pkg/online/cloudsave` | Works | Self-hosted HTTPS cloud save service (`cmd/cloudsaved`, plus `sqlitestore`, `pgstore`, `sqlstore`, `storetest`), authenticated by `accounts/authtoken`. Recommended fallback for Android without Google Play Services and HarmonyOS. | | `pkg/online/economy` | Works | Pure server-side idempotent wallets (`pkg/online/economy`); no client or Google dependency. | | `pkg/online/eos` | Unavailable | Epic Online Services boundary for the Epic Games Store on desktop PCs; it ships no native adapter yet, so a game supplies its own `Driver`, and `New` returns `ErrUnavailable` without one. Not used on Android; no Google dependency. | | `pkg/online/gameserver` | Works | Server-side headless fixed-step match runner, rooms, matchmaking, health, and metrics; no Google dependency. | | `pkg/online/lan` | Works | Pure-Go LAN game advertisement metadata (`pkg/online/lan`) for a discovery protocol the game supplies; no Google dependency. | | `pkg/online/leaderboard` | Unavailable | `ProviderFor(core.OSAndroid)` selects `ProviderPlayGames`; without Google Play Services `Available()` is `false` and `SignIn`/`Submit`/`Show`/`Scores` return `ErrUnsupported` (Game Center still works on iOS/macOS). Use [`pkg/online/leaderboard/selfhost`](http://nsgo.games/docs/leaderboard-selfhost/) instead. | | `pkg/online/leaderboard/selfhost` | Works | Self-hosted cross-platform leaderboards over HTTPS (`cmd/leaderboardd`), authenticated by `accounts/authtoken`. Recommended fallback on Google-free Android, HarmonyOS, Windows, Linux, and the web. | | `pkg/online/liveops` | Partial | `CrashReporter` (and `liveops/crashreport`), consent-gated `Analytics`, `CloudClient` (backed by `cloudsave`), `DirCloud`, and `Reminders` (OS-native local notifications) all work without Google services. `PlatformCloud` picks `CloudProviderPlayGames` on Android and fails with `ErrCloudUnavailable`—use `CloudClient` instead. `Purchases` is unavailable on Android (`core.PurchasesUnavailable`; [nsgo#1369](https://github.com/nsgo-dev/nsgo/issues/1369), [nsgo#1370](https://github.com/nsgo-dev/nsgo/issues/1370); Apple StoreKit works on iOS mainland China). `ReviewPrompt` is a safe no-op where `CanRequestReview()` is `false`. Remote push is unavailable everywhere ([nsgo#59](https://github.com/nsgo-dev/nsgo/issues/59), [nsgo#1323](https://github.com/nsgo-dev/nsgo/issues/1323)). | | `pkg/online/netplay` | Works | Pure-Go UDP, WebSocket, WebTransport, and loopback transports (plus `netplay/wire` and `netplay/roomstate`); no Google dependency. Host mainland servers on ICP-filed domains and mainland infrastructure for reliable latency. | | `pkg/online/portmap` | Partial | Gateway port-mapping contract (`pkg/online/portmap`) with no Google dependency; `Open` returns `ErrUnsupported` until the game installs a UPnP, NAT-PMP or PCP provider for the target. | | `pkg/online/presence` | Unavailable | Desktop-only rich presence (Steam `ISteamFriends` and Discord local IPC); returns `ErrUnavailable` on Android, iOS, and the web. No Google dependency (Steam works on mainland desktop PCs; Discord is generally unreachable). | | `pkg/online/realtime` | Works | Pure server-side notification store with live delivery to online subscribers (`pkg/online/realtime`); no client or Google dependency. Deliver to devices over the game's own socket, not Firebase Cloud Messaging. | | `pkg/online/records` | Works | Pure server-side versioned JSON records (`pkg/online/records`); no client or Google dependency. | | `pkg/online/servicehealth` | Works | Pure server-side deployment endpoints (`/healthz`, `/readyz`, Prometheus `/metrics`) for the self-hosted daemons and the game server (`pkg/online/servicehealth`); no client or Google dependency. | | `pkg/online/social` | Works | Pure server-side friends, blocks, groups, parties and chat (`pkg/online/social`); no client or Google dependency. | | `pkg/online/steam` | Unavailable | Steamworks boundary for achievements, stats, leaderboards, and rich presence; it needs a game-supplied desktop Steamworks `Driver` and returns `ErrUnavailable` without one. No Google dependency (Steam works on mainland desktop PCs). | | `pkg/online/steamworks` | Unavailable | Desktop-only Steamworks client (purego); returns `ErrUnavailable` on Android, iOS, and the web. No Google dependency (Steam works on mainland desktop PCs). | | `pkg/online/storeverify/wechatpay` | Works | Pure server-side signing of WeChat mini game virtual payment orders and once-per-`OutTradeNo` handling of goods delivery pushes ([liveops](http://nsgo.games/docs/liveops/)); no client or Google dependency. | | `pkg/online/wsclient` | Works | Pure-Go RFC 6455 WebSocket client on native targets and browser `js/wasm`; no Google dependency (unavailable in mini programs until [nsgo#1505](https://github.com/nsgo-dev/nsgo/issues/1505)). | ### Self-hosted fallback stack For cross-platform saves, accounts, and leaderboards that work identically across iOS, Google-free Android, desktop, and web: 1. Deploy [`pkg/online/accounts`](http://nsgo.games/docs/accounts/) (`cmd/accountsd` or a custom server with your chosen `IdentityVerifier` providers) to issue short-lived Ed25519 tokens. 2. Deploy [`pkg/online/cloudsave`](http://nsgo.games/docs/cloudsave/) (`cmd/cloudsaved`) and connect clients with `liveops.CloudClient` + `liveops.CloudSyncer` (`SyncAsync`) instead of `liveops.PlatformCloud`. 3. Deploy [`pkg/online/leaderboard/selfhost`](http://nsgo.games/docs/leaderboard-selfhost/) (`cmd/leaderboardd`) instead of `pkg/online/leaderboard`. 4. Keep achievements locally in `achievements.Tracker` (with `Persist(cx.Storage(), ...)`), optionally syncing via a custom `achievements.Reporter`. 5. Serve every endpoint over HTTPS on an ICP-filed mainland China domain (required for reliable connectivity and store compliance). ## Store-by-store notes ### Apple App Store (mainland China) - Enter your MIIT APP filing number in App Store Connect before enabling mainland China availability. - Paid games and games with in-app purchases require an NPPA publishing approval number in App Store Connect. - Apple's native services work without Google dependencies: StoreKit in-app purchases (`liveops.Purchases` with `apple.purchases: true`), Game Center (`achievements`, `leaderboard`), iCloud (`liveops.PlatformCloud`), and StoreKit review prompts (`liveops.ReviewPrompt`). ### Android OEM stores and TapTap Huawei AppGallery (Android), Xiaomi GetApps, OPPO, vivo, Honor, and TapTap each maintain a separate developer console, review queue, and privacy compliance scanner. - **Signed release `.apk`, not `.aab`**: mainland Android stores distribute signed 64-bit (`arm64-v8a`) `.apk` files rather than Google Play App Bundles. Build with `-channel direct` (never `-channel store`, which outputs `.aab`) and your release keystore: ```sh NSGO_KEYSTORE_PASSWORD="$STORE_PW" NSGO_KEY_PASSWORD="$KEY_PW" \ go tool game release -channel direct -target android ``` Or invoke `nsgo build` directly with `GOFLAGS=-tags=release`: ```sh NSGO_KEYSTORE_PASSWORD="$STORE_PW" NSGO_KEY_PASSWORD="$KEY_PW" \ GOFLAGS=-tags=release go tool nsgo build -channel direct -target android_arm64 \ -keystore certs/upload.p12 -key-alias upload ``` - **Channel SDKs and payments**: OEM channel distribution (联运) typically requires integrating each store's channel SDK (account login, channel billing, anti-addiction, update/exit dialogs) and shipping separate per-channel packages. NSGo does not bundle proprietary OEM SDKs, and Android billing is not yet implemented in NSGo ([nsgo#1369](https://github.com/nsgo-dev/nsgo/issues/1369), [nsgo#1370](https://github.com/nsgo-dev/nsgo/issues/1370)). TapTap is commonly used for official-server (官服) APK distribution and testing. - **Test on a Google-free device**: verify before submission that signing in, saving, viewing leaderboards/achievements, and checking purchases degrade cleanly without hanging or crashing when Google Play Services is absent. - **Target SDK and permissions**: keep `android.target_sdk` aligned with each store's current requirement and declare only minimal `android.permissions` in `nsgo.yaml`. ### HarmonyOS (AppGallery on HarmonyOS NEXT) HarmonyOS NEXT runs native HarmonyOS packages (`.hap` / `.app`) exclusively—Android APKs do not run on HarmonyOS NEXT. - **Building and signing (preview)**: NSGo includes a preview `harmonyos` target (WebAssembly running in ArkWeb with an ArkTS/ArkUI host) that writes `--harmonyos.hap`: ```sh NSGO_HARMONY_KEYSTORE_PASSWORD="$STORE_PW" NSGO_HARMONY_KEY_PASSWORD="$KEY_PW" \ GOFLAGS=-tags=release go tool nsgo build -target harmonyos ``` Signed release HAPs require the OpenHarmony SDK (`OHOS_BASE_SDK_HOME`, API 26), `hvigorw`, Java (`hap-sign-tool.jar`), and AppGallery Connect signing materials in `nsgo.yaml` (see [NSGo's Building guide — HarmonyOS](https://nsgo.dev/docs/building/#harmonyos)): ```yaml harmonyos: signing: keystore: signing/app.p12 key_alias: app certificate: signing/app.cer profile: signing/app.p7b ``` Run `go tool nsgo doctor` in your project directory to verify the signing config and profile bundle name. - **Preview limitations in NSGo `v0.3.4`**: `harmonyos` is an experimental preview target and is not yet ready for production game releases. As documented in [Platform support](http://nsgo.games/docs/platforms/), it currently lacks 3D GPU views, audio (`CanPlayAudio()` is `false`), gamepads, haptics, motion sensors, persistent `core.Storage` (currently in-memory only), native local notifications, UDP, game services, and HarmonyOS IAP Kit ([nsgo#1521](https://github.com/nsgo-dev/nsgo/issues/1521), [nsgo#1320](https://github.com/nsgo-dev/nsgo/issues/1320), [nsgo#1370](https://github.com/nsgo-dev/nsgo/issues/1370)). - **AppGallery submission**: HarmonyOS NEXT apps require HarmonyOS APP filing (bound to the HarmonyOS bundle name and signing public key), software copyright, privacy disclosure, and NPPA publishing approval for monetized games. ### Mini programs (WeChat, QQ, Douyin, Alipay) NSGo provides experimental targets `miniprogram_wechat`, `miniprogram_qq`, `miniprogram_alipay`, and `miniprogram_douyin`, writing a project for each platform's DevTools under `dist/releases/miniprogram/` with AppIDs configured under `miniprogram.appid` in `nsgo.yaml`: ```sh GOFLAGS=-tags=release go tool nsgo build -target miniprogram_wechat ``` - **Filing and review**: mini programs complete mini-program filing (小程序备案) through their host platform console. Commercial/monetized mini-games also require software copyright and NPPA approval (check each host platform's current policies for non-IAP or ad-supported mini-games). - **Experimental limitations in NSGo `v0.3.4`**: as documented in [Platform support](http://nsgo.games/docs/platforms/), mini programs enforce a 2 MB compressed package limit and currently lack 3D GPU views, audio, shaders (`nsgo_noshader`), gamepads, and standard browser `fetch`/`WebSocket` globals ([nsgo#1505](https://github.com/nsgo-dev/nsgo/issues/1505)). Local saves persist via `save.StorageBackend(cx.Storage(), ...)`, and NSGo exposes `core.SignInMiniProgram` for host sign-in. ## Official resources - [National Press and Publication Administration (NPPA / 国家新闻出版署)](https://www.nppa.gov.cn/) — game publishing approval (版号) notices and lists - [NPPA Online Game Anti-Addiction Real-Name System (网络游戏防沉迷实名认证系统)](https://wlc.nppa.gov.cn/) — real-name verification and play-behavior reporting portal - [MIIT ICP / APP Filing Portal (工业和信息化部政务服务平台)](https://beian.miit.gov.cn/) — ICP and mobile APP filing queries and rules - [Copyright Protection Center of China (中国版权保护中心)](https://www.ccopyright.com.cn/) — software copyright registration (软著) - [China Audio-video and Digital Publishing Association (中国音像与数字出版协会 / CADPA)](https://www.cadpa.org.cn/) — age-appropriateness notice standards (适龄提示) - [Apple App Store Connect China Support](https://developer.apple.com/cn/support/app-store-connect/) — mainland China APP filing and ISBN submission rules - [Huawei Developer & AppGallery Connect](https://developer.huawei.com/consumer/cn/doc/) — Android AppGallery and HarmonyOS NEXT signing & release guides - Android OEM & distribution consoles: [Xiaomi Developer](https://dev.mi.com/), [OPPO Open Platform](https://open.oppomobile.com/), [vivo Open Platform](https://dev.vivo.com.cn/), [Honor Developer](https://developer.honor.com/), [TapTap Developer](https://developer.taptap.cn/) - Mini program developer docs: [WeChat](https://developers.weixin.qq.com/miniprogram/dev/framework/), [QQ](https://q.qq.com/wiki/), [Douyin](https://developer.open-douyin.com/), [Alipay](https://opendocs.alipay.com/mini) - [NSGo Building guide](https://nsgo.dev/docs/building/) — HarmonyOS, mini programs, and Android keystore configuration details ### Reusable policy checks `pkg/online/antiaddiction` provides provider-neutral checks for a verified age: `Window` reports the 20:00–21:00 Beijing-time minor window on Friday, Saturday, Sunday and supplied public holidays, with the next time the answer changes, and `SpendLimit` and `SpendAllowed` apply the statutory per-payment and monthly CNY caps. Pass server-authoritative time and a holiday calendar to `Window`. Keep NPPA identity verification, login/logout reporting, health-advisory presentation and consent in the publisher or channel integration. --- Source: http://nsgo.games/docs/cli/ # Command Line `game` is the game layer's command-line tool: one command whose subcommands pack sprite atlases, convert audio, generate asset manifests, encode textures, open the scene editor, build release packages, show its build version, play input recordings headless, check benchmarks against a stored baseline, check a built package against its size budget, create projects, check, format and apply a project's `game.yaml`, run the game with asset hot reload, check a game's scenes, maps and atlases, build all of a game's assets from `game.yaml`, rebuilding only what changed, write new components, systems, scenes and prefabs into a project, move files while keeping the references to them working, keep the project index of stable file IDs, render pixelfx effects to sprite sheets and write shell completion scripts. They share how they are called: flags before arguments, `-in` for what a command reads and `-out` for what it writes, and the same help. ## Install Create a new project from outside any module with `go run`—nothing to install: ```sh go run github.com/nsgo-dev/game/cmd/game@latest new mygame ``` Inside a project, add the command as a Go module tool (projects created with [`game new`](http://nsgo.games/docs/cli/#new) already have it) and run every subcommand with `go tool game`: ```sh go get -tool github.com/nsgo-dev/game/cmd/game go tool game help ``` The `tool` line in `go.mod` pins the command to the module's version of the game layer, so everyone working on the game runs the same one. Every template's `go.mod` and the game layer itself also pin `github.com/nsgo-dev/nsgo` v0.4.0, whose recorded draw operations carry images and atlas sprites by index into the drawing's own buffers. Running the command as `nsgo game` through NSGo's generic extension mechanism (and `cmd/nsgo-game` outside a project) requires NSGo v0.4.0 or later; NSGo releases up to v0.3.4 ship a built-in `nsgo game` command hard-coded to the legacy `github.com/nsgo-dev/game/packages/game` module path. Inside a project whose tools declare the game layer's `cmd/game`, `nsgo game` runs the module's own tool; outside one, use `go run github.com/nsgo-dev/game/cmd/game@latest`. ## Commands | Command | What it does | | --- | --- | | `pack` | Packs a folder of PNG images into sprite atlas pages and TexturePacker JSON-hash metadata for `sprite.LoadAtlas` | | `audio` | Normalizes, resamples and converts a WAV file to WAV, AAC or MP3 | | `manifest` | Generates a typed Go asset manifest from a directory of assets, so a missing asset fails the build | | `tex` | Encodes a PNG or JPEG texture into a KTX2 container as BC1, BC3, BC7, ETC2, ETC2 RGBA, ASTC 4x4, UASTC or RGBA8, with optional mipmaps | | `editor` | Opens the scene editor on a project or a YAML scene, or on the start screen when none is named | | `mcp` | Serves the editor's MCP tools to an agent on standard input and output, forwarding each call to the editor that has the project open | | `release` | Builds the game's release packages for macOS, Windows, Linux, web, iOS and Android, or for `game.yaml`'s export presets, in one run of `nsgo build`, with a credits file of its assets' licenses | | `capture` | Checks the store screenshots and covers a capture plan describes: each scene and recording exists, and each image is a PNG of its target size | | `replay` | Checks the input recordings under the directories and plays them headless through their replay tests, failing on a mismatch | | `bench` | Runs the benchmarks headless and fails when one regresses past its stored baseline, or updates the baseline | | `size` | Measures a WebAssembly binary or an Android AAB or APK or iOS IPA package and fails when it exceeds its size budget | | `new` | Creates a game project in a directory from a template, with its `go.mod` requiring the game layer and the `game` and `nsgo` tools | | `project` | Checks a project's `game.yaml` and its autoloads, rewrites it in canonical form, writes the fields it owns into `nsgo.yaml`, or prints its export presets' build targets | | `dev` | Runs the game with `nsgo dev`, reloading its assets in the running game when they are saved | | `check` | Checks the scenes, Tiled and LDtk maps and sprite atlases under a directory, and the files they refer to, reporting each problem with its file and line | | `doctor` | Checks a project module, pinned tools, `game.yaml`/`nsgo.yaml`, release targets and platform readiness before building or releasing | | `assets` | Packs atlases, encodes textures, converts audio, bakes fonts, packs models and generates the manifest from `game.yaml`, rebuilding only what changed | | `generate` | Writes a new component, system, scene or prefab into a game project: its Go code and a test, the scene file of a scene or prefab, and its registration | | `mv` | Moves or renames a file or directory of a project and rewrites every reference to it, keeping the project index up to date | | `index` | Gives every scene and resource file a uid, points references at files moved without the tools, and writes the project index | | `library` | Finds asset, editor plugin and template packs in a library and installs them into a project, updates or removes them, or prints a pack's digest | | `credits` | Writes the credits file `release` ships: every asset's author and license, from the import settings sidecar beside it, failing when an asset has none | | `pixelfx` | Renders a pixelfx effect, or the effect acted out, to a PNG sprite sheet and Aseprite JSON for `sprite.LoadAtlas` | | `navmesh` | Bakes a scene's glTF level geometry into a navigation mesh for each agent type `game.yaml` declares, written to the file the scene's `navMesh` names | | `merge` | Merges scene YAML files object by object for Git, or sets up and checks the `nsgo-scene` Git merge driver in a project | | `schema` | Writes the project's scene JSON Schema, including its registered components and plugins, or the built-in scene schema when the project has no editor command of its own | | `admin` | Adds an operator to a service's operators file, sets its password, enrolls it for TOTP sign-in, or revokes its bearer tokens | | `version` | Prints the game and NSGo module versions, Go toolchain, operating system and architecture; `-json` writes machine-readable JSON and `-version` is an alias | | `completion` | Writes a completion script for zsh, bash or fish | | `help` | Lists the commands, or shows one command's flags | `go tool game help` lists the commands, and `go tool game help ` or `go tool game -h` shows a command's usage line, what it does and its flags. [Command Reference](http://nsgo.games/docs/cli-reference/) lists every command's flags and their defaults on one page, generated from the commands' definitions. ### doctor Run `go tool game doctor` from a project root, or pass its directory. It checks that `go.mod` declares the pinned `game` and `nsgo` tools and that both modules resolve, validates `game.yaml`, checks its agreement with `nsgo.yaml`, flags default `dev.nsgo.*` IDs, and reports release targets that need another host. With Apple presets it also runs the same release-readiness checks used by the editor. Human output is one `file: severity: message; fix: ...` finding per line. `-json` writes stable finding objects for agents and editor integrations. Errors exit 1, warnings and notes exit 0. ### Project CLI extensions The CLI also discovers extensions named `game-`. A tool declared in the current module's `go.mod` takes precedence and runs as `go tool `; when none is declared, an executable named `game-` on `PATH` runs (on Windows, `game-` with an extension `PATHEXT` lists, such as `game-.exe` or `game-.cmd`). Built-in commands always take precedence. `game help` and shell completion list discovered extensions, and `game help ` runs the extension with `-h`. The child receives `GAME_EXTENSION=1`, `GAME_VERSION` when build information is available and `GAME_PROJECT` when the command runs inside a project. Plugin installation wiring and command declarations in `plugin.yaml` are separate follow-ups. A command exits with 0 when it succeeds or shows help, 1 when it fails (a file it cannot read, an encoder it cannot find, a manifest or asset that is out of date, a build that fails, a replay whose end state does not match, a benchmark that regressed, a package over its size budget, a broken reference `check` found, a file `generate` would overwrite, an asset without a credit) and 2 when it is called wrongly (an unknown flag, a missing required flag, flags that conflict, an argument it does not take), in which case it also prints its usage. Its errors start with its name, such as `game pack: -in directory is required`, except an unknown or malformed flag, which Go's flag package reports in its own words, such as `flag provided but not defined: -nope`. An unknown command also exits with 2, and points to `game help` instead of printing a usage. ### version ```sh go tool game version go tool game version -json go tool game -version ``` Prints the game layer's module version, the NSGo module version when it is present in the build, and the Go toolchain with the target operating system and architecture. A development build prints `(devel)`, its VCS revision when available, and `+dirty` when the source tree was modified. Use `-json` for bug reports and tools that need to record the exact fields. ### pack ```sh go tool game pack -in art/ui -out assets -name ui -padding 2 ``` Writes `ui.png` and `ui.json` to `-out` (`ui-0.png`, `ui-0.json`, `ui-1.png` and so on when the frames need more than one page) and prints each path. `-padding` and `-extrude` set the transparent gap and the repeated edge pixels around each frame, `-max-width` and `-max-height` bound a page, `-scale` is written to `meta.scale`, and transparent borders are trimmed, each frame keeping its offset in its untrimmed size, unless `-trim=false`. When an [import settings sidecar](http://nsgo.games/docs/cli/#import-settings-beside-each-asset) sits beside a PNG in `-in`, its `image.slice` and `image.pivot` settings apply as they do in `assets`, slicing sprite sheets into grid frames and writing each frame's normalized TexturePacker `pivot` into the atlas JSON for `sprite.LoadAtlas`. ### audio ```sh go tool game audio -in sfx/jump.wav -out assets/jump.wav -rate 22050 -channels 1 -peak-db -1 go tool game audio -in music/theme.wav -out assets/theme.m4a -format aac -rms-db -14 -bitrate 192 ``` Reads a WAV file, resamples it to `-rate`, mixes it to `-channels`, and normalizes either its peak (`-peak-db`) or its loudness (`-rms-db`, with soft clipping), not both. Passing both is a usage error. WAV output is written in Go; MP3 needs `ffmpeg` on `PATH`, and AAC uses `ffmpeg`, or `afconvert` on macOS when `ffmpeg` is missing; otherwise the command fails with an error naming the missing encoder. When an [import settings sidecar](http://nsgo.games/docs/cli/#import-settings-beside-each-asset) sits beside the input, such as `sfx/jump.wav.import.yaml`, its `audio` settings apply as they do in `assets`, loop points included, and a flag given on the command line wins over the sidecar's setting of the same name: `-peak-db` or `-rms-db` replaces the sidecar's level, whichever kind it is. A loop needs `wav` output, and a sidecar holding settings for another kind of asset is refused. ### manifest ```sh go tool game manifest -resources -out assets/manifest_gen.go -pkg assets go tool game manifest -in assets -out assets/manifest_gen.go -pkg assets -check ``` Writes a Go file declaring a typed reference for every asset under `-in`, skipping files and folders whose names start with a dot, Go files and import settings sidecars (`*.import.yaml`), or prints it when `-out` is empty. `-resources` scans `resources/` (unless `-in` is set explicitly) and emits `"asset:"` URI references for app resources instead of `//go:embed`, so assets load on demand on every target without growing the binary; it cannot be combined with `-embed` or `-embed-dir`. `-embed` emits `//go:embed` directives instead of `asset:` URIs, with `-embed-dir` prefixed to their patterns, escaping glob metacharacters (`[`, `*`, `?`) so names such as `hero[1].png` match only themselves. In `-embed` mode, every asset path and `-embed-dir` must follow Go's `//go:embed` file-name rules (ASCII letters, digits, spaces, Unicode letters and `!#$%&()+,-.=@[]^_{}~`, with no trailing dot, reserved VCS directory such as `.git`, or Windows device name such as `CON`); names containing `*`, `?`, quotes, colons or other disallowed characters fail during scanning instead of emitting unbuildable code. `-check` leaves `-out` alone and fails when it differs from what would be generated, for CI; a `go:generate` line running the first form keeps the file current. The generated file's header names the command that wrote it (`// Code generated by game manifest. DO NOT EDIT.`), so a manifest generated by the earlier `gamemanifest` command must be regenerated once before `-check` passes. ### tex ```sh go tool game tex -format bc1 -mipmaps -srgb -out assets/albedo.ktx2 art/albedo.png ``` Encodes the image named by the argument (or `-in`) into a KTX2 file at `-out` (`-o` for short), by default the input's path with a `.ktx2` extension. `-format` is `bc1`, `bc3`, `bc7`, `etc2`, `etc2-rgba`, `astc4x4`, `uastc` or `rgba8`, `-mipmaps` writes the whole chain down to 1x1, and `-srgb` marks the texture sRGB and filters its mipmaps in linear light. When an [import settings sidecar](http://nsgo.games/docs/cli/#import-settings-beside-each-asset) sits beside the input, such as `art/albedo.png.import.yaml`, its `image` settings apply as they do for a texture target of `assets`: `format`, `mipmaps` and `srgb`, under the flags given, which win, and `filter`, which is written into the KTX2 file as `game.filter`. `slice` and `pivot` are atlas settings and are not read, since a texture holds the whole image, and a sidecar holding settings for another kind of asset is refused. ### editor ```sh go tool game editor scenes/level1.yaml go tool game editor . ``` Opens the NSGo Scene Editor in a window on the scene file named, or on the start screen when none is (showing recent projects, a folder picker, project creation from `game new`'s templates, and Open Demo). A directory or a `game.yaml` opens the game's [project file](http://nsgo.games/docs/project/) and its main scene, and a scene file inside a project's directory opens with that project. A project's scenes draw the project's own sprite atlases, found by name as [`game check`](http://nsgo.games/docs/cli/#check) finds them, the asset browser lists those atlases, its scene files place as instances, and its materials, physics materials, the YAML tilesets of layered tilemaps and Tiled and LDtk sources load from it and fill the tile palette; its components are free-form, since only the game's Go code registers their types. A scene file outside any project reads the files it names from its own directory and draws the demo room's atlases. With a project open, the editor opens the project's other scenes from its file browser, makes new ones, saves them under other paths, and asks before quitting or opening another scene or project loses unsaved edits ([Scene files and unsaved changes](http://nsgo.games/docs/editor/#scene-tabs-scene-files-and-unsaved-changes-866-873)). `-library` adds a panel that installs packs from that [library](http://nsgo.games/docs/library/) into the open project. It has no [editor plugins](http://nsgo.games/docs/editor/) built in and knows none of a game's component types. A project with an editor command of its own, which [`game generate editor`](http://nsgo.games/docs/cli/#generate) writes, or a `cmd/editor` main package that imports `editorcmd`, as [Field Medic](https://github.com/nsgo-dev/game/tree/main/examples/fieldmedic)'s does, is opened by running that command with `go run` in the project's directory, passing it the same arguments, with the scene and clip paths made absolute, and `-library`; that command checks every component against the game's types and the built-in physics components and builds in its plugins. A `cmd/editor` that does not import `editorcmd` is not run; `game editor` says so and opens the project itself. The scene format is described in [Editor & Scene Format](http://nsgo.games/docs/editor/). The editor, and a game's own editor command built on `editorcmd`, serve the open project to agents on a local endpoint, which `mcp` reaches. ### mcp ```sh go tool game mcp install go tool game mcp prompt -host claude claude mcp add game-editor -- go tool game mcp ``` An MCP server on standard input and output, which an agent such as Claude Code or Codex starts in the project's directory, or in a directory inside it, or with `-project` naming it. It finds the editor that has the project open and forwards all the editor tools listed in [mcp](http://nsgo.games/docs/mcp/#editor-tools) and its change stream; while no editor has the project open, each call answers with how to open it. Running `go tool game mcp install` (optionally with `-project`) once in a project writes or updates the `nsgo-game-editor` entry and every MCP server enabled in this user's **Settings › Tools** in `.mcp.json` (for Claude Code) and `.codex/config.toml` (for Codex), and removes project entries named like servers disabled there. Enabled servers' commands and arguments are copied from per-user editor settings into these project files, so review them before committing. Unrelated servers and other Codex settings are preserved, existing file permissions stay unchanged, and identical files are not rewritten. [mcp](http://nsgo.games/docs/mcp/#editor-tools) describes the tools and setup flow. `go tool game mcp prompt` prints a setup prompt to paste into an agent, worded for `-host claude`, `codex` or `other` (the default): keep what is installed and every other MCP server, install only what is missing (the [plugin](http://nsgo.games/docs/agent-skill/#install) or `mcp install`), prove the connection with a read-only `selection_get` call instead of trusting a configuration file, check that `go tool game` resolves, then wait for the game brief. An unknown host is refused with exit code 2. ### release ```sh go tool game release go tool game release -channel store -release-notes notes/0.2.0.md go tool game release -target macos_arm64,web -output build -dry-run ``` Builds the game in the directory named, the current one by default, which holds its `nsgo.yaml`, for every platform in one run of `nsgo build`: macOS, Windows and Linux on both architectures, web, iOS and Android on arm64 unless told otherwise. Each target's package goes to `/--`, and the files a release uploads (disk images, installers, Debian and Arch packages, AppImages, the IPA, the APK and the site's zip, each with a `.sha256`) to `/releases`, as `nsgo build` lays them out. A target that fails stops the run and exits with 1. The game's module must have NSGo as a tool (`tool github.com/nsgo-dev/nsgo/cmd/nsgo` in `go.mod`, as the starter has), since the command runs `GOFLAGS=-tags=release go -C tool nsgo build`, so the build uses the module's own NSGo version and compiles out development-only packages (`pkg/tooling/gamedebug`, `pkg/tooling/hotreload`, `pkg/tooling/devstate`, and physics/AI debug drawing); `-dry-run` prints that command instead of running it. When desktop targets are built, `game release` verifies each produced desktop executable's Go build info and symbol table afterwards and fails if the `release` tag is missing or a development-only debug symbol was linked. The targets come from `-target`, else from the `export` presets of the `game.yaml` beside `nsgo.yaml`, in order, a preset without `targets` building its platform name, else the six platforms above, or only macOS, Windows and Linux when the channel (`-channel`, else `nsgo.yaml`'s `updates.channel`) is `steam`, whose depots `nsgo build` makes of desktop targets alone. `nsgo.yaml`'s `build.targets` is not used: it holds the portable cross-host list for a plain `nsgo build` (omitting macOS and iOS so a plain `nsgo build` succeeds on Linux and Windows), while the full release list belongs in `game.yaml`'s export presets. When targets come from presets or defaults, `game release` skips any target the current host cannot build—macOS off macOS, and iOS, tvOS and watchOS without macOS and Xcode—printing which targets it skipped and why, and builds the rest; an explicitly requested `-target` that the host cannot build fails before `nsgo build` runs. On a Mac with Xcode, an `ios` device preset without `sign.profile` in `nsgo.yaml` is still built and reported on standard error as unsigned rather than dropped silently. The output directory comes from `-output`, else from `game.yaml`'s `export.output`, else from `nsgo.yaml`'s `build.output`: ```yaml version: 1 export: output: dist presets: - platform: macos - platform: windows targets: [windows_x64] - platform: linux - platform: web - platform: ios - platform: android ``` The command reads `game.yaml`'s `version`, which must be the integer 1, its `export` section and, for the credits file, its `assets` section. It refuses top-level fields outside the project file's (`version`, `name`, `id`, `appVersion`, `window`, `display`, `input`, `audio`, `autoload`, `export`, `editor`, `assets` and `navigation`), so a misspelt `export` is not skipped, and in `export` it refuses unknown fields, an empty `presets` list, unknown platforms and targets, a target of another platform, duplicates and an output outside the project; the rest of the file is the project file's. `-channel` is `nsgo build`'s: `store` builds the packages stores take (a Mac App Store package, universal when both macOS architectures are built, a Windows MSIX, a Flatpak bundle and an Android App Bundle) in place of the disk images, installers and APKs handed out directly, and `-release-notes` and `-jobs` pass through too. Signing, notarizing and store uploads follow `nsgo.yaml` and `nsgo publish`. The four experimental platforms (`tvos`, `watchos`, `harmonyos`, and `miniprogram`, along with their sub-targets such as `tvos_simulator`, `watchos_simulator`, and the mini program hosts) remain accepted in `game.yaml` presets and `-target`, but are not vetted in CI and lack audio and GPU views in NSGo ([Platform support](http://nsgo.games/docs/platforms/#experimental-targets)). `game release` prints one warning to standard error per experimental platform it builds, naming what is missing and linking the platform support page and upstream NSGo issue. Pass `-strict` to turn experimental platform warnings into an error (exiting with 1 before running `nsgo build`) in CI. When `game.yaml` has an `assets` section, which the whole file must then pass [project file](http://nsgo.games/docs/project/) validation for, the release ships a credits file: after `nsgo build` succeeds, the command writes `CREDITS.md` into the output directory, beside the packages, listing the author, license and source of every asset that section reaches and each notice a license asks to be shipped, from the `credit` section of each asset's [import settings sidecar](http://nsgo.games/docs/cli/#import-settings-beside-each-asset), as [`game credits`](http://nsgo.games/docs/cli/#credits) writes it. The assets are the images each atlas packs, the input of each texture, audio, font and model target, the buffers and images each model names by relative path, which its GLB embeds, and every file the manifest lists in its folder, such as fonts, maps and models, leaving out the files the targets write, which are made from those inputs. An asset without a credit stops the release before anything is built, with the list of the sidecars to write; a file the manifest lists that a target wrote before its output changed counts as an asset until `game assets` removes it. `-dry-run` checks the credits too and names the file it would write. A game without an `assets` section gets no credits file, and the command notes it on standard error. Files the game loads from elsewhere, such as `autoload` resources or files it embeds outside the manifest's folder, are not listed, so credit those yourself. The credits file is written beside the packages, not into them, since `nsgo build` decides what a package holds: it is for the publisher to put on the store page or download page. To ship it inside every package as well, write it into NSGo's `resources` folder, which `nsgo build` copies into each package, before the release: `go tool game credits -out resources/CREDITS.md`. Which targets a machine can build is what `nsgo doctor` shows: iOS needs a Mac with Xcode, and the macOS disk image needs `hdiutil` in a logged-in session, so a release of every platform runs on a Mac. ### capture ```sh go tool game capture go tool game capture -shot title -out build/store ./mygame ``` Loads the [store screenshot plan](http://nsgo.games/docs/shipping/#store-screenshot-plan) `-plan` (`store/capture.yaml` by default) of the project directory named, the current one by default, and fails, naming each problem, when a shot's scene or recording is missing or one of its images under `-out` (`store/media` by default) is missing, not a PNG or not its target size. `-shot` checks only the shot of that name. It does not render the images: that needs the fixed-step movie mode of [#1438](https://github.com/nsgo-dev/game/issues/1438). ### replay ```sh go tool game replay ./... go tool game replay -run '^TestBossReplay$' ./levels ``` Plays a game's [input recordings](http://nsgo.games/docs/replay/) headless, for CI. A recording needs the game's own simulation to play, so the command plays them through the game's tests: it first loads every `*.replay.yaml` file under each directory and fails, without running any test, when one cannot be played (an unknown key, a name missing from the header, a step out of order) or when a directory holds none, so a mistyped path cannot pass. It then runs the tests whose names match `-run`, by default every test with `Replay` in its name, headless with `go tool nsgo test`, and fails when one fails, which is what `replay.AssertEndState` does when a run ends in another state than the one the test expects. It also fails when no test in a directory passed, as when `-run` matches no test, so a misnamed test or a mistyped pattern cannot pass without playing a recording. Name the tests that play recordings accordingly, such as `TestLevel1ClearReplay`. Each directory is a tree, as `nsgo test` reads it: with or without a trailing `/...`, its subdirectories are searched and tested too, skipping directories whose names start with `.` or `_` and nested modules but not `testdata`. The default is `./...`. The command runs `go tool nsgo`, so the module needs NSGo's command as a tool, as an NSGo app has. ### playtest ```sh go tool game playtest go tool game playtest -config playtest.yaml -out playtest.report.yaml -recordings playtest-recordings go tool game playtest -check ``` Validates `playtest.yaml` (or `-config`) and runs the configured bot headless for every seed through the game's tests matching `-run` (`Playtest` by default, which call `playtest.RunTest`). Each seeded run records its inputs into `/run_NNN_seed_.replay.yaml` so any run can be watched or turned into a `game replay` test, and writes a deterministic YAML report to `-out` (`playtest.report.yaml` by default) containing per-run metrics, goal results (`met`, `missed` or `info`) and position data for heat maps. The command prints the report summary and exits 1 when any goal is missed or no matching test passed. Use `-count` or `-seeds` to override the runs in `playtest.yaml`, or `-check` to validate `playtest.yaml` without running tests. See [playtest](http://nsgo.games/docs/playtest/). ### bench ```sh go tool game bench ./sprite ./tilemap go tool game bench -update ./sprite ./tilemap go tool game bench -in bench.txt ``` Runs the benchmarks under each directory headless with `go tool nsgo test -bench`, `-count` times (3 by default) for `-benchtime` each (200ms by default), takes each benchmark's median time, bytes and allocations per operation, and compares them with the baseline file named by `-baseline`, by default `benchmarks/baseline.yaml`. It prints a line per benchmark in the baseline and fails when one grew past its limit or was not measured, or when the baseline holds no benchmark; a measured benchmark the baseline lacks is listed as new and does not fail. `-bench` narrows the benchmarks run, as `go test -bench` does. `-in` reads the results from a file of `go test -bench -benchmem` output instead of running anything. `-update` writes the measured medians to the baseline instead, creating it when it does not exist, and keeps the benchmarks it did not measure. The baseline is a YAML text file to review and edit like any other: the format version, a note, the regression allowed for each metric in percent, and one line per benchmark in name order. Loading and saving it changes nothing, and unknown keys and missing metrics are refused. ```yaml version: 1 note: Update with go tool game bench -update ./sprite ./tilemap max_regression_pct: {ns_per_op: 25, bytes_per_op: 25, allocs_per_op: 25} benchmarks: BenchmarkBatchDraw1000: {ns_per_op: 155412, bytes_per_op: 72232, allocs_per_op: 754} BenchmarkRaycast: {ns_per_op: 827.3, bytes_per_op: 0, allocs_per_op: 0} ``` Benchmarks are named without their `-GOMAXPROCS` suffix, so a baseline recorded on one machine is read on another, but time per operation depends on the machine: record the baseline on the kind of machine CI checks it on. The format is read and written by the `tooling/bench` package. ### size ```sh go tool game size -kind aab path/to/app.aab go tool game size -kind wasm -budget benchmarks/web-budget.json -markdown ``` Measures a package and checks it against a size budget: an Android App Bundle (`.aab`), an Android APK (`.apk`), an iOS App Store Package (`.ipa`) or a WebAssembly binary (`.wasm`). The kind comes from `-kind`, else from the package's extension, else it is `wasm`. A mobile package is checked against the budget file `-budget` names, or the platform's built-in budget; a WebAssembly binary against `-budget`, by default `benchmarks/web-budget.json`, building the budget's target with `GOOS=js GOARCH=wasm` when `-wasm` names no binary. `-budget-mb` and `-abi-budget-mb` override the total and per-ABI limits. The report is text, Markdown with `-markdown` or JSON with `-json`, and is written in full even when the package is over budget, which fails the command. [Package Size Budgets](http://nsgo.games/docs/package-size-budgets/) lists the categories, the default budgets and the budget files, read by the `tooling/sizecheck` package. ### new ```sh go run github.com/nsgo-dev/game/cmd/game@latest new mygame go run github.com/nsgo-dev/game/cmd/game@latest new -name "Space Rocks" -module example.com/rocks rocks go run github.com/nsgo-dev/game/cmd/game@latest new -list ``` Writes a project from a template into the directory named, creating it if needed, and prints each file's path. It then runs `go get -tool github.com/nsgo-dev/game/cmd/game@` and `go mod tidy` there, which need the Go module proxy, so the project requires that version of the game layer and has the `game` tool beside the `nsgo` tool, and builds and runs with `go tool nsgo dev` without edits. The game is named after the directory unless `-name` gives a name (letters, digits, spaces, `-` and `_`, starting with a letter), which `game.yaml` and `nsgo.yaml` hold as `name`, with `id` derived from it as `dev.nsgo.`. The module path is the name in lower case with its words joined by `-` unless `-module` gives one. A module path that is a standard-library package's, such as `time` for a game called Time, is refused because the project could not build, so such a game needs `-module`, such as `-module example.com/time`. `-version` is the version of the game layer to require, such as `v0.4.0`, a commit or `latest`; by default it is the version of the command running, so `go run …@v0.4.0 new`, or an `nsgo-game` installed at `v0.4.0`, creates a project on `v0.4.0`, and `latest` when the command was built from a checkout of this repository. `-template` chooses the template, `starter` by default, and an unknown name is refused with the names there are. `-list` prints each template's name, the default marked, beside a line saying what it is, and creates nothing. Those lines come from each template's [`template.yaml`](http://nsgo.games/docs/templates/#template-manifests), and `-list -json` prints the manifests themselves as a JSON array for scripts and agents; a template whose manifest does not load is left out and reported on standard error. [Templates](http://nsgo.games/docs/templates/) lists them with the module `nsgo init -template` takes for each, and describes how a template is laid out and how to add one. `new` writes nothing when any file it would write already exists in the directory, and fails with 1. Every template includes `.gitattributes` setting `* text=auto eol=lf` for text files, marking binary media extensions as `binary`, and registering `*.scene.yaml` and `*.scene.yml` with the `nsgo-scene` merge driver, as well as `.gitignore` ignoring `.nsgo/`, `.game/`, and `dist/`. `new` checks `git rev-parse --show-toplevel` from the new directory and configures the local Git driver automatically whenever it lies inside an existing Git repository (including a parent directory or monorepo), and otherwise prints `go tool game merge -setup` to run after `git init`. Because Git does not share `.git/config`, each clone runs `go tool game merge -setup` once (or enables it from the editor banner). When `go get` or `go mod tidy` fails, such as without a network, the files stay where they are written, and the error names the commands left to run in the directory to finish the project: both `go get -tool …` and `go mod tidy` when `go get` failed, and `go mod tidy` alone when it failed. ### project ```sh go tool game project check go tool game project fmt go tool game project -check sync path/to/game go tool game project targets ``` Works on the [project file](http://nsgo.games/docs/project/), `game.yaml`, of the project in the directory named, the working directory by default. `check` reports every problem of the project at once: a `game.yaml` that does not parse, an `nsgo.yaml` that disagrees with it, an autoload that is missing or invalid, and a file an installed pack wrote that is missing. `fmt` rewrites `game.yaml` in canonical form, which keeps no comments, and prints its path when it changed it. `sync` writes the fields `game.yaml` owns into `nsgo.yaml`, creating it when missing, and prints its path when it changed it; run it after editing `game.yaml`. `targets` prints the export presets' build targets, comma-separated, for `nsgo build -target`. With `-check`, `fmt` and `sync` write nothing and fail with 1 when the file is not in canonical form or the two files disagree, as CI runs them. `-check` with `check` or `targets`, or written after the verb, is a usage error. ### dev ```sh go tool game dev go tool game dev -target native -fps go tool game dev -scene scenes/level2.scene.yaml go tool game dev ./mygame -lang fr ``` Runs `go tool nsgo dev`, which builds the game, starts it and rebuilds it when its Go code changes, and tells the running game where its assets are: the absolute path of `-assets` (`resources` in the project directory by default) in the `NSGO_GAME_ASSETS` environment variable, which `hotreload.DevAssetsDir` returns. Passing `-scene ` sets `NSGO_GAME_SCENE` (`hotreload.SceneEnv`, read by `hotreload.DevScene`) so the running game can start directly at that scene (as the editor's Run command does when starting at the open scene). It must be the directory the game's `assets.Manager` reads `"asset:"` URIs from: one made with `assets.WithFS(os.DirFS(hotreload.DevAssetsDir()))`, since a `Manager` without `WithFS` reads packaged app resources through `core.Scope.ReadAsset` rather than live edits on disk. A game that starts a watcher on it with `hotreload.NewDevWatcher` sees an atlas, image, data file, shader or material it has loaded change within a second of the file being saved, without restarting; see [Reloading on save](http://nsgo.games/docs/assets/#reloading-on-save) and [Hot-reloading shaders and materials](http://nsgo.games/docs/render3d/#hot-reloading-shaders-and-materials). The first argument that is not a flag is the project directory, `.` when there is none, and the arguments after it go to `nsgo dev` unchanged; `-target`, `-fps` and `-automation` are passed on too (with `-automation` enabling NSGo's automation server so the editor's Remote tab or `go tool nsgo mcp` can inspect the running game), and a `-target` among the arguments after the directory decides the target, as it does for `nsgo dev`. `nsgo dev`'s output is game dev's, and Control+C stops both. `go tool game dev` exits with 1 when `nsgo dev` fails. Assets reload on the `native` and `tui` targets, and on `android` with `-android-host`, whose app's Go runs on this machine and reads the files. On the web and on phones the app cannot reach the asset directory, so game dev says so and the game picks up asset changes when `nsgo dev` rebuilds it. Without an asset directory game dev runs `nsgo dev` as it is and says that assets will not reload. An asset the game embeds with `go:embed` is part of its binary: `nsgo dev` rebuilds and restarts the game when such a file changes, and the watcher's reload shows the change before that. With `-debug`, the native target runs under the [Delve](https://github.com/go-delve/delve) debugger (`dlv` on `PATH`), as `nsgo dev -target native -debug` does; any other target is refused. When Delve prints its `API server listening at` line, game dev repeats the address with a ready VS Code attach configuration (the `Attach to game` entry the templates ship in `.vscode/launch.json`, with the port Delve chose), which a GoLand **Go Remote** configuration at the same host and port matches. The address stays the same across rebuilds, so the IDE reconnects to it after every build; the editor's **Debug** run mode surfaces the same address in its status bar. ### check ```sh go tool game check go tool game check examples/caverun ``` Checks every scene, map, tileset and atlas under the directory named (or `-in`, or the working directory when neither is given), and the references between them, so a broken reference fails before a player reaches it. Each problem is printed to standard error as `file:line: message`, with the file named from the working directory so an editor can open it, followed by a count, and the command exits with 1; with no problems it prints how many files of each kind it checked and exits with 0: ```text examples/caverun/assets/level1.tmj:1397: tileset image "tileset.png": not found game check: 1 problem ``` | Files | What must hold | | --- | --- | | Scenes (`*.scene.yaml`, `*.scene.yml`) | They parse and validate as the [scene format](http://nsgo.games/docs/editor/), with no unknown field; a tilemap `source` is a Tiled map (`.tmj` or `.tmx`, which checks) or an LDtk project (`.ldtk`, which checks and has the `level` it names) that exists; a layered tilemap's `tilesetFile` is a YAML tileset that exists and checks and has every tile its cells place; each sprite's `atlas` exists and has its `frame`; an inline tilemap's `tileset` atlas has a frame for every tile ID it uses; a `material` file exists, is a valid material, and its `texture` exists; a `model` is a `.gltf` or `.glb` file that exists and loads with `gltf.LoadFS`, holds the node a `modelNode` names or the mesh a `modelMesh` names, and a `mesh` is a built-in primitive ([scenemodel](http://nsgo.games/docs/scenemodel/)); a scene that instances or inherits others resolves, and each of its connections' `from` and `to` names an object of the resolved scene — and when the project has an editor command, its components and each connection's event, handler and handler arguments are checked against the project's component registry too ([Checking connections](http://nsgo.games/docs/editor/#checking-connections)) | | Tiled maps (`.tmj`) and tilesets (`.tsj`) | External tilesets are JSON tilesets (`.tsj`, or `.json` as older Tiled versions named them; not `.tsx`) that exist; tileset and image-layer images exist, also inside group layers; the map loads with `tilemap.LoadTiled`. A Tiled XML map (`.tmx`) that a scene names loads with `tilemap.LoadTiled` together with its external tilesets (`.tsx` or `.tsj`), and every tileset and image-layer image it draws exists | | YAML tilesets (`*.tileset.yaml`, `*.tileset.yml`) | They parse and validate as the [tileset format](http://nsgo.games/docs/tilemap/#yaml-tilesets); a grid tileset's `image` exists and is large enough for its `columns`, `tileCount`, `spacing` and `margin`; an atlas tileset's `atlas` exists and has each of its `frames` | | LDtk projects (`.ldtk`) | Tileset images and level backgrounds exist; no level is saved in a separate `.ldtkl` file, which `tilemap.LoadLDtkAll` does not read (turn off "Save levels to separate files" in LDtk); the project loads with `tilemap.LoadLDtkAll` | | Sprite atlases (JSON with top-level `frames` and `meta`, as TexturePacker and Aseprite export) | `meta.image` exists; every frame lies inside the image; the atlas loads with `sprite.LoadAtlas` | | `game.yaml` and every other reference between files | `game.yaml` parses and validates as the [project file](http://nsgo.games/docs/project/); each autoloaded scene and resource exists, as does each `assets` target's `in` (a folder for an atlas or glyph-image font), each font target's `charsFrom` and `charsFile` inputs, and every other file a reference names that the rows above do not reach: the scene a scene `inherits` and the scene an object instances (`scene`), whatever its file is called, the materials, models and tilemap sources in overrides and in scenes not named `*.scene.yaml`, a material's `texture` wherever the material is used, and the buffers and images a `.gltf` model keeps in separate files. What `game assets` writes (`out`, `cache`, `manifest.in`) and the navigation mesh file a scene's `navMesh` names, which `game navmesh` writes, need not exist yet. For every font target meant for a locale (either via `locale` or by listing that locale's string table in `charsFrom`), every string and plural form in that locale's localization tables must be drawable by the font target (checking the baked `.fnt` when present, or the source font and character sources before baking), naming each missing key and character | | Project indexes (`game.index.yaml`) | They parse, and no two scene or resource files of one project share a `uid`, as a copied file does until `game index` gives it its own; separate projects, such as two games made from one template, may | A path a map, tileset or atlas writes is relative to that file, as Tiled, LDtk and texture packers write them. A scene's tilemap `source`, `tilesetFile`, `material` and `model`, a YAML tileset's `image`, and a material's `texture`, are relative to the project root: the nearest directory above the scene holding `game.yaml`, `nsgo.yaml` or `go.mod`, or the checked directory when there is none. A scene names an atlas the way its game's `sceneformat.AssetResolver` does, so the check finds it by file name: the atlas JSON in the same project whose base name without `.json` is the name (`actors` is `art/actors.json`), or whose path from the project root is (`art/actors`). When several match, the one nearest the scene wins, counting the directories up from the scene and down to the atlas, so an atlas beside the scene beats one in a subdirectory, and two equally near are reported as ambiguous until the scene names one by its path. When no atlas matches but a JSON file of that name does not parse or is not an atlas, that file's fault is reported. A path must be relative and use forward slashes, and must not lead outside the checked directory. PNG, JPEG and GIF images must decode; other images only have to exist. Directories whose names start with `.` or `_`, and those named `testdata`, are skipped, as the go command skips them. A problem the loader of a map or atlas reports names no line, so it is printed as `file: message`; the check runs that loader only once the file's references resolve, so one fault is not reported twice. When a reference names a file that is gone and the project index knows where it went, the problem says so, and [`game index`](http://nsgo.games/docs/cli/#index) updates the reference: ```text scenes/room.scene.yaml:10: material "materials/stone.material.yaml": not found; it moved to "materials/rock.material.yaml"; run game index to update the reference ``` When `game.yaml` records an [`origin`](http://nsgo.games/docs/project/#the-file) of kind `template` naming a template this version of `game` embeds, `game check` also compares the project with that template, byte for byte, and prints what is still unchanged as warnings, `file:line: warning: message`, after the problems: the Go files holding the rules (other than `main.go` and tests) and the data files (YAML, JSON, CSV and Yarn files other than `game.yaml`, `nsgo.yaml`, `game.index.yaml`, `brief.yaml`, `template.yaml`, `playtest.yaml`, touch layouts and files under `.vscode`) still equal to the template's, listed together in one warning; a `name` or window title still the template's; and a `README.md` or `CREDITS.md` still the template's. Warnings do not fail the command: with no problems it exits with 0 and its summary counts them. For a deliberate as-is copy, list the warnings to leave out in `origin.keep`: `rules`, `data`, `name`, `readme` or `credits`. ```text game.yaml:20: warning: 12 rule and data files still equal template "cards2d": board.yaml, game.go, hud.go, notice.go, project.go, render.go, rules.go, rules.yaml, save.go, strings/en.yaml, strings/zh.yaml, table.go; change them, or add rules or data to origin.keep for a deliberate copy README.md: warning: README.md is still template "cards2d"'s; rewrite it for this game, or add readme to origin.keep ``` When `origin.path` and `origin.source` identify different bundled templates, `game check` skips the comparison. See [the template guide](http://nsgo.games/docs/templates/) for how the origin selects a template. When the checked directory is a project with its own editor command (either a `main` package in `cmd/editor` importing `pkg/editor/editorcmd`, or a `main` built with `-tags gameeditor` as `game generate editor` writes), `game check` runs that command with `-check `, which runs `assetcheck.CheckWith` using the project's `editorcmd.Options.Components` plus the built-in physics and skeletal components so component fields and connection events, handlers and arguments are checked too (including connections brought in by instanced or inherited scenes). Without an editor command, `game check` checks connection objects only and, when any scene has connections, prints a note explaining that events and handlers were not checked and how to enable it with `game generate editor`. The project editor command also checks YAML data tables that match `editorcmd.Options.DataTables`, printing `file:line:column` when the source position is known. In a project without a compatible editor command, `game check` prints a note that the typed data table checks were skipped. See [Data tables](http://nsgo.games/docs/datatable/) for the registry API. The Examples workflow runs `game check` on the sample games. To run it in a game's own CI, add the command as a tool as above and run `go tool game check` from the game's directory. The checks are also a package, `github.com/nsgo-dev/game/pkg/tooling/assetcheck`, whose `Check` takes an `fs.FS` and returns the problems as values, and whose `CheckWith` takes the game's component registry so tests (such as `action3d`'s `TestScenesCheck`) can check events and handlers directly without an editor command. ### assets ```sh go tool game assets go tool game assets -check ``` ### `dlc` `go tool game dlc build definition.yaml` creates a deterministic ZIP from the built asset directory and updates `manifest.json`. Use `-root`, `-out` and `-url` to select the input, output and CDN URL. `GAME_PACK_KEY` signs the archive digest. `go tool game dlc verify manifest.json -key ` verifies every local archive before publishing it. Builds every asset target that `game.yaml` (or the file `-in` names) declares, in one run: it packs the atlases, encodes the textures and converts the audio as `pack`, `tex` and `audio` do, bakes the fonts into bitmap fonts and packs the models into single GLB files, then regenerates the manifest as `manifest` does. Each target is rebuilt only when it changed: a second run with nothing changed writes no file, and changing one image repacks only the atlas it belongs to. It prints a line for each target it built and then the counts, such as `1 built, 4 up to date`. The targets are the `assets` section of `game.yaml`, the project file, which the command reads through package `project` as the game and the editor do, and which `release` accepts too, so one `game.yaml` holds them beside the window, input, autoload and export settings ([Project File](http://nsgo.games/docs/project/)). The file is versioned YAML and the command refuses a field it does not know, a file without an `assets` section, and a file the project schema refuses. The section's paths are slash-separated, relative to the file's directory, and may not leave it: ```yaml version: 1 name: Cave Run id: dev.nsgo.game.examples.caverun appVersion: 0.1.0 window: {width: 480, height: 640} assets: atlases: - name: ui # pages ui.png and ui.json in: art/ui # PNG images, searched recursively out: assets/atlases padding: 2 # 1 when omitted extrude: 1 maxWidth: 2048 maxHeight: 2048 scale: 1 trim: true # true when omitted textures: - in: art/albedo.png out: assets/albedo.ktx2 format: bc1 # rgba8, bc1, bc3, bc7, etc2, etc2-rgba, astc4x4 or uastc; rgba8 when omitted mipmaps: true srgb: true audio: - in: sfx/jump.wav out: assets/jump.wav format: wav # wav, aac or mp3; wav when omitted rate: 22050 channels: 1 peakDB: -1 # or rmsDB, not both bitrate: 128 # for aac and mp3 fonts: - in: fonts/Inter.ttf # a TrueType or OpenType font out: assets/fonts/hud.fnt # pages hud.png, or hud-0.png, hud-1.png and so on, beside it size: 24 # pixels; 32 when omitted chars: " 0123456789:" # printable ASCII when chars, charsFrom and charsFile are all omitted; merged otherwise charsFrom: # collect characters from l10n tables, *.table.yaml data tables and *.scene.yaml scenes - l10n/zh-Hans.yaml - data/items.table.yaml charsFile: fonts/extra-zh.txt # plain UTF-8 file of extra characters, merged locale: zh-Hans # optional BCP-47 locale checked by game check (inferred from l10n tables in charsFrom when omitted) padding: 1 # 1 when omitted - in: art/fonts/score # a folder of glyph images: 0.png ... 9.png, plus.png, times.png out: assets/fonts/score.fnt glyphs: # maps a name that is not one character to its character plus.png: "+" times.png: "×" spacing: 2 # extra advance in pixels; 0 when omitted align: bottom # top, center or bottom; bottom when omitted models: - in: models/ship.gltf # .gltf or .glb, with the buffers and images it names beside it out: assets/ship.glb scale: 0.01 # 1 when omitted animations: true # true when omitted manifest: in: assets out: assets/manifest_gen.go package: assets prefix: "asset:" embed: false embedDir: "" remote: out: dist/cdn base: https://cdn.example.com/game/ include: [music/] ``` Every list and the manifest are optional, and each setting means what the flag of the same name means for the single command. Two targets may not write the same file: an atlas named `ui` writes `ui.png` and `ui.json`, or `ui-0.png`, `ui-1.png` and so on with their `.json` files when it needs several pages, so no other target in its folder may write those names, nor another atlas there be named `ui` or `ui-1`. No target, and not the cache, may write over `game.yaml` or a file a target reads, since the next run would then read its own output. An atlas may not write its pages into a folder an atlas reads images from, nor may another target or the cache write a `.png` file there, since the atlas would then pack it on the next run, and the cache may not be inside the manifest's folder, since the manifest would then list it; a folder whose name starts with a dot is skipped by both scans, so any of them may go there. A font's pages are named after its `.fnt` file as an atlas's are after its name, `hud.png` or `hud-0.png`, `hud-1.png` and so on beside `hud.fnt`, and follow the same rules. No target may read a font's page either: fonts are built after textures and models, so a texture made from one would encode the page of the run before. A font target bakes a TrueType or OpenType font into an [AngelCode BMFont](http://nsgo.games/docs/text/) that `text.LoadBMFont` reads: the character set is formed by merging `chars`, every file in `charsFrom` (versioned YAML or JSON localization string tables — all strings and plural forms — YAML data tables' string cells, and custom text fields of `.scene.yaml` scenes, with `{placeholders}` and rich-text markup stripped), and any UTF-8 `charsFile` (control characters and line breaks ignored), defaulting to printable ASCII when all three are omitted. The target's cache key covers only the resulting sorted, deduplicated character set, so editing a string rebuilds the font only when the set of characters changes. Each character the font has a glyph for is drawn at `size` pixels, at most 2048, in white with its coverage as alpha, the glyphs are packed onto PNG pages up to 2048 pixels a side, `padding` pixels apart, and the `.fnt` text file records each glyph's place, offsets and advance, the line height and baseline, and the font's kerning between the baked characters. A character the font has no glyph for is left out and reported as a warning on standard error; a font with none of them is an error. An `in` that is a folder of PNG glyph images, such as score digits or damage numbers, bakes the same `.fnt` and pages from the images themselves: a file whose base name's stem is one character, such as `7.png`, draws that character, and `glyphs` maps every other name to its character, such as `plus.png` to `+`; an unmapped name, two images for one character, a `glyphs` entry for a file the folder does not hold and a file that is not a PNG image are refused, as are `size`, `chars`, `charsFrom` and `charsFile`, which pick the glyphs of a font file. Each glyph is drawn at its image's pixels, so `lineHeight` and `base` are the tallest image's height, its advance is the image's width plus `spacing`, and `align` places it at the top, center or bottom of the line; hand-drawn images carry no kerning, so the `.fnt` has none. A folder's own sidecar may set `padding` only. A model target packs a glTF model into one binary glTF file that [gltf](http://nsgo.games/docs/3d-models-blender/) loads with nothing to resolve: the buffers the model holds or names, a `.glb` file's binary chunk among them, are merged into the GLB's binary chunk, and each image it names by file or data URI is embedded there with its media type. Every other property is kept, extensions and extras included, and the result is checked by loading it. `scale` puts each root node of the model's scenes under a new node scaled by it, one per root even when several scenes list it, such as `0.01` for a model exported in centimeters, and `animations: false` leaves the animations out. The buffers and images the model names must be relative paths inside the project; they are inputs of the target, so editing a texture beside a `.gltf` file repacks it. When `remote` is configured, `go tool game assets` copies loose assets into `remote.out` under content-hashed filenames (`..`) and writes a sorted, versioned `remote.yaml` manifest mapping each URI (`remote.prefix`, `"asset:"` by default, plus relative path) to its hashed path, byte size and SHA-256, with `remote.base` recorded as the default origin URL for [`assets.WithRemote`](http://nsgo.games/docs/assets/#remote-assets). It scans `remote.in`, or `manifest.in` when `remote.in` is omitted (or the outputs of the build targets when neither is set), skipping dotfiles, `.go` files and `*.import.yaml` sidecars, and optionally filtering by `remote.include` prefixes or globs. Previous hashed files whose content changed are removed automatically, and `-resources` redirects `remote.in` while keeping `remote.out` intact. What each target was built from is kept in a cache, `.game/assets-cache.yaml` unless `assets.cache` names another path. It is YAML: for each target, a SHA-256 key over its settings, the version of the game layer that built it, the path and content of every input, a model's buffers and images included, and of the import settings sidecar beside it and, for AAC and MP3, the external encoder and its version, and the path and SHA-256 of every file it wrote. A target is up to date when its key matches and its outputs are still on disk with that content, so editing or deleting an output also rebuilds it, and so does installing another encoder. When an atlas needs fewer pages than before, the pages it no longer writes are deleted, and so are other page files of its name in its folder. When a target is renamed, moved to another output or removed from `game.yaml`, the files it last wrote are deleted before the manifest is generated. The manifest needs no cache entry: it is generated each run, which reads no file's content, and written only when it differs. A missing or damaged cache only costs a full rebuild. Add the `.game` folder to `.gitignore`. `-resources` writes every built target's outputs and the manifest's input scan into `resources/` (replacing a leading `assets/` prefix when present) and emits `"asset:"` URIs in the manifest with `embed` turned off, so built assets ship in NSGo's app resources rather than an embedded directory. `-force` rebuilds every target. `-check` writes nothing in the project: it lists the targets that are out of date and exits with 1 if there are any, for CI. A target the cache does not show as up to date, as in a fresh checkout without the `.game` folder, is built in a temporary folder and counts as up to date when the files in the project are exactly what it writes, so CI needs no cache when the outputs are committed. AAC and MP3 are the exception: another encoder, or another version of one, writes different bytes for the same input, so without a cache entry they count as up to date when their output exists, and CI needs no encoder. An atlas whose folder holds a page file of its name that it does not write, such as `ui-1.png` left from a build that needed more pages, is out of date until a build deletes it. When a target fails, the command keeps the cache of the targets it built before it, so the next run starts from there. #### Import settings beside each asset An asset may have a sidecar: a YAML file beside it, named after it with `.import.yaml` appended, such as `art/albedo.png.import.yaml`, that says how it is imported and who made it under what license. A setting in the sidecar overrides the same setting of the target that reads the file, so one asset's import is changed by editing the file beside it, and the next run rebuilds the targets that read it. A sidecar is versioned YAML that package `github.com/nsgo-dev/game/pkg/importsettings` reads and writes; it holds one `image`, `audio`, `font` or `model` section, a `credit` section, or a credit with one of the others, refuses a field it does not know, and is validated by the [published schema](http://nsgo.games/docs/schemas/) `https://nsgo.games/schemas/import.v1.json`. ```yaml # art/albedo.png.import.yaml, read by a texture target version: 1 image: filter: nearest # linear or nearest, written into the KTX2 key/value data as game.filter format: rgba8 # rgba8, bc1, bc3, bc7, etc2, etc2-rgba, astc4x4 or uastc mipmaps: false srgb: true ``` ```yaml # art/hero/run.png.import.yaml, read by the atlas whose folder holds run.png version: 1 image: slice: {width: 16, height: 16, margin: 1, spacing: 2, count: 6} pivot: default: [0.5, 1] cells: - cell: 2 pivot: [0.25, 0.75] ``` ```yaml # music/theme.wav.import.yaml, read by an audio target version: 1 audio: format: wav # wav, aac or mp3 rate: 32000 channels: 2 rmsDB: -14 # or peakDB; either one replaces the target's normalization bitrate: 128 loop: {start: 44100, end: 1323000} # in the source's sample frames; end 0 or left out is the end of the sound ``` ```yaml # fonts/Inter.ttf.import.yaml, read by a font target version: 1 font: size: 24 chars: " 0123456789:" # each once, in any order; merged with charsFrom and charsFile charsFrom: - l10n/zh-Hans.yaml charsFile: fonts/extra-zh.txt padding: 2 ``` ```yaml # models/ship.gltf.import.yaml, read by a model target and scenemodel.Build version: 1 model: scale: 0.01 animations: false lodHysteresis: 0.05 lods: - { node: Ship_LOD0, minScreenRatio: 0.25 } - { node: Ship_LOD1, minScreenRatio: 0.0 } ``` ```yaml # assets/fonts/pixel.ttf.import.yaml, a credit beside an asset no target imports version: 1 credit: author: Ana Souza license: OFL-1.1 # an SPDX license expression source: https://example.com/pixel-font notice: |- Copyright 2026 Ana Souza. Licensed under the SIL Open Font License, Version 1.1. ``` - A texture target reads `filter`, `format`, `mipmaps` and `srgb`. `filter` is stored under the key `game.filter` of the KTX2 file's key/value data, and [`render3d.LoadKTX2`](http://nsgo.games/docs/render3d/) sets the sampler's filters from it when it loads the texture: `nearest` draws it sharp, as pixel art wants, and `linear` blends neighboring texels. `slice` and `pivot` are refused, since a texture holds the whole image, unless an atlas also reads the image. - An atlas target reads `slice` and `pivot` from the sidecar of each image in its folder: `slice` cuts the image into cells of `width` by `height` pixels, `margin` pixels from its top and left edges and `spacing` pixels apart, taken row by row, and cell `i` of `run.png` is packed as the frame `run_i.png`. `count` keeps the first cells; left out, every cell that fits is a frame. `pivot` sets normalized `[x, y]` pivot coordinates as fractions of the untrimmed frame size (from `[0, 0]` at top left to `[0.5, 1]` at bottom center), written into each packed frame's TexturePacker `pivot` field so `sprite.LoadAtlas` sets `Frame.PivotX` and `Frame.PivotY`: `default` applies to an unsliced image and every cell of a sliced sheet without an override, and `cells` lists per-cell `{cell, pivot}` overrides in ascending 0-based cell order (requiring `slice`). The texture settings, `filter` included, are refused there, since an atlas page is one texture for every image packed into it, unless a texture target also reads the image: an image read by both may hold both kinds of settings, and each target takes its own. A frame that takes the name of another image in the folder is refused. - A font target reads every `font` setting: `size`, `chars` and `padding`. Listing the same characters in another order changes nothing. - A model target reads every `model` setting: `scale` and `animations`. - `game release` and `game credits` read `credit`, which any asset's sidecar may hold, beside an `image`, `audio`, `font` or `model` section or on its own; `game assets` builds nothing from it. `author` and `license` are required. `license` is an [SPDX license expression](https://spdx.github.io/spdx-spec/v2.3/SPDX-license-expressions/): identifiers from the SPDX license list such as `CC0-1.0`, `CC-BY-4.0` or `OFL-1.1`, joined by `AND` and `OR` and grouped by parentheses, a `+` for "or any later version" and `WITH` for an exception, such as `MIT OR Apache-2.0`; a license with no identifier, such as a store's or a studio's own, is `LicenseRef-` followed by a name of its own, with its terms in `notice`. Its form is checked, not the identifier against the list, and `NONE` and `NOASSERTION` are refused. `source` is where the asset came from, usually a URL, and `notice` is text the license asks to be shipped with the asset, such as a copyright line, kept word for word and on several lines if need be. - An audio target reads every `audio` setting. `loop` is written into the WAV output's `smpl` chunk as a forward loop that repeats forever, scaled to the output rate; AAC and MP3 carry no loop points, so a sound with a loop must be converted to `wav`. A loop already in a source WAV's `smpl` chunk is kept the same way. A sidecar's settings are part of the key of every target that reads its asset, so adding, editing or deleting them rebuilds those targets and no others, and `-check` reports them as out of date until the next run. Its `credit` section, comments and layout are not, since they change no output: fixing an author's name rebuilds nothing. Sidecars are not assets: the manifest skips files named `*.import.yaml`, and an atlas packs only `.png` files. `game pack`, `game tex` and `game audio` read the sidecar beside their input too, under the flags given. A sidecar in a folder a target reads from (an atlas's folder and the folders below it, or the folder of a texture, audio, font or model input) whose asset no target reads is refused, so a mistyped name, a sidecar beside a JPEG in an atlas folder, or one named in another case than its asset, such as `Hero.PNG.import.yaml` beside `hero.png`, is an error rather than settings that silently do nothing. A sidecar that holds only a `credit` says nothing about the build, so it may sit beside any file in those folders, such as a JPEG or an image a model embeds, as long as the file is there under exactly its name. ### generate ```sh go tool game generate component player_health go tool game generate system movement go tool game generate -main scene level_one go tool game generate prefab enemy go tool game generate editor ``` Writes the code and files of a new component, system, scene or prefab, or the game's editor command, into the game in `-in`, the working directory by default, laid out as [`game new`](http://nsgo.games/docs/cli/#new) lays out a project, and prints the path of each file it writes. The Go code goes into the package in that directory, under that package's name, and every Go file comes with a test beside it. The name is ASCII letters and digits starting with a letter, in camel case or with its words joined by `-` or `_`, and is written in each form it is used in: `player_health`, `player-health` and `PlayerHealth` all give the Go type `PlayerHealth`, the key `playerHealth` and files named `player_health_*`. | Kind | Writes | Registers it in | | --- | --- | --- | | `component` | `_component.go`: a struct (`PlayerHealth`) and the `sceneformat.ComponentType` scene files set it by (`playerHealth`), both without fields | `Components`, the `sceneformat.ComponentRegistry` that loading a scene checks its objects' components against | | `system` | `_system.go`: a function `MovementSystem(w *entities.World, dt time.Duration)`, added to the scheduler as `movement` | `Systems`, the `entities.Scheduler` the game steps each fixed step | | `scene` | `scenes/.scene.yaml`: a scene in the scene format's current version with an empty layer named `main` and the virtual resolution of `game.yaml` (its window's size when it has none); and `_scene.go`, which embeds the file and parses it with `LoadLevelOneScene`, checking its components against `Components` | `game.yaml`'s `autoload` scenes with `-autoload`, and as its `mainScene` with `-main` | | `prefab` | `prefabs/.scene.yaml`: a scene of one object whose `prefab` is the name, for other scenes to instance with `scene: prefabs/enemy.scene.yaml`; and `_prefab.go`, an `entities.Prefab` (`EnemyPrefab`) of that name | `Prefabs`, the game's prefabs by name | | `editor` (no name) | `editor.go`: the game's scene editor, a `main` function built with the `gameeditor` tag that runs `editorcmd.Main` with `Components` and `editorPlugins`, the game's editor plugins, which it declares empty; and `editor_test.go`, which opens the project in it | adds `//go:build !gameeditor` to the file that declares the game's own `main`, so the tag builds the editor in its place | The registries are declared once, in `components.go`, `systems.go` and `prefabs.go`, which the first component, system, scene or prefab that needs one writes. Each generated file adds itself to its registry in an `init` function, so `generate` never edits a file that is already there. The game uses them where it loads scenes and runs its loop: `sceneformat.ParseWith(data, sceneformat.ParseOptions{Components: Components})` refuses a component or field a scene sets that no component describes, and `Systems.Step(world, dt)` in the `game.Loop`'s `Update` runs the systems in their order, which `entities.After` and `entities.Before` set where each one is added. Fill in the generated code from there: a component's fields and the `sceneformat.Field` of each one a scene may set, a system's queries, a prefab's components with `entities.With`. The editor command is the game's own package built with the `gameeditor` tag, because a game made with `game new` keeps its code in its `main` package, which no other package can import: built that way, the editor links the game's component types, and the game built without the tag links no editor. [`game editor`](http://nsgo.games/docs/cli/#editor) runs it on the project as `go run -tags gameeditor .`, so the project's scenes open with their components and fields checked against `Components`, which the inspector lists. Add a plugin by appending its `editor.Plugin` to `editorPlugins`, keeping code only the editor uses in files built with the tag or in packages only they import; `game.yaml` turns it on under `editor.plugins` ([Editor plugins](http://nsgo.games/docs/editor/#editor-plugins-492-898)). Run its test with `go tool nsgo test . -tags gameeditor`. `generate editor` refuses a package that is not `main` or has no `main` function, a file declaring `main` whose build constraint is a legacy `// +build` line or names `gameeditor` already, as a second `generate editor` finds it, a file declaring `main` that also declares something the rest of the package needs, which the editor build, leaving out the whole file, would lose: a name another file or a test uses, an `init` function, a blank `var`, or a method on a type another file declares (move it into another file), and identifiers the package already declares; when rewriting that file fails, it removes what it wrote. What `generate` writes builds, passes the tests `go tool nsgo test` runs and passes `game check` as it is. It writes nothing and fails with 1 when a file it would write already exists, or when the package already declares an identifier it would declare, in any of its files, tests and files for other platforms included; choose another name then. It also fails when the package declares `Components`, `Systems` or `Prefabs` as something other than a variable, or declares a name a generated file imports a package as, such as `entities` or `time`, and refuses `components`, `systems` and `prefabs` as names, since their Go names are the registries'. `-autoload` and `-main` rewrite `game.yaml` in the form `game project fmt` writes, so they refuse a `game.yaml` in another form, such as one with comments, which rewriting would lose, until `game project fmt` has rewritten it, and refuse a name `game.yaml` already autoloads. The starter's `TestAutoloadsLoad` checks the files `game.yaml` autoloads, so an autoloaded scene that goes missing fails the game's tests; it reads them from the project directory, so it is skipped under `nsgo test -target` on a phone, a simulator or the web, where the generated tests read only the scene files their code embeds. ### mv ```sh go tool game mv materials/stone.material.yaml materials/rock.material.yaml go tool game mv -dry-run art gfx ``` Moves or renames a file or directory and rewrites every reference to what it moves: in `game.yaml` (including installed pack folders in `packs[].dir`), scenes, resource files, and Tiled and LDtk files, whose own paths relative to themselves are rewritten too when they move. Each reference is changed in place, keeping its quotes and the rest of its file byte for byte, comments included. The project index, `game.index.yaml`, is brought up to date. The paths are taken from the working directory and must lie inside the project, the directory `-in` names or else the nearest one at or above the working directory that holds `game.yaml`, `nsgo.yaml` or `go.mod`. Each change is printed; `-dry-run` prints them without making them, as it does for `release`. A move that would leave a reference broken is refused before anything changes, as are moving `game.yaml` or the index, a move onto an existing file, a move out of the project, and moving an individual file or subfolder tracked in an installed pack's `files` list without moving the pack's folder. See [Stable references](http://nsgo.games/docs/project/#stable-references). ### index ```sh go tool game index go tool game index -dry-run examples/caverun go tool game index -check ``` Gives every scene and resource file without a `uid` one, as a line after its `version`, points every reference to a file that was moved without the tools at the file's new path, gives a copied file that kept its original's uid a new one, and writes `game.index.yaml` at each project root, listing each scene and resource file's path and uid and each other referenced file's path and SHA-256 (with CRLF normalized to LF for text files so indexes agree across operating systems). It prints each change, or that the index is up to date; `-dry-run` prints them without making them. The directory is the one named, `-in`, or else the nearest at or above the working directory holding `game.yaml`, `nsgo.yaml` or `go.mod`. Unlike `check`, which checks the working directory and what is under it, `mv` and `index` default to that whole project, since a reference to a moved file can be anywhere in it and the index sits at its root: run from a subdirectory, `check` looks at the subdirectory alone while `index` updates the whole project. Run it once to start keeping an index, and again after moving files by hand or with Git; commit the index with the files. `-check` prints the same plan without writing and exits 1 when any uid, reference, hash or index entry needs an update, so a CI job can reject a stale index. ### library ```sh go tool game library list tiles go tool game library install dungeon-tiles go tool game library remove dungeon-tiles go tool game library digest library/packs/dungeon-tiles ``` Lists the packs of a library that match the words given (`-kind` keeps one kind), with the version the project has installed; installs packs into the project in the working directory (or `-project`), writing their files and recording them and the autoload entries and editor plugins they add in `game.yaml`; installs a newer release over an older one; removes an installed pack; and prints a pack directory's digest for the library's index. The library is the shared one in this repository unless `-index` names another. The index and pack formats, what an install may and may not overwrite, and how to add a pack are in [Asset and Plugin Library](http://nsgo.games/docs/library/). ### credits ```sh go tool game credits go tool game credits -in game.yaml -out CREDITS.md ``` Writes the credits file that `game release` writes beside its packages, to `-out`, or prints it when `-out` is empty, from the `assets` section of `-in` (`game.yaml` by default), without building anything. It lists the same assets as `release`, with the author, license and source from the `credit` section of the [import settings sidecar](http://nsgo.games/docs/cli/#import-settings-beside-each-asset) beside each one, and fails with 1, naming the sidecar each uncredited asset needs, when any has no credit, so CI can run it to keep every asset credited. The file is Markdown and depends only on the credits, so the same sidecars always give the same bytes: ````markdown # Credits | Asset | Author | License | Source | | --- | --- | --- | --- | | `assets/fonts/pixel.ttf` | Ana Souza | OFL-1.1 | | | `sfx/jump.wav` | Kenney | CC0-1.0 | | ## Licenses | License | Assets | | --- | --- | | [CC0-1.0](https://spdx.org/licenses/CC0-1.0.html) | 1 | | [OFL-1.1](https://spdx.org/licenses/OFL-1.1.html) | 1 | ## Notices ### `assets/fonts/pixel.ttf` ```text Copyright 2026 Ana Souza. Licensed under the SIL Open Font License, Version 1.1. ``` ```` The assets are sorted by path. The licenses table counts the assets under each license expression and links each single SPDX identifier to its page in the SPDX license list, and every notice follows word for word. Package `github.com/nsgo-dev/game/pkg/tooling/credits` collects the credits and writes the file, for a game that shows them on a screen of its own. ### pixelfx ```sh go tool game pixelfx -out assets/fx fire/torch go tool game pixelfx -set seed=4 -set palette=#102,#215,#43a,#8cf,#fff -flip -name frost-torch -out assets/fx fire/torch go tool game pixelfx -act -fps 30 -out assets/fx moves/ground-pound go tool game pixelfx -list ``` Renders one of the [pixelfx](http://nsgo.games/docs/pixelfx/) effects the command was built with to a PNG sprite sheet and its Aseprite JSON, `.png` and `.json` in `-out`, which `sprite.LoadAtlas` reads: every frame at the effect's own frame rate (or `-fps`), laid out in a grid, with each frame's duration and its pivot at the effect's origin, and one animation tag that loops a loop and plays a one-shot once. The name is the effect's (`torch`) unless `-name` gives one, which must be a file name without a directory. `-set name=value` sets one of the effect's options, as a number, `true` or `false`, a color such as `#4a3f69` (`#rgb`, `#rrggbb`, or `#rrggbbaa` with its alpha ignored), colors separated by commas for a palette, or text, and `-flip` mirrors it. `-act` renders the effect acted out instead: the stock character performing it, with its straw target, at 60 frames per second unless `-fps` says otherwise, and the JSON carries the act's timing for a game with its own character. `-list` lists the effects with their size, length and options. An effect, option or value the command does not know exits with 2. The categories it renders are the ones ported so far; each category's port adds its own. ### navmesh ```sh go tool game navmesh scenes/level1.scene.yaml go tool game navmesh -out build/level1.navmesh.yaml scenes/level1.scene.yaml ``` Bakes the [navigation meshes](http://nsgo.games/docs/navbake3d/) of a 3D scene: it resolves the scenes the scene instances and inherits, loads the glTF model (`.gltf` or `.glb`) each object's `mesh` names, from the project root, at the object's 3D transform, and bakes the triangles once for each agent type in the `navigation` section of the [project file](http://nsgo.games/docs/project/), with that section's settings; without one, it bakes one agent type called `default` with the default settings. It writes the [navigation mesh file](http://nsgo.games/docs/formats/#3d-navigation-meshes) to `-out`, or to the file the scene's `navMesh` names from the project root, and prints the file and each agent type's number of polygons. The project directory is `-in`, or the nearest directory at or above the working directory that holds `game.yaml`, `nsgo.yaml` or `go.mod`, and the scene must be inside it. The same scene and settings always write the same bytes, so the file belongs in version control beside the scene, and a bake that changes nothing shows no diff. A scene without a `navMesh` and no `-out` exits with 2, and one with no geometry to bake exits with 1. ### merge ```sh go tool game merge -setup go tool game merge -check go tool game merge %O %A %B %P go tool game merge -out merged.scene.yaml base.scene.yaml ours.scene.yaml theirs.scene.yaml scenes/level1.scene.yaml ``` Three-way Git merge driver for YAML scene files (`*.scene.yaml`, `*.scene.yml`). Instead of merging scenes line by line, it matches layers by `name`, objects by `id` anywhere in the scene tree (including across reparenting and layer moves), tilemaps and overrides by key, and connections by `(from, event, to, handler)`, merging fields one by one so independent edits on two branches combine cleanly and are written in canonical `sceneformat.Encode` order. When Git invokes the driver with ` [path]`, a clean merge overwrites `` (or `-out`) with the canonical merged scene and exits with 0. An empty `` file (a Git add/add merge) is handled by merging `` and `` against an empty ancestor. When both sides change the same field differently, one side deletes what the other modified, both add different objects with the same ID, reparenting conflicts or cycles occur, or the combined scene fails `sceneformat.Validate`, the driver writes a versioned, deterministic [scene merge conflict report](http://nsgo.games/docs/formats/#scene-merge-conflict-report) (`version: 1` YAML naming each object, field, and the `base`, `ours`, and `theirs` values) to `` (or `-conflict-out` / `-out`) and exits with 1 so Git marks the path unmerged. `-setup [dir]` registers `merge.nsgo-scene.name` and `merge.nsgo-scene.driver` (`go tool game merge %O %A %B %P`) in the repository's local Git config and ensures `.gitattributes` sets `* text=auto eol=lf` for text files, marks binary media extensions as `binary`, and routes `*.scene.yaml` and `*.scene.yml` to `merge=nsgo-scene`. Because Git never shares `.git/config` and silently falls back to line-by-line text merging when a driver named in `.gitattributes` is unconfigured, each clone runs `go tool game merge -setup` once. New projects created with `game new` include `.gitattributes` and configure the driver automatically whenever the new directory lies inside an existing Git repository (including a parent directory); otherwise `game new` prints the setup command to run after `git init`. `-check [dir]` verifies that `merge.nsgo-scene.driver` is configured in Git whenever `.gitattributes` (or Git's effective attributes) routes files to `merge=nsgo-scene`, exiting with 1 and printing the setup command if it is missing (or if `dir` is not inside a Git repository) and exiting with 0 otherwise. The scene editor runs the same check whenever a project inside a Git repository opens and offers one-click setup from a banner below the toolbar. ### schema ```sh go tool game schema go tool game schema -out schemas/scene.json go tool game schema -out schemas/scene.json path/to/project ``` Writes the project's draft-07 scene JSON Schema to standard output or to `-out`, with deterministic sorted component names and property order (see [Schemas for YAML files](http://nsgo.games/docs/schemas/#project-scene-schemas)). Because the `game` CLI cannot inspect a project's Go types directly, when the project has its own editor command (either a `main` package in `cmd/editor` importing `pkg/editor/editorcmd`, or a `main` built with `-tags gameeditor` as `game generate editor` writes), `game schema` runs that command with `-schema`, which prints the schema for `editorcmd.Options.Components` (including plugins and built-in physics and skeletal components) and exits without opening a window. A project without its own editor command gets the built-in scene schema, which types the built-in physics, skeletal and 2D navigation region components while keeping custom components free-form. ### net ```sh go tool game net decode session.capture.jsonl go tool game net decode --schema ./proto --format json --resolve-deltas session.capture.jsonl echo "230100000001" | go tool game net decode - go tool game net stats session.capture.jsonl ``` Inspects `pkg/online/netplay` packet capture logs (`*.capture.jsonl`) written by `netplay.NewCaptureTransport`, or standalone hex/base64 wire frames on standard input, driven by the `pkg/online/netplay/wire` schemas ([netplay](http://nsgo.games/docs/netplay/#packet-capture-and-inspection), [netplay/wire](http://nsgo.games/docs/netplay-wire/)). - `decode` prints each frame layer by layer as YAML (default) or JSON (`-format json`): transport header (`channel`, `seq`), optional relay frame and control body, and the inner replication, lockstep/rollback, membership, handshake, or custom game message selected by the wire discriminators. Pass `-schema ` to decode game-defined `*.wire.yaml` messages (including `EntityState.Props`), and `-resolve-deltas` to track per-peer replication baselines so `SnapshotDelta` frames also display the full resulting entity state. Pass `-` to read a JSONL capture or a single hex or base64 frame from standard input. - `stats` reads a JSONL capture (file or `-`) and prints total packets, bytes, duration, mean `SnapshotDelta` size, and breakdowns per message type and per peer in aligned text (default), YAML, or JSON (`-format text|yaml|json`). ### wire ```sh go tool game wire -in ./netmsg -out ./netmsg go tool game wire -lang ts -in ./netmsg -out ./netmsg/ts go tool game wire -in ./netmsg -out ./netmsg -check ``` Generates deterministic, zero-allocation Go codecs, or with `-lang ts` dependency-free TypeScript codecs, from `*.wire.yaml` schemas ([netplay/wire](http://nsgo.games/docs/netplay-wire/)): every schema in the `-in` directory, or the schema files named as arguments, together with the schemas they import. `-out` is a directory, or one `.go` or `.ts` file for a single schema, and defaults to the input directory; `-pkg` overrides the Go package name. `-check` writes nothing and fails when a generated file is missing or differs from what its schema produces, which is how CI keeps the committed codecs of `pkg/online/netplay/wire` current. ### admin ```sh printf '%s\n' "$PASSWORD" | go tool game admin operator add -role owner -totp ada go tool game admin -file ops/operators.yaml operator totp ada ``` Edits the operators file of a service's [admin listener](http://nsgo.games/docs/admin/), `operators.yaml` by default (`-file`): `operator add` adds an operator with a role (`-role`), a password read from the first line of standard input (or none with `-no-password`, for a token-only operator such as a CI job) and, with `-totp`, a TOTP secret; `operator passwd` replaces an operator's password; `operator totp` enrolls an operator for TOTP sign-in, or with `-off` stops requiring it; `operator revoke-tokens` refuses every bearer token issued for an operator until now, by setting its `tokensNotBefore`. A TOTP secret goes to the `.totp.yaml` file beside the operators file, readable by its owner alone, and is printed with the `otpauth://` URI to enroll an authenticator app with. The operators file only ever holds argon2id hashes. ### completion ```sh mkdir -p ~/.zfunc go tool game completion zsh > ~/.zfunc/_game ``` Writes a completion script for `zsh`, `bash` or `fish` to standard output. It completes the subcommands with their summaries, each subcommand's flags with their descriptions, the values `-format` and `release`'s `-channel` take, the kinds `generate` writes (offered for its name too, since a command's arguments complete alike at every position), the effects `pixelfx` renders, and file paths for `-in`, `-out` and the files and directories the other commands take. The script is generated from the commands' definitions, so after upgrading the game layer, write it again to complete the subcommands and flags the upgrade added. The script completes both `game` and `nsgo game` (for NSGo v0.4.0 or later; see [Install](http://nsgo.games/docs/cli/#install)): after `nsgo` it offers `game` and `nsgo`'s own commands, and after `nsgo game` whatever it offers after `game`. `go tool game` is not completed, since there the shell completes `go`. `nsgo` has no completion of its own, so the zsh and bash scripts register one for `nsgo` only while it has none: a completion of `nsgo` registered before the script, found by compinit earlier on `$fpath`, or that bash-completion can load, keeps completing `nsgo`, and a `_nsgo` later on `$fpath` still completes `nsgo`'s commands while `nsgo game` completes the game layer's. The fish script adds completions for `nsgo` that hold only after `nsgo game`, beside any of `nsgo`'s own. Save the script to a file once rather than generating it each time a shell starts, since generating it runs the command. zsh, with the script saved as `_game` in a directory on `$fpath`, which compinit registers for both commands, in `~/.zshrc`: ```zsh fpath=(~/.zfunc $fpath) autoload -Uz compinit && compinit ``` After replacing a script written before it completed `nsgo game`, delete `~/.zcompdump` so compinit reads the new registration. bash, in bash-completion's directory, which loads a completion the first time its command is completed, so the script is saved under both names; without bash-completion, source the file from `~/.bashrc`: ```sh mkdir -p ~/.local/share/bash-completion/completions go tool game completion bash > ~/.local/share/bash-completion/completions/game ln -s game ~/.local/share/bash-completion/completions/nsgo ``` fish, in its completions directory, which loads a command's completions from the file named after it: ```sh go tool game completion fish > ~/.config/fish/completions/game.fish ln -s game.fish ~/.config/fish/completions/nsgo.fish ``` Leave out the `nsgo` link when `nsgo` has a completion of its own there. To type `game` alone, install the command with `go install github.com/nsgo-dev/game/cmd/game@latest`, or define `game` as a shell function that runs `go tool game`, which keeps the version a module's `go.mod` pins inside the module: `game() { go tool game "$@"; }` in zsh and bash, and `function game; go tool game $argv; end` in fish. --- Source: http://nsgo.games/docs/cli-reference/ # Command Reference Every subcommand of `go tool game` (or `go run github.com/nsgo-dev/game/cmd/game@latest` outside a project), with its usage line and flags, generated from the commands' definitions so it always matches `game help`. [Command Line](http://nsgo.games/docs/cli/) shows how to add the command as a tool, what each subcommand is for and how to set up shell completion. ## game pack Pack a folder of PNG images into sprite atlas pages and TexturePacker JSON for sprite.LoadAtlas. ```sh go tool game pack [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-extrude int` | | edge pixels extruded around each frame | | `-in string` | | input directory of PNG images (required) | | `-max-height int` | `2048` | maximum atlas page height in pixels | | `-max-width int` | `2048` | maximum atlas page width in pixels | | `-name string` | `atlas` | base file name for atlas pages | | `-out string` | `.` | output directory for packed atlas PNG and JSON files | | `-padding int` | `1` | transparent pixels between adjacent frames | | `-scale int` | `1` | atlas scale written to meta.scale | | `-trim` | `true` | trim transparent borders around input images | ## game dlc Build and verify signed downloadable-content packs. ```sh go tool game dlc [flags] build|verify [flags] file ``` | Flag | Default | Description | | --- | --- | --- | | `-key string` | | Ed25519 public key for verify, as hex or base64 | | `-out string` | `dist/packs` | directory for the ZIP and manifest | | `-root string` | `resources` | directory of built assets to include | | `-url string` | | base URL written into manifest entries | ## game sprite Turn a directory of PNG frames or a GIF into a keyed, looped and anchored sprite atlas with an animation clip. ```sh go tool game sprite [flags] frames ``` | Flag | Default | Description | | --- | --- | --- | | `-anchor string` | `bottom-center` | where each frame's subject sits in the shared cell: bottom-center or center | | `-despill float` | | strength from 0 to 1 of removing the key colour's tint from edge pixels | | `-fps float` | `12` | clip frame rate | | `-height int` | | nearest-neighbor output height, with -width (0 keeps the source size) | | `-in string` | | directory of PNG frames, read in name order, or an animated GIF (required) | | `-key string` | | chroma key colour as #rrggbb; empty keeps the frames' own alpha | | `-loop` | `true` | make the clip loop | | `-max-frames int` | | most frames -seam keeps (0 for no limit) | | `-min-frames int` | `2` | fewest frames -seam keeps | | `-name string` | `animation` | base name of the atlas, its frames (\\_000, ...) and the clip | | `-out string` | `.` | output directory for the atlas PNG and JSON and the animation clip | | `-padding int` | `1` | transparent pixels between atlas frames | | `-seam` | | keep only the run of frames whose end best matches its start, dropping a duplicate end frame | | `-softness int` | `16` | width of the alpha ramp above -tolerance | | `-tolerance int` | `32` | RGB distance from -key at or below which a pixel becomes transparent | | `-width int` | | nearest-neighbor output width, with -height (0 keeps the source size) | ## game audio Normalize, resample and convert a WAV file to WAV, AAC or MP3. ```sh go tool game audio [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-bitrate int` | `128` | target bitrate in kbps for aac and mp3 output | | `-channels int` | | target channel count: 1 (mono), 2 (stereo), or 0 (keep input) | | `-format string` | `wav` | output format: wav, aac, or mp3 | | `-in string` | | input WAV file path (required) | | `-out string` | | output audio file path (required) | | `-peak-db float` | | normalize peak amplitude to this level in dBFS (e.g. -1) | | `-rate int` | | target sample rate in Hz (0 keeps input rate) | | `-rms-db float` | | normalize RMS loudness to this level in dBFS with soft-clip protection (e.g. -14) | ## game manifest Generate a typed Go asset manifest from a directory of assets, so a missing asset fails the build. ```sh go tool game manifest [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-check` | | verify that -out is up to date without modifying it | | `-embed` | | emit //go:embed directives instead of URI references | | `-embed-dir string` | | optional directory prefix prepended to //go:embed patterns | | `-in string` | `assets` | input assets directory | | `-out string` | | output Go file path (writes to stdout when empty) | | `-pkg string` | `assets` | Go package name for the generated file | | `-prefix string` | `asset:` | URI prefix prepended to each asset path | | `-resources` | | scan resources/ (unless -in is set) and emit "asset:" URI references for app resources instead of //go:embed | ## game tex Encode a PNG or JPEG texture into a KTX2 container as BC1, BC3, BC7, ETC2, ETC2 RGBA, ASTC 4x4, UASTC or RGBA8, with optional mipmaps. ```sh go tool game tex [flags] [input.png|input.jpg] ``` | Flag | Default | Description | | --- | --- | --- | | `-format string` | `rgba8` | output format: bc1, bc3, bc7, etc2, etc2-rgba, astc4x4, uastc, or rgba8 | | `-in string` | | input PNG/JPEG file path (alternative to the positional argument) | | `-mipmaps` | | generate full mipmap chain down to 1x1 | | `-normal` | | derive a tangent-space normal PNG from the input | | `-o string` | | shorthand for -out | | `-out string` | | output .ktx2 path (defaults to the input path with a .ktx2 extension) | | `-roughness` | | derive a roughness PNG from the input | | `-seamless-check` | | check wrap seams and fail when the edge ratio exceeds 1.3 | | `-seamless-fix` | | repair wrap seams and write a PNG output | | `-srgb` | | encode as sRGB with linear-light mipmap filtering | ## game editor Open the scene editor on a project or a YAML scene, and an animation clip on one of its objects, with the project's own editor command when it has one, or on the start screen when none is named. ```sh go tool game editor [flags] [project-dir | game.yaml | scene.yaml] [clip.animation.yaml [object-id]] ``` | Flag | Default | Description | | --- | --- | --- | | `-library string` | | show the library panel, which installs packs into the open project, for this library index: an https URL such as https://raw.githubusercontent.com/nsgo-dev/game/main/library/index.yaml, an index file, or a directory holding index.yaml | ## game mcp Serve the editor's MCP tools on stdio, run \`mcp install\` to configure Claude Code and Codex for this project, print an agent setup prompt with \`mcp prompt\`, or run \`mcp selftest\` with a YAML evidence report. ```sh go tool game mcp [flags] [install|prompt|selftest] ``` | Flag | Default | Description | | --- | --- | --- | | `-host string` | | with prompt: the agent the setup prompt is for, claude, codex or other (default other) | | `-output string` | `release-check.yaml` | selftest evidence YAML path | | `-project string` | `.` | the project: its directory, a directory inside it, or its game.yaml | ## game release Build the game's release packages for macOS, Windows, Linux, web, iOS and Android, or game.yaml's export presets, in one run of nsgo build, with a credits file of its assets' licenses. ```sh go tool game release [flags] [dir] ``` | Flag | Default | Description | | --- | --- | --- | | `-channel channel` | | the channel the packages are handed out through: direct, store, steam or none (default: nsgo.yaml's updates.channel) | | `-dry-run` | | print the nsgo build command instead of running it | | `-jobs int` | | how many targets build at once (default: nsgo's) | | `-output directory` | | the output directory (default: game.yaml's export.output, else nsgo.yaml's build.output) | | `-release-notes file` | | a Markdown file of the release's notes for the update prompts | | `-strict` | | fail with an error instead of warning when building an experimental target platform | | `-target targets` | | comma-separated nsgo build targets (default: game.yaml's export presets, else macos,windows,linux,web,ios,android, or macos,windows,linux for the steam channel) | ## game capture Check the store screenshots and covers a YAML capture plan describes against its scenes, recordings and sizes. ```sh go tool game capture [flags] [project] ``` | Flag | Default | Description | | --- | --- | --- | | `-out directory` | `store/media` | media directory relative to the project | | `-plan file` | `store/capture.yaml` | capture plan file relative to the project | | `-shot shot` | | check only the named shot | ## game replay Check the input recordings under the directories and play them headless through their replay tests, failing on a mismatch. ```sh go tool game replay [flags] [directory ...] ``` | Flag | Default | Description | | --- | --- | --- | | `-run regexp` | `Replay` | run the tests matching this regexp, as go test's -run: the tests that play the recordings | ## game playtest Validate playtest.yaml, run headless bot playtests with replays, write a YAML report and fail on missed goals. ```sh go tool game playtest [flags] [directory ...] ``` | Flag | Default | Description | | --- | --- | --- | | `-check` | | validate playtest.yaml without running any tests | | `-config file` | `playtest.yaml` | the playtest configuration file to validate and run | | `-count int` | | override runs.count in playtest.yaml when positive | | `-out file` | `playtest.report.yaml` | write the YAML playtest report to this file | | `-recordings directory` | `playtest-recordings` | write per-seed .replay.yaml recordings into this directory (empty skips writing files) | | `-run regexp` | `Playtest` | run the tests matching this regexp, as go test's -run: the tests that call playtest.RunTest | | `-seeds seeds` | | override runs.seeds with a comma-separated list of uint64 seeds | ## game bench Run the benchmarks headless and fail when one regresses past its stored baseline, or update the baseline. ```sh go tool game bench [flags] [directory ...] ``` | Flag | Default | Description | | --- | --- | --- | | `-baseline file` | `benchmarks/baseline.yaml` | the baseline file to check against, or to write with -update | | `-bench regexp` | `.` | run the benchmarks matching this regexp, as go test's -bench | | `-benchtime duration` | `200ms` | run each benchmark for this duration, or Nx times, as go test's -benchtime | | `-count times` | `3` | run the benchmarks this many times and compare each one's median | | `-in file` | | read benchmark results from this file of go test -bench output instead of running the benchmarks | | `-strict` | | fail when a measured benchmark has no baseline entry | | `-update` | | write the measured medians to the baseline instead of checking them | ## game size Measure a WebAssembly, Android AAB or APK, or iOS IPA package and fail when it exceeds its size budget. ```sh go tool game size [flags] [package] ``` | Flag | Default | Description | | --- | --- | --- | | `-abi-budget-mb MiB` | | override the per-ABI native library budget in MiB for Android packages (> 0) | | `-budget file` | | path to the budget JSON file (for wasm defaults to benchmarks/web-budget.json; for mobile packages defaults to the platform's built-in budget) | | `-budget-mb MiB` | | override the total package size budget in MiB (> 0) | | `-file archive` | | path to the package archive (.aab, .apk, .ipa, or .wasm); may also be passed as the positional argument | | `-json` | | output the report as JSON | | `-kind kind` | | package kind: aab, apk, ipa, or wasm (inferred from the file extension when omitted, defaults to wasm) | | `-markdown` | | output the report as a Markdown summary | | `-wasm file` | | optional path to an already built .wasm file; if empty in wasm mode, builds the budget's target with GOOS=js GOARCH=wasm | ## game new Create a game project in a directory from a template, with its go.mod requiring the game layer and the game and nsgo tools. ```sh go tool game new [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-from string` | | copy the game project in this directory, such as an example, an existing project or a template pack, instead of starting from -template; machine-local files are left out | | `-json` | | with -list, print the template manifests as a JSON array instead | | `-list` | | list the templates, each with a line describing it, instead of creating a project | | `-module string` | | the module path in go.mod (default: the name in lower case with its words joined by -) | | `-name string` | | the game's display name in game.yaml and nsgo.yaml: letters, digits, spaces, - and \_ (default: the directory's name) | | `-template string` | `starter` | the template to start from: starter, action3d, cards2d, coop2d, fighting2d, fps3d, idle, tap2d, platformer2d, puzzle2d, racing3d, rhythm, roguelike2d, rpg2d, rts2d, shmup2d, towerdefense2d, visualnovel; -list describes each | | `-version string` | | the version of github.com/nsgo-dev/game to require, such as v0.4.0, a commit or latest (default: this command's own version, or main for a development build) | ## game project Check a project's game.yaml, rewrite it in canonical form, write the fields it owns into nsgo.yaml, or print its export presets' build targets. ```sh go tool game project [flags] check|fmt|sync|targets [dir] ``` | Flag | Default | Description | | --- | --- | --- | | `-check` | | with fmt, fail unless game.yaml is in canonical form, and with sync, fail unless nsgo.yaml agrees with game.yaml, without rewriting either | ## game dev Run the game with nsgo dev, reloading its assets in the running game when they are saved. ```sh go tool game dev [flags] [dir] [nsgo dev flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-assets string` | `resources` | the directory, relative to the project directory, that the running game watches and its assets.Manager reads "asset:" URIs from, given to the game as hotreload.DevAssetsDir | | `-automation` | | enable NSGo automation so the editor and nsgo mcp can inspect and drive the running game | | `-debug` | | run the game under the Delve debugger (native target only) and print a ready VS Code or GoLand attach configuration when Delve listens | | `-fps` | | show NSGo's performance monitor in the running game | | `-scene string` | | start the game at this scene path relative to the project root, given to the game as hotreload.DevScene | | `-target string` | | the nsgo dev target, nsgo.yaml's dev.target when empty; assets reload on native and tui | ## game check Check the scenes, Tiled and LDtk maps and sprite atlases under a directory, and the files they refer to. ```sh go tool game check [flags] [dir] ``` | Flag | Default | Description | | --- | --- | --- | | `-in string` | | directory to check (alternative to the positional argument; defaults to the current directory) | ## game doctor Check a project module, game.yaml and nsgo.yaml before building or releasing. ```sh go tool game doctor [flags] [dir] ``` | Flag | Default | Description | | --- | --- | --- | | `-json` | | write findings as JSON | ## game assets Pack atlases, encode textures, convert audio, bake fonts, pack models and generate the manifest from game.yaml, rebuilding only what changed. ```sh go tool game assets [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-check` | | list the targets that are out of date without building them, and fail if there are any | | `-force` | | rebuild every target, even those the cache says are up to date | | `-in string` | `game.yaml` | project file whose assets section declares the targets | | `-resources` | | write asset outputs into resources/ and emit "asset:" URIs in the manifest instead of //go:embed | ## game generate Write a new component, system, scene or prefab into a game project: its Go code and a test, the scene file of a scene or prefab, and its registration; or the project's editor command, which checks the project's components and builds in its editor plugins. ```sh go tool game generate [flags] component|system|scene|prefab | editor ``` | Flag | Default | Description | | --- | --- | --- | | `-autoload` | | for a scene, also add it to the scenes game.yaml autoloads | | `-in string` | `.` | the game's project directory, which holds its game.yaml and the Go package the code is written into | | `-main` | | for a scene, also add it to the scenes game.yaml autoloads and make it the main scene | ## game mv Move or rename a file, directory, or text key (-text-key) and rewrite every reference to it, keeping the project index up to date. ```sh go tool game mv [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-dry-run` | | print what would change without changing anything | | `-in string` | | project directory (defaults to the nearest directory at or above the working directory holding game.yaml, nsgo.yaml or go.mod) | | `-text-key` | | rename a localization text key across screen files and YAML string tables instead of moving a file | ## game index Give every scene and resource file a uid, point references at files moved without the tools, and write the project index. ```sh go tool game index [flags] [dir] ``` | Flag | Default | Description | | --- | --- | --- | | `-check` | | print what would change and fail when the index is out of date | | `-dry-run` | | print what would change without changing anything | | `-in string` | | project directory (alternative to the positional argument; defaults to the nearest directory at or above the working directory holding game.yaml, nsgo.yaml or go.mod) | ## game library Find asset, editor plugin and template packs in a library and install them into a project, remove them, or print a pack's digest for the library's index. ```sh go tool game library [flags] list [words] | install ... | remove ... | digest ``` | Flag | Default | Description | | --- | --- | --- | | `-dir string` | | install the pack into this directory of the project instead of the one it is installed in or its manifest names (one pack at a time) | | `-index string` | `https://raw.githubusercontent.com/nsgo-dev/game/main/library/index.yaml` | the library's index: an https URL, an index file, or a directory holding index.yaml | | `-kind string` | | list only packs of this kind: asset, plugin, template | | `-project string` | `.` | the project directory holding game.yaml, which install and remove change and list marks installed packs from | ## game credits List every asset's author and license from its import settings sidecar as the credits file game release ships, failing when an asset has none. ```sh go tool game credits [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-in string` | `game.yaml` | project file whose assets section names the assets | | `-out file` | | the credits file to write (default: print it) | ## game pixelfx Render a pixelfx effect, or the effect acted out, to a PNG sprite sheet and Aseprite JSON for sprite.LoadAtlas. ```sh go tool game pixelfx [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-act` | | render the effect acted out: the stock character performing it, with its target | | `-flip` | | mirror the effect | | `-fps int` | | frames per second (default: the effect's own, or 60 acted out) | | `-list` | | list the effects and their options instead of rendering one | | `-name string` | | base file name and animation tag (default: the effect's name, such as torch) | | `-out directory` | `.` | the directory to write \.png and \.json into | | `-set name=value` | | set one of the effect's options as name=value, such as seed=4 or palette=#102,#215,#fff; repeat it for more | ## game navmesh Bake a scene's glTF level geometry into a navigation mesh per agent type of game.yaml's navigation section, written to the file the scene's navMesh names. ```sh go tool game navmesh [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-in string` | | project directory, whose game.yaml holds the navigation settings and from which the scene's paths start (defaults to the nearest directory at or above the working directory holding game.yaml, nsgo.yaml or go.mod) | | `-out file` | | navigation mesh file to write (defaults to the file the scene's navMesh names) | ## game merge Merge scene YAML files object by object for Git, or set up and check the Git merge driver in a project. ```sh go tool game merge [flags] [path] | -setup [dir] | -check [dir] ``` | Flag | Default | Description | | --- | --- | --- | | `-check` | | verify that merge.nsgo-scene.driver is configured when .gitattributes names nsgo-scene | | `-conflict-out string` | | file to write the YAML conflict report to instead of overwriting the output file on conflict | | `-out string` | | file to write the merged scene or conflict report to (default: overwrite \ in place, as Git expects) | | `-setup` | | register the nsgo-scene merge driver in local Git config and ensure .gitattributes has LF line-ending, binary media, and scene merge rules | ## game schema Write the project's scene JSON Schema, including its registered components and plugins, or the built-in scene schema when the project has no editor command of its own. ```sh go tool game schema [flags] [project-dir | game.yaml] ``` | Flag | Default | Description | | --- | --- | --- | | `-out file` | | write the JSON Schema to file instead of stdout | ## game net Decode packet captures layer by layer using wire schemas, or print traffic statistics per message type and peer. ```sh go tool game net [flags] decode [flags] | stats [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-format string` | | output format (decode: yaml or json, default yaml; stats: text, yaml, or json, default text) | | `-resolve-deltas` | | track per-peer replication baselines so SnapshotDelta frames also print full resulting entity states (decode only) | | `-schema string` | | directory or \*.wire.yaml file of game-defined wire schemas (for example, custom EntityState.Props) | ## game wire Generate Go and TypeScript codecs from \*.wire.yaml schemas, or check that the committed ones are current. ```sh go tool game wire [flags] [schema.wire.yaml ...] ``` | Flag | Default | Description | | --- | --- | --- | | `-check` | | verify that generated files in -out are up to date without writing | | `-in file` | `.` | input \*.wire.yaml file or directory containing \*.wire.yaml files | | `-lang language` | `go` | target language for code generation: go or ts | | `-out directory` | | output directory (or .go/.ts file for a single input); defaults to the input directory | | `-pkg name` | | override the Go package name (defaults to each schema's package field) | | `-self` | | omit the pkg/online/netplay/wire runtime import (used when generating Go inside pkg/online/netplay/wire) | ## game admin Add an operator to an operators file, set its password, enroll it for TOTP sign-in, or revoke its bearer tokens. ```sh go tool game admin [flags] operator add|passwd|totp|revoke-tokens [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-file file` | `operators.yaml` | the operators file to edit; its TOTP secrets are in the file of the same name ending in .totp.yaml | ## game version Show the game and Go versions. ```sh go tool game version [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-json` | | write machine-readable JSON | ## game completion Write a shell completion script for zsh, bash or fish. ```sh go tool game completion [flags] zsh|bash|fish ``` No flags. ## game help Show the commands, or one command's flags. ```sh go tool game help [command] ``` No flags. --- Source: http://nsgo.games/docs/a11y/ # a11y `game/a11y` provides accessibility building blocks built on NSGo's public API: live dialogue and directional SFX captions, color-blind-safe palettes with CVD simulation and WCAG contrast helpers, persisted assist options, and screen-reader-ready native menus. For end-to-end wiring with `gameui.SettingsMenu`, `postfx`, `sound`, and `input.TouchControls`, a guideline-by-guideline map against the Game Accessibility Guidelines and Xbox Accessibility Guidelines, a pre-release checklist, and Apple App Store Accessibility Nutrition Labels, see the [Accessibility Guide](http://nsgo.games/docs/accessibility-guide/). Templates should mount `gameui.FirstLaunchSettings` before their first sound. It turns captions on by default, persists completion in the shared settings store, and leaves the full Accessibility tab available through **More options**. Keep the same store connected to `a11y.NewAssistFromSettings` so captions, reduced motion, flash reduction, text scale, and input assists apply before gameplay begins. ```go import "github.com/nsgo-dev/game/pkg/a11y" ``` ## Persisted assist options (`Assist`) `NewAssistFromSettings(cx, store)` backs `*Assist` with the game's shared `*save.DefaultSettingsStore` (`save.Settings.Accessibility`) so `gameui.SettingsMenu`, `CaptionsView`, `AccessibleMenu`, and `postfx.Flash` / `postfx.Shake` stay in sync automatically whenever settings are saved. Wire `ApplyAccessibility: assist.ApplySettings` on `save.SettingsTargets` to also preview un-saved `SettingsMenu.Apply()` edits immediately: ```go store := save.NewStorageSettingsStore(cx.Storage(), "mygame") assist := a11y.NewAssistFromSettings(cx, store) // In game.Loop.Update, scale simulation dt by GameSpeed (0.25..2.0): loop := &game.Loop{ Update: func(dt time.Duration) { sim.Step(assist.ScaleDT(dt)) }, } ``` Any legacy `"a11y.assist.*"` keys left in `cx.Storage()` by the deprecated `NewAssist(cx, key)` constructor are migrated once into `store` and removed on startup; use `MigrateLegacyAssist(cx.Storage(), oldPrefix, store)` if migrating a custom legacy prefix. `ParseColorVision` accepts both `"normal"` and `"none"` for `VisionNormal`. Available persisted options on `*Assist` (and snapshot struct `AssistOptions` via `Snapshot()` / `Apply(opts)` / `Reset()`): | Option | Range / Default | Notes | | --- | --- | --- | | `GameSpeed` / `ScaleDT` | `0.25`–`2.0` (`1.0`) | Scales gameplay `dt` without changing display refresh rate. | | `ReduceMotion` | `bool` | Defaults to `cx.Env().ReduceMotion()` when unset; explicit `SetReduceMotion(false)` overrides the OS. | | `ReduceFlashes` | `bool` | Reduces full-screen flashes independently of `ReduceMotion`: passed to `postfx.FlashConfig.ReduceFlashes`, it turns them into low-contrast tints. | | `ScreenShake` | `0.0`–`1.0` (`1.0`) | Camera shake intensity multiplier (`0` disables shake). | | `HighContrast` | `bool` | Defaults to `cx.Env().IncreaseContrast()` when unset; switches `assist.Palette()` to `VisionHighContrast`. | | `ColorVision` | `ColorVision` | Selects `VisionNormal`, `VisionProtanopia`, `VisionDeuteranopia`, `VisionTritanopia`, or `VisionHighContrast`. | | `ColorBlindSeverity` | `0.0`–`1.0` (`1.0`) | Scales the strength of `ColorVisionFilter`; defaults to `1.0` when unset. | | `TextScale` | `0.5`–`3.0` (`1.0`) | Defaults to `cx.Env().FontScale()` (clamped) when unset; multiplier read by `CaptionsView` and `AccessibleMenu`. | | `Invincibility`, `AutoAim` | `bool` | Gameplay assist flags for your combat layer. | | `HoldToToggle` | `bool` | Convenience switch that fills `input.Assists.Toggle` from all toggle-eligible actions declared on `input.Actions` when applied via `ApplyToActions` / `ApplyToPlayers`. | | `InputAssists` | `input.Assists` | Per-action `Toggle` and `MashToHold` lists plus `MinPress` (slow keys) and `AcceptDelay` (bounce keys) persisted in `save.Settings.InputAssists`. | | `CaptionsEnabled`, `DialogueCaptionsEnabled`, `ChatterCaptionsEnabled`, `SFXCaptionsEnabled` | `bool` | Master speech captions switch plus per-kind toggles for main dialogue, background chatter, and sound/music cues. | | `CaptionSettings` (`CaptionBackground`, `CaptionBackgroundOpacity`, `CaptionTextColor`, `CaptionSpeakerColors`, `CaptionSize`) | `save.CaptionSettings` | Player-set caption backdrop color & opacity (`0`–`1`), text color, per-speaker name coloring, and size preset (`small`–`xlarge`). | When `AutoAim` is enabled, use `input.AimAssist` from the fixed-step update. It provides deterministic 2D and 3D friction, magnetism, optional snap, target priorities, and a game-owned line-of-sight callback. `Strength` is the player-controlled intensity from 0 (off) to 1 (full). `Assist.Reset()` resets only `save.Settings.Accessibility` and `save.Settings.InputAssists` back to defaults and OS fallbacks, preserving Audio, Display, Bindings, Locale, and Custom sections in the shared store. ## Player motor assists `Assist` persists `input.Assists` in `save.Settings.InputAssists` and bridges both `InputAssists` and `HoldToToggle` onto `input.Actions` (or `input.Players`) via `ApplyToActions` / `ApplyToPlayers`. Wire `ApplyInputAssists: assist.ApplyInputAssists` on `save.SettingsTargets` alongside `ApplyAccessibility: assist.ApplySettings` so `gameui.SettingsMenu`'s Controls tab previews and persists motor assists live: ```go cx.Effect(func() { assist.ApplyToActions(actions) }) ``` When `HoldToToggle()` is enabled, `ApplyToActions` automatically merges `actions.ToggleableActions()` (from `game.yaml` `assist: {toggle: true}` or `SetActionAssist`) into `input.Assists.Toggle`, so gameplay hold actions toggle without ever latching menu actions. See [input](http://nsgo.games/docs/input/#player-motor-assists) for fixed-step evaluation, pause release, and replay determinism. ## Live captions (`CaptionTrack` & `CaptionsView`) Queue timed dialogue (with optional delivery qualifiers), ambient chatter, directional SFX, music cues, and important alerts on a `CaptionTrack`, step it on `game.Loop`, and render it as a native NSGo overlay with `CaptionsView`: ```go captions := a11y.NewCaptionTrack(cx) // When an explosion plays to the player's right (direction in [-1, 1]): if assist.SFXCaptionsEnabled() { captions.ShowSFXAt("Explosion", 0.8, 2500*time.Millisecond) } captions.ShowDialogueWithQualifier("Guide", "on radio", "Watch the bridge ahead.", 3*time.Second) captions.ShowChatter("Scout", "Did you hear that?", 2500*time.Millisecond) // In game.Loop.Update: captions.Update(dt) // In your root Stack view: a11y.CaptionsView(cx, captions, a11y.CaptionStyle{Assist: assist}) ``` - **Formatting & qualifiers**: `Caption.Format()` formats speakers (`"Guide: ..."`), optional delivery qualifiers (`"Guide (on radio): ..."`), SFX brackets (`"[Explosion]"`), directional stereo indicators (`"[<] [Explosion]"` for left, `"[Explosion] [>]"` for right, added when `|Direction| >= 0.25`), important cues (`"! ..."`), and music cues (`"♪ ..."`). No directional indicator is added when `|Direction| < 0.25`. `ShowDialogue` remembers the last speaker/qualifier and suppresses repeated speaker names until a different speaker/qualifier appears or silence exceeds `CaptionTrack.SpeakerRepeatGap` (default `DefaultSpeakerRepeatGap` = `5s`; set `< 0` to always show speaker names). Dismiss entries early with `Dismiss(id)` or `Clear()`. - **Line wrapping & two-line limit**: `CaptionsView` wraps lines at word boundaries (and by character for CJK) to `CaptionStyle.MaxChars` (default `DefaultCaptionMaxChars` = `40`) and caps total simultaneous visible lines to `CaptionStyle.MaxLines` (default `DefaultCaptionMaxLines` = `2`), dropping older lines first. - **Player styling & speaker colors**: when `CaptionStyle.Assist` is set, `CaptionsView` reads `save.CaptionSettings` for background color (`black`, `gray`, `blue`, `white`, or `#rrggbb`), background opacity (`0.0`–`1.0`), text color (`white`, `yellow`, `cyan`, `green`, `black`, or `#rrggbb`), size preset (`small`, `medium`, `large`, `xlarge`), per-kind filtering (`Dialogue`, `Chatter`, `Sounds`), and per-speaker name coloring (`SpeakerColors`, using `CaptionStyle.SpeakerColors` overrides or deterministic CVD-safe colors from `PaletteFor`). - **Automatic sources**: `sound.Effect.SetCaption` with `CaptionEmitter` captions positional sounds in the direction the mixer pans them, without repeating a label within `MinInterval` ([sound](http://nsgo.games/docs/sound/#captions-for-positional-sounds)), and `cutscene.CaptionBridge` shows timeline dialogue for as long as each line plays ([cutscene](http://nsgo.games/docs/cutscene/#captions-for-dialogue)). Customize the live region's accessible name and cue prefixes via `CaptionStyle.RegionLabel` (default `"Captions"`), `CaptionStyle.ImportantPrefix` (default `"! "`), and `CaptionStyle.MusicPrefix` (default `"♪ "`), or fill them from an `l10n.Catalog` / `l10n.Localizer` with `CaptionStyleFromCatalog` / `CaptionStyleFromLocalizer`. ## Mono audio and stereo balance For players with hearing in one ear, [`game/sound`](http://nsgo.games/docs/sound/#mono-audio-and-leftright-balance), `game/save`, and `game/gameui` provide mono voice centering and a left/right balance control: - **`save.AudioSettings`**: `Mono` (`*bool`, `nil` by default to follow the platform's mono audio switch) and `Balance` (`float64` in `[-1, 1]`, `0` centered) persist with player settings and are applied to `*sound.Mixer` by `save.Apply` (`SettingsTargets.Sound`). - **`sound.Mixer`**: `SetMono(bool)` / `FollowSystemMono()` and `SetBalance(float32)` center every started voice to pan `0` under mono — preserving distance, rear, and cone attenuation — and offset stereo pan by `Balance` (clamped to `[-1, 1]`) otherwise. `Listener2D.Pan` and `Listener3D.Pan` still return the true spatial direction, so passing that pan to `CaptionTrack.ShowSFXAt` keeps directional caption cues intact even under mono. - **`gameui.SettingsMenu`**: the Audio tab includes **Mono Audio** (`System Default` / `On` / `Off`) and **Balance** rows wired directly to `save.AudioSettings`. - **Current NSGo v0.3.4 limits**: stereo audio assets (such as stereo music or ambience tracks) keep their own channels until NSGo supports output down-mixing (`nsgo-dev/nsgo#2676`), and automatic tracking of the OS mono audio toggle takes effect once NSGo exposes `Env.MonoAudio` (`nsgo-dev/nsgo#2677`). ## Color-blind palettes, frame filter & CVD preview `PaletteFor(mode)` returns an Okabe-Ito / Wong-grounded semantic `Palette` (`Player`, `Ally`, `Enemy`, `Hazard`, `Pickup`, `Neutral`, `Background`, `Foreground`, `Highlight`, `Accent`). Use `Simulate`, `SimulateAt`, `Daltonize`, `ColorDistance`, `ContrastRatio`, and `EnsureContrast` in tests or runtime UI theming: ```go pal := assist.Palette() simEnemy := a11y.Simulate(pal.Enemy, a11y.VisionDeuteranopia) ratio := a11y.ContrastRatio(pal.Foreground, pal.Background) readable := a11y.EnsureContrast(accentColor, pal.Background, 4.5) _, _, _ = simEnemy, ratio, readable ``` ### Whole-frame color-vision filter Games with hand-authored sprites, tilemaps, and particles that do not read `a11y.Palette` directly can still honor the player's `ColorBlindMode` and `ColorBlindSeverity` (`Color-Blind Mode` and `Color-Blind Strength` in `gameui.SettingsMenu`) by appending `a11y.ColorVisionFilter` to their [`postfx.Chain`](http://nsgo.games/docs/postfx/#color-vision-filter): ```go if filter, ok := assist.ColorVisionFilter(); ok { post = postfx.MustCompile(postfx.VignetteEffect(), filter) } ``` - `a11y.ColorVisionFilter(settings)` (and `assist.ColorVisionFilter()`) returns `(postfx.Effect, bool)` configured for daltonization correction (`correct: true`) from `save.AccessibilitySettings.ColorBlindMode` and `EffectiveColorBlindSeverity()`, or `false` when the mode is `"none"` or severity is `0`. - `a11y.ColorVisionSimulation(mode, severity)` returns the matching deficiency simulation effect (`correct: false`) for developer previews and tooling. ### Previewing in the editor and testing with `gametest` - **Editor**: open the **Overlays** popover in the 2D scene viewport or the **Color Vision & Contrast** panel beside the text-width table in **HUD & menu layout** to switch between Normal, Protanopia, Deuteranopia, and Tritanopia. The scene viewport applies `postfx.ColorVisionEffect` live over the frame, and the HUD layout simulates every device frame and updates each node's WCAG contrast ratio live. - **Automated tests (`pkg/gametest`)**: pass `ColorVision` on `gametest.RenderOptions` to render goldens under deficiency simulation (or daltonization with `ColorVisionCorrect: true`), and assert minimum separation between gameplay-critical colors or rendered screen regions: ```go sim := gametest.RenderOps(128, 64, ops, gametest.RenderOptions{ ColorVision: a11y.VisionDeuteranopia, }) gametest.AssertColorDistinguishable(t, a11y.VisionDeuteranopia, pal.Player, pal.Enemy, 40) gametest.AssertRegionsDistinguishable(t, frame, heroRect, enemyRect, a11y.VisionProtanopia, 40) _ = sim ``` ### Design guidance: never rely on color alone A whole-frame filter helps existing art, but **do not convey essential gameplay information by color alone** (Game Accessibility Guidelines; XAG 103). Pair every color cue with a secondary visual channel — silhouette, icon, pattern, outline, or text label: - **Match & puzzle tiles (`template/puzzle2d`)**: pair each gem or block color with a distinct inner symbol or shape (triangle, diamond, circle, star) so players can match pieces even in monochrome. - **Units, projectiles & hazards (`template/shmup2d`, `template/towerdefense2d`)**: give player and enemy shots different shapes and sizes (for example, crisp elongated bolts vs. ringed orbs), and distinguish tower or enemy classes by silhouette and status icon rather than tint alone. - **Cards, meters & pickups (`template/cards2d`, `template/platformer2d`)**: pair suit or rarity colors with suit glyphs, border patterns, and numeric labels, and mark low-health or active states with icons or motion cues in addition to hue changes. ## Screen-reader menus (`AccessibleMenu`) Set `ScanEnabled` with `ScanInterval` to let one switch cycle enabled menu items. The `ScanSelectKey` key activates the highlighted item, and `ScanLoops` pauses after a configured number of passes. Render pause, settings, and assist menus with native ARIA/accessibility roles (`RoleMenu`, `RoleMenuItem`, `RoleMenuItemCheckbox`), full keyboard navigation (`Up`/`Down`/`Home`/`End`/`Return`/`Space`/`Escape`), and `cx.Announce` screen-reader feedback: ```go a11y.AccessibleMenu(cx, a11y.MenuProps{ Label: "Assist Options", Assist: assist, OnClose: closeMenu, Items: []a11y.MenuItem{ { ID: "reduce-motion", Label: "Reduce Motion", Checked: assist.ReduceMotion, OnSelect: func() { _ = assist.SetReduceMotion(!assist.ReduceMotion()) }, }, { ID: "game-speed", Label: "Game Speed", Value: func() string { return fmt.Sprintf("%d%%", int(assist.GameSpeed()*100)) }, OnSelect: cycleGameSpeed, }, }, }) ``` When focus moves to an item whose role natively exposes `Checked` (`RoleMenuItemCheckbox`, `RoleMenuItemRadio`, `RoleCheckbox`, `RoleSwitch`, `RoleRadio`), `AccessibleMenu` relies on the platform's own checked state instead of repeating the checked/unchecked word; toggle activation and the initial mount announcement still announce the item's state. ## Localization (`MenuText` & `l10n`) `pkg/a11y` ships embedded English (`en`) and Simplified Chinese (`zh`) `l10n` YAML string tables. Load them directly with `DefaultCatalog()`, or merge them into your game's catalog before loading your own overrides with `LoadDefaultCatalog(cat)`. Pass `MenuText` on `MenuProps.Text` (unset fields inherit from `DefaultMenuText()`), or build it from an `*l10n.Catalog` or `*l10n.Localizer`: ```go cat := a11y.DefaultCatalog() loc := l10n.NewLocalizer(cx, cat) loc.SetLocale("zh-Hans") capStyle := a11y.CaptionStyleFromLocalizer(loc) capStyle.Assist = assist a11y.AccessibleMenu(cx, a11y.MenuProps{ Label: "辅助选项", Text: a11y.MenuTextFromLocalizer(loc), Items: items, }) ``` Documented `l10n` keys (also exported as `Key*` constants): | Key | Type | Placeholders | Default (`en`) | | --- | --- | --- | --- | | `a11y.menu.defaultLabel` | string | — | `Menu` | | `a11y.menu.items` | plural | `{count}` | one: `{count} item`, other: `{count} items` | | `a11y.menu.opened` | string | `{label}`, `{items}`, `{count}` | `{label} opened, {items}` | | `a11y.menu.openedWithItem` | string | `{label}`, `{items}`, `{count}`, `{item}` | `{label} opened, {items}. {item}` | | `a11y.menu.position` | string | `{item}`, `{index}`, `{count}` | `{item}, {index} of {count}` | | `a11y.menu.selected` | string | `{label}` | `{label} selected` | | `a11y.menu.closed` | string | `{label}` | `{label} closed` | | `a11y.menu.checked` | string | — | `checked` | | `a11y.menu.unchecked` | string | — | `unchecked` | | `a11y.menu.on` | string | — | `On` | | `a11y.menu.off` | string | — | `Off` | | `a11y.menu.separator` | string | — | `, ` | | `a11y.captions.regionLabel` | string | — | `Captions` | | `a11y.captions.importantPrefix` | string | — | `! ` | | `a11y.captions.musicPrefix` | string | — | `♪ ` | | `a11y.captions.bgBlack` / `bgGray` / `bgBlue` / `bgWhite` | string | — | `Black` / `Gray` / `Navy` / `White` | | `a11y.captions.textWhite` / `textYellow` / `textCyan` / `textGreen` / `textBlack` | string | — | `White` / `Yellow` / `Cyan` / `Green` / `Black` | | `a11y.captions.sizeSmall` / `sizeMedium` / `sizeLarge` / `sizeXLarge` | string | — | `Small` / `Medium` / `Large` / `Extra Large` | | `a11y.captions.previewSpeaker` / `previewQualifier` / `previewDialogue` / `previewChatterSpeaker` / `previewChatter` / `previewSFX` | string | — | Sample preview strings (`Guide`, `on radio`, `Watch the bridge!`, `Scout`, `Did you hear that?`, `Wind howling`) | ## Photosensitivity Every `postfx.Flash` runs at most three times in any rolling second, and a saturated-red flash color is desaturated to the gray of its luminance. Share one `postfx.FlashLimiter` between the full-screen flashes of a screen so that together they stay within three a second, and pass `assist.ReduceFlashes` to `postfx.FlashConfig.ReduceFlashes` so that the player's Reduce Flashes setting turns them into low-contrast tints; see [postfx](http://nsgo.games/docs/postfx/#photosensitivity). ## Text size `gameui` roots scale text up to 200% through `Root.TextScale` and `Theme.TextScale`. Pass the largest scale the game supports as `ScreenCheckOptions.TextScale` so `CheckScreen` reports localized text that overflows only at that size before shipping; see [gameui](http://nsgo.games/docs/gameui/#text-scale-textscale). --- Source: http://nsgo.games/docs/ability/ # ability `github.com/nsgo-dev/game/pkg/ability` runs gameplay abilities: costs, cooldowns, charges, cast and channel times and conditions, activated by [input](http://nsgo.games/docs/input/) actions and advanced one fixed [`game.Loop`](http://nsgo.games/docs/loop/) step at a time. ```go import "github.com/nsgo-dev/game/pkg/ability" ``` ## Ability sets Abilities are defined in a versioned YAML file: ```yaml version: 1 abilities: - id: fireball name: ability.fireball action: cast costs: - resource: mana amount: 20 cooldown: 2s castTime: 500ms conditions: [grounded, '!silenced'] - id: dash action: dash cooldown: 250ms charges: 3 recharge: 4s - id: drain action: drain trigger: hold costs: - resource: mana amount: 5 cooldown: 6s channelTime: 3s tickInterval: 500ms ``` | Field | Meaning | | --- | --- | | `id` | Unique within the set: ASCII letters, digits, `_`, `-` and `.`, at most 64 bytes | | `name` | Optional display name or localization key | | `action` | The input action that activates it; empty means only code activates it with `TryActivate` | | `trigger` | `press` (default) tries on the step the action is first pressed; `hold` tries on every step it is held and cancels the cast or channel when it is released | | `costs` | Resources one use spends, each resource once, with a positive `amount` | | `cooldown` | Shortest time between two uses, counted from the step a use takes effect; it applies even while charges remain | | `charges` | Uses stored, 1 when omitted, at most 99; more than one needs a `recharge` | | `recharge` | Time for one spent charge to come back; spent charges come back one after another | | `castTime` | Time spent casting before the ability takes effect | | `channelTime` | Time spent channeling after it takes effect | | `tickInterval` | How often a channel ticks; needs a `channelTime` and must not exceed it | | `conditions` | Names that must all hold to start and to keep casting or channeling; `!name` must not hold | Durations are Go duration strings (`500ms`, `1m30s`) from 0 to 24h. `ability.Parse` refuses unknown fields, duplicate keys and IDs, other versions and out-of-range values; `ability.Encode` writes the fields in a fixed order and durations in their canonical form (`1500ms` becomes `1.5s`), and `Parse` reads its output back to an equal `Set`. ## Caster A `Caster` runs one character's abilities. Make it with the set and the loop's rate, then call `Update` once per step after stepping the input: ```go set, err := ability.Parse(data) if err != nil { return err } hero, err := ability.NewCaster(set, 60) // the same Rate as game.Loop if err != nil { return err } hero.Resources = ability.Pool{"mana": 100, "stamina": 50} hero.Condition = func(name string) bool { switch name { case "grounded": return player.OnGround case "silenced": return player.Silenced } return false } hero.OnEvent = func(e ability.Event) { if e.Kind == ability.EventActivated && e.Ability == "fireball" { spawnFireball() } } loop := &game.Loop{Rate: 60, Update: func(dt time.Duration) { actions.Step() hero.Update(actions) }} ``` `Update` takes anything with `Pressed` and `JustPressed`, such as `*input.Actions`, a replay or a network input; `nil` advances timers without reading input. Code activates abilities with `TryActivate(id)`, which returns `ReasonOK` or the reason it did not: `ReasonUnknown`, `ReasonBusy`, `ReasonCooldown`, `ReasonNoCharges`, `ReasonCondition` or `ReasonCost`, checked in that order. `CanActivate(id)` returns the same reason without changing anything, for greying out a button. At most one ability casts or channels at a time. Its life is: 1. Activation checks the cooldown, charges, conditions and costs, and sends `EventStarted`. 2. The cast runs for `castTime`, nothing spent yet. A failing condition interrupts it (`EventInterrupted` with `ReasonCondition`), and `Cancel` stops it (`EventCanceled`), both spending nothing. 3. When the cast completes, the costs and a charge are spent, the cooldown starts and `EventActivated` is sent; this is where the game applies the effect. A cost that is no longer affordable interrupts it with `ReasonCost` instead. An ability with no cast time does this on the step it is activated. 4. A channel then runs for `channelTime`, sending `EventChannelTick` every `tickInterval` and `EventChannelEnded` at the end. Conditions, `Cancel` and releasing a `hold` action stop it early. `EventCooldownEnded` and `EventChargeRestored` report timers finishing. `OnEvent` may call `TryActivate` or `Cancel`, for example to chain a follow-up when an ability takes effect; the events that causes follow the current one. Events that happened before a `Reset` or `Restore` called from `OnEvent` are still delivered, and when that call is made during `Update`, `Update` goes on to read input against the reset or restored state. `Status(id)` reports charges, remaining cooldown and recharge, and the cast or channel progress in steps, and `Duration(steps)` converts them to game time for a cooldown bar. `Active()` reports the ability casting or channeling now. ### Costs and conditions `Resources` is an interface with `Amount` and `Spend`, so costs can draw on the game's own stats. `ability.Pool` is a ready map-based one. Every cost of a use is checked before any is spent. With a nil `Resources`, abilities with costs cannot be activated; with a nil `Condition`, every condition is false. ## Determinism `NewCaster` turns each duration into whole steps at its rate, rounding up, and every timer counts whole steps. At 60 Hz, `game.Loop`'s `dt` is 16,666,666 ns, so summing it would take 121 steps to reach 2 s; a `Caster` puts a 2 s cooldown at exactly 120 steps. Within a step, `Update` advances every cooldown and recharge in set order, then the active cast or channel, then reads input, so an ability whose cooldown ends on a step can be used again on that same step. When several abilities share an action, they are tried in set order and the first that activates wins, which lets conditions pick between them. The same inputs on the same steps therefore give the same events on the same steps on every machine. `Snapshot` returns a `State` (step counts, JSON and YAML tags) for save slots, rollback and replays, and `Restore` puts it back, refusing a state from another set or rate. `Update` does not allocate. ## Cosmetic cues An ability reports `EventActivated` and leaves presentation to the game. To keep particles, sounds and camera shake out of the simulation, map gameplay tags to them in a [cues](http://nsgo.games/docs/cues/) file and dispatch the tags from the client with `cues.Player`. --- Source: http://nsgo.games/docs/accessibility-guide/ # Accessibility Guide This guide maps the [Game Accessibility Guidelines](https://gameaccessibilityguidelines.com/) (GAG) and [Xbox Accessibility Guidelines](https://learn.microsoft.com/en-us/gaming/accessibility/guidelines) (XAG) to NSGo Game packages, shows how to wire player preferences end to end, provides a pre-release checklist, and maps Apple's App Store Accessibility Nutrition Labels to what the engine lets you claim truthfully. For the `pkg/a11y` API reference, see [a11y](http://nsgo.games/docs/a11y/). Each item below states what works today, which row in [`gameui.SettingsMenu`](http://nsgo.games/docs/gameui/#ready-settings-menu-settingsmenu) controls it, what remains the **game's responsibility**, and the open issue wherever the engine does not yet cover a requirement. ## Wiring settings end to end All accessibility, audio, display, and control preferences live in one typed [`save.Settings`](http://nsgo.games/docs/save/#player-settings-settingsstore--accessibilitysettings) store (`save.DefaultSettingsStore`), kept separate from save slots. Backing [`a11y.Assist`](http://nsgo.games/docs/a11y/#persisted-assist-options-assist) with that same store via `a11y.NewAssistFromSettings` connects `gameui.SettingsMenu`, `a11y.CaptionsView`, `a11y.AccessibleMenu`, `sound.Mixer`, and `postfx.Flash` / `postfx.Shake`: ```go store := save.NewStorageSettingsStore(cx.Storage(), "mygame") assist := a11y.NewAssistFromSettings(cx, store) mixer := sound.NewMixer(cx, "mygame") captions := a11y.NewCaptionTrack(cx) // Load and apply saved settings before the first sound or frame. _, _ = store.LoadAndApply(save.SettingsTargets{ Sound: mixer, ApplyDisplay: video.Apply, ApplyBindings: func(b map[string][]string) error { gameui.ApplyBindingsToActions(actions, b, true); return nil }, ApplyLocale: setLocale, ApplyAccessibility: assist.ApplySettings, }) // Wire SettingsMenu to the same store and Env so OS defaults apply when unset. settingsMenu := gameui.NewSettingsMenu(gameui.SettingsMenuConfig{ Store: store, Env: cx.Env(), Video: video, Targets: save.SettingsTargets{ Sound: mixer, ApplyDisplay: video.Apply, ApplyBindings: func(b map[string][]string) error { gameui.ApplyBindingsToActions(actions, b, true); return nil }, ApplyLocale: setLocale, ApplyAccessibility: assist.ApplySettings, }, OnBack: closeSettings, }) // Full-screen flashes stop under ReduceMotion and turn into low-contrast tints under ReduceFlashes; shake scales with ScreenShake. flash := postfx.NewFlash(cx, postfx.FlashConfig{ Color: core.RGB(0xffffff), ReduceMotion: assist.ReduceMotion, ReduceFlashes: assist.ReduceFlashes, }) shake := postfx.NewShake(cx, postfx.ShakeConfig{ Seed: 42, ReduceMotion: assist.ReduceMotion, }) // Inside game.Loop.Update: sim.Step(assist.ScaleDT(dt)) captions.Update(dt) // When triggering camera shake, multiply by assist.ScreenShake() (0..1): if amp := 6.0 * assist.ScreenShake(); amp > 0 { shake.Trigger(amp, 400*time.Millisecond) } // Mount native CaptionsView above your Canvas in a core.Stack: a11y.CaptionsView(cx, captions, a11y.CaptionStyle{Assist: assist}) ``` ### Platform preferences followed automatically NSGo exposes the operating system's accessibility settings as reactive signals on `cx.Env()`: | OS signal (`core.Env`) | Engine integration | | --- | --- | | `Env().ReduceMotion()` | Default for `save.AccessibilitySettings.EffectiveReduceMotion` (`assist.ReduceMotion()`), `SettingsMenu`, `postfx.Flash`, and `postfx.Shake` until the player explicitly overrides it. | | `Env().IncreaseContrast()` | Default for `save.AccessibilitySettings.EffectiveHighContrast` (`assist.HighContrast()`), `assist.Palette()` (`VisionHighContrast`), `CaptionsView`, and `SettingsMenu`'s automatic `HighContrastTheme()`. | | `Env().FontScale()` | Default for `save.AccessibilitySettings.EffectiveCaptionScale` (`assist.TextScale()`, clamped to `0.5`–`3.0`), read by `CaptionsView` and `AccessibleMenu`. | | `Env().ScreenReader()` | Readable anywhere to adjust narration or route focus into native views (`a11y.AccessibleMenu`, `cx.Announce`). | | `Env().Dark()` / `Env().Appearance()` | Readable for dark-mode UI adaptation. | | `Env().RTL()` | Read by [`l10n.EnvDirection`](http://nsgo.games/docs/l10n/#rtl-visual-ordering-and-layout-mirroring) for RTL text ordering and HUD mirroring. | | `Env().SafeArea()` | Read by [`screen.Viewport.SafeGameRectForEnv`](http://nsgo.games/docs/screen/#safe-area-for-mobile-huds), [`input.TouchControls.Resize`](http://nsgo.games/docs/input/#on-screen-touch-controls), and [`gameui`](http://nsgo.games/docs/gameui/#screen-files-screenyaml) screen files. | | `Env().Pointer()` | `input.NewTouchControls` shows touch controls automatically when `core.PointerCoarse`. | Calling `Assist.Reset()` (or clicking **Reset** in `SettingsMenu`) clears explicit overrides so `ReduceMotion`, `HighContrast`, and `TextScale` follow the operating system again. ## Motor Covers GAG Motor (Basic & Intermediate) and XAG 106 (Touch), 107 (Input), 108 (Timing/Holds), and 117 (Settings). | Guideline (GAG / XAG) | Level | Engine support & SettingsMenu row | Gaps & game's responsibility | | --- | --- | --- | --- | | **Remappable controls** (GAG / XAG 107) | Basic | [`input.Actions`](http://nsgo.games/docs/input/#defining-actions-and-axes) (`Bind`, `Save`/`Load`), [`gameui.SettingsMenu`](http://nsgo.games/docs/gameui/#ready-settings-menu-settingsmenu) **Controls** tab (`save.Settings.Bindings`, `ApplyBindingsToActions`). | Ensure every gameplay and menu action is bound through `input.Actions` rather than hard-coded keys or buttons. | | **Multiple input methods & device switching** (GAG / XAG 107) | Basic | [`input.Actions`](http://nsgo.games/docs/input/) unifies keyboard, mouse, gamepad, touch, and motion sensors under the same action names; `input.DeviceTracker` and `input.PromptTable` update prompts automatically; [`Players.SetDisconnectPolicy`](http://nsgo.games/docs/input/#controller-disconnect-reconnect-and-fallback) pauses or falls back to keyboard/touch on controller disconnect. | Avoid requiring two devices at once (for example, mouse plus keyboard) when a single device can drive the same actions. | | **Single input method for menus and play** (GAG / XAG 107) | Basic | [`gameui.SpatialNavigator`](http://nsgo.games/docs/gameui/#spatial-action-focus-navigation-spatialnavigator) (`StepActions`, `focusOrder` in `*.screen.yaml`), `SettingsMenu` (pointer, touch, keyboard, and `StepGamepad`), [`a11y.AccessibleMenu`](http://nsgo.games/docs/a11y/#screen-reader-menus-accessiblemenu) (keyboard, press, and screen-reader actions). | **Engine gap**: one-switch scanning for `gameui` screens and `SettingsMenu` is tracked in [#1778](https://github.com/nsgo-dev/game/issues/1778). | | **Touch target size, spacing, left-handed layout & saved edits** (GAG / XAG 106, 107) | Basic / Interm. | [`input.TouchControls`](http://nsgo.games/docs/input/#on-screen-touch-controls) enforces `input.MinTouchTarget` (`44 pt`), stays inside `SafeArea`, supports `SetMirrored(true)` for left-handed play, and persists player layout edits via `Save`/`Load`. [`gameui.CheckScreen`](http://nsgo.games/docs/gameui/#validation-game-check-and-safe-refactoring-toolingrefs-game-mv) (`go tool game check`) flags touch targets under `44 pt` on phones and tablets. | Expose a layout editor or left-handed toggle in your game's UI if players rely on virtual sticks and buttons. | | **Hold-to-toggle & avoiding rapid button mashing** (GAG / XAG 108) | Basic / Interm. | Touch buttons support `mode: toggle` and `mode: tap` (`TouchModeToggle`, `TouchModeTap`). `Assist.HoldToToggle()` and `SettingsMenu` **Accessibility → Hold to Toggle** persist the player's preference. | **Engine gap**: built-in action modifiers on `input.Actions` (hold-to-toggle, press-once instead of mashing, minimum press time, repeat debounce) are tracked in [#1777](https://github.com/nsgo-dev/game/issues/1777). **Game's responsibility**: read `assist.HoldToToggle()` on sustained actions (sprint, aim, crouch, block) and avoid mandatory rapid-press QTEs. | | **Sensitivity, axis inversion, dead zones & haptics** (GAG / XAG 107, 108) | Basic / Interm. | Per-axis `GamepadAxisOptions` (`DeadZone`, `Axial`, `Sensitivity`, `Invert`), `PointerAxisOptions` (`Sensitivity`, `Invert`), `MotionAxisOptions` (`DeadZone`, `Smoothing`, `Calibrate`), and `input.Haptics.SetEnabled(false)` (persisted with `Haptics.Save`/`Load`). | **Engine gaps**: standard player settings for look sensitivity, invert axes, stick dead zone, FOV, camera bob, and haptics strength applied to input and 3D cameras are tracked in [#1780](https://github.com/nsgo-dev/game/issues/1780); native gamepad rumble hardware support is tracked in [nsgo#1049](https://github.com/nsgo-dev/nsgo/issues/1049). | | **Adjustable game speed & input leniency** (GAG / XAG 108, 117) | Interm. | `Assist.GameSpeed()` / `Assist.ScaleDT(dt)` (`0.25`–`2.0`), `SettingsMenu` **Accessibility → Game Speed**; [`platformer.Config`](http://nsgo.games/docs/platformer/#timing) (`coyote_time`, `jump_buffer`, `wall_coyote_time`); [`rhythm.CalibrationScreen`](http://nsgo.games/docs/rhythm/#calibration) + `OffsetStore`. | **Game's responsibility**: let players slow down real-time play (`assist.ScaleDT(dt)`) without punishing score or locking progression, and provide forgiving timing windows or skippable QTEs. | | **Aim assist** (GAG / XAG 108) | Interm. | `Assist.AutoAim()` and `SettingsMenu` **Accessibility → Auto-Aim** persist the toggle. | **Engine gap**: built-in 2D/3D aim assist (slowdown near targets, magnetism, snap) with player-set strength is tracked in [#1779](https://github.com/nsgo-dev/game/issues/1779). | Minimal pattern for reading `assist.HoldToToggle()` until [#1777](https://github.com/nsgo-dev/game/issues/1777) lands: ```go if assist.HoldToToggle() { if actions.JustPressed("crouch") { crouching = !crouching } } else { crouching = actions.Pressed("crouch") } ``` ## Cognitive Covers GAG Cognitive (Basic & Intermediate) and XAG 112 (Reading/Timing), 113–115 (Guidance/Difficulty), and 117 (Settings). | Guideline (GAG / XAG) | Level | Engine support & SettingsMenu row | Gaps & game's responsibility | | --- | --- | --- | --- | | **Save and remember all settings** (GAG / XAG 117) | Basic | [`save.DefaultSettingsStore`](http://nsgo.games/docs/save/#player-settings-settingsstore--accessibilitysettings) persists audio, video, bindings, language, and accessibility settings outside save slots with atomic backup recovery. | **Engine gap**: wiring a Settings screen with the Accessibility tab into every starter template on first launch before any sound is tracked in [#1783](https://github.com/nsgo-dev/game/issues/1783). | | **Pause at any time & undo mistakes** (GAG / XAG 115) | Basic | [`game.Loop.SetPaused`](http://nsgo.games/docs/loop/#pausing-and-syncing-subsystems) (`Loop.OnPause = mixer.SetPaused`), automatic pause on `core.LifecycleBackground`, and [`undo.History`](http://nsgo.games/docs/undo/) (`Undo`/`Redo`/`Seek`, saved via `undo.EncodeLog`) for puzzle and turn-based games. | **Game's responsibility**: allow pausing during gameplay and cutscenes; avoid unpausable real-time prompts in single-player modes. | | **Self-paced text, backlog & skippable cutscenes** (GAG / XAG 112) | Basic / Interm. | [`vn.Presenter`](http://nsgo.games/docs/vn/#presenter) (`CharsPerSecond` with negative values for instant reveal, `Advance`, `SetAuto`, `SetSkip`, `Backlog` and `ReplayVoice`); [`cutscene.Cutscene`](http://nsgo.games/docs/cutscene/#skipping) (`skippable: true`, `skipAfter`). | **Game's responsibility**: require manual confirmation to advance dialogue by default instead of auto-dismissing story text on a short timer. | | **Adjustable speed & invincibility assists** (GAG / XAG 115) | Basic / Interm. | `Assist.GameSpeed()` / `ScaleDT` (`SettingsMenu` **Accessibility → Game Speed**) and `Assist.Invincibility()` (**Accessibility → Invincibility**). | **Game's responsibility**: provide selectable difficulty levels (such as Story / Relaxed / Standard), skip-encounter options, and generous checkpoints. | | **Clear objectives, reminders & device-accurate prompts** (GAG / XAG 113, 114) | Basic / Interm. | [`quest.Log`](http://nsgo.games/docs/quest/#running-quests) tracks active quests and objectives for a HUD/journal; `input.PromptTable` + `DeviceTracker` display prompts matching the player's current device; [`l10n.Catalog`](http://nsgo.games/docs/l10n/) localizes all text. | **Game's responsibility**: surface the current objective on demand, allow replaying tutorials, keep UI copy concise and jargon-free, and allow disabling optional timers. | ## Vision Covers GAG Vision (Basic & Intermediate) and XAG 101 (Text), 102 (Contrast), 103 (Color), 104 (Visual Comfort/Layout), and 105 (Screen Narration). | Guideline (GAG / XAG) | Level | Engine support & SettingsMenu row | Gaps & game's responsibility | | --- | --- | --- | --- | | **Legible, scalable text (up to 200%)** (GAG / XAG 101) | Basic / Interm. | `cx.Env().FontScale()` and `Assist.TextScale()` (`0.5`–`3.0`, `SettingsMenu` **Accessibility → Text Scale**) scale `CaptionsView` and `AccessibleMenu` automatically. [`text.SDFFont`](http://nsgo.games/docs/text/#signed-distance-field-fonts) and [`text.DrawPlatform`](http://nsgo.games/docs/text/#platform-text-with-drawplatform) stay crisp at any size. `gameui.CheckScreen` (`go tool game check`) checks localized text overflow across Phone, Tablet, Desktop, and Ultrawide reference sizes. [`Root.TextScale`](http://nsgo.games/docs/gameui/#text-scale-textscale) scales `gameui` widgets and `*.screen.yaml` text up to 200%, and `ScreenCheckOptions.TextScale` checks overflow at that scale. | **Engine gap**: following `Env.FontScale()` and the player's setting automatically, and a separate HUD scale, are tracked in [#1772](https://github.com/nsgo-dev/game/issues/1772). **Game's responsibility**: pick clean sans-serif or readable fonts and avoid tiny pixel text for essential UI. | | **Sufficient contrast & high-contrast mode** (GAG / XAG 102) | Basic | `cx.Env().IncreaseContrast()`, `Assist.HighContrast()` (`SettingsMenu` **Accessibility → High Contrast**), `a11y.PaletteFor(VisionHighContrast)` (`21:1` fg/bg), `gameui.HighContrastTheme()` (auto-applied by `SettingsMenu` when `Theme` is nil), `a11y.ContrastRatio`, `a11y.EnsureContrast`, and `gameui.CheckScreen` (`go tool game check`) enforcing ≥ `4.5:1` WCAG contrast on `*.screen.yaml` text nodes. | **Game's responsibility**: place translucent dark scrims behind HUD text drawn over busy gameplay backgrounds, and audit custom canvas text with `a11y.ContrastRatio(fg, bg) >= 4.5`. | | **Color-blind-safe palettes & CVD testing** (GAG / XAG 103) | Basic | `a11y.PaletteFor(mode)` (Okabe-Ito / Wong palettes for `VisionNormal`, `VisionProtanopia`, `VisionDeuteranopia`, `VisionTritanopia`, `VisionHighContrast`), `Assist.ColorVision()` / `Assist.Palette()` (`SettingsMenu` **Accessibility → Color-Blind Mode**), `a11y.Simulate(c, mode)`, and [`postfx.PaletteSwap`](http://nsgo.games/docs/postfx/#palette-swap). | **Engine gap**: full-frame color-blind post-processing filter and editor/test CVD preview are tracked in [#1776](https://github.com/nsgo-dev/game/issues/1776). **Game's responsibility**: **never convey information by color alone** — always pair color with distinct silhouettes, icons, patterns, outlines, or text labels. | | **Screen reader & UI narration** (GAG / XAG 105) | Interm. | `cx.Env().ScreenReader()`, `cx.Announce(text)`, `cx.Speak(text, voice, done)` (`cx.Env().CanSpeak()`), native NSGo accessibility attributes (`Role`, `Label`, `Hint`, `AccessibilityDescription`, `AccessibilityValue`, `LiveRegion`), [`a11y.AccessibleMenu`](http://nsgo.games/docs/a11y/#screen-reader-menus-accessiblemenu) (localized via `MenuText` / `l10n`), [`a11y.CaptionsView`](http://nsgo.games/docs/a11y/#live-captions-captiontrack--captionsview), and `input.TouchControls.Draw` (`core.CanvasNode` labels and roles). | **Engine gap**: exposing canvas-drawn `gameui` widgets, `SettingsMenu`, and `*.screen.yaml` files to screen readers with focus and value announcements is tracked in [#1425](https://github.com/nsgo-dev/game/issues/1425). Until `#1425` lands, use `a11y.AccessibleMenu` or native NSGo views when full VoiceOver/TalkBack menu support is required. | | **Safe areas, dark interface & RTL layout** (GAG / XAG 102, 104) | Interm. | `cx.Env().Dark()` / `Env().Appearance()`, [`screen.Viewport.SafeGameRectForEnv`](http://nsgo.games/docs/screen/#safe-area-for-mobile-huds), `safeArea` in `*.screen.yaml`, [`l10n.MirrorX`](http://nsgo.games/docs/l10n/#rtl-visual-ordering-and-layout-mirroring) / `LayoutAlignment`, and [`screen.Video`](http://nsgo.games/docs/screen/#video-settings) windowed/full-screen modes. | **Game's responsibility**: ensure HUD elements never clip into notches, home indicators, or curved edges, and keep important gameplay elements separated from cluttered backgrounds. | | **3D camera FOV & camera bob** (GAG / XAG 104) | Interm. | `scene3d.Camera` accepts configurable field-of-view angles in game code. | **Engine gap**: standard player settings for FOV and camera bob applied to 3D cameras are tracked in [#1780](https://github.com/nsgo-dev/game/issues/1780). | Use `a11y.Simulate` and `a11y.ContrastRatio` in unit tests to guard custom gameplay palettes: ```go for _, mode := range []a11y.ColorVision{a11y.VisionProtanopia, a11y.VisionDeuteranopia, a11y.VisionTritanopia} { pal := a11y.PaletteFor(mode) if ratio := a11y.ContrastRatio(pal.Foreground, pal.Background); ratio < 4.5 { t.Errorf("%s foreground contrast %.2f < 4.5", mode, ratio) } _ = a11y.Simulate(pal.Enemy, mode) } ``` ## Hearing Covers GAG Hearing (Basic & Intermediate) and XAG 109 (Captions) and 110–111 (Audio/Alternatives). | Guideline (GAG / XAG) | Level | Engine support & SettingsMenu row | Gaps & game's responsibility | | --- | --- | --- | --- | | **Subtitles & directional SFX captions** (GAG / XAG 109) | Basic / Interm. | [`a11y.CaptionTrack`](http://nsgo.games/docs/a11y/#live-captions-captiontrack--captionsview) + `CaptionsView` (`ShowDialogue`, `ShowSFX`, `ShowSFXAt`, `ShowImportant`, `CaptionMusic`), `CaptionStyleFromLocalizer`, `Assist.CaptionsEnabled()` and `Assist.SFXCaptionsEnabled()`, `SettingsMenu` **Accessibility → Subtitles**, **SFX Captions**, and **Text Scale**. `Caption.Format()` adds `[<]` or `[>]` when `|Direction| >= 0.25`. | **Engine gaps**: player-set caption background/opacity, speaker colors, per-kind toggles, 2-line limit, and live preview in `SettingsMenu` are tracked in [#1773](https://github.com/nsgo-dev/game/issues/1773); automatic caption feeding from sounds, cutscenes, and dialogue plus an on-screen directional sound indicator is tracked in [#1774](https://github.com/nsgo-dev/game/issues/1774). | | **Separate volume controls & mute** (GAG / XAG 110) | Basic | [`sound.Mixer`](http://nsgo.games/docs/sound/#mixer-and-persistent-volumes) (`Master` and per-bus groups such as `"music"`, `"sfx"`, `"voice"`, `"ui"`), `save.AudioSettings` (`Master`, `Groups`, `Muted`), `SettingsMenu` **Audio** tab. | **Game's responsibility**: route music, sound effects, voice, and UI sounds through distinct mixer groups so players can turn down background music while keeping speech audible. | | **Mono audio & stereo balance** (GAG / XAG 110) | Basic / Interm. | [`sound.Mixer`](http://nsgo.games/docs/sound/#mono-audio-and-leftright-balance) (`SetMono`, `FollowSystemMono`, `SetBalance`), `save.AudioSettings` (`Mono`, `Balance`), `SettingsMenu` **Audio → Mono Audio** and **Balance**. `Listener2D.Pan` and `Listener3D.Pan` still report true spatial direction so directional captions remain accurate under mono. | **NSGo v0.3.4 limits**: stereo audio assets keep their channels until output down-mixing lands ([nsgo#2676](https://github.com/nsgo-dev/nsgo/issues/2676)); automatic OS mono-switch tracking awaits `Env.MonoAudio` ([nsgo#2677](https://github.com/nsgo-dev/nsgo/issues/2677)). | | **Visual & haptic alternatives to sound cues** (GAG / XAG 109, 111) | Basic / Interm. | [`input.Haptics`](http://nsgo.games/docs/input/#on-screen-touch-controls) (`Play`, `Rumble`, `PlayPattern`, and `OnHaptic` callback for visual indicators); `CaptionTrack.ShowImportant` and `ShowSFXAt`. | **Game's responsibility**: ensure every gameplay-critical audio cue (enemy attack telegraph, low-health beep, off-screen threat, rhythm beat) has a clear visual or haptic equivalent so the game is fully playable muted. | ## Speech Covers GAG Speech (Basic & Intermediate) and XAG 118–119 (Communication). | Guideline (GAG / XAG) | Level | Engine support & SettingsMenu row | Gaps & game's responsibility | | --- | --- | --- | --- | | **Never require voice input** (GAG / XAG 118) | Basic | No package in NSGo Game requires microphone or voice input. Native text-to-speech (`cx.Speak`, `cx.Env().CanSpeak()`) and speech recognition (`cx.StartSpeech`, `cx.Env().CanRecognizeSpeech()`) are available as optional hooks on `core.Scope`. | **Game's responsibility**: keep every mechanic and menu operable without speaking. | | **Text alternatives for multiplayer communication** (GAG / XAG 119) | Basic / Interm. | Native NSGo text inputs and views (`core.TextInput`, `gameui.AnchorOverlay`) can render text chat and quick-phrase wheels over the game canvas. | **Game's responsibility**: if your game includes voice chat, provide text chat or pre-written ping/call-out phrases, individual player mute controls, and optional TTS/STT bridges. | ## Photosensitivity and Motion Comfort Covers GAG General/Vision (Photosensitivity & Motion Sickness) and XAG 104 (Visual Comfort) and 120 (Photosensitivity). | Guideline (GAG / XAG) | Level | Engine support & SettingsMenu row | Gaps & game's responsibility | | --- | --- | --- | --- | | **Reduced motion & screen shake control** (GAG / XAG 104) | Basic | `cx.Env().ReduceMotion()`, `Assist.ReduceMotion()` and `Assist.ScreenShake()` (`0.0`–`1.0`), `SettingsMenu` **Accessibility → Reduce Motion** and **Screen Shake**, [`postfx.Shake`](http://nsgo.games/docs/postfx/#vignette-flash-and-shake) (`ShakeConfig.ReduceMotion`). | **Game's responsibility**: gate [`tilemap.Camera.Shake`](http://nsgo.games/docs/tilemap/#following-clamping-and-shaking), parallax scrolling, idle UI bounce, and camera transitions on `assist.ReduceMotion()` and `assist.ScreenShake()`. | | **Full-screen flashes & seizure safety** (GAG / XAG 120) | Basic | `Assist.ReduceFlashes()`, `SettingsMenu` **Accessibility → Reduce Flashes**, [`postfx.Flash`](http://nsgo.games/docs/postfx/#photosensitivity) (`FlashConfig.ReduceFlashes`, `FlashConfig.Limiter`). A `postfx.Flash` runs at most 3 times per rolling second, a shared `postfx.FlashLimiter` budgets several flashes together, saturated-red flash colors are desaturated, and passing `assist.ReduceFlashes` to `FlashConfig.ReduceFlashes` turns flashes into low-contrast tints. | **Engine gap**: particles and sprite flashes do not read `ReduceFlashes`, and automated test checks for flash and high-contrast pattern failures on recorded frames are tracked in [#1775](https://github.com/nsgo-dev/game/issues/1775). **Game's responsibility**: share one `FlashLimiter` between the full-screen flashes of a screen, keep other flashing content below 3 per second, and avoid rapid saturated-red or full-screen luminance strobes outside `postfx.Flash`. | | **Repeating patterns & screen distortion** (GAG / XAG 104, 120) | Interm. | [`postfx.CRT`](http://nsgo.games/docs/postfx/#crt-and-scanlines) scanlines and curvature are opt-in shader passes that can be disabled when `ReduceMotion()` or `ReduceFlashes()` is active. | **Engine gap**: 3D FOV and camera-bob settings are tracked in [#1780](https://github.com/nsgo-dev/game/issues/1780). **Game's responsibility**: avoid high-contrast static or scrolling stripe/checkerboard patterns across large screen areas, and offer a toggle for post-processing distortion or bloom. | Gate `tilemap.Camera.Shake` alongside `postfx.Shake`: ```go if !assist.ReduceMotion() { if intensity := 6.0 * float32(assist.ScreenShake()); intensity > 0 { cam.Shake(intensity, 250*time.Millisecond) } } ``` ## Pre-release Accessibility Checklist Run through every item before cutting a release build ([Building and Shipping](http://nsgo.games/docs/shipping/)): - [ ] **Settings saved and restored**: change every Audio, Video, Controls, Language, and Accessibility setting in `SettingsMenu`, restart the app, and confirm every value persists separately from save slots (`save.DefaultSettingsStore`); click **Reset** and confirm unset `ReduceMotion`, `HighContrast`, and `TextScale` follow `cx.Env()` again. - [ ] **Accessibility & captions available before first sound**: confirm players can enable subtitles, SFX captions, mono audio, and reduced motion/flashes before opening cutscenes or title music play (template defaults tracked in [#1783](https://github.com/nsgo-dev/game/issues/1783)). - [ ] **Text readable at 200%**: set OS text scale to 200% (`Env.FontScale() == 2.0`) and `Assist.TextScale()` to `2.0`; inspect `CaptionsView`, `AccessibleMenu`, and native HUD text for truncation or overlap (also inspect `gameui` screens manually until [#1772](https://github.com/nsgo-dev/game/issues/1772) lands). - [ ] **Contrast and non-color audit**: run `go tool game check` to verify every `*.screen.yaml` meets `4.5:1` contrast, `44 pt` touch targets on mobile, and zero text overflow across all locales; test custom canvas colors with `a11y.ContrastRatio` and `a11y.Simulate`, and play in greyscale to confirm no mechanic relies on color alone. - [ ] **Flash and motion check**: turn on **Reduce Motion** and **Reduce Flashes**, then trigger every hit flash, explosion, lightning strike, screen shake, boss transition, and cutscene; confirm zero unexpected flashes, zero screen shake, and no rapid > 3 Hz full-screen luminance or saturated-red flicker (automated frame check tracked in [#1775](https://github.com/nsgo-dev/game/issues/1775)). - [ ] **One input method end to end**: play from title screen through Settings, gameplay, pause, and game over using each supported input method alone — keyboard-only, gamepad-only, touch-only (checking `44 pt` targets inside `SafeArea`), and mouse-only — and verify controller disconnect recovery (`Players.SetDisconnectPolicy`). - [ ] **Screen reader pass on iOS and Android**: test with **VoiceOver** (iOS) and **TalkBack** (Android) across every native view, `AccessibleMenu`, `CaptionsView`, and `TouchControls` canvas node; verify focus order, spoken labels/values, and that canvas-only `gameui` screens do not block navigation (see [#1425](https://github.com/nsgo-dev/game/issues/1425)). ## Apple App Store Accessibility Nutrition Labels Apple's App Store lets developers declare nine [Accessibility Nutrition Labels](https://developer.apple.com/help/app-store-connect/manage-app-accessibility/overview-of-accessibility-nutrition-labels) in App Store Connect. Only claim a label when your **entire** core experience meets Apple's criteria — not merely because an engine helper exists. | App Store Label | Engine features that support it | Limits & open issues | What to test before claiming | | --- | --- | --- | --- | | **VoiceOver** | Native NSGo views (`Role`, `Label`, `Hint`, `AccessibilityValue`, `LiveRegion`), `a11y.AccessibleMenu`, `a11y.CaptionsView`, `input.TouchControls.Draw` (`core.CanvasNode`), `cx.Announce`, `cx.Env().ScreenReader()`. | Canvas-drawn `gameui` widgets, `SettingsMenu`, and `*.screen.yaml` are not yet exposed to VoiceOver ([#1425](https://github.com/nsgo-dev/game/issues/1425)); custom canvas/3D scenes require your own `CanvasNode`s or native UI alternatives. | Complete onboarding, menus, settings, and core gameplay on a real iOS device with VoiceOver enabled (including Screen Curtain); confirm every interactive control has an accurate label, role, value, and logical focus order. | | **Voice Control** | Native NSGo views with distinct `Label`s, `a11y.AccessibleMenu`, and `input.TouchControls.Draw` (`CanvasNode` labels) expose named elements to iOS Voice Control. | Canvas-drawn `gameui` widgets and `*.screen.yaml` are not yet exposed ([#1425](https://github.com/nsgo-dev/game/issues/1425)); real-time continuous movement/aiming usually cannot be played by voice commands alone. | Enable iOS Voice Control with **Show Names** and **Show Numbers**; confirm every common task and menu action can be operated reliably by voice without getting stuck. | | **Larger Text** | `cx.Env().FontScale()`, `Assist.TextScale()` (`0.5`–`3.0`), `CaptionsView`, `AccessibleMenu`, native `core.Text`, `text.SDFFont`, `text.DrawPlatform`. | `gameui` widgets, `SettingsMenu`, and `*.screen.yaml` do not yet automatically scale to 200% from `Env.FontScale()` ([#1772](https://github.com/nsgo-dev/game/issues/1772)). | Set iOS Dynamic Type to Accessibility Extra Large (≥ 200%) before launch; verify all readable text across menus, HUD, dialogue, and captions scales cleanly without clipping or overlapping. | | **Dark Interface** | `cx.Env().Dark()` and `cx.Env().Appearance()`, dark-first `a11y.PaletteFor` presets, `gameui.DefaultTheme()` / `HighContrastTheme()`. | Game art and custom themes must respect dark appearance themselves. | Switch iOS between Light and Dark Mode; verify all screens, dialogs, settings, and overlays adapt to dark styling with comfortable legibility and no sudden bright white flashes. | | **Differentiate Without Color Alone** | `a11y.PaletteFor(...)` (Okabe-Ito / Wong palettes), `a11y.Simulate(...)`, `SettingsMenu` Color-Blind Mode. | Full-frame post-process color-blind filter is tracked in [#1776](https://github.com/nsgo-dev/game/issues/1776); palettes alone do not satisfy this label if gameplay meaning depends solely on color. | Enable iOS **Color Filters → Grayscale** and play every core mechanic (enemies, pickups, hazards, puzzle pieces, status bars); confirm shape, icon, pattern, or text always communicates state without color. | | **Sufficient Contrast** | `gameui.CheckScreen` / `go tool game check` (checks ≥ `4.5:1` on `*.screen.yaml`), `a11y.ContrastRatio`, `a11y.EnsureContrast`, `CaptionsView` (`7.0:1` enforced), `Assist.HighContrast()` following `cx.Env().IncreaseContrast()`, `gameui.HighContrastTheme()`. | Custom `Canvas` / 3D HUD text and icons drawn outside `*.screen.yaml` are not checked automatically by `game check`. | Run `go tool game check`, enable iOS **Increase Contrast**, and measure custom HUD/menu foregrounds against their backgrounds to verify ≥ `4.5:1` for regular text and ≥ `3:1` for large text and essential UI controls. | | **Reduced Motion** | `cx.Env().ReduceMotion()`, `Assist.ReduceMotion()` (follows OS by default), `Assist.ScreenShake()`, `Assist.ReduceFlashes()`, `SettingsMenu` Accessibility tab, `postfx.ShakeConfig.ReduceMotion`, `postfx.FlashConfig.ReduceMotion`. | `postfx.Flash` requires wiring `FlashConfig.ReduceFlashes` explicitly; `tilemap.Camera.Shake`, tweens, parallax, and particles must check `assist.ReduceMotion()` in game code. | Enable iOS **Reduce Motion** before opening the game (without changing in-game settings); verify camera shake, full-screen flashes, animated transitions, parallax, and idle UI motion are reduced or turned off immediately. | | **Captions** | `a11y.CaptionTrack`, `a11y.CaptionsView`, `Assist.CaptionsEnabled()`, `Assist.SFXCaptionsEnabled()`, `Caption.Format()` (speaker names and `[<]`/`[>]` directional cues), `SettingsMenu` Accessibility tab. | Games must push dialogue, SFX, and cutscene cues to `CaptionTrack` themselves ([#1774](https://github.com/nsgo-dev/game/issues/1774)); player-customizable caption backdrop, opacity, and speaker colors are tracked in [#1773](https://github.com/nsgo-dev/game/issues/1773). | Play the full game muted on iOS (intro, cutscenes, dialogue, and gameplay); verify every spoken line and gameplay-relevant sound is accurately captioned in sync with audio. | | **Audio Descriptions** | No built-in audio-description track player in `pkg/cutscene` or `pkg/sound`; games can layer a synchronized narration bus through `sound.Mixer` or speak cues with `cx.Speak` (`Env.CanSpeak()`). | Fully the game's responsibility for visual-only cutscenes and media. | Claim only if every visual-only video or narrative sequence includes selectable, synchronized audio descriptions explaining essential visual action without talking over dialogue. | --- Source: http://nsgo.games/docs/accounts/ # accounts `github.com/nsgo-dev/game/pkg/online/accounts` is a self-hostable player account service. A player starts as a guest, upgrades to an email address or links an OAuth or platform identity (Game Center, Play Games, Steam) without losing their data, and every device gets short-lived tokens a game server verifies offline. The service is server-side code in its own packages. A game client or game server that does not import them links none of their dependencies (argon2id from `golang.org/x/crypto`, the SQLite and Postgres drivers); a game server that verifies tokens imports only `accounts/authtoken`, which needs the standard library and the YAML package. | Package | What it holds | | --- | --- | | `accounts` | `Service`, `Config`, the `Store` interface, `MemoryStore`, argon2id password hashing and the HTTP `Handler` | | `accounts/authtoken` | Ed25519 token `Signer` and offline `Verifier`, the `KeySet` YAML file and PEM signing keys | | `accounts/sqlitestore` | A `Store` in a SQLite file (pure Go, no cgo); every target but the web | | `accounts/pgstore` | A `Store` in Postgres, shared by several service processes | | `accounts/sqlstore` | The SQL schema and queries both stores share | | `accounts/storetest` | The `Store` contract tests, for a store of your own | | `accounts/identity` | OIDC and Sign in with Apple JWT verification, plus redacted exchange adapters for Steam and mini-program providers | | `cmd/accountsd` | A standalone HTTP server for guests and email accounts | ## Accounts, sessions and tokens An account is a permanent random ID. Key everything the game keeps for a player (saves, progress, purchases) by that ID: linking an email address or an identity never changes it, so a guest who upgrades keeps their data. Every sign-in returns `Credentials`: - `Session` is a long-lived secret the device stores. It gets new tokens with `Refresh` and is revoked by `SignOut`. For a guest it is the only way back into the account. - `Token` is a short-lived signed token the game sends its server. It expires after the configured `tokenTTL`, and it is good only for game servers: see [Token audiences](http://nsgo.games/docs/accounts/#token-audiences). - `Created` reports whether the sign-in created the account. ```go svc, err := accounts.New(cfg, accounts.Options{ Store: store, Key: key, // from authtoken.ParsePrivateKey Identities: map[string]accounts.IdentityVerifier{"gamecenter": gameCenter, "steam": steam}, Logger: slog.Default(), }) guest, _ := svc.CreateGuest(ctx) // play at once _ = svc.LinkEmail(ctx, guest.AccountID, "ada@example.com", pass) // upgrade, same ID again, _ := svc.SignInEmail(ctx, "ada@example.com", pass) // a second device fresh, _ := svc.Refresh(ctx, again.Session) // a new token saves, _ := svc.RefreshFor(ctx, again.Session, "cloudsave") // a token for cloud save ``` | Method | What it does | | --- | --- | | `CreateGuest` | A new account with neither an email address nor an identity (`ErrGuestsDisabled` with `disableGuests`) | | `Register` | A new account with an email address and password | | `LinkEmail` | Gives an account without one an email address and password | | `SignInEmail` | Signs in with an email address and password | | `SignInIdentity` | Signs in with a provider credential, creating the account when the identity is new | | `LinkIdentity` | Links a provider identity to an account | | `ChangePassword` | Replaces an email account's password after checking the old one, and signs out every other device | | `UnlinkIdentity` | Removes a provider identity unless it is the account's last way to sign in | | `Refresh` / `SignOut` | A new game server token for a session / revokes the session | | `RefreshFor` | A new token for a session meant for another audience: `ServiceAudience` or one of `audiences` | | `Profile` | The account, its email address and its identities; `Profile.Guest` reports a guest | Errors are `ErrNotFound`, `ErrTaken` (the address or identity belongs to another account), `ErrAlreadyLinked`, `ErrLastCredential`, `ErrInvalidCredentials` (never saying whether the address, the password or the session was wrong), `ErrInvalidEmail`, `ErrWeakPassword`, `ErrUnknownProvider` and `ErrUnknownAudience` (a `RefreshFor` audience the configuration does not offer). ## Identities An `IdentityVerifier` turns a credential from the device into the provider's stable subject for the player: ```go steam := identity.Steam(func(ctx context.Context, ticket string) (string, error) { return steamWebAPI.AuthenticateUserTicket(ctx, ticket) // the SteamID }) apple := identity.Apple("com.example.game") ``` `accounts/identity` verifies OIDC ID tokens and Apple's signed identity tokens (RS256, ES256 or EdDSA) against a JWKS endpoint, checking issuer, audience, expiry, not-before and the signature; a token it refuses is an error wrapping `identity.ErrInvalidToken`. It does not check a nonce: a game that sends one must compare the token's `nonce` claim itself. `identity.Steam` and `identity.MiniProgram` wrap a game's server-side exchange callback and redact provider errors. Game Center and Play Games credentials still need the corresponding NSGo APIs before a built-in verifier can be added. The game supplies verifiers under provider names of its choosing (`a-z`, `0-9`, `.`, `_`, `-`, up to 32 characters). Linking an identity lets a second device sign in to the same account with `SignInIdentity`. An account has at most one identity per provider, and an identity belongs to one account: linking one that another account has returns `ErrTaken`. Two devices signing in with a new identity at the same time get one account between them. The service never shows a verifier's error to the caller or logs it, since it may quote the credential; the caller gets `ErrInvalidCredentials`. ## Token audiences A token names the one consumer it is for in its audience, and each consumer accepts only its own: | Audience | Who accepts it | How a device gets one | | --- | --- | --- | | `audience` of the configuration (`my-game`) | the game's servers, with `authtoken.NewVerifier` | every sign-in, `Refresh` | | `accounts` (`ServiceAudience`) | the service's own `GET /v1/me`, `POST /v1/link/*`, password and identity management endpoints | `RefreshFor(session, "accounts")` | | an entry of `audiences` (`cloudsave`, `leaderboard`) | that service, with `authtoken.NewVerifierFor` | `RefreshFor(session, "cloudsave")` | A player sends the game server token to every server it joins, and whoever runs that server can replay it until it expires. Because cloud save, the leaderboard and the account service refuse it, a game server learns who the player is and nothing more: it cannot read, overwrite or purge the player's saves, submit scores for them, or link an email address or identity to their account. A device keeps its session to itself and sends each service only a token for that service. ## Verifying tokens on a game server A token is a compact JWT signed with Ed25519 (`"alg": "EdDSA"`) holding the issuer, the account ID as subject, the audience, the issue and expiry times and a random ID. The game server loads the service's public keys from a key set file and verifies each token without a network call: ```go data, _ := os.ReadFile("keys.yaml") ks, err := authtoken.ParseKeySet(data) v, err := authtoken.NewVerifier(ks) v.Leeway = 5 * time.Second // clock skew between the two machines claims, err := v.Verify(tok) if err != nil { /* refuse the player */ } player := claims.Subject // the account ID ``` `NewVerifier` accepts the key set's audience, the game server one. A service that acts for the player verifies its own audience instead, with `authtoken.NewVerifierFor(ks, "cloudsave")`. `Verify` checks the signature, the issuer, the audience and the expiry, and its errors wrap `ErrMalformed`, `ErrUnknownKey`, `ErrSignature`, `ErrIssuer`, `ErrAudience`, `ErrExpired` or `ErrNotYetValid`. Tokens longer than `MaxLength` are refused before any work. A revoked session stops getting new tokens, but tokens already issued stay valid until they expire, so keep `tokenTTL` short. The key set file: ```yaml version: 1 issuer: https://accounts.example.com audience: my-game keys: - id: 2317febd373fcbcd key: hze+0cYruVRddgjkbHzgCeWWJbEsBkn6K8JNHRDf6Wg= ``` Each `id` is the first 8 bytes of the key's SHA-256 in hex and must match its key. To rotate the signing key, add the new key beside the old one, give game servers the new file, switch the service to the new key, and drop the old key once its last tokens have expired. Give the service the old keys too, as `Options.KeySet` (or `accountsd serve -keyset keys.yaml`): it then accepts bearer tokens signed with any key in the set, and `GET /v1/keys` serves the signing key followed by those keys, so tokens issued before the restart keep working on the service and on game servers until the old key is removed from the file. ## Configuration The service reads a versioned YAML file: ```yaml version: 1 issuer: https://accounts.example.com audience: my-game audiences: - cloudsave - leaderboard tokenTTL: 15m password: minLength: 10 argon2id: time: 2 memoryKiB: 19456 threads: 1 allowedOrigins: - https://play.example.com metrics: 127.0.0.1:9101 ``` | Field | Meaning | | --- | --- | | `version` | Schema version, `1` | | `issuer` / `audience` | Written into every token and checked by verifiers; `audience` names the game's servers and the key set, and may not be `accounts` | | `audiences` | The other services a device may get tokens for with `RefreshFor`, such as `cloudsave` and `leaderboard`; never the game's audience or `accounts`, which is always available; omitted when empty | | `tokenTTL` | Token lifetime, whole seconds from `1s` to `24h` | | `disableGuests` | Refuses `CreateGuest`, so every account starts with an email address or an identity | | `password.minLength` | Fewest characters in a password, at least 8; passwords are at most 1024 bytes | | `password.argon2id` | The argon2id cost: passes, memory in KiB and lanes | | `allowedOrigins` | Web origins whose pages may call the service; omitted when empty | | `metrics` | The address `accountsd serve` serves `/healthz`, `/readyz` and `/metrics` on, such as `127.0.0.1:9101`, a listener of its own (see [Health and metrics](http://nsgo.games/docs/backend-deploy/#health-and-metrics)); omitted when unset, and then none of them is served | `ParseConfig` refuses unknown fields, trailing documents, out-of-range values, a `metrics` address without a port and an origin that is duplicated or has a path, query, fragment, user, wildcard, port outside 1 to 65535 or scheme other than `http` and `https`. `Config.Marshal` writes the canonical form: the fields in the order above, durations in their shortest text (`15m`, not `15m0s`), `disableGuests` only when it is true, `audiences` and `allowedOrigins` only when they have entries and `metrics` only when set. A file in that form, such as one `Marshal` or `accountsd init` wrote, reads back and writes again unchanged; a hand-written file in another order or spelling is normalized. `DefaultConfig` returns the settings shown, without origins. A version 1 file without `audiences` still reads, but its service then issues tokens only for game servers and for itself, so add the audiences of the cloud save and leaderboard services it serves. ## Passwords and secrets - Passwords are stored only as argon2id hashes in the PHC format (`$argon2id$v=19$m=19456,t=2,p=1$salt$hash`), OWASP's recommended cost by default. A sign-in with a password hashed at an older cost rehashes it at the configured one. `Options.MaxConcurrentHashes` bounds how many hashes run at once, so a burst of sign-ins cannot take all the server's memory. - An unknown email address takes as long to refuse as a wrong password, so sign-in does not reveal whether an address has an account. `Register` and `LinkEmail` do: they answer `ErrTaken` (`409 taken`) for an address that belongs to an account, so anyone can test an address there without its password. Rate-limit those requests per client. - `Register`, `LinkEmail` and `ChangePassword` refuse a password with fewer characters than `password.minLength` or more than `MaxPasswordBytes` bytes with `ErrWeakPassword`. `accounts.ValidatePassword` applies the same rule without hashing, so a client form can check a password before it submits it. - Session secrets are 256 random bits; the store keeps only their SHA-256. - `ChangePassword(ctx, account, keep, old, new)` ends every session of the account except `keep`, the session of the device that asks, so a device that signed in with a leaked password can no longer refresh. With a zero `keep` every session ends, the caller's too; a `keep` of another account is `ErrInvalidCredentials`. A sign-in that checked the old password a moment before the change gets `ErrInvalidCredentials` rather than a session that outlives it, and rehashing an old password at a new cost cannot undo a change. Tokens already issued stay valid until they expire. - `UnlinkIdentity` refuses to remove the last way to sign in (`ErrLastCredential`): the store checks and removes in one step, so two devices unlinking an account's two identities at once cannot both succeed. - `Credentials.Session` and `Credentials.Token` are `Secret` values, which print, log and marshal as `[redacted]`; `Reveal` returns the value for the one place that sends it. The service logs account events (created, signed in, linked) with account IDs and provider names, never a password, session secret, token or identity credential. - Signing keys are PKCS #8 PEM files written with mode `0600`; a Postgres DSN is read from the environment, not the command line. ## Storage `Store` is the interface the service keeps its records in. Implementations enforce uniqueness atomically, so two devices racing to claim one email address or identity cannot both succeed. They also make `UnlinkIdentity`'s last-credential check, `ChangePasswordHash`'s revocation of the other sessions and `CreateSession`'s password and suspension checks each atomic with the change they guard. For operators, a store also searches accounts (`SearchAccounts` by ID or email prefix, identity and creation time, in pages ordered by ID), sets and lifts a suspension (`SetSuspension`), removes an identity without the last-credential check (`RemoveIdentity`), and lists and deletes an account's sessions (`Sessions`, `DeleteSessions`). `Account`, `AccountByEmail`, `AccountByIdentity` and `SearchAccounts` return the account's `Suspension`, which the account's JSON and its data export leave out. ```go store, err := sqlitestore.Open(ctx, "accounts.db") // one service process store, err := pgstore.Open(ctx, os.Getenv("ACCOUNTS_POSTGRES_DSN")) // several processes ``` `sqlitestore` uses the pure-Go `modernc.org/sqlite` driver with write-ahead logging and one connection; `pgstore` uses `github.com/jackc/pgx/v5`, takes an advisory lock while it creates the schema, and locks an account's row (`Dialect.RowLock`) while it changes the account's credentials or opens a session of it. Both create their tables when missing and refuse a database whose schema is newer than they know. The schema is at version 2, which added the suspension columns of `accounts`; opening a version 1 database adds them in the same transaction that records the new version. `NewMemoryStore` keeps everything in memory for tests and prototypes. A store of your own passes `storetest.Run`: ```go func TestContract(t *testing.T) { storetest.Run(t, func(t *testing.T) accounts.Store { return openEmptyStore(t) }) } ``` ## HTTP `Service.Handler` serves the service with JSON bodies; every response carries `Cache-Control: no-store`: | Request | Body | Answer | | --- | --- | --- | | `POST /v1/guest` | | credentials | | `POST /v1/register` | `{"email", "password"}` | credentials | | `POST /v1/signin/email` | `{"email", "password"}` | credentials | | `POST /v1/signin/identity` | `{"provider", "credential"}` | credentials | | `POST /v1/refresh` | `{"session", "audience"}`, `audience` optional | credentials | | `POST /v1/signout` | `{"session"}` | 204 | | `POST /v1/link/email` | `{"email", "password"}`, with an `accounts` bearer token | 204 | | `POST /v1/link/identity` | `{"provider", "credential"}`, with an `accounts` bearer token | 204 | | `POST /v1/password` | `{"oldPassword", "newPassword", "session"}`, with an `accounts` bearer token; ends every other session of the account | 204 | | `POST /v1/unlink/identity` | `{"provider"}`, with an `accounts` bearer token | 204 | | `GET /v1/me` | `accounts` bearer token | profile | | `GET /v1/me/export` | `accounts` bearer token | the account's data export | | `DELETE /v1/me` | `accounts` bearer token | 204 | | `GET /v1/keys` | | the key set as YAML | Credentials are `{"account", "session", "token", "expires", "created"}`, with status 201 when the account is new. A sign-in's token is for game servers; `refresh` with `audience` returns one for that audience instead. The bearer endpoints accept only a token for `accounts` and answer `invalid_token` to any other. Errors are `{"error": code}`: `invalid_credentials` and `invalid_token` 401, `guests_disabled` 403, `suspended` 403 (see [Suspensions](http://nsgo.games/docs/accounts/#suspensions)), `not_found` 404, `taken`, `already_linked` and `last_credential` 409, `request_too_large` 413, `bad_request`, `invalid_email`, `weak_password`, `unknown_provider` and `unknown_audience` 400, `unavailable` 503 when the request was cancelled or timed out (for example while waiting for a password hash slot under load), and `internal` 500. `POST /v1/password` keeps only the request's `session`, which must belong to the bearer token's account (`invalid_credentials` otherwise); without `session` every session of the account ends, the caller's too. Request bodies are limited to 32 KiB and unknown fields are refused. For `allowedOrigins` the handler answers CORS preflight requests and allows `Authorization` and `Content-Type`; other origins receive no CORS headers. The handler does not limit request rates: run it behind TLS and a rate limiter. `GET /v1/me/export` returns the account's data as `{"account": {"id", "email", "created"}, "identities": [{"provider", "subject"}]}` (`accounts.Export`), without passwords, password hashes, session secrets or tokens. `DELETE /v1/me` permanently deletes the account with its email address, identities and sessions, so no device can refresh or sign in to it again; tokens already issued stay valid until they expire. Deleting the account does not erase the player's cloud saves or leaderboard scores: the deployment has to remove those from its other services before it offers full account erasure. ## accountsd `cmd/accountsd` runs the service for guests and email accounts: ```sh accountsd init -config accounts.yaml -issuer https://accounts.example.com -audience my-game accountsd genkey -config accounts.yaml -key key.pem -keyset keys.yaml accountsd serve -config accounts.yaml -key key.pem -keyset keys.yaml -sqlite accounts.db -addr :8080 ACCOUNTS_POSTGRES_DSN=postgres://... accountsd serve -config accounts.yaml -key key.pem -keyset keys.yaml -postgres ``` `init` never overwrites a configuration and writes no `allowedOrigins`; if a web build calls the service from another origin, add the game page's origin to `allowedOrigins` in `accounts.yaml` before `serve`. `genkey` never overwrites a key and adds the new public key to the key set file, the first step of a rotation; it replaces the file through a temporary file and a rename, so a game server reading it never sees half of it, and it removes the new key again when the key set cannot be written. `serve -keyset` accepts and serves every key in the key set, so tokens signed with an old key keep working on the service after a rotation. `serve` logs JSON to stderr and stops on SIGINT or SIGTERM. With `metrics` set, `serve` also answers `/healthz`, `/readyz` and `/metrics` on that address, exporting requests, sign-ins and their failures, accounts and open sessions (see [Health and metrics](http://nsgo.games/docs/backend-deploy/#health-and-metrics)). A game that links platform identities builds its own command around `accounts.New` with its verifiers. ### Operator access An optional `admin:` block at the end of `accounts.yaml` makes `serve` run an [admin listener](http://nsgo.games/docs/admin/) on an address of its own, for the operators in its operators file; without it no admin route exists. `accountsd admin-token -config accounts.yaml -key key.pem -operator ci -ttl 24h` prints a bearer token for an operator of the operators file the `admin:` block names (or `-operators` names, without the block), signed with the service's key for the `admin` audience, which every service's admin listener accepts. The configuration refuses `admin` as `audience` or in `audiences`, so no player can get such a token. ### Operator routes `serve` adds the service's operator routes (`Service.AdminRoutes`) to the admin listener. Each requires one permission, and the listener writes one audit record of every call, reads included since they return personal data, with the operator, the action and `account:`; a search's record names `accounts` and holds its query and how many accounts it returned: | Request | Permission | Answer | | --- | --- | --- | | `GET /admin/v1/accounts?q=&cursor=` | `accounts.read` | `{"accounts": [...], "next"}` | | `GET /admin/v1/accounts/{id}` | `accounts.read` | the account with `guest`, `identities`, `sessions` and `suspension` | | `POST /admin/v1/accounts/{id}/suspend` `{"until", "reason"}` | `accounts.suspend` | the suspension | | `DELETE /admin/v1/accounts/{id}/suspend` | `accounts.suspend` (audited as `accounts.unsuspend`) | 204 | | `POST /admin/v1/accounts/{id}/unlink` `{"provider", "force"}` | `accounts.unlink` | 204 | | `POST /admin/v1/accounts/{id}/sessions/revoke` | `accounts.revoke` | `{"revoked": n}` | | `GET /admin/v1/accounts/{id}/export` | `accounts.export` | the account's data export | | `DELETE /admin/v1/accounts/{id}` | `accounts.delete` | 204 | Search takes `q`, which is an email prefix when it contains `@`, `provider:subject` when it contains `:` (such as `steam:76561198000000000`), and an ID prefix otherwise, or instead of `q` the fields `id` (ID prefix), `email` (email prefix), `provider` and `subject`. `from` and `to` bound the creation time in RFC 3339 (`from` inclusive, `to` exclusive) and `limit` is 1 to 100, 50 by default (a store's `SearchAccounts` takes up to `MaxSearchLimit`, 1000, and refuses more with `ErrInvalidSearchLimit`); an unknown or repeated parameter is `bad_request`. Pages are ordered by account ID and `next` continues after the last account of a page, so accounts created while an operator pages neither repeat nor push others off a page. An account is `{"id", "email", "created", "suspension"}`, the suspension `{"since", "until", "reason", "by", "active"}` with `until` absent for one without an end; a session is `{"id", "created"}`, never its secret or hash. Unlinking an account's last way to sign in answers `last_credential` 409 unless the request sets `"force": true`; the account is then reachable only through the sessions it still has. Revoking sessions ends every session of the account, as `ChangePassword` does for the others. Errors are those of the player routes, plus `invalid_suspension` 400 for an `until` that is not RFC 3339 or not in the future, or a reason over 500 bytes. Of the built-in roles, `viewer` reads, `support` also suspends, revokes and exports, `moderator` suspends and revokes, and `operator` and `owner` may do everything. ### Suspensions `Service.Suspend(ctx, id, until, reason, actor)` suspends an account until `until`, or until it is lifted when `until` is zero, and `Unsuspend` lifts it. While it is in force, `SignInEmail`, `SignInIdentity`, `Refresh` and `RefreshFor` return a `*SuspendedError` (`errors.Is(err, ErrSuspended)`) carrying `Until` and the public `Reason`, and the HTTP routes answer 403 `{"error": "suspended", "until", "reason"}`, `until` absent for a suspension without an end and `reason` absent for none. A sign-in with a wrong password still gets `invalid_credentials`, so a suspension tells nothing to someone without the password. The store refuses a session of a suspended account in the same step it creates it, so a sign-in that read the account a moment before an operator suspended it opens no session either. A suspension keeps the account's sessions: they refresh again once it ends or is lifted. Tokens issued before it began stay valid until they expire (`tokenTTL`, 15 minutes by default); a game server that must drop a player at once does so itself, for example by closing the player's connection. A suspended account's `accounts` token still reads it (`GET /v1/me`, `GET /v1/me/export`), but its changes, `POST /v1/link/email`, `/v1/link/identity`, `/v1/unlink/identity`, `/v1/password` and `DELETE /v1/me`, answer 403 `suspended`, so a player cannot unlink their identity or delete the account to sign up again with it unsuspended. An operator can still delete a suspended account with `DELETE /admin/v1/accounts/{id}`. ## Session lifecycle core `accounts.SessionDirectory` keeps device sessions in memory under a `SessionPolicy`: idle (`IdleTTL`) and absolute (`AbsoluteTTL`) expiry, and, with `Rotate`, a new secret on every `Refresh`. The previous secret stays valid for `Overlap`, so a client that retries a refresh whose reply it lost still gets in; any other secret revokes the session and returns `ErrSessionReuse`. `List` returns an account's sessions, most recently used first, `RevokeAll` signs out every session but one, and `Sweep` removes the expired ones. The service's `Store`, configuration and HTTP routes do not use the directory yet: their sessions still never expire. ## Game-side session client A game signs in through `liveops.Account`, which keeps the long-lived session in the platform keychain (`cx.Secrets()`, the Keychain or Android Keystore) and never in `core.Storage`. `NewAccountForScope(cx, opts)` restores a session saved by an earlier launch; `SignInEmail` and `Register` replace it, and `SignOut` deletes it and revokes it on the service. `Token(ctx)` returns a bearer token for `AccountOptions.Audience` (the game servers' audience when empty), refreshing it `RefreshMargin` (30 seconds by default) before it expires; concurrent callers share one refresh. Without a session, or once the service refuses it, `Token` returns `liveops.ErrSignedOut` and the saved session is deleted. ```go account := liveops.NewAccountForScope(cx, liveops.AccountOptions{ URL: "https://accounts.example.com", Audience: "cloudsave", }) if _, err := account.Token(ctx); errors.Is(err, liveops.ErrSignedOut) { err = account.SignInEmail(ctx, email, password) } cloud, err := liveops.NewCloudClient(liveops.CloudClientOptions{ URL: "https://saves.example.com", Token: account.Token, }) ``` Use one `Account` per audience: a token for `cloudsave` is refused by the game servers, and the other way round (see [Token audiences](http://nsgo.games/docs/accounts/#token-audiences)). ## Game-side client `liveops.NewAccount` keeps the long-lived session in a caller-supplied `SecretStore`, restores it on start, and hands out short-lived tokens for `AccountOptions.Audience` from `Token`, refreshing them before they expire with one request for all concurrent callers. `NewAccountForScope` adapts `core.Secrets`, the platform keychain, and keeps the session under `session` unless `SecretsKey` says otherwise. `Register` and `SignInEmail` save the new session; `LinkEmail`, `LinkIdentity` and `Profile` call the service with a token for its own audience, and `LinkIdentity` returns an `*AccountConflict` when the identity belongs to another account. `SignOut` revokes the session and deletes it from the keychain. A session the service no longer accepts makes `Token` sign out and return `ErrSignedOut`. Pass `Account.Token` to `CloudClientOptions.Token` or another service client. ## Public profiles `accounts.PublicDirectory` stores the public fields shown beside an account ID. `Set` normalizes usernames with NFKC and case folding, enforces the 3–20 character username policy and atomically claims names. `Users` batches lookups by IDs or usernames, returns each profile once in account ID order, and returns no email or linked identities. Set `UsernameCooldown` and `NameFilter` for game policy, and use `Now` for deterministic tests. The directory is provider-agnostic and can be backed by the account service or a database adapter. ## China anti-addiction rules The core-free `online/antiaddiction` package evaluates the mainland China minor play window using a server-supplied clock and holiday date set. It also exposes the under-8, 8–15 and 16–17 per-payment and monthly spending caps. Keep the clock and holiday calendar on the server. Client clocks and age flags are not authoritative. [Releasing in Mainland China](http://nsgo.games/docs/shipping-china/) covers the rest of the publishing requirements. See [Deploying backend services](http://nsgo.games/docs/backend-deploy/) for production store and daemon topology. --- Source: http://nsgo.games/docs/achievements/ # Achievements ```go import "github.com/nsgo-dev/game/pkg/online/achievements" ``` `achievements` declares a game's achievements once, in a versioned YAML file, tracks the player's progress toward them, and reports that progress through NSGo's [`gameservices`](https://nsgo.dev/docs/services/#game-services) package: Game Center on macOS, iOS and tvOS, and Google Play Games Services on Android. It uses only Go's standard library, NSGo's public API and the YAML library the module already depends on. ## The achievements file Each achievement has a game-wide `id` that game code uses, and the ID each platform service knows it by. Game Center IDs are chosen by the developer in App Store Connect and Play Games IDs are generated by Play Console, so each is written out; an achievement without an ID for a service is not reported to that service. ```yaml version: 1 achievements: - id: first-match title: First Match description: Clear your first line of gems. platforms: gameCenter: com.example.mygame.first_match playGames: CgkIxxxxxxxxxxEAIQAQ - id: gem-collector title: Gem Collector description: Clear 300 gems. steps: 300 platforms: gameCenter: com.example.mygame.gem_collector playGames: CgkIxxxxxxxxxxEAIQAg - id: high-roller title: High Roller hidden: true platforms: gameCenter: com.example.mygame.high_roller ``` | Field | Meaning | | --- | --- | | `version` | Schema version, `1` | | `id` | 1 to 128 ASCII letters, digits, `.`, `_` or `-`, unique in the file | | `title`, `description` | Optional text for the game's own UI; the platform screens show what their consoles hold | | `hidden` | The game's own UI should not reveal the achievement before it is unlocked | | `steps` | Steps that complete the achievement, 1 to `MaxSteps`; omitted means 1, a one-shot achievement | | `platforms.gameCenter`, `platforms.playGames` | The achievement's ID on each service: no whitespace or control characters, at most 255 bytes, and not shared by two achievements on the same service | `Parse` refuses unknown fields, a version other than 1, trailing YAML documents, duplicate IDs and malformed platform IDs. `Encode` writes deterministic 2-space YAML in the order above, and a file `Encode` wrote parses and encodes back to the same bytes, so a test can keep the file canonical: ```go //go:embed achievements.yaml var achievementsYAML []byte set, err := achievements.Parse(achievementsYAML) out, err := achievements.Encode(set) // equal to achievementsYAML when the file is canonical ``` ## Tracking progress A `Tracker` holds the steps the player has made toward each achievement of a `Set`. Progress only moves forward. - `Unlock(id)` completes an achievement; unlocking a completed one does nothing. - `Add(id, n)` adds steps and saturates at the achievement's step count; `SetSteps(id, n)` raises progress to `n` and ignores a lower count. - `Steps`, `Percent`, `Unlocked` and `Lookup` read the state; `Definitions` lists the achievements in declared order. - `OnUnlock(fn)` is called once when an achievement completes through `Unlock`, `Add` or `SetSteps`, never when progress is restored. - An ID the set does not declare returns an error wrapping `ErrUnknownAchievement`. ```go tracker, err := achievements.NewTracker(set) tracker.OnUnlock(func(d achievements.Definition) { status.Set("Achievement unlocked: " + d.Title) }) tracker.Unlock("first-match") tracker.Add("gem-collector", cleared) ``` The Tracker's methods are safe for concurrent use, and its callbacks run without its lock held, so they may call back into it. ## Saving progress `Persist(store, key)` loads the progress stored under `key`, if any, and from then on writes it back after every change. `core.Storage` is a `Store`, as is any type with `GetItem` and `SetItem`. When the stored progress cannot be parsed, `Persist` returns the error and changes nothing, so the game decides whether to discard it: ```go store := cx.Storage() if err := tracker.Persist(store, "mygame.achievements"); err != nil { store.RemoveItem("mygame.achievements") err = tracker.Persist(store, "mygame.achievements") } ``` The stored progress is a versioned YAML document, sorted by ID, holding the steps made and, per service, the steps that service last acknowledged: ```yaml version: 1 achievements: - id: first-match steps: 1 reported: gameCenter: 1 - id: gem-collector steps: 42 ``` `Progress` and `Restore` give and replace the same state in memory, and `ParseProgress` and `EncodeProgress` read and write it with the same rules as the achievements file. Restoring drops records for achievements the set no longer declares and caps steps at an achievement's step count. A failed save keeps the progress in memory and returns an error wrapping `ErrSave`; the next successful write saves it. ## Reporting to Game Center and Play Games `SignIn(cx, tracker, done)` picks the service for the running platform with `ServiceFor`, signs the player in with `gameservices.Authenticate` and, once the player is signed in, connects the Tracker to that service, which reports everything the service has not acknowledged. `done` runs on the engine goroutine with the player or the error: - `gameservices.ErrUnsupported` where the platform has no game service (Windows, Linux, the web, watchOS) or `cx.Env().CanUseGameServices()` is false. - `gameservices.ErrUnauthenticated` when the service answers without a signed-in player, and `gameservices.ErrCancelled` when the player dismisses sign-in. On failure the Tracker keeps counting, and a later `SignIn` reports what was made in the meantime. Answers from the service arrive through `cx`, so disposing `cx` or letting its current owner run again, as a view body does on every render, disconnects the Tracker; sign in from an event handler or an effect, or with a scope that lives as long as the game, such as the root scope, or call `SignIn` again from the next screen. `gameservices.ShowAchievements(cx)` opens the platform's own achievements screen. ```go signedIn := core.NewSignal(cx, false) achievements.SignIn(cx, tracker, func(_ gameservices.Player, err error) { signedIn.Set(err == nil) }) core.Show{ When: signedIn.Get, Then: func(*core.Scope) core.Node { return ui.Button{Text: "Achievements", OnPress: func() { gameservices.ShowAchievements(cx) }} }, } ``` The Tracker remembers, per service, the steps the service last acknowledged, so progress made offline or before sign-in is reported once a service is connected, and progress the service already has is not sent again. While a report is waiting for an answer, further progress on that achievement is held back and sent as one follow-up report, so a run of `Add` calls does not flood the service. A failed report stays pending: `OnError` receives it, and the next change, `Flush` or `Connect` sends it again. `Pending(service)` lists what a service has not acknowledged. Progress goes to the service as a percentage: a 300-step achievement with 42 steps is reported as 14%. Configure it in Play Console as a standard achievement, not an incremental one, since `gameservices` reports percentages. `Connect(service, reporter)` and `Disconnect` attach and detach a service directly, for a game that signs in by other means; `GameServices(cx)` is the `Reporter` backed by `gameservices.ReportAchievement`, and any type with a `ReportAchievement(id, percent, done)` method is a `Reporter`. A `Reporter` must answer every report exactly once; `GameServices(cx)` stops answering once `cx` is disposed, so call `Disconnect` then. ## Platform setup - **Game Center**: enable Game Center for the app's ID and create each achievement in App Store Connect, using the IDs in `platforms.gameCenter`. NSGo does not yet add the Game Center entitlement to the app it builds. - **Play Games**: create each achievement in Play Console and copy its generated ID into `platforms.playGames`. NSGo's `gameservices` has its Android side in place, but the Java runtime hook that reaches Play Games Services is not in NSGo's runtime yet, so `CanUseGameServices` is false on Android today and `SignIn` answers `ErrUnsupported` there; progress is still kept and is reported once that hook ships. ## Testing NSGo's `nsgotest` gives each test app an in-memory game services fake. Enable it with `nsgotest.Environment(core.Environment{OS: core.OSAndroid, CanUseGameServices: true})`, sign a player in with `App.SetGameServicesPlayer`, and read what was reported with `App.GameServicesAchievements`: ```go app := nsgotest.Start(t, root, nsgotest.Environment(core.Environment{OS: core.OSMacOS, CanUseGameServices: true})) app.SetGameServicesPlayer(gameservices.Player{ID: "p1", DisplayName: "Ada"}) // ... play until the achievement unlocks ... app.Settle() got := app.GameServicesAchievements() // [{ID: "com.example.mygame.first_match", PercentComplete: 100, Unlocked: true}] ``` `App.SetGameServicesError` and `App.SetGameServicesAuthError` simulate an outage or a cancelled sign-in. The [SlideGem example](https://github.com/nsgo-dev/game/tree/main/examples/slidegem) unlocks its first achievement on Game Center and on Play Games this way. ## Steam achievement IDs Add an optional `steam` ID under `platforms` with the achievement's API name in Steamworks. It is validated, checked for duplicates and written back like the Game Center and Play Games IDs, and files without it load unchanged. The `Tracker` does not report to Steam yet: `ServiceFor` never picks `Steam`, so pass `Platforms.ID(achievements.Steam)` to `online/steam`'s `Platform.Unlock` yourself. --- Source: http://nsgo.games/docs/admin/ # admin ```go import "github.com/nsgo-dev/game/pkg/online/admin" ``` `admin` gives the self-hosted services an operator door of their own: who the operators are, what each may do, how they sign in, and an audit record of every operator call that changes something. `accountsd`, `cloudsaved` and `leaderboardd` serve it on a second listener when their configuration has an `admin:` block, and a dedicated server can mount `gameserver.Inspector` on the same foundation. Operator routes never mount on a player-facing listener. It is server-side code and does not depend on NSGo. ## Turning it on Add an `admin:` block at the end of the daemon's configuration file (`accounts.yaml`, `cloudsave.yaml` or `leaderboards.yaml`): ```yaml admin: addr: 127.0.0.1:9090 operators: operators.yaml audit: audit allowedOrigins: - https://console.example.com sessionTTL: 8h idleTimeout: 30m ``` | Field | Meaning | | --- | --- | | `addr` | Address of the admin listener. It must differ from the daemon's `-addr`; keep it on a private network or behind a proxy only operators reach. | | `operators` | The operators file. Its TOTP secrets, when an operator needs them, are in the file of the same name ending in `.totp.yaml`. | | `audit` | Directory of the audit log, one JSON Lines file per UTC day ([audit log](http://nsgo.games/docs/formats/#audit-log)). | | `allowedOrigins` | Web origins of an operator console allowed to use a session from a browser. Command-line tools that use tokens need no entry. | | `sessionTTL` | How long a session lasts from sign-in, 1m to 24h; 8h when omitted. | | `idleTimeout` | How long a session lasts without a request, 1m to the session TTL; 30m (or the TTL, when shorter) when omitted. | Relative paths are relative to the configuration file's directory. Without the block the daemon has no admin listener and answers 404 for every `/admin/` path. The daemon reloads the operators and secrets files within a few seconds of a change; if the new files do not load, it logs why and keeps the previous ones. ## Operators and roles `operators.yaml` lists the operators, each with a role and an argon2id password hash, never a plaintext password: ```yaml version: 1 operators: - id: ada role: owner password: $argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaGhhc2g totp: required - id: ci role: viewer tokensNotBefore: "2026-11-30T12:00:00Z" roles: support-lead: - '*.read' - accounts.* ``` An operator ID is 1 to 64 characters of `a-z`, `0-9`, `.`, `_` and `-`; audit records name it as `op:`. An operator without a password cannot sign in with a session and uses bearer tokens only, as a CI job does. `totp: required` adds a code from an authenticator app at sign-in. `tokensNotBefore`, a UTC time in whole seconds, refuses the operator's bearer tokens issued before it. A permission is a `service.action` string, such as `accounts.suspend` or `cloudsave.restore`. A role grants a list of patterns: `*` (everything), `service.*` (every action of one service), `*.action` (one action of every service) or an exact permission. `*.read` grants `accounts.read` but not `cloudsave.read.payload`, so reading a save's contents, which may hold personal data, needs its own grant. The built-in roles: | Role | Patterns | | --- | --- | | `viewer` | `*.read`, which includes `audit.read`: the audit log, with every operator's actions and failed sign-ins | | `support` | `*.read`, `accounts.export`, `accounts.revoke`, `accounts.suspend`, `cloudsave.read.payload`, `cloudsave.restore` | | `moderator` | `*.read`, `accounts.revoke`, `accounts.suspend`, `leaderboard.delete`, `leaderboard.hide` | | `operator` | `*.read`, `accounts.*`, `cloudsave.*`, `leaderboard.*`, `server.*` | | `owner` | `*` | A file may define more roles under `roles:`, but not redefine a built-in one. The permissions this package and `gameserver.Inspector` check are `audit.read` (the audit log), `server.read` (a game server's runtime, matches, rooms and peers) and `server.pprof` (its profiles); each service names its own operator routes' permissions on its page, such as cloud save's [operator routes](http://nsgo.games/docs/cloudsave/#operator-routes). ## Managing operators `game admin` edits the files, so no one writes a hash or a secret by hand: ```sh printf '%s\n' "$ADA_PASSWORD" | go tool game admin operator add -role owner -totp ada go tool game admin operator add -role viewer -no-password ci printf '%s\n' "$NEW_PASSWORD" | go tool game admin operator passwd ada go tool game admin operator totp ada go tool game admin operator totp -off ada go tool game admin operator revoke-tokens ci ``` `-file` names the operators file (`operators.yaml` by default). A password is read from the first line of standard input, 12 to 1024 characters; the line is echoed on a terminal, so pipe it in from a password manager or a secret store. `add -totp` and `totp` write a new 160-bit secret to the `.totp.yaml` file, readable by its owner alone, and print it with its `otpauth://` URI for an authenticator app (`-issuer` sets the name the app shows). `revoke-tokens` sets the operator's `tokensNotBefore` to now, so every bearer token issued for it until then is refused; `add` sets it too, so the tokens of an earlier operator with the same ID stay refused. Keep the `.totp.yaml` file out of version control; the operators file holds no secret in the clear and may be reviewed like any other text file. Both formats are on [File Formats](http://nsgo.games/docs/formats/#operators). ## Signing in A browser console signs in with a session: ```http POST /admin/v1/session Content-Type: application/json {"operator": "ada", "password": "...", "totp": "123456"} ``` The answer is `{"service", "operator", "role", "permissions", "via": "session", "csrf", "expires"}` and a `nsgo_admin_` cookie (such as `nsgo_admin_accounts`, so the listeners of several services on one host keep their sessions apart) that is `HttpOnly`, `SameSite=Strict`, limited to `/admin/` and `Secure` behind TLS (or a proxy that sets `X-Forwarded-Proto: https`). A wrong operator, password or code all answer 401 `invalid_credentials`. A TOTP code is good for its 30-second step and one step on either side, and is accepted once: signing in again with the same code, even within its window, is refused, on every service that shares the operators file and after a restart. The listeners record the codes they accept in the `.totp-used` directory beside the operators file (`operators.totp-used` for `operators.yaml`), which each daemon needs to be able to write; a TOTP sign-in that cannot be recorded there answers 503. Five refusals in a row lock the operator ID for five minutes (429 `locked`), and an ID never has more sign-ins in flight than it has refusals left, so attempts sent at once are refused with 429 rather than checked. Sessions live in the daemon's memory, so a restart signs everyone out; a session also ends when its operator leaves the operators file or changes password. Every state-changing request made with the cookie must carry the session's CSRF token in `X-CSRF-Token` and an `Origin` header naming an allowed origin or the listener itself; otherwise it gets 403 `csrf`. A sign-in from a browser must come from such an origin too. `GET /admin/v1/whoami` returns the operator, its role and permissions, and for a session the CSRF token again, so a reloaded console page can pick it up. `DELETE /admin/v1/session` signs out. ## Tokens for tools and CI A command-line tool or a CI job sends `Authorization: Bearer ` instead, with a token for the `admin` audience signed by the account service's key. Mint one where the key is: ```sh accountsd admin-token -config accounts.yaml -key key.pem -operator ci -ttl 24h ``` The operator must be in the operators file the configuration's `admin:` block names, or the one `-operators` names when `accounts.yaml` has no such block. The token's subject is `op:ci`; every daemon's admin listener accepts it with the key set it already verifies players with, for as long as `-ttl` (1m to 720h), the operator stays in its operators file and the token was issued no earlier than the operator's `tokensNotBefore`. A password change does not end tokens: `game admin operator revoke-tokens` does. A request with a token needs no CSRF token, since a browser never attaches one by itself. The account service never issues a player a token for the `admin` audience: every service's configuration refuses `admin` as its audience. ## Audit log Every state-changing request, refused or not, writes an `audit.Record`: the actor `op:`, the route's action (such as `accounts.suspend`), what it acted on, and the method, path, status and whether it came with a session or a token. A missing permission writes `admin.denied` for reads too. Sign-in writes `admin.signin` or `admin.signin.failed`, and sign-out `admin.signout`. A request with no session or token is refused with 401, and recorded as `admin.denied` by `anonymous` when it would have changed something. Every record the listener writes has the remote address in `remote`; behind a proxy that is the proxy's. Anonymous requests cost their sender nothing, so their records (`admin.denied` by `anonymous` and `admin.signin.failed`) are limited to 30 a minute per remote address; the next record from that address once a minute has passed counts the ones left out in `suppressed`. Operators' records are never left out: they wait up to ten seconds for room in the audit log's queue. A sign-in whose record cannot be queued in that time is refused with 503 `audit_unavailable`; the record of a call already made is written to the daemon's log instead. The daemon also logs an error whenever the audit log drops records. `GET /admin/v1/audit` reads the records back for operators with `audit.read`: | Parameter | Meaning | | --- | --- | | `from`, `to` | RFC 3339 times; records at or after `from` and before `to`. | | `actor` | Only this actor, such as `op:ada`. | | `action` | Only this action, or with a trailing `*` (`accounts.*`) every action that starts with it. | | `limit` | At most this many records, 1 to 1000 (the default). | | `cursor` | Continue from the `next` of the previous answer. | The answer is `{"records": [{"time", "actor", "action", "subject", "data"}], "next", "corrupt"}` in the order the records were written; `next` is absent once there is nothing more, and `corrupt`, present when not zero, counts lines skipped because they are not records, such as one torn by a crash. A last line still being written is left for a later read. ## Routes of a service A service registers its operator routes on the listener's `Server`, each with the one permission it requires (the account service's are listed in [accounts](http://nsgo.games/docs/accounts/#operator-routes)): ```go err := srv.Handle(admin.Route{ Method: http.MethodPost, Path: "/admin/v1/accounts/{id}/suspend", Permission: "accounts.suspend", Handler: func(w http.ResponseWriter, r *http.Request, c *admin.Call) { c.SetSubject("account:" + r.PathValue("id")) c.Set("until", until) // ... }, }) ``` `leaderboardd` serves the leaderboard's routes this way: listing boards and entries, deleting and hiding an account's entries and resetting a board (see [leaderboard/selfhost](http://nsgo.games/docs/leaderboard-selfhost/#operator-routes)). The `Server` authenticates the request, checks the CSRF token and the permission, runs the handler and writes the audit record with the handler's subject and details and the status it answered; `AuditReads` audits a `GET` route too, for reads of personal data. A daemon passes its routes to `admin.Listen` in `ListenOptions.Routes`. A handler that authorizes requests itself, such as `gameserver.Inspector`, mounts with `Server.Mount`; `admin.Require(authorizer, w, r, permission)` is the same check for any handler, and `*admin.Server` is the `Authorizer` it takes. With a `*admin.Server`, `Require` records the refusals a route records; a mounted handler that changes state writes the audit record of each call it makes itself: ```go insp := gameserver.NewOperatorInspector(srv) // server.read; server.pprof for profiles insp.Pprof = true _ = srv.Mount("/admin/v1/runtime", insp) _ = srv.Mount("/admin/v1/pprof/", insp) ``` --- Source: http://nsgo.games/docs/agent-eval/ # Agent evaluation catalog `tools/agenteval` grades coding agents on versioned task YAML files under `tools/agenteval/tasks/`; its [README](https://github.com/nsgo-dev/game/blob/main/tools/agenteval/README.md) describes the modes, the rubric and how to run it. ## Tool coverage A task may list `required_tools` under `checks` to declare the editor and runtime MCP tools it is meant to exercise. The names are checked against a known catalog: `game_scenes_list`, `game_layers_list`, `game_entities_list`, `game_entity_inspect`, `game_input_action`, `game_input_pointer`, `scene_edit`, `file_edit`, `datatable_review_propose`, `game_check`, `game_replay_list` and `game_replay_play`. An unknown or duplicate name fails task loading. The list is metadata for reviewing coverage. The built-in agent can inspect and call staged MCP servers through `mcp_list_tools` and `mcp_call`, while command mode agents use the staged `mcp.json` directly. ## Task families A task may declare `family` as `create`, `editor`, `debug`, `3d`, `data`, `code` or `safety`, and `mcp_servers`, the names of the MCP servers it expects an agent to use, such as `[nsgo]`. An unknown family, an empty or whitespace-containing server name, or a duplicate server name fails task loading. Both fields are optional. `platformer-level`, `add-enemy-type` and `add-menu` are `create` tasks and `editor-workflow` is an `editor` task, all on `[nsgo]`, the only server the staged `mcp.json` configures today. In built-in agent mode, the `nsgo` server connects lazily on the first MCP call in the staged workspace and closes when the task ends. ## Tasks `editor-workflow` asks for the same menu as `add-menu` and is graded by the same rubric, with a prompt that directs the agent to inspect scenes and layers before editing, edit through `scene_edit` and validate with `game_check`. Task metadata may declare one family (`create`, `editor`, `debug`, `3d`, `data`, `code`, or `safety`) and the MCP servers it expects. The loader rejects unknown families, empty or whitespace-containing server names, and duplicates so coverage reports remain reviewable. ## Repeated trials A live agent does not give the same result on every run, so one run per task can turn normal variance into a pass or a failure. `-trials N` (default 1) runs every selected task N times, each in a freshly staged workspace, so no trial sees another's edits or caches: ```sh go run ./tools/agenteval -mode=agent -trials 3 -out agent-eval-agent-report.json ``` Each task in the JSON report then carries: - `trials`: the number of trials run. - `pass_rate`: the fraction of trials that reached the task's passing score. - `mean_score`: the mean score over the trials; `score` is this value rounded. - `stddev`: the population standard deviation of the scores. A task passes only when every trial passes. Its `criteria`, `agent_output` and `agent_error` come from the first failing trial, or from the first trial when all pass, and `duration_ms`, `agent_turns`, `agent_tool_calls` and the token counts are summed over every trial. With more than one trial the Markdown summary prints these statistics above each task's criterion breakdown. ## Comparing reports Reports also record `commit_sha` and a deterministic `context_hash` over the staged docs and skill. Pass a previous JSON report with `-compare report.json` to print criteria whose pass state changed. Comparisons are ignored when mode or model differs, so model upgrades do not create false regressions. The scheduled workflow still owns retention and history publishing. --- Source: http://nsgo.games/docs/agent-skill/ # Agent Skill The repository publishes an Agent Skill at [`skills/nsgo-game`](https://github.com/nsgo-dev/game/blob/main/skills/nsgo-game/SKILL.md) so coding agents know how to scaffold, build, test, inspect and drive NSGo games using the `go tool game` CLI, plain-text YAML formats and the `game/mcp` tool suite. ## Install Claude Code and Codex install the skill, an onboarding skill ([`skills/nsgo-game-onboarding`](https://github.com/nsgo-dev/game/blob/main/skills/nsgo-game-onboarding/SKILL.md)) and both local MCP servers in one step from this repository's plugin: `nsgo-game-editor` runs `go tool game mcp` (the editor) and `nsgo-game` runs `go tool nsgo mcp` (the running game), both in the project directory. In Claude Code: ```text /plugin marketplace add nsgo-dev/game /plugin install nsgo-game@nsgo-dev ``` In Codex, add the `nsgo-dev/game` repository as a plugin marketplace (`.agents/plugins/marketplace.json`) and install `nsgo-game` from it. The manifests are [`.claude-plugin/plugin.json`](https://github.com/nsgo-dev/game/blob/main/.claude-plugin/plugin.json) and [`.codex-plugin/plugin.json`](https://github.com/nsgo-dev/game/blob/main/.codex-plugin/plugin.json). The onboarding skill keeps unrelated MCP servers, installs only what is missing, and proves the editor connection with a read-only `selection_get` call instead of reporting success because a configuration file exists. For an agent without the plugin, `go tool game mcp prompt -host claude|codex|other` prints a setup prompt with the same steps to paste into it ([`game mcp`](http://nsgo.games/docs/cli/#mcp)), and the Connect dialog's Copy setup prompt button copies the host-neutral prompt directly. ### Manual install Install the skill with `bunx skills add`: ```sh bunx skills add nsgo-dev/game ``` Pair it with NSGo's own `nsgo` skill for core UI primitives, signals, `nsgotest` and `go tool nsgo`: ```sh bunx skills add nsgo-dev/nsgo ``` To let an agent inspect and drive a running game live, register both project MCP servers: ```sh go tool game mcp install ``` ## What the skill covers - **[`SKILL.md`](https://github.com/nsgo-dev/game/blob/main/skills/nsgo-game/SKILL.md)**: project rules (Go only, plain-text versioned YAML formats, `go tool nsgo check`/`test`, stability tiers), quick-start CLI workflow, minimal `game.Loop` + `mcp.Attach` wiring, and the deterministic MCP verification loop. - **[`references/packages.md`](https://github.com/nsgo-dev/game/blob/main/skills/nsgo-game/references/packages.md)**: complete grouped catalog of every package in `github.com/nsgo-dev/game`, with import paths and stability status matching [API Stability](http://nsgo.games/docs/stability/). - **[`references/cli-and-formats.md`](https://github.com/nsgo-dev/game/blob/main/skills/nsgo-game/references/cli-and-formats.md)**: all `go tool game` subcommands ([Command Reference](http://nsgo.games/docs/cli-reference/)), companion module tools, the YAML format contract ([File Formats](http://nsgo.games/docs/formats/)), JSON Schemas ([Schemas](http://nsgo.games/docs/schemas/)) and native external formats (Tiled, LDtk, Aseprite, TexturePacker, BMFont, glTF, Yarn). - **[`references/mcp-tools.md`](https://github.com/nsgo-dev/game/blob/main/skills/nsgo-game/references/mcp-tools.md)**: `mcp.Bridge` setup ([mcp](http://nsgo.games/docs/mcp/)) and the full tool catalog covering scene/entity inspection, fixed-step loop control, game-coordinate input, live spawning and component editing, screenshots with diagnostic overlays, debug console tunables, input recording/replay, performance telemetry and live asset hot reload. ## Typical agent workflow 1. Scaffold with `go run github.com/nsgo-dev/game/cmd/game@latest new` and add building blocks with `go tool game generate`, `go tool game assets` and `go tool game check`. 2. Before building or releasing, run `go tool game doctor -json` and fix every error finding. The JSON finding objects are suitable for an agent or editor to parse. 3. Attach `mcp.Bridge` on the game's `*core.Scope` and run `go tool nsgo dev -automation` (or `nsgotest.Start` in tests). 4. Drive reproducible checks through MCP: pause with `game_loop_pause`, seed with `game_loop_seed`, inject inputs or spawn entities, advance synchronously with `game_loop_step`, inspect entities with `game_entities_list` / `game_entity_inspect` / `game_component_get`, and capture overlays with `game_screenshot`. ## New project agent files Every starter template includes `AGENTS.md` with the project rules and commands an agent should run, plus `CLAUDE.md` importing it for Claude Code. After creating a project, use `go tool game mcp install` to configure the editor and game MCP connections, then run the relevant `go tool nsgo check` and `go tool nsgo test` commands before changing code. --- Source: http://nsgo.games/docs/ai/ # ai `game/ai` provides deterministic game AI building blocks stepped cleanly on `game.Loop`: steering behaviors, velocity-based local avoidance (ORCA) in 2D and 3D XZ, behavior trees, utility AI scoring, goal-oriented action planning (GOAP), attack tokens and squads, spatial influence maps, EQS-style tactical position queries with cover points and reservations, perception with sight, hearing and memory, and smart objects with claimable interaction slots. Grids, A*, graphs, waypoints and 2D navigation meshes are in [pathfind](http://nsgo.games/docs/pathfind/). ```go import "github.com/nsgo-dev/game/pkg/ai" ``` Nothing in `ai` uses background goroutines or hidden global randomness. ## Steering behaviors `Agent` integrates smooth 2D steering forces (`MaxSpeed`, `MaxForce`, `Radius`) on fixed steps via `Agent.Step(force, dt)`: ```go agent := ai.Agent{ Pos: core.Point{X: 20, Y: 20}, MaxSpeed: 120, MaxForce: 300, Radius: 10, } var followState ai.PathFollowState // Inside game.Loop.Update: force := ai.Combine(agent.MaxForce, ai.WeightedForce{Force: ai.FollowPath(agent, waypoints, &followState, 8, false), Weight: 1.0}, ai.WeightedForce{Force: ai.Separation(agent, nearbyAgents, 24), Weight: 1.5}, ) agent.Step(force, dt) ``` Built-in 2D steering functions: | Function | Behavior | | --- | --- | | `Seek(a, target)` | Accelerates toward `target` at `MaxSpeed`. | | `Arrive(a, target, slowRadius)` | Scales desired speed smoothly down to zero inside `slowRadius`. | | `Flee(a, threat, panicRadius)` | Accelerates away from `threat` while closer than `panicRadius` (or always if `<= 0`). | | `Pursue(a, target, maxLookAhead)` | Intercepts a moving `target` by predicting its position from `target.Vel`, capped to `maxLookAhead` seconds when positive. | | `Evade(a, pursuer, panicRadius, maxLookAhead)` | Flees the predicted position of `pursuer` while closer than `panicRadius` (or always if `<= 0`). | | `OffsetPursuit(a, leader, localOffset, slowRadius, maxLookAhead)` | Follows `leader` at a heading-frame offset (`X` forward, `Y` left) using `Arrive`. | | `FollowPath(a, path, &state, radius, loop)` | Follows waypoints, using `Arrive` on the final waypoint when `loop` is `false`. | | `Separation(a, neighbors, desiredSep)` | Pushes away from close neighbors (defaults to `a.Radius + neighbor.Radius` when `<= 0`). | | `Alignment(a, neighbors, radius)` | Steers toward the average heading of neighbors within `radius`. | | `Cohesion(a, neighbors, radius)` | Steers toward the center of mass of neighbors within `radius`. | | `ObstacleAvoidance(a, obstacles, maxAhead)` | Deflects around the nearest circular `Obstacle` intersecting the forward detection corridor. | | `WallAvoidance(a, walls, feelerLength)` | Keeps clear of `Wall` line segments using three forward feelers and direct radius containment. | | `Hide(a, pursuer, obstacles, standoff, slowRadius)` | Picks the closest hiding spot behind a circular `Obstacle` opposite `pursuer` (falls back to `Evade` if none exist). | | `Interpose(a, targetA, targetB, slowRadius)` | Intercepts the predicted midpoint between two moving agents. | | `Wander(a, &state, radius, dist, jitter, nextRand)` | Smooth random wandering using your deterministic `nextRand() float32` in `[0, 1)`. | | `Combine(maxForce, forces...)` | Sums weighted forces and clamps magnitude to `maxForce`. | | `CombinePrioritized(maxForce, forces...)` | Spends `maxForce` in priority order (e.g. `WallAvoidance` before `FollowPath`), ignoring lower-priority forces once the budget is saturated. | ### Zero-allocation flocking with `NeighborGrid` For large flocks, index agents once per step in a `NeighborGrid` so `Rebuild`, `Query`, and `QueryInto` reuse internal buffers with zero heap allocations after warm-up: ```go grid := ai.NewNeighborGrid(48) // Inside game.Loop.Update: grid.Rebuild(agents) for i := range agents { neighbors := grid.Query(agents[i].Pos, 48) forces[i] = ai.CombinePrioritized(agents[i].MaxForce, ai.WeightedForce{Force: ai.Separation(agents[i], neighbors, 18), Weight: 1.6}, ai.WeightedForce{Force: ai.Alignment(agents[i], neighbors, 45), Weight: 1.0}, ai.WeightedForce{Force: ai.Cohesion(agents[i], neighbors, 48), Weight: 0.9}, ) } for i := range agents { agents[i].Step(forces[i], dt) } ``` ### 3D and XZ-plane steering `Agent3D`, `Vec3`, `Obstacle3D`, `Wall3D`, `WeightedForce3D`, and `NeighborGrid3D` provide the matching 3D steering suite (`Seek3D`, `Arrive3D`, `Flee3D`, `Pursue3D`, `Evade3D`, `OffsetPursuit3D`, `FollowPath3D`, `Separation3D`, `Alignment3D`, `Cohesion3D`, `ObstacleAvoidance3D`, `WallAvoidance3D`, `Hide3D`, `Interpose3D`, `Combine3D`, `CombinePrioritized3D`). `ai.Vec3` shares the exact `X, Y, Z float32` layout of `math3d.Vec3` (right-handed Y-up: `+X` right, `+Y` up, `-Z` forward), so values convert with `ai.Vec3(v)` at zero cost while keeping `game/ai` free of experimental imports. Set `Agent3D.PlanarXZ = true` for grounded agents following `pathfind3d.NavMesh` paths on the horizontal XZ plane: ```go rawPath, ok := navMesh3D.FindPath(start, goal) if ok { path := make([]ai.Vec3, len(rawPath)) for i, p := range rawPath { path[i] = ai.Vec3(p) } agent := ai.Agent3D{Pos: ai.Vec3(start), MaxSpeed: 12, MaxForce: 40, Radius: 0.5, PlanarXZ: true} var st ai.PathFollowState force := ai.FollowPath3D(agent, path, &st, 0.8, false) agent.Step(force, dt) } ``` ## Velocity-based local avoidance (ORCA) Push-apart separation reacts only after bodies overlap, causing head-on deadlocks and jostling in doorways. `ORCASolver` implements Optimal Reciprocal Collision Avoidance (RVO2-style velocity obstacles with 2D linear programming and minimum-penetration infeasible fallback) so agents steer smoothly around neighbors and static obstacle edges before contact: ```go solver := ai.NewORCASolver(ai.ORCAConfig{ TimeHorizon: 2.0, // seconds to look ahead for agents TimeHorizonObst: 1.0, // seconds to look ahead for static walls MaxNeighbors: 16, }) walls := []ai.ORCAObstacle{ {A: math2d.V2(-12, 0), B: math2d.V2(-1.5, 0)}, {A: math2d.V2(1.5, 0), B: math2d.V2(12, 0)}, } // Inside game.Loop.Update: for i := range agents { agents[i].PrefVel = desiredVelocity(agents[i], goals[i]) } // Step updates Vel and Pos synchronously, or call Solve(out, agents, walls, dt) // to obtain collision-free velocities without mutating agent positions. solver.Step(agents, walls, dt) ``` - **2D and 3D XZ-plane sharing**: use `Solve`, `SolveAgent`, and `Step` with `ORCAAgent` / `ORCAObstacle` (`math2d.Vec2`) in 2D, or `SolveXZ`, `SolveAgentXZ`, and `StepXZ` with `ORCAAgent3D` / `ORCAObstacle3D` (`ai.Vec3`) so 2D and grounded 3D navmesh agents share the same solver while preserving `Pos.Y` and zeroing `Vel.Y`. - **Static obstacle edges**: `ORCAObstacle` line segments are treated as two-sided (winding-agnostic) and act as hard constraints during LP3 infeasible fallback so overcrowded agents stay clear of walls and doorway jambs. - **Layers, masks, and priority**: set `Layer` (zero defaults to `ORCALayerDefault`, bit 0) and `Mask` (zero defaults to `ORCAMaskAll`; obstacle `Layer` 0 also defaults to `ORCAMaskAll`) to separate movement domains such as ground vs. air. When an agent avoids a non-cooperative neighbor whose `Mask` ignores it, or a `Stationary` / zero-`MaxSpeed` neighbor, it automatically takes full avoidance responsibility (`1.0`). Among cooperative neighbors, higher `Priority` smoothly yields less (`pB / (pA + pB)`) so holding-position units hold their ground while lower-priority units steer around them. - **Deterministic and zero-allocation**: internal spatial-hash neighbor lookups and candidate/obstacle sorting canonicalize every constraint by distance and intrinsic agent properties before solving the LP, so shuffling neighbor or obstacle order produces bit-identical velocities and replays produce identical positions every step. Reusing `ORCASolver` and output buffers allocates `0 B/op` after warm-up. ## Behavior trees Compose enemy decision logic from `Node` trees returning `StatusSuccess`, `StatusFailure`, or `StatusRunning` on each `Tick(dt)`: ```go tree := ai.Selector( ai.Guard(playerInRange, ai.Sequence( ai.Cooldown(1500*time.Millisecond, ai.Action(attackPlayer)), ai.Wait(300*time.Millisecond), )), ai.Sequence( ai.Condition(hasPatrolPath), ai.Action(patrolStep), ), ) // Inside game.Loop.Update: tree.Tick(dt) ``` Available nodes: - **Composites**: `Sequence`, `Selector` (preempts and resets lower-priority running branches when a higher-priority branch succeeds or runs), `Parallel(policy, ...)` (`RequireAll` or `RequireOne`), `RandomSelector(stream, ...)`, `RandomSequence(stream, ...)`, `WeightedSelector(stream, options...)` (using `WeightedNode{Node, Weight}`), `UtilitySelector(reasoner, ctx, rng, subtrees)`. - **Decorators**: `Guard(cond, child)`, `BlackboardCondition(bb, key, op, value, abort, child)`, `Cooldown(d, child)` (tracks elapsed tree time even while its branch is not ticked and survives `Reset()` from interruptions; call `ResetCooldowns(root)` or `bt.ResetCooldowns()` to clear active cooldowns explicitly, such as on respawn), `TimeLimit(d, child)`, `Retry(n, child)`, `Service(interval, fn, child)`, `WithAttackToken(pool, agentID, priority, child)`, `Inverter`, `Succeeder`, `Failer`, `Repeater(count, child)`, `UntilFail`. - **Leaves**: `Action(fn)`, `Condition(fn)`, `Wait(d)`, `HasAttackToken(pool, agentID)`, `SquadHasOrder(squad, kind)`, `SquadHasRole(squad, agentID, role)`, `SquadStateBool(squad, key)`, `SquadOrderAction(squad, fn)`. ### Blackboard and observer aborts `Blackboard` holds typed keys (`bool`, `int`, `float64`, `string`, 2D vectors via `math2d.Vec2` / `core.Point`, 3D vectors via `ai.Vec3`, and `uint64` entity IDs) scoped per agent with an optional shared parent blackboard for a squad or team (`NewChildBlackboard(parent)`). Reads fall back to the parent when a key is not set locally; `Set*` writes locally and `SetShared*` targets the parent. `KeyRevision(key)` and `Revision()` track mutations monotonically without heap allocations, and `Watch(key, fn)` delivers synchronous change notifications (propagating non-shadowed parent updates) with a returned cancel function. `BlackboardCondition(bb, key, op, value, abort, child)` compares `key` using `BBOpEq`, `BBOpNe`, `BBOpLt`, `BBOpLte`, `BBOpGt`, `BBOpGte`, `BBOpSet`, or `BBOpUnset` (omitting `child` uses it as a condition leaf). Its `AbortMode` controls how key changes interrupt running branches: - `AbortNone` (`none`): checks the condition only on entry. - `AbortSelf` (`self`): resets its own running child (or an enclosing `Sequence`'s later running child when used as a leaf) on the next tick if the watched key changes and the condition becomes false. - `AbortLower` (`lower`): aborts a running lower-priority sibling in an enclosing `Selector` on the next tick when the watched key changes and the condition becomes true. - `AbortBoth` (`both`): combines `AbortSelf` and `AbortLower`. A `Selector` uses key-driven observer preemption only for higher-priority branches whose gating is governed solely by `BlackboardCondition` nodes (such as a `BlackboardCondition` wrapping actions, or a `Sequence` whose gating prefix consists solely of `BlackboardCondition` nodes). When a higher-priority branch mixes `BlackboardCondition` with plain `Condition`, `Guard`, `WithAttackToken`, or another non-blackboard gating node, `Selector` re-evaluates that branch on every tick so non-blackboard conditions still preempt running lower-priority siblings, while `AbortSelf` and `AbortBoth` continue to self-abort when the watched key changes. ```go squadBB := ai.NewBlackboard() agentBB := ai.NewChildBlackboard(squadBB) agentBB.SetBool("enemy_seen", false) tree := ai.Selector( ai.BlackboardCondition(agentBB, "enemy_seen", ai.BBOpEq, ai.BBBool(true), ai.AbortBoth, ai.Action(chaseTarget), ), ai.Action(patrol), ) ``` ### Behavior trees in YAML Author behavior trees in versioned `*.bt.yaml` files (`version: 1`, JSON Schema `https://nsgo.games/schemas/bt.v1.json`) with `ParseBehaviorTree` / `ParseBehaviorTreeWith`, `LoadBehaviorTreeFS`, `EncodeBehaviorTree`, `BuildBehaviorTree`, and `BuildBehaviorTreeFS`: ```go doc, err := ai.LoadBehaviorTreeFS(assetsFS, "ai/guard.bt.yaml") if err != nil { return err } tree, err := ai.BuildBehaviorTree(doc, ai.BTBindings{ Blackboard: agentBB, Stream: rng, FS: assetsFS, Actions: map[string]func(ai.BTNodeContext) (ai.Node, error){ "attack": func(ctx ai.BTNodeContext) (ai.Node, error) { dmg, _ := ctx.Params.Int("damage") return ai.Action(func(dt time.Duration) ai.Status { return doAttack(dmg) }), nil }, }, }) ``` - Supports every built-in composite and decorator (`sequence`, `selector`, `parallel`, `random_selector`, `random_sequence`, `weighted_selector`, `guard`, `cooldown`, `time_limit`, `retry`, `service`, `inverter`, `succeeder`, `failer`, `repeater`, `until_fail`, `blackboard_condition`), `wait`, game-registered `action` / `condition` leaves with typed `params`, and `subtree` references by `path` with `${param}` parameter substitution and `keys` blackboard key remapping. - `ParseBehaviorTreeWith`, `LoadBehaviorTreeFS`, and `BuildBehaviorTree` refuse unknown fields, unknown node types, invalid operators or abort modes, trailing YAML documents, and circular subtree references, reporting file, line, column, field path, and fix hints via `*loaderr.Error`. - `EncodeBehaviorTree` writes canonical 2-space YAML prefixed with `BTSchemaComment` in fixed key order so load-and-save round trips change nothing. ### Timeouts, retries, deterministic random choices, and services - **`TimeLimit(d, child)`** fails and calls `child.Reset()` if `child` is still `StatusRunning` once `d` of game time has elapsed. - **`Retry(n, child)`** reruns a failing child up to `n` additional times (`1+n` total attempts), returning `StatusRunning` between attempts and `StatusSuccess` as soon as `child` succeeds. - **`RandomSelector(stream, children...)`** and **`RandomSequence(stream, children...)`** shuffle child order at the start of each run using a caller-supplied `*random.Stream` and keep that order across `StatusRunning` ticks until completion or `Reset()`. - **`WeightedSelector(stream, options...)`** draws `WeightedNode` children without replacement proportional to `Weight` using `stream` (skipping non-positive, `NaN`, or infinite weights and `nil` nodes), keeping a running child across ticks and remaining deterministic for a given seed. - **`Service(interval, fn, child)`** invokes `fn` immediately on entry into `child` and then every `interval` of game time while `child` continues returning `StatusRunning`, stopping cleanly when `child` finishes or is reset. ```go rng := random.New(42) combat := ai.Service(250*time.Millisecond, refreshTarget, ai.WeightedSelector(rng, ai.WeightedNode{Node: ai.TimeLimit(2*time.Second, chargeAttack), Weight: 2}, ai.WeightedNode{Node: ai.Retry(2, rangedShot), Weight: 3}, ), ) ``` ### Saving and restoring behavior tree state Save mid-run behavior tree state (for save slots, rollback netcode, or state dumps) with `SnapshotBehaviorTree` / `RestoreBehaviorTree`, or wrap a root `Node` in `NewBehaviorTree(root)` to call `bt.Snapshot()` and `bt.Restore(snap)`: ```go bt := ai.NewBehaviorTree(tree) bt.Tick(dt) // Capture every built-in stateful node by deterministic structural path ("0/1/2"). snap, err := bt.Snapshot() if err != nil { return err } data, err := yaml.Marshal(snap) // plain struct: marshals to YAML or JSON // Later, restore into a fresh tree of the exact same shape: var loaded ai.BehaviorTreeSnapshot if err := yaml.Unmarshal(data, &loaded); err != nil { return err } if err := freshBT.Restore(loaded); err != nil { return err // refuses mismatched tree shapes without mutating freshBT } ``` - **Complete built-in coverage**: captures progress for `Sequence`, `Selector`, `Parallel`, `Repeater`, `Cooldown`, `Wait`, `TimeLimit`, `Retry`, `RandomSelector`, `RandomSequence`, `WeightedSelector`, `Service`, `BlackboardCondition`, `Guard`, `WithAttackToken`, and `UtilitySelector`, plus wrapper/leaf kinds (`Inverter`, `Succeeder`, `Failer`, `UntilFail`, `Action`, `Condition`) so shape mismatches are always detected. - **Transactional shape validation**: `RestoreBehaviorTree` checks `Version`, every node's structural path and kind, `Parallel` policies, and state bounds before applying any change. Mismatched trees return an error wrapping `ErrInvalidBTSnapshot` naming the exact path and expected vs got kind without mutating the target tree. - **Custom and shared nodes**: custom `Node` implementations can participate by implementing `SnapshotNode` (`SnapshotKind`, `SnapshotState`, `RestoreState`), and custom composites or decorators can expose their children via `ChildNodes` (`Children() []Node`). If a tree uses `RandomSelector`, `RandomSequence`, or `WeightedSelector`, also save and restore the associated `*random.Stream` state for identical subsequent draws. ### Inspecting behavior trees Attach optional labels with `Named(name, child)` (or set `name:` on any node in `*.bt.yaml`, which `BuildBehaviorTree` preserves automatically) and inspect live execution with a reusable `BTInspector`: ```go tree := ai.Named("root", ai.Selector( ai.Named("attack", ai.Sequence( ai.Named("in_range", ai.Condition(playerInRange)), ai.Named("swing", ai.Action(attackPlayer)), )), ai.Named("patrol", ai.Action(patrolStep)), )) inspector := ai.NewBTInspector(tree) traceBuf := make([]ai.BTNodeTrace, 0, inspector.Len()) pathBuf := make([]ai.BTNodeTrace, 0, inspector.Len()) // Inside game.Loop.Update (zero heap allocations once warmed up): tree.Tick(dt) traceBuf = inspector.WalkInto(traceBuf) pathBuf = ai.RunningPathInto(pathBuf, traceBuf) _ = pathBuf ``` - **Read-only pre-order snapshots**: `WalkInto(dst)` (or one-shot `Walk()` / `InspectBehaviorTree(root)`) fills `BTNodeTrace` records (`Path`, `Depth`, `Name`, `Kind`, `LastStatus`, `Ticked`, `Active`, `StatusString()`) without mutating execution state or allocating per tick once `dst` has capacity `inspector.Len()`. - **Running path**: `Active` is `true` for every node along the currently running branch; extract that path with `RunningPathInto(dst, nodes)` or `inspector.RunningPath()`. - **Deterministic text for `statedump`**: `inspector.Format()` (or `FormatBTTrace(nodes)`) renders a canonical indented tree prefixed with `* ` on active nodes so a game can store it in [`statedump`](http://nsgo.games/docs/statedump/) `Values` (`dump.SetValue("guard_bt", inspector.Format())`) and diff AI decisions across runs. - **Live overlay & steering guides**: pass `gamedebug.BehaviorTreeSnapshot("guard", inspector)` to [`game/pkg/tooling/gamedebug`](http://nsgo.games/docs/gamedebug/) to show the tree with its running path highlighted, and call `overlay.DrawSteering` to draw velocity, desired velocity, target, and path guides (all stripped under `-tags release`). ## State trees A state tree describes designer-authored states, such as a guard's patrol and combat with nested attack and reposition, in a strict version 1 `*.statetree.yaml` file over the same blackboard and actions behavior trees use (JSON Schema `https://nsgo.games/schemas/statetree.v1.json`). `ParseStateTree` / `ParseStateTreeWith`, `LoadStateTreeFS`, `ValidateStateTree`, and `EncodeStateTree` read, check, and write it: ```go doc, err := ai.LoadStateTreeFS(assetsFS, "ai/guard.statetree.yaml") if err != nil { return err } ``` ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/statetree.v1.json version: 1 name: guard blackboard: - key: enemy_seen type: bool default: false states: - id: patrol tasks: - action: walk_route transitions: - trigger: condition conditions: - key: enemy_seen op: eq value: true to: combat - id: combat transitions: - trigger: event event: enemy_lost to: patrol children: - id: attack tasks: - action: attack params: damage: 15 transitions: - trigger: completed to: next - id: reposition tasks: - action: move_to_cover transitions: - trigger: completed to: combat/attack restart: true ``` - `parameters` declares default values for `"${name}"` references in condition values and task `params`, so one tree serves several characters; `blackboard` declares typed keys with optional defaults, as in a behavior tree. - Each state has an `id` unique in the tree (without `/`, and none of `next`, `parent`, `succeed`, and `fail`), `enter` conditions in the `blackboard_condition` vocabulary (`key`, `op`, `value`, `valueType`) that must all hold, `select: first | random | none` for how a state with children enters one, `tasks` (behavior tree actions by registered name with `params`, all ticked while the state is active), `completeWhen: all | any` for a state with tasks, `transitions`, and `children` in file order. - A transition fires on `trigger: completed | succeeded | failed | condition | event` (the key is not `on`, which YAML 1.1 readers take for the boolean `true`); `trigger: event` names its `event` and `trigger: condition` lists its `conditions`. `to` is a state id, a path from the root such as `combat/attack`, or one of `next`, `parent`, `succeed`, and `fail`, and every state target must exist in the tree. `priority` orders transitions that fire together, `delay` counts steps, and `restart: true` re-enters a target state that is already active. - Unknown fields, unsupported versions, trailing YAML documents, duplicate or reserved ids, invalid operators or values, unresolved targets, negative delays, and fields that do not apply (`select` without children, `completeWhen` without tasks, `event` or `conditions` on another trigger) are refused with file, line, column, field path, and fix hints via `*loaderr.Error`. - `EncodeStateTree` writes canonical 2-space YAML prefixed with `StateTreeSchemaComment` in fixed key order, so load-and-save round trips change nothing. The format is the current boundary: stepping a tree with `BTBindings`, snapshots, and the AI inspector view are follow-up work on #1725. ## Utility AI When agents weigh continuous factors (distance, health, ammo, threat) instead of fixed boolean priorities, score candidate `UtilityAction`s with a `Reasoner[C]` using Dave Mark's Infinite Axis Utility System (IAUS): ```go type UnitState struct { HP float64 EnemyDst float64 Potions float64 } reasoner := ai.NewReasoner( ai.UtilityAction[UnitState]{ Name: "attack", Weight: 1.2, Considerations: []ai.Consideration[UnitState]{ { Name: "close", Input: func(s UnitState) float64 { return s.EnemyDst }, Min: 0, Max: 200, Curve: ai.LinearCurve(-1, 0, 1), }, { Name: "healthy", Input: func(s UnitState) float64 { return s.HP }, Min: 0, Max: 100, Curve: ai.LogisticCurve(1, 10, 0.35, 0), }, }, }, ai.UtilityAction[UnitState]{ Name: "heal", Weight: 1.1, Considerations: []ai.Consideration[UnitState]{ { Name: "low_hp", Input: func(s UnitState) float64 { return s.HP }, Min: 0, Max: 100, Curve: ai.PolynomialCurve(-1, 2, 0, 1), }, { Name: "has_potion", Input: func(s UnitState) float64 { return s.Potions }, Curve: ai.StepCurve(1, 0, 1), }, }, }, ) reasoner.Momentum = 0.1 // bonus for the currently active action idx, score := reasoner.Choose(state, nil) _, _ = reasoner.ActionName(idx), score ``` ### Considerations and response curves Each `Consideration[C]` reads a number from `C`, optionally normalizes `[Min, Max]` into `[0, 1]` (or clamps directly to `[0, 1]` when `Max <= Min`), and maps it through a `ResponseCurve` whose output is clamped to `[0, 1]`: | Kind / Constructor | Formula | | --- | --- | | `CurveLinear` / `LinearCurve(slope, shiftX, shiftY)` | `slope*(x - shiftX) + shiftY` | | `CurvePolynomial` / `PolynomialCurve(slope, exponent, shiftX, shiftY)` | `slope*(x - shiftX)^exponent + shiftY` | | `CurveLogistic` / `LogisticCurve(slope, steepness, midpoint, shiftY)` | `slope / (1 + exp(-steepness*(x - midpoint))) + shiftY` | | `CurveLogit` / `LogitCurve(slope, midpoint, shiftY)` | `slope*ln(u/(1 - u)) + shiftY`, `u = x - midpoint + 0.5` | | `CurveStep` / `StepCurve(threshold, low, high)` | `low` for `x < threshold`, `high` for `x >= threshold` | | `CurveResource` / `ResourceCurve(eval)` | Delegates to a `CurveEvaluator` (`Eval(float32) float32`), satisfied directly by `*resource.Curve` | | `CustomCurve(fn)` | Wraps a `func(float64) float64` as a `CurveEvaluator` | ### Scoring, momentum, and selection - **Compensation factor**: an action's `N` considerations are multiplied together (any `0` vetoes the action immediately) and compensated with `modFactor = 1 - 1/N`, `score = score + (1 - score)*modFactor*score`, then multiplied by `Weight` (defaulting to `1` when `0`; negative disables the action). - **Momentum bonus**: while an action is currently active and its base score is positive, `Reasoner.Momentum + UtilityAction.Momentum` is added so the agent does not oscillate between two nearly equal options every step. A vetoed action (`0`) never receives momentum. - **Top-N weighted choice**: set `Reasoner.TopN > 1` and pass a deterministic `*random.Stream` to pick among the top `N` positive-scoring actions weighted by score. Leaving `TopN <= 1` or passing a `nil` stream picks the highest-scoring action deterministically. Ties always break in fixed action declaration order. - **Zero-allocation multi-agent sharing**: call `reasoner.ChooseWithCurrent(ctx, agent.ActiveAction, rng)` to score many agents with one shared `Reasoner` and zero heap allocations after warm-up. ### Behavior tree integration Use `UtilitySelector(reasoner, ctx, rng, subtrees)` to embed utility scoring as a behavior tree `Node`. Each `UtilitySelector` tracks its own active action for momentum and calls `Reset()` on an interrupted running subtree when another action overtakes it: ```go node := ai.UtilitySelector(reasoner, func() UnitState { return unit.State() }, rng, map[string]ai.Node{ "attack": attackSubtree, "heal": healSubtree, }) ``` ### YAML configuration Define actions, considerations, and curves in a versioned YAML file (`version: 1`) parsed with `ParseUtility` and encoded deterministically with `EncodeUtility`. Bind Go input functions and an optional `resource` curve loader (`LoadCurve`) via `BuildReasoner`: ```go cfg, err := ai.ParseUtility(yamlBytes) if err != nil { return err } reasoner, err := ai.BuildReasoner(cfg, ai.UtilityBindings[UnitState]{ Inputs: map[string]func(UnitState) float64{ "target_distance": func(s UnitState) float64 { return s.EnemyDst }, "health_ratio": func(s UnitState) float64 { return s.HP / 100 }, }, LoadCurve: func(path string) (ai.CurveEvaluator, error) { return resource.LoadAs[*resource.Curve](resLib, path) }, }) ``` Unknown fields, unsupported versions, and trailing YAML documents are refused; canonical documents round-trip byte-for-byte unchanged (see [File Formats](http://nsgo.games/docs/formats/#utility-ai)). ## Goal-oriented action planning (GOAP) When agents need to assemble multi-step action chains dynamically toward goals (fetch an axe, chop wood, build a fire) without hand-wiring every transition, define a `FactSchema`, `GOAPAction`s, and prioritized `GOAPGoal`s for a `GOAPPlanner`: ```go schema := ai.NewFactSchema() hasAxe := schema.MustBool("has_axe") hasFire := schema.MustBool("has_fire") wood := schema.MustInt("wood") planner, err := ai.NewGOAPPlanner( ai.GOAPAction{ Name: "fetch_axe", Cost: 1, Effects: ai.Effects{}.SetBool(hasAxe, true), Check: func(ai.WorldState) bool { return camp.AxeAvailable() }, }, ai.GOAPAction{ Name: "chop_wood", Cost: 1, Preconditions: ai.Conditions{}.RequireBool(hasAxe, true), Effects: ai.Effects{}.AddInt(wood, 1), }, ai.GOAPAction{ Name: "gather_sticks", Cost: 3, Effects: ai.Effects{}.AddInt(wood, 1), }, ai.GOAPAction{ Name: "build_fire", Cost: 1, Preconditions: ai.Conditions{}.RequireIntGte(wood, 2), Effects: ai.Effects{}.SetBool(hasFire, true).AddInt(wood, -2), }, ) if err != nil { return err } goal := ai.GOAPGoal{ Name: "light_campfire", Priority: 10, Target: ai.Conditions{}.RequireBool(hasFire, true), } plan, cost, err := planner.PlanNames(ai.WorldState{}, goal) // plan == ["fetch_axe", "chop_wood", "chop_wood", "build_fire"], cost == 4 _, _, _ = plan, cost, err ``` ### World state, conditions, and effects - **`WorldState`** is a compact comparable value type packing up to `MaxBoolFacts` (128) named boolean facts into a `[2]uint64` bitset and up to `MaxIntFacts` (16) small `int16` integer facts. Register names with `FactSchema.Bool` / `FactSchema.Int` (or `MustBool` / `MustInt`). - **`Conditions`** express required boolean values (`RequireBool`) and integer bounds (`RequireIntEq`, `RequireIntGte`, `RequireIntLte`, `RequireIntGt`, `RequireIntLt`, `RequireIntRange`) for action preconditions and goal targets. - **`Effects`** express boolean assignments (`SetBool`) and integer updates (`SetInt`, `AddInt`). - **`GOAPAction.Check`** is an optional procedural precondition (`func(WorldState) bool`) evaluated against the current world state so actions can verify runtime conditions (such as reachability or entity availability) outside the symbolic bitset. ### Regressive A* search and node budget - `GOAPPlanner` runs deterministic regressive A* from `goal.Target` back to the current `WorldState`, using an admissible heuristic over usable actions to guarantee the cheapest plan. - Ties break in a fixed order (lowest `f`, lowest `h`, fewest actions, lowest discovery index in action declaration order), producing identical plans across runs. - `GOAPPlanner.NodeBudget` (default `DefaultGOAPNodeBudget`, 1024) caps how many search nodes are expanded per plan; exceeding it fails cleanly with `ErrBudgetExceeded` instead of searching unboundedly. Unreachable goals return `ErrNoPlan`. - Internal node, heap, and open-addressing hash-table buffers are reused across calls: use `PlanInto(dst, start, goal)` or `PlanBestGoalInto(dst, start, goals)` for zero heap allocations after warm-up. ### Plan runner and behavior tree integration `NewPlanRunner(planner, worldFn, goals, executors)` executes planned actions in order by ticking each action's bound `Node` (`executors[action.Name]`): - When an action returns `StatusFailure`, `PlanRunner` resets it, temporarily excludes the failed action, and replans to reach the goal by another route (returning `StatusFailure` if no route exists). - When `worldFn()` invalidates a remaining precondition or procedural check, or when a higher-priority goal becomes unsatisfied and achievable, `PlanRunner` resets the running action and replans automatically. - `*PlanRunner` implements `ai.Node` directly, so it can run standalone on `game.Loop` or sit inside any behavior tree: ```go runner := ai.NewPlanRunner(planner, camp.WorldState, goals, map[string]ai.Node{ "fetch_axe": fetchAxeNode, "chop_wood": chopWoodNode, "gather_sticks": gatherSticksNode, "build_fire": buildFireNode, }) tree := ai.Selector( ai.Guard(camp.InDanger, fleeNode), runner, ) ``` ### GOAP YAML configuration Author facts, actions, node budgets, and prioritized goals in a versioned YAML file (`version: 1`) decoded with `ParseGOAP`, encoded deterministically with `EncodeGOAP`, and compiled with `BuildGOAP`: ```go cfg, err := ai.ParseGOAP(yamlBytes) if err != nil { return err } set, err := ai.BuildGOAP(cfg, ai.GOAPBindings{ Checks: map[string]func(ai.WorldState) bool{ "axe_available": func(ai.WorldState) bool { return camp.AxeAvailable() }, }, }) ``` Unknown fields, unsupported versions, undefined fact references, invalid operators, and trailing YAML documents are refused; canonical documents round-trip byte-for-byte unchanged (see [File Formats](http://nsgo.games/docs/formats/#goap-action-set)). ## Attack tokens, engagement slots, and squads Coordinate groups of enemies in action games, brawlers, and shooters so only a bounded number attack at once, surrounding enemies spread around moving targets without crossing paths, and squads share state, tactical roles, and orders. ### Attack token pools `TokenPool` arbitrates a fixed number of attack tokens for one target, and `TokenManager` manages one `TokenPool` per target ID. Agents submit or refresh requests with `Request(agentID, priority)` during a step, and `Step(dt)` advances cooldowns and hold timeouts while resolving pending requests deterministically (highest priority first, breaking ties by lowest `AgentID` regardless of submission order): ```go tokens := ai.NewTokenPool(ai.TokenPoolConfig{ Capacity: 2, // at most 2 attackers at once Cooldown: 400 * time.Millisecond, // pause before a returned token is reused PreemptMargin: 1.5, // advantage needed to take a token from another attacker MaxHoldDuration: 3 * time.Second, // auto-release if an attacker stalls }) // Each enemy's behavior tree requests a token and falls back to circling while waiting: enemyTree := ai.Selector( ai.WithAttackToken(tokens, enemyID, enemyPriority, attackSequence), circleTargetNode, ) // On fixed step: tick behavior trees, then resolve token grants/preemptions: enemyTree.Tick(dt) tokens.Step(dt) // When an enemy dies or disengages: tokens.Remove(enemyID) ``` - **Priority preemption**: when no free tokens are available, a waiting requester whose priority beats the weakest holder by at least `PreemptMargin` (or strictly exceeds it when `PreemptMargin <= 0`) takes that holder's token directly without entering cooldown. `WithAttackToken` resets an interrupted child and returns `StatusFailure` on the next tick so a parent `Selector` falls back cleanly. - **Per-target pools**: use `NewTokenManager(defaultCfg)` when enemies engage multiple targets; call `ConfigureTarget(targetID, cfg)` for custom limits, `RemoveAgent(agentID)` when an enemy dies across all targets, and `Step(dt)` to step every target deterministically in ascending target ID order. ### Engagement slots `SlotAssigner` places agents onto concentric `EngagementRing`s around a target using optimal minimum-cost bipartite matching (the Hungarian algorithm): ```go assigner := ai.NewSlotAssigner( ai.EngagementRing{Radius: 45, Slots: 4}, // inner melee ring fills first ai.EngagementRing{Radius: 90, Slots: 6}, // outer circling ring ) assigner.StayBias = 10 // world-unit hysteresis suppressing boundary oscillation var slots []ai.SlotAssignment // Inside game.Loop.Update as targetPos moves: slots = assigner.Assign(slots, targetPos, []ai.SlotAgent{ {ID: 1, Pos: enemy1.Pos}, {ID: 2, Pos: enemy2.Pos}, }) ``` - **Non-crossing & ring priority**: inner rings fill completely before outer rings are used, and minimizing total Euclidean distance prevents straight-line agent-to-slot paths from crossing. When there are more agents than slots, the optimal subset is assigned and extra agents receive `Assigned: false` (`Ring: -1`, `Slot: -1`). - **Stability & determinism**: setting `StayBias > 0` gives each agent a cost bonus for keeping its previous slot as the target moves. Input agents are sorted by ascending `ID` internally, so assignments are identical across runs regardless of slice order and reuse internal scratch buffers with zero allocations after warm-up. ### Squads `Squad` groups enemy IDs in deterministic ascending order with a shared key-value `SquadState`, score-driven tactical roles (`AssignRoles`), and squad-level `SquadOrder`s readable by behavior trees: ```go squad := ai.NewSquad(1, 10, 20, 30) squad.State().SetBool("player_spotted", true) squad.State().SetPoint("last_known_pos", playerPos) squad.AssignRoles( ai.SquadRoleSpec{Name: "flanker", Count: 1, Score: flankScore}, ai.SquadRoleSpec{Name: "suppressor", Count: 2, Score: suppressScore}, ) squad.SetOrder(ai.SquadOrder{Kind: "pinch", TargetID: playerID, Position: playerPos}) // Inside a squad member's behavior tree: flankBranch := ai.Sequence( ai.SquadStateBool(squad, "player_spotted"), ai.SquadHasOrder(squad, "pinch"), ai.SquadHasRole(squad, memberID, "flanker"), ai.SquadOrderAction(squad, moveToFlank), ) ``` - **`AssignRoles`** solves maximum-weight bipartite matching over `SquadRoleSpec`s, maximizing the number of filled eligible roles first and total score second. Return `NaN` or `±Inf` from `Score` to mark a member ineligible for a role. - **`SquadOrder.Revision`** increments on every `SetOrder` and `ClearOrder` call so behavior trees can detect newly issued directives even when `Kind` is unchanged. - **`SquadState`** provides typed helpers (`Bool`, `Int`, `Float`, `String`, `Point`, `ID`), generic `SquadStateGet[T]`, and deterministic sorted `Keys`. ## Influence maps `InfluenceLayer` stores a 2D scalar influence grid matching a `pathfind.Grid` (and using the same `Origin` / `CellSize` world mapping as `rts.FlowField`) so strategy and tactics AI can reason about threat, control, tension, and safe positioning: ```go friendly := ai.NewInfluenceLayerForGrid(grid, math2d.Zero(), 16) enemy := ai.NewInfluenceLayerForGrid(grid, math2d.Zero(), 16) control := ai.NewInfluenceLayerForGrid(grid, math2d.Zero(), 16) tension := ai.NewInfluenceLayerForGrid(grid, math2d.Zero(), 16) squadID := friendly.AddSource(ai.InfluenceSource{ Cell: pathfind.Cell{Col: 2, Row: 3}, Strength: 10, Radius: 5, Falloff: ai.FalloffLinear, }) enemy.AddSource(ai.InfluenceSource{ Cell: pathfind.Cell{Col: 12, Row: 3}, Strength: 12, Radius: 6, Falloff: ai.FalloffExponential, FalloffRate: 0.45, }) // Incremental update (0 allocs/step after warm-up; matches Rebuild bit-for-bit): friendly.MoveSource(squadID, pathfind.Cell{Col: 3, Row: 3}) friendly.Update(grid) enemy.Spread(grid, ai.SpreadOptions{Decay: 0.2, Momentum: 0.5, Iterations: 2, Diagonal: true}) // Combine into tactical layers: control.Subtract(friendly, enemy) // positive = friendly control, negative = enemy control tension.Add(friendly, enemy) // total presence from both sides control.Normalize() // signed [-1, 1] preserving 0 as neutral // Find the least threatened reachable cell within 4 cells of a unit: safeCell, threatVal, ok := enemy.LowestInRadius(pathfind.Cell{Col: 5, Row: 3}, 4, ai.InfluenceQuery{ Grid: grid, Reachable: true, }) // Sample bilinearly or follow the downhill/uphill gradient in world coordinates: val, inBounds := enemy.Sample(unitPos) grad := enemy.Gradient(unitPos) _, _, _, _, _ = safeCell, threatVal, ok, val, inBounds _ = grad ``` ### Sources, falloffs, and obstacle-aware spreading - **Falloffs**: each `InfluenceSource` stamps cells within Euclidean cell `Radius` using `FalloffLinear` (`max(0, 1 - dist/Radius)`), `FalloffExponential` (`exp(-FalloffRate * dist)`), or `FalloffCustom` (`CustomFalloff(dist, radius)`). Blocked cells (`!grid.Walkable(col, row)`) always stay `0`. - **Incremental updates**: register moving units with `AddSource` and update them via `MoveSource`, `SetSource`, `RemoveSource`, `MarkDirtyCell`, or `MarkDirtyRect`. `Update(grid)` recomputes only dirty footprints in fixed source-slot order so results are deterministic, match `Rebuild(grid)` bit-for-bit, and perform zero heap allocations per step after warm-up. For one-off static stamps, call `Stamp(grid, src)`. - **Propagation with decay and momentum**: `Spread(grid, opts)` propagates influence around blocked cells (4-way or 8-way with no corner-cutting around walls, using `(1 - Decay)` on cardinal steps and `(1 - Decay)^sqrt(2)` on diagonals) and blends against previous values with `Momentum` (`next = prev*Momentum + target*(1 - Momentum)`). When tracked sources are present, `Spread` syncs dirty source changes incrementally before propagating so moving or removed sources decay smoothly. ### Layer combinations and spatial queries - **Combining layers**: `Add`, `Subtract`, `Multiply`, `Combine(terms...)`, `AddScaled`, `Scale`, `Abs`, `Clamp`, `Normalize`, and `CopyFrom` operate in place without allocating on pre-sized destination layers and support self-aliasing. - **Queries**: `HighestInRadius` and `LowestInRadius` find extrema within a cell radius, optionally filtering by walkability and BFS reachability (`InfluenceQuery{Grid: grid, Reachable: true, Diagonal: ...}`) with deterministic tie-breaking (closer cell, then smaller row, then smaller column). `Highest(grid)` and `Lowest(grid)` scan the full layer; `Sample(worldPos)` returns bilinearly interpolated values; `Gradient(worldPos)` and `GradientAtCell(col, row)` return uphill `math2d.Vec2` gradients in influence per world unit. ### Debug heatmap Draw any layer over a `tilemap.Camera` for debugging: ```go d.Save() cam.Apply(d) control.DrawHeatmap(d, cam, ai.HeatmapOptions{DrawGrid: true}) d.Restore() ``` `DrawHeatmap` culls cells outside `cam.VisibleBounds()`, tints positive values with `PositiveColor` (default green) and negative values with `NegativeColor` (default red), and scales opacity by `|value| / MaxAbs`. Under `-tags release`, `DrawHeatmap` compiles to a no-op stub and `InfluenceHeatmapEnabled()` returns `false`. ## Tactical position queries and cover points Cover shooters, stealth games, and tactics games use `CoverPoint`, `TacticalQuery`, `PointReservations`, and `QueryBudget` to answer "where should I stand" (behind cover from a threat, at a flanking angle with clear line of fire, or in a low-threat reachable cell) with deterministic ordering and zero heap allocations after warm-up: ```go // Generate cover points from a tilemap's solid edges (or physics 2D/3D colliders, or scene YAML): covers := ai.GenerateCoverFromTilemap(levelMap, ai.TileCoverOptions{ DefaultHeight: ai.CoverFull, }) reservations := ai.NewPointReservations(ai.ReservationConfig{ DefaultTimeout: 3 * time.Second, }) budget := ai.NewQueryBudget(16, 8) // at most 16 LOS raycasts and 8 path queries per step query := ai.NewTacticalQuery( []ai.CandidateGenerator{ &ai.CoverPointGenerator{Points: covers, MaxRadius: 240}, }, &ai.AngleTest{ Mode: ai.AngleCoverToTarget, Filter: ai.AtMost(math.Pi / 3), // cover faces within 60 degrees of the threat Weight: 2.0, Invert: true, }, &ai.CoverHeightTest{Prefer: ai.CoverFull, Weight: 1.0}, &ai.InfluenceTest{Layer: threatLayer, Weight: 1.5, Invert: true}, &ai.LOSTest{LOS: hasLineOfSight, WantClear: false, Weight: 2.0}, // hidden from threat &ai.PathDistanceTest{Grid: navGrid, CellSize: 16, Weight: 2.0, Invert: true}, ) // Inside game.Loop.Update: budget.Reset() reservations.Step(dt) spot, ok := query.RunAndReserve(ai.TacticalContext{ QuerierID: agentID, QuerierPos: agentPos, TargetPos: threatPos, Reservations: reservations, Budget: budget, }, 0) _, _ = spot, ok // When an agent dies or leaves cover: reservations.Release(agentID) ``` ### Cover points and generators Each `CoverPoint` records a world standing position (`Pos`), a unit `Facing` vector pointing from `Pos` into the cover obstacle (the incoming threat direction the cover blocks; the obstacle's outward normal is `Facing.Neg()`), a `CoverHeight` (`CoverHalf` or `CoverFull`), optional 3D `Elevation`, `ID`, and `Tags`. - **Tilemap and grid generation**: `GenerateCoverFromTilemap(m, opts)` merges contiguous exposed solid tile edges (reading optional `HalfCoverMask`, `HeightFunc`, or a tile's `"cover": "half"|"full"` property) and verifies generated positions lie in open tiles. `GenerateCoverFromGrid(g, origin, cellW, cellH, opts)` generates cover directly from any `pathfind.Grid`. - **2D and 3D collider generation**: `GenerateCoverFromBoxes`, `GenerateCoverFromWorld` (supporting `physics.Box`, `physics.Circle` pillars, and `World.Tiles`), and `GenerateCoverFromSegments` generate 2D cover points while pruning candidates embedded inside neighboring colliders. For 3D scenes, `cover3d.FromWorld(w, opts)` in `github.com/nsgo-dev/game/pkg/ai/cover3d` (or `cover3d.FromBodies(bodies, opts)` for a body list) projects vertical side faces of axis-aligned boxes, oriented boxes, spheres, capsules, and cylinders standing on an end onto the XZ plane (convex hulls and cylinders lying on their side generate no cover), classifying `CoverHalf` vs `CoverFull` from collider height and preserving floor `Elevation`. - **Scene YAML authoring**: register the built-in `"cover_point"` component on a `sceneformat.ComponentRegistry` via `sceneformat.RegisterCoverPoint(reg)` (`height`, `facingX`, `facingY`, `tags`), then extract world-transformed `[]ai.CoverPoint` values with `sceneformat.ExtractCoverPoints(doc)` or `sceneformat.ExtractBuiltCoverPoints(built)`. ### Candidate generators and ordered tests `TacticalQuery` runs one or more `CandidateGenerator`s, excludes points reserved by other agents, evaluates `TacticalTest`s in declaration order, and returns surviving `TacticalCandidate`s sorted deterministically by descending `Score` (breaking ties by `CoverID`, `Pos.Y`, `Pos.X`, `Facing`, and generation index): - **Generators**: `CoverPointGenerator` (with optional `MaxRadius`, `MinHeight`, `RequiredTag`), `RingGenerator` (concentric rings or arcs around a target or querier with optional `FaceCenter`), `GridGenerator` (world-space grid or walkable `pathfind.Grid` cells), and `NavMeshGenerator` (polygon centroids or spaced samples contained in an `*pathfind.NavMesh`). - **Tests**: each test sets `Purpose` (`TestFilterAndScore`, `TestFilterOnly`, or `TestScoreOnly`), optional `Filter` (`AtLeast`, `AtMost`, `Between`), `Weight`, `Invert`, and optional fixed `NormMin`/`NormMax` (defaulting to dynamic normalization across surviving candidates): - `DistanceTest`: Euclidean distance to `OriginQuerier`, `OriginTarget`, or `OriginCustom`. - `AngleTest`: angle in radians (`AngleCoverToTarget`, `AngleFlank`, `AngleToDirection`, `AngleFromTargetToDir`). - `InfluenceTest`: bilinearly sampled value from an `*ai.InfluenceLayer`. - `CoverHeightTest`: filters by `MinHeight` and scores preferred `CoverHalf`/`CoverFull`. - `LOSTest`: line of sight to or from a target via a game-supplied `LOSFunc` (`WantClear: true` for firing lines, `false` for hidden cover). - `PathDistanceTest`: travel distance via a `PathCost` callback, zero-allocation grid `AStar`, or zero-allocation 2D `NavMesh` funnel path length. - `CustomTest`: caller-supplied `Eval(ctx, candidate)` callback. ### Reservations and per-step budgets - **`PointReservations`**: guarantees two agents never reserve the same `CoverID` or non-cover positions closer than `MinSeparation`. `RunAndReserve` selects and reserves the best unreserved candidate while atomically replacing that agent's prior reservation; `Release(agentID)` frees a spot on death, `ReleaseCover(coverID)` frees destroyed cover, `Refresh` extends a timeout, and `Step(dt)` expires timed reservations deterministically. - **`QueryBudget`**: caps `MaxRaycasts` (for `LOSTest`) and `MaxPathQueries` (for `PathDistanceTest`) per simulation step across all agents sharing the budget. Before running a budgeted test, surviving candidates are ordered deterministically by preliminary score so the highest-ranked spots consume the step budget first. Call `Reset()` once per step, and use `Best`, `RunInto(dst, ctx)`, or `RunAndReserve` for zero heap allocations after warm-up. ## Perception A `Perception` gives one agent sight, hearing and a memory of what it sensed, so a guard can see the player right now, go to where it last heard a noise, and give up after a while. A `PerceptionSystem` steps the perceptions of many agents together on `game.Loop`'s fixed steps: ```go walls := []lights2d.Occluder{lights2d.RectOccluder(wallBounds)} guard := &ai.Perception{ Self: guardID, // never senses itself Team: teamGuards, Facing: core.Point{X: 1}, Sight: ai.SightConfig{ Range: 160, HalfAngle: math.Pi / 4, // a 90° cone PeripheralRange: 24, // all around, unless PeripheralHalfAngle narrows it }, Hearing: ai.HearingConfig{Range: 120}, ForgetAfter: 5 * time.Second, } senses := ai.PerceptionSystem{ LineOfSight: lights2d.LineOfSight(&walls), Budget: 32, // line-of-sight checks per step, shared by every agent } senses.Add(guard) // Inside game.Loop.Update: guard.Pos = guardAgent.Pos if guardAgent.Vel != (core.Point{}) { guard.Facing = guardAgent.Vel } if player.Running { senses.PostNoise(ai.Noise{Source: playerID, Team: teamPlayer, Pos: player.Pos, Loudness: 1}) } senses.Step(dt, []ai.Target{{ID: playerID, Team: teamPlayer, Pos: player.Pos, Vel: player.Vel}}) for _, ev := range guard.Events() { switch ev.Kind { case ai.EventGained, ai.EventUpdated: chase(ev.Memory.Pos) case ai.EventLost: search(ev.Memory.Pos, ev.Memory.Vel) case ai.EventForgotten: resumePatrol() } } ``` ### Sight A target is in view when it lies within `Range` of the eye and within `HalfAngle` (radians) of `Facing`, or within the shorter `PeripheralRange` and within `PeripheralHalfAngle`, which is zero for all around; a negative `PeripheralHalfAngle` disables the peripheral range. The eye is `Pos + EyeOffset`, in world space; hearing measures from the same point. A target in view is seen when the system's `LineOfSight` reports the segment from the eye to the target clear; a nil `LineOfSight` lets every target in view be seen. Three adapters cover the usual occluders: | Adapter | Occluders | | --- | --- | | `ai.PhysicsLineOfSight(world, query, layers)` | Bodies and tiles of a `physics.World`, through `RaycastFirstLayer`. | | `lights2d.LineOfSight(&occluders)` | The `lights2d` occluders that cast shadows, through `lights2d.Visible`; it reads the slice on every call, so the level can change it. | | `perception3d.PhysicsLineOfSight(world, layers)` | Bodies and static colliders of a `physics3d.World`, for 3D agents. | A ray that starts inside the agent's body or ends inside the target's hits that body, so keep agents and targets off the layers that block sight, for example by putting walls on a layer of their own. ### Hearing `PostNoise` queues a `Noise` with a position, a `Loudness` and its source's ID and team, and the next `Step` hears it: an agent hears a noise within `Hearing.Range × Loudness` of its eye, with no line of sight needed. Noises are heard in the order they were posted, and a step consumes them. ### Memory and events Each agent keeps one `Memory` per `StimulusID`, so a target seen and later heard refreshes one memory. A memory holds the last known `Pos` and `Vel` (zero when heard), the `Sense` that last refreshed it, its `Age` since it was last sensed, whether it is `Visible` now, and a `Strength` that is 1 when seen, is raised to at least `1 - distance/reach` when heard (1 for an infinite reach), and falls linearly to 0 over `ForgetAfter`. A memory is forgotten once `Age` reaches `ForgetAfter`. Read memories with `Memories`, `AppendMemories`, `Memory(id)` and `Sees(id)`, and drop them with `Forget(id)` and `Clear`. `Remove` takes an agent out of the system but keeps its memories, with none of them visible and no events, so `Sees` reports false until the agent is added and stepped again. A copy of a `Perception` that was added, such as a configured prototype, is a separate agent: `Add` gives it its own copy of the memories. After each `Step`, `Events` lists what changed: | Kind | When | | --- | --- | | `EventGained` | A stimulus is sensed with no memory of it before. | | `EventUpdated` | A remembered stimulus is seen again after being out of sight, is seen moving, or is heard. A still target in sight makes no events. | | `EventLost` | A stimulus in sight leaves it; the memory stays. | | `EventForgotten` | A memory reaches `ForgetAfter` and is dropped. | ### Teams `Team` is a small team number. The system's `Attitude` function, `DefaultAttitude` when nil, decides whether an agent regards a stimulus as `Hostile`, `Neutral` or `Friendly`: the same team is friendly, `NoTeam` on either side is neutral, and other teams are hostile. `SightConfig.Detect` and `HearingConfig.Detect` choose the attitudes each sense notices, with `DetectHostile`, `DetectNeutral`, `DetectFriendly` and `DetectAll`; zero detects hostile stimuli only. ### Budget and determinism With hundreds of agents, casting a ray for every agent and target on every step is too much. `Budget` caps the line-of-sight checks of a step: the pairs in view are ordered by the order agents were added and then by target ID, a step checks `Budget` of them starting after the last pair checked, and the next step carries on from there, so every agent gets its turn in a fixed order. A pair not yet rechecked keeps its previous result. `Stats` reports a step's candidates, checks and deferred pairs. A nil `LineOfSight` casts no rays, so the budget does not apply and every pair in view is seen at once. With a deterministic `LineOfSight`, every run with the same inputs produces the same memories and events. ### 3D The experimental package `game/ai/perception3d` runs the same engine on `math3d.Vec3`, so its senses, memory, events, teams and budget behave exactly as above. Its `Perception` points the cone along `Forward` (zero faces -Z), with angles measured in 3D, and `EyeOffset` is typically head height on +Y; `System`, `Target`, `Noise`, `Memory`, `Event` and `LineOfSight` mirror the 2D types, and it reuses `ai.SightConfig`, `ai.HearingConfig`, `ai.StimulusID`, `ai.Team` and the event kinds: ```go import "github.com/nsgo-dev/game/pkg/ai/perception3d" guard := &perception3d.Perception{ Team: teamGuards, Forward: math3d.Vec3{Z: -1}, EyeOffset: math3d.Vec3{Y: 1.7}, Sight: ai.SightConfig{Range: 40, HalfAngle: math.Pi / 4}, ForgetAfter: 5 * time.Second, } senses := perception3d.System{LineOfSight: perception3d.PhysicsLineOfSight(world, layerWalls), Budget: 64} senses.Add(guard) // Inside game.Loop.Update: senses.Step(dt, []perception3d.Target{{ID: playerID, Team: teamPlayer, Pos: playerPos}}) ``` ## Smart objects `SmartObjects` is a registry of world objects that advertise interaction slots, such as the seats on a bench or the places at a workstation. Each `SmartSlot` has an ID, a position, tags, and a `Behavior` name that the game or a behavior-tree action interprets. `FindInRadius` returns the free slots on enabled objects within a radius that carry every tag of the query, ordered by object ID and then slot ID. `Claim` gives a slot to one agent and refuses a second claim, `Use` tells the holder whether its claim still stands, and `Release` frees it. `Disable` releases every claim on an object and runs the `SetOnReleased` callback once per claim; `Enable` brings the object back with free slots. `Snapshot` and `Restore` copy the whole registry, occupancy included, for saves and rollback. ```go objects := ai.NewSmartObjects() objects.SetOnReleased(func(c ai.SmartClaim) { bb(c.Agent).Delete("slot") }) objects.Register(ai.SmartObject{ID: "bench", X: 40, Y: 12, Slots: []ai.SmartSlot{ {ID: "left", X: -6, Tags: []string{"sit"}, Behavior: "sit"}, {ID: "right", X: 6, Tags: []string{"sit"}, Behavior: "sit"}, }}) // When a villager wants to rest: if free := objects.FindInRadius(pos.X, pos.Y, 64, ai.SmartQuery{Tags: []string{"sit"}}); len(free) > 0 { if claim, ok := objects.Claim("villager-3", free[0].ObjectID, free[0].SlotID); ok { current = claim } } // Each step while sitting: if !objects.Use(current) { // The bench was disabled or the claim was restored away: pick another activity. } ``` Slot positions are offsets the game applies to the object; the registry does not move agents. Scene components, editor slot placement and behavior-tree actions on top of the registry are not part of `ai`. --- Source: http://nsgo.games/docs/anim3d/ # anim3d `game/anim3d` provides 3D skeletal animation driven on `game.Loop`'s fixed steps: glTF 2.0 node and skin playback (`Player`, `ClipFromGLTF`), pose state machines with cross-fade transitions, 1D/2D blend spaces with foot-phase synchronization, bone-masked override and additive layers, timed clip events, two-bone and FABRIK inverse kinematics, and root motion extraction. ```go import "github.com/nsgo-dev/game/pkg/anim3d" ``` All joint transforms follow [math3d](http://nsgo.games/docs/math3d/) conventions (right-handed Y-up). ## Playing glTF animations Create a `Player` from any loaded `*gltf.Document` to advance translation, rotation, scale, and morph-target weight channels on `game.Loop.Update` fixed steps without mutating the shared document. Multiple players can animate the same `*gltf.Document` independently at different clips or timestamps: ```go player, err := anim3d.NewPlayer(doc) if err != nil { return err } if err := player.PlayByName("Walk"); err != nil { return err } // In game.Loop.Update: player.Step(dt) player.ApplyToScene(scene) // optional: sync named nodes in scene3d.Scene joints, err := player.SkinMatrices(0) // joint matrices for skinned rendering _ = joints ``` `Player` evaluates `STEP`, `LINEAR` (with shortest-path quaternion Slerp), and `CUBICSPLINE` (Hermite spline with normalized rotations) interpolation modes directly from the glTF channels, preserving matrix-authored non-animated nodes (such as COLLADA `Z_UP` roots). It provides `Play`, `PlayByName`, `Crossfade`, `CrossfadeByName`, `Pause`, `Stop`, `Seek`, `SetLoop`, `SetSpeed` (including negative values for reverse playback; with `Loop` false, `Play` and `Crossfade` start a reversed clip at its `Duration` and play back to `0`, and flipping `Speed`'s sign while playing at a clamped end jumps to the opposite end), `Time`, `Duration`, `Playing`, `LocalTransforms`, `WorldTransforms`, `MorphWeights`, `SkinMatrices`, `SkinMatricesForNode`, `ApplyToScene`, and `ApplyToNodes`. `Player` also implements `PoseSampler` via `Update` and `Pose`. `SkinMatrices(skinIndex)` computes glTF 2.0 joint matrices normalized by the skinned mesh node's inverse world transform (`inverse(worldMatrix[meshNode]) * worldMatrix[joint] * inverseBindMatrix[i]`), so bind-pose joints evaluate to identity matrices even under rotated root nodes. To feed glTF clips into `StateMachine`, `BlendSpace1D`, `BlendSpace2D`, `LayerStack`, or root motion extraction, convert them with `ClipFromGLTF` or `ClipsFromGLTF`. Unanimated TRS components on targeted nodes are seeded from each node's rest transform so bone offsets stay intact, untargeted nodes are omitted from `Tracks` so bone-masked layers leave them untouched, and any timed events in glTF `extras` (`events` or `nsgo_events`) are attached automatically — non-object `extras` and unrelated keys are ignored, while malformed event entries return a `*loaderr.Error` naming the animation index. ## Clips, state machines, and blend spaces Build a `StateMachine` whose states sample single `*Clip`s, `*BlendSpace1D` (for example idle -> walk -> run by speed), `*BlendSpace2D` (directional strafing), or any custom `PoseSampler`: ```go // Locomotion clips cycle, so mark them looping; a blend-space sample whose clip has Loop false plays once and holds its last frame. idleClip.Loop, walkClip.Loop, runClip.Loop = true, true, true loco := anim3d.NewBlendSpace1D( anim3d.BlendSample1D{Param: 0.0, Clip: idleClip}, anim3d.BlendSample1D{Param: 2.0, Clip: walkClip, FootPhaseOffset: 0.0}, anim3d.BlendSample1D{Param: 6.0, Clip: runClip, FootPhaseOffset: 0.0}, ) loco.ParamName = "speed" sm := anim3d.NewStateMachine("locomotion") sm.AddState(anim3d.State{Name: "locomotion", Blend1D: loco, ParamName: "speed"}) sm.AddState(anim3d.State{Name: "jump", Clip: jumpClip}) sm.AddTransition(anim3d.Transition{ From: "locomotion", To: "jump", BlendDuration: 120 * time.Millisecond, When: func() bool { return sm.Param("airborne") > 0.5 }, }) // In game.Loop.Update: sm.SetParam("speed", moveSpeed) pose := sm.Update(dt) _ = pose ``` `BlendSpace1D` and `BlendSpace2D` advance a shared normalized phase (`[0, 1)`) using weighted cycle speeds and per-sample `FootPhaseOffset` so blending between clips of different lengths avoids foot skating. A sample whose clip has `Loop: true` wraps with the shared phase; a clip with `Loop: false` plays once from the blend space's last `Reset` and holds its final frame, and fires each of its events once. Samples placed at the same parameter (or the same 2D point) split that position's weight equally, so none of them is shadowed. `StateMachine.Update(0)` is a paused step: it returns the current pose without advancing time or starting conditional transitions. A state with a negative `Speed` plays backward and fires the events it crosses in reverse order: entering a non-looping clip state (`Loop: false`) with negative `Speed` starts at `Duration` and plays back to `0` (looping clips start at `0` and wrap backward), and replacing the active non-looping clip state with an opposite-sign `Speed` while parked at a clamped end jumps to the opposite end. When the two states of a crossfade share one blend space or sampler, it advances once per step. ## Bone-masked layers and additive clips Combine a base locomotion sampler with upper-body actions or additive recoil/breathing using `LayerStack` and `BoneMask`: ```go upperMask := anim3d.NewBoneMask(jointCount, 0) upperMask.SetBranch(jointParents, spineJoint, 1.0) stack := anim3d.NewLayerStack(jointCount) stack.AddLayer(anim3d.AnimLayer{Name: "base", Mode: anim3d.LayerOverride, Weight: 1, Sampler: sm}) stack.AddLayer(anim3d.AnimLayer{Name: "aim", Mode: anim3d.LayerOverride, Weight: 0.9, Mask: upperMask, Clip: aimClip, Loop: true}) stack.AddLayer(anim3d.AnimLayer{Name: "recoil", Mode: anim3d.LayerAdditive, Weight: 0.6, Mask: upperMask, Clip: recoilClip, ReferencePose: &idleRef}) finalPose := stack.Update(dt) _ = finalPose ``` When a layer plays a `Clip`, only the joints the clip has a track for take part: an override layer leaves the other joints at the pose below it and an additive layer adds nothing to them. `BlendPosesMasked` likewise keeps base joints the overlay pose does not have, and `MakeAdditivePose` gives them the identity delta. For manual composition, use `BlendPoses`, `BlendPosesWeighted`, `BlendPosesMasked`, `MakeAdditivePose`, and `ApplyAdditivePose`. ## Clip events Attach timed `ClipEvent` markers (`Time`, `Name`, `Payload`, `Data`) to clips directly via `clip.AddEvent` or load them from glTF `extras` (`LoadEventsFromGLTFExtras`) or versioned JSON sidecar files (`LoadEventsSidecar` / `MarshalEventsSidecar`): ```go walkClip.AddEvent(anim3d.ClipEvent{Time: 0.25, Name: "footstep", Payload: "left"}) sm.SetEventWeightThreshold(0.5) // suppress events from low-weight cross-fading states sm.OnEvent(func(ev anim3d.FiredEvent) { if ev.Event.Name == "footstep" { playFootstepSFX(ev.Event.Payload) } }) ``` `LoadEventsSidecar` requires the versioned `{"version": 1, "clips": {...}}` envelope (`EventsSidecarVersion`) and refuses missing or unsupported versions, unknown or misspelled keys, duplicate keys, and trailing data with a located `*loaderr.Error`. `LoadEventsFromGLTFExtras` and `ClipFromGLTF` ignore absent, `null`, or non-object `extras` as well as unrelated `extras` keys, and return a `*loaderr.Error` naming `animations[i].extras...` when `events` or `nsgo_events` is present and malformed. During a crossfade each state fires its events at its crossfade weight at the midpoint of the part of the step inside the crossfade, so the step that completes the crossfade still fires the outgoing state's events. You can also pull fired events once per step with `sm.DrainEvents()` or drive standalone clips through `EventDispatcher`. ## Inverse kinematics and root motion - **Two-bone IK** (legs/arms): `newMid, newEnd, rootRot, midRot := anim3d.SolveTwoBoneIK(hip, knee, ankle, footTarget, kneePole)` solves an exact analytic hinge bend oriented toward `pole`. If one bone has zero length, the other bone alone is aimed at the target. - **FABRIK** (arbitrary chains such as spines, tails, or tentacles): `solved := anim3d.SolveFABRIK(jointPositions, target, 10, 0.001)`. - **Root motion**: extract per-step translation and yaw/rotation deltas from an authored clip, strip root movement from the sampled pose so the mesh does not double-move, and apply it to the character's world transform: ```go opts := anim3d.RootMotionOptions{RootJoint: 0, ExtractYawOnly: true, StripRootXZ: true, StripRootRot: true} rm := anim3d.ExtractRootMotion(attackClip, prevTime, currTime, opts) pose = anim3d.StripRootMotion(pose, opts) characterTransform = anim3d.ApplyRootMotion(characterTransform, rm) ``` A step that crosses the end of a looping clip, whether passed as wrapped times (`currTime < prevTime`) or monotonic ones, is split at each loop boundary and its rotations compose in playback order, so one long step turns the character exactly as the shorter steps on either side of the boundary would, including clips that pitch and yaw at once. `DeltaPos` is measured in the clip's root parent space and the pieces add. `anim3d.BoneMap` stores a versioned humanoid mapping beside a model. `GuessBoneMap` proposes mappings from common names, such as Mixamo's `mixamorig:LeftHand` or side-suffixed `hand_l` and `Hand.R`, never maps a role to a bone on the other side, prefers a bone named exactly as the role, and reports the roles it could not map for review. Maps round-trip through strict YAML. ### Spring bone contract `SpringBones` stores named chains and sphere colliders for deterministic secondary-motion integration after animation and IK. `Reset` clears accumulated state for teleports; the integration hook currently preserves the pose snapshot for future solvers. ### Modifier stacks `ModifierStack` applies deterministic post-animation pose modifiers in order, each at an influence from 0 to 1 (`SetInfluence`): 0 skips the modifier, 1 keeps the pose it produces, and a value in between blends each joint from the pose before it toward that result, translation and scale linearly and rotation by slerp. `Apply` returns a new pose and leaves its input unchanged. Look-at, IK, limits and foot-placement modifiers can plug into this contract. ### Animation graph resources `resource.AnimGraph` files describe 3D animation layers, state machines, one-shots, bone-name masks and one-dimensional blend samples in deterministic YAML. --- Source: http://nsgo.games/docs/animclip/ # animclip `game/animclip` plays animation clips, the [resource files](http://nsgo.games/docs/resources/#animation) of type `animation`, on scene objects: any registered property keyed on a timeline. The [editor](http://nsgo.games/docs/editor/#animation-editor) keys clips with the same package, so a clip plays the same in the game as in the editor's preview. ```go import "github.com/nsgo-dev/game/pkg/animclip" ``` ## Properties A track's `property` is written as in the scene file: - an object field: `x`, `y`, `rotation`, `scaleX`, `scaleY`, `alpha` (0 to 1), `originX`, `originY`, `flipX`, `flipY`, `sprite.frame` (`PropertySpriteFrame`, discrete atlas frame names stepping without interpolation), `posZ`, `rotX`, `rotY`, `rotZ` and `scaleZ` (`ObjectProperties` lists them with their documentation); - a registered component field, written `component.field` and split at the first dot, such as `body.speed`. The field must be registered in a `sceneformat.ComponentRegistry` (see [Component types](http://nsgo.games/docs/editor/#component-types)) as a `FieldFloat`, `FieldInt` or `FieldBool`; a string component field has no number to key. `Properties(reg)` returns every keyable property, the object fields first, and `Lookup(reg, name)` resolves one. A property's `Kind` says how a keyed value is written: a float as it is, an int rounded to the nearest whole number, a bool as true from 0.5 up, and `KindFrame` (`sprite.frame`) as a discrete atlas frame name (`Property.GetFrame`, `Property.SetFrame`, `Property.CheckFrame`). Numeric values are clamped to the field's range. `Check(clip, reg)` checks a whole clip: every property must resolve, `sprite.frame` tracks must hold non-empty `frames` keys, and numeric tracks must hold `keys` whose values their property can take (0 or 1 for a bool, a whole number for an int, and inside the field's range). A track's `target` is the ID of another object in the scene, and an empty target is the object the clip plays on. ## Flipbook clips Three helpers build a `sprite.frame` clip directly from a sprite atlas: - `FromAsepriteTag(atlas, tag)` converts an Aseprite frame tag from `atlas.Animations` into a clip matching the tag's frame sequence (direction and repeat count), exact millisecond durations and loop flag. - `FromSpriteAnimation(name, anim)` does the same for any `sprite.Animation`, turning any frame `Event` names into clip events at each frame's start time. - `FromFrames(name, frames, fps, loop)` builds a clip stepping through an ordered slice of atlas frame names at a fixed frame rate `fps`. ## Playing a clip ```go lib := resource.NewLibrary(os.DirFS(".")) clip, err := resource.LoadAs[*resource.Animation](lib, "anims/hop.animation.yaml") if err != nil { return err } player, err := animclip.NewPlayer(clip, components, animclip.BindScene(built, "hero")) if err != nil { return err // an unknown property, a bad key, or a target the scene does not have } player.OnEvent = func(name string) { if name == "land" { mixer.Play(landSound) } } player.Play() // Inside game.Loop.Update: player.Update(dt) ``` `NewPlayer` turns the clip into a `tween.Timeline`, one tween per pair of neighboring keys eased by the first key's `interp` (`linear`, `smooth` or `step`), so playback runs on the same deterministic clock as every other [timeline](http://nsgo.games/docs/tween/). A track holds its first key's value before it and its last key's value after it, as `Animation.Sample` does. The player writes nothing until the first `Seek` or `Update`. - `Play`, `Pause` and `Restart` start, stop and replay it; `Done` reports a clip that does not loop at its end. - `Seek(at)` writes every track's value at `at` without firing events. A looping clip wraps a time before `0` or past `Length` into `[0, Length)` and shows its end at exactly `Length`, so a playhead dragged to the end shows the last keys; one that does not loop clamps `at`. - `OnEvent` is called with the name of each clip event playback crosses, in time order. - `SetLoop` overrides the clip's `loop` for one player. - Key times and values are widened from the file's float32 by their shortest decimal (`KeyValue`, `Seconds`), so a key written `0.1` sits at exactly 100ms and plays the value 0.1. The player reads the clip once; to play a clip edited or reloaded by `Library.Reload`, make a new player. ## Binding A `Binder` connects each track to what it drives. It receives the track's target and resolved `Property` and returns the function that writes the value, which arrives already rounded and clamped for the property; an error fails `NewPlayer`, so a clip that names a missing object is refused before it plays. - `BindDoc(doc, self)` writes into the objects of a `sceneformat.SceneDoc`, refusing a `sprite.frame` track on an object without a sprite. - `BindScene(built, self)` writes into the objects of a `sceneformat.BuiltScene` and syncs each object it writes (`BuiltObject.Sync`), so the next `Draw` shows the object and its children at their new world transform, sprite frame and alpha, multiplied by the material's opacity as `Build` does. For a `sprite.frame` track, binding checks up front that the target object has a sprite and that its atlas holds every keyed frame name. A track's target may be a nested child object's ID. Component fields are written into the object's `components` mapping as `float64`, `int` or `bool`, creating the component's mapping when the object has none, so code that reads them with `ComponentRegistry.Resolve` sees the animated value. A custom `Binder` receives `Property.Frames` on `KindFrame` tracks and maps keyed indices to frame names with `p.Frame(v)`: ```go bind := func(target string, p animclip.Property) (func(float64), error) { e := world.Find(target) if e == nil { return nil, fmt.Errorf("no entity %q", target) } switch p.Name { case "x": return func(v float64) { e.Pos.X = float32(v) }, nil case animclip.PropertySpriteFrame: return func(v float64) { e.Frame = p.Frame(v) }, nil case "body.speed": return func(v float64) { e.Speed = v }, nil } return nil, fmt.Errorf("entity cannot play %s", p.Name) } ``` ## Sprite state machines A sprite state machine lives in a `*.states.yaml` file (version 1, schema [`states.v1.json`](http://nsgo.games/docs/schemas/#published-schemas)): named `states` pointing at `*.animation.yaml` clips, typed `parameters` (`float`, `bool`, `trigger`), an `entry` state, and ordered `transitions` guarded by `when` expressions and/or `onEnd: true`. Wildcard `from: '*'` transitions (such as a `hurt` interrupt) are checked from any state other than the target. Attach the built-in `animator` component (`sceneformat.AnimatorComponentName`) to an object in a scene file: ```yaml components: animator: states: anim/knight.states.yaml startClip: idle ``` Play it on `game.Loop`'s fixed steps with `animclip.NewAnimator` (or `animclip.NewStateMachine` with a custom `Binder`): ```go lib := resource.NewLibrary(os.DirFS(".")) sm, err := animclip.NewAnimator(built, "knight", animclip.FSStates{FS: os.DirFS(".")}, lib, components) if err != nil { return err } sm.OnTransition = func(from, to string) { /* ... */ } sm.OnEvent = func(state, event string) { /* ... */ } // Inside game.Loop.Update(dt): sm.SetFloat("move.x", vx) sm.SetFloat("velocity.y", vy) sm.SetBool("on_floor", onFloor) if jumpPressed { sm.Trigger("jump") } sm.Update(dt) ``` - **Condition expressions**: `when` supports `||`/`or`, `&&`/`and`, `!`/`not`, `|param|` / `abs(param)`, unary `-`, and comparisons (`==`, `!=`, `<`, `<=`, `>`, `>=`, `≤`, `≥`). Expressions are parsed and type-checked against `parameters` at load time (`ParseStateMachine`). - **Triggers**: `Trigger(name)` arms a trigger parameter; it is automatically consumed when a transition referencing it fires or cleared at the end of the fixed step (`Update`). - **Scripted input and testing**: `InputDriver` maps project `input.Actions` (such as `move_left`, `move_right`, `jump`, `attack`, `hurt`) into locomotion parameters (`move.x`, `velocity.y`, `on_floor`, `jump`, `attack`, `hurt`), and `SimulateStateMachine` drives a state machine deterministically across fixed steps to report visited states, transition trace, and stuck states. - **Validation and references**: `game check` (`tooling/assetcheck`) validates every `*.states.yaml` file and `animator` component, refusing transitions to missing states, unknown clip files, and parameters no transition reads, with exact file and line numbers. `tooling/refs` follows both `animator.states` and `states[].clip` paths when moving files. ### Scene connections The built-in `animator` component (`sceneformat.RegisterAnimatorComponent` / `sceneformat.AnimatorComponentRegistry`) declares two events and two handlers backed at run time: | Member | Kind | Arguments / Payload | Description | | --- | --- | --- | --- | | `animator.stateChanged` | Event | `sceneformat.AnimatorStateChangedEvent{ObjectID, From, To}` | Emitted once each time the state machine switches to a different state (by transition or `SetState`). | | `animator.clipEvent` | Event | `sceneformat.AnimatorClipEvent{ObjectID, State, Name}` | Emitted once each time the active state's clip crosses a named cue event during `Update`. | | `animator.setState` | Handler | `state` (`string`) | Switches the target object's state machine directly to `state` via `SetState`. | | `animator.trigger` | Handler | `name` (`string`) | Pulses the named trigger parameter on the target object's state machine via `Trigger`. | Connect a state machine to a scene's `sceneformat.Signals` with `animclip.Connect`: ```go sig, err := sceneformat.Connect(built.Doc, components, built) if err != nil { return err } if err := animclip.Connect(sm, sig, "knight"); err != nil { return err } ``` `animclip.Connect` binds `sm` on `sig` (`sig.BindAnimator`) so `animator.setState` and `animator.trigger` handlers drive it, and emits `animator.stateChanged` and `animator.clipEvent` through `sig` alongside any `OnTransition` / `OnEvent` callbacks. `NewAnimator` also registers `sm` on `built` (`BuiltScene.SetAnimator`, implementing `sceneformat.AnimatorProvider`), so passing `built` as the context to `sceneformat.Connect` lets `animator.setState` and `animator.trigger` drive it even before calling `animclip.Connect`. State machine resources now preserve blend-space samples and transition `switch`, `xfade` and `priority` fields for future crossfade and travel playback. Validation requires each state to choose exactly one of `clip`, `blend2d` or `states`; blend-space axes must name declared `float` parameters, samples must have finite coordinates and clips, and `switch` must be `immediate`, `sync` or `atEnd` with a finite non-negative `xfade`. These fields are metadata only until runtime crossfade, travel and nested-machine playback land. Until then `NewStateMachine` refuses a document with a `blend2d` or nested state, naming the state, instead of failing to resolve its empty clip. --- Source: http://nsgo.games/docs/assets/ # assets For the trade-offs between `resources/`, embedded startup files and first-load groups, see [Small downloads and fast starts](http://nsgo.games/docs/small-downloads/). `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. ```go 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): ```go 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()` (`float64` in `[0, 1]`) - `g.Loaded()` and `g.Total()` (`int`) - `g.Loading()`, `g.Done()` (`bool`), and `g.Err()` (`error`) Once loaded, retrieve typed assets from the group or from `Manager` (which searches the most recently registered group holding `name`): ```go 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()`): ```go 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](https://github.com/nsgo-dev/nsgo/issues/1127). ## Tracking decoded asset memory Pass a [`gamedebug.MemoryTracker`](http://nsgo.games/docs/gamedebug/#tracking-asset-memory) to the manager to account for every successfully loaded group asset automatically, and optionally set an `OnBudget` callback: ```go 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: ```go 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`](http://nsgo.games/docs/cli/#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: ```go 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:"` 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](http://nsgo.games/docs/render3d/#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. ```yaml version: 1 id: forest group: forest packVersion: 1.2.0 minBuild: 42 include: [levels/forest/**, music/forest/**] exclude: ["**/*.psd"] ``` ```sh 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. ```go 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 with `ErrInvalidSignature`, because whoever supplies the `PackSpec` (URL, size and hash) would otherwise choose what is mounted. Set `AllowUnsigned` to 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. `DirPackCache` reads 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.FS` that `Fetch` returns is also an `io.Closer`. Close it when the pack is no longer used; one never closed is released when it is garbage collected. `FetchGroup` hands its pack to the group, which releases it on `Group.Reset`, `Group.SetFS`, the next `FetchGroup` into the same group, or when the asset manager's scope is disposed. `Remove` of 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; a `Fetch` of the pack before then keeps it. - `Limits` caps the number of entries, the size of one file, the total unpacked size and the archive itself (zero fields use `DefaultPackLimits()`: 32768 entries, 256 MiB, 1 GiB and 1088 MiB). A pack over a limit is refused before mounting. A download stops with `ErrPackTooLarge` once it would pass `MaxPackBytes`, which bounds the `.part` file of a `PackSpec` without a `Size`. 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 with `ErrPackTooLarge` past `MaxFileBytes`. - A spec that could never verify (a malformed `sha256` or `signature`, or a negative `size`) 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 Content` without a `Content-Range` header starts over from the first byte rather than appending a body whose range it cannot check. - `ParsePackManifest` refuses fields it does not define, such as a misspelt `sha265`, 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 1` pulls 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. - `-seam` keeps 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-frames` and `-max-frames` bound the loop. - `-anchor bottom-center` (the default) or `-anchor center` crops 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. - `-width` and `-height` scale 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): ```yaml 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`](http://nsgo.games/docs/cli/#assets) in `game.yaml` so `go tool game assets` copies them to content-hashed paths (`..`) and writes a sorted, versioned `remote.yaml` manifest, then pass `assets.WithRemote` when creating the `Manager`: ```go 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 from `Base` (defaulting to `Manifest.Base`) using its content-hashed path, checked against exact byte size and SHA-256 (`ErrSizeMismatch` / `ErrHashMismatch`), and stored in `Cache`. URIs not in `Manifest` fall through to local sources (`WithReadAsset`, `WithFS`, or packaged `resources/`). - 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 to `net/http`. Targets without `net/http` (such as mini-program runtimes) can plug in their host request API directly. - `DirRemoteCache` enforces `Quota` (200 MiB by default, matching mini-game filesystem caps) with least-recently-used eviction that never removes files pinned by a loaded or loading `Group`, writes files atomically via temporary files, persists access times in a small `index.yaml` text index, and exposes `Usage()` (`Bytes`, `Quota`, `Files`, `PinnedBytes`) and `Clear()` for a settings screen. Use `MemoryRemoteCache` on 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](http://nsgo.games/docs/project/#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. --- Source: http://nsgo.games/docs/backend-deploy/ # Deploying backend services Use Postgres for production accounts, cloud saves and self-hosted leaderboards. SQLite is suitable for development, tests and a single node with a durable volume. Memory stores are test-only. Run `accountsd`, `cloudsaved` and `leaderboardd` behind one TLS-terminating proxy with rate limits and health checks. Give each daemon an explicit address and share the account service key set from `accountsd genkey` through a protected secret store. Back up Postgres with managed snapshots or `pg_dump` and rehearse restores. Each daemon creates or migrates its schema when it opens the database, and on Postgres the migration takes an advisory lock, so several instances may start at once. A daemon refuses a database whose schema is newer than it knows, so roll forward instead of starting an older binary against a newer database. The file-backed leaderboard keeps boards in memory and is intended for a single process until a shared SQL store is configured. SQLite files require a durable volume and WAL files must be backed up together. Give operators an [admin listener](http://nsgo.games/docs/admin/) by adding an `admin:` block to each daemon's configuration. Bind it to a private address, never the public one the proxy forwards players to, and expose it only through a VPN or an access-controlled proxy that terminates TLS and sets `X-Forwarded-Proto: https`, so the session cookie is `Secure`. Keep each operators file in version control and its `.totp.yaml` secrets file and the audit directory on protected storage, and let every daemon that shares an operators file write the `.totp-used` directory beside it, where accepted TOTP codes are recorded; the audit directory is append-only text, so ship it to your log store like other logs. ## Health and metrics Each daemon serves its deployment endpoints when its configuration sets `metrics` to a listen address. They are absent otherwise, and they never share the listener players reach: ```yaml metrics: 127.0.0.1:9101 ``` | Endpoint | Answers | | --- | --- | | `GET /healthz` | `200` while the process runs | | `GET /readyz` | `200` while the database answers a ping within 2 seconds, else `503`; `leaderboardd -data` checks that its score directory is there | | `GET /metrics` | The series below, in the Prometheus text format | Point a load balancer's readiness probe at `/readyz`, so an instance that loses its database leaves rotation until the database is back, and a liveness probe at `/healthz`, which does not depend on the database, so the orchestrator does not restart every instance during a database outage. On SQLite, `/readyz` and the store counts read through a second, read-only handle on the database file, so a long write on the store's single connection, such as a large cloud save on a slow disk, neither fails the probe nor waits behind a scrape. The endpoints have no authentication: bind `metrics` to `127.0.0.1`, a private interface or a port the proxy does not forward. A daemon whose `metrics` address is not loopback, such as `:9101` for an in-cluster Prometheus, logs a warning at startup to remind you. | Series | Daemon | Meaning | | --- | --- | --- | | `nsgo_http_requests_total{route,code}` | all | Requests served, by route pattern (such as `POST /v1/guest`) and status code; requests no route matched count under `route="unmatched"` | | `nsgo_http_request_duration_seconds{route}` | all | Histogram of the time to serve a request, from 5 ms to 10 s | | `nsgo_accounts_signins_total{method}` | `accountsd` | Sign-ins that returned credentials, `method` one of `guest`, `register`, `email` and `identity` | | `nsgo_accounts_signin_failures_total{method}` | `accountsd` | Sign-ins answered with an error status | | `nsgo_accounts_accounts`, `nsgo_accounts_sessions` | `accountsd` | Accounts, and device sessions signed in and not yet signed out | | `nsgo_cloudsave_accounts` | `cloudsaved` | Accounts with at least one slot, live or deleted | | `nsgo_cloudsave_slots` | `cloudsaved` | Slots whose newest version is a save, not a deletion | | `nsgo_cloudsave_stored_bytes` | `cloudsaved` | Payload bytes of every kept version of every slot | | `nsgo_leaderboard_entries{board}` | `leaderboardd` | Accounts with a score in the board's current period | The account, session, slot and byte counts scan their tables in full, so a daemon runs them at most once every 15 seconds and answers the scrapes in between with the last count; a scrape interval shorter than that sees the same values repeated. Each count gives up after 5 seconds and leaves its series out until the next count, with a warning in the log. A program that builds its own server around `accounts.New`, `cloudsave.New` or `selfhost.New` gets the same endpoints from package `servicehealth`: wrap the player handler in a `servicehealth.Requests`, add collectors to a `servicehealth.Health`, and serve it with `servicehealth.Listen` or mount it on another listener with `Register`. `servicehealth.AuditCollector` exports an `audit.Writer`'s dropped records as `nsgo_audit_dropped_total`. --- Source: http://nsgo.games/docs/backend/ # backend `github.com/nsgo-dev/game/pkg/online/backend` composes the online services' HTTP handlers and compiled game RPC routes into one embeddable `http.Handler`, so one server process can host [accounts](http://nsgo.games/docs/accounts/), [cloudsave](http://nsgo.games/docs/cloudsave/), [leaderboard/selfhost](http://nsgo.games/docs/leaderboard-selfhost/) and the game's own server-side calls. ```go b := backend.New(func(r *http.Request) (backend.Caller, error) { claims, err := verifyBearer(r) if err != nil { return backend.Caller{}, err } return backend.Caller{AccountID: claims.Subject}, nil }) if err := b.Mount("/accounts/", accountsService.Handler()); err != nil { log.Fatal(err) } if err := b.Mount("/saves/", cloudsaveService.Handler()); err != nil { log.Fatal(err) } if err := b.RPC("claim-daily-reward", func(ctx context.Context, caller backend.Caller, raw json.RawMessage) (any, error) { return rewards.Claim(ctx, caller.AccountID) }); err != nil { log.Fatal(err) } log.Fatal(http.ListenAndServe(":8080", b)) ``` ## Mounts `Mount` serves a handler below a prefix and removes the prefix before the handler sees the request, so the accounts service mounted at `/accounts/` answers `GET /v1/me` at `GET /accounts/v1/me`. Each service keeps its own authentication, CORS, validation and error responses. A prefix without a trailing slash gets one. `Mount` returns an error for `/`, a prefix that is not a clean path, a prefix under `/v1/rpc/`, a prefix with characters other than letters, digits, `-`, `_`, `.` and `/`, a nil handler, and a prefix mounted twice. ## RPCs `RPC` serves `POST /v1/rpc/{name}`. A name is letters, digits, `-`, `_` and `.`, and each name is registered once. Every call runs the authentication function given to `New`, which returns the `Caller` passed to the handler together with the raw JSON body; without an authentication function every RPC answers 401. `AddBeforeHook` callbacks run in registration order after authentication and may rewrite the JSON body (returning nil keeps it; a replacement that is not valid JSON answers 500) or return a client-visible `StatusError`. `AddAfterHook` callbacks run in registration order after a successful RPC, observe the authenticated caller, final request body and result, and cannot change the response. | Case | Status | | --- | --- | | The handler returns a result | 200, the result encoded as JSON | | Authentication fails | 401 | | The body is missing, not one JSON value, or larger than 1 MiB | 400 | | The handler returns a `backend.StatusError` with a 4xx or 5xx code | That code, with the error's message | | The handler returns any other error, or a result that cannot be encoded | 500, with a generic message | Return `backend.StatusError{Code: http.StatusConflict, Err: err}` for errors the client should see, such as "already claimed"; its message is sent to the client. Any other error stays on the server, so a database error never leaks its text to players. ## Limits Register mounts, hooks and RPCs before serving: registration is not safe to run concurrently with `ServeHTTP`. Hooks are process-local and apply to game RPCs, while mounted services retain their own request lifecycle. The mux has no goroutines or service stores of its own. --- Source: http://nsgo.games/docs/battle/ # battle `github.com/nsgo-dev/game/pkg/battle` resolves turn-based battles between a party and a troop. It holds no presentation: each turn returns a list of events for the game to animate in its own time, and every roll draws from a [`random.Stream`](http://nsgo.games/docs/determinism/), so a seed and the same commands replay the same battle on every platform. ## A turn ```go r := battle.New( []battle.Fighter{{ID: "hero", HP: 30, MaxHP: 30, MP: 6, Attack: 5, Agility: 7}}, []battle.Fighter{{ID: "slime", HP: 12, Defense: 1, Attack: 3, Agility: 4}}, battle.Rules{CriticalChance: 0.1}, random.New(seed), ) slash := battle.Action{ID: "slash", Scope: battle.OneEnemy, Power: 4, Accuracy: 0.9} bite := battle.Action{ID: "bite", Scope: battle.OneEnemy, Power: 2} events := r.Resolve([]battle.Command{ {Actor: battle.Ref{Side: battle.PartySide, Index: 0}, Action: slash, Target: 0}, {Actor: battle.Ref{Side: battle.TroopSide, Index: 0}, Action: bite, Target: 0}, }) ``` The game chooses every fighter's command, the troop's included. `Resolve` runs them by `Agility`, highest first; ties go to the party before the troop and then to the lower index, whatever the order of the slice. A command for a fighter that does not exist is dropped, and a fighter defeated earlier in the turn does not act. ## Actions and scopes | Scope | Targets | Effect | | --- | --- | --- | | `Self` | the actor | heals `Power` | | `OneAlly` | the living ally at `Target` | heals `Power` | | `AllAllies` | every living ally | heals `Power` | | `OneEnemy` | the living opponent at `Target` | damages | | `AllEnemies` | every living opponent | damages | Damage is `Power + Attack - Defense`, at least 1. Each target of a hostile action rolls to hit against `Accuracy` (0 and 1 mean a sure hit and draw no roll), then for a critical against `Rules.CriticalChance`, which doubles the damage. Healing never raises HP above `MaxHP` when `MaxHP` is set. An action with a `Cost` spends that much MP first; an actor short of MP produces a `NoMP` event and nothing else. ## Events and outcome `Resolve` returns `Missed`, `Damaged`, `Healed`, `Defeated` and `NoMP` events, and the state events below, with the acting and the affected fighter, and `Amount` as the HP actually lost or gained. When the last troop member falls it appends `Won` and stops; when the last party member falls it appends `Lost` and stops. After that, `Resolve` returns nil. ## Saving and replay `Runner.Snapshot` copies the fighters, the turn counter, the outcome and the stream's state, and marshals to JSON for a save slot. `Runner.Restore` puts a snapshot back, after which the same commands produce the same events as the original battle did. ## Not covered yet The runner is the first part of #1757. It has no time-progress (gauge) mode, element rates, items, escape, enemy AI, troop events or rewards, and the rpg2d template does not use it yet. ## States `battle.State` adds a deterministic status effect to a fighter. An action can carry `AddState`, which applies after a successful hostile hit. A state's `Damage` is applied at the start of each turn, `CannotAct` emits `StateBlocked`, and `Turns` decrements until `StateExpired`. Each state event names the state in `Event.State`. A fighter that state damage defeats gets a `Defeated` event and takes no further state damage that turn, and when the last fighter of a side falls this way the turn ends with `Won` or `Lost` before any command runs. State changes are included in `Fighter` and `Snapshot`, so seeded replays and restored battles retain the same effects. ## Damage formulas `battle.EvaluateFormula` evaluates the deterministic formula vocabulary used by `Action.Formula`. It accepts numeric literals, `a.attack`, `a.defense`, `b.attack`, `b.defense`, arithmetic operators and parentheses. When a formula is set, its result, truncated toward zero, is the whole base damage: `Attack` and `Defense` are not added again, and the minimum-one rule and criticals still apply. The evaluator refuses unknown values, syntax errors, division by zero and results that are not finite numbers in the int32 range, because converting those to an integer differs between architectures. An action whose formula fails to evaluate deals its ordinary `Power + Attack - Defense` damage, so check each formula with `EvaluateFormula` when the game loads its actions. --- Source: http://nsgo.games/docs/bullets/ # bullets `game/bullets` spawns, moves and draws the bullet patterns of shooters: rings, spirals and aimed bursts defined in YAML, taken from a `mempool.Pool` and drawn through one `sprite.Batch`. ```go import "github.com/nsgo-dev/game/pkg/bullets" ``` ## Pattern files A pattern file is YAML with a `version` and a list of named `patterns`: ```yaml version: 1 patterns: - name: bloom kind: ring frame: orb count: 24 speed: 90 spin: 7.5 shots: 6 interval: 400ms lifetime: 6s radius: 4 - name: vortex kind: spiral frame: orb count: 5 speed: 140 speedJitter: 8 angleJitter: 2.5 spin: 11 shots: 0 interval: 50ms accel: -20 turn: 15 radius: 3 - name: volley kind: aimed frame: dart count: 7 speed: 220 spread: 45 shots: 3 delay: 1s interval: 150ms lifetime: 3s radius: 2.5 faceHeading: true ``` `Parse` reads a file and refuses unknown fields, a `version` other than `FormatVersion` (1), trailing YAML documents and invalid patterns. `Encode` writes a file back with 2-space indents, its fields in a fixed order and zero optional fields left out, so the same file always encodes to the same bytes and a load and save changes nothing. `File.Pattern(name)` finds a pattern. Angles are in degrees clockwise from +X on the screen, speeds in points a second, and durations are Go durations (`50ms`, `2s`). | Field | Meaning | | --- | --- | | `name` | Unique, not empty | | `kind` | `ring`, `spiral` or `aimed` | | `frame` | Atlas frame each bullet draws; empty spawns bullets that move and collide but draw nothing | | `count` | Bullets each shot fires, 1 to `MaxCount` (4096) | | `speed`, `speedJitter` | Starting speed, varied by a random amount in `[-speedJitter, speedJitter)`, never below 0 | | `angle`, `angleJitter` | Direction of a shot's first bullet (for `aimed`, the turn from the target's direction), varied per bullet by `[-angleJitter, angleJitter)` | | `spread` | Arc an `aimed` burst covers from its first bullet to its last; `aimed` only, above 0 when `count` is above 1 | | `spin` | Degrees each shot turns more than the one before; a `spiral` needs one other than 0 | | `shots`, `delay`, `interval` | Number of shots (0 fires until stopped), time before the first, time between shots (at least `1ms`, or 0 when `shots` is 1) | | `lifetime` | How long each bullet lives; 0 keeps it until it leaves the field's bounds | | `accel`, `turn` | Speed change in points a second each second (a bullet slowed to 0 stops), and path curve in degrees a second | | `radius` | Hit radius, also used to tell when a bullet has left the bounds | | `faceHeading` | Turns the sprite to the direction the bullet moves | | `z` | Sprite order in the field's batch | - `ring` spaces `count` bullets evenly around a full turn, the first at `angle`, turned by `spin` more each shot. - `spiral` is a ring with a `spin`: with a short `interval`, each of its `count` bullets traces an arm. - `aimed` spreads `count` bullets evenly across `spread`, centered on the direction from the emitter to its target and turned by `angle` and `spin`. With an odd `count` and no `angle` or `spin`, the middle bullet flies straight at the target; a single bullet flies at the target turned by `angle`. ## Field and Emitter A `Field` owns the live bullets. `NewField(atlas, capacity)` keeps `capacity` bullets ready in a pool, so spawning up to that many allocates nothing. Set `Bounds` to remove bullets whose hit circle has wholly left the playfield, and `Limit` to cap how many the field holds. `NewEmitter(field, pattern, seed)` fires a copy of the pattern into the field, and checks that the field's atlas has the pattern's frame. Move it with `X`, `Y`, aim it with `TargetX`, `TargetY`, pause it with `Stopped`, and start it over with `Reset`. A stopped emitter's clock stops too, so when it resumes it picks up its pattern where it paused instead of firing the shots it missed. ```go file, err := bullets.Parse(data) field := bullets.NewField(atlas, 6000) field.Bounds = math2d.Rect{W: 480, H: 640} volley, _ := file.Pattern("volley") boss, err := bullets.NewEmitter(field, volley, seed) loop := &game.Loop{ Update: func(dt time.Duration) { boss.X, boss.Y = bossX, bossY boss.TargetX, boss.TargetY = playerX, playerY field.Update(dt) // move the bullets already in flight boss.Update(dt) // then fire the shots due in this step field.RemoveFunc(func(b *bullets.Bullet) bool { return b.Circle().Overlaps(playerHitbox) }) }, } // In a core.Canvas's Draw: field.Draw(d) ``` - Update the field before its emitters each step. A shot due partway through a step spawns its bullets where they are at the step's end, so bullets do not bunch up when the interval is not a whole number of steps. - One `Update` fires at most 4096 bullets' worth of shots (at least one shot). When more are due, as after a long step from a hitch, it fires the latest and skips the earlier ones, which count as fired but spawn nothing and draw no random numbers. - `Field.Bullets()` lists the live bullets oldest first, each with its position, `Speed`, `Heading` (radians), `Radius`, `Age`, `Lifetime`, `Pattern` name, `Shot` index and `Sprite`. The bullets are the field's: do not keep a pointer past the next `Update`, `RemoveFunc` or `Clear`, as the field reuses it. - `Field.Update` keeps the order of the bullets it keeps, and `Field.Draw` draws them lowest `Z` first and oldest first for the same `Z`. - A shot past the field's `Limit` spawns only the bullets that fit, and still draws the same random numbers. ## Determinism An emitter draws its jitter from its own `random.Stream`. Two emitters with the same pattern and seed, moved and stepped with the same `dt`s and targets, spawn the same bullets in the same places: on one build target the results are bit-for-bit equal, which `random.AssertDeterministic` checks in the package's tests. Floating-point results can differ across CPU architectures, so a lockstep game across platforms should compare inputs, not bullet positions. ## Performance `BenchmarkFrame5000` runs one 60 fps frame of a steady 5000-bullet scene: ten spiral emitters with jitter and curving paths, half of them with turned sprites, moving, expiring, spawning and drawing into a `core.Drawing`. On a desktop Ryzen 9 3900X it takes about 0.63 ms of the 16.7 ms a frame has; moving 5000 bullets alone (`BenchmarkUpdate5000`) takes about 0.14 ms. The performance baselines in CI (`benchmarks/baseline.yaml`) fail a change that makes a frame take more than 6.25 ms on the CI runner. This measures the CPU work of a frame: simulating the bullets and recording their draw ops. It does not measure how long the platform's renderer takes to put those ops on screen, which is NSGo's and depends on the GPU. - Moving and firing allocate nothing once the pool is warm. - `sprite.Batch` draws the bullets as runs through NSGo's `Drawing.DrawAtlas`, which copies each run and allocates three values per run, however many bullets it holds. --- Source: http://nsgo.games/docs/cards/ # cards `game/cards` drags cards between the slots of a board in the game view and lays them out as fanned hands, decks, piles and grids. A card dropped on a slot that accepts it snaps into place; one dropped anywhere else flies back to where it came from. Every move is a `game/tween` advanced on `game.Loop`'s fixed steps, and the mouse and touch take the same path. ```go import "github.com/nsgo-dev/game/pkg/cards" ``` ## Boards, slots and cards A `Board` holds `Slot`s in the order they are added (later slots sit on top), and each slot holds an ordered list of `Card`s, the first at the bottom. A slot's `Rect` is both where its `Layout` places its cards and where a pointer drops onto it. The zero `Board` is ready to use. ```go board := &cards.Board{CardSize: math2d.V2(63, 88), Curve: core.EaseOut} hand := &cards.Slot{ID: "hand", Rect: math2d.Rect{X: 40, Y: 400, W: 560, H: 120}, Layout: cards.Fan{Arc: 24, Sag: 14}} play := &cards.Slot{ID: "play", Rect: math2d.Rect{X: 40, Y: 160, W: 560, H: 200}, Layout: cards.Grid{Gap: math2d.V2(8, 8)}, Accepts: []string{"spell"}, Capacity: 5} deck := &cards.Slot{ID: "deck", Rect: math2d.Rect{X: 620, Y: 400, W: 63, H: 88}, Layout: cards.Stack{Offset: math2d.V2(0, -0.5), Depth: 8}, Grab: cards.GrabTop} for _, s := range []*cards.Slot{hand, play, deck} { board.AddSlot(s) } for _, c := range opening { board.Add(&cards.Card{ID: c.Name, Tags: []string{c.Kind}, Data: c}, hand, -1) } ``` - `Add` places a card at once, for the opening position; `Move` tweens it to another slot, as dealing or an undo does; `Remove` takes it off and closes the gap. None of them checks the slot's rules. - `Card.Pose()` is where to draw a card now: its center `Pos` and its rotation `Rot` in radians. `Slot.Cards()`, `Slot.Top()`, `Card.Slot()` and `Card.Index()` say where it belongs. - `Card.Locked` keeps a card in place, and `Slot.Grab` says which cards of a slot a pointer may take: `GrabAny` (a hand), `GrabTop` (a deck or a discard pile) or `GrabNone`. ## Layouts | Layout | Arranges | Fields | | --- | --- | --- | | `Fan` | A hand in a row centered in the slot, tilting and dropping toward its ends | `Spacing` between centers (0 is 60% of the card's width), `Arc` in degrees for a full-width hand, `Sag` in points at its ends | | `Stack` | A deck or a pile from the slot's top-left corner | `Offset` from each card to the next, `Depth` capping how many offsets show | | `Grid` | Rows of cards from the slot's top-left corner | `Columns` (0 fits the slot's width), `Gap` between cards | A fan closes up when the hand would not fit the slot, and its cards tilt by how far they sit from the middle, so a short hand stays nearly flat and a full one reaches `±Arc/2`. A layout also decides where a dropped card goes: a fan inserts it at the place nearest its center, so dragging within a hand reorders it, a grid at the cell under it and a stack on top. A game can write its own `Layout` with `Arrange` and `InsertIndex`. After changing a slot's `Rect` or `Layout`, `board.Relayout(slot)` tweens its cards to their new places. ## Dragging with the mouse and touch NSGo reports the primary mouse button as finger 0 of `core.TouchEvent` on the desktops and every pointer as a finger on the web, so one handler takes the mouse and touch alike. Attach the board to the view that holds the game's `Canvas`, and step it in the loop: ```go view := core.View{Children: []core.Node{core.Canvas{Draw: draw}}} board.Attach(&view) // chains any OnTouch the view already has loop.Update = func(dt time.Duration) { board.Update(dt) } ``` Touch positions arrive in the view's coordinates; set `board.MapPoint` when the board is drawn through a camera or a scaled viewport, returning false for a point outside it. A game that reads pointers some other way calls `PointerDown`, `PointerMove`, `PointerUp` and `PointerCancel` with its own pointer IDs. - A press takes the topmost card under it, following each card's rotation. The card starts following once the pointer moves more than `DragSlop` (6 points by default), keeping where it was held and turning upright; a release before that is a tap (`OnTap`). - Each finger drags its own card, so two hands can play at once; a card already pressed by one pointer is not taken by another. - On release, the card drops on the topmost slot under the pointer, or failing that the slot its body overlaps most. It snaps in over `SnapDuration` when `CanDrop` allows it: its own slot always does, another needs room under `Capacity`, one of the card's tags in `Accepts` when that is set, and `Slot.Accept` and `Board.Accept` when they are set. Otherwise, or over no slot, or when the touch is cancelled, it flies back to its place over `ReturnDuration`. - `OnPickUp`, `OnDrop` (with the slots and indices it moved between) and `OnReturn` (with the slot that refused it, if any) report each step, and `DropTarget(card)` says during a drag which slot is under the card and whether it would accept it, for highlighting. ```go board.Accept = func(c *cards.Card, from, to *cards.Slot) bool { return to != play || mana >= c.Data.(Spell).Cost } board.OnDrop = func(e cards.DropEvent) { if e.To == play { cast(e.Card.Data.(Spell)) } } ``` ## Drawing `DrawOrder(dst)` lists the cards bottom first: each slot's cards in slot order, then the cards being dragged or flying, in the order they were lifted. Draw each at its pose: ```go order = board.DrawOrder(order[:0]) for _, c := range order { p := c.Pose() d.Save() d.Translate(p.Pos.X, p.Pos.Y) d.Rotate(p.Rot) drawCard(d, c, board.Size()) d.Restore() } ``` Once the board's slices have grown, `DrawOrder`, `Update` and `PointerMove` during a drag allocate nothing. Picking up a rotated card, dropping one and sending one back each allocate a tween for every card that starts to move. ## Board files A board's card size and slots can be written as YAML and loaded with `ParseBoardDoc` and `LoadBoard`. Unknown fields are refused, the version must be `1`, and `EncodeBoardDoc` writes the fields in a fixed order and in block style, as below, so a file in that form is unchanged when read and written again; a hand-written file in flow style (`rect: {x: 40, ...}`) comes back in block style the first time it is saved. `board.Doc()` turns a board built in code back into a `BoardDoc`; a slot's `Accept` function and the board's callbacks and timings stay in code. ```yaml version: 1 card_size: w: 63 h: 88 slots: - id: hand rect: x: 40 "y": 400 w: 560 h: 120 layout: fan: arc: 24 sag: 14 - id: deck rect: x: 620 "y": 400 w: 63 h: 88 layout: stack: offset: x: 0 "y": -0.5 depth: 8 accepts: - spell capacity: 40 grab: top ``` Each slot names exactly one of `fan`, `stack` or `grid`; `grab` is `top` or `none`, and is left out for the default, any card; `grab: any` is refused so the default has one form. The encoder quotes the `y` key, which YAML 1.1 reads as a boolean, so other tools read the file the same way. ## Deck piles `pkg/cards/deck` provides deterministic draw, hand, discard, and exhaust piles. Draw refills from a shuffled discard pile, while end-turn handling retains cards with `retain` and exhausts cards with `ethereal`. --- Source: http://nsgo.games/docs/cloudsave/ # cloudsave `github.com/nsgo-dev/game/pkg/online/cloudsave` is a self-hostable cloud save service: each player account has save slots over HTTPS, kept in versions. Two devices writing the same slot at once cannot overwrite each other, a slot over the size limit is refused with a clear error, and the last few versions of each slot can be listed and restored. Games talk to it through `liveops.CloudClient`, a `liveops.CloudSync`, so a `liveops.CloudSyncer` keeps local saves in step with it and resolves conflicts by its policy. The service is server-side code in its own packages; a game client imports only `liveops`. It keeps no accounts of its own: it verifies the tokens of the [account service](http://nsgo.games/docs/accounts/) offline with `accounts/authtoken`, accepting only those for its own audience (`cloudsave` by default, see [Token audiences](http://nsgo.games/docs/accounts/#token-audiences)), and files each player's slots under the token's subject, the account ID. A player signed in to the same account on the web and on an Android phone reads and writes the same slots. | Package | What it holds | | --- | --- | | `cloudsave` | `Service`, `Config`, the `Store` interface, `MemoryStore` and the HTTP `Handler` | | `cloudsave/sqlitestore` | A `Store` in a SQLite file (pure Go, no cgo); every target but the web | | `cloudsave/pgstore` | A `Store` in Postgres, shared by several service processes | | `cloudsave/sqlstore` | The SQL schema and queries both stores share | | `cloudsave/storetest` | The `Store` contract tests, for a store of your own | | `cmd/cloudsaved` | A standalone HTTP server | | `liveops` | `CloudClient`, the game's side | ## On the device ```go cloud, err := liveops.NewCloudClient(liveops.CloudClientOptions{ URL: "https://saves.example.com", Token: func(ctx context.Context) (string, error) { return session.TokenFor(ctx, "cloudsave") // POST /v1/refresh {"session", "audience": "cloudsave"}, refreshed when it expires }, }) if err != nil { return err } syncer, err := liveops.NewCloudSyncer(liveops.CloudSyncOptions{ Local: save.StorageBackend(cx.Storage(), "mygame"), Cloud: cloud, State: cx.Storage(), Device: deviceID, SaveVersion: 2, // the Store.Version this build writes Policy: liveops.PolicyKeepBoth, }) ``` Save through `save.NewStore(syncer.Backend(), save.WithVersion(2), ...)` and call `syncer.Sync(ctx)` when the game starts, after a save and when it returns to the foreground; see [liveops](http://nsgo.games/docs/liveops/#cloud-saves) for how the syncer detects and resolves conflicts. ## Mixed client versions When a player plays on a newer build (for example save version 3) and then opens an older build (save version 2), setting `CloudSyncOptions.SaveVersion` to the build's `save.Store.Version` keeps the older client from overwriting either side: - Before writing a cloud copy locally, `CloudSyncer` checks its save envelope version (`save.EnvelopeVersion`). When it exceeds `SaveVersion`, the syncer leaves the local slot and sync state untouched and reports `liveops.OutcomeNeedsUpdate` with `SlotResult.LocalVersion` and `SlotResult.CloudVersion` (collected by `res.NeedsUpdate()`), so the game can prompt the player to update while keeping the local save loadable. - If the player keeps playing or starts fresh on the older build, the next sync sees both sides diverged and never uploads over the newer-version cloud copy. - In conflicts where both copies carry different envelope versions, `CloudSyncer` never resolves in favour of the older envelope version; it falls back to keeping both (and when the cloud copy still exceeds `SaveVersion`, forks the local copy without overwriting the local slot and reports `OutcomeNeedsUpdate`). `Conflict.Local.EnvelopeVersion` and `Conflict.Cloud.EnvelopeVersion` expose both versions so `PolicyAsk` dialogs can tell the player a copy was saved by a newer game version. ```go res, err := syncer.Sync(ctx) if err != nil { return err } for _, slot := range res.NeedsUpdate() { showUpdatePrompt(slot.Slot, slot.LocalVersion, slot.CloudVersion) } ``` `CloudClient` needs an `https` URL; `http` is accepted only on a loopback host (`localhost`, `127.0.0.1`, `::1`) for development. It uses `net/http`, so it works on every target: on the web its requests go through the browser's `fetch`, and the page's origin must be in the service's `allowedOrigins`; an Android app needs the `INTERNET` permission. Its errors wrap the `liveops` sentinels: | Error | When | | --- | --- | | `ErrSlotNotFound` | The slot, or the version asked for, does not exist | | `ErrCloudChanged` | A conditional write lost to another device's; nothing was written | | `ErrSlotTooLarge` | The payload is over the service's `maxSlotBytes`; the message gives the limit | | `ErrTooManySlots` | A new slot would exceed the service's `maxSlots` | | `ErrCloudUnavailable` | The network or the service failed, the token source failed or the service refused the token; a sync stops on it as it does when offline | A done context's error is returned as it is. ## Concurrent writes Every write names the payload it replaces. `CloudClient` implements `liveops.ConditionalCloudSync`: `SaveIf(ctx, slot, data, match)` writes only while the slot holds the payload whose `liveops.PayloadHash` is `match` (`"sha256:"` and the hex SHA-256 of the raw bytes), or does not exist when `match` is empty, and `DeleteIf` deletes on the same condition. Over HTTP the condition is `If-Match: ""` or `If-None-Match: *`; the service checks and writes in one atomic step, and answers `412 changed` when the slot holds anything else. `CloudSyncer` makes every cloud write conditional on the copy it read. When the phone and the browser both changed a slot and the browser uploads first, the phone's upload fails with `ErrCloudChanged` and changes nothing; on its next sync the phone sees both copies as a conflict, and the policy keeps the newer, keeps both as a fork slot, or asks the player. No upload is ever overwritten silently. ## Versions and restore Every write or delete adds a version to the slot, numbered from 1, and the service keeps the newest `keepVersions` of them. A delete is a version that marks the slot deleted, so a deleted slot keeps its history and can be brought back. ```go versions, err := cloud.Versions(ctx, "main") // newest first: Number, Deleted, Hash, Size, Created data, err := cloud.LoadVersion(ctx, "main", versions[2].Number) err = cloud.Restore(ctx, "main", versions[2].Number) err = cloud.Purge(ctx, "main") // the slot and its history, for good ``` `Restore` writes the old copy as a new version, conditional on the slot still holding the copy it read (`ErrCloudChanged` otherwise); restoring a deletion deletes the slot. A payload written by `CloudSyncer` is re-stamped with the next revision and the current time, so every device takes the restore as the newest copy: a device whose copy has not changed since its last sync downloads it, and one with unsynced changes gets a conflict its policy resolves. Other payloads are restored byte for byte. `Service.Restore` on the server restores the bytes unchanged. ## Limits - `maxSlotBytes` bounds a payload. A larger one is refused with `413 slot_too_large` and `{"limit": maxSlotBytes}` before the service reads past the limit, and the slot keeps its current copy. A `CloudSyncer` payload is the save inside a JSON envelope: about 250 bytes more, with the save's quotes and backslashes escaped, or base64, a third larger, for data that is not UTF-8. - `maxSlots` bounds an account's live slots; a write that would create one more is refused with `409 too_many_slots`. Fork slots made by `PolicyKeepBoth` count. A deleted slot does not count, but once an account has more than `maxSlots` deleted slots the oldest are purged with their history, so an account never holds more than twice `maxSlots` slots. - Slot names are 1 to 200 bytes of UTF-8 without control characters or `/`, other than `.` and `..` (`ValidateSlot`); every name `save.ValidateSlot` accepts passes. In URLs they are path segments, escaped as `url.PathEscape` does. ## Configuration `Config` is a versioned YAML file: ```yaml version: 1 audience: cloudsave maxSlotBytes: 1048576 maxSlots: 32 keepVersions: 5 allowedOrigins: - https://play.example.com metrics: 127.0.0.1:9102 ``` | Field | Meaning | | --- | --- | | `version` | The schema version, `1` | | `audience` | The token audience the service accepts, `cloudsave` when omitted; the account service must list it in its `audiences`, and it must differ from the key set's audience | | `maxSlotBytes` | The largest payload, from 1 byte to 64 MiB | | `maxSlots` | Live slots per account, from 1 to 10000 | | `keepVersions` | Versions kept per slot, the current one included, from 1 to 100 | | `allowedOrigins` | Web origins whose pages may call the service; omitted when empty | | `metrics` | The address `cloudsaved serve` serves `/healthz`, `/readyz` and `/metrics` on, such as `127.0.0.1:9102`, a listener of its own (see [Health and metrics](http://nsgo.games/docs/backend-deploy/#health-and-metrics)); omitted when unset, and then none of them is served | `ParseConfig` refuses unknown fields, trailing documents, out-of-range values, a `metrics` address without a port, `audience: accounts` (the account service's own audience) and an origin with a path, a wildcard, a port outside 1 to 65535 or a scheme other than `http` and `https`. `Config.Marshal` writes the canonical form: the fields in the order above, `audience` and `metrics` only when set and `allowedOrigins` only when it has entries. A file in that form, such as one `Marshal` or `cloudsaved init` wrote, reads back and writes again unchanged. `DefaultConfig` returns the settings shown, without origins. ## Storage `Store` keeps the versions. Its `Append` is atomic: of two writes based on the same version, at most one commits. ```go store, err := sqlitestore.Open(ctx, "saves.db") // one service process store, err := pgstore.Open(ctx, os.Getenv("CLOUDSAVE_POSTGRES_DSN")) // several processes verifier, err := authtoken.NewVerifierFor(keySet, cfg.TokenAudience()) // not authtoken.NewVerifier, which accepts game server tokens svc, err := cloudsave.New(cfg, cloudsave.Options{Store: store, Tokens: verifier, Logger: slog.Default()}) ``` `New` refuses a verifier for any audience other than `Config.TokenAudience`, and one for the audience of the key set it was built from, which names the game's servers, even when the configuration names that audience. The SQL store keeps two tables, `cloudsave_slots` (each slot's newest version) and `cloudsave_versions` (the kept versions with their payloads), and versions its schema in `cloudsave_schema`. Each write compares and sets the slot's newest version number in one transaction; on Postgres it also takes an advisory lock on the account, so the slot count and pruning see every concurrent write. SQLite uses the pure-Go `modernc.org/sqlite` driver with write-ahead logging and one connection; Postgres uses `github.com/jackc/pgx/v5`. Both create their tables when missing and refuse a schema newer than they know. `NewMemoryStore` keeps everything in memory for tests and prototypes, and a store of your own passes `storetest.Run`. ## HTTP `Service.Handler` serves the service. Every request except `GET /v1/openapi.yaml` carries `Authorization: Bearer ` with a token from the account service for the service's audience; a token for any other audience, such as the one a player sends a game server, is `invalid_token`. Every response carries `Cache-Control: no-store`. Payloads are `application/octet-stream`; a version is `{"slot", "version", "deleted", "hash", "size", "created"}`, `created` in RFC 3339 with milliseconds and `deleted` and `hash` only when set. The full machine-readable contract is published as an [OpenAPI 3.1 description](https://nsgo.games/schemas/cloudsave-openapi.v1.yaml) and served live at `GET /v1/openapi.yaml`. | Request | Answer | | --- | --- | | `GET /v1/openapi.yaml` | the OpenAPI 3.1 description in YAML (unauthenticated; CORS allowed for `allowedOrigins`) | | `GET /v1/saves` | `{"slots": [version]}`, the live slots by name | | `GET /v1/saves/{slot}` | the payload, with `ETag` (its hash in quotes) and `Save-Version` | | `PUT /v1/saves/{slot}` | version; `If-Match: ""` or `If-None-Match: *` make it conditional | | `DELETE /v1/saves/{slot}` | 204; the same headers make it conditional | | `GET /v1/saves/{slot}/versions` | `{"versions": [version]}`, newest first | | `GET /v1/saves/{slot}/versions/{n}` | the payload of version `n` | | `DELETE /v1/saves/{slot}/versions` | 204, the slot and its history purged | Errors are `{"error": code}`: `bad_request` 400 (an invalid slot name, version number or precondition header), `invalid_token` 401, `not_found` 404, `too_many_slots` 409, `deleted` 410 (a version that is a deletion has no payload), `changed` 412, `slot_too_large` 413 with `limit`, `unavailable` 503 when the request was cancelled or timed out, and `internal` 500. For `allowedOrigins` the handler answers CORS preflight requests and exposes `ETag` and `Save-Version`. It does not limit request rates: run it behind TLS and a rate limiter. ## cloudsaved `cmd/cloudsaved` runs the service: ```sh cloudsaved init -config cloudsave.yaml cloudsaved serve -config cloudsave.yaml -keyset keys.yaml -sqlite saves.db -addr :8081 CLOUDSAVE_POSTGRES_DSN=postgres://... cloudsaved serve -config cloudsave.yaml -keyset keys.yaml -postgres ``` `init` never overwrites a configuration. `-keyset` is the key set file `accountsd genkey` keeps; `serve` reads it once at start, so restart it after a key rotation adds a key. `serve` accepts only tokens for the configuration's `audience` and refuses to start when that is the key set's audience, which names the game's servers. `serve` logs JSON to stderr and stops on SIGINT or SIGTERM. With `metrics` set, it also answers `/healthz`, `/readyz` and `/metrics` on that address, exporting requests, live slots and stored bytes (see [Health and metrics](http://nsgo.games/docs/backend-deploy/#health-and-metrics)). Use the `Token` method of a [`liveops.Account`](http://nsgo.games/docs/accounts/#game-side-client) whose `Audience` is the service's audience as `CloudClientOptions.Token`, so refreshes are shared and the session stays in the platform keychain. An optional `admin:` block at the end of `cloudsave.yaml` makes `serve` run an [admin listener](http://nsgo.games/docs/admin/) on an address of its own, which accepts operator sessions and the account service's `admin` bearer tokens; without it no admin route exists. The configuration refuses `admin` as its `audience`. See [Deploying backend services](http://nsgo.games/docs/backend-deploy/) for production store and daemon topology. ## Operator routes With an `admin:` block, the [admin listener](http://nsgo.games/docs/admin/) also serves `Service.AdminRoutes`, so support can look at and fix a player's saves without the player's token. A service embedded in a server of your own registers them with `admin.ListenOptions.Routes` or `Server.Handle`. Each route needs one permission; `*.read` does not grant `cloudsave.read.payload`, because a save may hold personal data. | Request | Permission | Answer | | --- | --- | --- | | `GET /admin/v1/cloudsave/stats` | `cloudsave.read` | `{"accounts", "slots", "bytes"}`: accounts with a slot, live slots, bytes of every kept version, counted at most once every 15 seconds | | `GET /admin/v1/cloudsave/accounts/{id}/slots` | `cloudsave.read` | `{"slots": [version]}`, deleted slots included | | `GET /admin/v1/cloudsave/accounts/{id}/slots/{slot}/versions` | `cloudsave.read` | `{"versions": [version]}`, newest first | | `GET /admin/v1/cloudsave/accounts/{id}/slots/{slot}/versions/{n}` | `cloudsave.read.payload` | the payload of version `n` as an attachment (`Content-Disposition: attachment`, `X-Content-Type-Options: nosniff`), with `ETag` and `Save-Version`; every download is audited | | `POST /admin/v1/cloudsave/accounts/{id}/slots/{slot}/restore` | `cloudsave.restore` | `{"version": n, "ifMatch": ""}` -> the version written | | `DELETE /admin/v1/cloudsave/accounts/{id}/slots/{slot}` | `cloudsave.purge` | 204, the slot and its history purged | | `DELETE /admin/v1/cloudsave/accounts/{id}` | `cloudsave.purge` | 204, every slot of the account purged, deleted ones included | A restore writes the kept version's bytes back unchanged as the slot's next version, as `Service.Restore` does, conditional on the slot still holding the payload with hash `ifMatch`, or, without it, the payload it held when the request was read; a slot that changed in between answers `412 changed` and nothing is written. The player's next sync receives the restored copy: a device whose copy has not changed since its last sync downloads it, and a device that writes on top of the replaced copy gets `412 changed`, which its conflict policy resolves. Restoring a deletion deletes the slot. Every request that changes something writes an audit record whose subject is `account:`: a restore carries `slot`, `version` (the one restored) and the operator's `ifMatch` when given, and when it succeeds `before` and `after` (the slot's hashes, `before` empty for a deleted slot) and `written` (the new version's number); a slot purge carries `slot`, `before` (empty for a deleted slot) and `versions`, and is recorded as `cloudsave.purge`; an account purge carries `slots` and `versions` and is recorded as `cloudsave.purge.account`. A purge records what the store removed, counted in the same transaction as the removal, so a player's write that lands just before it is both removed and counted. A payload download writes a `cloudsave.read.payload` record with `slot`, `version` and `hash`. A purge of a slot or an account that holds nothing answers 404. Errors are those of the player API, with `bad_request` also for an invalid account ID or restore body, and the listener's own `401 unauthorized`, `403 forbidden` (with `permission`) and `403 csrf`. The routes are in the [OpenAPI description](https://nsgo.games/schemas/cloudsave-openapi.v1.yaml) under the `operator` tag. `Store.Purge` and `Store.PurgeAccount` remove a slot or every slot and version of an account in one transaction and return what they removed (`cloudsave.Purged`), and `Store.Stats` counts accounts, live slots and kept bytes; a store of your own implements them, and `storetest.Run` checks them. `Service.Stats` answers from one count for 15 seconds and gives up on a count after 5 seconds; `Options.Stats` replaces the store's count, and `cloudsaved` sets it to count through the read-only handle its probes use on SQLite, so an operator asking for statistics never holds the connection players' requests wait for. --- Source: http://nsgo.games/docs/cues/ # cues `github.com/nsgo-dev/game/pkg/cues` keeps gameplay presentation mappings in a versioned YAML file, so gameplay code names a cue tag and never an asset. The package owns deterministic parsing and cue lifecycle bookkeeping. A game supplies `cues.Hooks` to connect the mapping to its particle, audio, camera and sprite systems. ```yaml version: 1 cues: - tag: cue.hit.fire once: true particles: file: fx/hit.yaml attach: chest offset: x: 0.5 "y": -1 sound: file: sfx/hit.yaml shake: amplitude: 0.5 duration: 100ms flash: color: '#ff8800' duration: 50ms - tag: cue.status.burning whileActive: true particles: file: fx/burning.yaml sound: file: sfx/burning.yaml loop: true animation: burning ``` Each cue has a unique dotted `tag`, sets `once`, `whileActive` or both, and names at least one handler: `particles` (an effect file, an optional attach point and offset), `sound` (a file, optionally looping), `shake` (a non-negative amplitude and a duration), `flash` (a color and a duration on the target sprite) or `animation` (an animation state). `cues.Parse` refuses unknown fields, duplicate keys, trailing documents and invalid handlers with a `*loaderr.Error` naming the field, and `cues.Encode` writes the set back unchanged. The format is listed on [File Formats](http://nsgo.games/docs/formats/). ## Playing cues `NewPlayer` validates the set and builds a client-side dispatcher. `Dispatch` takes an `Event`: - `EventExecuted` fires a `once` cue. A one-shot is keyed by tag, target, instance and simulation step, so dispatching the same event again while re-simulating after a rollback does not play it twice. `Forget` drops the records of steps a rollback can no longer return to. - `EventAdded` starts a `whileActive` cue on a target, and is ignored while the cue is already active there. `EventRemoved` stops it, calling `Hooks.Stop` once. After a rollback, keep dispatching the re-simulated events, then call `Reconcile` with the while-active cues of the corrected present state. Cues missing from that state stop, ordered by tag and then target, and newly present cues start in input order; a cue active before and after the rollback keeps playing without a restart. `Reset` stops every active cue and clears the one-shot records. `Hooks` callbacks receive the parsed handler and the original event. Resource loading, pooling and target attachment stay in the game layer. The package imports no sound, rendering or scene code, so a headless server can parse cue files without constructing a player. --- Source: http://nsgo.games/docs/cutscene/ # cutscene `game/cutscene` plays both pre-rendered video cutscenes and in-engine timeline cutscenes in a game, in a scene or between scenes. Video cutscenes play in NSGo's own video view (`core.Video`) over the game's view while pausing `Loop` and `Mixer`. Timeline cutscenes run deterministically on `game.Loop` fixed steps against a `sceneformat.BuiltScene` or `sceneformat.SceneDoc`, driving camera, actor, localized dialogue, sound effect and music tracks. Both kinds are skippable and call the game back when they end. ```go import "github.com/nsgo-dev/game/pkg/cutscene" ``` ## Cutscene files A cutscene is a `Cutscene`, written in YAML as either version 1 (video only, `cutscene.MinVersion`) or version 2 (video or timeline, `cutscene.CurrentVersion`). Published JSON Schemas live at `https://nsgo.games/schemas/cutscene.v1.json` and `https://nsgo.games/schemas/cutscene.v2.json`. ### Video cutscenes (version 1 and 2) ```yaml version: 1 source: asset:cutscenes/intro.mp4 group: cutscenes skippable: true skipAfter: 1.5s fit: cover ``` | Key | Meaning | | --- | --- | | `version` | `1` (`cutscene.MinVersion`) or `2` (`cutscene.CurrentVersion`). | | `kind` | Optional in version 2: `video` (default when `source` is set) or `timeline`. Forbidden in version 1. | | `source` | The video: an `asset:` path in the app's resources, a project-relative path or a URL, as `core.Video` takes. Required for video cutscenes. | | `group` | The mixer group whose volume, times the master volume, the video plays at. Left out: the master volume alone. | | `skippable` | Whether the player can skip it. Left out: `false`. | | `skipAfter` | How far into the cutscene a skippable cutscene must play before a skip works, written as Go writes durations (`500ms`, `2s`), so a press meant for the game just before it does not skip it at once. Left out: from the start. | | `fit` | How the picture fits the screen: `contain` (the default, with bars), `cover` (cropped) or `stretch` (distorted). | | `transparent` | Leave the screen behind the picture clear rather than black, so the game shows in the bars and through a video with an alpha channel where the platform keeps it. | ### Timeline cutscenes (version 2) A version 2 timeline cutscene (`*.cutscene.yaml`) sets `kind: timeline`, `length` and ordered `tracks` of clips, each with a `start`, `duration` and optional `easing` (`linear`, `easeIn`, `easeOut`, `easeInOut`, `hold`): ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/cutscene.v2.json version: 2 kind: timeline scene: scenes/level_01.scene.yaml length: 12s skippable: true skipAfter: 1s tracks: - id: camera name: Camera kind: camera clips: - id: cam1 start: 0s duration: 1.6s easing: hold action: hold target: door - id: cam2 start: 1.6s duration: 2.4s easing: easeInOut action: pan target: knight - id: cam3 start: 4s duration: 8s action: follow target: knight - id: knight name: Knight kind: actor target: knight clips: - id: kn1 start: 1s duration: 2.4s easing: easeOut action: walk fromX: 60 toX: 220 state: run - id: kn2 start: 3.4s duration: 4.6s action: state state: idle - id: slime name: slime_01 kind: actor target: slime_01 clips: - id: sl1 start: 6s duration: 800ms easing: easeIn action: drop fromY: -40 toY: 276 - id: sl2 start: 6.8s duration: 5.2s action: patrol fromX: 420 toX: 520 speed: 40 - id: dialogue name: Dialogue kind: dialogue clips: - id: dl1 start: 3.6s duration: 2.4s line: intro.knight.01 - id: sfx name: Sound kind: sound group: sfx clips: - id: sx1 start: 200ms duration: 600ms source: audio/door_slam.wav - id: music name: Music kind: music group: music clips: - id: mu1 start: 2s duration: 10s source: audio/cellar_theme.ogg fadeIn: 2s ``` | Track kind | Track fields | Clip actions & fields | | --- | --- | --- | | `camera` | `id`, `name`, `kind`, `clips` | `action: hold` (`target` or `toX`/`toY`, optional `offsetX`/`offsetY`, `zoom`), `action: pan` (`target` or `toX`/`toY`, optional `fromX`/`fromY`, `offsetX`/`offsetY`, `zoom`, `easing`), `action: follow` (`target`, optional `offsetX`/`offsetY`, `zoom`). | | `actor` | `id`, `name`, `kind`, `target` (scene object ID), `clips` | `action: walk` (`toX`/`toY`, optional `fromX`/`fromY`, `state`, `easing`), `action: state` (`state`), `action: drop` (`toY`, optional `fromY`/`fromX`/`toX`, `state`, `easing`), `action: patrol` (`toX`/`toY`, optional `fromX`/`fromY`, `speed`, `state`, `easing`). | | `dialogue` | `id`, `name`, `kind`, `clips` | `line` (required l10n key — text lives in the localization tables, never inline), optional `speaker`. | | `sound` | `id`, `name`, `kind`, optional `group` (default `sfx`), `clips` | `source` (audio path or URI), optional `group`, `volume` (`[0, 1]`). | | `music` | `id`, `name`, `kind`, optional `group` (default `music`), `clips` | `source`, optional `group`, `volume` (`[0, 1]`), `fadeIn`, `fadeOut`, `loop`. | `cutscene.Parse(data)` reads both versions strictly, refusing unknown keys, a second YAML document, unsupported versions, timeline fields in version 1, mixing video and timeline fields, overlapping clips on non-sound tracks, non-finite numbers and negative or non-string durations. `cutscene.Encode(c)` writes canonical 2-space YAML (prefixing version 2 files with `SchemaCommentV2` and keeping version 1 output unchanged) so files round-trip byte for byte. A cutscene constructed in code may leave `Version` at 0. ## Playing a timeline cutscene `NewTimelinePlayer(c, target)` runs a timeline cutscene deterministically on `game.Loop`'s fixed steps against a `*sceneformat.BuiltScene` (or `*sceneformat.SceneDoc`), resolving dialogue line IDs through an `*l10n.Catalog` and triggering sound/music cues: ```go tl, err := cutscene.NewTimelinePlayer(c, cutscene.TimelineTarget{ Scene: builtScene, Catalog: catalog, Locale: "en", Mixer: mixer, OnActorState: func(actorID, state string) { setAnim(actorID, state) }, OnSound: func(clip cutscene.Clip, group string, vol float32) { playSFX(clip.Source, group, vol) }, OnDone: func(r cutscene.Result) { resumeGameplay() }, }) if err != nil { return err } tl.Play() // Inside game.Loop.Update: tl.Update(dt) ``` `tl.Seek(at)` scrubs directly to any timestamp in `[0, Length]` and evaluates actor, camera and dialogue states purely without firing sound, music or completion callbacks. `tl.Reset()` rewinds to time 0 and restores initial actor and camera positions. To wire the same skip keys, press-to-skip, back handling, `CanSkip()`, reactive `Dialogue()` and between-scene transitions (`TimelineScene`) as video cutscenes, play through `Player`: ```go _, err := player.PlayTimeline(c, cutscene.TimelineTarget{Scene: builtScene, Catalog: catalog}, func(r cutscene.Result) { resumeGameplay() }) // Inside game.Loop.Update: player.Step(dt) ``` Unlike video cutscenes, `PlayTimeline` leaves `Options.Loop` and `Options.Mixer` running so the scene continues drawing and playing cutscene audio while `Player.View()` captures skip input. ## Validation with `game check` and `tooling/refs` `game check` (package `tooling/assetcheck`) validates every `*.cutscene.yaml` / `*.cutscene.yml` file in a project: - Parses and validates the cutscene schema. - Verifies that `scene` (when set) and every project-relative video or audio `source` exists. - Verifies that every actor track `target` and camera clip `target` names an object in the referenced scene (including inherited and instanced scenes). - Verifies that every dialogue clip `line` ID exists in the project's YAML localization string tables (`l10n.ParseYAML`), reporting missing IDs with file and line. `tooling/refs` (`game mv` and `game index`) tracks `scene`, project-relative video `source` and timeline audio `source` paths in `*.cutscene.yaml` files so moving a scene or audio asset rewrites cutscene references in place. ## Playing a video cutscene Make one `Player` for the game and mount its `View` over the game's view, as the last child of the view that holds the canvas: ```go loop := &game.Loop{Update: update, Draw: draw} loop.Run(cx) mixer := sound.NewMixer(cx, "sound") player := cutscene.NewPlayer(cx, cutscene.Options{Loop: loop, Mixer: mixer}) return core.View{Class: "flex-1", Children: []core.Node{ core.Canvas{Class: "flex-1" /* ... */}, player.View(), }} ``` `View` shows nothing while no cutscene plays. `player.Play(c, done)` plays one, from a game's `Update` or anywhere else on the engine's goroutine: ```go if bossDoorOpened { player.Play(bossIntro, func(r cutscene.Result) { startBossFight() }) } ``` While it plays: - `Options.Loop` is paused (`Loop.SetPaused`), so `Update` stops and `Draw` goes on under the video. When the cutscene ends the loop is set back as it was, so one the game had paused stays paused. - `Options.Mixer` is suspended (`Mixer.Suspend`, see [sound](http://nsgo.games/docs/sound/)): effects stop and music pauses, then plays on from there. - The display is kept awake, and the video pauses while the app is in the background and plays on as it returns. `done` receives a `Result`: its `Reason` (`Finished`, `Skipped`, `Stopped` or `Failed`), the `Position` the video reached as the platform last reported it, and for `Failed` the platform's `*core.MediaError` in `Err`. The loop and the mixer are back by the time `done` runs, so it can switch scenes or play the next cutscene. `Play` returns an error, and plays nothing, for a cutscene with no source, an unknown fit or a negative `skipAfter`; playing a cutscene while another plays stops the first, whose `done` is told `Stopped`. If that `done` plays a cutscene of its own, that one plays instead, and `Play` returns `cutscene.ErrReplaced`, playing nothing and never calling its own `done`. `Stop` ends the one playing, skippable or not. Disposing the player's scope stops a cutscene without calling `done`, and still sets the loop and the mixer back. ## Between scenes `player.Scene(c, done)` makes a cutscene a [scene](http://nsgo.games/docs/scene/) of its own: it plays as the scene enters, and `done` switches on from it. ```go intro, err := player.Scene(c, func(cutscene.Result) { scenes.Switch(level1, scene.Crossfade(500*time.Millisecond)) }) if err != nil { return err } scenes.Switch(intro, nil) ``` Leaving the scene some other way before the cutscene ends stops it without calling `done`. That holds when switching from one cutscene scene to another of the same player with a transition too, although the new scene enters before the old one exits. ## Skipping A `skippable` cutscene is skipped, once it has played to `skipAfter`, by: - a press on the video; - a skip key, `Enter` or `Space` unless `Options.SkipKeys` names others (an empty slice for none); - back: `Escape`, the back button or gesture, or the browser's back; - `player.Skip()`, for a game that reads its own input. Back is taken while any cutscene plays, so it does not navigate the game away under the video; on one that cannot be skipped it does nothing. `player.CanSkip()` reports whether a skip works now and, read in a view, updates it as that changes, so a game can show its own skip prompt over the video: ```go core.Show{When: player.CanSkip, Then: func(*core.Scope) core.Node { return core.Text{Class: "absolute bottom-6 right-6 text-white", Content: "Skip ›"} }} ``` When the platform pauses the video itself, for a call or headphones unplugged, a press or a skip key plays it on rather than skipping it. It stays paused until then, also when the window loses or regains focus; only returning from the background plays it on by itself. ## Audio routing The platform's player decodes the video and plays its sound, which does not go through the game's mixer: - The mixer's master volume times the cutscene's `group` volume sets how loud the video plays, and follows a settings menu as it changes; a volume of 0 mutes it. - The mixer's bus effects (`EffectChain`) and anything else that processes samples do not apply to it. - Nothing the game draws can go between the video's picture and the screen; only NSGo views over `player.View()` show on top of it. Drawing decoded frames into the game, with the sound in the mixer, needs a frame-decoding API NSGo does not have yet. ## Testing with nsgotest `nsgotest` reports what a platform's player would: `app.Play` loads the video, `app.Progress` plays it to a position (and to its end at its duration), `app.PauseVideo` and `app.PlayVideo` pause and play it as the platform does, and `app.Report` sends an `EventError`. The video's test ID is `cutscene`, or `Options.TestID`. ```go app.Play("id:cutscene", core.VideoInfo{Duration: 3 * time.Second}) app.Progress("id:cutscene", 3*time.Second, 3*time.Second) // done gets Finished ``` ## Captions for dialogue `cutscene.NewCaptionBridge(player, captions)` mirrors the timeline's active dialogue line into an `a11y.CaptionTrack`, so cutscene lines get the player's caption settings in `CaptionsView`. Call its `Update` after `Player.Step` on each fixed update. It shows each line once with its speaker, and dismisses the caption when the dialogue clip ends or the next line replaces it, so the caption lasts as long as the clip and a replayed line shows again. --- Source: http://nsgo.games/docs/datatable/ # datatable `game/datatable` loads typed game data, such as enemies, items, levels and quests, into slices of your own Go struct, and reloads it while the game runs when a designer saves the file. Tables are YAML, so designers and AI tools edit them directly and every change reads as a line in review; CSV and JSON exports from spreadsheets and other tools load too. ```go import "github.com/nsgo-dev/game/pkg/datatable" ``` ## A table and its type A row type is a struct. Each field is a column named by its `table` tag, else its `json` tag, else its Go field name; a tag of `-` leaves the field out. Fields can be strings, bools, integers, unsigned integers, floats, `time.Duration`, pointers to these (absent or `null` leaves the pointer nil) and slices of them. ```go type Enemy struct { ID string `table:"id,key"` Name string `table:"name"` HP int `table:"hp"` Speed float64 `table:"speed"` Boss bool `table:"boss"` Tags []string `table:"tags"` Cooldown time.Duration `table:"cooldown"` } ``` The YAML file is a mapping with a `version`, which is `datatable.FormatVersion` (1), and a `rows` list. Each row is a mapping from column names to values; a column a row leaves out keeps its zero value. ```yaml version: 1 rows: - id: goblin name: Cave Goblin hp: 45 speed: 3.5 boss: false tags: [melee, scout] cooldown: 500ms - id: dragon name: Ancient Wyrm hp: 1200 speed: 6.25 boss: true tags: [flying, fire, boss] cooldown: 2s ``` `LoadFile[T](path)` picks the reader by extension (`.yaml`, `.yml`, `.csv` or `.json`); `LoadYAML[T](name, data)` reads bytes you already have, such as an embedded file. ```go enemies, err := datatable.LoadFile[Enemy]("data/enemies.yaml") ``` Add `,key` to designate one string or integer column as the primary key. YAML, CSV, and JSON readers report duplicate keys with the offending cell and the first row that used the key. Unknown options in a `table` tag are an error. A loaded `Table[Enemy]` can find an enemy with `table.Get("goblin")`. The argument uses the key field's exact Go type. For several reads from the same generation, use `table.View().Get("goblin")`. ## What a YAML table refuses A YAML table is strict, so a typo is an error at load time rather than a silently missing value: - a missing `version`, a version other than 1, or a top-level key other than `version` and `rows`; - a bare list of rows without the `version`/`rows` mapping, or a second YAML document after `---`; - a row key that names no column (`datatable.ErrUnknownField`), including a field tagged `-`; - a column set twice in one row, for example as `hp` and `HP` (`datatable.ErrDuplicateField`); - a merge key (`<<: *defaults`): anchors and aliases load, but each row spells out its own columns; - a value the field's type cannot hold, such as `speed: fast` or an `int8` of 300. Errors inside a row are a `*datatable.CellError` with the file, the 1-based row, the column and the value: ```go var ce *datatable.CellError if errors.As(err, &ce) { log.Printf("%s row %d, %s = %q: %v", ce.File, ce.Row, ce.Field, ce.Value, ce.Err) } ``` Column names match exactly first and then without regard to case, so `Armor` and `armor` both fill a field named `Armor`. CSV and JSON stay as their tools export them: they have no version, and columns the type does not have are skipped. ## Saving a table `MarshalYAML(rows)` and `SaveYAML(path, rows)` write the same format, for an editor or a script that generates data. The output is deterministic: `version` first, then every column of every row in struct declaration order, two-space indentation, lists inline, strings quoted only where YAML needs it, a nil pointer as `null` and a duration in its `String` form. A file saved by `SaveYAML`, loaded and saved again is byte for byte the same. A nil list and an empty list are both written as `[]`. Non-finite floats and field types the loader cannot read (maps, structs, interfaces) are an error. Every column has one field: a row type in which two fields share a column name, such as two fields tagged `hp` or an embedded struct's `name` and the outer struct's own `name`, is refused by both `LoadYAML` and `MarshalYAML`, because only one of the two could be written or read back. Give each field its own tag, or tag one of them `-`. ```go if err := datatable.SaveYAML("data/enemies.yaml", enemies); err != nil { return err } ``` ## Untyped editing and row-type validation Tools and editors that work on YAML data tables without importing every game's Go row struct can open a file as an untyped `*datatable.Document` with `ParseDocument` or `LoadDocument`: - Each `Row` stores an ordered slice of `Cell{Key, Value}` entries so per-row key order is preserved, `Columns()` returns the union of row keys in first-appearance order, and `ColumnKind(col)` infers `KindString`, `KindNumber`, `KindBool`, `KindDuration`, or `KindList`. - `Marshal` and `Save` return the exact input bytes when no edits were made, patch only the edited line when a single scalar or inline-list cell changes, and encode deterministically from the preserved YAML AST after structural edits (`AddRow`, `DeleteRow`, `MoveRow`). - `RowTypeFor[T]()` and `Registry` (`RegisterRowType[T](reg, pattern)`) validate untyped cells, rows, and documents against Go struct types with `LoadYAML`'s exact rules (`ValidateCell`, `ValidateRow`, `ValidateDocument`, `ParseCellText`), refusing unknown fields, duplicate fields, and type-conversion failures with `*datatable.CellError`. The registry can also check files directly. `reg.CheckFS(os.DirFS(projectDir))` reads the `.yaml` and `.yml` files matched by the registered patterns and returns the first problem per file, in filesystem walk order. Each problem carries the file path relative to the supplied directory, the 1-based line and column when known, and a message. Pass the registry to [the project editor command](http://nsgo.games/docs/editor/) through `editorcmd.Options.DataTables` to run the same checks with `game check`. ## Hot reload `NewTable[T](path)` loads the file and holds its rows. `datatablewatch.Watch` (in `game/datatable/datatablewatch`) registers it with a `hotreload.Watcher` (from `game/tooling/hotreload`) and calls back on the engine goroutine with the new rows after each valid save. `datatable` itself imports no NSGo package, so a dedicated server loads tables with it headlessly; only the game client links the watcher: ```go func Game(cx *core.Scope) core.Node { enemies, err := datatable.NewTable[Enemy]("data/enemies.yaml") if err != nil { panic(err) } w := hotreload.NewWatcher(cx, "data") datatablewatch.WatchWithError(enemies, w, func(rows []Enemy, err error) { if err != nil { log.Printf("enemies.yaml: %v", err) // rows are still the last valid ones return } spawner.SetEnemies(rows) }) // ... } ``` An edit that does not load, such as a misspelt column, keeps the previous rows, leaves `Version` unchanged and records the error in `LastError`; the next valid save replaces the rows and increases `Version`. `Rows` returns a copy, so callers cannot change the table's rows. In release builds (`-tags release`) the watcher is a no-op and the table keeps the rows it loaded at start. ## Immutable views `Table.View` returns a `View` holding the table's current rows and the `Version` they were loaded as, read together under one lock, so the two always come from the same load. `View.Rows` returns the table's own slice without copying it, so a caller reading rows every tick allocates nothing; the slice and its rows are read-only, and changing them changes what every other holder of the view sees. A reload publishes a new slice and leaves an existing `View` unchanged, so a server pins a `View` when a match starts, records its `Version` with the match or replay, and new matches pick up the reloaded rows. `Rows` still returns a copy. ## Reloading a set of tables Register each file and row type with `datatable.RegisterTable[T](set, name, path)`, then call `set.Reload()` to load them together. If a file cannot load or the validation function supplied to `NewSet` rejects the candidate, `Current()` keeps the previous snapshot. Use the validator to check relationships between tables before they become visible. `Current()` returns the latest snapshot or nil before the first successful load. Keep that snapshot for the duration of a match. Read its shared rows with `datatable.Rows[T](snapshot, name)` or find one row with `datatable.Lookup[T](snapshot, name, key)`. Treat the rows and nested values as read-only. A later reload advances `snapshot.Version()` on the new publication and leaves existing snapshots intact. [Server matches](http://nsgo.games/docs/gameserver/#data-tables). Declare a cross-table reference with `table:"boss,ref=monsters"`. Register the target under that name and mark one of its columns with `,key`. The source field may contain a scalar or a slice whose element type matches the target key's Go type. Set reloading checks every reference before publication. A missing key reports its file, row and column name and leaves the previous snapshot available. --- Source: http://nsgo.games/docs/determinism/ # Determinism A deterministic simulation produces the exact same state from the same starting seed and inputs on every run, across macOS, iOS, Windows, Linux, Android and the web. Determinism makes replays, seeded daily runs, save/load continuity and automated gameplay tests under `nsgotest` reliable instead of flaky. This guide describes the rules that keep an NSGo game deterministic and how to verify them with `pkg/random`. ## 1. Advance time only with `game.Loop`'s fixed `dt` Move simulation state exclusively inside `game.Loop.Update(dt)` using the fixed step `dt` (or an integer tick counter). Never read `time.Now()`, `time.Since`, or frame-to-frame display intervals inside simulation logic. ```go loop := &game.Loop{ Rate: 60, Update: func(dt time.Duration) { sim.Tick++ sim.Step(dt) // dt is always 1/60s }, Draw: func(alpha float64) { // Interpolate visuals only; never mutate simulation state here. render(sim.Prev, sim.Curr, alpha) }, } ``` - `Draw(alpha)` runs at the display's refresh rate and must be read-only with respect to gameplay state. - Count cooldowns and timers in integer ticks or exact multiples of `dt` rather than wall-clock deadlines. ## 2. Use seeded `random.Stream` per purpose Never call Go's global `math/rand` or `math/rand/v2` inside simulation code. Global generators share hidden mutable state across subsystems, and standard library helpers can change algorithms across Go releases. Import `github.com/nsgo-dev/game/pkg/random` instead: ```go import "github.com/nsgo-dev/game/pkg/random" streams := random.NewStreams(masterSeed) ai := streams.Stream("ai") loot := streams.Stream("loot") particles := streams.Stream("particles") ``` - Every `Stream` runs a self-contained SplitMix64 + Xoshiro256\*\* generator with fixed rejection sampling (`Intn`, `IntRange`, `Float64`, `Float32`, `Range`, `Range32`, `Bool`, `Chance`, `Pick`, `WeightedIndex`, `Shuffle`). The output sequence is bit-for-bit identical across Go versions, operating systems and CPU architectures (32-bit, 64-bit, ARM64, x64 and WebAssembly). - Beyond uniform draws, `Normal(mean, stddev)` draws from a normal distribution as a fixed 12-draw Irwin-Hall sum, and `InCircle(r)`, `OnCircle()` and `InRect(x, y, w, h)` return uniformly distributed 2D points inside a circle, on the unit circle (a random direction) and inside a rectangle. They deliberately avoid `math.Sin`, `math.Cos`, `math.Log` and `math.Exp` (which round differently across architectures), so their results are bit-for-bit identical everywhere too. - Forking by purpose (`root.Fork("loot")`, `root.Fork("level-1").Fork("spawns")`, or `streams.Stream("loot")`) derives independent child streams without advancing the parent or perturbing siblings. Adding particle effects or reordering stream creation will not change enemy AI or loot drops. - Keep cosmetic randomness (particles, camera shake, sound pitch variation) on its own stream so visual tweaks never alter gameplay. ## 3. Never depend on Go map iteration order Go intentionally randomizes `for k, v := range m` iteration order. Iterating a map directly in order-sensitive gameplay code—such as applying damage, resolving collisions, spawning waves or drawing from a `random.Stream`—causes runs to diverge. - Prefer slices ordered by creation or stable entity ID for anything `Update` iterates over. - When you must iterate a map, sort its keys first: ```go for _, id := range slices.Sorted(maps.Keys(enemies)) { enemies[id].Update(dt, ai) } ``` ## 4. Keep simulation single-threaded and order-independent of goroutines Run all simulation mutations sequentially on the engine's goroutine inside `Loop.Update`. - Do not let multiple goroutines mutate game state or draw from the same `random.Stream`. - Do not make gameplay decisions from `select` over multiple ready channels, because Go chooses among ready cases pseudo-randomly. - If background work (such as pathfinding or procedural chunk generation) runs off-thread, deliver its result at a deterministic tick boundary and apply queued results sorted by a canonical key rather than arrival order. ## 5. Keep floating-point evaluation order consistent (and prevent arm64 FMA drift) IEEE-754 floating-point addition and multiplication are not associative: `(a + b) + c` can differ in the last bit from `a + (b + c)`. On arm64, Go's compiler is also allowed by the language specification to contract `a*b + c` into a single fused multiply-add instruction (`FMADD`/`FMSUB`) with only one rounding instead of two, whereas amd64 executes separate multiply and add instructions. Over hundreds of ticks, even a 1-ULP difference between arm64 and amd64 can cross a collision or branch threshold and cascade. - Accumulate forces, velocities and scores in a fixed, deterministic entity order. - In custom simulation code that must match bit-for-bit across amd64 and arm64, wrap multiply-add products in an explicit conversion (`float32(a*b) + c` or `float64(a*b) + c`), which the Go specification guarantees forbids FMA contraction, and avoid standard library transcendentals (`math.Sin`, `math.Cos`, `math.Atan2`, `math.Hypot`) whose arm64 implementations emit FMA, and `math.Pow`, `math.Exp` and `math.Log`, which take different code on each architecture (`math.Exp` has its own assembly on amd64 and on arm64, `math.Log` is assembly on amd64 only) and round differently. - `pkg/physics`, `pkg/physics3d`, and `pkg/vehicle3d` already eliminate arm64 FMA instructions across their stepped simulation paths and verify cross-architecture golden trajectory hashes in CI on both Ubuntu amd64 and macOS arm64. In `pkg/physics` that covers the rigid world, the XPBD `SoftWorld`, the character controller and tile collision, and on arm64 its tests also disassemble the package with `go tool objdump` and fail on any `FMADD`, `FMSUB`, `FNMADD` or `FNMSUB` outside the debug drawing code. - Avoid mixing `float32` and `float64` inconsistently across code paths. - Use integer ticks or fixed-point values for exact counters, timers, grids and resource totals. ## 6. Save and restore PRNG and physics state for saves, replays, and rollback A `Stream`'s full state (its seed and 256-bit generator words) can be snapshotted with `State()` and restored with `SetState(state)`. `State` marshals cleanly with `encoding/json`, so a saved game resumes the exact same future random sequence after reload: ```go // Save data, err := json.Marshal(streams.States()) // Load var saved map[string]random.State if err := json.Unmarshal(data, &saved); err == nil { streams.Restore(saved) } ``` For a single stream, use `s.State()` and `s.SetState(state)`. Call `s.Reset()` or `streams.Reset()` to rewind to the start of a seed for replays or level restarts. For physics worlds, `physics.World`, `physics.RigidWorld`, `physics3d.World`, and `vehicle3d.Vehicle` all provide `Save()`, `Restore(snap)`, and `Checksum()` capturing every piece of private solver state (warm-start impulse caches, sleep timers, previous poses, active contact/trigger pair sets, and joint state). Snapshots marshal cleanly to plain-text JSON and pair directly with `netplay.RollbackSession` (`netplay.SimState`): ```go // Inside a netplay.SimState implementation: func (s *MatchSim) Save() []byte { data, _ := json.Marshal(s.world.Save()) return data } func (s *MatchSim) Load(b []byte) error { var snap physics3d.WorldSnapshot if err := json.Unmarshal(b, &snap); err != nil { return err } return s.world.Restore(snap) } func (s *MatchSim) Checksum() uint64 { return s.world.Checksum() } ``` ## 7. Verify determinism in tests under `nsgotest` The `random` package includes test helpers that execute a simulation multiple times from scratch and fail if any run diverges. Use `AssertDeterministic` to check a full run, including a real `game.Loop` driven by `nsgotest`: ```go func TestMain(m *testing.M) { nsgotest.Main(m) } func TestSimulationIsDeterministic(t *testing.T) { random.AssertDeterministic(t, 4, func() WorldSnapshot { streams := random.NewStreams(42) world := NewWorld(streams) loop := &game.Loop{ Rate: 60, Update: func(dt time.Duration) { world.Step(dt) }, } app := nsgotest.Start(t, func(cx *core.Scope) core.Node { loop.Run(cx) return core.View{} }) app.Advance(2 * time.Second) return world.Snapshot() }) } ``` When a multi-step simulation diverges, use `CheckSteps` or `AssertDeterministicSteps` to pinpoint the exact first step where two runs differ and inspect both states: ```go func TestStepByStepDeterminism(t *testing.T) { random.AssertDeterministicSteps(t, 300, func() func(step int) WorldSnapshot { world := NewWorld(random.NewStreams(42)) dt := time.Second / 60 return func(step int) WorldSnapshot { world.Step(dt) return world.Snapshot() } }, nil) } ``` Run the suite with: ```sh go tool nsgo test ./... ``` If `AssertDeterministicSteps` fails, it reports the first divergent step index along with both states (`run A` and `run B`), letting you narrow the cause directly to the tick that introduced nondeterminism. --- Source: http://nsgo.games/docs/dialogue/ # dialogue `game/dialogue` runs branching conversations written as [Yarn Spinner](https://www.yarnspinner.dev/) scripts. `ParseYarn` reads a script of titled nodes into a `Script`, and a `Runner` steps through it one line or choice menu at a time, keeps its variables and node visit counts, and hands each `<>` to the game. [vn](http://nsgo.games/docs/vn/) presents a script as a visual novel on top of a `Runner`. ```go import "github.com/nsgo-dev/game/pkg/dialogue" ``` Nothing in `dialogue` reads the wall clock, spawns goroutines or keeps package-level state: a `Runner` moves only when the game calls it, so a conversation plays the same every time and under `nsgotest`. ## Scripts A script is plain text, usually a `.yarn` file next to the game's other assets. Each node has a `title:` header (and any other `key: value` headers) above `---`, and its body ends at `===`: ```yarn title: Shop --- <> Merchant: You have {$gold} gold. #line:shop_01 -> Buy a potion (10 gold) <= 10>> <> <> Merchant: Here you go. -> Leave <> === title: Farewell --- Merchant: Come back soon. === ``` `ParseYarn` reads: - Comments starting with `//`. - Lines, `Speaker: Text` or narration without a speaker, with `{expr}` interpolation, an optional `#line:` and any other `#tags`. - Choices, `-> Option text`, each with an optional `<>` guard, `#line:` and tags, and an indented body. - Conditionals: `<>`, `<>`, `<>` and `<>`. - Variables: `<>` (or `to`, `+=`, `-=`, `*=`, `/=`) and `<>`, which sets a variable only when it is unset. - `<>` and `<>`. - Game commands, `<>`, for any other name. Expressions take numbers, strings, `true` and `false`, `$variables`, the arithmetic operators, comparisons (`==` or `is`, `!=`, `<`, `<=`, `>`, `>=`), `and`/`&&`, `or`/`||`, `not`/`!`, and `visited("Node")` and `visited_count("Node")`. Its errors are `*loaderr.Error` values with the line at fault and how to fix it; name the file with `loaderr.WithFile` when the script came from one (see [Errors](http://nsgo.games/docs/errors/)). A parsed `Script` never changes, so many runners can share it; `Nodes`, `HasNode` and `NodeHeaders` list what it holds. ## Running a script ```go script, err := dialogue.ParseYarn(src) if err != nil { return err } r := dialogue.NewRunner(script, dialogue.Options{ OnCommand: func(e dialogue.Event) { runCommand(e.Command, e.Args) }, }) step, err := r.Start("Shop") for err == nil && step.Kind != dialogue.StepEnded { switch step.Kind { case dialogue.StepLine: show(step.Line.Speaker, step.Line.Text) step, err = r.Continue() case dialogue.StepChoices: step, err = r.Choose(pick(step.Choices)) } } ``` - `Start`, `Continue` and `Choose` each run the script up to the next line (`StepLine`), choice menu (`StepChoices`) or end (`StepEnded`) and return it as a `Step`. - A `Choice` has `Available` false when its `<>` guard failed: show it greyed out or hide it. `Choose` on it returns `ErrChoiceUnavailable`; `Continue` while a menu waits returns `ErrChoiceRequired`. - `Start` on a node the script lacks, or a `<>` to one, returns `ErrUnknownNode`. `Options.MaxStepsPerContinue` (default `DefaultMaxStepsPerContinue`, 1024) bounds the statements one call runs, so a `<>` loop returns `ErrStepLimitExceeded` instead of hanging. - `SetVar`, `Var` and `Vars` read and write variables from Go, with or without the leading `$`; Go numbers become `float64`, as in Yarn. `Visited` gives how often a node was entered and `CurrentNode` the node running now. ## Commands Every `<>` that is not part of Yarn's syntax becomes an `Event` with the command's name, its arguments (variables and `{expr}` already evaluated) and the node it ran in. A runner passes it to `Options.OnCommand`, and publishes it on `Options.Bus`, a [flow](http://nsgo.games/docs/flow/) `Bus`, so other systems can subscribe to it with `flow.Subscribe`: ```go var bus flow.Bus flow.Subscribe(&bus, func(e dialogue.Event) { if e.Command == "give_item" { inventory.Add(e.Args[0], 1) } }) r := dialogue.NewRunner(script, dialogue.Options{Bus: &bus}) ``` ## Localization A line's or choice's `#line:` tag is its key in a string table. With `Options.StringResolver` set, a runner calls it with the id, the script's own text as the fallback and a copy of the variables, then interpolates any `{expr}` left in the returned text, so a translation can move a placeholder. The resolver usually looks the id up in an [l10n](http://nsgo.games/docs/l10n/) string table and returns the fallback when the table has no entry. ## Shared variables With `Options.Vars` set to a [flow](http://nsgo.games/docs/flow/) `Vars` store loaded from `vars.yaml`, a runner reads and writes that store instead of a variable map of its own, so other runners and the rest of the game see every `<>` at once. `<>` or `<>` of a name the store does not declare returns an error wrapping `flow.ErrUndeclaredVar`, a `<>` of a declared name keeps the store's value, and assignments keep the declared kind and range. `Script.VarRefs` lists every variable a script reads or writes with its line, which `go tool game check` compares against `vars.yaml`. ## Saving `State` returns a runner's variables and node visit counts as a `State`, which marshals to JSON for a [save](http://nsgo.games/docs/save/) slot; `LoadState` restores it into a runner made from the same script. Start the runner at the node to resume from after loading. --- Source: http://nsgo.games/docs/economy/ # Economy `pkg/online/economy` is the provider-neutral wallet core for server-owned balances. It validates versioned currency definitions, applies caps, rejects insufficient spends, and makes grants, spends and exchanges idempotent with caller-supplied keys. Wrap it in a records-backed transaction and expose it through a service that authorizes player reads/spends separately from server grants. Amounts must be positive (`ErrInvalidAmount` otherwise). Replaying an idempotency key with the same operation, currency and amount returns the first result without changing anything; reusing it for a different change is `ErrDuplicateKey`. A grant past a currency's cap or past the largest `int64` is `ErrCapExceeded`. --- Source: http://nsgo.games/docs/editor/ # Editor & Scene Format This document records the scope decision for NSGo's game editor ([#159](https://github.com/nsgo-dev/game/issues/159)) and specifies the version 1 YAML scene format ([#160](https://github.com/nsgo-dev/game/issues/160)) implemented in `github.com/nsgo-dev/game/pkg/sceneformat`. Prebuilt desktop installers for **NSGo Game Editor** (`cmd/editor`)—signed and notarized `.dmg` images for macOS (`arm64` / `x64`), `-setup.exe` installers for Windows (`x64` / `arm64`), and `.deb` / `.pkg.tar.gz` / `.AppImage` packages for Linux (`x64` / `arm64`)—are published on [GitHub Releases](https://github.com/nsgo-dev/game/releases/latest), alongside one-line installers (`install.sh` / `install.ps1`). The standalone editor requires **Go 1.27 or later** ([go.dev/dl](https://go.dev/dl/)) to create projects, play games, run checks, and build exports; when opened from Finder, the Dock, Spotlight, or a desktop launcher, it resolves `go` from `PATH`, standard install locations (`/usr/local/go/bin`, `C:\Program Files\Go\bin`), Homebrew, version-manager shims, and your login shell's `PATH`. You can also launch the editor directly via `go tool game editor` or `go run ./cmd/editor`. ## Editor Scope Decision (#159) NSGo takes **option (b) growing into (c)**: keep Go code and Tiled first-class, define a clean human-editable YAML scene format shared by hand-authored scenes and tooling, and build a lightweight NSGo-native scene editor on top of it. ### Why this scope - **Code and Tiled stay first-class.** A game written purely in Go—or authored with Tiled `.tmj` maps and TexturePacker/Aseprite atlases—never has to go through an editor. `sceneformat` is an ordinary library package with zero runtime lock-in. - **One text format, readable diffs.** Scenes are plain versioned YAML (`version: 1`) with deterministic 2-space encoding. Hand-editing a scene in a text editor and saving it from a visual editor produce the same diff-friendly structure. - **Dogfooding NSGo.** Rather than wrapping a third-party desktop shell or building a monolithic IDE, the lightweight scene editor is an NSGo app built with NSGo's own `ui` views and `Canvas`. Every improvement to inspectors, tree views, shortcuts, or canvas tooling benefits NSGo itself. ### Planned lightweight editor capabilities The NSGo-native editor operates directly on `sceneformat.SceneDoc` files and focuses on the workflows where visual feedback beats hand-editing coordinates: 1. **Object placement & transforms**: place, drag, rotate, scale, flip and Z-order objects across world and screen layers. 2. **Tile painting**: paint inline tile grids, and the tile layers of layered grids with flipped tiles, or preview referenced Tiled `.tmj` and LDtk `.ldtk` maps. 3. **Typed property & component editing**: inspect and edit `components` and `properties` with validation against the scene schema. 4. **Undo / redo**: command-based editing history over scene documents. 5. **Play-in-editor**: run the live `game.Loop` and `BuiltScene` directly inside the editor's `Canvas` without leaving the tool. 6. **Asset browsing**: browse project atlases, frames, animations and tilemaps and drag them into layers. Out of scope for the initial editor: custom scripting languages, bespoke shader/material graphs, and proprietary binary project formats. --- ## Scene Format (`version: 4`) (#160) ```go import "github.com/nsgo-dev/game/pkg/sceneformat" ``` ### Top-level fields | Field | Type | Description | | --- | --- | --- | | `version` | `int` | Required schema version: `4` (`CurrentVersion`), `3` for a scene using version 3 parallax/repeat layers without version 4 3D lights/environment/cameras, `2` for version 2 features without version 3/4 fields, or `1` for none of the fields added in versions 2–4. `Encode` writes it back unchanged. | | `uid` | `string` | Optional stable ID that stays the same when the file is renamed or moved, written by `go tool game index` (all versions; see [Stable references](http://nsgo.games/docs/project/#stable-references)). `Resolve` keeps the scene's own uid, not its base's. | | `inherits` | `string` | Optional slash-separated path from the project root to a base scene this one inherits (version 2+, see Instancing and inheritance below). | | `name` | `string` | Optional human-readable scene name. | | `navMesh` | `string` | Optional slash-separated path from the project root to the scene's baked [navigation mesh file](http://nsgo.games/docs/navbake3d/), which `go tool game navmesh` writes (all versions). In a scene that inherits another, it replaces the base's. | | `virtualWidth`, `virtualHeight` | `float32` | Virtual viewport size in points. Must both be `0` or both positive. | | `backgroundColor` | `string` | Optional CSS color string parsed by `core.ParseColor` (for example `"#141824"`). Filled over `(0, 0, virtualWidth, virtualHeight)` before layers draw. | | `ambientColor` | `string` | Optional CSS color string parsed by `core.ParseColor` (for example `"rgba(12, 16, 30, 0.85)"`). Sets the ambient darkness tint of the scene's 2D lighting pass (`lights2d.Scene.Ambient`, both versions). | | `camera` | object | Optional default 2D camera for world-space layers (`x`, `y`, `zoom`, `rotation`, optional `bounds`). | | `environment` | object | Optional 3D scene environment (version 4): `sky` (`kind`: `color`, `gradient`, or `hdr` with `color` / `zenith`, `horizon`, `ground` / `hdr` path), `ambientColor`, `ambientIntensity`, `iblIntensity`, `fog` (`mode`: `off`, `linear`, `exp`, `exp2`; `color`, `start`, `end`, `density`, `maxOpacity`, height fog `heightEnabled`, `heightBase`, `heightFalloff`, `heightDensity`), `tonemapping` (`none`, `reinhard`, `aces`, `neutral`, `agx`), and `exposure`. | | `tilemaps` | map | Optional named tilemaps referenced from layers via `tilemap.ref`. | | `layerOverrides` | map | Changes to inherited layers by name: `space`, `order`, `visible`, `tilemap` (version 2+), plus `parallaxX`, `parallaxY`, `repeatX`, `repeatY`, `repeatWidth`, `repeatHeight` (version 3, requires `inherits`). | | `overrides` | map | Changes to inherited objects by ID (version 2+, requires `inherits`). | | `layers` | list | Ordered list of layers drawn lowest `order` first, preserving document order on ties. | | `connections` | list | Optional connections from one object's events to another object's handlers, written after the layers (all versions, see [Connections](http://nsgo.games/docs/editor/#connections-490)). | ### Camera - `x`, `y`: world coordinates placed at the center of the virtual viewport `(virtualWidth/2, virtualHeight/2)` (or `(0, 0)` when virtual dimensions are `0`). - `zoom`: positive zoom factor; defaults to `1` when omitted. - `rotation`: camera rotation in radians (clockwise on screen); world layers rotate by `-rotation` around `(x, y)`. - `bounds`: optional `{x, y, width, height}` world rectangle clamping the visible area (`width > 0`, `height > 0`). - When `camera` is omitted, world layers draw with the identity transform. ### Tilemaps A tilemap entry (in top-level `tilemaps` or inline on a layer) uses exactly one mode: - **Reference** (`ref`, layers only): names an entry in top-level `tilemaps`. - **External map** (`source`): a slash-separated path from the project root to a Tiled map (`.tmj` or `.tmx`) or an LDtk project (`.ldtk`); for LDtk, `level` names the level to build (version 2), and without it the project's first level is built. - **Inline grid**: `tileWidth`, `tileHeight`, `width`, `height`, either `tileset` (atlas name whose frames are keyed `"1"`, `"2"`, …) or `tilesetFile` (version 2+, path of a YAML tileset `*.tileset.yaml`), optional `offsetX` / `offsetY` (version 3, shifting cell `(0, 0)` in layer points), and row-major `data` of length `width * height` (`0` is an empty tile; when using `tilesetFile`, ID `n` places local tile `n - 1`). - **Layered grid** (version 2): `tileWidth`, `tileHeight`, `width`, `height`, optional `offsetX` / `offsetY` (version 3), `tilesetFile`, the path of a YAML tileset (`*.tileset.yaml`, see [YAML tilesets](http://nsgo.games/docs/tilemap/#yaml-tilesets)) whose tiles the cells place, and `tileLayers`, up to `MaxTileLayers` named layers drawn in order. The tileset of a layered grid defines each tile once, with its flags, properties, collision shapes, animation and terrain, so the map only places tiles. Each tile layer has a `name`, optional `visible` (default `true`) and `opacity` (default `1`), and `rows`: `height` rows from the top, each `width` cells separated by spaces. A cell is `.` when empty, or the tile's local ID in the tileset (`0`, `1`, …) followed by any of `h`, `v` and `d` to flip it horizontally, vertically or across its diagonal, as Tiled's flip bits do, so `3hv` is tile 3 turned half a turn. A row may align its cells with extra spaces and write the letters in any order; `Encode` writes single spaces and the order `h`, `v`, `d`, so each row is one line in a diff. ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/scene.v2.json version: 2 name: Cave virtualWidth: 320 virtualHeight: 180 layers: - name: ground tilemap: tileWidth: 16 tileHeight: 16 width: 4 height: 2 tilesetFile: tilesets/cave.tileset.yaml tileLayers: - name: floor rows: - 0 0 0 0 - . . 1h 3hvd - name: deco opacity: 0.5 rows: - 2 . . . - . . . . ``` `TileLayerDoc.Cell`, `SetCell` and `Cells` read and write a layer's cells as tile values, the GIDs they have once built: `0` for an empty cell, otherwise the local ID plus 1 with `tilemap.FlipHorizontal`, `FlipVertical` and `FlipDiagonal` set; `ParseTileRow` and `FormatTileRow` do the same for one row. `Build` turns a single grid of atlas frames into a sprite batch (`BuiltLayer.Tilemap`), and a layered grid, an inline grid with `tilesetFile`, or an external map into a `tilemap.Tilemap` (`BuiltLayer.Map`). The map carries the tileset's flags, properties, shapes, animations and terrains, so in the layer's coordinates it answers `FlagsAt`, `TileProperties`, `TilesInRect` and `Raycast`, collides directly with `physics.MoveAndSlide`, and serves `tileshape.New` for slopes and occluders. `BuiltScene.Draw` draws only the map tiles inside the virtual viewport, seen through the camera for a world-space layer, unless the scene has no virtual size or `DrawAllTiles` is set, as the editor sets it for its edit view; `BuiltScene.Update(dt)` advances animated tiles. `Build` reads YAML tilesets, Tiled maps with their external tilesets and LDtk projects through the resolver's `FileResolver` (`ReadFile`), with paths in a Tiled or LDtk file taken from that file's directory, and loads their images through an `ImageResolver` (`Image`) when the resolver has one, or names them by path (`core.ImageSource{URI: path}`) otherwise. `FSAssets` reads a project's files from an `fs.FS`, so a scene that names a `.tmj`, `.ldtk` or `.tileset.yaml` builds with no resolver of the game's own. A resolver that implements `TilemapResolver` still loads every `source` itself into a `TilemapDoc`, as before, except a source that names an LDtk `level`: `Tilemap(source)` cannot receive the level, so `Build` reads that one through the `FileResolver`. ### Layers and Objects Each layer has: - `name` (required, unique within the scene) - `space`: `"world"` (default when omitted, draws under camera) or `"screen"` (draws in canvas coordinates, ignoring camera) - `order`: integer draw order (lowest first) - `visible`: boolean, defaults to `true` when omitted - `parallaxX`, `parallaxY` (version 3): optional finite scroll factors applied to the camera position on `"world"` layers, matching `scene.Layer`; omitted defaults to `1`, `0` pins the layer against camera translation, `0.5` scrolls at half speed, and values above `1` scroll faster for foregrounds. `layerOverrides` can override them on inherited scenes. - `repeatX`, `repeatY` (version 3): optional booleans that tile a `"world"` layer seamlessly across the camera's visible region using `repeatWidth` / `repeatHeight` (non-negative layer points; `0` falls back to the layer's tilemap pixel size, then the scene's virtual viewport size). `layerOverrides` can override them on inherited scenes. - `tilemap`: optional tilemap drawn beneath the layer's objects - `objects`: placed objects in the layer Each object has: - `id` (required, unique across the entire scene) - `name`, `prefab` (optional) - Transform: `x`, `y`, `originX`, `originY`, `rotation` (radians, clockwise), `scaleX` (default `1`), `scaleY` (default `1`), `flipX`, `flipY`, `alpha` (`[0, 1]`, default `1`), `z` (layer-local draw order, lowest first) - `sprite`: optional `{atlas, frame}` referencing a `sprite.Atlas` and frame name - `particles`: optional `{file, atlas}` (version 2) placing a 2D particle emitter YAML file (`file` is a slash-separated path from the project root; optional `atlas` resolves the emitter's `frameNames`). `sceneformat.Build` loads `file` through `ParticlesResolver` when implemented, falling back to `FileResolver` + `particles.UnmarshalConfigYAML` (so `FSAssets` works automatically), creates `BuiltObject.Emitter` (collected in `BuiltLayer.Emitters`), positions it at the object's composed world transform (updated by `BuiltObject.Sync`), advances it in `BuiltScene.Update(dt)`, and draws it in Z-order interleaved with sprites in `BuiltScene.Draw(d)` - `material`: optional slash-separated path from the project root to a shared material file, such as `materials/stone.material.yaml`, resolved at build time through `MaterialResolver` (see [resource](http://nsgo.games/docs/resources/)) - 3D look: `mesh`, one of the built-in primitives `box`, `sphere`, `plane`, `capsule` and `cylinder`, `model` (version 2), the slash-separated path from the project root to a glTF 2.0 file (`.gltf` or `.glb`), optionally narrowed to one of its nodes by `modelNode` or one of its meshes by `modelMesh`, or `gridMap` (version 2), the slash-separated path from the project root to a `*.gridmap.yaml` / `*.gridmap.yml` file; an object's `material` replaces the model's or grid map's materials or gives the primitive its surface; optional `occluder` (version 2) marks the object as a 3D occluder (`mode: model` or `mode: box` with optional `center`, `size`, and `doubleSided`). `scenemodel.Build` turns them into geometry, LODs, and occluders ([scenemodel](http://nsgo.games/docs/scenemodel/)). `CheckObjectModel` checks these fields on one object, and the editor's `PlaceObject` refuses an object it refuses; the inspector's Mesh and GridMap fields are mutually exclusive with each other and with `model` - 3D light (`light`, version 4): optional 3D light attached to the object's transform (`kind`: `directional`, `point`, or `spot`; CSS `color`, `intensity`, `range`, spot `innerCone` and `outerCone` half-angles in degrees, and `shadows`). Directional and spot lights aim along the object's local `-Z` axis. `CheckObjectLight` validates one object's light. - 3D camera (`camera`, version 4): optional 3D camera attached to the object's transform (`projection`: `perspective` or `orthographic`, `fov` in degrees or `orthoHeight`, `near`, `far`, and `current`). At most one 3D camera in a scene may set `current: true`. `CheckObjectCamera3D` validates one object's camera. - `components`: optional mapping from a component type name to its fields; free-form unless a component registry is given (see [Component types](http://nsgo.games/docs/editor/#component-types)) - `properties`: optional `map[string]any` for custom metadata - `scene`: optional slash-separated path from the project root to a scene file this object instances (version 2, see Instancing and inheritance below) - `overrides`: optional changes to the instanced scene's objects by ID (version 2, requires `scene`) - `children`: optional list of objects attached to this one (see Node tree below) ### Node tree (#484) An object can hold child objects under `children`, nested up to `MaxObjectDepth` (64) levels. A child's transform is local to its parent: `x`, `y`, `rotation`, `scaleX` and `scaleY` (and in 3D `posZ`, `rotX`, `rotY`, `rotZ` and `scaleZ`) compose with every ancestor's, and its `alpha` multiplies theirs. `originX`, `originY`, `flipX` and `flipY` stay the object's own, and `z` orders the whole layer, children included, with ties drawing each parent before its children. Children belong to their parent's layer, and their IDs share the scene-wide namespace, so an ID used anywhere in the tree is refused anywhere else. ```yaml layers: - name: ships objects: - id: ship x: 100 y: 50 rotation: 1.5707964 scaleX: 2 scaleY: 2 sprite: { atlas: actors, frame: hull } children: - id: turret x: 10 # lands at (100, 70): a quarter turn and twice the size of ship sprite: { atlas: actors, frame: turret } children: - id: barrel x: 5 # lands at (100, 80) ``` The same tree loads three ways: - `Build` links each `BuiltObject` to its `Parent` and `Children`, sets `World` to the composed 2D affine transform and `WorldAlpha` to the composed alpha, and draws each child's sprite at its world position, rotation and scale. A sprite whose composed transform is sheared (a rotated child under a non-uniformly scaled parent) cannot be drawn as a sprite, so `Validate` refuses it, and with it `Parse`, `Encode` and `Build`; `CheckObjectTree` makes the same check, and the nesting limit, for a single tree. A parent collapsed to zero size along one axis (such as `scaleX: 0`) is not a shear: its child sprites draw at zero scale. Objects without a sprite keep the exact matrix in `World`. `BuiltLayer.Objects` lists a layer's top-level objects, and `BuiltScene.Objects` indexes every object by ID. After changing a built object's document fields, `BuiltObject.Sync` recomposes its `World` and `WorldAlpha` and its sprite, and its descendants', and reports false for a sprite the change would shear. - `SpawnEntities(doc, world)` spawns one entity per object into an `entities.World`, parented in its `Hierarchy2D` as the objects nest, with the object's local `Transform2D` and an `ObjectRef` component naming the object and its layer. The top-level objects of a hidden layer spawn hidden, so their subtrees are not world-visible. Pass a registry via `SpawnEntitiesWith(doc, world, SpawnOptions{Components: reg})` to validate and resolve every component up front and invoke each registered `ComponentType.Spawn` factory on its entity (rolling back entities created so far on error). - `BuildNodes3D(doc, scene.Root())` builds a `scene3d` node tree: one group node per layer (carrying the layer's visibility), and one node per object named by its ID, with `UserData` pointing at its `ObjectDoc`. `ObjectLocalTransform3D` gives each node's local transform; `rotX`, `rotY` and `rotZ` apply in that order about fixed axes, the same order the editor's 3D viewport uses. - `scenemodel.Build(doc, scene.Root(), assets)` builds the same tree and attaches to each object's node the geometry and materials of its `mesh`, `model` or `gridMap`, with the node's `LocalBounds` set from the geometry, ready for `render3d.Queue` ([scenemodel](http://nsgo.games/docs/scenemodel/)). ```go spawned, err := sceneformat.SpawnEntities(doc, world) if err != nil { return err } world.Hierarchy2D().Sync() wt, _ := world.Hierarchy2D().WorldTransform(spawned["barrel"]) // wt.X == 100, wt.Y == 80 nodes, err := sceneformat.BuildNodes3D(doc, scene.Root()) if err != nil { return err } pos := nodes.Objects["barrel"].WorldTransform().Pos ``` Moving, deleting or undoing an object in the editor carries its children along, and the editor never hands out an ID that a nested child already uses. It refuses to place a tree deeper than `MaxObjectDepth` or holding a sheared sprite, and refuses a scale or rotation that would shear a sprite, the object's own or a descendant's, under the transforms of its ancestors. Both viewports draw, pick and edit nested children, and the [scene tree](http://nsgo.games/docs/editor/#scene-tree-861) selects, reparents, reorders and renames them. ### Instancing and inheritance (#483) A version 2 scene reuses other scene files. Every reference is a slash-separated path from the project root, like a material's, and `Parse` and `Encode` keep references and overrides exactly as written: a level of instances saves as the same instances, never as copies of their objects. An object with `scene` instances that file. The top-level objects of every layer of the instanced scene, in document order, become the object's first children, ahead of its own `children`, so the object's transform places the whole instance. Their IDs are prefixed with the object's ID and a slash, so ten instances of one enemy hold `enemy_1/body` to `enemy_10/body`. `overrides` changes the instanced objects, keyed by their IDs inside the instanced scene; a scene instanced inside it is reached by its prefixed ID, such as `gun/barrel`. The instanced scene's layer settings, camera, background and virtual size do not carry over, and a scene whose layers hold a tilemap cannot be instanced. ```yaml # scenes/enemy.scene.yaml version: 2 name: Enemy layers: - name: root objects: - id: body sprite: { atlas: actors, frame: hero } properties: { health: 3, speed: 40 } children: - id: torch x: 6 sprite: { atlas: actors, frame: torch } # level.scene.yaml version: 2 layers: - name: actors objects: - id: enemy_1 x: 32 "y": 40 scene: scenes/enemy.scene.yaml overrides: body: alpha: 0.5 - id: enemy_2 x: 64 "y": 40 scene: scenes/enemy.scene.yaml overrides: torch: x: -6 ``` A scene with `inherits` starts as a copy of its base and changes only what it declares: - `name`, `backgroundColor`, the virtual size and `camera` replace the base's when set, and `tilemaps` entries are added or replaced by name. - `overrides` changes inherited objects by ID, nested children and instanced objects (`enemy_1/body`) included. - `layerOverrides` changes inherited layers by name. - A layer named like one of the base's adds its objects to that layer and may set nothing else; any other layer is added after the base's layers. An inherited object or layer cannot be removed, and its ID cannot change. ```yaml # scenes/fast_enemy.scene.yaml: the enemy above, twice as fast version: 2 inherits: scenes/enemy.scene.yaml overrides: body: properties: speed: 80 ``` An override sets any object field except `id`, `children`, `scene` and `overrides`; a field it leaves out keeps the base's value, and a value of `0` or `false` is still a change. `components` and `properties` are replaced key by key, keeping the object's other keys. `Resolve(doc, scenes)` loads the referenced files through a `SceneResolver`, such as `FSScenes{FS: os.DirFS(root)}`, and returns a self-contained copy in which no object instances anything and nothing is inherited. It loads each file once per call and never changes `doc` or the documents the resolver returns. It refuses a cycle of scenes that instance or inherit each other, a chain deeper than `MaxSceneNesting` files, a result of more than `MaxResolvedObjects` objects, an override that names no object or layer of the scene it changes, and a result that does not validate, such as one whose prefixed IDs collide with other IDs. `Build` resolves a scene itself when its `AssetResolver` also implements `SceneResolver`, and `BuiltScene.Doc` is then the resolved copy; `SpawnEntities` and `BuildNodes3D` refuse a scene that still refers to others, so resolve it first. ```go type assets struct { sceneformat.AtlasMap sceneformat.FSScenes } built, err := sceneformat.Build(level, assets{atlases, sceneformat.FSScenes{FS: os.DirFS("project")}}) ``` In the editor, `PlaceScene(layer, path, x, y)` places an instance of a scene file as an undoable command, with an ID named after the file (also triggered by dragging a scene file from the File Browser onto the viewport, clicking its `+` button, or pressing **Place** with a scene file selected; registered prefabs in the Asset Browser can likewise be clicked or dragged onto the viewport via `PlacePrefab`). The editor's `Resolver` must implement `SceneResolver`; `PlaceScene`, and `PlaceObject` for any object tree that names a `scene`, resolve the scene as it would be with the instance placed and refuse it when that fails: a missing or invalid file, an override that names no object or holds a bad value, or IDs that collide once instances are expanded. Set the editor's `ScenePath` to the open scene's path from the project root (`OpenYAML` clears it) so that an instance leading back to the open scene, directly or through other files, is refused as a scene cycle before the saved file instances itself. Placing an instance raises a version 1 scene to version 2 (which Undo restores). New IDs are checked against the IDs the scene gets from its base and its instances as well as its own. Both the 2D and 3D viewports and the scene tree (`SceneTreeView`) let you select any instanced child or inherited object directly (shown muted in the scene tree with an `inst`/`base` tag and an override dot when modified). Editing its transform, sprite, material, particles, 3D light/camera/occluder/mesh/model/GridMap, custom properties, or component fields records an undoable override on the owning instance (`ObjectDoc.Overrides`, keyed by its ID inside the instanced scene) or on the inheriting scene (`SceneDoc.Overrides`, leaving the base file unchanged), and refuses edits whenever `sceneformat.Resolve` fails. Editing an inherited layer's visibility, space, parallax, or repeat records `SceneDoc.LayerOverrides`. The inspector shows an instance/inherited bar with the source scene path, instance count, and override count, marks each overridden field with a warning dot (whose tooltip shows the source value) and a per-field **Revert** button (`RevertObjectOverrideField` / `RevertLayerOverrideField`), and offers **Revert All** (`RevertObjectOverrides` / `RevertLayerOverrides`, pruning empty override maps so the saved YAML stays clean), **Open Scene** / **Open Base Scene** (`OpenSourceScene` / `OpenInstancedScene` / `OpenBaseScene`), **Apply to Source** (`ApplyOverridesToSource`, writing an instance's overrides back to its source scene file and clearing them on the instance in one undo step that restores the source file on Undo), and **Make Local** (`MakeInstanceLocal`, replacing a scene instance with a local copy of its resolved objects and prefixed connections in one undo step). Play runs a resolved copy of the scene, so changes made through `BuiltObject.Doc` show in the editor's document until Stop restores it. ### Example ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/scene.v2.json version: 2 name: Cave Room virtualWidth: 320 virtualHeight: 180 backgroundColor: "#141824" camera: x: 160 y: 90 zoom: 1 bounds: x: 0 y: 0 width: 320 height: 180 tilemaps: floor_grid: tileWidth: 16 tileHeight: 16 width: 4 height: 2 tileset: cave_tiles data: [1, 2, 2, 1, 1, 0, 0, 1] layers: - name: floor space: world order: 0 tilemap: ref: floor_grid - name: actors space: world order: 10 objects: - id: hero name: Hero prefab: prefabs/hero x: 48 y: 40 originX: 8 originY: 8 z: 5 sprite: atlas: actors frame: hero components: collider: { w: 12, h: 14 } properties: spawn: true - name: hud space: screen order: 100 objects: - id: heart_1 x: 8 y: 8 sprite: atlas: ui frame: heart ``` ### Loading, building and drawing in Go ```go doc, err := sceneformat.Parse(yamlBytes) if err != nil { return err } built, err := sceneformat.Build(doc, sceneformat.FSAssets{ FS: os.DirFS(projectDir), // YAML tilesets, Tiled and LDtk maps Atlases: sceneformat.AtlasMap{ "cave_tiles": tilesAtlas, "actors": actorsAtlas, "ui": uiAtlas, }, }) if err != nil { return err } // Each update step: built.Update(dt) // In a core.Canvas's Draw callback: built.Draw(d) ``` `Parse` rejects unknown YAML keys, trailing documents, unsupported versions, newer-version fields in older scene versions (version 2 fields in version 1, version 3 parallax/repeat fields in versions 1 and 2, version 4 `environment`/`light`/`camera` fields in versions 1–3), multiple `current: true` 3D cameras, scene references that are not slash-separated paths from the project root, overrides without the `scene` or `inherits` they change, duplicate layer names or object IDs (nested children included), object trees deeper than `MaxObjectDepth`, invalid spaces, malformed colors, and non-finite or out-of-range transforms, light/camera/environment parameters, parallax factors, or repeat periods. `Encode` validates and emits deterministic 2-space YAML that round-trips through `Parse` without loss. ### Schema The scene format's JSON Schemas are published at `https://nsgo.games/schemas/scene.v1.json` (`sceneformat.SchemaURL`), `https://nsgo.games/schemas/scene.v2.json` (`sceneformat.SchemaURLV2`, for scenes that instance or inherit other scene files, name glTF models, or hold layered grids or LDtk levels), `https://nsgo.games/schemas/scene.v3.json` (`sceneformat.SchemaURLV3`, for version 3 scenes with parallax and repeating layers), and `https://nsgo.games/schemas/scene.v4.json` (`sceneformat.SchemaURLV4`, for version 4 scenes with 3D lights, environment, and 3D cameras). `Encode` starts every file with the `# yaml-language-server: $schema=…` line for its version (`sceneformat.SchemaCommentFor`), so VS Code's YAML extension and other editors with a YAML language server validate and complete a scene as it is written. See [Schemas for YAML files](http://nsgo.games/docs/schemas/). ### Merging scene files in Git (#1058) `sceneformat.Merge(base, ours, theirs)` performs an identity-based three-way merge of scene documents: layers are matched by `name`, objects by `id` anywhere in the tree (including across reparenting and layer moves), tilemaps and overrides by key, and connections by `(from, event, to, handler)`. Individual fields—including nested `components`, `properties`, `overrides`, `camera` and `args` maps—merge one by one. The schema `version` merges monotonically to the highest version across `base`, `ours` and `theirs` (never below `base`) so branches that independently raise a scene's version do not conflict, and clean merges are validated with `Validate` and written with `Encode`. When both sides edit the same field differently, one side deletes what the other modified, both add different items under the same ID, reparenting conflicts or forms a cycle, or the combined scene fails `Validate`, `MergeResult.ConflictDoc(path)` produces a versioned, deterministic YAML `ConflictDoc` (`version: 1`, read and written with `ParseConflict` / `EncodeConflict`) naming every conflict's object, field, and `base`/`ours`/`theirs` values alongside the list of cleanly merged items. Projects wire this into Git through `.gitattributes` (`*.scene.yaml merge=nsgo-scene`) and `go tool game merge -setup` (run once per clone, verified with `go tool game merge -check`; the editor also checks this when opening a project in a Git repository and offers one-click setup from a banner; see [`game merge`](http://nsgo.games/docs/cli/#merge) and [Scene merge conflict report](http://nsgo.games/docs/formats/#scene-merge-conflict-report)). `sceneformat.DiffObjects` compares two scene documents by stable object ID, nested children included, and reports added, removed, and changed objects with copies of each side: the removed and changed objects in the first scene's document order, then the added objects in the second scene's, so the same two scenes always give the same list. A parent whose children changed is reported as changed too. `sceneformat.DiffScenes` returns the same changes grouped into `Added`, `Removed` and `Changed`, for hot-reload integrations that inspect a saved scene before applying it. Neither is used by the editor's Changes panel yet; they are the exported core for tools and a future `game diff` review command. ### Component types A `ComponentRegistry` declares, in Go and without reflection, the component types scene files may use: each type's name and documentation, and each field's name, kind (`FieldBool`, `FieldInt`, `FieldFloat`, `FieldString`, `FieldStringList`, `FieldPoint`, `FieldRect`, `FieldCircle` or `FieldPolygon`), optional allowed `Enum` values (for `FieldString` fields), default, optional inclusive range, optional `Step` for the inspector and documentation. `Register` refuses empty or duplicate names, ranges or steps on non-numeric fields, `Enum` on non-`FieldString` fields, a minimum above the maximum, a fractional range or step on a `FieldInt`, a negative step, and a default of the wrong kind or out of range. The four 2D shape kinds (`FieldKind.IsShape`) describe world geometry in an object's local coordinate space and are also published as `Point`, `Rect`, `Circle` and `Polygon` definitions in `scene.v1.json`, `scene.v2.json` and `scene.v3.json`: | Field kind | Go type | YAML form | Validation | | --- | --- | --- | --- | | `FieldPoint` | `sceneformat.Point` | `{x, y}` | Finite `x`, `y`; unknown keys refused | | `FieldRect` | `sceneformat.Rect` | `{x, y, width, height}` | Finite numbers, `width >= 0`, `height >= 0`; unknown keys refused | | `FieldCircle` | `sceneformat.Circle` | `{x, y, radius}` | Finite numbers, `radius >= 0`; unknown keys refused | | `FieldPolygon` | `[]sceneformat.Point` | `[{x, y}, ...]` | Sequence of valid finite points | `ParsePoint`, `ParseRect`, `ParseCircle` and `ParsePolygon` normalize decoded YAML values into their Go types, and `MarshalYAML` emits alphabetical keys so saved shape fields round-trip unchanged. ```go reg := sceneformat.NewComponentRegistry() reg.MustRegister(sceneformat.ComponentType{ Name: "body", Doc: "A moving body that collides with the level.", Fields: []sceneformat.Field{ {Name: "solid", Kind: sceneformat.FieldBool, Default: true, Doc: "Blocks other solid bodies."}, {Name: "speed", Kind: sceneformat.FieldFloat, Default: 32.0, Min: sceneformat.Float64(0), Max: sceneformat.Float64(500), Doc: "Top speed in points per second."}, {Name: "layer", Kind: sceneformat.FieldInt, Default: 1, Min: sceneformat.Float64(0), Max: sceneformat.Float64(31), Doc: "Collision layer."}, }, }) doc, err := sceneformat.ParseWith(data, sceneformat.ParseOptions{File: "scenes/room.scene.yaml", Components: reg}) ``` With a registry, `ParseWith` checks the components of every object, nested children included, and refuses an unregistered component type, a misspelled or unknown field, a value of the wrong kind (a `FieldInt` refuses `3.0`; a `FieldFloat` accepts an integer), a non-finite number and a value out of range. The error is a `*ComponentError` carrying the file, line and column of the offending key or value, the object ID, component and field, and lists the registered names: ```text scenes/room.scene.yaml:11:13: sceneformat: object "hero" component "body" field "sped": unknown field (registered: solid, speed, layer) ``` Defaults are not written into the document, so loading and saving a scene changes nothing; `reg.Resolve("body", fields)` returns every field with its default filled in. `ValidateComponents` checks a document built in Go (without positions), and `CheckField` checks one value and normalizes it to `bool`, `int`, `float64` or `string`. `Parse` without a registry keeps `components` free-form. In the editor, `Editor.SetComponentRegistry(reg)` checks the open scene's components and, as `OpenFile` does, its connections, then makes `OpenFile` report component errors with the file and line, and makes `SetComponentField` and `PlaceObject` refuse fields the registry does not allow. Changing the registry clears undo/redo history, so an undone edit the new registry refuses cannot be redone. The inspector lists every registered field of a component in declaration order, including fields the scene leaves unset, which show their default; the label's tooltip gives the field's documentation, kind, range and default, enum fields show a selector, string-list fields edit comma-separated items, and numeric inputs are bounded by the range and step by the field's `Step` (1 for an int, 0.1 for a float when unset). Floats are shown at full precision, and an edit the registry refuses is reported in the status bar. Components without a registered type, or every component when no registry is set, are shown from the values in the file as before (with the built-in physics component schemas available automatically in the inspector). ### Built-in physics components (#817) `sceneformat` ships six versioned built-in physics components (`PhysicsComponentVersion = 1`), registered together with `RegisterPhysicsComponents(reg)` or `PhysicsComponentRegistry()`: | Component | Dimension | Key fields | | --- | --- | --- | | `body2d` | 2D | `version` (`1`), `kind` (`static`, `kinematic`, `dynamic`), `mass`, `gravityScale`, `vx`, `vy`, `friction`, `restitution`, `linearDamping`, `angularDamping`, `material` | | `collider2d` | 2D | `version` (`1`), `shape` (`box`, `circle`), `width`, `height`, `radius`, `offsetX`, `offsetY`, `layer`, `mask` (`[]string`), `isTrigger`; declares events `enter`, `stay`, `exit` | | `trigger2d` | 2D | `version` (`1`), `shape` (`box`, `circle`), `width`, `height`, `radius`, `offsetX`, `offsetY`, `layer`, `mask` (`[]string`); declares events `enter`, `stay`, `exit` | | `body3d` | 3D | `version` (`1`), `kind` (`static`, `kinematic`, `dynamic`, `trigger`), `mass`, `gravityScale`, `vx`, `vy`, `vz`, `friction`, `restitution`, `linearDamping`, `angularDamping`, `lockRotation`, `layer`, `mask` (`[]string`), `material`, `physicsMaterial`; declares events `enter`, `stay`, `exit` | | `collider3d` | 3D | `version` (`1`), `shape` (`box`, `sphere`, `capsule`, `cylinder`, `convex`, `trimesh`, `heightfield`), `width`, `height`, `depth`, `radius`, `offsetX`, `offsetY`, `offsetZ`, `rotX`, `rotY`, `rotZ`, `terrain`, `maxVertices`, `layer`, `mask` (`[]string`), `isTrigger`; declares events `enter`, `stay`, `exit` | | `trigger3d` | 3D | `version` (`1`), `shape` (`box`, `sphere`, `capsule`, `cylinder`, `convex`), `width`, `height`, `depth`, `radius`, `offsetX`, `offsetY`, `offsetZ`, `rotX`, `rotY`, `rotZ`, `maxVertices`, `layer`, `mask` (`[]string`); declares events `enter`, `stay`, `exit` | - **Named collision layers**: `layer` and `mask` reference human-readable layer names declared under `physics.layers` in [`game.yaml`](http://nsgo.games/docs/project/) instead of raw bitmasks (on `collider2d`, `trigger2d`, `body3d`, `collider3d`, and `trigger3d`). Pass `ParseOptions{File: ..., PhysicsLayers: proj.PhysicsLayerTable()}` to `sceneformat.ParseWith` (done automatically by `project.File.LoadAutoloads` and `Editor.OpenProject`): any misspelled or unknown layer name fails to load with a `*loaderr.Error` carrying the exact file path, 1-based line, column, field path, and allowed layer names. - **Building and stepping (`BuildPhysics`)**: `ps, err := sceneformat.BuildPhysics(built, proj.PhysicsSettings(), lib)` constructs the matching `physics.World`, `physics.RigidWorld`, and `physics3d.World` (applying project gravity, solver iterations, named `Layer`/`Mask` bitmasks, optional `*.physics.yaml` files via `PhysicsMaterialResolver`, glTF/primitive meshes for `convex` and static `trimesh` colliders via `ModelResolver` or `FileResolver`, and `*.terrain.yaml` heightfields for static `heightfield` colliders via `TerrainResolver` or `FileResolver`, recorded in `ps.Bodies3D`, `ps.TriMeshes3D`, and `ps.Heightfields3D`). Calling `ps.Step(dt)` steps 2D kinematic and rigid bodies, 2D triggers, and 3D bodies and triggers, writes updated local poses back onto `BuiltObject.Doc`, and dispatches `PhysicsTriggerEvent` (`TriggerEnter`, `TriggerStay`, `TriggerExit`) to `ps.OnTrigger` and any attached `ps.Signals` (`enter` / `stay` / `exit`). - **Play-in-editor, viewport debug outlines, 3D collider handles & fit to bounds (#902)**: `Editor.PlayIn` automatically builds and steps `PhysicsScene` (`Editor.PlayPhysics`, `Editor.PlayTriggerEvents`, `Editor.OnPlayTrigger`) so a scene with a player body, wall colliders, and a coin trigger plays in the editor with collision and trigger events without writing game collision code. While `Editor.ShowPhysicsDebug` is enabled (the default; toggle with `SetShowPhysicsDebug`), both the 2D and 3D viewports render wireframe outlines for every `collider2d`, `trigger2d`, `collider3d`, and `trigger3d` (including cylinders, convex hulls, triangle meshes, and terrain heightfields). Switch the 3D gizmo to `Gizmo3DCollider` (`View > 3D Gizmo > Collider`, the Command Palette, or shortcut `shift+c`) to drag collider size handles (`ColliderHandles3D`, `PickGizmo3D`, `BeginGizmoDrag3D`, `UpdateGizmoDrag3D`, `EndGizmoDrag3D`), committing each drag as a single undo step; press **Fit to Model Bounds** in the Inspector (or call `Editor.FitCollider3DToBounds`) to fit a collider's size and local offset to its mesh or glTF model bounds in one undo step. ### Built-in 2D lighting and occluder components (#887) `sceneformat` ships two versioned built-in 2D lighting components (`Lights2DComponentVersion = 1`), registered together with `RegisterLights2DComponents(reg)` or `Lights2DComponentRegistry()` (and available automatically in the editor's inspector): | Component | Key fields | | --- | --- | | `light2d` | `version` (`1`), `kind` (`point`, `spot`), `color` (CSS color), `radius`, `intensity`, `falloff`, `direction` (radians, added to object rotation), `angle` (spotlight cone spread in radians), `castShadows`, `enabled`, `offsetX`, `offsetY` | | `occluder2d` | `version` (`1`), `shape` (`rect`, `polygon`, `tilemap`), `width`, `height`, `offsetX`, `offsetY`, `points` (`[][2]float64`, flow YAML `[[x, y], ...]`), `layer`, `tileLayers` (`[]string`), `enabled` | - **Automatic `lights2d.Scene` build**: `sceneformat.Build` turns `SceneDoc.AmbientColor`, every `light2d` and `occluder2d` on visible world-space layers, and any `shape: "tilemap"` occluders (derived from tilemap collision shapes via [`tileshape.View`](http://nsgo.games/docs/tileshape/)) into `BuiltScene.Lights2D` (`*lights2d.Scene`). `BuiltScene.Draw` renders `Lights2D` over world-space layers under the scene camera transform (before screen-space HUD layers) unless `SkipLights2D` is set; call `BuiltScene.SyncLights2D()` after moving lights or occluders at runtime. - **2D lighting preview & interactive handles**: **View > 2D Lighting Preview** or the Command Palette (`Editor.ShowLightingPreview`, `SetShowLightingPreview`, command `CmdToggleLightingPreview`) toggles live `lights2d.Scene` shadows and ambient darkness in edit mode. Selecting a `light2d` object shows interactive handles for its radius (`Handle2DLightRadius`), spotlight cone angle (`Handle2DLightSpotAngle`), and spotlight aim direction (`Handle2DLightSpotDirection`). Selecting an `occluder2d` object shows edge handles for `rect` occluders (`Handle2DOccluderRectN/E/S/W`) and draggable vertex (`Handle2DOccluderVertex`) and edge-midpoint insertion (`Handle2DOccluderEdgeMid`) handles for `polygon` occluders (`SetOccluderPolygonPoints`, `InsertOccluderVertex`, `RemoveOccluderVertex`, `ConvertOccluderToPolygon`). Every drag records one undoable step, Escape cancels it, and `SetAmbientColor` (or the Scene Lighting section in the Inspector) edits `ambientColor` undoably. ### Built-in 2D navigation region components (#888) `sceneformat` ships a versioned built-in 2D navigation region component (`NavRegion2DComponentVersion = 1`), registered with `RegisterNavRegion2DComponent(reg)` or `NavRegion2DComponentRegistry()` (and available automatically in the editor's inspector and `scene.v1.json` / `scene.v2.json` / `scene.v3.json`): | Component | Key fields | | --- | --- | | `navregion2d` | `version` (`1`), `mode` (`walkable`, `obstacle`), `points` (`[][2]float64`, flow YAML `[[x, y], ...]`), `offsetX`, `offsetY`, `subtractTileCollision` (`bool`), `tileLayer` (`string`), `tileLayers` (`[]string`), `agentRadius` (`float`, `>= 0`), `enabled` (`bool`) | - **Automatic `pathfind.NavMesh` build (`BuildNavMesh2D`)**: `sceneformat.Build` collects every enabled `navregion2d` on visible world-space layers (normalizing polygon winding so overlapping walkable regions union and obstacle cutouts subtract cleanly), optionally subtracts solid tile collision geometry from scene tilemaps (via [`tileshape.View`](http://nsgo.games/docs/tileshape/) and non-rectangular solid tile shapes), attaches any authored 2D `nav_link` components, bakes convex polygons with [`game/pathfind/navbake`](http://nsgo.games/docs/navbake/), and populates `BuiltScene.NavBake2D` (`*navbake.Mesh`) and `BuiltScene.NavMesh2D` (`*pathfind.NavMesh`). Scenes with no `navregion2d` components keep both fields `nil`; call `BuiltScene.SyncNavMesh2D()` after runtime edits. - **2D NavMesh overlay, polygon handles & Test Path tool**: The 2D viewport renders the built `NavBake2D` convex polygons, shared portals, and authored `navregion2d` outlines whenever `Editor.ShowNavMesh2D` is enabled (default `true`, toggled via **View > 2D NavMesh Overlay**, the 2D viewport's **Overlays** popover, `CmdToggleNavMesh2D`, or `SetShowNavMesh2D`). Selecting a `navregion2d` object exposes draggable vertex handles (`Handle2DNavRegionVertex`) and edge-midpoint insertion handles (`Handle2DNavRegionEdgeMid`) plus `PlaceNavRegion2D`, `InitNavRegionPolygon`, `SetNavRegionPoints`, `InsertNavRegionVertex`, and `RemoveNavRegionVertex`; dragging updates the built mesh overlay live and commits one undoable step on release (Escape cancels). Selecting the **Test Path** tool (`ToolNavTestPath`, **View > Tools > Test Nav Path**, or command `CmdToolNavTestPath`) lets you press start and end points in the viewport to draw the exact path `BuiltScene.NavMesh2D.FindPath` finds (recomputed live as vertices or tiles change, and cleared with Escape or `ClearNavPathPreview2D`). ### Built-in timer component (#1362) `sceneformat` ships a built-in timer component, registered with `RegisterTimerComponent(reg)` or `TimerComponentRegistry()` (and available automatically in the editor's inspector and the scene JSON schemas): | Component | Key fields | | --- | --- | | `timer` | `seconds` (`1`, `>= 0`), `oneShot` (`false`), `autostart` (`false`); declares the event `timeout` and the handlers `start` and `stop` | - **Running on the game clock**: `Signals.Update(dt)` advances every timer of the connected scene once per update step — call it in `game.Loop`'s `Update` before `Flush` — and enqueues each `timeout` for that `Flush`, in document order, so a scene wires a timer to any handler with no Go code and timer order stays deterministic. A one-shot timer fires once and stops; a repeating one carries the overshoot into the next period, so it does not drift; `seconds: 0` fires once per update step. The timer of an object whose entity has been destroyed (`SpawnConnected`) stops. - **`start` and `stop` handlers**: connecting any event to a timer's `start` restarts it from its full `seconds`, and to `stop` halts it without resetting, so a button can arm a door's timer in the file. ### Built-in 2D motion behavior components (#1751) `sceneformat` ships ten drop-in 2D motion behaviors registered via `RegisterBehaviorComponents(reg)` or `BehaviorComponentRegistry()` (and available automatically in the editor's inspector, Play-in-Editor, and the scene JSON schemas). Each carries `version: 1` and optional `enabled` (`true`), and advances deterministically via `BuiltScene.Step(dt)`: | Component | Key fields, events and handlers | | --- | --- | | `bullet` | `speed` (`240`), `acceleration` (`0`), `gravity` (`0`), `angle` (`0`), `setAngle` (`true`), `bounceOffSolids` (`false`); event `bounced`; handlers `setSpeed`, `setAngle`, `start`, `stop` | | `sine` | `property` (`x\|y\|angle\|scale\|alpha`), `period` (`1.5`), `magnitude` (`6`), `wave` (`sine\|triangle\|sawtooth\|reverse_sawtooth\|square`), `phase` (`0`); handlers `start`, `stop` | | `rotate` | `speed` (`180`), `acceleration` (`0`); handlers `setSpeed`, `start`, `stop` | | `orbit` | `target` (`""`), `radius` (`32`), `speed` (`90`), `angle` (`0`), `setAngle` (`false`); handlers `setSpeed`, `start`, `stop` | | `move_to` | `maxSpeed` (`120`), `acceleration` (`0`), `stopOnSolids` (`false`), `targetX`, `targetY`, `active` (`false`); event `arrived`; handlers `moveTo(x, y)`, `setSpeed`, `stop` | | `wrap` | `mode` (`scene\|view`), `margin` (`0`); event `wrapped`; handlers `start`, `stop` | | `bound` | `mode` (`edge\|origin`); handlers `start`, `stop` | | `destroy_outside` | `margin` (`64`), `mode` (`scene\|view`); event `destroyed`; handlers `start`, `stop` | | `fade` | `fadeIn` (`0`), `wait` (`1`), `fadeOut` (`0.5`), `destroy` (`true`), `autostart` (`true`); event `finished`; handlers `start`, `stop` | | `flash` | `on` (`0.05`), `off` (`0.05`), `duration` (`0`); event `finished`; handlers `flash(duration)`, `stop` | ### Connections (#490) A scene file connects an event one object emits to a handler of another object, so a button opens a door with no Go code that names either of them: ```yaml layers: - name: props objects: - id: button components: button: {} - id: door components: door: {} connections: - from: button event: pressed to: door handler: open args: speed: 2.5 ``` | Field | Type | Description | | --- | --- | --- | | `from` | `string` | Required ID of the object that emits the event. | | `event` | `string` | Required event name, such as `pressed`, or `button.pressed` to say which component when several components of the object declare it. | | `to` | `string` | Required ID of the object whose handler runs; it may be `from` itself. | | `handler` | `string` | Required handler name, such as `open`, or `door.open`. | | `args` | map | Optional values for the handler's params by name, each a bool, a number or a string; a param left out takes its default. | | `once` | `bool` | Disconnects after the first time the event fires. | | `when` | `string` | Optional condition; the handler runs only while it holds. Empty or left out, the connection always runs. | The events and handlers come from the component registry: a `ComponentType` lists the `Events` an object with that component emits and the `Handlers` it can run, each handler with typed `Params` (declared and checked like fields) and the `Func` that runs it. The game registers what each kind of component does once; the scene files decide which objects are wired together. A `when` condition is `true`, `false`, a bare name such as `has_key`, or a name, an operator and a value separated by spaces, such as `score >= 10` or `mode == combat`: a number compares with `<`, `<=`, `>`, `>=`, `==` and `!=`, a string or a bool with `==` and `!=`, and the value may be quoted but holds no space. The names are the game's: it passes a `sceneformat.RuleContext` of `Numbers`, `Strings` and `Bools` maps to `Signals.SetRuleContext`, and changes a value by changing its map, since each event's conditions read the maps when it fires. A condition that does not hold skips its handler, and a `once` connection stays connected until it fires with its condition holding. Loading a scene refuses a `when` it cannot parse; a name the rule context has no value of, or a value of the wrong type, skips the handler and makes `Emit` and `Flush` return the error after running the rest. `sceneformat.EvaluateWhen` evaluates an expression the same way, for tools. ```go reg.MustRegister(sceneformat.ComponentType{ Name: "button", Events: []sceneformat.Event{{Name: "pressed", Doc: "The player pressed the button."}}, }) reg.MustRegister(sceneformat.ComponentType{ Name: "door", Fields: []sceneformat.Field{{Name: "open", Kind: sceneformat.FieldBool}}, Handlers: []sceneformat.Handler{{ Name: "open", Params: []sceneformat.Field{{Name: "speed", Kind: sceneformat.FieldFloat, Default: 1.0, Min: sceneformat.Float64(0)}}, Func: func(c sceneformat.Call) { c.Target.Components["door"].(map[string]any)["open"] = true }, }}, }) doc, err := sceneformat.ParseWith(data, sceneformat.ParseOptions{File: "scenes/hall.scene.yaml", Components: reg}) signals, err := sceneformat.Connect(doc, reg, game) // Where the game handles a press on an object with a button component: err = signals.Emit(objectID, "pressed", nil) ``` `Connect(doc, reg, ctx)` checks the scene's components and connections and returns a `*Signals`. `Signals.Emit(from, event, payload)` calls the handler of every connection from that event in the order the file lists them, skipping a `once` connection that has run. Each handler gets a `Call`: the `Signals` (so it can emit further events, nested at most `MaxEmitDepth` levels), the `ctx` given to `Connect` (such as the game's state or a `*BuiltScene`), the source and target `*ObjectDoc` in the scene, the components and names of the event and handler, `Args` holding every param (the connection's value or the default) and the `payload`. `Emit` refuses an object the scene does not hold, an event none of its registered components declares, and a bare name two of its components declare (write `component.event`). `Signals` is a snapshot of the scene's objects as `Connect` finds them: after adding or removing objects in `doc`, which may also move the others in memory, call `Connect` again. A scene that instances or inherits other scene files is connected after `Resolve` (or through `BuiltScene.Doc`), and `Signals` is not safe for concurrent use. `Parse` checks a connection's form: all four names set, `event` and `handler` written as a name or `component.name`, arguments that are bools, finite numbers or strings, no connection repeated, and, in a scene that refers to no other scene file, `from` and `to` naming its objects. With a registry, `ParseWith` also checks the names against it and reports a `*ConnectionError` with the file, line and column: an event or handler no registered component of the object declares, a bare name two of its components declare, an argument the handler has no param for, and an argument of the wrong kind or out of range. The error lists what the object does declare: ```text scenes/hall.scene.yaml:16:14: sceneformat: connection 0 ("button" pressed -> "door" opne): no registered component of object "door" declares handler "opne" (it has: door.open) ``` `ValidateConnections` makes the same checks on a resolved document without positions. `Register` refuses an event or handler with an empty name, a dot in its name or a name its type already uses, and handler params on the same terms as fields; a registry used only to check files, such as an editor's, may leave `Func` unset, which `Connect` refuses. `Resolve` carries connections along: an instanced scene's connections come with the instance, the objects they name prefixed like its objects' IDs (`door_1/button`), so every copy of a prefab keeps its own wiring; an inheriting scene keeps its base's connections and adds its own after them. A scene may connect objects of the scenes it instances or inherits, and those names are checked once it is resolved. In the editor, `DeleteObject` also removes the connections from or to the deleted object and its descendants, and undoing the delete puts them back. #### Queued events `Emit` runs the handlers before it returns, so a handler that emits runs the next handlers inside itself. To keep a step's order plain, emit with `Signals.Enqueue(from, event, payload)` instead and call `Signals.Flush()` once per step, such as at the end of `game.Loop`'s `Update`: ```go loop.Update = func(dt time.Duration) { updateSystems(dt) // the game's own input and systems, which call signals.Enqueue if err := signals.Flush(); err != nil { log.Print(err) } } ``` `Enqueue` refuses what `Emit` refuses before it holds anything, so a misspelled event fails where it is raised. `Flush` runs the events enqueued before it began, in the order they were enqueued, each as `Emit` runs it; an event a handler enqueues, its own included, waits for the next `Flush`, so one `Flush` always ends and a handler never re-enters itself. `Flush` from a handler is refused, and `Pending` says how many events wait. A handler's panic passes through `Flush`, and the events after the one that panicked stay queued for the next `Flush`. Once the queue has grown to a step's events, a step allocates nothing more than emitting them would. #### Listening to events from Go A scene's connections are declared in the file; the code side of the same events — audio, analytics, achievements, UI — subscribes from Go instead, without a target object or a connection line per scene: ```go stop, err := signals.Listen("", "opened", func(c sceneformat.Call) { playSound("door_open") }, sceneformat.ListenOptions{}) defer stop() ``` `Signals.Listen(from, event, fn, opts)` checks `from` and `event` as `Emit` does and refuses an unknown object or event at the call, so a misspelt name fails at once; an empty `from` listens to every object of the scene that declares the event. The listener runs after the file's connections for the same event, in the order the listeners were added, and its `Call` carries the source object, the event and the payload (`Target`, `Component`, `Handler` and `Args` stay unset, a listener not being a connection). `ListenOptions.Once` runs it the first time only (`CONNECT_ONE_SHOT`), `ListenOptions.Deferred` queues each run for the next `Flush` (`CONNECT_DEFERRED`), and the returned `stop` ends the subscription — idempotent and safe to call inside a handler. A listener on an object never runs for it once its entity has been destroyed (`SpawnConnected`), as connections do. #### Spawning connected entities `SpawnConnected(doc, world, reg, ctx)` checks the scene as `Connect` does and spawns its objects via `SpawnEntitiesWith` with `reg` (so every registered `ComponentType.Spawn` attaches its typed ECS state and rolls back on error), then returns each object ID's entity and the `*Signals` that connects those entities. Every check runs before the first entity is spawned, so a scene whose connection names a missing object, event, handler or `Func`, or whose components break their types, spawns nothing. `EmitEntity(e, event, payload)` and `EnqueueEntity` address an object by its entity, `Entity(id)` returns an object's entity, and each `Call` carries `SourceEntity` and `TargetEntity`, so a handler reaches the target's components with `entities.Get`. A destroyed entity emits nothing: `Emit`, `Enqueue` and their entity forms refuse it, `Flush` drops the events it enqueued, and connections to it are skipped. A scene that instances or inherits others is spawned after `Resolve`, its instances' connections reaching the instances' entities (`west/door`). #### Checking connections `go tool game check` resolves each scene that instances or inherits others. It fails on a scene that does not resolve, such as a cycle or an override naming no object, at the instance or `inherits` line, and on a connection whose `from` or `to` names no object of the resolved scene, at the line that names it. When the project has its own editor command (`cmd/editor` importing `pkg/editor/editorcmd`, or `-tags gameeditor` from `game generate editor`), `go tool game check` runs it with `-check` so `assetcheck.CheckWith` also checks components and every connection's event, handler and handler arguments against the project's registry (plus built-in physics and skeletal components). Without an editor command, `game check` checks objects only and prints a note when scenes contain connections explaining how to enable it with `game generate editor`; a game can also run `assetcheck.CheckWith` directly in its own tests with its registry. In both cases it reports, at the file and line, a connection naming an event, handler or argument its objects do not declare and a component that breaks its type; in a scene that instances or inherits others, it also checks the components its overrides write and every connection of the resolved scene, so an override that breaks a connection the instanced or inherited scene brings, such as one adding a second component that declares the same event, fails at the override: ```go func TestScenesCheck(t *testing.T) { report, err := assetcheck.CheckWith(os.DirFS("."), assetcheck.Options{Components: Components}) if err != nil { t.Fatal(err) } for _, p := range report.Problems { t.Error(p) } } ``` ```text scenes/level.scene.yaml:12: sceneformat: connection 0 ("lever" held -> "west/door" open): no registered component of object "lever" declares event "held" (it has: button.pressed) ``` A fault that a scene brings unchanged from a scene it instances or inherits is reported on that file, and one that its overrides cause on the override, so each fault is reported once. Problems carry the line, not the column. ### Inspector (#865) The inspector sets up an object without editing YAML. Every edit it makes is one undoable step, and each has a method on `Editor` that does the same in Go; while Play is on, the methods return `ErrPlaying` and the controls are disabled. An edit the editor refuses is reported in the status bar. - **Sprite**: the Sprite field picks an atlas frame from those the asset browser lists (`Assets`), grouped by atlas and searchable, and its clear button unbinds it; the button beside it takes the frame selected in the asset browser. `SetObjectSprite(id, ref)` needs both an atlas and a frame, and with a resolver set the atlas must resolve and hold the frame; a nil `ref` unbinds the sprite. - **Origin and flip**: `originX` and `originY`, the pivot inside the sprite's frame, are set with `SetObjectOrigin(id, x, y)`, which refuses values that are not finite, and `flipX` and `flipY` with `SetObjectFlip(id, flipX, flipY)`. - **Material**: the Material field picks one of the open project's `*.material.yaml` files and its clear button names none; `SetObjectMaterial(id, path)` takes a slash-separated path from the project root, or an empty one. A material must load through the editor's resolver, which therefore has to implement `sceneformat.MaterialResolver` (as `resource.Library` does), since the scene could not be built otherwise; with any other resolver the field lists no files and stays enabled only to clear a material the object already names. - **Model (#893)**: in 3D the inspector shows a **MODEL** summary card (`ObjectModelSummary3D`: offscreen thumbnail, project-relative path, triangle count, and distinct material count) above the searchable Model field (`ProjectModels`: the project's `.gltf` and `.glb` files and the outputs of `game.yaml`'s model targets) whose clear button names none, a **MATERIAL** summary (`ObjectMaterialSummary3D`: material file name with roughness and metallic readouts), a **COLLIDER** summary (`ObjectColliderSummary3D`: e.g. `Convex hull · static`), a **CHILDREN** summary card (`ObjectChildrenSummary3D`) when inspecting a group, and **Ask to add a component…** (`OpenComponentAgentPrompt`). `SetObjectModel(id, path)` refuses a model that does not load and a model on an object that draws a built-in primitive, as the Mesh field is disabled on an object that draws a model; changing the model clears `modelNode` and `modelMesh`, which named parts of the old one, and naming one raises a version 1 scene to version 2, the first that has models, and leaves a later one as it is. Undo puts back all three fields and the version. - **Properties**: Add Property takes a key and a kind (`string`, `int`, `float` or `bool`) and adds the property holding that kind's zero value (`AddProperty(id, key, kind)`); the field trims the key, and an empty key, one with leading or trailing whitespace or one the object has, is refused. A whole-number float property is saved with a decimal point (`2.0`), so it opens again as a float. Each property's delete button removes it (`DeleteProperty`). - **Components**: the Add Component field filters the registered types the object lacks, and pressing one adds it holding every registered field at its default, so the file shows what the component does (`AddComponent(id, name)`). Enter adds the type the field names, or the one type it matches. A component the object already has, a name the registry does not know, and a name with leading or trailing whitespace or a `.` (which connections use in `component.event`) are refused; without a registry the field adds a component of any name with no fields. Adding a component is refused, too, when it would declare an event or handler that a connection names bare and another of the object's components declares as well, since the connection would no longer say which it means: write it as `component.event` first. In a scene that instances or inherits others, the check runs on the scene as resolved through the editor's resolver, the connections of the scenes it refers to included; it is skipped when the resolver cannot load scene files or the scene does not resolve and bind even without the new component. Each component's remove button removes it (`RemoveComponent(id, name)`) with every connection that needs it, from the object with an event the component declares or to the object with a handler it declares, named bare or as `component.name`; a bare name is attributed through the component's registered type, so without a registry, or for a type the registry does not know, only connections written as `component.name` are removed. `ComponentConnections(id, name)` lists them, and Undo puts the component and its connections back where they were. A component without a registered type keeps its fields editable from the values in the file; having no schema, a whole-number float in one of its fields is saved as `2` and opens again as an int. - **Connections (#872)**: the Connections section lists the events declared by the selected object's registered components (`ObjectEvents`) and every outgoing and incoming connection touching it (`ObjectConnections`). Pressing **Connect** opens an inline form to pick an event, choose a target object from the searchable object list (`SceneObjectIDs`) or pick it directly from the 2D/3D viewport or scene tree (`BeginConnectionPick` / `CancelConnectionPick` without losing the current selection), pick one of the target's registered handlers (`ObjectHandlers`), fill the handler's params with typed controls from the component registry, and toggle `once`. Each connection row lets you jump to its other end (`JumpToConnectionOtherEnd`), edit it (`UpdateConnection`), or remove it (`RemoveConnection`). Adding, editing and removing connections (`AddConnection`, `UpdateConnection`, `RemoveConnection`) are undoable commands checked with `sceneformat.Validate` and `sceneformat.ValidateConnections` before reaching `History`: an invalid connection (such as naming a handler the target lacks, a duplicate connection, or a wrong param type or out-of-range value) is refused with the reason shown in the status bar, leaving the scene and undo history unchanged. Without a component registry, existing connections remain visible, jumpable, editable and removable. - **Scene settings (#871, #884)**: when no object, room, layer, or asset file is selected (`ShowingSceneSettings`), the inspector displays the open scene's own settings instead of an empty state: scene `name` (`SetSceneName`), `virtualWidth` and `virtualHeight` (`SetVirtualSize`), `backgroundColor` via NSGo's color picker (`ui.ColorWell`) and CSS hex input with a clear button (`SetBackground`), and the default 2D `camera` (`SetCamera`, `SetCameraPosition`, `SetCameraZoom`, `SetCameraRotation`) with toggleable clamp `bounds` (`SetCameraBounds`, `ClearCameraBounds`). Each change is validated against `sceneformat.Validate` before touching the document or history—refusing non-positive virtual sizes, zoom, or bounds and invalid color strings in the status bar—updates the viewport live, saves and reloads unchanged, and participates in Undo/Redo. While scene settings are shown in 2D edit mode, the viewport highlights the camera's start view frame and dashed bounds, draws a draggable camera position handle (`CameraHandleCanvasPos`, `HitTestCameraHandle`, `BeginCameraDrag`, `UpdateCameraDrag`, `EndCameraDrag`, `CancelCameraDrag`), and draws 8 corner/edge resize handles on `camera.bounds` (`CameraBoundsHandleCanvasPos`, `HitTestCameraBoundsHandle`, `BeginCameraBoundsDrag`, `UpdateCameraBoundsDrag`, `EndCameraBoundsDrag`, `CancelCameraBoundsDrag`) so dragging a handle resizes `camera.bounds` (and dragging the border or empty interior moves it) live, cancels on Escape, and commits as a single undoable step. - **Room maps (`*.rooms.yaml`, #884)**: open an existing `*.rooms.yaml` file beside the scene from the file browser (`OpenRoomsProjectFile`, `OpenRoomsFile`, `OpenRoomsYAML`) or create one from the Scene Settings inspector (`NewRoomMap`). All rooms draw over the 2D scene viewport with their IDs, display names, transition tags, and 8 resize handles on the selected room. Create rooms by toggling **Draw Room** (`SetRoomCreateMode`) and dragging in the viewport or pressing **Add Room** (`AddRoom`, `AddRoomAtViewCenter`); select, move, and resize rooms with handles (`HitTestRoom`, `HitTestRoomHandle`, `BeginRoomDrag`, `UpdateRoomDrag`, `EndRoomDrag`, `CancelRoomDrag`) and delete them with the Delete button or Delete/Backspace key (`DeleteRoom`). When **Grid Snap** is enabled (default on, `SetRoomSnapToGrid`), room edges snap to the scene's tile grid (`RoomGridSize`, from the scene's inline or external tilemap or an explicit `SetRoomGridSize`). Selecting a room opens the Room Inspector to edit its `id` (`SetRoomID`), `name` (`SetRoomName`), bounds (`SetRoomRect`), and per-room `transition` (`SetRoomTransition`: inherit, `cut`, `slide`, or `fade` with duration, easing, and fade color), as well as the map-level default transition (`SetRoomMapTransition`). All room edits go through `Editor.History`, participate in `HasUnsavedChanges` and `Save`, and save deterministically via `rooms.Encode` (`SaveRooms`, `SaveRoomsFile`, `SaveRoomsYAML`) so files load with `rooms.Parse` and round-trip unchanged. - **Layer inspector (#885, #877)**: when a layer is selected with no object selected (for example after pressing a layer's row in the scene tree, choosing **Inspect Layer** in the layers panel context menu, pressing **Set Up Tilemap** in an empty tile palette, or calling `SetActiveLayer`), the inspector shows that layer's parallax factors (`Parallax X`, `Parallax Y`), tiling settings (`Repeat` X/Y, `Repeat W`, `Repeat H`), and **Tilemap** setup. In Go, `SetLayerParallax(layer, x, y)` and `SetLayerRepeat(layer, repeatX, repeatY, width, height)` edit parallax and repeat, and `AddLayerTilemap(layer, tileset, tileW, tileH, w, h)`, `SetLayerTilemapTileset(layer, tileset)`, `SetLayerTilemapTileSize(layer, tileW, tileH)`, `ResizeLayerTilemap(layer, left, right, top, bottom)`, `ExtractLayerTilemap(layer, refName)`, `InlineLayerTilemap(layer)`, and `RemoveLayerTilemap(layer)` set up and edit the layer's tilemap—all undoable through `History`. Growing or shrinking from the left or top edge shifts painted cells and updates `offsetX`/`offsetY` so every painted tile keeps its world position (raising version 1 or 2 scenes to version 3 when a non-zero offset is written, restored by Undo). Invalid sizes and tilesets missing frames for painted tile IDs are refused with a status message. Moving a tilemap into top-level `tilemaps` creates a `ref`, and moving it back inline removes the top-level entry once no other layer or `layerOverrides` references it. Parallax and repeat controls are disabled on screen-space layers; inherited base-owned layers disable all layer inspector edits. ### Projects The editor also opens a game's [project file](http://nsgo.games/docs/project/): `OpenProject` reads `game.yaml` and opens its main scene, `EditProject` changes it as an undoable step, and `SaveProject` writes it with the `nsgo.yaml` beside it in step. `go tool game editor ` opens a project directory. With `ProjectAssets` set, as the editor commands of package `editorcmd` set it, opening a project makes `Resolver` a `project.Resolver` over the project's directory: the scene draws the project's own sprite atlases, found by name nearest the open scene as `game check` finds them, the asset browser lists them, `PlaceScene` instances the project's scene files, and materials, physics materials, YAML tilesets and Tiled and LDtk maps load from the project, the tilesets and maps through its `ReadFile` as `FSAssets` reads them. An atlas a scene names is found nearest the file that names it, so a scene file instanced or inherited from another directory draws the atlas `game check` finds for it. The editor reads the atlases and material files again whenever it makes a change that may add, remove or rewrite them, such as installing or removing a pack, moving files, `ReloadAssets` or `RefreshSearch`; saving a scene keeps what it has read. `OpenProjectScene(path, scene)` opens the project with the scene file `scene` in place of its main scene, which `go tool game editor` does for a scene file inside a project's directory, so `ScenePath` names it and an instance of it in itself is refused as a cycle. `MoveFile(from, to)` moves a file or directory of the project and rewrites every reference to it, on disk and in the open scene and project, as `go tool game mv` does ([Stable references](http://nsgo.games/docs/project/#stable-references)), as one step that Undo takes back and Redo makes again. Undo puts each file the move rewrote back byte for byte, unless it changed since, in which case only its references are rewritten back. While a project is open, the file browser below the asset browser (`FilesView`) lists its files and directories (`ProjectFiles`), leaving out the directories that `game index` and `game mv` skip too: those whose names start with `.` or `_` and those named `testdata`. Pressing one selects it and puts its path in the field below the list; edit the path and press Move to rename or move it through `MoveFile`, press Open Table on a `.yaml`/`.yml` file to open it in the Data Table editor (`OpenDataTableProjectFile`), or press Find Refs to list every reference to it across the project (`ShowReferences`). Refresh lists the files again and rescans the project search and references index (`RefreshSearch`) after something outside the editor changed them. ## Data Table editor (#918) The Data Table panel (`DataTablePanelView`) opens versioned YAML data tables ([`datatable`](http://nsgo.games/docs/datatable/)) from the file browser as a spreadsheet-style grid below the viewport: - **Columns and kinds**: columns are the union of every row's keys in deterministic first-appearance order (plus any fields declared by a registered Go row type that no row currently sets). Each column's value kind (`string`, `number`, `bool`, `duration`, or `list`) is inferred from its cell values or taken from the registered Go row type; boolean cells render as toggle buttons and scalar/list cells commit on Enter or blur. - **Row operations and view controls**: add (`AddDataTableRow`), delete (`DeleteDataTableRow`), and reorder (`MoveDataTableRow`) rows, sort by clicking any column header (`SetDataTableSort`), and filter visible rows by case-insensitive substring match (`SetDataTableFilter`). Sorting and filtering affect only the view and never reorder or modify the underlying YAML document. - **Undo and lossless round-trip**: opening, closing, adding, deleting, reordering, and editing cells all go through the editor's shared `History`. Opening and saving a table without edits leaves the file byte-for-byte identical, and editing a single cell changes only that line while preserving comments, formatting, and each row's key order. - **Go row-type validation and panel states**: a game's own editor command can bind Go struct row types to slash-separated path or filename patterns with `editor.RegisterDataTableType[T](ed, pattern)` (or `Editor.RegisterDataTableRowType`). Matching tables are checked on open and on every cell or row edit with the exact same rules `datatable.LoadYAML` applies, refusing unknown columns, duplicate fields, and invalid cell values in the grid and showing the `*datatable.CellError` in the dismissible panel banner (`DataTableError` / `ClearDataTableError`) and status bar. Asynchronous table loaders can also toggle the loading card with `DataTableLoading` / `SetDataTableLoading`. ```go if err := editor.RegisterDataTableType[Enemy](ed, "data/enemies/*.yaml"); err != nil { log.Fatal(err) } ``` To share row types between the grid and `game check`, register them on a `datatable.Registry` and set `DataTables` in the project's `editorcmd.Options`. For a project created with `game generate editor`, add this to `editorOptions` in `editor.go` and include any existing component and plugin options in the returned value. ```go tables := datatable.NewRegistry() if err := datatable.RegisterRowType[Enemy](tables, "data/enemies/*.yaml"); err != nil { log.Fatal(err) } return editorcmd.Options{Components: Components, Plugins: editorPlugins, DataTables: tables} ``` Run `go tool game check` from the project root to validate matching tables even when they have never been opened in the grid. The editor command's `-check ` mode uses paths relative to the checked directory and prints the YAML line and column for table problems when available. ### Reviewing an agent's data table changes (#1033) When an agent proposes changes to one or more data table files (through `Editor.OpenDataTableReview` or the `datatable_review_propose` MCP tool), the editor opens a full-window row-by-row Data Table review (`DataTableReviewView`) using exclusively the editor's design spec tokens: - **Turn files and empty tables**: the left sidebar lists every data table touched in the turn (`27 of 40 changed`, `new · 0 records`); selecting a newly created empty file shows `"No records — ask the agent to add some"`. - **Filter chips, search, and sorting**: switch between **All**, **Changed**, **Unchanged**, **Reverted**, and **Yours** chips with live counts (`SetDataTableReviewFilter`), search across all fields (`SetDataTableReviewSearch`), and click any column header (`CycleDataTableReviewSort`) to cycle ascending, descending, and back to file order (reporting `aria-sort` via `DataTableReviewAriaSort`). Numeric columns with changes show a `Δ` header and sort by percentage delta without mutating file order. - **Old → new cells, in-place edits, and drag-to-reorder**: changed cells render in the Spec `changed` dashed pill showing struck-through old value `→` new value and `Δ%`, while numeric zeros render as `—` (`FormatReviewCellValue`). Each changed record has its own **Revert** / **Restore** button (`ToggleDataTableReviewRecord`). Clicking a cell value edits it in place (`StartDataTableReviewCellEdit`, `SetDataTableReviewCellText`, `StepDataTableReviewCellNumber`) and dragging a row's grip handle reorders it (`ReorderDataTableReviewRecord`); both join the review under **Yours** with a solid accent border and a `you` tag in the right-hand YAML diff pane (`DataTableReviewFocusedYAML`). - **Agent's check figures**: the agent attaches named figures (`DataTableReviewCheck`: label, value, optional value before the request, and basis) via `SetDataTableReviewChecks` or the `datatable_review_checks` MCP tool. Any person revert, restore, in-place edit, or row reorder marks those figures **Out of date** (`DataTableReviewChecksOutOfDate`) until the agent refreshes them. - **Pause, lossless Keep, and single-step Undo**: pressing `Esc` or **Editor** pauses the review (`PauseDataTableReview`), keeping autosave paused (`HasOpenReview`) and showing a `"Review paused"` toast with **Resume** plus a pending review card in the Agent panel (`ResumeDataTableReview`). **Keep N of M** (`KeepDataTableReview`, `⌘↵`) starts from the original parsed `datatable.Document` bytes and patches only the kept and edited lines so untouched and reverted lines stay byte-for-byte identical, committing every file in **one atomic Undo step** (`Undo` restores all files byte for byte and removes newly created files). **Revert all** (`RevertAllDataTableReview`, `⌘⌫`) closes the review cleanly without modifying disk and stays undoable with `⌘Z`. ### 2D viewport navigation (#864) The 2D viewport's canvas fills its panel and shows the scene through the editor's own view (`View2D`: the world point at the canvas's center, a zoom and a rotation), separate from the scene's `camera`, so a level larger than one screen can be seen and edited anywhere. The view is never saved to the scene nor recorded in the undo history. - A mouse wheel, a pinch, or a touchpad scroll with Control or Command held zooms about the pointer, keeping the world point under it fixed (`ZoomView2DAt`), between `MinView2DZoom` and `MaxView2DZoom`. - A touchpad's two-finger scroll, a mouse wheel's sideways scroll (Shift+wheel or a tilting wheel), a middle-button drag, a drag with Space held or a two-finger drag on a touch screen pans (`PanView2D`). - F, or the Frame Selection button, frames the selected object (`FrameSelection2D`, which frames everything when nothing is selected); Home, or Frame All, frames every object of the visible layers, their inline tilemaps and the camera's frame (`FrameAll2D`); Mod+0, or Scene Camera View, returns to the scene camera's view (`ResetView2D`). Until the author pans or zooms, and again after `ResetView2D` or opening another scene, the view is the scene camera's view: the virtual screen centered in the canvas at the camera's zoom and rotation, following the camera as the scene changes (`View2DFollowsCamera`). In edit mode the whole canvas takes the scene's `backgroundColor`, so objects far from the camera are seen against the game's clear color; it outlines the camera's frame, the virtual screen as the player sees it, and draws the camera's `bounds` dashed. Screen-space layers draw inside that frame. In Play mode only the frame shows, centered at the camera's view whatever view the author left, as in the game; the view does not pan or zoom until Stop brings the author's view back. Hit testing, placing, moving, tile painting, the selection outline and plugin tools all go through the view, applying each world-space layer's parallax offset (and previewing its repeat tiling) smoothly as the 2D view pans. `CanvasToWorld` and `WorldToCanvas` convert between canvas points and the world; `CanvasToScreen` and `ScreenToCanvas` between canvas points and the scene's virtual screen, where screen-space layers live; `ScreenToWorld` and `WorldToScreen` apply the scene's camera alone, as the game does. `CanvasSize` is the canvas's laid-out size, the scene's virtual size until the viewport lays out (`SetCanvasSize`); the 3D viewport fills the same canvas. ### 2D transform gizmo (#863) With the Select or Move tool, the 2D viewport edits an object's transform by dragging: - A drag on any object selects it and moves it, keeping the offset from where it was grabbed, so the object does not jump to the pointer. - The selected object carries a gizmo drawn at a fixed size on the canvas: a square at its origin moves it freely; a red and a green arrow move it along its own X and Y axes, which turn with its rotation; a ring around it turns it about its origin; and, once its outline is at least 24 points on a side on the canvas (zoom in on a small object), handles on its corners and edges scale it about its origin, the edges one axis and the corners both. A handle that sits on or next to the origin's line along an axis it scales is left out, as the top and left handles of a sprite whose origin is its top left corner are, and where the move square and a handle overlap, the square is taken. Holding Shift while scaling keeps the aspect ratio. Dragging a scale handle through the origin mirrors the object with a negative scale. - Each drag is one undoable step, recorded when it ends ("Move hero", "Rotate hero", "Scale hero"); Undo restores the object's fields exactly, an unset `scaleX` or `scaleY` staying unset, and an edge handle leaves the other axis's field alone. A drag that ends where it began records nothing. - Escape, a gesture the system cancels or a second finger coming down puts the object back as it was before the drag and records nothing; the rest of that gesture does nothing. Undo, Redo, Play, Save, Delete, Duplicate, or changing the tool or the view mode during a drag cancels it first. - A scale that would be zero or nearly so (below 0.001), or a scale or rotation that would shear a sprite in the object's tree, its ancestors included (a rotated child under a non-uniformly scaled parent, which `ScaleObject` and `RotateObject` refuse too), is not taken: the object keeps its last valid transform and the status bar says why. - A nested child carries the gizmo too and is dragged in its parent's space, so it follows the pointer under a turned or scaled parent. An object hidden or locked in the scene tree, or under one that is, has no gizmo and is not dragged, even while it is selected. Drags map through the object's layer: a world-space layer's objects move by the world distance the pointer travels, whatever the 2D view's or the scene camera's zoom and rotation, and a screen-space layer's by the distance on the virtual screen. A tap still selects, and with the Move tool still puts the selected object where it is pressed. A drag with Space held, or a middle-button drag, pans the view instead. In Go, `BeginDrag2D(x, y)` starts a drag at a canvas point and returns the handle it took (`GizmoHandle2D`), `UpdateDrag2D(x, y, keepAspect)` follows the pointer, and `EndDrag2D` or `CancelDrag2D` finishes it; `PickGizmo2D` names the handle under a canvas point, `Dragging2D` the one held, and `Gizmo2DShown` says whether the gizmo is drawn. ### 2D component shape handles (#882) In 2D edit mode, the viewport draws every registered shape field (`FieldPoint`, `FieldRect`, `FieldCircle` and `FieldPolygon`) of the selected object in its local space (accounting for parent transforms, rotation, scale, layer space and parallax). Toggling **View > Show All Component Shapes** (or the Command Palette, `SetShowAllShapes`, `CmdToggleAllShapes`, `Editor.ShowAllShapes`) draws shape fields of all visible objects in the scene at once, keeping the selected object highlighted on top. With the Select or Move tool, interactive handles appear on the selected object's shape fields: - **Point**: drag the handle to move `(x, y)`. - **Rectangle**: drag any of the 4 corner or 4 edge handles to resize (dragging past the opposite edge flips smoothly while keeping `width >= 0` and `height >= 0`), or drag the center handle when it does not overlap the object's origin move square. - **Circle**: drag any of the 4 cardinal rim handles to change `radius` (clamped `>= 0`), or drag the center handle when offset from the object's origin. - **Polygon**: drag any vertex handle to move it; click or drag an edge midpoint handle to insert a new vertex (`AddPolygonVertex`); right-click or Alt+click a vertex handle to remove it (`RemovePolygonVertex`, keeping at least 3 vertices). - **Grid snapping**: toggle **Snap** in the 2D viewport bar (`viewport-bar-snap`, **View > Snap to Grid**, `SetSnapToGrid`, `CmdToggleSnapGrid`, `Editor.SnapToGrid`) or configure snapping in the Snap Settings popover (`view-snap-settings`, **View > Snap Settings...**, `CmdSnapSettings`) to snap handle edits and inserted vertices to `EffectiveGridStep` (or whole points when pixel snapping is enabled; holding `Ctrl` / `Cmd` inverts snapping during a drag). Every drag, vertex addition, and vertex removal commits through `SetComponentField` as one undoable step, and Escape, a cancelled gesture, a second finger, Undo/Redo, Play, Save or switching tools cancels an in-progress drag and restores the pre-drag field unchanged. In Go, `VisibleShapes2D`, `ShapeHandles2D`, `PickShapeHandle2D`, `BeginShapeDrag2D`, `UpdateShapeDrag2D`, `EndShapeDrag2D`, `CancelShapeDrag2D`, `DraggingShape2D`, `ActiveShapeHandle2D`, `AddPolygonVertex`, `RemovePolygonVertex` and `HandleCanvasSecondaryPress` expose the same workflow, and the inspector displays editable controls for every shape field kind. ### Snapping and 2D grid overlay (#869) The editor provides unified snapping across object placement, dragging, 2D handles (transform gizmo, component shapes, 2D lights/occluders, and 2D navigation regions), and 3D gizmos (translate, rotate, and scale): - **Snap settings in the viewport bar and menus**: toggle grid snapping with the 2D viewport bar's **Snap** switch (`viewport-bar-snap`), **View > Snap to Grid**, or `CmdToggleSnapGrid` (`SetSnapToGrid`), or open the compact Snap Settings popover (`view-snap-settings` in the 2D viewport bar, `view3d-snap-settings` in the 3D bottom bar, **View > Snap Settings...**, or `CmdSnapSettings`) to switch each mode independently: - **Grid snap** (`SnapToGrid`, `SetSnapToGrid`): snaps positions to `EffectiveGridStep()`, which defaults to the active layer's tilemap tile size (supporting non-square tiles) when `GridSize` is `0`, falling back to `8` when the active layer has no tilemap. Setting an explicit step (`SetGridSize`) overrides the tile size until **Auto** (`ResetGridSize`) is pressed. - **Pixel snap** (`SnapToPixel`, `SetSnapToPixel`, `CmdToggleSnapPixel`): snaps positions to whole points (1-unit increments) when grid snap is off. - **Rotation snap** (`SnapRotation`, `SetSnapRotation`, `CmdToggleSnapRotation`): snaps 2D and 3D rotation drags to multiples of `RotationSnapDeg` degrees in radians (`SetRotationSnapDeg`, default `15°`). - **Scale snap** (`SnapScale`, `SetSnapScale`, `CmdToggleSnapScale`): snaps 2D and 3D scale drags to multiples of `ScaleSnapStep` (`SetScaleSnapStep`, default `0.25`) without collapsing scales to zero. - **Modifier inversion**: holding `Ctrl` or `Cmd` during a drag or placement press temporarily inverts snapping—disabling active snapping for free precision edits, or enabling snapping when it is off (`SetSnapInvert`). - **Optional 2D grid overlay** (`ShowGrid`, `SetShowGrid`, `CmdToggleShowGrid`): draws a hairline grid across the visible 2D canvas at the active snap step even outside tile tools, following `View2D` pan, zoom, rotation, and active-layer space/parallax, doubling drawn spacing automatically when zoomed far out so the grid never obscures the canvas. - **Multi-object selection moves as a whole**: select multiple objects with `SelectObjects`, `ToggleSelectObject`, or Shift-click in 2D `ToolSelect` (`SelectedIDs`). Dragging any selected object (or using the Move tool or 3D Translate gizmo) snaps the primary anchor and moves every other non-descendant selected object by the exact same snapped delta, preserving relative offsets and recording one undoable step (Escape cancels and restores all objects). - **Per-project preferences**: snap settings (`SnapSettings`, `SetSnapSettings`) are editor preferences saved per project in `.game/editor.yaml` (`ViewStateFile`), never written to scene files and never marking a scene dirty. Switching scenes within the same project keeps the project's snap settings; switching projects saves and restores each project's own preferences. ## 3D viewport (#890) In 3D the viewport shows the scene as the game draws it: a `gpu.View` fills the panel and draws the scene's 3D build with render3d, and the canvas over it draws the ground grid, the origin axes, the selection outline and the gizmo. The build is `scenemodel.Build`'s (`Scene3D`): every object's built-in primitive (`mesh`) or glTF model (`model`, `modelNode`, `modelMesh`) with its materials and textures, the objects that instanced scenes add included. Models, material files and images load through the editor's `Resolver` when it implements `scenemodel.ModelResolver`, `sceneformat.MaterialResolver` or `scenemodel.ImageResolver`, and from the open project's files otherwise. When the scene does not build, such as when a model it names does not load, a line in the viewport's corner says why (`Viewport3DError`) and every object keeps a box. - **Lights and sky**: when a version 4 scene defines lights or an `environment`, the viewport renders the scene's own lights, shadows, sky (solid color, gradient, or HDR cubemap via `scenemodel.HDRResolver`), ambient/IBL, fog, tonemapping, and exposure through `scenemodel.Renderer` (`PrepareScene`, `RecordShadows`, `DrawSky`, `ClearColor`), matching the game's render path pixel for pixel. When a scene defines neither lights nor an environment, the viewport falls back to `DefaultLights3D` under a gradient sky. An editor built on this package can still override lighting with `SetLights3D` (`Editor.Lights3D`), which draws over `backgroundColor`. - **Shading**: the 3D viewport bar's Shading menu (`view3d-shading`), `View > 3D Shading`, and the commands `view.shading.lit`, `view.shading.unlit` and `view.shading.wireframe` switch `Shading3D` (`SetShading3D`): Lit, Unlit (each surface's textured base color plus its emissive color, without lights), and Wireframe, which lights the geometry and draws the edges of its triangles over it. Shading is a view setting: it is not undoable and is not saved. - **Picking and nested children (#894)**: every nested object up to 64 levels deep—including children added by instanced and inherited scenes—draws at its composed world transform (`ObjectLocalTransform3D` composed up the parent chain, matching `BuildNodes3D` identically) across meshes, wireframes, light/camera/probe icons, physics debug wireframes, occluders, and component gizmos. A press selects the deepest hit object under the pointer: an object that draws a mesh or model is hit on its triangles through `scene3d` picking, while an object without geometry is hit on its world-space box only where no geometry is hit (with a hit descendant winning over its enclosing ancestor). Pressing a second time on an already-selected nested child steps selection up to its parent—and through to the owning scene instance root—before cycling back to the deepest child; holding `Alt`/`Option` while clicking (`Select3DAtWithModifiers`, `HandleViewport3DPressWithModifiers`, `HandleCanvasPressWithModifiers`) directly selects the owning scene instance root for an instanced child or the immediate parent for a locally nested child (and composes with `Shift` to add and `Mod` to toggle). Hidden and locked objects (with their descendants) are passed over. - **Parent-space gizmo editing and instance overrides (#894)**: when a nested child is selected, the 3D transform gizmo (`Translate`, `Rotate`, `Scale`, single- or multi-selection) draws at the child's composed world position and orientation; dragging moves or turns the child under the pointer in world space while inverting the parent chain to write the child's local transform in parent space. Dragging an object that comes from an instanced scene or base scene writes an override entry under the owning instance's `overrides` (or `SceneDoc.Overrides` for inherited scenes) without touching the source scene file, round-trips through YAML, and commits as one undoable step. - **Live edits**: the build is made again only when what the scene looks like changes (an object's look, its place in the tree, an instanced scene or an override, or the project's files). A gizmo drag, an undo of a move, the open animation clip's pose at the playhead and a playing game's changes move the built nodes in place, so a drag rebuilds and uploads no mesh. `ObjectCorners3D` and `ObjectAABB3D` give an object's box as the bounds of its geometry when it has any, and Frame Selection (`f`) frames those bounds, so a model a meter across fills the view. - **Without a GPU**: on a target where the GPU view is not supported, before its first frame and after a device loss, the canvas draws the whole wireframe view instead: the scene's background, the grid, a box around every object (its geometry's bounds when it has any) and the gizmo. `Viewport3DOnGPU` reports which one shows. `OrbitCamera3D.SceneCamera` turns the editor's orbit camera into the `scene3d.Camera` the GPU view draws through, with the same eye, projection and clip planes the canvas projects with, so the overlays line up with the geometry. ### Navigating the 3D view (#891) Navigating moves only the editor's camera (`Camera3D`, an `OrbitCamera3D`): it is never an edit, never goes into the undo history and never changes the scene file. The camera jumps where it is told without animating. | Do | With a mouse | With a touchpad or touch screen | With the keyboard or a button | | --- | --- | --- | --- | | Orbit about the target | Drag | Drag with one finger | The Orbit 15° left and right buttons under the axis widget | | Pan | Middle-button drag, or Shift+drag | Two-finger scroll, or a two-finger drag on a touch screen | | | Zoom toward the target | Wheel | Pinch, or scroll with Control or Command held | | | Fly | Hold the right button: move the pointer to look, W, A, S, D to move, Q and E down and up, Shift to go faster, the wheel to change the speed | | | | Focus the selection | | | `f` or the bottom bar's Focus `F` button, framing its bounds, or the whole scene with nothing selected | | Axis views | | Click an axis button (`X`, `Y`, `Z` or negative ends) on the orientation widget in the top right corner | `1` Front, `ctrl+1` Back, `3` Right, `ctrl+3` Left, `7` Top, `ctrl+7` Bottom, or Tab/Enter on the orientation widget | | Perspective or orthographic | | | `5`, or Persp and Ortho in the top-left viewport bar | | Shading mode | | | The top-left viewport bar's Shading menu (`Lit`, `Unlit`, `Wireframe`) | | Transform space (Local / Global) | | | `t`, Local / Global in the bottom bar, or command `gizmo.3d.space` | | Back to the default view | | | The top-left viewport bar's Reset view button | - **Mouse navigation mappings (`Editor.Navigation3D`, `Navigation3D.Resolve`, Settings › Viewport › 3D navigation)**: choose between three desktop mouse presets (touchpad scrolling, pinch zoom, and two-finger touch panning remain unchanged across all three): - **Default (`Navigation3DDefault`)**: left-drag on empty space orbits (and drags gizmos/tools when started on them), Shift+left-drag or middle-drag pans, right-drag flies, and the mouse wheel dollies. - **Blender (`Navigation3DBlender`)**: middle-drag orbits, Shift+middle-drag pans, right-drag flies, the mouse wheel dollies, and left-drag is reserved for selection, tools, and gizmos. - **Maya (`Navigation3DMaya`)**: Alt+left-drag orbits, middle-drag (or Alt+middle-drag) pans, Alt+right-drag or the mouse wheel dollies, plain right-drag flies, and plain left-drag is reserved for selection, tools, and gizmos. - **The viewport HUD and status bar** follow the editor's design spec tokens: the top-left bar pairs Persp/Ortho, the Shading menu (`Lit`, `Unlit`, `Wireframe`), the current view name (`ViewName3D`: an axis view name or `Perspective`, with ` · ortho` in orthographic and `User · ortho` when orbited off-axis), Reset view, and Camera/Env toggles, with the keycap help line directly underneath (updating live with the active 3D navigation mapping, e.g. `Drag orbit · Middle pan · Right WASD fly · F focus` in Default mode). The top-right circular orientation widget exposes clickable, keyboard-focusable buttons for all six axis ends above the Orbit 15° left and right buttons. The bottom bar holds the `Local` / `Global` transform space toggle (`GizmoSpace3D`, `SetGizmoSpace3D`), Snap settings popover (`view3d-snap-settings`), 3D Overlays popover (`view3d-overlays`: LOD, Occluders, Render Stats, 3D NavMesh), GridMap tools (`Paint`, `Erase`, `Pick`, `Box`), and `Focus F` button. The status bar adds the view's yaw and pitch in degrees (` · yaw N° · pitch M°`) and the active gizmo space (` · Local` or ` · Global`). - **Orthographic** (`SetOrthographic3D`, `OrbitCamera3D.Orthographic`) projects in parallel. The view is `OrthoHeight` high, the height the perspective view shows at the target, so switching keeps what lies there the same size, and zooming changes that height. `Project`, `ScreenRay`, `SceneCamera`, picking and the gizmo work the same in both: in orthographic every pixel's ray runs along the view, so a press picks what lies under it and a gizmo drag moves the object by the distance the pointer travels along the axis. An axis view in orthographic is a true plan or elevation. - **Flying** (`BeginFly3D`, `FlyLook3D`, `FlyMove3D`, `EndFly3D`) turns the camera about its eye and moves eye and target together. While it flies, W, A, S, D, Q and E, with or without Shift, move the camera instead of running their usual shortcuts (the gizmo's W and E, Rotate's and Erase Tile's E), and the pointer is locked to the viewport where the platform can lock it. A flight looks in perspective, so an orthographic view switches to perspective; a right-click that neither turns nor moves the camera leaves it orthographic. Its speed, `FlySpeed3D` in world units a second, starts at the camera's distance from its target and the wheel doubles or halves it (`AdjustFlySpeed3D`). - **Axis views** (`SetView3D`, the commands `view.3d.front`, `view.3d.back`, `view.3d.right`, `view.3d.left`, `view.3d.top` and `view.3d.bottom`, and `view.3d.orthographic` for the projection) keep the target and the distance. Front looks along -Z, Right along -X and Top straight down with -Z at the top of the view. - **Saved per scene**: each scene of a project opens at the camera it was left at. The editor writes the views to `.game/editor.yaml` in the project (`ViewStateFile`, described on [File Formats](http://nsgo.games/docs/formats/)) as another scene opens, as the scene is saved and as the window closes, and an app that ends the editor another way calls `SaveViewState`. A scene it has no view of opens at `DefaultOrbitCamera3D`. Creating the `.game` folder, the editor writes a `.gitignore` there that ignores the folder, so the views stay out of version control. A file a newer editor wrote, with a higher `version`, is neither read nor written over. ### 3D transform gizmos (#892) The 3D viewport's transform gizmo reuses `render3d.Gizmo` for drawing, picking, and constrained drags in **Global** (world) or **Local** space: - **Modes and shortcuts**: press `w` (Translate, `Gizmo3DTranslate`), `e` (Rotate, `Gizmo3DRotate`), and `r` (Scale, `Gizmo3DScale`) in the 3D viewport (`ScopeViewport3D`, without clashing with 2D tile tools' `e`), or choose them in the header bar's tool group, `View > 3D Gizmo`, or the Command Palette. - **Global / Local space toggle**: toggle `Editor.GizmoSpace3D` (`GizmoSpaceGlobal` / `GizmoSpaceLocal`) via the 3D bottom bar's **Local** / **Global** toggle (`view3d-space-local` / `view3d-space-global`), shortcut `t` (`CmdGizmoSpace3D`), `View > 3D Gizmo > 3D Gizmo: Local / Global Space`, or `SetGizmoSpace3D` / `ToggleGizmoSpace3D`. In Local mode, handles orient to the selected object's Gram-Schmidt orthonormalized world orientation—including its ancestors for nested children (`GizmoOrientation3D`). - **Exact rotation about the drawn axis**: dragging any rotation ring (X, Y, or Z) composes the drag around the exact world-space axis the drawn ring represents and converts the child-local result (`RParentᵀ · RDeltaWorld · RWorldStart`) back to scene Euler XYZ (`Rz·Ry·Rx`), so even on an object already rotated about multiple axes or nested under a rotated or scaled parent, every ring turns strictly about the axis drawn. - **Plane handles, screen-space center handle, and uniform scale**: Translate exposes `Axis3DXY`, `Axis3DXZ`, and `Axis3DYZ` planar squares (moving strictly within the active two-axis plane, with grazing-ray guards) and a center `Axis3DAll` handle (translating in the camera view plane). Scale exposes a center `Axis3DAll` cube that scales all three axes proportionally. - **Snapping and live drag delta**: 3D translate, rotate, and scale drags share the editor's snap settings (`SnapSettings`, `EffectiveGridSize`, `EffectiveRotationSnapDeg`, `EffectiveScaleSnapStep`) and temporary `Ctrl`/`Cmd` modifier inversion (`SetSnapInvert`). While dragging, the status bar displays the live delta (`GizmoDragDelta3D`: `dx`/`dy`/`dz`, degrees `°`, or scale factor `x`) alongside the active space (`Global`/`Local`), and every completed drag commits as **one undo step** that round-trips cleanly through scene YAML (`Escape` cancels and restores the pre-drag transform). ### Placing models in 3D (#893) The asset browser lists, under its atlases, the models to place in 3D (`Models`): the built-in primitives, then the open project's glTF models by path, the outputs of `game assets` model targets included before they are built (`ModelEntry.Output`). Each has a thumbnail rendered offscreen (`ModelThumbnail`): the model alone, framed from above and in front and lit by `DefaultLights3D`, drawn through scenemodel on NSGo's software GPU. Each model loads on the UI goroutine the first time its thumbnail is drawn, as everything the editor's `Resolver` serves loads, and apart from the scene's own cache of models; the rendering runs off the UI goroutine, so the list shows at once and the pictures follow. A model that does not load gets none. - **Place tool**: pressing a model selects it (`SelectModel`, `SelectedModel`) and, in 3D, turns on the Place tool (also reachable via `p`, `View > Tools > Place`, or `CmdToolPlace`). In 3D a press then adds an object drawing the model, named after it, where the pointer's ray hits the scene's geometry, or where it crosses the ground plane, the horizontal plane at `PlaceHeight3D`, when it hits none (`PlacementAt3D`, `PlaceModelAt3D`). The object rests on that point: it is raised along the surface's normal by how far its geometry reaches below its origin, so a unit box on the floor sits on it rather than half under it. Hidden and locked objects are passed over, as picking passes over them. - **Snap and Align**: while the Place tool is active in 3D, the contextual Place bar (`view3d-place-bar`)—alongside `View > Tools` and the Command Palette (`CmdTogglePlaceSnap3D`, `CmdTogglePlaceAlign3D`)—exposes **Snap** (`place3d-snap`, snapping the X and Z of a point on the ground plane to the spacing of the grid the viewport draws, `PlaceSnap3D`; a point on the scene's geometry is not snapped, since the grid's spacing can be wider than the object under the pointer), **Align** (`place3d-align`, turning a model placed on the scene's geometry so that its +Y axis follows the surface's normal, `PlaceAlign3D`), and the ground height field (`place3d-height`, setting `PlaceHeight3D`). They are view settings, not edits (`SetPlaceOptions3D`). - **Drag and drop**: dragging a model from the asset browser onto the 3D viewport places it where it is dropped, through the Place tool's rules, whatever the active tool. A `.gltf` or `.glb` file dropped on the viewport from another app is placed when it lies inside the project's folder, outside the folders the asset browser leaves out (names starting with `.` or `_`, and `testdata`) (`DropModelFiles`), several files as one step; a file outside the project, of another kind or from the web, which names no path, is refused with the reason in the status bar. A file drop carries no position, so dropped files land where the view's middle points. - **Bottom MODELS strip**: in 3D view (outside Assets drawer mode), a **MODELS** strip (`Viewport3DModelsStripView`, `StripModels`) sits along the bottom of the 3D viewport (`"drag in"`), showing offscreen-rendered thumbnails of the project's models first followed by built-in primitives, each with the tooltip `"Drag into the viewport to place "`, click-to-select and drag-into-viewport placement, and a pinned **Or ask for one** button (`OpenModelAgentPrompt`) that opens an inline agent prompt (`"Describe a model… e.g. a low stone planter, 1 × 0.5 m, same stone as the walls"`) dispatching `Viewport3DAgentRequest` to `Editor.OnAskAgent3D` (`SubmitViewport3DAgentPrompt`). - **One step**: every placement is one undoable step, which Undo takes back and Redo makes again. It is refused while playing, on a locked active layer and on a screen-space one, and for a model that does not load; placing a model in a version 1 scene raises it to the current version, as `PlaceObject` does. ### 3D lights, environment and scene cameras (#895) Version 4 scenes carry their own 3D lighting, environment, and 3D camera objects, edited directly in the 3D viewport and panels: - **Icons and picking**: visible directional, point, and spot lights and 3D cameras draw crisp, color-tinted icons in the 3D viewport overlay instead of generic marker cubes; clicking an icon selects its object (`Pick3D`). - **Interactive undoable handles**: selecting a light or 3D camera reveals wireframe guides and draggable handles (`Handle3DKind`, `HandlePosition3D`, `PickHandle3D`, `BeginHandleDrag3D`, `UpdateHandleDrag3D`, `EndHandleDrag3D`, `CancelHandleDrag3D`): - Directional light: direction arrow and aim handle (`Handle3DLightDirection`). - Point light: three orthogonal range circles and range radius handle (`Handle3DLightRange`). - Spot light: aim handle (`Handle3DLightDirection`), range distance handle (`Handle3DLightRange`), and separate outer (`Handle3DLightOuterCone`) and inner (`Handle3DLightInnerCone`) cone rim handles. - 3D camera: frustum wireframe with vertical FOV / orthographic height handle (`Handle3DCameraFOV`) and far plane handle (`Handle3DCameraFar`). Every drag updates the live GPU viewport in place without rebuilding meshes and commits as one undoable step on `Editor.History`. - **Scene Environment panel (`EnvironmentPanelView`)**: toggled from the 3D viewport bar's **Env** button, `View > Scene Environment`, or `CmdEnvironmentPanel` (`EnvironmentPanelOpen` / `SetEnvironmentPanelOpen`), editing sky (`none`, `color`, `gradient`, `hdr`), ambient color and intensity, IBL intensity, distance and height fog, tonemapping (`none`, `reinhard`, `aces`, `neutral`, `agx`), and exposure through `SetEnvironment` (validated and undoable, upgrading scenes below version 4 to version 4 and restoring the prior version on Undo). - **Inspector and creation helpers**: in 3D view (or on any object with a light or 3D camera), the inspector exposes `LIGHT 3D` (`SetObjectLight`) and `CAMERA 3D` (`SetObjectCamera3D`, switching `current` atomically across cameras in one undo step). In Go, `AddLight3D(kind)` and `AddCamera3D(proj)` place pre-configured lights and 3D cameras on the active world layer, and `ProjectHDRs()` lists `.hdr`/`.pic` skies in the open project. - **Look Through Scene Camera**: press `0`, click **Camera** in the 3D viewport bar, or run `CmdView3DCamera` (`SetLookThroughCamera3D` / `ToggleLookThroughCamera3D`) to view the 3D viewport through the scene's active 3D camera (`ActiveSceneCamera3D`), matching the game's first frame pixel for pixel. Orbiting, panning, zooming, flying, or choosing an axis view exits camera preview cleanly. ### Reflection probes and light probe grids (#903) Version 4 scenes also support local 3D reflection probes (`ObjectDoc.ReflectionProbe`) and 3D light probe grids (`ObjectDoc.LightProbeGrid`) baked directly from the editor so runtime shading in `scenemodel` matches the editor 3D viewport pixel for pixel: - **Placement & inspector**: place probes with `AddReflectionProbe3D` / `AddLightProbeGrid3D` (or command palette `CmdAddReflectionProbe` / `CmdAddLightProbeGrid`) and edit their local box bounds (`center`, `size`), blend distance, intensity, priority, box projection, cubemap resolution, grid counts, and baked file paths in the inspector (`REFLECTION PROBE` via `SetObjectReflectionProbe`, `LIGHT PROBE GRID` via `SetObjectLightProbeGrid`) as undoable steps. - **Viewport icons, wireframes, and 3D bounds handles**: reflection probes draw a cyan chrome-sphere icon, outer influence wireframe box, and inner blend wireframe box; light probe grids draw an amber dot-grid icon, bounds wireframe box, and projected sample points. Selecting either exposes six draggable face-center bounds handles (`Handle3DProbeBoundsPosX`..`Handle3DProbeBoundsNegZ`) that resize the box while anchoring the opposite face, commit as a single undoable step (`EndHandleDrag3D`), and cancel cleanly with Escape (`CancelHandleDrag3D`). - **Baking**: click **Bake Cubemap** / **Bake Probes** in the inspector, **Bake Probes** in the Scene Environment panel, or run `CmdBakeProbes3D` (`BakeReflectionProbe3D`, `BakeLightProbeGrid3D`, `BakeAllProbes3D`). Reflection probes render the 3D scene from the probe origin and write a lossless 6×1 Radiance `.hdr` cubemap strip (`render3d.EncodeCubemapHDR`); light probe grids sample the scene at every grid point and write L2 spherical harmonic irradiance coefficients as deterministic versioned YAML (`*.probes.yaml`, `render3d.EncodeLightProbeGrid`, schema `https://nsgo.games/schemas/lightprobes.v1.json`). Output paths are validated against traversal/symlinks/reserved filenames, written atomically, linked onto the probe undoably, and loaded by `scenemodel.Build` and `scenemodel.Renderer` so game and editor shading match identically. ## Tile palette (#874) While the Paint, Erase, Fill, Pick or Terrain tool is active in 2D, the tile palette shows right of the viewport. It shows the tiles of the active layer's tileset as a grid in tile ID order, each at the tilemap's tile size (a tile wider than the panel is scaled down to fit it). The tiles are the tileset atlas's frames whose names are tile IDs (`"1"`, `"2"`, …), as the scene format looks tiles up; other frames are left out. Pressing a tile, or moving between tiles with the arrow keys, makes it the tile Paint and Fill write (`SetActiveTileID`); every arrow key steps through the tiles in ID order, Left and Up to the previous tile and Right and Down to the next, not by rows of the grid. The selected tile is ringed, and with Paint or Fill the status bar shows its ID. Choosing a tile is not an edit and does not go into the undo history; the paint that follows is one undoable step. The palette follows the active layer: when it changes, the palette shows the new layer's tileset, and if that tileset has no tile with the selected ID, its first tile is selected. A layer with no inline tilemap (none, or an external Tiled or LDtk map), a tileset the resolver cannot resolve and a tileset without tile frames each show a message saying so instead of an empty grid. In Go, `TilePalette()` returns what the palette shows for the active layer: its tileset, tile size and tiles, or the message. For an inline or layered grid naming a `tilesetFile`, the palette shows the tiles of its YAML tileset, read through the resolver's `sceneformat.FileResolver` (such as `FSAssets`), with IDs from 1 as `PaintTile` takes them: tile ID `n` paints the tileset's local tile `n - 1`. The palette's labels and the status bar name each tile by its local ID, the number the rows and the tileset's `tiles[].id` write (`PaletteTile.Number`), and a footer note reminds you that collision, terrain and variant rules live in the tileset file. Above the tiles, a toggle per tile layer (for layered grids) picks the one Paint, Erase, Fill and Terrain change (`SetActiveTileLayer`, `ActiveTileLayer`, the first by default), the H, V and D toggles set the flips Paint and Fill place tiles with (`SetActiveTileFlip`, `ActiveTileFlip`), the terrain toggles pick the terrain set Terrain paints (`SetActiveTerrain`, `ActiveTerrain`), and **Edit Tileset** opens the layer's `*.tileset.yaml` in the Tileset Editor. While a 2D tile tool is active on a YAML tileset layer with no object selected, the right-side **Tile Inspector** shows the picked tile's swatch, display name and source cell, a `COLLISION` toggle (`Solid`, `One-way`, `None`), its terrain/collision/variant-weight rules, and a button to open the full Tileset Editor. The edits write the layer's rows in the form `Encode` saves, one undoable step each, and Fill joins cells whose tile and flips both match. ## Painting, erasing and picking tiles (#875) With Paint or Erase, a drag with the mouse or one finger paints or erases every cell it crosses, however fast it moves, and the whole stroke is one undoable step, so one Undo takes back a row painted in one drag. A click or tap paints or erases its one cell. With Paint, a right-button drag erases. A stroke that starts off the map paints once it reaches it, a stroke that changes nothing records nothing, and a drag with Space held pans the view instead. A second finger cancels a one-finger stroke and puts its cells back, so a two-finger pan never paints. While a tile tool is active, the cell under the mouse is outlined, snapped to the grid: with Paint and Fill it shows the selected tile faded in the cell, with Terrain it shows the autotiled tile faded in emerald, with Erase it is tinted red, and when a press would pick it is outlined in amber. Picking takes the tile in a cell as the tile to paint, and the palette selects it: Alt+click (or Alt+drag) with any tile tool, or the **Pick** tool (`ToolPickTile`, reachable from the tile palette's **Pick** button, `View > Tools > Pick Tile`, or `CmdToolPickTile`), which then hands over to Paint. An empty cell leaves the selected tile as it was. Picking is not an edit and does not go into the undo history. In Go, `BeginTileStroke(mode, x, y)`, `ContinueTileStroke` and `EndTileStroke` draw a stroke (`TileStrokePaint`, `TileStrokeErase`, `TileStrokePick`, `TileStrokeTerrain` or `TileStrokeEraseTerrain`) at canvas points, `CancelTileStroke` puts it back and `TileStrokeActive` reports one under way; painting and erasing refuse locked or hidden layers, and choosing a tool or layer, changing layers, switching views, saving, Undo, Redo and Play end a stroke under way first (while Revert cancels it). `PickTile(layer, col, row)` picks, `SetTileHover` and `ClearTileHover` move the outline and `HoveredTile` returns the cell it is on. ## Terrain painting and tileset editor (#878, #879) Inline and layered tilemaps backed by `*.tileset.yaml` share their tile flags, collision shapes, animations, custom data and autotiled terrain sets between the runtime (`tilemap.ApplyTerrain`, `tilemap.SetTerrainTile`, `physics.MoveAndSlide`, `tileshape.New`) and the editor: - **Terrain brush (`ToolTerrain`, shortcut `t`)**: drags place terrain (`TileStrokeTerrain`) and right-button drags erase terrain (`TileStrokeEraseTerrain`), updating each touched cell and its surrounding neighbors with the exact same 4-bit cardinal (`cardinal`) and 8-bit corner-gated (`blob`) rules as `tilemap.Tilemap.SetAutotile`. The entire stroke — both placed/erased cells and every updated neighbor — is recorded as one undoable step, so one Undo restores the stroke cleanly. In Go, `PaintTerrain(layer, col, row, terrain)` and `EraseTerrain(layer, col, row, terrain)` perform single-cell edits. - **Tileset Editor (`TilesetEditorPanelView`)**: open any `*.tileset.yaml` from the tile palette's **Edit Tileset** button (`OpenActiveLayerTileset`), the Tile Inspector, double-clicking or pressing **Open** / **Edit Tileset** in the file browser (`OpenTilesetProjectFile`), or `OpenTilesetFile` / `OpenTilesetYAML`. The left atlas grid previews every tile with badges for solid/one-way collision, custom shapes, animation, terrain masks and default tiles, while four tabs edit each tile: - **Terrain**: create or delete 4-bit (`cardinal`) and 8-bit (`blob`) terrain sets (`AddTilesetTerrain`, `RemoveTilesetTerrain`, `SetTilesetTerrainMode`), set an explicit fallback default tile (`SetTilesetTerrainDefault`), and assign each tile's neighbor bitmask by clicking its center, edges (`N`, `E`, `S`, `W`) and — in 8-bit `blob` mode — corners (`NW`, `NE`, `SW`, `SE`) (`ToggleTilesetEdgeOrCorner`, `ToggleTilesetTileCenter`, `SetTilesetTileMask`). Corner clicks enforce corner-gating automatically (enabling a corner enables both adjacent edges; clearing an edge clears dependent corners). If an intermediate click matches a mask owned by another tile, the editor leaves that tile intact so you can keep clicking or press **Reassign** (`ReassignTilesetEditMask`). - **Collision**: toggle `Solid`, `One-way`, `None`, or custom flag bits (`SetTilesetTileCollision`, `SetTilesetTileFlags`, `ToggleTilesetTileFlagBit`), and draw rectangular (`rect`) or multi-vertex (`polygon`) collision shapes directly over the magnified tile canvas (`AddTilesetTileShape`, `UpdateTilesetTileShape`, `RemoveTilesetTileShape`, `AddTilesetDraftPolygonPoint`, `CommitTilesetDraftPolygon`). - **Animation**: build and reorder per-tile animation frames with durations (`AddTilesetTileAnimFrame`, `UpdateTilesetTileAnimFrame`, `RemoveTilesetTileAnimFrame`, `SetTilesetTileAnimation`) alongside a live playing/pausable frame preview (`SetTilesetAnimPlaying`, `TilesetAnimPreviewTile`). Animated tiles advance live in the 2D editor viewport as well as in Play mode and the game (`StepTileAnimations`). - **Data**: edit each tile's display `name`, variant `weight`, and typed custom properties (`bool`, `int`, `float`, `string`) (`SetTilesetTileName`, `SetTilesetTileWeight`, `SetTilesetTileProperty`, `DeleteTilesetTileProperty`). - Every tileset edit goes through the editor's `History` (undoable/redoable), takes effect immediately in the viewport, Play mode and Terrain brush before saving, and saves back as canonical YAML (`SaveTileset`, `SaveTilesetYAML`). Agents can read and edit the same fields atomically via the editor MCP tools `tileset_read` and `tileset_edit` ([MCP](http://nsgo.games/docs/mcp/#tools)). ## 3D GridMap painting (#899) In 3D view (`ViewMode3D`), the editor opens and paints modular 3D [`*.gridmap.yaml`](http://nsgo.games/docs/world3d/#modular-3d-gridmap) files directly on an editable floor grid: - **Opening and attaching**: set an object's `gridMap` field in the inspector (`SetObjectGridMap`) or open a `*.gridmap.yaml` file (`OpenGridMap`, `OpenGridMapFS`, `OpenGridMapDoc`, `NewGridMap`). Switching to a GridMap tool in the 3D bottom bar (**Paint**, **Erase**, **Pick**, or **Box**), **View > Tools**, or the Command Palette (`CmdGridMapPaint`, `CmdGridMapErase`, `CmdGridMapPick`, `CmdGridMapBoxFill`) automatically opens the selected object's `gridMap` when none is open yet, and `MoveFile` tracks the open GridMap's path and `meshLibrary` reference. - **Palette with 3D thumbnails**: while a GridMap tool is active in 3D view, `GridMapPaletteView` (`GridMapPalette()`) appears right of the viewport, rendering an isometric shaded 3D thumbnail for every tile in the glTF `meshLibrary` alongside controls for the active floor height and 24-orientation index. - **Floor height and 24 orientations**: press `]` / `PageUp` and `[` / `PageDown` (`SetGridMapFloor`, `StepGridMapFloor`) to move the active horizontal painting plane up or down by one cell. Press `X`, `Y`, `Z` (with `Shift` for reverse) or `Q` / `Shift+Q` (`RotateGridMapOrientation`, `StepGridMapOrientation`, `SetGridMapOrientation`) to rotate the active tile through all 24 axis-aligned cube orientations (`world3d.RotateGridOrientation`). - **Painting, erasing, picking and box fill**: hovering in the 3D viewport projects the pointer ray onto the active floor (`ScreenToGridMapCell`) and draws a live hovered cell preview (and a dashed rectangular preview while dragging **Box** fill). Clicking or dragging paints or erases every cell crossed as a single undoable stroke (`BeginGridMapStroke`, `ContinueGridMapStroke`, `EndGridMapStroke`, `CancelGridMapStroke`, `Escape` cancels), **Pick** (or Alt+click) adopts the tile and orientation under the pointer, and **Box** drags out a filled rectangle on the active floor (`FillGridMapBox`). - **Undo and canonical save**: every paint stroke, erase stroke, box fill, and cell rotation (`PaintGridMapCell`, `EraseGridMapCell`, `FillGridMapBox`, `RotateGridMapCell`) goes through the editor's shared `History` (Undo/Redo). `Save` (`SaveGridMap`, `SaveGridMapFile`) writes canonical deterministic `.gridmap.yaml` via `world3d.GridMap.ToDoc` and `world3d.EncodeGridMap`, so saved files round-trip byte-for-byte and instance identically in `scenemodel.Build`. ## Rectangle, line, stamp and random tile brushes (#876) Four additional tile brushes extend inline and layered tilemap painting, each showing a live preview in the 2D viewport before release, cancelling cleanly on **Escape** (or a second touch) without mutating the scene, and committing every changed cell as **one undoable step** in `Editor.History`: - **Rectangle (`ToolRectTile`, shortcut `u`)**: drag between two cells to fill the rectangle with `ActiveTileID` (`TileStrokeRect`, `FillTileRect`), or right-drag to erase the dragged rectangle (`TileStrokeRectErase`, `EraseTileRect`). - **Line (`ToolLineTile`, shortcut `l`)**: drag between two cells to draw a Bresenham line of `ActiveTileID` (`TileStrokeLine`, `DrawTileLine`), or right-drag to erase along the line (`TileStrokeLineErase`, `EraseTileLine`). - **Stamp and region clipboard (`ToolStampTile`, shortcut `c`)**: paint a rectangular `TileStamp` pattern anchored to the click or pattern-aligned across a drag (`TileStrokeStamp`, `StampTiles`), preserving per-cell flip bits on layered tilemaps and empty (`0`) cells from copied regions. Build a stamp either by selecting a rectangle of tiles in the tile palette (`SelectPaletteStamp`, `SelectPaletteStampRange`, or clicking an anchor tile and pressing **Rect** or holding Shift before clicking the opposite corner) or by right-dragging a map region (`TileStrokeSelectRegion`, `SetTileSelection`) and using **Copy** (`mod+c`, `CopyTileRegion`, `CopySelectedTileRegion`), **Cut** (`mod+x`, `CutTileRegion`, `CutSelectedTileRegion`, one undo step) and **Paste** (`mod+v`, `PasteTileRegion`). - **Random (`ToolRandomTile`, shortcut `n`)**: paint a deterministic weighted pick from multiple tiles (`SetRandomBrushTiles`, `SetRandomBrushTileWeight`, `ToggleRandomBrushTile`) controlled by a fixed seed (`SetRandomBrushSeed`, `RandomBrushSeed`). In the tile palette, clicking tiles toggles them in the weighted pool with per-tile `-`/`+` weight controls and a Seed field; right-drag erases. In Go, `TilePreview()` inspects the live preview cells of an in-progress brush stroke before `EndTileStroke`, `TileStamp` / `TileClipboard` / `TileSelection` manage patterns and regions, and all four brushes work identically on single-grid and layered YAML tilemaps while keeping deterministic YAML round-trip saves. ## Agent tile tools and region-based tile edit review (#1064) Coding agents connected to the editor's MCP server ([MCP](http://nsgo.games/docs/mcp/#tools)) can inspect and paint inline and layered tilemaps while the author reviews changes by connected region rather than individual cells: - **Query and paint tools**: `tile_query` (`Editor.QueryTiles`) finds matching cells or empty pockets by tile ID, YAML tileset `tileName`, or sub-rectangle (for example, `"an 11 × 5 pocket at columns 2–12, rows 12–16"`). `tile_paint` (`Editor.AgentPaintTiles`) paints explicit cells, inclusive rectangles, or deterministic seeded weighted tile picks (with optional `noAdjacentDuplicates`). `tile_autotile` (`Editor.AgentAutotile`) re-edges or places a YAML tileset terrain set using the same 4-bit `cardinal` / 8-bit `blob` rules as `ToolTerrain`. `tile_erase` (`Editor.AgentEraseTiles`) clears cells or rectangles. Each call applies as one undoable edit and joins the active tile review by default (`review: true`). - **Region-based review (`TileReviewPanelView`)**: pending agent changes are grouped into connected regions by kind — **painted** (`+`, green dashed outline), **replaced** (`~`, amber dashed outline), and **erased** (`−`, red solid outline) — each showing its cell count, bounding rect, and human-readable detail (such as `"from 4 cave tiles"`). Clicking a region focuses it in the 2D viewport; each region can be independently toggled between **Revert** and **Restore** (`SetTileReviewRegionReverted`, `ToggleTileReviewRegion`). **Before / After** and **hold `B`** (`SetTileReviewViewMode`, `SetTileReviewPeekBefore`, `TileReviewHandleKeyEvent`) preview the pre-review tilemap live. **Keep N of M** (`KeepTileReview`) commits all kept regions cleanly as **one** undoable `History` step (so one Undo restores the exact pre-review tilemap), and **Revert all** (`RevertAllTileReview`) restores the original tilemap immediately. Agents and tests can also drive reviews via `tile_review_status`, `tile_review_revert_region`, `tile_review_restore_region`, `tile_review_keep`, and `tile_review_revert_all`. - **Palette & viewport caption**: while a tile layer is selected in 2D, the viewport shows a top-left layer dimension caption (`ActiveTileLayerCaption`, e.g., `World · 24 × 20 cells · 16 px`), and the tile palette displays `TILESET ` with a selected-tile readout showing the picked tile's swatch, name, atlas cell coordinates, collision rule, and terrain set. ## Scene tree (#861) The scene tree panel (`SceneTreeView`), at the left of the editor, lists the open scene's layers and, under each, its objects with their children nested. It follows every edit and every undo. Pressing an object's row selects it, and selecting an object in either viewport selects its row and opens the rows above it; pressing a layer's row makes it the active layer. Every object edit works on a nested child as on a top-level object: `FindObject` and `SelectObject` find an object by ID anywhere in the tree, the inspector edits the selected child, and its transform is edited in its parent's space, so the Move tool puts its origin under the press and the 3D gizmo moves it along the world axis. - **Moving in the tree**: drag a row onto another to make it that object's last child, or near the top or bottom edge of the row to put it before or after it; drop it on a layer's row to move it to the top level of that layer. A row's context menu moves it up or down among its siblings, makes it a child of the sibling above, moves it out of its parent, or moves it to another layer. In Go, `ReparentObject(id, parentID, index)`, `MoveObjectToLayer(id, layer, index)`, `ReorderObject(id, index)` and `DropObject(id, targetID, place)` do the same, each as one undoable step; an index below 0 or past the end puts the object last. - **World transform**: a moved object keeps its world transform. Its local transform is computed again under its new parent in 2D (`x`, `y`, `rotation`, `scaleX`, `scaleY`), and Undo puts every field back exactly; a flipped object keeps its negative scale on the axis it had. When the object or one of its old or new ancestors sets a 3D field, its depth (`posZ`, `scaleZ`) is kept too. When one of them sets a 3D rotation (`rotX`, `rotY`, `rotZ`), the 2D and 3D views no longer agree on where `x` and `y` lead, and only the 3D world transform is kept: the object stays in place in the 3D viewport, and may move in the 2D one. The move is refused when it would put an object under itself or one of its descendants, nest deeper than `MaxObjectDepth`, or leave a transform that cannot be written as a translation, rotation and scale under the new parent, as a sprite under a turned parent stretched along one axis would be. A move between a world and a screen layer keeps the numbers, not where the object appears on screen. - **Rename**: F2, a double press or the context menu's Rename edits the selected object's name in its row; Return or leaving the field keeps it, and Escape drops it. Change ID edits its ID through `SetObjectID(oldID, newID)`, which rewrites the scene's connections that name the object, and the objects of a scene it instances (`enemy_1/body` becomes `boss/body`), in the same step, as well as the open animation clip's target and the targets of its tracks, and refuses an ID the scene already uses, including one an instanced or inherited scene adds. Another scene file that instances or inherits this one and overrides the object by its old ID is not rewritten; move such references with `game mv` or edit them by hand. - **Eye and lock**: the eye button of a row hides the object, and with it its descendants, in both viewports, and the lock button stops a press in either viewport from picking it, so the press reaches what lies under it (`SetObjectHidden`, `SetObjectLocked`). Neither viewport moves a hidden or locked object: its 3D gizmo is not shown and the Move tool leaves it where it is. Both belong to the editing session: they are not edits, Undo does not touch them, they are never written to the scene file, Play draws every object, and opening another scene clears them. A hidden or locked object can still be selected from the tree and edited in the inspector. The 3D viewport draws and picks every object, nested children included: `Objects3D` lists them depth first, each with its parent's ID, and a child's geometry and box are placed by its ancestors' transforms ([3D viewport](http://nsgo.games/docs/editor/#3d-viewport-890)). ### Object context menu (#1039) Secondary-clicking or Control-clicking an object in the 2D viewport, the 3D viewport, or a Scene Tree row—or pressing `Shift+F10` or the Context Menu key (`contextmenu`) on the active selection—opens a unified `ui.ContextMenu` headered with the object's display name and kind/layer subtitle (for example, `Sprite · layer actors`). Right-dragging in the 3D viewport still flies the camera, right-dragging with 2D tile tools still erases or selects a tile region, and right-clicking a polygon collider vertex still removes that vertex; actions whose feature does not apply to the target object or session are omitted rather than shown disabled. - **Copy as YAML (`mod+c`) and Paste (`mod+v`)**: `CopyObjectYAML` / `CopySelectedYAML` (`ObjectYAML`) encodes the object as a canonical `sceneformat` YAML document onto the clipboard (`core.Scope.SetClipboard` or `Editor.WriteClipboard`) that `sceneformat.Parse` round-trips back to the exact same object, and shows a floating viewport toast (`Copied as YAML · N lines`). `Paste` / `PasteObjectYAML` pastes from the clipboard onto the active layer with a fresh unique ID in one undo step. - **Duplicate (`mod+d`) and Group (`mod+g`)**: `DuplicateObjects` clones the selected object(s), and `GroupObjects` / `GroupSelected` wraps them under a new parent object in one undo step while preserving world transforms. - **Move under**: the submenu (`MoveUnderCandidates`, `MoveObjectUnder`) lists valid candidate parent objects—excluding the object itself, its descendants, and moves that would exceed `MaxObjectDepth`—annotated with current parent, locked state, child count, or layer, and reparents in one undo step so a single Undo puts the object back. - **Select same prefab**: when the object sets `prefab` or `scene`, `SelectSamePrefab` selects every object in the scene sharing that reference (`SelectedIDs`, `SelectObjects`, `IsObjectSelected`). - **Hide / Show (`h`), Lock / Unlock, Find usages (`shift+f12`), Rename (`f2`), and Ask the agent (`mod+l`)**: toggle session visibility (`ToggleObjectHidden`) and lock (`ToggleObjectLocked`), find usages in the open project (`FindObjectUsages` / `ShowObjectUsages`, opening the Find Usages review screen for scene/prefab-path targets or Search for plain IDs, omitted without an open project), start inline renaming in the Scene Tree (`RequestRenameObject`), or send an `AgentPromptRequest` draft to `Editor.OnAskAgent` (`AskAgentAboutObject`). Context menus read live custom shortcuts (`EffectiveShortcut`), expose scene-instance and inherited-object override actions (`Open Instanced Scene`, `Make Local`, `Apply Overrides to Source`, `Open Source Scene`, `Revert Overrides`) while guarding local-only structural edits on foreign objects, and retain Scene Tree order, Cut, Paste as Child, Ungroup, Change ID, Move to Layer, and Delete actions. - **MCP parity (`pkg/editor/editormcp`)**: every context menu action calls an exported `Editor` method that the editor MCP server exposes (`object_copy_yaml`, `object_paste_yaml`, `object_duplicate`, `object_group`, `object_move_under`, `object_select_same_prefab`, `object_visibility`, and `object_find_usages`, alongside `scene_edit` and `selection_get`'s `selectedIds`). The edit tools among them take the objects they edit from `id` / `ids` or, inside an agent turn, from the selection the request pinned, never from the live selection ([mcp](http://nsgo.games/docs/mcp/#edit-targets)). ### Multi-object selection and batch editing (#867) The editor tracks an ordered selection set with `Editor.SelectedID` as the primary object (`SelectedIDs`, `SelectionCount`, `IsSelected`, `SelectedObjects`, `SelectObjectsWithPrimary`, `AddToSelection`, `RemoveFromSelection`, `ToggleSelection`, `ClearSelection`): - **Viewport selection and marquee**: In 2D and 3D, `Shift`+click adds an object to the selection and `Mod` (`Cmd`/`Ctrl`)+click toggles membership (`HandleCanvasPressWith`, `HandleViewport3DPressWith`). In 2D with Select, dragging on empty canvas draws a marquee box (`BeginMarquee2DWith`, `UpdateMarquee2D`, `EndMarquee2D`, `CancelMarquee2D`, `SelectMarquee2D`) that selects enclosed objects by default, or touching objects when `Alt` is held (`MarqueeEnclose`, `MarqueeTouch`); `Shift` adds and `Mod` toggles marquee matches. `Escape` cancels an active drag or marquee first, and clears selection at rest. - **Scene tree synchronization**: `SceneTreeView` follows and drives the same multi-selection set with `Shift`+click and `Mod`+click, expanding ancestors of selected objects. - **Common-center transforms, Delete and Duplicate**: Move, rotate, and scale gizmos in both 2D and 3D act on the whole selection about its combined bounding-box center (filtering out descendants whose ancestor is also selected so children never double-transform), and `DeleteSelected` / `DuplicateSelected` act on the whole selection; each operation records **one undo step** via `History.Group`. `FrameSelection` frames all selected objects together. - **Shared-field inspector**: When multiple objects are selected, `InspectorView` shows `"N selected"` and only the sections shared by every selected object (Transform, Sprite when all have sprites, shared Properties and shared Components). Differing values display as `"Mixed"` (or indeterminate for checkboxes), and editing any field writes every selected object in **one undo step** (`EditSelected`, `SetSelectedComponentField`, `SetSelectedProperty`, `SetSelectedX`, …) so a single Undo restores each object's own prior value. ### Copy, paste, duplicate and group objects (#868) The scene tree supports multi-object selection (`SelectObjects`, `SelectedIDs`, `ToggleSelectObject`, `IsObjectSelected`), and object clipboard, duplication, and grouping actions live in the Edit menu, Scene Tree context menu, Command Palette, and keyboard shortcuts: - **Copy (`mod+c`, `CopyObjects`, `CopySelected`) and Cut (`mod+x`, `CutObjects`, `CutSelected`)**: serialize the selected object(s) — including nested children, components, properties, `overrides`, and every connection whose endpoints both belong to the copied subtrees — as canonical `sceneformat` YAML onto the system clipboard (`core.Scope.SetClipboard`, or the injectable `Editor.WriteClipboard` hook), so they paste into another scene or a text editor. Cut removes the originals and their connections in one undoable step. When a 2D tile region selection is active under a tile tool, `mod+c` and `mod+x` continue to copy or cut the tile region instead. - **Paste (`mod+v`, `Paste`, `PasteWith`, `PasteYAML`, `PasteYAMLWith`) and Paste as Child (`mod+shift+v`, `PasteInto`)**: parse scene-format YAML from the system clipboard (`core.Scope.ReadClipboard` / `Editor.ReadClipboard`) and place the objects on `ActiveLayer` (or under `ParentID`) at the hovered viewport pointer (`SetViewportPointer2D` / `SetViewportPointer3D`) or offset next to originals when IDs are already taken in the scene. Original IDs are kept when unused in the target scene and allocated fresh unique IDs when taken, rewriting internal connections and scene overrides (including instanced `"enemy_1/body"` paths) to the new IDs and clearing duplicate `current` flags on pasted 3D cameras. Every paste runs `PlaceObject`'s checks (`sceneformat.Validate`, `ValidateComponents`, `ValidateConnections`, `ValidatePhysicsLayers`, and `Resolve` for instanced scenes) and commits as **one undo step**; unparseable or invalid YAML is refused in the status bar without modifying the scene or history. - **Duplicate (`mod+d`, `DuplicateObject`, `DuplicateObjects`, `DuplicateSelected`, `DuplicateSelectedObjects`)**: clones the selected object(s) next to the originals on the same layer and parent in **one undo step**, allocating unique IDs and rewriting internal connections and overrides to the copies without overwriting the system clipboard. - **Group (`mod+g`, `GroupObjects`, `GroupSelected`) and Ungroup (`mod+shift+g`, `UngroupObject`, `UngroupSelected`)**: Group wraps the selection under a new empty parent placed at their common 2D/3D world centre without moving any object on screen (converting child local transforms via `keepWorldTransform`), in **one undo step**. Ungroup lifts direct children out into the parent's slot while preserving their world transforms in **one undo step**, removing an empty unconnected group container automatically while keeping non-empty parents intact. ## 3D navigation mesh baking (#901) In 3D view mode, the editor can bake a 3D navigation mesh directly from the open scene's static geometry (`navbake3d`) and preview it over the 3D viewport: - **NavMesh bake panel** (`NavMeshPanelView`, toggled by **View > 3D NavMesh Bake...**, the Command Palette `CmdNavMeshPanel`, or `SetNavMeshPanelOpen`): configures the agent name, radius, height, step height (`MaxClimb`), maximum walkable slope (`MaxSlope`), voxel cell size (`CellSize`), cell height (`CellHeight`), and output `.navmesh.yaml` path (`NavMeshBakeConfig` / `SetNavMeshBakeConfig`). When a project with a `navigation` section is opened, the panel seeds its defaults from `game.yaml`. - **Baking and scene link** (**Bake** button, `CmdBakeNavMesh3D`, or `BakeNavMesh3D`): collects static 3D geometry from the open scene's glTF models (including `modelNode` and `modelMesh`), built-in `mesh` primitives, static non-trigger `collider3d` shapes (skipping dynamic/kinematic `body3d` objects, triggers, and screen-space layers), plus any extra terrain heightmaps, `GridMap`s, or physics colliders supplied by `Editor.OnBakeNavMesh3DGeometry`. Writes a deterministic, byte-identical `.navmesh.yaml` atomically, updates `SceneDoc.NavMesh` as one undoable step (`SetSceneNavMesh`, also editable in the Scene Settings inspector), and loads the baked mesh for immediate viewport preview. Reopening a scene whose `navMesh` file exists on disk automatically loads it (`LoadNavMesh3D`). - **3D viewport overlay** (3D viewport bar **Overlays** popover, **Overlay** panel switch, **View > Show 3D NavMesh**, Command Palette `CmdNavMeshOverlay`, or `ShowNavMesh3D` / `SetShowNavMesh3D`): draws translucent cyan walkable polygons, detail edges, and crisp polygon boundary outlines over the 3D scene viewport through `Camera3D`. ## Scene tabs, scene files and unsaved changes (#866, #873) The editor keeps each open scene in its own tab in the tab bar above the viewport (`SceneTabsView`), so an author can edit an instanced or base scene beside the level that uses it without losing undo history: - **Per-tab state**: each tab (`Tabs`, `ActiveTab`, `TabCount`, `SelectTab`, `SelectTabByID`) keeps its own `SceneDoc`, `BuiltScene`, `History`, selection (`SelectedID`), active layer and tile selection, 2D and 3D view transforms (`View2D`, `Camera3D`), scene-tree visibility/lock session flags, `OnSave` callback, and dirty marker (`TabDirty`). Switching tabs never clears any tab's undo history; undoing in one tab never changes another. - **Opening and deduplicating tabs**: opening a scene from the file browser (a `*.scene.yaml` or `*.scene.yml` file, or one listed under `autoload.scenes`), the Problems panel, the Search and References panel, the Command Palette, `NewScene`, `OpenScene`, or `OpenFile` opens a new tab (replacing an untouched initial untitled tab) or switches to the existing tab when that scene is already open. **Open Instanced Scene** (`OpenInstancedScene`, available in the inspector for an instancing object, the scene tree context menu, the File menu, and the Command Palette) and **Open Base Scene** (`OpenBaseScene`, available in the Scene Settings inspector for an inheriting scene, the File menu, and the Command Palette) open the referenced scene in a tab or switch to it when already open. - **Live instance and inheritance updates on save**: saving a scene (`Save`, `SaveFile`, `SaveSceneAs`, `SaveTab`, `SaveAll`) rebuilds every other open tab that instances or inherits scenes (`BuiltScene` and `Scene3D`), so instances and inherited objects show the change immediately without reopening those tabs. `MoveFile` rewrites paths and references across every open tab. - **Shared project, plugins, Play, and closing tabs**: the project file (`game.yaml`), plugins, and Play mode stay shared across tabs, with plugins and Play acting on the active tab (tab switching and closing are disabled while Play runs). Closing a clean tab (`CloseTab`, `RequestCloseTab`, `CmdCloseTab` / `mod+w`, or the tab's close button) closes it immediately; closing a dirty tab prompts to Save (saving only that tab and rebuilding dependent tabs), Discard (discarding only that tab while keeping shared project edits intact), or Cancel. Closing the last remaining tab replaces it with a clean untitled scene. The header bar's scene File menu (`toolbar-file`) holds New Scene, which writes a minimal valid scene (named after its file, as large as the project's display or window, with one world layer) to a path from the project's root (`NewScene`), Save, Save As, which saves the active scene under another path and makes that file the tab's (`SaveSceneAs`), Revert, which puts back the active scene as its file holds it (`RevertScene`), Open Instanced Scene, Open Base Scene, Settings, and Close Tab. A path without a `.yaml` or `.yml` extension gets `.scene.yaml` (one ending in `.scene` gets `.yaml`), the name `game check` and `game index` find scenes by. Neither New Scene nor Save As overwrites another file or writes a scene under the project's own file names, `game.yaml` and `nsgo.yaml`. Revert is one undoable step, so Undo brings the reverted edits back. `SceneDirty` reports whether the active scene differs from what it was opened from or last saved to, comparing encodings as `ProjectDirty` does for `game.yaml` and `ClipDirty` does for the open animation clip, so undoing back to the saved state makes the scene, project or clip clean again; `TabDirty` checks a specific tab and `AnySceneDirty` reports whether any open tab is dirty. A `MoveFile` that rewrites an open scene's file leaves it as clean or dirty as it was; one that rewrites references in an open scene but not in its file, as for a scene `game mv` does not read (no `.scene.yaml` name and nothing names it), leaves the scene dirty so that saving it keeps the new paths. Each dirty tab displays a `*` marker, the header bar shows the active scene's breadcrumb and an unsaved dot (`toolbar-unsaved`) while any open tab, the project, open clip or another auxiliary document has unsaved edits (`HasUnsavedChanges`), and the window title follows (`WindowTitle`). `EditorView` owns the window title, so an editor built on the package, such as a game's own, names itself with `Editor.AppName` rather than setting the title, and the title ends with that name ("NSGo Scene Editor" while it is empty). **File > Save** in the header or desktop menu bar, the Command Palette's Save, and Mod+S (`Save`, the `CmdSave` command) save what was edited in the active scene and the shared project; an unedited file is left as written, comments included. Switching projects (`RequestOpenProject`), quitting the editor, and closing its window ask first while any open tab, the project or open clip has unsaved edits: Save saves all dirty tabs and the project (`SaveAll`) and goes on, Discard drops them and goes on, and Cancel keeps them and stays. Discarding the project's edits puts back what follows from the project, as undoing them does: an audition through an audio bus the edits added stops, for example. A forced quit, as at logout, cannot wait for an answer and does not ask. ### Reloading files changed on disk and save conflict guard (#906) While a UI scope is attached, the editor watches the open scene (`FilePath`), the open animation clip (`ClipPath`), `game.yaml` (`ProjectPath`) and the project directory tree (`DiskWatchInterval`, default 250ms; `PollDiskChanges` performs an immediate check in Go): - **Clean files reload automatically**: when an open scene, clip or `game.yaml` changes on disk without unsaved edits, the editor reloads it automatically as one undoable `History` step (batching multi-file git branch switches such as `Switched branch · main → boss-room · 2 files`), updates the saved snapshot so the file stays clean, and shows a dismissible reload notice (`DiskReloadNotice`) with object-level diff details (**Show diff**). - **Dirty files never reload under the author**: when an open file with unsaved edits changes on disk, the editor keeps the in-memory edits intact and shows an external-change conflict bar (`DiskConflicts`, `PrimaryDiskConflict`) offering **Reload from disk** (`ReloadFromDisk`, keeping the author's edits in `History` as `"Unsaved edits before reload"`), **Keep mine** (`KeepLocalVersion`, keeping the disk version in `History` as `"Changed outside the editor"` and acknowledging the disk snapshot so a subsequent Save succeeds), and for scenes **Compare** (`SetDiskCompareOpen`, `SetSceneConflictChoice`, `ApplySceneConflictMerge`) to pick **Mine** or **Disk** per overlapping object while taking single-side changes automatically. - **Save conflict guard**: `Save`, `SaveFile`, `SaveProject` and `SaveClipFile` compare the on-disk SHA-256 snapshot recorded at open or last save before writing and refuse to overwrite externally modified files with `ErrDiskConflict` (`*DiskConflictError`). In `EditorView`, hitting a conflict opens a confirmation dialog (**Cancel**, **Reload from disk**, or **Overwrite** via `ConfirmOverwriteSave` / `ForceSave`). - On Windows, the editor retries a save briefly if replacing the file fails with a sharing or access error. If it still cannot replace the file, the previous contents stay on disk and the editor reports the save error. - **Automatic file browser refresh**: adding, removing or renaming files in the open project directory automatically updates the file browser (`FilesView`) and invalidates the project index and Problems check without pressing Refresh. ## Layers panel (#862) The layers panel (`LayersView`), under the scene tree, lists the open scene's layers in draw order, the first drawn at the top, each with its space (`world` or `screen`) and its tilemap: the tileset and size of an inline grid (`tiles 16x12`), the name of the top-level tilemap it refers to, or the path of an external Tiled map. Pressing a layer's row makes it the active layer, which the Place tool and the tile tools work on, the tile palette shows and the status bar names, with `hidden` and `locked` after it when they apply; pressing a layer's row in the scene tree does the same. In Go, `Layers()` returns what the panel shows. - **Add and remove**: the + button adds a world layer named `layer_N` that draws over every other layer and makes it active (`AddLayer(name, space)`, which takes the highest order of the layers the scene draws, those of a scene it inherits included, and puts the layer last in the file). The bin button removes the active layer (`RemoveLayer(name)`), with its objects and tilemap and with the scene's connections from or to its objects; Undo puts all of them back where they were, and the scene is saved byte for byte as before. When the active layer is removed, the layer that takes its place in the file, or the one before it, becomes active. - **Rename**: a double press or the context menu's Rename edits the name in the row; Return or leaving the field keeps it, and Escape drops it (`RenameLayer(oldName, newName)`). An empty name and one another layer has are refused. The active layer and the layer's lock follow the new name. - **Order**: drag a row onto the top or bottom half of another to put the layer before or after it, or use the context menu's Move Layer Up and Move Layer Down (`MoveLayer(name, index)`, where index is the position in the draw order). The layer moves in the file next to the layer it is to draw after or before, and its `order` changes only when the value it has would not draw it there, to that neighbour's value; the other layers keep their place and their orders. - **Space**: the context menu's World Space and Screen Space set the layer's `space` (`SetLayerSpace(name, space)`); its objects keep their coordinates. - **Visibility**: the eye button hides or shows the layer by writing its `visible` field (`SetLayerVisible(name, visible)`). Hiding writes `visible: false`; showing leaves the field unset, its default, so hiding and showing a layer gives back the same file. This is the scene's own setting, which the game reads too, and an undoable edit. A hidden layer is not picked in either viewport, and its objects are not moved there even when they are selected (no 3D gizmo, no Move-tool drag), as for an object hidden in the scene tree. - **Lock**: the lock button locks the layer against the viewports for the session (`SetLayerLocked(name, locked)`): a press passes over its objects to what lies under them, its objects are not moved there (no 3D gizmo, no Move-tool drag), and the Place, Paint, Erase and Fill tools change nothing while it is the active layer and say so in the status bar. Like the scene tree's object lock, it is not an edit, is not undone, is never written to the scene file, and opening another scene clears it; the panels and the inspector still edit the layer and its objects. In a scene that inherits another (`inherits`), a layer named like one of the base's extends it: its name and draw order belong to the base scene, so renaming or moving it, renaming a layer to a base layer's name, and adding one with a base layer's name are refused, while hiding it, changing its space, or editing its parallax and repeat records undoable entries under `layerOverrides` (with per-field Revert and Revert All in the inspector and layer context menu), and removing it removes only the objects the scene adds to it. Other scene files that inherit the open one and name its layers are not rewritten by a rename. Every layer edit that would leave a scene that does not validate, or does not resolve with the scenes it instances or inherits, is refused before it reaches the history. ## Animation editor The editor's animation panel keys any registered property on a timeline and saves the clip as an [`animation` resource file](http://nsgo.games/docs/resources/#animation), played in the game by [animclip](http://nsgo.games/docs/animclip/) (an AnimationPlayer equivalent). The panel shows below the viewport while a clip is open. - **Opening a clip**: the Command Palette's **Animate** command (`CmdAnimate`) starts a new one-second clip on the selected object. In Go, `NewClip(target, name, length)` does the same, `NewClipFromAsepriteTag(target, tag)` builds a clip matching an Aseprite tag's frames, exact durations and loop setting from the target object's atlas, `NewClipFromFrames(target, name, frames, fps, loop)` builds a flipbook clip from a run of atlas frames at a fixed frame rate, `OpenClipFile(path, target)` and `OpenClipYAML(data, target)` open a clip file, checked against the component registry (a misspelled property fails to open with the file name), and `CloseClip` closes it. The panel's Flipbook row also lets you pick an Aseprite tag (From Tag) or a frame rate (From Frames) directly when the target object has a sprite atlas. `go tool game editor scene.yaml clip.animation.yaml [object-id]` opens a scene and selects the object `object-id` (the scene's first object when it is left out), opens the clip on it when the file exists, and the panel's Save Clip button writes that file. - **Keying**: pick a property (an object field such as `x`, `alpha` or `sprite.frame`, or a registered component field such as `body.speed`) and press Key to key the value it has in the scene at the playhead; `KeyProperty(target, property, at)` does the same. Choosing `sprite.frame` reveals a frame picker listing the target object's atlas frames (`ClipTargetFrames`) so you can key any frame directly (`KeySpriteFrame(target, frame, at)`). With another object selected, the key goes to a track that targets it. A track that names the clip's own object is the same track as one with an empty target, and a clip with two tracks driving the same property of one object is refused. A bool key holds its value until the next key, and `sprite.frame` always steps discretely without interpolation. - **Editing keys**: each track is a lane of its keys; a `sprite.frame` track displays each keyed frame as a thumbnail cell spanning its duration (`ClipFrameEntry`). Press a key to select it and move the playhead to it, then edit its time and value/interpolation (`linear`, `smooth` or `step`) for numeric tracks, or its atlas frame (`SetKeyFrame`) and duration (`-10ms` / `+10ms`, `FrameDuration`, `SetFrameDuration`) for `sprite.frame` tracks, or delete it; `SetKeyValue`, `MoveKey`, `SetKeyInterp`, `DeleteKey` and `RemoveClipTrack` do the same in Go. Values are checked against the property: 0 or 1 for a bool, a whole number for an int, inside the field's range, and a frame name present in the target's atlas for `sprite.frame`. - **Clip settings and events**: the panel edits the clip's name, length and loop (`SetClipName`, `SetClipLength`, `SetClipLoop`), and adds named events at the playhead (`AddClipEvent`, `DeleteClipEvent`). - **Scrubbing and preview**: the scrubber moves the playhead (`SeekClip`; at the end of a looping clip it shows the last keys) and Play plays the clip on a `game.Loop` (`PlayClip`, `PauseClip`, or `StepClip` to step it by hand). The viewport, in 2D and 3D, then shows a copy of the scene posed by the clip with the same `animclip.Player` and `BindScene` the game uses, so the scene being edited never takes animated values and a clip plays the same in the game. A clip the scene cannot play, such as one whose track targets a deleted object, stays open and `ClipError` says why. Asynchronous clip loaders can toggle the panel's loading card with `ClipLoading` / `SetClipLoading`. - **Undo**: every clip edit, opening and closing included, goes through the same undo/redo history as scene edits. `SaveClipYAML` and `SaveClipFile` write deterministic YAML, so a clip that is opened and saved again does not change. ### Sprite state machine graph (#1054) Opening a `*.states.yaml` file (from the file browser, command palette, or `OpenStatesFile` / `OpenStatesYAML` / `OpenStatesProjectFile`) opens the **State Machine** graph panel below the viewport: - **Graph and active state**: every state appears as a node card showing its name, clip metadata (frame count, frame duration, loop/once) and sprite thumbnail, with directed labelled transition edges and an `Any state` wildcard badge. During preview, the active state node highlights live and the preview card renders the active clip frame. - **Drive with keys**: toggling **Drive with keys** binds the preview to the project's input actions (such as `move_left`, `move_right`, `jump`, `attack`, `hurt`) through the same `animclip.InputDriver` and `animclip.StateMachine` the game uses, advancing on fixed steps on `game.Loop` so interactive preview and runtime playback match frame for frame. - **Outgoing transitions (`LEAVING `)**: selecting any state displays its outgoing transitions (including `Any state` interrupts) and their conditions, and graph edits (`AddStatesState`, `RemoveStatesState`, `AddStatesTransition`, `RemoveStatesTransition`, `SetStatesEntry`, `SetStatesNodePos`, `SetStatesDoc`) go through the editor's undo/redo history and save back to deterministic canonical YAML (`SaveStatesYAML` / `SaveStatesFile`). ## Mods, plugins and packs (#1268) The engine has three ways to extend a game, and they are not interchangeable: | | Editor (Go) plugin | Script mod | Library pack | | --- | --- | --- | --- | | Written in | Go | TSX | YAML and media | | Who writes it | the game's developers, third-party tool authors | players | anyone | | When it loads | compiled into the editor binary | at run time, with hot reload (`Manager.Reload`) | installed into the project | | Trust | full | sandboxed, capability-gated | carries no code | | Platforms | all, iOS and the web included | native; the web only with `ManagerOptions.WebUnisolated` | all | | Extends the editor | yes | no (today) | turns on built-in plugins only | An editor plugin is an `editor.Plugin` the editor binary registers with `Editor.RegisterPlugin` and a project turns on by name under `editor.plugins` in `game.yaml`, as the next section describes. A script mod is a `mod.yaml` manifest plus a TSX entry script that `modding.Manager` runs in a sandbox limited to the capabilities the manifest asks for and the host grants; see [modding](http://nsgo.games/docs/modding/). A library pack is a set of files `library.Install` writes into the project and records in `game.yaml`; see [Asset and Plugin Library](http://nsgo.games/docs/library/). A pack may not hold Go source or module files (`.go`, `go.mod` and the like are refused), so a plugin pack only turns on editor plugins the editor binary was already built with — it never ships their code. Which one do you need? - A new panel, inspector, viewport tool or 3D gizmo in the editor, or component types the editor checks scenes against: an editor plugin, below. - Let players change the shipped game, within limits the game sets: a script mod. - Share sprites, scenes, sounds or a starter template: a library pack. A Go plugin is compiled into the binary rather than loaded at run time because Go has no portable way to load code on every platform — iOS and the web cannot load native code at run time — so a plugin ships inside the editor command it extends. ## Editor plugins (#492, #898) A plugin extends the scene editor with its own panels, an inspector for its own component types, 2D and 3D viewport tools, and per-component 3D gizmos. Go cannot load code at run time on every platform, so a plugin is Go code built into the editor binary: the binary registers it with `Editor.RegisterPlugin`, and a project turns it on by naming it in its [project file](http://nsgo.games/docs/project/): ```yaml editor: plugins: [health] ``` A registered plugin the open project does not name stays off, and the order of `editor.plugins` is the order its panels and tools appear in. `OpenProject` names in the status bar the plugins the project lists that this binary was built without (`MissingPlugins`). `go tool game editor` registers no plugins and no component types, so a game that has its own builds its own editor command. `go tool game generate editor` writes one into a game's `main` package, built with the `gameeditor` tag in place of the game, that calls `editorcmd.Main` with the game's `Components` and its plugins, and `go tool game editor` runs it on the project ([Command Line](http://nsgo.games/docs/cli/#generate)). Package `editorcmd` is the command line both share: `New(Options)` builds an editor with the component types, plugins, name and library given and `ProjectAssets` set, checking scenes against the component types together with the built-in physics components (`body2d`, `collider2d`, `trigger2d` and their 3D forms) the registry does not register itself, `Open(ed, args)` opens a project, a scene or a clip as `go tool game editor` does, and `Main` and `Run` parse the command line, open the project in the working directory without arguments and show the window, 1120 by 680 points unless `Options.WindowWidth` and `Options.WindowHeight` set another size. An editor command written by hand calls `editorcmd.Main` the same way: ```go // cmd/editor/main.go: the game's own editor command. package main func main() { editorcmd.Main(editorcmd.Options{ Components: health.Components(), Plugins: []editor.Plugin{healthplugin.Plugin()}, AppName: "Field Medic Editor", RequirePlugins: true, // refuse a project that lists a plugin this command lacks }) } ``` An `editor.Plugin` has a `Name`, which follows the rule of other names in `game.yaml` (no spaces or control characters), and lists of extensions: - **Panels** (`Panel`): a view docked left of the viewport (`DockLeft`, after the asset browser), right of the inspector (`DockRight`) or below the viewport (`DockBottom`), under its `Title`. `View(cx, ed, rev)` builds it once when it appears, and the panel stays mounted, with its state, while its plugin is on, however other panels come and go; it reads `rev` inside reactive functions, as the editor's own panels do, to follow every change to the editor's state. A dock without panels takes no space. - **Inspectors** (`Inspector`): the inspector draws the component `Component` names with `View(cx, ed, rev, objectID)` below the component's title, in place of its generic fields. `Editor.ComponentField` reads a field, with its registered default when the scene leaves it unset, and reports false for an object without the component. Like the generic fields, the inspector's controls should be disabled while `Playing` reports true, and an edit the editor refuses should go to the status bar with `Editor.Report`. When two plugins that are on draw the same component, the one listed first in `editor.plugins` wins. - **Tools** (`PluginTool`): a custom tool listed in **View > Tools** and the **Command Palette** (`⌘K`), active in 2D and/or 3D depending on which hooks the tool implements. While it is the active tool (`SetPluginTool`; `Tool` is then `ToolPlugin`): - **2D hooks**: a press on the 2D viewport calls `Press(ed, x, y)` with canvas coordinates (`CanvasToWorld` converts them to the world, `CanvasToScreen` to a screen-space layer), drags call `OnDragBegin(ed, x, y)` (returning `true` to claim the drag), `OnDragMove(ed, x, y)`, `OnDragEnd(ed, x, y)` and `OnDragCancel(ed)` (`BeginPluginDrag2D`, `UpdatePluginDrag2D`, `EndPluginDrag2D`, `CancelPluginDrag2D`, `PluginDragging2D`), pointer motion calls `OnHover(ed, x, y, active)` (`SetPluginHover2D`, `ClearPluginHover2D`), and `Draw`, when set, draws over the 2D scene in edit mode. - **3D hooks (#898)**: a press on the 3D viewport calls `Press3D(ed, ray)` with the camera's world-space `math3d.Ray` (`PickRay3D`), drags call `OnDragBegin3D(ed, ray)` (returning `true` to claim the drag instead of orbiting the camera), `OnDragMove3D(ed, ray)`, `OnDragEnd3D(ed, ray)` and `OnDragCancel3D(ed)` (`BeginPluginDrag3D`, `UpdatePluginDrag3D`, `EndPluginDrag3D`, `CancelPluginDrag3D`, `PluginDragging3D`), pointer motion calls `OnHover3D(ed, ray, active)` (`SetPluginHover3D`, `ClearPluginHover3D`), and `Draw3D(ed, d, proj)` draws over the 3D viewport using `Projection3D` (`Camera`, `Width`, `Height`, `ViewProj`, `Project`, `ProjectSegment`, `ScreenRay`, `GizmoLength`, `DrawPoint`, `DrawLine`, `DrawBox`). - A tool must provide at least one of `Press`, `OnDragBegin`, `Press3D`, or `OnDragBegin3D`. Tools with only 2D hooks stay idle in 3D; tools with 3D hooks activate 3D view automatically when run from the Command Palette or **View > Tools**. Choosing another tool, or turning the plugin off, ends it. - **3D Component Gizmos** (`Gizmos3D []ComponentGizmo3D`, #898): registers per-component-type 3D handles in object space (`GizmoHandlePoint3D`, `GizmoHandleLine3D`, `GizmoHandleBox3D`, optionally `DisplayOnly`) returned by `Handles(ed, objectID)` and an interactive `Drag(ed, drag GizmoDrag3D) error` function. The editor transforms handles from object space through the object's full ancestor hierarchy, hit-tests them in screen space (`PickComponentGizmo3D`, `BeginComponentGizmoDrag3D`, `UpdateComponentGizmoDrag3D`, `EndComponentGizmoDrag3D`, `CancelComponentGizmoDrag3D`), and passes `GizmoDrag3D` (with world and object-space rays plus `AxisDelta`, `PlanePoint`, `PlaneDelta`, and `ViewPlaneDelta` helpers). Edits written inside `Drag` through `Editor` (such as `SetComponentField` or `Editor.History`) preview live on every pointer move, roll back cleanly on `Escape` or cancel without polluting history, and commit as **one undo step** when the drag ends. When two active plugins register a 3D gizmo for the same component, the first in `editor.plugins` wins. The editor's built-in 3D transform gizmo (`Translate`, `Rotate`, `Scale`) and built-in `collider3d` / `trigger3d` handles share this same 3D handle API. A plugin changes the scene only through the editor's methods, such as `SetComponentField`, `PlaceObject` and `MoveObject`, or by executing its own `Command` on `Editor.History`, so every edit it makes is undone and redone with the rest. `History.Group(label, fn)` records the edits `fn` makes as one step that one Undo takes back, and when `fn` fails it undoes them and records nothing; the editor's MCP server ([mcp](http://nsgo.games/docs/mcp/#editor-tools)) applies each agent request that way. `RegisterPlugin` refuses a plugin without a name or with a name already registered, a panel, inspector or tool missing its ID, title, label, component or function, an ID or component name with control characters, an unknown dock and two panels, inspectors or tools with the same ID or component. Test IDs join the plugin name and the ID with `-` (`plugin-panel--`, `tool--`, `inspector-plugin--`), so plugins used together should have names and IDs that do not join to the same string. `SetPluginEnabled(name, on)` adds a registered plugin to `editor.plugins` or removes it, as one undoable edit of the project that **File > Save** (`mod+s`) writes; removing the last plugin removes the `editor` section when nothing else is left in it, including an `editor: {}` the author wrote, and Undo puts it back. `RegisteredPlugins`, `ActivePlugins` and `PluginEnabled` report which plugins the binary has and which are on. ### Shipping an editor with plugins A game ships its editor as one more command in its own module, beside the game, and runs it with `go run ./cmd/editor` from the project directory. Keep the plugin in a package of its own that only the editor command imports, so the shipped game does not link the editor, and the component types in a package that both import, so the game and the editor check scenes against the same fields: | Package | Imports | Holds | | --- | --- | --- | | the component package | `sceneformat` | the component types (`ComponentType`), a registry for `ParseWith` and `SetComponentRegistry`, and helpers that read a component with its defaults (`ComponentRegistry.Resolve`) | | the plugin package | `editor` and the component package | `Plugin()`, returning the `editor.Plugin` | | the game (`main`) | the component package | loads its scenes with `sceneformat.ParseWith` and the registry | | `cmd/editor` | `editor`, the component and plugin packages | registers the component types and the plugin, then opens the project | `game.yaml` names the plugin under `editor.plugins`, so the plugin is on whenever the game's editor opens the project. An editor command that should not start without its plugins sets `editorcmd.Options.RequirePlugins`, or checks `MissingPlugins` after `OpenProject` and fails when it is not empty. `go tool game editor` on a project with a `cmd/editor` main package runs that command with `go run ./cmd/editor`, as it runs the one `game generate editor` writes, and passes it the same command line, `-library` and a project, scene file, clip and object ID, so a `cmd/editor` should parse it with `editorcmd.Main` or `editorcmd.Run`. A `cmd/editor` that does not import `editorcmd` is not run: `go tool game editor` says so and opens the project itself. [Field Medic](https://github.com/nsgo-dev/game/tree/main/examples/fieldmedic) (`examples/fieldmedic`) is a runnable game laid out this way. Its patients carry a `health` component (package `health`), and its `cmd/editor` registers the `health` plugin (package `healthplugin`): a Ward panel docked right of the inspector that lists every patient's hit points, with a Heal All button that heals them all in one undoable step it executes on `Editor.History`; an inspector for the `health` component with hit point and max fields and a bar of what is left; and an Admit tool that places a patient where the viewport is pressed and outlines every patient while it is active. Its tests open the game's own project in the editor and drive the panel, the inspector and the tool. The editor's own tests hold a smaller `health` plugin as well (`pkg/editor/plugin_test.go`). ## Library panel (#493) With `Editor.Library` set to a pack library (`library.Open`), as `go tool game editor -library ` sets it, a panel beside the asset browser lists every pack in the library, with its kind, version, description and the version the open project has installed. Its Install, Update and Remove buttons call `InstallPack` and `RemovePack`, which write the pack's files beside `game.yaml`, record the pack and the autoload entries and plugins it adds in the project, and save the project; a registered plugin a plugin pack names turns on at once. They refuse while playing, without a project and while the project has unsaved edits (`ErrProjectDirty`), and they empty the undo history, since the files they write cannot be undone. A pack from a library over https is fetched off the event loop, with its button busy until it arrives (`FetchingPack`). The library format and what an install writes are in [Asset and Plugin Library](http://nsgo.games/docs/library/). ## Unified Settings pages: Agent, Project, Input map, Audio buses, Export, General, and Shortcuts (#907, #908, #909, #916, #1028, #1060, #1061) All per-computer agent controls, project-level `game.yaml` settings, and editor preferences share one unified **Settings** workspace (`SettingsView`, opened with `OpenSettingsPage(page)`, inspected with `SettingsOpen()` / `SettingsPage()`, and closed with `CloseSettings()` / `Escape`) laid out from `design/editor/Settings.dc.html` and `Spec.dc.html` using `theme.Palette` tokens in both Dark and Light appearances. The left sidebar groups **`AGENT`** (**Models and connections**, **Tools**, **Usage and privacy** — all per-computer and **You only**), **`PROJECT · game.yaml`** (**Project**, **Input map**, **Audio buses**, **Export**), and **`EDITOR · THIS COMPUTER`** (**General**, **Shortcuts**); each row displays its label, help text, value control, and agent-policy badge (**Agent may change** or **You only**), and every interactive control across all pages uses real focusable `ui.Button` / `ui.*` widgets reachable via `Tab` with visible focus rings. ### Local agents over the Agent Client Protocol (#1935) The composer's local route runs the agent the agent table names. The table is the built-in rows (`editor.BuiltinAgentDefinitions`) and the person's `agents.yaml` beside `editor.yaml` (`editor.DefaultAgentDefinitionsPath`, format in [File Formats](http://nsgo.games/docs/formats/#local-agent-table)): the person's rows come first, in their order, then the built-in rows whose IDs they do not reuse. A project's files never add or change a row, and no agent may write `agents.yaml`. A request names a row with `AgentRequest.AgentKind`, set from the connected agent's MCP client name (`DetectExternalAgentKind` matches it against each row's ID and aliases); when it names none, the first row whose `bin` is installed runs, skipping rows with `explicit_only: true`. | Row | Adapter | Started as | | --- | --- | --- | | `claude` | `claude` | `claude --print --output-format=stream-json` under the local agent launch policy (below) | | `codex` | `codex` | `codex exec --json` under the local agent launch policy (below) | | `gemini` | `acp` | `gemini --acp`, then `gemini --experimental-acp` for releases from before the flag was renamed | | `opencode` | `acp` | `opencode acp`, only when a request names it (`explicit_only`, below) | | `kimi` | `acp` | `kimi acp`, then `kimi --acp` for releases from before the subcommand | `ACPAgentRunner` speaks ACP version 1 with the agent over its stdin and stdout (`pkg/editor/internal/acp`): - `initialize` declares no `fs` or `terminal` capability, so the agent cannot read or write files or run commands through the editor. - A thread with a stored session continues it with `session/resume` when the agent advertises `sessionCapabilities.resume`, or with `session/load` when it advertises `loadSession` (the history it replays is not shown again). Otherwise, or when the agent cannot continue that session, the runner opens `session/new`. Each request passes the project root as `cwd` and, as `mcpServers`, the editor's server and the servers enabled in Settings › Tools, never the project's `.mcp.json`. - The request's model is set through the session's `model` config option (`session/set_config_option`), or with `session/set_model` for an agent that lists models the older way, and only when the agent offers that model; otherwise the agent keeps its default. A row's `model_flag` passes the model on the command line instead. The reasoning effort goes through the `thought_level` option the same way. - `session/prompt` sends the turn. Message chunks join into one message, the plan becomes the Agent panel's planned steps, tool calls and their updates become steps, and the `usage` of the prompt's response becomes the turn's token counts. The `max_tokens`, `max_turn_requests`, `cancelled` and `refusal` stop reasons end the turn with a message the person can continue from. - Stopping the turn sends `session/cancel` while the prompt is in flight and waits up to 10 seconds for the agent to answer with the `cancelled` stop reason before it stops the process. - `session/request_permission` gets the agent's `allow_once` option only for a tool of the editor's own MCP server whose kind is not `edit`, `delete`, `move` or `execute`, and `reject_once` for everything else; a request that does not offer the option it needs ends the turn with an error, and the step of a rejected call shows as denied. ACP has no field for the server a tool belongs to, so the runner accepts the identifications agents send: Gemini CLI's `_meta["gemini-cli"].mcp.server_name`, or a tool name of the form `mcp__nsgo-game-editor__`, `nsgo-game-editor_` (OpenCode) or `nsgo-game-editor/`. The display title never counts. - When the agent fails before the prompt is sent (it does not start, refuses the arguments or fails the handshake), the row's next `acp_fallbacks` argument set is tried, then the next ACP row. A failure after the prompt is sent ends the turn, so a turn is never sent twice. The permission answer only refuses what the agent asks about. Gemini CLI and Kimi Code ask before they edit files or run commands by default; OpenCode's default permissions allow both without asking, and it loads the project's own OpenCode configuration, so the local agent launch policy below does not hold for an OpenCode row. The built-in `opencode` row is therefore `explicit_only`: the composer never runs it because it is the only agent installed. It runs when OpenCode is the connected MCP client, or when the person writes an `opencode` row in `agents.yaml` (a row they write is tried in order unless it sets `explicit_only: true` itself). With only OpenCode installed, a request the composer would route to the first installed agent fails, and the Agent panel's error says OpenCode was passed over and why. Gemini CLI and Kimi Code rows are tried in order as before. ### Agent pages: Models and connections, Tools, and Usage and privacy (#1028, #1030) The local agent the composer runs is picked from the agent table, described in [Local agents over the Agent Client Protocol](http://nsgo.games/docs/editor/#local-agents-over-the-agent-client-protocol-1935). External agent requests carry the selected `AgentRequest.Model` and `ReasoningEffort` through the CLI boundary. Claude Code receives `--model `. Codex receives the same model flag and a `-c model_reasoning_effort=""` override. Values are validated before `os/exec` receives them, so shell metacharacters, whitespace and overlong values are rejected while the launch policy and `--` prompt delimiter remain in force. Stored per computer in `EditorSettings` (`editor.yaml` under `agent`, never inside the project) with every mutator refused when invoked by an agent (`ErrAgentSettingsYouOnly`): - **Models and connections (`SettingsPageModels`)**: shows connected local MCP agents (such as Claude Code), the built-in API connection (`Anthropic API`, whose key is stored exclusively in NSGo's `core.Secrets` under `AgentAPIKeySecretAccount` / the host OS keychain under `AgentKeychainServiceName` via `StoreAgentAPIKey`, `HasAgentAPIKey`, `DeleteAgentAPIKey`, and `AgentAPIKey` — never written to `editor.yaml`, project files, or logs), **+ Connect another agent or model** (opening `ConnectAgentDialogView`), and **WHO DOES WHAT** task routing (`AgentTaskRoute` / `SetAgentTaskRoute` / `ResolveAgentModelRoute`). The sidebar meta reports the active connection count (`AgentActiveConnectionCount`, e.g. `2 on`). - **Built-in agent runner (`SubmitAgentTaskPrompt`, `Editor.AgentTools`, `Editor.BuiltInAgentEndpoint`)**: routes each task kind (`AgentTaskSceneEdit`, `AgentTaskPlaytest`, `AgentTaskProblems`, `AgentTaskAskInPlace`, `AgentTaskArtSound`) to either a connected local MCP agent or the built-in Anthropic Messages API runner (`DefaultBuiltInModel` / `DefaultBuiltInFastModel`), validating that custom endpoints use `https://` (or loopback `http://` for local tests) and never forward `x-api-key` across redirect hosts. `editormcp.New` wires `Editor.AgentTools` automatically so built-in tool calls execute through the same `editormcp.Server` tool toggles, permission rules, `WithAgentActor` You-only guard, and symlink-aware outbound privacy enforcement as external MCP clients. - **Weekly limit queueing & model error failover (`AgentStatusLimitReached`, `AgentQueuedRequests`, `AgentModelErrorState`)**: reaching the person-only weekly request limit (`WeeklyRequestLimit` / `SetWeeklyRequestLimit`) transitions the Agent header chip to `Limit reached · resets 00:00` with a **Usage** link and queues subsequent requests (`SendQueuedAgentRequest`, `RemoveQueuedAgentRequest`) until `CheckAgentUsageReset` crosses the weekly reset or the person raises the limit. Transient model errors (`429`, `5xx`, `529` overloaded) retry on `AgentModelRetryDelays` (`4 s, 8 s, 16 s, 32 s`), rendering the model error card with **Retry now** (`RetryAgentTurn`) and **Use ``** (`SwitchAgentTurnToAlternative`) to update WHO DOES WHAT and run the request on another connected agent without double-counting usage. - **Tools (`SettingsPageTools`)**: lists every tool registered on the editor's MCP server (`RegisteredMCPTools`) with its monospace name, description, and an accessible `role="switch"` toggle (`IsMCPToolEnabled` / `SetMCPToolEnabled`), showing `"enabled / total"` in the sidebar (`EnabledMCPToolCount`). `game_delete_file` is off by default; turning any tool off removes it from the MCP server's client tool list (`tools/list_changed`) and returns a readable refusal if called. Below the editor's tools, **OTHER MCP SERVERS THE AGENT MAY USE** starts with **Running game · nsgo dev** (`nsgo-game` / `go tool nsgo mcp`) and provides **+ Add a server** (`AddAgentMCPServer`, `SetAgentMCPServerEnabled`, `RemoveAgentMCPServer`), syncing enabled servers into the open project's `.mcp.json` and `.codex/config.toml` (`editormcp.InstallWithServers`). - **Usage and privacy (`SettingsPageUsage`)**: displays **This week** requests against a user-configured weekly limit (`WeeklyRequestLimit` / `SetWeeklyRequestLimit` / `RecordAgentRequest`), **Kept** share of reviewed agent changes (`RecordAgentReviewOutcome`), and local **Playtests** run count (`RecordPlaytestRun`), followed by the four **WHAT MAY LEAVE THIS COMPUTER** switches (`AgentPrivacy` / `SetAgentPrivacy`): **Scene and data files** (on), **Viewport images** (on), **Go source code** (off), and **Art and audio files** (off). The editor's MCP server refuses, with the reason, any tool call or resource read whose result would carry switched-off content for every connected agent. Files that look like credentials or the editor's private state never leave, whatever the switches say: `.env`, `.env.*` and `*.env`, `.envrc`, `*.pem`, `*.key`, `*.p8`, `*.p12`, `*.pfx`, `*.jks`, `*.keystore`, `keystore.properties`, `.netrc`, `.npmrc`, `.git-credentials`, `credentials.json`, `google-services.json`, `GoogleService-Info.plist`, `service-account*.json`, SSH keys named `id_*`, and anything inside a `.git`, `.nsgo`, `.aws` or `.ssh` folder. The match ignores case, including Unicode case folding and the names a case-insensitive file system stores (such as NTFS short names), and follows in-project symbolic links; every tool that reads, edits, renames or deletes a file by its path refuses them with "looks like a credential or the editor's private state; the editor never sends it to an agent", the `@`-mention picker does not offer them, and a file chip never carries them. Keep other secrets out of files an agent may read, or turn **Scene and data files** off. - **Spend counters and caps (`RecordAgentSpend`, `AgentSpendCapReached`)**: `agent.usage` in `editor.yaml` also records this week's uncached input tokens (`inputTokens`), prompt-cache reads (`cachedInputTokens`), output tokens (`outputTokens`) and estimated spend in US dollars (`estimatedCostUSD`), which reset with the weekly request count at 00:00 UTC on Monday. Three person-only caps sit beside `weeklyRequestLimit`: `weeklySpendLimitUSD` (weekly estimated spend), `requestSpendLimitUSD` (estimated spend of one request) and `toolCallLimit` (tool calls in one request), where `0` or an omitted value means no cap and a negative, NaN or infinite value is refused on load. `AgentSpendCapReached` reports whether this week's estimated spend has reached `weeklySpendLimitUSD`. The settings store the caps only: the agent runners, automations and the Usage page do not yet record spend or enforce these caps (#1746). ### Project page (#907, #1060) While a project is open, **Project > Project Settings**, `mod+shift+,`, or the Command Palette (`CmdProjectSettings`, `ProjectSettingsOpen` / `SetProjectSettingsOpen`, or `OpenSettingsPage(SettingsPageProject)`) opens the **Project** page in `SettingsView` (`ProjectSettingsPanelView`) to edit `game.yaml` exclusively through `EditProject`, so every change is validated by `project.Validate`, participates in Undo/Redo, and writes both `game.yaml` and the synced `nsgo.yaml` beside it on **Save** (`SaveProject`): - **General**: edits `name`, `id`, `window` width/height, `autoload.mainScene`, and `appVersion` directly on the overview page (`SetProjectName`, `SetProjectID`, `SetProjectWindowSize`, `SetProjectMainScene`, `SetProjectAppVersion`). - **Window**: edits `window.title`, `width`/`height`, `minWidth`/`minHeight`/`maxWidth`/`maxHeight` limits, `resizable`, and `appearance` (`SetProjectWindowTitle`, `SetProjectWindowSize`, `SetProjectWindowLimits`, `SetProjectWindowResizable`, `SetProjectWindowAppearance`). - **Display**: toggles the optional `display` section (`SetProjectDisplayEnabled`) and edits its virtual `width`/`height`, `mode` (`fit`, `fill`, `stretch`, `expand`), `integerScale`, `pixelSnap`, and `barColor` (`SetProjectDisplaySize`, `SetProjectDisplayMode`, `SetProjectDisplayIntegerScale`, `SetProjectDisplayPixelSnap`, `SetProjectDisplayBarColor`). - **Autoload**: selects `autoload.mainScene` (`SetProjectMainScene`) and adds, updates, or removes `autoload.scenes` and `autoload.resources` entries (`AddProjectAutoloadScene`, `UpdateProjectAutoloadScene`, `RemoveProjectAutoloadScene`, `AddProjectAutoloadResource`, `UpdateProjectAutoloadResource`, `RemoveProjectAutoloadResource`) with searchable file pickers populated from the open project's files (`ProjectSceneFiles`, `ProjectResourceFiles`). - **Physics**: edits `physics.gravity2D`, `physics.gravity3D`, `physics.solverIterations2D` / `solverIterations3D`, and named collision `physics.layers` (`SetProjectPhysicsGravity2D`, `SetProjectPhysicsGravity3D`, `SetProjectPhysicsSolverIterations`, `AddProjectPhysicsLayer`, `RemoveProjectPhysicsLayer`). - **Editor plugins**: shows every registered plugin (`RegisteredPlugins`) with a toggle switch backed by `SetPluginEnabled`, plus any plugins listed in `game.yaml` that this editor binary lacks (`MissingPlugins`) with an option to remove them. Any value `project.Validate` refuses displays its validation error inline on the offending row without mutating the project or history. Before the first save of the open project (`ProjectCanonicalSavePending`), the page displays a notice explaining that saving writes `game.yaml` in canonical YAML form, which does not preserve comments. ### Audio buses page (#909, #1060) While a project is open, **Project > Audio Bus Mixer**, the Command Palette (`CmdAudioMixer`), or **Settings › Audio buses** (`AudioMixerOpen` / `SetAudioMixerOpen`, or `OpenSettingsPage(SettingsPageAudio)`) opens the **Audio buses** Settings page (`AudioMixerPanelView`) to edit `game.yaml`'s `audio` section directly through `EditProject`, so every edit validates against `project.Validate`, participates in the editor's Undo/Redo history, and writes cleanly on **Save** (`SaveProject`): - **Master and buses**: adjust the master volume slider with dB readout (`SetAudioMasterVolume`), add new buses (`AddAudioBus`), rename (`RenameAudioBus`), delete (`DeleteAudioBus`), reorder (`MoveAudioBus`), and adjust each bus's routing (`Into Master`) and volume slider (`SetAudioBusVolume`). Deleting the last bus when no master volume is set removes the empty `audio` section, and Undo restores it. - **Per-bus DSP effect chains**: add (`AddAudioBusEffect` / `AddAudioBusEffectKind`), remove (`RemoveAudioBusEffect`), reorder (`MoveAudioBusEffect`), and edit (`SetAudioBusEffect`) all six `project.Effect` types (`lowPass`, `highPass`, `delay`, `reverb`, `gain`, `bitcrush`). Numeric inputs bound parameters to `project.Validate`'s ranges (with `ClampAudioEffect`), and Go API calls refuse out-of-range values without altering the project or history. - **Live audition**: choose any audio file from the open project (`ProjectAudioFiles`, `SelectAudioFile`) and press **Audition** (`AuditionAudioBus`, `StopAudition`, `SetAuditionLoop`) to play it through the selected bus on an editor-owned `sound.Mixer` configured with `project.File.ConfigureMixer`. Volume changes apply live to the playing stream without restarting it, and effect chain edits or Undo/Redo immediately re-process through the same `sound.Mixer` bus chain that `Music.Play` and `Mixer.LoadEffect` apply at run time. That chain runs on in-memory 16-bit PCM WAV sources only: a shipped game plays other formats without it (logging once per group), and auditioning one on a bus with effects reports the WAV decode error instead. ### Input map page (#908, #1060) While a project is open, the Command Palette (`CmdInputMap`) or **Settings › Input map** (`InputMapOpen` / `SetInputMapOpen`, or `OpenSettingsPage(SettingsPageInput)`) opens the **Input map** Settings page (`InputMapPanelView`) to edit `game.yaml`'s `input` section directly through `EditProject` with full Undo/Redo and validation against `project.Validate`: - **Action overview & editor**: lists each configured action with its keyboard, gamepad, and touch triggers alongside a button that jumps directly into editing that action. Add (`AddInputAction`), rename (`RenameInputAction`), and delete (`DeleteInputAction`) actions, and add (`AddInputBinding`), edit (`SetInputBinding`), or remove (`RemoveInputBinding`) bindings of every `game/input` kind: `key`, `keyCode`, `gamepadButton`, `mouseButton`, `touchRegion`, and `mouseRegion`. Renaming an action atomically updates every axis in `input.axes` that reads it so references stay consistent across Rename, Undo, and Redo. - **Key capture**: pressing **Press a key** (`BeginKeyCapture` with `project.KindKey`) or **Press code** (`project.KindKeyCode`) enters capture mode and binds the next hardware key press (`CaptureKeyEvent`) directly to the selected action, with **Cancel** (`CancelKeyCapture`) to back out without changing the project. - **Regions over virtual display size**: the region canvas scales to the project's `display` resolution (falling back to `window` when `display` is unset; `InputMapDisplaySize`), draws all `touchRegion` and `mouseRegion` bounds, and lets you drag existing regions to move them, drag a selected region's bottom-right handle to resize it, or drag on empty space to draw a new region (`BeginRegionDrag` / `UpdateRegionDrag` / `EndRegionDrag` / `SetInputRegion`). Each drag commits as one undoable `EditProject` step. - **Axes, motion axes and gamepad sticks**: the **Axes** tab edits action axes (`AddInputAxis`, `SetInputAxis`, `DeleteInputAxis`), device motion sensor axes (`AddInputMotionAxis`, `SetInputMotionAxis`, `DeleteInputMotionAxis`), and controller analog stick axes (`AddInputGamepadAxis`, `SetInputGamepadAxis`, `DeleteInputGamepadAxis`). `BuildInputActions` binds the open project's map into a live `*input.Actions` via `project.File.BindInput`. ## Localization panel (#917) The Localization panel (`LocalizationPanelView`) edits per-locale YAML string tables side by side below the viewport, with message keys as rows and project locales as columns. - **Opening**: choose **Project > Localization Strings** or the Command Palette's **Localization Strings** command (`CmdLocalization`, which opens `/locales` when a project is open, or starts an in-memory `"en"` table otherwise), or call `OpenLocalizations(dir)` / `NewLocalizations(dir, locales...)` in Go. `CloseLocalizations` closes the panel. - **Keys and locales**: add or remove locale columns (`AddLocalizationLocale`, `RemoveLocalizationLocale`) and message key rows (`AddLocalizationKey`, `RemoveLocalizationKey`), normalizing locale tags to canonical BCP-47 form (for example `zh_hans` -> `zh-Hans`). - **Simple strings and CLDR plurals**: toggle a key as plural (`SetLocalizationKeyPlural`) to edit all six CLDR categories (`zero`, `one`, `two`, `few`, `many`, `other`) via `SetLocalizationPlural` or `SetLocalizationPluralForm`, or edit simple strings via `SetLocalizationString`. - **Missing translations**: cells whose translation is empty (or whose plural `other` fallback is empty) are highlighted with a warning border and `Missing` indicator; `LocalizationMissing`, `LocalizationMissingCount`, and `LocalizationIsMissing` report them programmatically. Untranslated keys are omitted when saved so runtime `l10n.Catalog` lookups fall back along the BCP-47 chain. - **Undo, saving, and panel states**: every localization edit goes through `Editor.History` (Undo/Redo). **Save Strings** (`SaveLocalizations` / `SaveLocalizationsTo`) writes each locale's canonical YAML file to `/.yaml` using `l10n.EncodeYAML` and removes files for locales that were deleted from the workspace. Panel errors are surfaced in a dismissible banner (`LocalizationError` / `ClearLocalizationError`), and asynchronous loaders can toggle the loading state via `LocalizationLoading` / `SetLocalizationLoading`. ## Problems panel and live agent-proposed fixes (#913, #1036) While a project is open, the Problems panel (`ProblemsView`) below the viewport runs `assetcheck.CheckWith` (using the editor's component registry) and `project.Check` over the project directory overlaid with every open, unsaved editor document off the UI goroutine, and reports the live problem count in the status bar (`Problems: N`). It re-checks automatically (debounced via `ProblemCheckDebounce`, defaulting to 80 ms) after every edit in the editor—made by the person or the agent—without waiting for a save, as well as when a project opens (`OpenProject`), after saving (`SaveFile`, `SaveProject`, `SaveClipFile`), after moving files (`MoveFile`, including undo and redo), and when the component registry changes (`SetComponentRegistry`). The panel's Check button (`CheckProblems`) re-runs the check on demand after edits made outside the editor. Each row displays a problem's `file:line:column` location (`assetcheck.Problem.Location`, carrying the 1-based column wherever the scene or YAML format knows it), a Spec alert icon, and the message, sharing the asset and component checks in `go tool game check` and adding the project-level issues reported by `project.Check` (such as an `nsgo.yaml` out of sync with `game.yaml`, a missing installed pack file, or an invalid non-`.scene.yaml` autoloaded scene). Pressing a row (`OpenProblem`) opens the scene in a tab without discarding unsaved edits in other tabs, or selects a non-scene file in the file browser (`SelectedFile`, `SelectFile`). Problems attributed to objects in the open scene also draw directly on live objects in the 2D viewport using the Spec Problem overlay (2 px solid problem outline plus a filled alert pill with icon and message, toggled via `SetProblemOverlayVisible`) and show a problem count badge on the object's row in the scene tree (`ObjectProblems`, `ObjectProblemCount`). - **Agent-proposed fixes (`ProposeProblemFix`, `ApplyProposedFix`, `ProblemAgentPanelView`)**: an agent inspecting live problems through MCP (`game_check`) can propose a fix via `problem_propose_fix` (providing the problem, an explanation, and a validated structured edit). Proposing a fix simulates the edit on a cloned scene document to verify validity and compute the exact `-`/`+` YAML diff, opens the right-hand **Agent** panel showing the problem card (`file:line:col`), explanation, diff, **Apply fix**, **Show me**, **Ignore**, and **"Ask about this problem…"**, and **never applies the edit or mutates any file**. Only the person pressing **Apply fix** (`ApplyProposedFix`) applies the change as a single undoable `History` step with a Spec toast and **Undo** action, so one Undo restores the previous YAML and brings the problem back. - **Show me, Ignore, and Ask about this problem (`ShowProblem`, `IgnoreProblem`, `AskAboutProblem`)**: **Show me** opens the problem's scene, selects and frames the offending object, and highlights the exact YAML line. **Ignore** hides that problem from the Problems panel, status bar, scene tree badge, and viewport overlay until its file changes again (tracked by live content hash); any subsequent edit to that file evicts the ignore entry so the problem reappears automatically if it still holds. Submitting **"Ask about this problem…"** delivers the question with the problem, attributed object, and proposed fix attached (`OnAskAboutProblem`). In Go, `Problems`, `ProblemCount`, `ProblemErr`, `CheckingProblems`, `WaitForProblems`, `IgnoreProblem`, `IsProblemIgnored`, `ProposeProblemFix`, `ProposedFixes`, `ApplyProposedFix`, `ShowProblem`, and `AskAboutProblem` manage live problems and proposed fixes safely. ## Export and release builds (#916, #1060) While a project is open, **File > Export & Release...**, `mod+shift+e`, the Command Palette (`CmdExport`), or **Settings › Export** (`ExportPanelOpen` / `SetExportPanelOpen`, or `OpenSettingsPage(SettingsPageExport)`) opens the **Export** Settings page (`ExportPanelView`) in `SettingsView` to edit `game.yaml`'s `export` section and run release builds directly from the editor: - **Presets, readiness, and output directory**: edit `export.output` (`SetExportOutput`) with inline validation and add, remove, or reorder per-platform presets (`AddExportPreset`, `RemoveExportPreset`, `MoveExportPreset`) with targets chosen strictly from each platform's valid `project.TargetsOf(platform)` (`SetExportPresetTargets`, `ToggleExportPresetTarget`). Each preset row displays its readiness (`ExportPresetReadiness`: **Ready** or **Set up** when signing/team configuration or credits are missing) and policy badge, and the **Export** sidebar item surfaces a warning badge (`ExportNavWarningMeta`) whenever a preset needs setup. Every change goes through `EditProject` (`project.Validate` + Undo/Redo), clears an empty `export` section automatically, and writes canonical YAML plus the synced `nsgo.yaml` on **Save** (`SaveProject`), matching `game project targets`. - **Credits pre-flight**: whenever the panel opens, refreshes (`CheckExportCredits`), or starts a build, it runs the same `tooling/credits` scan that `game release` uses. Any asset without a credit is listed with its expected `*.import.yaml` sidecar path and blocks building until credited; once credited, refreshing clears the warning and successful builds write `CREDITS.md` beside the packages. - **Builds, dry runs, and Output stream**: build all configured presets or toggle specific targets (`ExportSelectedTargets`), optionally selecting a distribution channel (`SetExportChannel`), release notes file (`SetExportReleaseNotes`), or **Dry Run** (`SetExportDryRun`). `StartExportBuild` / `RunExportBuild` share the release command planner with `go tool game release`, so dry-run builds stream the exact same `nsgo build` command line into the panel's Output view off the UI goroutine, and successful non-dry-run builds open the resolved output folder (`OpenOutputFolder` / `OpenExportOutputFolder`). ### Build and release screen (#1048, #1050) For full release preparation, **Project > Build & Release...** (`CmdBuildRelease`, shortcut `mod+shift+r`, or `OpenBuildReleaseScreen` / `CloseBuildReleaseScreen` / `BuildReleaseScreenOpen`) opens the full-window `BuildReleaseScreenView` styled with Spec tokens: - **Header and pre-build checks**: shows `"Release · Version from on · last release "` with an editable version field (`SetReleaseVersion`), Dry Run toggle (`SetReleaseDryRun`), and **Build** / **Stop** / **Resume** controls (`StartReleaseBuild`, `StopReleaseBuild`, `ResumeReleaseBuild`). **BEFORE EVERY BUILD** summarizes `nsgo check` (problem count and elapsed time via `RefreshBuildPreflight`), the smoke playtest, and release budgets declared under `export.budgets` in `game.yaml` (`qualityProfile`, `downloadSizeMB`, `frameTimeP95Ms`, defaulting to Low profile / 80 MB / 16.7 ms). - **Export presets, ordered steps, and logs**: lists each preset with an include checkbox (`SetBuildPresetIncluded`), platform summary, live status (`Queued`, `Building`, `Notarizing`, `Done`, `Failed`, `Set up`), artifact size, and delta against the last release (`SetLastReleaseBaseline`). Selecting a running preset shows the 6 ordered steps (`Check project`, `Compile Go`, `Pack assets`, `Sign`, `Smoke playtest`, `Measure`) with elapsed times, exact `releaseplan` commands matching `game release -dry-run`, and its streaming log (`build/.log`). Presets build one at a time; **Stop** keeps completed steps and **Resume** continues from the interrupted step. - **Failure isolation and agent preset fixes**: if a preset fails (for example, a missing signing keystore at `Sign`), the screen shows the error, step and elapsed time, failing commands, and `"Other platforms keep building. Nothing was uploaded."` while continuing remaining checked presets. An agent-proposed preset fix diff (`SetBuildPresetFixProposal`) can be applied and rebuilt in one click (`ApplyBuildPresetFixAndRebuild`). - **Finished results, real measurements, and platform readiness**: completed presets inspect the real packages `nsgo build` wrote in the release plan's output directory (using NSGo's `--` and `releases/--` naming via the shared `pkg/tooling/sizecheck` package — `MeasureWasm` for Web `.wasm` builds and `InspectMobilePackage` for Android `.aab`/`.apk` and iOS `.ipa` archives, plus directory/archive inspection for desktop targets). When a built package is found, the screen shows its real artifact path, size, delta against the last release, `code` / `textures` / `audio` / `other` breakdown highlighting what grew, **Show in Finder** (`ShowBuildArtifactInFinder`), **Edit preset**, and (for Web builds) a local test-link QR card. The **Smoke playtest** step runs an injected `Editor.ReleasePlaytestRunner`, or—on the host desktop target when a built package exists and `autoload.mainScene` is configured—a real headless simulation of the main scene reporting its measured p95 frame time; on dry runs, non-host targets without a playtest runner, or projects without a built package, the step reports `"not run"`, the playtest card shows **Smoke playtest · not run**, and the frame-time budget badge shows **Not measured** (`FrameTimeBudgetMet == false`). Likewise, when no built package is found (such as during a dry run), artifact size is not estimated from source files: the download budget badge shows **Not measured** (`DownloadBudgetMet == false`), no synthetic breakdown is rendered, and no `build/last-release.yaml` baseline is written. Platforms that cannot build yet (such as iOS) open the **READINESS** checklist (`EvaluateBuildReadiness`, backed by the shared `nsgo.yaml` checks: `id`, `icon.apple` / `icon.png` or default `assets/AppIcon.icon` / `assets/Icon.png`, `sign.identity`, `sign.profile`, `apple.privacy` and `resources/PrivacyInfo.xcprivacy` merged with NSGo's built-in privacy manifest, and `*.touch.yaml` layouts or `game.yaml` `touchRegion` bindings) clearly separating what the agent can handle (`RunBuildReadinessAction` / `RunBuildReadinessAgentSetup`, such as syncing `nsgo.yaml`, writing `resources/PrivacyInfo.xcprivacy`, or generating `controls.touch.yaml` from `game.yaml`'s existing actions) from steps that require the person (provisioning profile and Apple signing credentials). - **Release notes drafted from commits and kept reviews (#1050)**: **RELEASE NOTES** reads git commits since the last release tag (or initial commit when untagged), kept review summaries (`SetReleaseKeptReviews` / `AddReleaseKeptReview`), and `changelog.d/*.md` fragments to draft player-facing Markdown (`DraftReleaseNotes`, `RedraftReleaseNotes`, `DefaultReleaseNotesDraft`, pluggable via `Editor.ReleaseNotesDrafter`, and `release_notes_draft` in `editormcp`), displaying `"Drafted from N commits since "`. Editing the notes in place (`SetReleaseNotesText` / `SaveReleaseNotes`) saves directly and atomically to the exact Markdown file read by `game release -release-notes` (`ReleaseNotesFile` / `SetReleaseNotesFile`, defaulting to `release-notes.md`), modifying only that file. - **Store uploads that always ask first and system keychain credentials (#1050, #1762)**: pressing **Review uploads…** (`ReviewReleaseUploads` / `OpenReviewUploads`, or `release_review_uploads` in `editormcp`) opens the **Review uploads** confirmation dialog listing every artifact (name, path, size), its destination (`itch.io`, `Google Play · internal testing`, `TestFlight`), exact channel/track, version, and keychain credential status before anything is sent. For itch.io targets, channel labels come from `nsgo.yaml`'s `itch.channels` or NSGo's per-target defaults (`html5`, `osx-`, `windows-`, `linux-`). Desktop builds made with the `steam` channel are left out of itch.io and listed as `"upload with SteamPipe"` until a Steam destination exists. A strict trust boundary ensures no upload can ever start without the person confirming in **Review uploads** (`ConfirmReleaseUploads` with a single-use session ID; `StartReleaseUpload` and agent-actor confirmation calls via `WithAgentActor` / `editormcp` are always refused, even under `PermissionProfileAutonomous`). Upload credentials are stored under `PublishKeychainService` through `Editor.Keychain`, a `keychain.Store` from `github.com/nsgo-dev/game/pkg/editor/keychain` (`StorePublishCredential`, `HasPublishCredential`, `DeletePublishCredential` — backed by macOS Keychain, Linux Secret Service, Windows Credential Manager, or `keychain.NewMemory` in tests), handed to the uploader as a redacted `PublishCredential`, and are never written into project files or serialized into snapshots. By default (when `Editor.ReleaseUploader` is nil), confirmed uploads run `go tool nsgo publish` in the project directory (`publish itch -target …` with `BUTLER_API_KEY`, `publish -target android -track internal` with `NSGO_PLAY_SERVICE_ACCOUNT`, and `publish ios ` with `NSGO_APP_STORE_KEY` plus optional `NSGO_APP_STORE_KEY_ID` / `NSGO_APP_STORE_ISSUER` parsed from JSON `{key, key_id, issuer}` or `key_id:issuer` account metadata), passing credentials only via environment variables, streaming output as progress, redacting secrets from logs and errors, and surfacing printed store URLs or processing states. ### Try a build on a phone (LAN QR) or connected device (#1049, #1506) When a Web or Android build completes on the Build and Release screen, authors can test it directly on their computer, on a phone over local Wi-Fi, or on a USB-connected Android device: - **LAN-only HTTP server and pure-Go QR code**: finishing a non-dry-run Web build automatically starts a local-network HTTP server (`StartWebBuildServer` / `StopWebBuildServer` / `WebBuildServerState`) bound strictly to a private RFC 1918 LAN IPv4 address (or loopback when offline, customizable via `Editor.LANAddressResolver` and `Editor.WebBuildServePort`). Public bind addresses are refused (`ErrNonLANAddress`), non-LAN peer requests receive `403 Forbidden`, symlinks escaping the build directory are blocked, and stopping the server (via **Stop serving**, closing the editor `Close()`, switching projects, or unmounting `EditorView`) immediately closes the listener and frees the TCP port. The Web result card renders a deterministic scannable ISO/IEC 18004 QR code (`pkg/editor/internal/qrcode`, `EncodeBuildQR`) on a high-contrast light quiet-zone card using Spec tokens alongside the LAN URL, **Copy URL** (`CopyWebBuildURL`), and **Stop serving** / **Start serving** controls. - **Play-mode MCP bridge over LAN**: served web builds retain exact `index.html` and asset bytes while advertising bridge discovery via `X-NSGo-MCP-Bridge: /__nsgo_mcp/info` and `X-NSGo-Play-Mode: debug` headers. In `js/wasm` web builds, attaching `game/mcp` (`mcp.Attach`) or running `game.Loop.Run` registers `window.__nsgoMCP.callTool` (and `listTools`) backed by the game's live MCP tools (`game_state_dump`, `game_scenes_list`, `game_entities_list`, `game_entity_inspect`, `game_loop_*`, `game_input_*`, `game_console_*`, `game_screenshot`, etc.) and probes the page with `HEAD`: when `X-NSGo-Play-Mode: debug` is present, it fetches `/__nsgo_mcp/info` and loads `/__nsgo_mcp/bridge.js`, authenticates at `POST /__nsgo_mcp/session`, and long-polls `/__nsgo_mcp/poll` + `/__nsgo_mcp/reply` (disconnecting on `pagehide`). From the editor's MCP server (`pkg/editor/editormcp`), agents list connected phone sessions with `phone_sessions_list` and forward calls to them with `phone_call_tool` (governed by `permissions.yaml` `run` rules under `playtests: phone/` and privacy rules, decoding `game_screenshot` PNGs directly as MCP images), backed by `Editor.WebBridgeSessions`, `Editor.CallWebBridgeTool`, and `Editor.WebBridgeHandler`. - **RUN ON DEVICE**: shows live device targets and states (`BuildDeviceState`) in the finished build rail: - **This Mac's / computer's browser** (`LaunchBuildOnDevice("browser")`, injectable `Editor.OpenBrowserURL`): opens the active LAN URL in the local browser (`ready` -> `running`). - **Phone · Wi-Fi** (`LaunchBuildOnDevice("phone-wifi")`): tracks `serving`, `connected` (showing the connected phone's name when attached to the MCP bridge), and `stopped` states. - **Connected Android device on USB** (`RefreshConnectedDevices`, `RunBuildOnAndroidDevice`, `WaitAndroidDeviceRun`, `StopAndroidDeviceRun`, injectable `Editor.DeviceDiscoverer` and `Editor.DeviceCommandRunner`): once the Android build finishes, installs and launches via `go -C tool nsgo build -target -run -device `, reporting `ready`, `installing`, `running`, `failed`, and `disconnected` states cleanly. ## Project search and Find References (#914) While a project is open, the file browser's **Search** button (`SearchOpen` / `SetSearchOpen`) toggles the Search & References panel (`SearchPanelView`) below the viewport to jump anywhere in the project or answer "what uses this file?": - **Project-wide search (`Search`, `SetSearchQuery`, `SearchResults`)**: indexes every project file (following the same walk rules as `ProjectFiles` and `refs.Scan`) and parses every scene file (`*.scene.yaml`, `*.scene.yml`, autoloaded scenes, and scenes referenced by other files). Case-insensitive queries (including space-separated multi-term queries) match file names and paths (`SearchFile`), file UIDs from file headers or `game.index.yaml` (`SearchUID`), scene titles, and inside scenes: object IDs and display names (`SearchObject`, including nested children), component types (`SearchComponent`, including overrides), prefab names (`SearchPrefab`), and instanced or inherited scene paths (`SearchSceneRef`). - **Jump-to-result (`OpenSearchResult`)**: activating a result for a non-scene file selects it in the file browser (`SelectedFile`). Activating a result for a scene file opens that scene (setting `ScenePath` and `SelectedFile`) and selects the matching object (`SelectedID`), nested children included, falling back to its top-level ancestor when the child cannot be selected. If the scene is already open, it selects the object in place without reloading from disk or discarding unsaved edits and undo history. - **Find References (`FindReferences`, `ShowReferences`, `ShowSelectedFileReferences`, `References`, `OpenReference`)**: selecting any file or directory in the file browser and pressing **Find Refs** queries `refs.Scan` for every incoming reference, listing each referring file, 1-based line, field, and written value in the exact order `refs.Scan` reports them. Pressing a reference row opens the referring scene (and selects the top-level object owning that line when applicable) or selects a non-scene referring file in the file browser. - **Live index updates (`RefreshSearch`)**: edits to the currently open scene (`PlaceObject`, `SetObjectName`, `DeleteObject`, Undo/Redo) immediately update active search results in memory; saving scenes, projects, clips, data tables, or localizations, installing/removing packs, and moving files (`MoveFile`, including Undo/Redo, which also follows `ReferencesTarget`) automatically invalidate and refresh the index; external edits on disk are detected via a lightweight directory fingerprint or refreshed explicitly via **Refresh** (`RefreshSearch`). Asynchronous callers can also toggle the panel's loading card with `SearchLoading` / `SetSearchLoading`. ## Running the game and Output panel (#910) Alongside the existing in-editor **Play** preview (`Play`, `PlayIn`, `Stop`, toggled with `mod+p` / **F5**), the editor can launch the open project itself on desktop via `go tool game dev` and stream its logs into a docked Output panel (`OutputPanelView`) below the viewport: - **Run and Stop**: choose **Project > Run Game**, `mod+r`, or the Command Palette (`CmdRunGame`) to launch `go tool game dev` in the open project directory (`RunGame` / `RunGameWith`). Enable **Run From Open Scene** (`CmdRunOpenScene`, `SetRunStartAtOpenScene`)—or pass `RunGameOptions{StartAtOpenScene: true}`—to pass `-scene ` and `NSGO_GAME_SCENE` (`hotreload.SceneEnv`) for the currently open scene. While the game is running, **Stop Game** (`CmdStopGame`, **Shift+F5** / `StopGame`) terminates the child process and its entire process tree cleanly (via its own process group on Unix and `taskkill /T /F` on Windows). Unmounting `EditorView`, switching projects (`OpenProject`), or calling `Close()` also stops any running game cleanly. Custom tools and tests can inject `Editor.RunGameCommand`. - **Output / Log panel**: docked below the viewport (`OutputPanelView`, toggleable via the status bar's **Output** button, **View > Panels > Output**, Command Palette `CmdOutputPanel`, or `SetOutputPanelOpen`), streaming the running game's standard output (`OutputStdout`) and standard error (`OutputStderr`) live off the UI goroutine alongside a timestamped history of the editor's own status and error messages (`OutputEditor`). Consecutive editor errors stay in the log instead of overwriting one another. - **Filter, Clear, and `file:line` navigation**: toggle **Errors** (`SetOutputErrorsOnly`) to show only error entries, press **Clear** (`ClearOutput`) to empty the log, and click any log line carrying a `file:line` location (`OpenOutputEntry`) to open that file in the editor when it is a scene (`*.scene.yaml`, `*.scene.yml`, or listed under `autoload.scenes`) or select it in the file browser otherwise. - **Run and Stop**: press the toolbar's **Run** button (or **F5**) to launch `go tool game dev` in the open project directory (`RunGame` / `RunGameWith`). Enable the **Current Scene** toggle (`SetRunStartAtOpenScene`)—or pass `RunGameOptions{StartAtOpenScene: true}`—to pass `-scene ` and `NSGO_GAME_SCENE` (`hotreload.SceneEnv`) for the currently open scene. While the game is running, the button switches to **Stop Game (Running)** (**Shift+F5** / `StopGame`), which terminates the child process and its entire process tree cleanly (via its own process group on Unix and `taskkill /T /F` on Windows). Unmounting `EditorView`, switching projects (`OpenProject`), or calling `Close()` also stops any running game cleanly. Custom tools and tests can inject `Editor.RunGameCommand`. - **Debug run mode**: the toolbar's **Debug** button (or **Mod+Shift+D**, `CmdDebugGame`, `DebugGame` / `RunGameOptions{Debug: true}`) launches `go tool game dev -debug`, running the game under the Delve debugger on the native target. When Delve announces its API server address, the status bar shows it (`GameDebugAddress`) with a **Copy** action (`CopyDebugAttachConfig`, the VS Code attach configuration for the address) and a **VS Code** action (`WriteVSCodeDebugConfig`, which writes or updates the `Attach to game` entry in the project's `.vscode/launch.json` so Run and Debug attaches in one click); the address is re-announced in the Output panel after every rebuild, and an attached IDE reconnects at the same address. GoLand users add a **Go Remote** configuration with the same host and port. - **Output / Log panel**: docked below the viewport (`OutputPanelView`, toggleable via the toolbar's **Output** button or `SetOutputPanelOpen`), streaming the running game's standard output (`OutputStdout`) and standard error (`OutputStderr`) live off the UI goroutine alongside a timestamped history of the editor's own status and error messages (`OutputEditor`). Consecutive editor errors stay in the log instead of overwriting one another. - **Filter, Clear, and `file:line` navigation**: toggle **Errors** (`SetOutputErrorsOnly`) to show only error entries, press **Clear** (`ClearOutput`) to empty the log, and click any log line carrying a `file:line` location (`OpenOutputEntry`) to open that file in the editor when it is a scene (`*.scene.yaml`, `*.scene.yml`, or listed under `autoload.scenes`), open it in the external editor at that line when it is a Go source file (`OpenGoFileAtLine`, through `Editor.OnOpenSourceFile` / `Editor.OnOpenFileAtLine` when set), or select it in the file browser otherwise. The panic card's stack frames link the same way. ## Keyboard shortcuts, menu bar, and command palette (#920) Every common editor action lives in a single command registry (`Editor.Commands`, `Editor.RegisterCommand`, `Editor.ExecuteCommand`) that drives keyboard shortcuts, the desktop application menu bar, and the Command Palette from one source of truth: - **Platform shortcuts and text-field guard**: shortcuts use NSGo's `"mod"` modifier (Command on macOS, Ctrl on Windows and Linux; formatted via `FormatShortcut`) and are bound with `core.KeyNotEditing` and `core.MenuNotEditing` so typing or pressing Delete/Backspace/Undo/Save while any text field has focus (such as the inspector's Name field or a search box) never triggers editor shortcuts. When two enabled commands in different scopes share a key, the more specific active scope wins (`shortcutScopePriority`): in 2D with no tile tool active (such as Select), **Viewport** outranks **Tile**, so `e` selects **Rotate** and `r` selects **Scale**; once any tile tool (`b`, `g`, `t`, `u`, `l`, `c`, `n`) is active, **Tile** takes precedence and `e` switches to **Erase Tile**. In 3D (`alt+3`), **3D Viewport** takes `w`, `e`, `r`, `t`, and the axis/camera keys (`1`, `ctrl+1`, `3`, `ctrl+3`, `7`, `ctrl+7`, `5`, `0`); the Lit, Unlit, and Wireframe shading commands under `View > 3D Shading` and `View > Scene Environment` have no shortcut, and `f` (`Frame Selection`) frames the independent 2D `View2D` via `FrameSelection2D` without mutating `Doc.Camera` (and `Camera3D` in 3D). While the right-rail **Agent** tab is active, **Agent** takes `mod+n` (`CmdNewAgentThread`) over `File > New Project...`; while Play mode is running, **Play** takes `mod+l` (`CmdAskFrozenFrame`) over `Ask the Agent About Selection`. - **Global**: `mod+n` (New Project...), `mod+o` (Open Project...), `mod+s` (Save), `mod+w` (Close Scene Tab), `mod+z` (Undo), `mod+shift+z` (Redo), `mod+c` (Copy), `mod+x` (Cut), `mod+v` (Paste), `mod+shift+v` (Paste as Child), `alt+2` (Switch to 2D View), `alt+3` (Switch to 3D View), `mod+l` (Ask the Agent About Selection), `mod+1` (Agent Panel), `mod+2` (Inspector Panel), `mod+k` (Command Palette), `mod+/` (Keyboard Shortcuts), `mod+shift+t` (Background Tasks), `mod+y` (History), `mod+shift+,` (Project Settings), `mod+shift+f` (Project Search & References), `mod+shift+u` (HUD & Menu Layout), `mod+shift+e` (Export & Release), `mod+shift+r` (Build & Release Screen), `mod+shift+m` (Profiler), `mod+shift+b` (Check Problems), `shift+f12` (Find Usages), `mod+,` (Editor Settings), `mod+shift+y` (Playtest Report), `mod+enter` (Keep Agent Turn), `mod+backspace` (Revert Agent Turn), `mod+.` (Stop Agent). - **Viewport**: `delete` / `backspace` (Delete Selected Object), `mod+d` (Duplicate Selected Object), `mod+g` (Group Selected Objects), `mod+shift+g` (Ungroup Selected Object), `v` (Tool: Select), `w` / `m` (Tool: Move), `e` (Tool: Rotate), `r` (Tool: Scale), `space` (Tool: Pan), `p` (Tool: Place), `f` (Frame Selection). - **2D Viewport**: `d` (Sketch on Viewport), `mod+enter` (Sketch: Go Ahead), `shift+m` (Sketch: Correct a Mark), `o` (Review: Toggle Sketch Overlay), `mod+shift+enter` (Review: Keep Changes and Clear Sketch), `mod+backspace` (Review: Revert Changes and Keep Sketch). - **3D Viewport**: `w` (3D Gizmo: Translate), `e` (3D Gizmo: Rotate), `r` (3D Gizmo: Scale), `shift+c` (3D Gizmo: Collider), `1` (3D View: Front), `ctrl+1` (3D View: Back), `3` (3D View: Right), `ctrl+3` (3D View: Left), `7` (3D View: Top), `ctrl+7` (3D View: Bottom), `5` (3D View: Orthographic), `t` (3D Gizmo: Local / Global Space), `0` (3D View: Scene Camera). - **Tile**: `b` (Tool: Paint Tile), `e` (Tool: Erase Tile), `g` (Tool: Fill Tile), `t` (Tool: Terrain), `u` (Tool: Rectangle Tile), `l` (Tool: Line Tile), `c` (Tool: Stamp Tile), `n` (Tool: Random Tile). - **Sketch**: `p` (Sketch Tool: Pen), `a` (Sketch Tool: Arrow), `b` (Sketch Tool: Box), `t` (Sketch Tool: Text), `i` (Sketch: Add Mark at Cursor), `mod+z` (Sketch: Undo Last Mark), `h` (Sketch: Hide / Show Marks), `mod+shift+backspace` (Sketch: Clear Marks), `shift+d` (Sketch: Finish Sketch Mode), `mod+enter` (Sketch: Send to Agent). - **Review**: `j` (Review: Next Change), `k` (Review: Previous Change), `c` (Review: Note for the Agent), `x` (Review: Revert or Restore), `b` (Review: Peek Before Request), `mod+enter` (Review: Keep Changes), `mod+backspace` / `mod+delete` (Review: Revert All). - **Play**: `mod+p` / `f5` (Play / Stop), `alt+f` (Mark Play Moment), `mod+l` (Something Looks Wrong), `mod+r` (Run Game), `mod+shift+d` (Debug Game). - **Agent**: `mod+n` (New Agent Thread). - **Desktop menu bar**: `EditorView` registers the native application menu bar (`File`, `Edit`, `View`, `Project`, `Help`) through `desktop.SetApplicationMenu` (`Editor.ApplicationMenu`), exposing the same registered commands with live enabled/checked states, formatted shortcut hints, active plugin tools under `View > Tools`, active plugin commands under `Project > Plugins`, and `Help` (`Replay tips`, `Keyboard Shortcuts`, `Check for Updates...`). **Check for Updates...** (`CmdCheckForUpdates`, also in the Command Palette) runs `updater.Check`: a released editor checks its GitHub release's appcast and offers a newer version in Sparkle's window on macOS, WinSparkle's on Windows, and an alert that installs the signed package on Linux; released copies also check once a day on their own. A copy run from source with `go tool nsgo dev` says it does not update. - **Command Palette (`ui.CommandDialog`)**: press `mod+k` (or the header bar's **Search `⌘K`** button / `View > Command Palette...`) to open `CommandPaletteView`, which lists every built-in and custom command, active plugin commands, active plugin tools (activating them via `SetPluginTool`), active plugin panels (focusing them via `FocusPluginPanel`), and the open project's scenes and files (opening scenes or selecting files via `OpenProjectFile`) with ranked substring and fuzzy matching. - **Platform shortcuts and text-field guard**: shortcuts use NSGo's `"mod"` modifier (Command on macOS, Ctrl on Windows and Linux; formatted via `FormatShortcut`) and are bound with `core.KeyNotEditing` and `core.MenuNotEditing` so typing or pressing Delete/Backspace/Undo/Save while any text field has focus (such as the inspector's Name field or a search box) never triggers editor shortcuts: - File & Edit: `mod+s` (Save), `mod+z` (Undo), `mod+shift+z` (Redo), `mod+c` (Copy objects or active tile region), `mod+x` (Cut objects or active tile region), `mod+v` (Paste objects or tile region), `mod+shift+v` (Paste as Child), `mod+d` (Duplicate), `mod+g` (Group), `mod+shift+g` (Ungroup), `delete` / `backspace` (Delete selected objects). - 2D Tools: `v` (Select), `m` (Move), `p` (Place), `b` (Paint Tile), `e` (Erase Tile), `g` (Fill Tile), `t` (Terrain), `u` (Rectangle Tile), `l` (Line Tile), `c` (Stamp Tile), `n` (Random Tile). - 3D Gizmo & View: `w` (Translate), `e` (Rotate), `r` (Scale), `t` (Local / Global space), `shift+c` (Collider), `alt+2` (2D View), `alt+3` (3D View), the Lit, Unlit and Wireframe 3D shading commands under `View > 3D Shading` (no shortcut), `f` (Frame Selection, framing the independent 2D `View2D` via `FrameSelection2D` without mutating `Doc.Camera` and `Camera3D` in 3D), `1`, `ctrl+1`, `3`, `ctrl+3`, `7` and `ctrl+7` (the Front, Back, Right, Left, Top and Bottom 3D views), `5` (3D perspective or orthographic) and `0` (Look Through Scene Camera), which work in the 3D view only, `View > Scene Environment` (toggle the Environment panel), `mod+k` (Command Palette). - Project: `f5` (Play / Stop), `mod+r` (Run Game via `Editor.OnRunGame`, falling back to play-in-editor when a scope is attached), `mod+shift+d` (Debug Game under Delve), `mod+,` (Settings), `mod+shift+,` (Project Settings), `mod+shift+u` (HUD & Menu Layout), `mod+shift+e` (Export & Release panel), `mod+shift+r` (Build & Release screen), `mod+shift+m` (Profiler), `mod+shift+b` (Check Problems). - **Desktop menu bar**: `EditorView` registers the native application menu bar (`File`, `Edit`, `View`, `Project`) through `desktop.SetApplicationMenu` (`Editor.ApplicationMenu`), exposing the same registered commands with live enabled/checked states, formatted shortcut hints, active plugin tools under `View > Tools`, and active plugin commands under `Project > Plugins`. - **Command Palette (`ui.CommandDialog`)**: press `mod+k` (or the toolbar's **Commands** button / `View > Command Palette...`) to open `CommandPaletteView`, which lists every built-in and custom command, active plugin commands, active plugin tools (activating them via `SetPluginTool`), active plugin panels (focusing them via `FocusPluginPanel`), and the open project's scenes and files (opening scenes or selecting files via `OpenProjectFile`) with ranked substring and fuzzy matching. - **Plugin commands**: plugins can declare `Commands []PluginCommand` with an optional `Shortcut`. `RegisterPlugin` normalizes each shortcut (`NormalizeShortcut`) and refuses any shortcut that clashes with a built-in, custom, or other registered plugin command across macOS and Windows/Linux before mutating the editor. ## Asset import settings and rebuilding (#915) Selecting an image (`.png`, `.jpg`, `.jpeg`, `.webp`), sound (`.wav`, `.ogg`, `.mp3`, `.flac`), font (`.ttf`, `.otf`), or 3D model (`.gltf`, `.glb`) in the file browser (`SelectedFile`, excluding generated target outputs and `*.import.yaml` sidecars) displays its import settings and credit metadata in the Inspector (`InspectorView`): - **Sidecar and target defaults**: `InspectAssetImport` reads the asset's `*.import.yaml` sidecar when present and overlays it on the matching target's defaults in `game.yaml`'s `assets` section (image `filter`, `format`, `mipmaps`, `srgb`, sprite-sheet `slice`, and frame `pivot`; audio `format`, `rate`, `channels`, `bitrate`, `peakDB`/`rmsDB` normalization, and `loop`; font `size`, `padding`, and `chars`; model `scale`, `animations`, `lodHysteresis`, and `lods`), plus the shared `credit` section (`author`, `license` as an SPDX expression, `source`, and `notice`). - **Interactive sprite-sheet slice grid and frame pivots (#880)**: when an image is selected, the import panel shows an interactive preview canvas (`DrawImageImportPreview`) over a transparency checkerboard with the live slice grid (`width`, `height`, `margin`, `spacing`, `count`) and draggable pivot markers per cell (or a single marker when unsliced). Authors can drag any marker directly on the preview (`BeginImagePivotDrag` / `UpdateImagePivotDrag` / `EndImagePivotDrag` / `CancelImagePivotDrag`), pick default presets (`TL`, `Center`, `Bottom`), or edit/reset `pivot.default` and per-cell `pivot.cells` numerically (`SelectImportSliceCell`, `SetImageImportPivot`, `SetImageImportDefaultPivot`, `SetImageImportCellPivot`). Every drag commits once to the sidecar as a single undoable step, and running **Reimport** or **Build Assets** writes those pivots into the packed TexturePacker JSON so `sprite.LoadAtlas` loads exact `Frame.PivotX` and `Frame.PivotY` values immediately. - **Interactive glTF/GLB model preview and animation playback (#897)**: when a `.gltf` or `.glb` model is selected in the file browser, the import panel renders the model through an orbit camera (`DrawModelPreview`, `RenderModelPreview`, `OrbitModelPreview`, `PanModelPreview`, `ZoomModelPreview`, `ResetModelPreviewCamera`) reflecting the effective import `scale`, and inspects its contents (`InspectModelImport`): unscaled and scaled bounds, total triangle and vertex counts, and lists of its nodes, meshes, materials, and animations. Each animation can be selected, played, paused, stopped, looped, or scrubbed (`SelectModelPreviewAnimation`, `PlayModelPreviewAnimation`, `PauseModelPreviewAnimation`, `StopModelPreviewAnimation`, `SeekModelPreviewAnimation`, `StepModelPreviewAnimation`), supporting node TRS transforms, skeletal skinning, and morph targets. Editing `scale`, `animations`, `lodHysteresis`, or `credit` writes the deterministic sidecar through `importsettings.Encode` and shows which `game.yaml` model target reads the file, so the next `game assets` run rebuilds only that model. - **Validated undoable edits and field reset**: every change writes the sidecar atomically through `importsettings.Encode` as one undoable `Editor.History` step (`EditAssetImportSettings`, typed `SetImageImport*` / `SetAudioImport*` / `SetFontImport*` / `SetModelImport*` setters, and `SetAssetImportCredit`). **Undo** restores the exact previous sidecar bytes verbatim (or removes a newly created sidecar file), and **Reset** (`ResetAssetImportField`) clears an override back to the target's default, removing the sidecar once no overrides or credit remain. - **Reimport, Build Assets, and live reload**: the inspector's **Reimport** button (`ReimportAsset`) and the Command Palette's **Build Assets** command (`CmdBuildAssets`, `BuildAssets` / `BuildAssetsWith`) run `go tool game assets` off the UI goroutine, streaming stdout and stderr into the docked **Output** panel (`OutputPanelView`). On completion, `ReloadAssets` reloads changed atlases and textures from disk into `Editor.Resolver` (updating `sceneformat.AtlasMap` or existing `*sprite.Atlas` values in place and invoking `AssetReloader` / `OnReloadAssets` when set), refreshes the Asset Browser and Viewport immediately without restarting the editor, and re-runs the Problems check. Custom tools and tests can inject `Editor.AssetsCommandRunner`. ## Profiler panel and frame time strip (#912) While playing in the editor or connected to a running game over MCP (`game_perf_readout`, `game_perf_zones`, `game_perf_reset`), the editor displays a live frame-time strip beneath the viewport and opens a full Profiler panel styled with the editor's design spec tokens (`design/editor/PlayMode.dc.html` and `Spec.dc.html`): - **Play-mode `FRAME TIME · LAST 60 S` strip (`ProfilerStripView`)**: always visible below the game view while Play mode is active or a remote game is connected (`ConnectProfiler`). It shows `avg`, `p99`, and `allocs/frame` from `game_perf_readout`, threshold lines and legend markers at `8.3 ms` (`over 8.3 ms`) and `16.7 ms` (`missed 16.7 ms`), the `−60 s`, `−30 s`, and `now` axis, and a callout pill labelling spikes with their cause when the game supplies one via `gamedebug.Overlay.NoteFrameCause` (or `"GC pause"` on GC hitches). Pressing the strip's **Profiler** button opens the full Profiler panel. - **Connecting to a running game**: connect via `ConnectProfilerMCP` (official MCP Go SDK over any `mcp.Transport`), `ConnectProfilerCommand` (spawning `go tool nsgo mcp`), `ConnectProfilerScope` (an in-process `*core.Scope` with `mcp.Bridge` attached), or `NewBridgeProfilerClient`, and pass the client to `Editor.ConnectProfiler`. While attached to a scope, the editor polls `game_perf_readout` and `game_perf_zones` every `Editor.ProfilerPollInterval` (default `250 ms`), or on demand via `Editor.PollProfiler`. Built-in Play mode (`Play` / `PlayIn`) also instruments its loop with `gamedebug.Overlay`, `gamedebug.Profiler`, and `gamedebug.GCMonitor` automatically when no external profiler client is connected. - **Full Profiler panel (`ProfilerPanelView`)**: toggleable from the strip, status bar **Debugger** button, `Project > Profiler`, Command Palette, or `mod+shift+m` (`CmdProfiler` / `SetProfilerOpen`). It displays live KPI cards and switchable time-series charts (`SetProfilerMetric`) for **Frame** (stacked update, draw, total, and GC hitch markers with 8.3 ms / 16.7 ms lines), **FPS**, **Allocs & GC** (allocations per frame, live heap bytes, and GC hitches), and **Memory** (tracked asset memory against budget and per-group totals), alongside a scrollable table of named timing zones from `game_perf_zones` sorted by cost. - **Reset and Chrome/Perfetto trace export**: pressing **Reset** (`Editor.ResetProfiler`) invokes `game_perf_reset` on the connected game and clears the editor's recorded history and zone table. Pressing **Export Trace** (or calling `Editor.ExportProfilerTrace` / `Editor.ExportProfilerTraceFile`, or intercepting via `Editor.OnExportProfilerTrace`) writes the recorded frames and zones as Chrome/Perfetto Trace Event Format JSON through `gamedebug.Profiler.WriteChromeTrace`. ## Start screen (#922) Running `go tool game editor` with no arguments opens the Start Screen (`StartScreenView`, toggled with `SetStartScreenOpen`), designed from `design/editor/Start.dc.html`, step 1 of `FirstRun.dc.html`, and the `Spec.dc.html` tokens: - **Recent projects (`RecentProjects`, `ParseRecentProjects`, `EncodeRecentProjects`)**: opening a project records its name, directory path, and UTC RFC3339 `lastOpened` timestamp in a strict versioned per-user YAML file outside any project (`/nsgo-game/recent-projects.yaml` via `DefaultRecentProjectsPath`, or `Editor.RecentProjectsPath`). The sidebar's **RECENT** list appears once at least one project has been opened, displays relative times, marks entries whose folder or `game.yaml` is missing on disk (`Missing`) with a badge and remove action (`RemoveRecentProject`), and persists across restarts. - **Open folder (`BrowseAndOpenProject`)**: opens a project directory through NSGo's native folder picker (`core.Scope.PickDirectories`) or the injectable `Editor.PickProjectFolder` hook. - **New project from template (`ProjectTemplates`, `StartCreateProject`)**: template cards and `All` / `2D` / `3D` filter chips are populated dynamically from `game new`'s template registry, so newly added templates appear without editor changes. The project name, parent folder (defaulting to `~/games`), and optional module path are validated live as typed (`ValidateNewProjectInputs`): checking `a–z`, `0–9`, and `-` characters, write access to the parent folder, and existing folders (offering **Open it** or the next free sibling name such as `dungeon-run-2`). Pressing **Create** runs `game new` (including its `go get` and `go mod tidy` steps) off the UI goroutine while streaming stdout and stderr into the Start Screen, then opens the created `game.yaml`. - **Open Demo (`OpenDemo`, `NewDemo`)**: opens the built-in Demo Room scene without creating or opening a project on disk. - **Start with AI — from one sentence to the first review (#1051, #1505)**: pressing **Start with AI** (`StartWithAI`) runs the five-stage flow in `design/editor/FirstRun.dc.html` backed by the connected agent and the editor's MCP server: - **WHAT HAPPENS NEXT & Connect in place**: the Start Screen lists the three steps (**Connect an agent**, **Approve its plan**, **Review the first scene**). When no agent is connected yet, **Start with AI** opens **Connect an agent** (`FirstRunStageConnect`) in place on the Start Screen while preserving the idea and project name (with **Edit** and **Later** returning cleanly to Step 1). It detects `claude` and `codex` on `PATH` (or via `Editor.FirstRunDetectAgents`), connects by querying the editor's MCP server tool count (`Editor.AgentTools`) and running a readiness probe through `Editor.AgentRunner` / `CLIAgentRunner` (failing visibly with diagnostics when the MCP server or CLI cannot answer, replaceable via `Editor.FirstRunConnectAgent`), or validates a pasted API key immediately with a minimal request to `BuiltInAgentEndpoint` (never written to YAML, replaceable via `Editor.FirstRunValidateAPIKey`). - **The first plan (`FirstRunStagePlan`, `OpenFirstRunPlan`)**: asks the connected agent to propose a plan tailored to the author's idea via `plan_propose` (or a structured JSON plan response, replaceable via `Editor.FirstRunPlanner`), displaying any clarifying question, numbered steps, and dashed-violet ghosts (`FirstRunGhost`) beside the read-only template preview viewport with **Just do it** (`JustDoItFirstRunPlan`) and **Approve ⌘↵** (`ApproveFirstRunPlan`). Planning runs off the UI goroutine when mounted so MCP `plan_propose` calls never block the UI, and fails visibly with **Try again** when the agent cannot produce a plan. No project folder is created on disk until **Approve**. - **Building (`FirstRunStageBuilding`)**: after **Approve** creates the brand-new folder, the editor scaffolds the project, opens the target scene, asks the connected agent to build it via `scene_edit` (streaming live object counts and placed object labels from the scene), runs `project.Check` and `assetcheck`, and runs `go tool game playtest` (or `Editor.FirstRunPlaytest`) when `playtest.yaml` exists — or marks Playtest **Skipped** with an honest label when the template has no `playtest.yaml`. Pressing **Cancel** or `Esc` pauses and asks first (**Keep building**, **Stop, keep the files**, or **Stop and delete the folder** — offered and permitted only for the brand-new folder created by this flow, never touching sibling or pre-existing folders). A failed `Check` stops before the review with a proposed fix (**Fix it** / **Review as is**). - **The first review & one-time tips (`FirstRunStageReview`)**: derives its change list, counts, shapes, and deviations directly from the actual project files and scene written on disk, displaying the plan summary on top, **Before / After** toggle plus hold-`B` peek (`Before: an empty folder`), per-change revert/restore toggles, **Revert all**, and **Keep N of M** (`KeepFirstRunReview`). Three onboarding tips (**keep or revert each change**, **hold B**, **select then ⌘L**) show one at a time and once per person, stored under `seenTips` in `EditorSettings` (`editor.yaml`); **Skip tips** ends all three and **`Help › Replay tips`** (`CmdReplayTips` / `ReplayTips`) clears them and brings them back. - **Clean project switching and unsaved-edits prompt**: opening a project from the Start Screen or later through `File > Open Project...` (`mod+o`), `File > New Project...` (`mod+n` outside the right-rail **Agent** tab, where `ScopeAgent` binds `mod+n` to `CmdNewAgentThread` instead), or `File > Start Screen` replaces the current project, scene, clip, cutscene, data table, localization workspace, skeletal rig, and undo history cleanly. Whenever the open session has unsaved edits (`HasUnsavedChanges`), the editor's unified unsaved-changes dialog asks to **Save** (`ConfirmSaveAndSwitch`), **Discard** (`ConfirmDiscardAndSwitch`), or **Cancel** (`CancelPendingSwitch`) before replacing anything. ## 3D LOD and occluder visualization (#904) In 3D view (`View3D`), the viewport runs the same `scenemodel.Build` + `render3d.OcclusionBuffer` + `render3d.Queue` evaluation used at runtime (automatically backed by `scenemodel.NewAssets` when a project is open, or an injected `Editor.ModelResolver`): - **LOD overlay (`ShowLODOverlay` / `SetShowLODOverlay`)**: color-codes each multi-LOD object by its active level and draws a `LOD` badge beside it in the viewport; the 3D inspector also reports the selected object's active LOD (`ObjectLOD3D`, `ObjectLODCount3D`). Editing a model's `lods` or `lodHysteresis` in the asset import inspector invalidates the 3D build so switches take effect immediately. - **Occluder visualization and editing (`ShowOccluders` / `SetShowOccluders`, `SetObjectOccluder`)**: draws magenta wireframes with `OCC` / `OCC BOX` badges for every visible occluder (including explicit `box` occluders and `model` occluders), dims objects culled behind an occluder (`ObjectOccluded3D`), and exposes undoable Occluder mode (`none` / `model` / `box`), box size, and double-sided controls in the 3D inspector (raising version 1 scenes to version 2 automatically). - **RenderStats overlay (`ShowRenderStats` / `SetShowRenderStats`, `RenderStats3D`)**: displays the live `render3d.RenderStats` readout (`Draws`, `Visible`, `Occluded`, `Tris`, `Verts`, plus active per-object `LOD` levels) in the bottom-right corner of the 3D viewport, toggleable alongside the LOD and Occluders overlays from the 3D viewport bar's **Overlays** popover (`view3d-overlays`), `View > Overlays`, or the Command Palette (`CmdToggleLODOverlay`, `CmdToggleOccluders`, `CmdToggleRenderStats`). ## Remote scene tree and live inspector (#911) While a game built with [`game/mcp`](http://nsgo.games/docs/mcp/) runs with `-automation`, the editor connects as an MCP client (using `github.com/modelcontextprotocol/go-sdk/mcp` over `go tool nsgo mcp` on desktop, or any `mcp.Transport` passed to `ConnectRemote` / `Editor.RemoteTransport`) to inspect and tune the running game live: - **Connecting**: enable **Auto-connect on Run** in the **Remote** tab (`SetRunWithAutomation`) or call `RunGameWith(RunGameOptions{Automation: true})` to pass `-automation` to `go tool game dev` and connect automatically once the game starts, or call `ConnectRemote` / `ConnectRemoteCommand` to attach to an already-running game. `NewRemoteBridgeServer(bridge, run)` wraps a `*mcp.Bridge` directly as an MCP server for deterministic in-process or pipe testing. - **Remote tab beside the Scene Tree**: switch between **Scene** (`SceneTreeLocal`) and **Remote** (`SceneTreeRemote`) in `SceneTreeView`. The Remote tab lists active scenes (`game_scenes_list`), layers in draw order (`game_layers_list`), and live entities with their parent-child hierarchy (`game_entities_list`), refreshed automatically while unpaused (interval `Editor.RemoteRefreshInterval`, default 250 ms) or on demand via `RefreshRemote`. Entities without a scene `ObjectRef` group under **SPAWNED AT RUNTIME**, and scene objects that are destroyed while running appear dimmed with the step they were taken at. - **Live Inspector and Live Changes**: selecting a live entity (`SelectRemoteEntity`) inspects its components (`game_entity_inspect`) in `InspectorView`. Read-only derived components (`world_transform2d`, `object_ref`) show live readouts, while editable components render typed controls that patch the running game immediately through `game_component_set` (`SetRemoteComponentField` / `SetRemoteComponentValue`) and display `"was X"` beside changed fields. Every live edit is recorded in **LIVE CHANGES** (`RemoteLiveChanges`), which stays after disconnecting or stopping the game: revert individual rows (`RevertRemoteLiveChange`), discard all (`DiscardRemoteLiveChanges`), or press **Keep in scene** (`KeepRemoteLiveChangesInScene`) to write all changes on scene-backed entities into the open scene as a single undoable `History.Group` step that one Undo restores. - **Live Play Bar, Tunables, Variables, and Console**: while connected, the Play Bar exposes **Pause / Resume** (`mod+shift+p`, `RemotePause` / `RemoteResume`), **Step** (`.` while paused) and **Step N** fixed updates (`RemoteStep`), **Time Scale** (`0.25×`, `0.5×`, `1×`, `2×`, `RemoteSetTimeScale`), and live frame/time/entity readouts in the status bar. When the game configures a `gamedebug.Console`, the Remote Inspector also lists live **Tunables** (`game_tunables_list` / `RemoteSetTunable`) and a **Console** command line (`RemoteExecConsole` / `game_console_exec`); when it configures a `flow.Vars` store, the Remote Inspector lists and edits live **Variables** (`game_vars_list` / `RemoteSetVar`) and displays active per-object **Self Variables**. ## 3D terrain sculpting and painting (#900) In 3D view (`ViewMode3D`), choose **Project > 3D Terrain Editor** or the Command Palette (`CmdTerrainEditor`)—or open a `*.terrain.yaml` file from the file browser via double-click / **Terrain**, or call `NewTerrain`, `OpenTerrainFile`, `OpenTerrainProjectFile`, or `OpenTerrain` in Go—to edit a `world3d` terrain directly in the 3D viewport with the docked `TerrainPanelView` below it: - **Sculpt and paint brushes**: choose `TerrainBrushRaise`, `TerrainBrushLower`, `TerrainBrushSmooth`, `TerrainBrushFlatten` (targeting the height sampled where the stroke starts, or `TargetHeight` when `UseTargetHeight` is set), `TerrainBrushSetHeight` (`TargetHeight`), `TerrainBrushPaintLayer` (increasing the active texture layer's weight while keeping all layers normalized to 1), or `TerrainBrushPaintFoliage` (blending the active foliage layer's density toward `TargetDensity` in `[0, 1]`, where `0` erases). Configure `Radius`, `Strength`, and `Falloff` (`TerrainFalloffSmooth`, `TerrainFalloffLinear`, `TerrainFalloffFlat`) via `SetTerrainBrush` or the panel controls. - **3D raycast strokes and single-step Undo/Redo**: clicking or dragging across the terrain in the 3D viewport raycasts against the live `world3d.Heightmap` (`RaycastTerrain3D`, `BeginTerrainStrokeAt` / `ContinueTerrainStrokeAt` / `EndTerrainStroke`, or world-coordinate `BeginTerrainStroke` / `ContinueTerrainStroke`), interpolates continuous dabs along fast drags, draws a terrain-conforming brush radius ring overlay, and records each complete stroke as **one undo step** in `Editor.History` (with `Escape` / `CancelTerrainStroke` aborting an active stroke cleanly). Undo and Redo restore exact heightmap, layer-weight, and foliage-density samples and track `TerrainDirty()` / `HasUnsavedChanges()`. - **Lossless 16-bit saving**: **Save Terrain** (`SaveTerrain`, `SaveTerrainTo`, or `Save` when dirty) writes the 16-bit grayscale PNG heightmap (`*image.Gray16`, eliminating 8-bit slope banding), per-layer grayscale weight-map PNGs (or packed RGBA `splatMaps`), foliage density-map PNGs, and deterministic `*.terrain.yaml` atomically so `world3d.LoadTerrainFS`, `TerrainDoc.ScatterFoliage`, and `render3d.TerrainMaterialFromDoc` load and draw the exact same terrain in the game. ## Particle emitter editor (#883) The Particle Emitter Editor (`ParticleEditorPanelView`), opened via **Project > Particle Emitter Editor**, the Command Palette (`CmdParticleEditor`), by double-clicking a `*.particles.yaml` / `*.emitter.yaml` file or pressing **Open Emitter** in the file browser, or from the Inspector's **Edit Emitter** button on an object with `particles`, edits every field of a 2D `particles.Config` with live preview and full Undo/Redo: - **Live preview without restart**: the panel runs a live `*particles.Emitter` (`ParticlePreview`) on a preview canvas with **Play/Pause** (`PlayParticlePreview` / `PauseParticlePreview`), **Restart** (`RestartParticlePreview`), **Step** (`StepParticlePreview`), **Burst** (`BurstParticlePreview`), **Preview Atlas** (`SetParticlePreviewAtlas`), and an optional **Floor** collider (`SetParticlePreviewFloor`) to test bounce/stop/kill collisions. Editing rate, curves, motion, or other fields calls `Emitter.ReloadConfig` so the running preview reflects changes live without restarting or clearing live particles. When no atlas or frames are bound, the preview draws colored fallback discs so particles remain visible while tuning. - **Every emitter field & interactive curve widget**: edits `space`, position, rotation, `z`, `seed`, `shape` (`point`, `circle`, `ring`, `rect`), `rate`, `maxParticles`, scheduled `bursts` (add/edit/remove `time`, `count`, `cycles`, `interval`), `lifetimeMin`/`Max`, `speedMin`/`Max`, `angleMin`/`Max`, `gravityX`/`Y`, `initialRotationMin`/`Max`, `rotationSpeedMin`/`Max`, `collision`, `trail`, and recursive `subEmitters` (navigate into any child config via `SetParticleTargetPath` / **Edit Child**). The curve widget plots `sizeCurve`, `alphaCurve`, `rotationCurve`, `colorCurve`, `trail.widthCurve`, and `trail.colorGradient` on an interactive canvas where stops can be dragged, clicked to add, or edited numerically, and the atlas frame picker toggles `frameNames` directly from the resolver's atlases. - **Undo/Redo and deterministic save**: every edit goes through `Editor.History`, and **Save Emitter** (`SaveParticleEmitterFile` / `SaveParticleEmitterYAML` / `OnSaveParticleEmitter`) writes canonical versioned YAML (`particles.MarshalConfigYAML`) that round-trips unchanged and hot-reloads matching emitters already placed in the open scene. - **Scene placement**: bind any object's `particles` field via `SetObjectParticles`, `PlaceParticles`, or the Inspector's **PARTICLES** section (`file` and `atlas` pickers). Placed emitters animate live in the 2D edit viewport (`StepSceneEmitters`, hidden when the object is hidden), run in Play mode (`PlayIn`) and in the game (`sceneformat.Build`), are scanned by `tooling/refs` (`MoveFile` rewrites `particles.file`), and are validated by `assetcheck`. ## Language and appearance settings (#921) The editor UI is localized in English (`en`) and Simplified Chinese (`zh`) through embedded versioned `l10n` YAML string tables (`editor/locales/en.yaml`, `editor/locales/zh.yaml`), and per-user preferences are stored outside any project as deterministic versioned YAML: - **Per-user settings file (`EditorSettings`, `SettingsVersion = 1`, #921, #1005, #1006, #1028)**: stored at `DefaultSettingsPath()` (under `os.UserConfigDir()` as `nsgo-game/editor.yaml`, outside every game project) and loaded/saved with `ParseEditorSettings`, `EncodeEditorSettings`, `LoadEditorSettings`, `SaveEditorSettings`, `Editor.LoadSettings`, `Editor.LoadUserSettings`, and `Editor.SaveSettings`. It stores `version`, `language`, `appearance`, optional `autoSave` (defaults to `true` when omitted), optional `interfaceSize` (`compact`, `default`, or `large`), optional `snap` (per-person defaults for `grid`, `gridSize`, `pixel`, `rotation`, `rotationStepDeg`, `scale`, `scaleStep`, and `showGrid`, used when a project does not override snap in `.game/editor.yaml`), optional `showAgentChanges` (defaults to `true` when omitted), optional `navigation3D` (`default`, `blender`, or `maya`), optional `viewportOverlays` (canonical sorted list of enabled 2D viewport overlay IDs; omitted for defaults, `[]` for all off), optional `overlayLegend` (canonical sorted list of enabled Spec viewport overlay legend kinds: `selection`, `agent`, `added`, `changed`, `removed`, `problem`; omitted enables all six, `[]` hides all six), optional `shortcuts`, optional `seenTips`, and optional `agent` preferences (task routing, MCP tool toggles, external MCP servers, weekly request limit, outbound privacy switches, and local usage counters; secrets such as API keys are never stored in `editor.yaml`). Unknown keys, YAML anchors/aliases/merge keys, trailing documents, negative/non-finite snap steps, and invalid enum values are refused with `*loaderr.Error`. Output is deterministic 2-space YAML prefixed with `SettingsSchemaComment` so a load-save round trip changes nothing byte-for-byte. Its published JSON Schema is `https://nsgo.games/schemas/editor-settings.v1.json` (`SettingsSchemaURL`). ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/editor-settings.v1.json version: 1 language: system appearance: system autoSave: true interfaceSize: default snap: grid: true gridSize: 16 rotation: true rotationStepDeg: 15 showGrid: true showAgentChanges: true navigation3D: default shortcuts: view.frame: g ``` - **Unified Settings window (`SettingsView`, `⌘,` / `Esc`, #1005)**: - **Opening, closing, and focus restoration**: pressing `⌘,` (`mod+,`, `CmdEditorSettings`) opens the full-window Settings view (with or without an open project) and pressing `Esc` closes it, returning keyboard focus to the exact control that had focus before opening. - **Grouped navigation and page anatomy**: the left navigation list is grouped into **`AGENT`** (Models and connections, Permissions, Game brief, Project rules, Tools, Usage and privacy), **`PROJECT · game.yaml`** (Project, Input map, Audio buses, Export — hidden when no project is open), and **`EDITOR · THIS COMPUTER`** (General, Viewport, Shortcuts), with a live meta line on each entry and no empty group headings. Each page shows its title, one-line subtitle, and scope chip (`"This computer"`, `"Project · shared"`, or `"Project · game.yaml"`), and each row renders a label, help text, value control, and `"Agent may change"` or `"You only"` policy column. - **Search and agent handoff**: typing into the top search field (`"Search settings, or tell the agent what you want"`) matches setting labels and help text across all pages, narrowing both the sidebar navigation (hiding non-matching pages and empty groups) and the rows on the active page. When no setting matches and the agent panel is enabled, Settings offers sending the query directly to the agent (`AskAgentFromSettings`). - **General page (`SettingsPageGeneral`)**: edits **Language** (`Editor.SetLanguage`), **Appearance** (`Editor.SetAppearance`), **Save automatically** (`Editor.SetAutoSave`, kept changes only after 2 s), and **Interface size** (`Editor.InterfaceSize`, `Editor.SetInterfaceSize`: `Compact`, `Default`, `Large`, scaling text and controls together). - **Viewport page (`SettingsPageViewport`, `OpenViewportSettings`)**: edits **Snap** (toggle + grid step in `px` + rotation angle in `°`, hold `⌘` to ignore), **Grid** (dots/grid every snap step, `SetShowGrid`), **Show agent changes** (`Editor.ShowAgentChanges`, `Editor.SetShowAgentChanges`: outlines in the viewport while a review is open), **3D navigation** (`Editor.Navigation3D`, `Editor.SetNavigation3D`, `Navigation3D.Resolve`: `Default` — left-drag orbit / Shift+left-drag or middle-drag pan / right-drag fly; `Blender` — middle-drag orbit / Shift+middle-drag pan / right-drag fly / left-drag select & gizmos; `Maya` — Alt+left-drag orbit / middle-drag or Alt+middle-drag pan / Alt+right-drag dolly / plain right-drag fly / plain left-drag select & gizmos; wheel dollies and touch/trackpad gestures stay unchanged in all modes), and every toggleable **Overlay legend** choice (`ViewportOverlays`, persisted per computer). - **Keyboard and accessibility**: `ArrowDown` / `ArrowUp` / `Home` / `End` move through the left navigation list; every on/off toggle uses `SpecSwitch` (`RoleSwitch` with `aria-checked` and a 2 px Spec accent focus ring); every row is reachable with `Tab`. - **Automatic saving and status bar save status (#1016)**: - **General › Save automatically (`Editor.AutoSave`, `Editor.SetAutoSave`)**: enabled by default and persisted as `autoSave` in `EditorSettings`. Kept changes to file-backed scenes and `game.yaml` save automatically after a 2-second debounce (`DefaultAutoSaveDelay`, configurable via `Editor.AutoSaveDelay`). Edits inside an open review (`Editor.HasOpenReview()`, including `BeginReview` / `KeepReview`, cutscene reviews, playtest metric reviews, safe rename reviews, merge conflicts, and unresolved disk conflicts) are not kept yet and pause autosave until kept. - **Status bar save item (`Editor.SaveStatus`, `SaveStatusSaved` / `SaveStatusSaving` / `SaveStatusFailed`)**: displays muted `Saved` (hover tooltip shows the last save time), transitions to `Saving…` only after a write has stayed in flight for at least 300 ms (`DefaultSavingIndicatorDelay`, configurable via `Editor.SavingIndicatorDelay`) so quick saves never flicker, and keeps failed autosaves in the status bar (never as a toast) with a human-readable cause (such as `"Couldn't save: folder is read-only"` or `"Couldn't save: disk is full · 12 MB free"`), plus **Retry** (`Editor.RetrySave`) and **Save as…** actions until fixed. - **While saving fails**: the unsaved dot beside the scene name and on the failing scene tab turns Spec problem red (`#FF6B6B`), quitting asks first (`Editor.HasUnsavedChanges()` remains `true`), and `editormcp` appends a warning to every tool result until a save succeeds. - **Live language switching**: `Language` accepts `LanguageSystem` (`"system"`), `LanguageEnglish` (`"en"`), or `LanguageChinese` (`"zh"`). Calling `Editor.SetLanguage` or picking a language on the **General** page under **`EDITOR · THIS COMPUTER`** in the unified **Settings** view (`SettingsView` / `EditorSettingsDialogView`, opened via `File > Editor Settings...`, Command Palette `CmdEditorSettings`, or `mod+,`) updates the header bar, desktop menu bar, file browser, asset browser, scene tree, layers, inspector, bottom panels, dialogs, command palette, and status bar immediately without restarting. `Editor.ResolvedLanguage()` reports the active locale (`"en"` or `"zh"`) and is exposed to connected MCP agents through `selection_get`. - **Appearance (`core.Scope.SetAppearance`) and Spec Dark/Light theme (#1062)**: `Appearance` accepts `AppearanceSystem` (`"system"`), `AppearanceLight` (`"light"`), or `AppearanceDark` (`"dark"`). `EditorView` installs the embedded YAML Spec theme (`theme.yaml`, loaded via `core.ParseTheme` and exposed through `theme.Core`, `theme.Dark`, `theme.Light`, `theme.PaletteFor`, and `Editor.Palette`) onto the root scope so every NSGo `ui` widget, panel, viewport overlay, overlay legend (`SpecOverlayLegendView` / `SetOverlayLegendOpen`), and toast (`ShowToast` / `DismissToast` / `ToastView`) follows the Spec tokens in both Dark and Light appearances instead of falling back to NSGo's default theme. Every foreground/background, button-on-fill, warning-card, and viewport-overlay pair in both palettes is measured against the same WCAG 2.2 contrast table (`theme.ContrastRatio`, `theme.ContrastTable`: >= 4.5:1 AA for text, pill labels, and text on accent/agent/problem fills; >= 3:1 UI contrast for focus rings and viewport overlay edges). With `AppearanceSystem`, changing the OS appearance repaints the editor live without a restart; explicit `AppearanceLight` or `AppearanceDark` choices persist to `Editor.SettingsPath` across restarts. - **Shortcuts: searchable and rebindable within a scope (#1061)**: - **Command scopes**: every `EditorCommand` and `PluginCommand` carries a `Scope` (`ScopeGlobal`, `ScopeViewport`, `ScopeViewport2D`, `ScopeViewport3D`, `ScopeSceneTree`, `ScopeTile`, `ScopeAnimation`, `ScopePlay`, defaulting to `ScopeGlobal` when omitted). - **Settings › Shortcuts (`EditorSettingsTabShortcuts`, `OpenShortcutsSettings`, `CmdShortcutsSettings`)**: lists every registered built-in, custom, and active plugin command with its scope and live formatted key, searchable by command name, key/shortcut, or scope (`FilterShortcutCommands`). Pressing a command's key binding enters key-capture mode (`ShortcutFromKeyEvent`, cancelled cleanly with `Escape` without closing the dialog). Rebinding to a key already used in the **same** scope (`ShortcutConflict` / `*ShortcutConflictError`) flags the conflict in place with a **Swap** button (`SwapShortcut`, leaving both commands bound to each other's keys); binding a key used only in a **different** scope (`RebindShortcut`) succeeds immediately without a prompt. Per-row **Reset** (`ResetShortcut`) and **Reset all** (`ResetAllShortcuts`) restore defaults. - **Persistence and live surfaces**: custom bindings persist under `shortcuts` in `EditorSettings` (`editor.yaml`, outside any project) and immediately update `EffectiveShortcut`, header bar tooltips/labels, the desktop menu bar (`ApplicationMenu`), Command Palette (`CommandPaletteView`), runtime key bindings, and the **`⌘/` Keyboard Shortcuts sheet** (`ShortcutsSheetView`, `CmdShortcutsSheet` / `mod+/`). - **Plugin localization**: plugins may attach a `Catalog *l10n.Catalog` or versioned `LocaleYAML [][]byte` string tables (`RegisterPlugin` validates them strictly) and set optional `TitleKey` / `LabelKey` / `DescriptionKey` / `CategoryKey` on their panels, tools, and commands. Inside `Panel.View` and `Inspector.View`, plugins call `Editor.PluginT(pluginName, key, args...)` and `Editor.PluginPlural(...)` so all plugin UI follows the editor's active language live. ## 2D skeletal rig editor (#886) The editor opens, edits, previews, saves, and places version-1 `.skel.yaml` 2D skeletal rigs (`game/skeletal`) directly through `RigPanelView` below the viewport: - **Opening and lossless round-tripping**: select any `*.skel.yaml` or `*.skel.yml` file in `FilesView` and double-click it or press **Open Rig** (`OpenRigProjectFile`, `OpenRigFile`, `OpenRigYAML`), or start a fresh rig with `NewRig`. Opening and saving an existing rig without edits (or after undoing every edit back to the opened state) writes back the exact original bytes unchanged (`SaveRigYAML`, `SaveRigFile`, `Editor.OnSaveRig`); edited rigs serialize deterministically via `skeletal.Encode`. - **Interactive rig canvas and handles**: `DrawRigViewport` renders attachments through the runtime `skeletal.Skeleton.Draw` beneath the bone hierarchy and interactive handles: - **Bone Move (`RigHandleBoneMove`)**: drag a bone's joint circle to move it in its parent's local space (in Bind Pose) or key its `translate` offset at the current playhead when an animation is active. - **Bone Rotate (`RigHandleBoneRotate`)**: drag the rotation ring around a bone to rotate it (bind pose or active animation `rotate` keyframe). - **Bone Length (`RigHandleBoneLength`)**: drag the tip diamond to set `BoneData.Length`. - **Attachment Origin (`RigHandleAttachmentOrigin`)**: drag the pivot crosshair on the selected slot's active skin attachment to adjust `OriginX` and `OriginY`. - Every handle drag (`BeginRigDrag`, `BeginRigHandleDrag`, `UpdateRigDrag`, `EndRigDrag`) commits as one undoable `Editor.History` step, and `CancelRigDrag` (or pressing `Escape` during a drag) restores the pre-drag snapshot without touching history. - **Bones, slots, skins, and attachments**: add (`AddRigBone`), rename (`RenameRigBone`), delete (`DeleteRigBone`), move/rotate/scale (`MoveRigBone`, `RotateRigBone`, `ScaleRigBone`, `SetRigBoneLength`), and reparent bones (`ReparentRigBone`, optionally preserving bind-pose world transforms and refusing cycles); add, delete, rebind, fade, and reorder draw slots (`AddRigSlot`, `DeleteRigSlot`, `SetRigSlotBone`, `SetRigSlotAlpha`, `MoveRigSlotOrder`); manage skins (`AddRigSkin`, `DeleteRigSkin`, `SelectRigSkin`) and attach atlas frames with origin pivots (`AttachRigFrame`, `SetRigAttachment`, `SetRigAttachmentOrigin`, `SetRigAttachmentTransform`, `RemoveRigAttachment`). - **Timeline, playback, and crossfade preview**: create animations (`AddRigAnimation`, `DeleteRigAnimation`, `SelectRigAnimation`, `SetRigAnimationDuration`, `SetRigAnimationLoop`), key bone `translate`, `rotate`, `scale` and slot `attachment` and `alpha` tracks (`KeyRigBoneTranslate`, `KeyRigBoneRotate`, `KeyRigBoneScale`, `KeyRigSlotAttachment`, `KeyRigSlotAlpha`, `DeleteRigBoneKeyframe`, `DeleteRigSlotKeyframe`), scrub (`SeekRig`), play (`PlayRig`, `PauseRig`, `StopRig`, `StepRig`), and preview crossfade blends (`CrossfadeRig`, `RigBlending`) directly through the runtime `skeletal.Skeleton` (`RigSkeleton`). - **Placing rigs in scenes**: press **Place in Scene** (`PlaceOpenRig`, `PlaceRig`) to add a scene object carrying the built-in `"skeletal"` component (`sceneformat.SkeletalComponent`, `version: 1`, `rig`, `atlas`, `skin`, `animation`, `loop`). `sceneformat.Build` loads the rig through `SkeletonResolver` or `FileResolver` (`FSAssets`), builds a live `BuiltObject.Skeleton` with the chosen skin and animation, draws it in exact Z order in both `BuiltScene.Draw` and the 2D editor viewport, and advances it in `BuiltScene.Update(dt)`. `refs.Scan` tracks `components.skeletal.rig` (`refs.FieldSkeletalRig`) so `MoveFile` rewrites rig paths across scenes automatically. ## HUD and menu layout screen (#1047) Open the HUD and menu layout screen (`HUDLayoutView`) via `Project > HUD & Menu Layout`, Command Palette (`mod+shift+u` / `CmdHUDLayout`), double-clicking or opening any `*.screen.yaml` file in the file browser, or clicking a screen diagnostic in the Problems panel (`OpenHUDScreen` / `OpenHUDScreenFile` / `OpenHUDScreenDoc`). Styled strictly with the editor's design spec tokens (`design/editor/HUDLayout.dc.html` and `Spec.dc.html`), it previews every screen size and project language side by side while keeping manual layout edits focused and undoable: - **Header and Language switcher**: displays the ` / screens / ` breadcrumb (with a back button returning to the scene editor), a **Language** segmented control listing every locale from `locales/*.yaml` (and any unsaved `Editor.l10n` workspace edits) via `SetHUDLocale`, **Search ⌘K**, and **Play**. Switching languages immediately redraws all four screen sizes, the text-width table, the inspector's localized values and overflow zoom, and **GAME CHECK**. - **Left rail (`SCREENS` and `NODES`)**: lists all project `*.screen.yaml` files (`HUDScreens`) with each screen's node count and active-language problem count, plus the active screen's hierarchical node tree (`HUDTree`) with monospace anchor tags (`TL`, `TC`, `TR`, `CL`, `C`, `CR`, `BL`, `BC`, `BR`, `FILL`) and red problem dots. - **Four simultaneous device frames and overlays**: draws the active screen at **Phone 19.5:9 with a notch** (`780 × 360`), **Tablet 4:3** (`640 × 480`), **Desktop 16:9** (`640 × 360`), and **Ultrawide 21:9** (`840 × 360`) at once through real `gameui.BuildScreen` layout (`HUDLayoutFrames`), with switches for **Safe areas**, **Anchors**, **Touch areas**, and **Focus order** (`HUDOverlays` / `ToggleHUDOverlay`), plus a floating **TEXT WIDTH, PX** table (`HUDTextWidths`) comparing each text node's box width against its measured width in every locale with overflows highlighted. - **Inspector, zoomed overflow detail, and `GAME CHECK`**: inspects the selected node's **ANCHOR** (a 3×3 grid of buttons plus **Fill**, anchor and offset in words, and **Keep inside the safe area**), **SIZE** (**Fixed** / **Fit text** toggle and touch target size), **TEXT** (key, every locale's value, and a `1.5×` zoomed overflow detail card when localized text spills past its box), and live **GAME CHECK** diagnostics backed by `gameui.CheckScreen` (`HUDProblems`) with **Show** buttons to select offending nodes, **Ask the agent to fix N**, and an empty `"No problems at any size in this language"` state when clean. - **Manual edits and agent composer**: reordering children inside a container (`ReorderHUDNode`), adjusting container spacing (`SetHUDNodeSpacing`), changing anchor/safe-area/sizing (`SetHUDNodeAnchor`, `SetHUDNodeSafeArea`, `SetHUDNodeSizeMode`), and directly dragging touch controls (`BeginHUDTouchDrag`, `UpdateHUDTouchDrag`, `EndHUDTouchDrag`, `CancelHUDTouchDrag`) each record **one undo step** in `Editor.History` and write canonical YAML back to the `*.screen.yaml` file on disk (restored verbatim on Undo). A bottom composer (`SubmitHUDPrompt`, `AskAgentToFixHUDProblems`, `Editor.OnHUDPrompt`) forwards broader HUD changes to the agent. ## Cutscene timeline and agent review (#1056) Opening any `*.cutscene.yaml` / `*.cutscene.yml` file (from the file browser, Command Palette, `OpenCutsceneProjectFile`, `OpenCutsceneFile`, `OpenCutsceneYAML`, or an agent `cutscene_write` MCP call) opens the full-workspace cutscene timeline editor (`CutscenePanelView`), styled strictly with `Spec.dc.html` design tokens and laid out from Screen 2 of `design/editor/Animation.dc.html`: - **Left rail (`CUTSCENES` and `LINES`)**: lists every project cutscene (`ProjectCutscenes`) with its length or `video` kind marker, plus every localized dialogue line (`CutsceneLines`) resolved from `loc/en.yaml` and `loc/zh.yaml` (or `Editor.CutsceneCatalog` / the open Localization workspace) showing its line ID, English text, and Chinese text. - **Live preview stage and thumbnail scrub strip**: runs a live `cutscene.TimelinePlayer` against an isolated copy of the scene (`CutscenePreviewScene`, `SeekCutscene`, `PlayCutscene`, `PauseCutscene`, `StepCutscene`) so scrubbing to any timestamp poses actors, camera, and subtitle identically to runtime playback. Displays the active camera caption (`CutsceneCameraLabel`), localized subtitle overlay (`CutsceneActiveDialogue`), Play/Pause transport, time readout, and a 24-frame clickable thumbnail strip (`CutsceneThumbs`). - **Track lanes and clip inspector**: displays ordered lanes for Camera, each actor, Dialogue, Sound, and Music tracks with positioned clip blocks. Selecting a clip (`SelectCutsceneClip`, `SelectCutsceneClipByID`) inspects and edits **Start** and **Duration** with `±0.1 s` steppers (`AdjustCutsceneClipStart`, `AdjustCutsceneClipDuration`, `SetCutsceneClipTiming`) and **Easing** (`Linear`, `In`, `Out`, `In-out`, `Hold` via `SetCutsceneClipEasing`) on camera and actor tracks. Selecting a dialogue clip displays its line ID, English and Chinese text, and the reminder that text lives in `loc/en.yaml` and `loc/zh.yaml` while the cutscene stores only the ID. - **Agent review mode (`OpenCutsceneReview`)**: compares the original cutscene (`Before`) against the agent's proposal (`After`) without overwriting the file on disk until accepted. Supports toggling **Before** / **After** (`SetCutsceneReviewViewMode`) or holding **B** to peek at Before (`SetCutsceneReviewPeekBefore`, `CutsceneHandleKeyEvent`), marks added and changed clips with dashed line styles (`added` green dashed, `changed` amber dashed, `selected` blue solid) alongside the legend, lists `N CHANGES` with per-change **Revert** / **Restore** (`ToggleCutsceneReviewChange`) and click-to-focus (`FocusCutsceneReviewChange`), lets manual clip edits join the active review with `⌘Z` undo (`"Your edit joins this review · ⌘Z undoes it"`), offers **Revert all** (`RevertAllCutsceneReview`), and commits the remaining kept changes and joined edits on **Keep N of M** (`KeepCutsceneReview`) in **one atomic undo step** (both in memory and on disk). ## Changes and commit panel (#1057) Open the full-window **Changes and commit** screen (`ChangesPanelView`) from the status bar's **Changes** entry (showing the live working-tree changed-file count), `Project > Changes & Commit`, or Command Palette (`CmdChanges` / `OpenChangesPanel` / `CloseChangesPanel`), matching `design/editor/VersionControl.dc.html` (screen 1) using only `Spec.dc.html` design tokens: - **Branch switcher, upstream status, and Pull**: the header displays ` / `, a branch switcher dropdown (`GitSwitchBranch`) showing the active branch plus ahead/behind counts (`ahead N`, `behind M`), **Refresh** (`RefreshChanges`), **Pull** (`GitPull`, fast-forward only), and **Play**. - **CHANGES grouped by category**: working-tree changes against `HEAD` (`git status --porcelain=v1 -uall`) group under **SCENES**, **DATA**, **CODE**, and **ASSETS** (`ChangesCategory`), each file carrying an include checkbox (`SetChangeIncluded`, `ToggleChangeIncluded`), status badge (`M`, `A`, `D`, `R`), and a concise detail line (`4 added · 3 changed objects`, `+7 -4 lines`, or audio duration and file size). - **Per-file comparison with `HEAD` in the Review layout**: - **Scenes (`*.scene.yaml` / `*.scene.yml`)**: compares `HEAD` (`git show HEAD:`) with the working tree via side-by-side **HEAD** and **Now** 2D scene previews (plus single-view **HEAD** / **Now** toggles via `SetChangesSceneView`), outlining added objects in dashed green, changed objects in dashed amber, and removed objects in dashed red, with per-object change badges (`added · ...`, `changed · Door (x 584 → 560)`, `removed · ...`). - **Data and Go code**: displays the latest `nsgo check` and `nsgo test` status and relative timestamp (`RunChangesChecks`, injectable via `Editor.ChangesCheckRunner`) above a color-coded unified line-by-line diff (`git diff HEAD -- `, or full `+` lines for untracked files) and an **Open in editor** button (`OpenChangedFileInEditor`). - **Audio assets**: renders a playable audition card (`AuditionChangedAudio`, `StopChangedAudio`) with duration, format/sample-rate metadata, a 60-bar waveform, and incoming references (`Used by ...`) gathered from the project reference index and scene objects. - **Selective commit card and History milestones**: drafts a commit summary and description from the included files, review/playtest context (`SetChangesContext`), and checks via `Editor.CommitMessageDrafter` or deterministic `DefaultCommitDraft` with **Redraft** (`RedraftCommitMessage`), editable summary and description inputs (`SetCommitSummary`, `SetCommitDescription`), `"Made from N agent requests, reviewed and kept"` attribution when present, included `+/−` line counts, **Commit** (`CommitSelectedChanges`), **Commit and push** (`CommitAndPushSelectedChanges`), and **Push N commits** (`PushCommits`). Committing stages and commits **only** the checked files (`git add -A -- ` + `git commit --only -m ... -- `), leaving every unchecked file untouched and uncommitted, and records a `CommitMilestone` in `Editor.History` (`History.Milestones` / `CommitMilestones`). Nothing is ever committed or pushed automatically without user action. - **SHARE**: **Copy as PR description** (`CopyPRDescription` / `BuildPRDescription`, writing structured Markdown with summary, changed files, checks, and playtest numbers via `core.Scope.SetClipboard` or `Editor.ChangesClipboard`) and **Open pull request** (`OpenPullRequest`, enabled when `gh` is on `PATH` or `Editor.GHRunner` is set). ## Scene merge conflict resolution (#1059, #1531) When Git leaves an unmerged scene file — during `git merge`, `git rebase`, `git pull --rebase`, `git cherry-pick`, `git revert`, or `git stash pop` (whether written by the object-by-object `go tool game merge` driver from #1058 or by Git's standard text conflict markers) — opening the project (`OpenProject`), pressing the status-bar conflict pill, or invoking `Project > Resolve Scene Merge Conflicts` (`CmdMergeConflicts` / `OpenMergeConflict`) opens the full-window **Scene merge conflict** screen (`MergeConflictView`, styled strictly with `design/editor/Spec.dc.html` tokens matching `VersionControl.dc.html` screen 2): - **Git operation detection and stage mapping**: detects `MERGE_HEAD`, `REBASE_HEAD` (or `.git/rebase-merge` / `rebase-apply`), `CHERRY_PICK_HEAD`, `REVERT_HEAD`, and unmerged index entries without a `*_HEAD` ref (`git stash pop` / `apply`). During a `rebase` or `pull --rebase`, stages `:2:` and `:3:` are swapped relative to the author so stage `:3:` is shown as **Mine (commit being replayed)** and stage `:2:` is shown as **Upstream**; cherry-pick and revert name the picked or reverted commit. - **Header and progress**: displays operation-specific progress (`Merging into `, `Rebasing onto `, `Cherry-picking onto `, `Reverting on `, or `Applying stash@{0} onto ` with `N of M objects need you`), the matching abort button (`AbortMerge` running `git merge --abort`, `git rebase --abort`, `git cherry-pick --abort`, `git revert --abort`, or `git reset --merge` for a stash conflict), and the finish button (`FinishMerge`, enabled only once every conflict is resolved). - **Conflicts and MERGED BY ID**: groups `sceneformat.MergeResult.Conflicts` object by object under **CONFLICTS**, each row showing a status dot, object name, `Unresolved` / `Agent` / `Mine` / `Theirs` (or `Upstream` / `Picked` / `Revert` / `Stash`) / `Custom` chip, and a plain-language summary (such as `Both moved it: x 560 here, x 600 on main` or `Your speed change; main deleted it`). Objects joined cleanly without conflicts appear under **MERGED BY ID** with which side added or changed them. **Take the agent's suggestion for all N** (`TakeAllAgentMergeSuggestions`) resolves every conflict in one click. - **MINE, THEIRS, and RESULT previews**: displays clickable **MINE** (or **MINE (COMMIT BEING REPLAYED)** during rebase, with branch, author, short commit SHA) and **THEIRS** (**UPSTREAM** / **PICKED COMMIT** / **REVERT** / **STASH**) 2D scene preview canvases over a larger **RESULT** canvas. Unresolved objects render at both Mine and Theirs positions with dashed amber outlines so overlapping moves are immediately visible; selecting a resolution updates **RESULT** live. - **Agent's suggestion, Mine, Theirs, and hand-edited YAML**: the right inspector shows three selectable cards for the focused object — **Agent's suggestion** (from a connected `Editor.MergeSuggester`) or **Suggested by rule** (from deterministic `DefaultMergeSuggestion`, combining non-conflicting fields from both sides or explaining why a deletion or higher `z` holds), **Mine**, and **Theirs** (labeled by operation) — each with its YAML snippet and reason. **Edit the result YAML by hand** (`SetMergeCustomEditing`, `ApplyMergeCustomYAML`) validates custom object YAML with `KnownFields(true)` and `sceneformat.Validate` before applying it. - **Verification and Git completion (`FinishMerge`)**: writes canonical `sceneformat.Encode` YAML to the scene path, runs `game check` (`runProjectCheck` or `Editor.MergeCheckRunner`) and a short 10-second deterministic playtest (`sceneformat.Build` + `Update` + `PhysicsScene.Step` or `Editor.MergePlaytestRunner`), refuses to finish if either fails, and otherwise stages the scene (`git add`) and completes the active operation (`git commit --no-edit` for merge, `git rebase --continue` for rebase, `git cherry-pick --continue` for cherry-pick, `git revert --continue` for revert, or stage-only without committing for stash), reloading the resolved scene into the editor. - **MCP tools (`editormcp`)**: `merge_status`, `merge_resolve`, `merge_finish`, and `merge_abort` expose the active `operation` and let coding agents inspect conflicted objects, supply or refine suggestions and reasons, apply choices or custom YAML, and finish or abort merges, rebases, cherry-picks, reverts, or stash conflicts. ## Find usages and safe rename (#1041) Pressing `Shift+F12` (`CmdFindUsages`), choosing **Project > Find Usages** from the menu bar or Command Palette, right-clicking a file in the file browser (**Find Usages** / **Rename Safely…**), right-clicking an instanced scene or prefab object in the scene tree (**Find Usages**), or calling `OpenUsagesScreen(path)` opens the full-window **Find usages and safe rename** screen (`ReferencesScreenView`, styled strictly with `design/editor/Spec.dc.html` tokens matching `References.dc.html`): - **Grouped usages (`FindUsages`)**: shows **Back to the editor** (`Esc`), `"Usages of "`, and `"N usages in M files"`, grouped into **SCENES** (each instanced object with its position and override count), **PREFAB VARIANTS** (files with `inherits:` targeting the file), **DATA TABLES** (rows referencing the path), and **GO CODE** (string literals and constants parsed from project `*.go` files via `go/parser` + `go/ast`, marked `not rewritten`). `↑`/`↓` moves through usages, clicking a scene card focuses that scene's instances on a plotted thumbnail grid, and `Enter` opens the scene with the referencing object selected and framed. - **Safe rename review (`PreviewSafeRename` / `StartSafeRename` / `SetSafeRenameInput`)**: pressing **Rename…** (`F2`) shows a **NEW NAME** field between the fixed folder prefix and compound file suffix, validating live against `game mv` / `MoveFile` path rules (non-empty, safe relative path, free destination) and computing the exact dry-run rename plan without touching disk. The review lists the moved file (`"content unchanged"`), every rewritten YAML file with exact `−` (old) and `+` (new) line diffs showing preserved instance overrides, and every non-rewritten Go reference as a problem (`" loads the old path and is not rewritten"`) with **Ask the agent to update it** (`AskAgentToUpdateUsage`, invoking `Editor.OnAskAgentUpdateRef`) and **Open ``** (`Editor.OnOpenSourceFile`). - **One-step Keep and Undo (`ApplySafeRename` / `UndoSafeRename`)**: clicking **Keep · Rename N files** (`Mod+Enter`) writes only YAML through `MoveFile` as one undoable `Editor.History` step and enters the done summary with **Undo · ⌘Z** and **Back to ``**. One Undo restores every moved and rewritten file on disk byte-for-byte along with all open tabs. - **MCP tools (`editormcp`)**: `refs_find` returns the grouped usages across scenes, prefab variants, data tables, and Go code (optionally opening the screen), and `refactor_rename` prepares the same safe-rename review in the editor with exact planned diffs and non-rewritten Go warnings without silently mutating disk unless `apply: true` is passed. ## Material editor (#896) Assign and edit shared `*.material.yaml` resource files ([resource](http://nsgo.games/docs/resources/)) directly inside the editor with live preview and full Undo/Redo: - **Assigning and creating materials**: in the Inspector, the searchable **Material** selector (`SetObjectMaterial`) picks from the open project's `*.material.yaml` files; **New Material** (`CreateObjectMaterial` / `CreateMaterialFile`) creates a new canonical `.material.yaml` file written with `resource.Encode`, assigns it to the selected object, and opens it; **Edit Material** (`OpenMaterial` / `OpenMaterialProjectFile`), double-clicking a material file or pressing **Open** / **Edit Material** in the file browser, picking a material in the Command Palette (`OpenProjectFile`), or invoking `Project > Material Editor` (`CmdMaterialEditor`) opens the docked `MaterialEditorPanelView` below the viewport. - **Every material field**: edits `name` (`SetMaterialName`), `baseColor` and `emissive` via NSGo `ColorWell` / `ColorPicker` popups and CSS color inputs (`SetMaterialBaseColor`, `SetMaterialEmissive`), `texture` via a searchable project image picker (`SetMaterialTexture`, `ProjectTextures`), `metallic`, `roughness`, and `opacity` via bounded sliders and numeric inputs (`SetMaterialMetallic`, `SetMaterialRoughness`, `SetMaterialOpacity`), `blend` from `resource.BlendModes()` (`SetMaterialBlend`), and `doubleSided` / `unlit` checkboxes (`SetMaterialDoubleSided`, `SetMaterialUnlit`). Invalid values are refused by `resource.Encode` without mutating state or history. - **Live preview and viewport sync**: the panel renders a live preview (`MaterialPreviewImage`, `SetMaterialPreviewShape`) as a 3D **Sphere** or **Cube** lit with `render3d` (respecting `unlit`, PBR metallic/roughness, emissive, texture, opacity, and double-sidedness) or a 2D **Sprite** preview (defaulting to Sprite in 2D view and Sphere in 3D view). Every edit—including color-picker drags and Undo/Redo—pushes the updated material live through `resource.Library.Reload` (using `project.Resolver.Library()` and `scenemodel.Assets.Library()`), updating the preview, every 2D sprite (`BuiltScene.SyncMaterials`), and every 3D viewport object using that material immediately before saving. - **Undo/Redo and deterministic save**: every edit goes through `Editor.History` (`EditMaterial`), tracks unsaved state (`MaterialDirty`, `HasUnsavedChanges`), follows file renames (`MoveFile`), and **Save Material** (`SaveMaterial`, `SaveMaterialFile`, `Save`, `SaveAll`, or `Editor.OnSaveMaterial`) writes the exact deterministic YAML produced by `resource.Encode`. ## Playtest report screen (#1044) Open the full-window **Playtest Report** screen (`PlaytestReportView`) from `Project > Playtest Report`, Command Palette (`mod+shift+y` / `CmdPlaytestReport`), the status-bar playtest badge, double-clicking any `*.report.yaml` file in the file browser, programmatically via `OpenPlaytestReport` / `OpenPlaytestReportFile`, or from an agent calling `playtest_report`. Styled strictly with `design/editor/Spec.dc.html` color and contrast tokens (including `#101216` text on `#3B7BFF` primary accent buttons) matching `design/editor/Playtest.dc.html`: - **Header and replay hand-off**: displays `"Playtest · "`, the project name and runs summary (such as `"20 headless runs by the agent · 1 m 40 s"`), **Watch run N** (`WatchPlaytestRun` / `WatchPlaytestRunIn`, which loads that run's saved `.replay.yaml` file through `replay.LoadFile`, starts Play mode with a live `*replay.Player` via `PlayReplayIn`, and provides a **Back to Playtest** banner), and **Ask the agent to tune it** (`AskAgentToTunePlaytest` / `Editor.OnPlaytestPrompt`). - **BOT PROFILE strip and `playtest_define` review**: shows the bot profile switcher/name (`BotProfileDisplayName`), `"playtest.yaml from template "` with **Open** (`OpenPlaytestConfigPreview` / `Editor.OnOpenPlaytestConfig`), and a one-sentence strategy. When the agent proposes a metric through `playtest_define`, a violet banner (`"Proposed with playtest_define: …"`) appears with **Review**, opening an inline unified-diff drawer to **Apply** or **Dismiss** without touching `playtest.yaml` on disk until accepted (`ApplyPlaytestProposal`, `DismissPlaytestProposal`). - **Metric cards**: displays each metric's label, a text-and-icon **Met** or **Missed** badge (never color alone), formatted value, foot line, and `"Goal · "` paired with its monospace source file (`brief.yaml`, `game.yaml`, or `playtest.yaml`). - **Automatic chart selection (all 4 chart kinds)**: `SelectPlaytestChart` and `DrawPlaytestChart` choose and render one canvas chart per report from the report's metrics: 1. **Heat map over the level** (`PlaytestChartHeatMap`) for deaths or time per tile, with clustered density blobs and hotspot callout chips. 2. **Bars per wave against a goal line** (`PlaytestChartBars`) with a dashed target line and flagged standout bars. 3. **Line per level** (`PlaytestChartLine`) for per-level progression curves with flagged spike/dip markers. 4. **Win-rate matrix** (`PlaytestChartMatrix`) with cells above the threshold (default 60%) flagged by border, marker, and `"above 60%"` label. - **Agent's read, actionable suggestions, and footnote**: presents a concise diagnostic read (`DefaultPlaytestAgentRead` or custom `SetPlaytestAgentRead`) and clickable suggestion cards (`RequestPlaytestSuggestion`) that dispatch requests coming back as reviews, above the footnote noting that runs use the replay system and that metrics and the bot come from `playtest.yaml`. - **MCP integration (`editormcp`)**: `game_playtest` loads freshly generated reports into the editor, `playtest_define` pushes pending proposals directly onto the Playtest Report banner with synced Apply/Dismiss handlers, and `playtest_report` lets the agent open, inspect, annotate, or watch runs from the report screen. ## Asset drawer (#1052) Switch the top of the left rail between **Scene** (`LeftRailScene`) and **Assets** (`LeftRailAssets`, also reachable via Command Palette `CmdToggleAssetsMode`) to browse, filter, preview, and drag every kind of project asset directly into the scene, styled strictly with `design/editor/Spec.dc.html` design tokens and laid out from `design/editor/Assets.dc.html` (screen 1): - **Left rail (`AssetsLeftRailView`)**: switches between **Scene** and **Assets** (`LeftRailSwitchView`), lists project **FOLDERS** with live asset counts (including empty asset directories such as `audio/music`), provides **SHOW ONLY** filters with counts (**Unused**, **Missing files**, **Generated**, **Proposed**), and includes a file drop zone (`"Drop files anywhere to import"`). **Unused** and **Missing files** are computed directly from `refs.Project.UnreferencedAssets` and `refs.Project.MissingAssets`. - **Drawer under the viewport (`AssetDrawerView`)**: offers kind tabs (**All**, **Sprites**, **Tiles**, **Audio**, **Fonts**), a live **Name or path** filter (`SetAssetDrawerQuery`), a sort toggle defaulting to recently changed (`SetAssetDrawerSort`), **Import** (`TriggerAssetImport` / `ImportAssetFiles`), and **Generate** (`TriggerAssetGenerate`). Cards display a checkerboard preview, a status badge (`new`, `Missing`, `Generated`, `Not used`), the asset name, and a meta line (such as `"6 frames · used 31×"`). The footer reports `"N assets · M shown"` and any missing-file problem (`"1 problem · door_open.png missing"`). Empty folders display `"audio/music is empty · Drop .ogg or .wav files here, or ask the agent."` and empty filter results display `"Clear a filter to see more assets."`. - **Drag to viewport (place snapped or swap sprite)**: dragging a sprite card onto empty space in the 2D viewport shows a snapped drop ghost and pill (`"coin.png new Sprite on Actors · snapped to 16 px"`) and places a new sprite object on the active layer in **one undo step** (`DropAssetAt`). Dropping a sprite onto an existing object swaps that object's sprite in **one undo step**, so one **Undo** restores the previous sprite. Pressing **Escape** (`CancelAssetDrag`) cancels the drag cleanly without mutating the scene. - **Selected asset panel (`AssetInspectorView`)**: displays a checkerboard preview with dimensions/format metadata, frame-by-frame playable clip controls (`SetAssetPreviewPlaying`, `SetAssetPreviewClip`, `SetAssetPreviewFrame`, `StepAssetPreviewFrame`) for multi-frame sprites, playable sound controls (`ToggleAssetAudioPreview`, `StopAssetAudioPreview`) with waveform preview for audio files, a compact **IMPORT** summary from `InspectAssetImport`, and **USED BY** listing every referring file and usage from `refs.Project.UsedBy` (clicking a reference opens it). Unused assets display `"Nothing references it. The agent can propose deleting it; deleting files always asks you."`, and missing assets offer **Replace with a file** (`TriggerReplaceMissingAsset` / `ReplaceMissingAsset`) and **Ask the agent** (`AskAgentAboutAsset`). ## Viewport Overlays menu and agent viewport images (#1040) In 2D edit mode (`ViewMode2D`), a floating bar at the bottom-center of the viewport (`design/editor/Inspector.dc.html`, styled strictly with `Spec.dc.html` tokens) pairs zoom (`−` / `%` / `+`), **Snap**, and **Fit** with an **Overlays N** button showing the count of active overlays: - **`SHOW IN VIEWPORT` popover (`ui.Popover`)**: opens above **Overlays N** (also reachable via `View > Overlays` and `CmdViewportOverlays`) with a swatch, localized label, live count in the current scene, and `ui.Switch` for each overlay, plus the footer note *"The agent's screenshots use the same set: `viewport_overlays`"*: - **Collision shapes** (`collision_shapes`): registered non-trigger component shape fields (#882) and non-trigger 2D physics colliders. - **Triggers** (`triggers`): trigger/sensor/area component shapes and 2D physics trigger volumes (amber dotted outline). - **Connections** (`connections`): arched arrows from emitting object to handler object labelled `"event → handler"` (such as `"pulled → open"`) from the scene's `connections`. - **Patrol paths** (`patrol_paths`): enemy/actor patrol ranges and waypoint paths, built on the same `ViewportOverlay` registry that plugins use. - **Navigation** (`navigation`): built 2D navigation mesh polygons, portals, and `navregion2d` outlines (#888), kept in sync with `ShowNavMesh2D`. - **Camera bounds** (`camera_bounds`): scene camera bounds rectangle and `"bounds W × H"` caption (#884). - **Labels** (`labels`): compact object name/ID pills below visible objects. - **Custom plugin overlays (`ViewportOverlay`)**: plugins add custom overlays via `Plugin.Overlays` (or directly on an editor with `Editor.RegisterViewportOverlay`), supplying an `ID`, `Name`/`NameKey`, optional `Count` callback, and `Draw func(*Editor, *core.Drawing, *sceneformat.BuiltScene)` function. Active plugin overlays appear in the popover, `View > Overlays`, and `editormcp`'s `viewport_image`. - **Per-user persistence**: toggling any overlay (`SetViewportOverlay`, `ToggleViewportOverlay`, `SetViewportOverlays`) writes `viewportOverlays` to `Editor.SettingsPath` (`EditorSettings` YAML outside the project), never to any project or scene file, so choices survive restarts (including an explicit empty list `[]` when all overlays are turned off). - **Shared with `editormcp`'s `viewport_image`**: `Editor.DrawViewportWithOverlays(d, size, overlayIDs)` renders the exact same overlay set into `viewport_image`. Omitting `viewport_overlays` uses the editor's active overlays; passing explicit names (or `[]`) overrides them for that image without mutating editor settings. ## Inspector titled sections, field filter, scrub fields, Open YAML, and Ask to add (#1038) The object Inspector (`InspectorView`), styled with `design/editor/Spec.dc.html` tokens matching `Inspector.dc.html`, `Main.dc.html`, and `Viewport3D.dc.html`, organizes object editing into compact collapsible sections while keeping every control backed by an `Editor` method and matching `editormcp` tool: - **Header and Open YAML**: displays a kind-colored swatch, object ID, kind-and-layer subtitle (such as `Sprite · layer actors`), and **Open YAML** (`FindObjectYAMLLine` / `OpenSelectedObjectYAML`), which locates the object's exact 1-based line in the scene YAML (reading the file on disk when clean so comments and formatting match, or `SaveYAML` when dirty), invokes `Editor.OnOpenFileAtLine(path, line)` when set, and reports `Opened :` in the status bar. - **Field filter (`InspectorFilter` / `SetInspectorFilter`)**: the **Filter fields** search bar narrows visible sections and fields by case-insensitive substring match against field labels, component names, and section titles (for example, filtering `speed` leaves only fields matching `speed`), auto-expanding matching sections and hiding non-matching ones. - **Titled collapsible sections and compact transform rows**: sections render in Spec section-header style (uppercase title, chevron toggle via `ToggleInspectorSection`, field count badge, e.g. `TRANSFORM`, `SPRITE`, `PATROL`, `HEALTH`), with Position and Scale laid out as compact `X Y` rows (plus `Z` in 3D, alongside 3D Rotation `X Y Z`), Alpha, and Z order. - **Scrubbable number fields**: dragging any number field's label (`BeginInspectorScrub`, `UpdateInspectorScrub`, `EndInspectorScrub`, `CancelInspectorScrub`) previews changes live in the viewport and records **one undo step** per drag; pressing `Escape` during a scrub cancels and restores the original value without touching history. In 3D view, holding `Shift` while scrubbing steps in `0.01` increments. Focused numeric fields support `↑`/`↓` stepping, `Shift` ×10 stepping, `Enter` commit, and `Escape` restore. - **Grouped Add component and Ask to add**: registered components the object lacks are grouped under `GAMEPLAY`, `PHYSICS`, and `AUDIO AND VISUAL` (`ComponentCategoryOf`, `AddableComponentGroups`). Beside the input, **Ask to add** (`AskToAddComponent`, `ComposerDraft`, `SetComposerDraft`, `Editor.OnComposerPrompt`) stages `"Add a component to that "` in the agent composer. - **Review and problem indicators plus footer**: fields with active agent review changes (`SetInspectorReviewChanges`) show an amber accent bar and `"was · in review"`; fields failing a project check or schema bound (`SetInspectorFieldProblems` / `Editor.Problems`) show a problem pill beside the control and on the section header. The footer reminds authors: `"Everything else about this object is in its YAML. Ask the agent, or open the file."` - **Matching MCP tools (`editormcp`)**: `object_set_field` edits any single object field, component field, or custom property through the same `Editor` commands as one undo step; `object_locate_yaml` returns an object's 1-based YAML line and snippet (optionally triggering `OnOpenFileAtLine`); and `scene_edit` `set` supports all 2D/3D inspector fields including `particles`, `model`, `gridMap`, `occluder`, `light`, and `camera`. ## Reusable scene parameters (#1936) Scenes may declare typed parameters (`SceneParameter`) with defaults and bindings to fields on their own objects. An instance stores per-use values in its object `parameters` map, while validation rejects duplicate names, unsupported types, wrong defaults, empty bindings, and bindings to missing objects. Existing raw overrides remain available until parameter resolution and inspector/MCP controls are added. ## Generated assets through MCP generator servers (#1053) Open the full-window **Generated Assets** screen (`AssetGeneratorView`) from `Project > Generated Assets` or the Command Palette (`CmdGeneratedAssets` / `SetAssetGeneratorOpen`). Styled strictly with `design/editor/Spec.dc.html` tokens matching Screen 2 of `design/editor/Assets.dc.html`, it connects to external MCP image and sound generator servers, checks returned candidates against the game's `brief.yaml`, and keeps generated output off disk until a person explicitly picks a candidate: - **MCP generator servers (`GENERATORS · MCP`)**: configure servers (`GeneratorServerConfig`, `SetGeneratorServerConfigs`) under **Settings › Tools** (`EditorSettingsDialogView`) and connect via `ConnectAssetGenerator` (any `mcp.Transport`, mirroring `ConnectRemote`) or `ConnectAssetGeneratorCommand` (stdio process on desktop). `AssetGenerators` lists every connected or configured server with live connection status. A server's `kind` is `images`, `sound`, `textures`, `models`, `animation` or `tiles`; only `images` and `sound` can generate today, because `GenerateAsset` refuses a kind that has no in-memory validator (`AssetGeneratorKind.Generatable`) before it calls the server. - **Canonical generation parameters (`pkg/tooling/genparams`)**: on connect the editor reads the tool's `InputSchema` from `ListTools` and maps its properties onto canonical keys (`prompt`, `negativePrompt`, `seed`, `count`, `width`, `height`, `aspectRatio`, `background`, `referenceImages`, `duration`, `loop`, `voice`, `instrumental`, `frameCount`, `faceLimit`) through a built-in alias table that matches snake_case, camelCase and kebab-case spellings of one name, plus an optional `params:` override on the generator entry (canonical key to wire key; a dotted wire key such as `size.width` targets a property nested one object deep; `SetGeneratorServerConfigs` refuses unknown canonical keys). Before any call the request is validated against the tool's schema — types, enums, minimum, maximum, required — and a refused value names the canonical key and the allowed range, with no call made; a valid request is emitted under the tool's own wire spelling. Generated Assets renders one control per parameter the schema declares that the request's own fields do not already carry — primary: aspect ratio, width, height, background, duration, loop; the rest under Advanced — and none for a parameter it does not; the values chosen there travel as extra parameters on vary, refine and regenerate. A tool whose schema is absent or names no canonical property keeps the private argument set, unchanged, and refuses extras rather than dropping them. - **Untrusted output decoded in memory only**: `GenerateAsset` strictly decodes image payloads to raster pixels in memory (re-encoding clean PNG bytes, enforcing bounds, and refusing SVG/HTML/non-image payloads) and validates WAV (`audioconv.DecodeWAV`) or OGG audio in memory. Nothing is written to disk before **Pick**. - **Durable generation job records (`pkg/tooling/genjob`)**: accepted requests have a strict versioned YAML record with request ID, generator/tool, canonical parameters, input fingerprint, lifecycle state and phase, optional remote task ID, and candidate file hashes. Parameter keys and candidates encode in deterministic order, and unknown fields, duplicate keys, trailing documents, unsafe file names, and invalid hashes are refused. The editor writes the record and decoded candidate bytes atomically below `.game/generated//`, which is outside the authored project and ignored by templates. Reopening a project rebuilds the GENERATED rail from completed records and verifies every byte count and SHA-256 before showing it. A request with the same input fingerprint reuses its completed record without another generator call. Records left queued or running by a process exit become failed and are never submitted again. Failed and cancelled records require an explicit Generate again action. The generator receives the stable `request_id` idempotency key when its tool declares it or when it uses the legacy private argument set. A server may return `remoteTask` and configure `statusTool`; the editor polls that task with the same request ID until candidates arrive, while each poll has its own timeout. Closing the Generated Assets screen leaves a call running. **Cancel** explicitly cancels it and records a cancelled job. - **Preview backdrops, `brief.yaml` style checks, and sound audition**: image candidates preview side-by-side with their reference asset on selectable backdrops (`PREVIEW ON`: Floor 3, Floor 1, Checker via `SetAssetGenPreviewBackground`) with pass/fail checks for **Palette**, **Pixel grid**, **Size** against the reference asset, and **Contrast** against the selected wall (`LoadAssetStyleBrief`, `SetAssetStyleBrief`). Sound candidates display waveform bars, duration, RMS loudness (`dBFS`), peak loudness check against the reference sound or brief target, and in-memory audition (`PlayGeneratedSoundCandidate`, `StopGeneratedSoundCandidate`). - **Brief-anchored prompts and reference identity**: generation requests compose the person's prompt, the deterministic style summary loaded from the brief, and a kind-specific framing suffix in that order through `ComposeAssetPrompt`, and only the composed text reaches the generator. The request keeps the person's prompt as `AssetGenerationRequest.Prompt`, which is what **Vary this**, **Refine**, **Regenerate N** and the `.source.yaml` `prompt` use, and the sent text as `AssetGenerationRequest.ComposedPrompt`. `AssetReferenceHash` returns the lowercase SHA-256 digest for reference bytes captured by a generator integration, so provenance can identify the exact payload used. - **Atomic undoable Pick and provenance sidecar (`.source.yaml`)**: **Pick** (`PickGeneratedCandidate`) writes **exactly** the picked media file and its deterministic version-1 `.source.yaml` sidecar (`importsettings.AssetSource`, `AssetSourceVersion = 1`, schema `https://nsgo.games/schemas/source.v1.json`) recording `version`, `generator`, `model`, `prompt`, `seed`, `references`, `license`, `commercialUse`, and `approvedBy` in **one undoable `Editor.History` step**; one `Editor.Undo()` removes both files cleanly. The sidecar also records the request's `kind`, and has an optional `files` list naming further generated files the same record covers (for a model and its material draft, for example); both fields are optional, so version-1 sidecars without them stay valid. Pick also records the lineage of the picked bytes, all optional too: `sha256`, the lowercase hex SHA-256 of the picked file, so a later tool can tell whether the file in the project is still the generated one; `parameters`, the generation arguments sent besides the prompt and references (`count`, `kind`, and when set `model`, `seed`, `vary_seed` and `refine`) as a sorted map, named by canonical key for a mapped generator (for example `aspectRatio`, not the server's wire spelling) and by the private argument's own name otherwise; `referenceHashes`, the SHA-256 captured at request time for each reference that names a readable project file (a `brief.yaml#art` reference hashes `brief.yaml`), keyed by the entry in `references` and captured when the generator request is sent; and, after **Vary this** or **Refine**, `derivedFrom` with the `asset` path and `sha256` of the candidate the request started from (the varied candidate, or for Refine the picked candidate, else the selected one). **Vary this** (`VaryGeneratedCandidate`), **Refine** (`RefineGeneratedAsset`), and **Regenerate N** (`RegenerateAsset`) re-invoke the generator with the same references without writing to disk. - **Export license gate (`LICENSES · CHECKED AT EXPORT`)**: `credits.ScanGeneratedLicenses`, `credits.CheckGeneratedLicenses`, `credits.Collect`, `releaseplan.Build`, `game release`, and the editor's Export panel (`CheckExportCredits`) scan every `*.source.yaml` sidecar in the project. Any generated file with an empty or unknown license (`license: ""` or `license: unknown`) blocks release builds with `*credits.UnknownLicenseError` naming the asset's path until resolved (for example via `SetGeneratedAssetLicense` / **Set license**). `credits.Collect`, `game check`, `game credits` and release checks also surface generated assets whose current bytes differ from the recorded `sha256` as edited after generation. ## Focus ring and keyboard regions (#1003) Every interactive control in the editor carries the `design/editor/Spec.dc.html` focus ring on keyboard focus and is reachable via `Tab`, `F6`, or arrows: - **Keyboard-only focus ring (`:focus-visible`)**: `EditorView` installs `theme.Core()` (also returned by `FocusTheme()`), mapping `info`, `focus`, and `ring` to Spec accent (`#3B7BFF` in Dark, `#1D5CE6` in Light) while preserving Spec Dark and Spec Light surfaces. Buttons, toggle buttons, selects, checkboxes, and `SpecIconButton` / `SpecSwitch` draw a 2 px accent ring with a +2 px offset on keyboard focus only—mouse clicks never draw it. - **Inset rings and `:focus-within`**: tree rows (`SceneTreeView`, `LayersView`), list rows (`AssetBrowserView`, `FilesView`), text fields (`ui.Input`, `ui.NumberInput`), and F6-focused regions draw an inset `-2 px` accent ring via `theme.Palette.FocusRing(-2)` so scrolling parents never clip them. Selected and focused rows keep both their selection fill and the inset ring. Composer and card containers (`SpecFocusWithinCard`, `hud-composer-card`) draw the +2 px accent ring on the card via `:focus-within`. - **Fixed-order keyboard regions (`F6` / `Shift-F6`)**: `F6` moves to the next visible region and `Shift-F6` moves to the previous region in fixed Spec order: **Header** (`RegionHeader`) → **Scene tree** (`RegionSceneTree`) → **Viewport** (`RegionViewport`) → **Agent and Inspector** (`RegionInspector`) → **Status bar** (`RegionStatusBar`) → **Toast** (`RegionToast`, included only while a toast is active in `ToastView` via `Editor.ShowToast`). Entering a region via `F6` / `Shift-F6` draws its inset `-2 px` ring and restores the last control focused in that region. `F6` / `Shift-F6` are suppressed during shortcut capture and full-window screens, and close any open object context menu. - **Viewport focus is the selection**: the viewport canvas draws no focus ring of its own; while focus is in the viewport (`editor-viewport-frame`), `Tab` (`Editor.SelectNextObject`) and `Shift-Tab` (`Editor.SelectPreviousObject`) cycle through visible, unlocked scene objects in order. - **Dialog focus trapping and opener restoration**: editor dialogs (`EditorSettingsDialogView`, `ShortcutsSheetView`, `CommandPaletteView`, unsaved-changes prompt, scene path dialog, and save-conflict dialog) trap `Tab` / `Shift-Tab` inside the topmost modal (respecting shortcut capture in `Settings › Shortcuts`), block global shortcuts behind the modal except `⌘.` / `Ctrl+.` (`Editor.OnStopAgent`) to stop an active agent, and return focus to the exact control that opened the dialog when dismissed with `Esc` or an action button. - **Focus stability**: nothing moves focus automatically during an active drag or inspector scrub (`Editor.IsDragging`) or while typing in a text field (`Editor.IsTyping`). Showing a toast never steals focus, and `Editor.ShouldFocusAgentPrompt` returns `true` only when no drag or text input is active and focus is already inside the agent panel (`Editor.SetAgentPanelRef`). ## Connect an agent and status chip (#1009) Connect an external coding agent (Claude Code, Codex, or any MCP client on your computer) directly from the editor or with `go tool game mcp install`, matching `design/editor/Connect.dc.html`, `design/editor/AgentStates.dc.html`, and `design/editor/Settings.dc.html` using exclusively `design/editor/Spec.dc.html` tokens: - **One-time project install (`go tool game mcp install`)**: writes `.mcp.json` (Claude Code) and `.codex/config.toml` (Codex) idempotently in the project root while preserving existing unrelated servers and settings, and prints each file written or left unchanged. - **Connect dialog (`ConnectAgentDialogView`)**: reachable from `Project > Connect an Agent...`, Command Palette (`CmdConnectAgent`), `Editor Settings > Models and connections` (`+ Connect another agent or model`), or the Agent panel header. Offers three choices (**An agent on this computer** — Recommended, **Built in, with your API key**, and **No agent**), shows `go tool game mcp install` with a **Copy** button, displays `"Waiting for an agent to connect…"` which turns to `"Connected · over "` as soon as the first MCP client attaches, provides four starting permission checkboxes (**Edit scenes and data (always reviewable)**, **Run game check**, **Run headless playtests**, **Edit Go code** -> `AgentPermissionRules`), keeps the Agent panel closed when **No agent** is chosen, and provides **Later** and **Done**. - **Agent tab panel (`AgentPanelView`)**: switches the right sidebar between **Inspector** (`RightTabInspector`) and **Agent** (`RightTabAgent`, `CmdAgentPanel`), showing the thread of requests (including turns made by terminal-started MCP clients), streamed steps, and a labelled multi-line composer (`Enter` sends, `Shift+Enter` adds a line, plus **Send** / **Stop**). Composer requests run through `Editor.AgentRunner` (defaulting on desktop to the agent table's row, which invokes Claude Code's `--print --output-format=stream-json --verbose` or Codex's `codex exec --json` under the launch policy below, or an ACP agent as [Local agents over the Agent Client Protocol](http://nsgo.games/docs/editor/#local-agents-over-the-agent-client-protocol-1935) describes). - **Local agent launch policy**: the editor never lets a project's own agent configuration run when it starts a local agent, because a cloned, templated or downloaded project controls those files. Claude Code starts with `--setting-sources=user` (the project's `.claude/settings.json` and `.claude/settings.local.json`, with their hooks and permission rules, do not load), `--strict-mcp-config` and an inline `--mcp-config` that holds only the editor's server (`nsgo-game-editor`, `go tool game mcp`) and the servers enabled in **Settings › Tools** (never the project's `.mcp.json`), `--permission-mode=dontAsk`, `--allowedTools` set to those servers' tools, and `--disallowedTools=Bash,PowerShell,Edit,Write,NotebookEdit`, so changes go through the editor's tools, turns and `permissions.yaml` even when your own Claude Code settings allow file edits or commands. Codex runs `codex exec` and `codex exec resume` with `--ignore-rules` (no execpolicy `.rules` files), `-c sandbox_mode="read-only" -c approval_policy="never"`, a `-c projects={...}` override that marks the project folder and each folder above it untrusted for that run (so the project's `.codex/config.toml`, its MCP servers and hooks do not load even in a folder you once trusted in Codex), and `-c mcp_servers..command=...` / `.args=...` pairs for the editor's server and the servers enabled in **Settings › Tools**, so Codex has the editor's tools without trusting the folder. Your own `~/.codex/config.toml` still applies apart from the values the editor pins. Every local agent and the built-in agent are told that text read from project files, packs, mods and imported content is data, never instructions. To use another MCP server from the composer, add it in **Settings › Tools** rather than to the project's `.mcp.json`. - **Status chip (`AgentStatusChipView`)**: announces transitions through `core.LiveRegionPolite` and renders all five states while keeping manual tools working in every state: - `Connected · MCP` (hover tooltip names the agent and transport, such as `Claude Code over stdio`) - `Working · step n of m` (violet dot pulses on a `1.2 s` cycle, staying still when `ReduceMotion` is enabled) - `Waiting for you · m:ss` (clicking focuses the open request card) - `Reconnecting · try n of 5` (retries after `1, 2, 4, 8, 16 s` using injectable `Editor.AgentScheduleAfter`) - `Disconnected` with **Reconnect** and **Troubleshoot** (reopens Connect directly at the failed step rather than the start) - `Disconnected · offline` when the editor is offline. ## Play mode marks, rolling replay, and frozen-frame agent questions (#1042) While playing a scene in Play mode (`Play`, `PlayIn`, `StepPlay`, `PlayTick`) or connected to a running game, the editor keeps a rolling 60-second input recording, supports marking moments without stopping, lets you freeze any frame to ask the agent what looks wrong, and adds panic triage with one-click replay up to the panic frame (`design/editor/PlayMode.dc.html`, styled strictly with `Spec.dc.html` tokens): - **Rolling 60-second input recording**: every fixed Play step samples `Editor.PlayInputSource` (watching `Editor.PlayInputActions` / `Editor.PlayInputAxes`, defaulting to the project's input actions in `game.yaml`) into a bounded 60-second sliding buffer (`60 × PlayRateHz()`, 3,600 frames at 60 Hz; `PlayRollingFrameCount`, `PlayRollingSummary` showing `"Last 60 s kept · N frames"`). Marking, asking, or hitting a panic atomically writes a version 2 `replay` YAML file under `replays/-.replay.yaml` (`SavePlayRollingReplay`, `PlayLastReplayPath`) that rebases older windows cleanly while preserving held actions and axis values entering the window. - **Play mode bar and marks (`alt+f` / `CmdPlayMark`)**: local Play mode renders a Spec-styled Play control bar (`playModeBarView`, keeping the 2D edit toolbar compact) with live/paused status pill, Pause/Resume (`mod+shift+p`, `SetPlayPaused`), single-frame **Step** (`.` while paused, `StepPlay`), time scale (`0.25×`–`2×`, `SetPlayTimeScale`), **Mark `⌥F`** (`AddPlayMark`), **Something looks wrong `⌘L`**, and **Stop**. Pressing `alt+f` marks the current frame without stopping Play, saves its `.replay.yaml` under `replays/`, pins a flag on the 60-second frame-time strip, and lists it under **MARKS · N** in the Inspector's **Agent** tab (`PlayInspectorTab`, `PlayMarks`) with time, frame, and `"replay attached"`. Stopping Play (`Stop`)—or clicking **Send marks now** (`SendPlayMarks`) earlier—bundles all unsent marks into **one thread** dispatched to `Editor.OnPlayMarksThread` and stored in `LastPlayMarksThread`. - **Frozen-frame questions (`mod+l` / `CmdAskFrozenFrame`) and MCP replay stepping**: pressing `mod+l` or **Something looks wrong** (`OpenAskFrozenFrame`) pauses Play, captures the frozen viewport PNG, and opens **"Ask about frame N"** with the frame preview, attachment chips, prompt field (`"What looks wrong? e.g. the slime walks through the wall"`), `"A fix comes back as a review"`, **Cancel**, and **Ask**. Submitting (`SubmitAskFrozenFrame`) saves the rolling replay, attaches the frame image and live entity snapshot, dispatches `Editor.OnAskFrozenFrame`, and switches to the **Agent** tab. Connected agents inspect the frozen frame through `editormcp`'s `play_frozen_context` tool and step the replay through `play_replay_step` (`AgentStepPlayReplay`), showing the viewport agent pill (`"agent stepping frames A–B"`) and step log (`"Stepped frames A–B with game_loop_step…"`) while keeping the game paused until the person resumes. - **Output panel panic card and Replay up to the panic**: `ParsePanicTrace` detects Go panic messages and stack traces in run output or recovered Play panics (`OutputPanic`, `SetOutputPanic`). `OutputPanelView` displays a Spec-styled panic card with the message, clickable `file:line` links for game stack frames, folded runtime frames (`"N frames in the game runtime · Show"` / `"Hide"`, `SetOutputPanicRuntimeExpanded`), **Ask the agent to fix** (`AskAgentToFixPanic`, `Editor.OnAskPanicFix`), and **Replay up to the panic** (`ReplayUpToPanic`, `ReplayUpToFrame`), which resets the scene (calling `Editor.OnPlayReset` when set), replays the saved recording through `PlayActiveInput()`, and stops and pauses at `panicFrame - 1` without triggering the panic. ## Permissions and MCP enforcement (#1010) The editor governs every mutating and running MCP tool call with a tracked, versioned YAML rules file, `permissions.yaml`, stored beside `game.yaml` (keeping `.nsgo/` git-ignored for editor-local state while teams share and review permission rules in Git): - **Three profile presets**: - **Cautious** (`cautious`): asks before every content edit, config edit, code edit, file creation, `game check`, and playtest, and denies deleting files or running shell commands. - **Balanced** (`balanced`, default when `permissions.yaml` is absent): edits content (`scenes/**`, `prefabs/**`, `data/**`) and runs `game check` and playtests on its own; asks before `game.yaml`, `brief.yaml`, `**/*.go`, and creating files anywhere; denies deleting any file or running shell commands. - **Autonomous** (`autonomous`): lets the agent complete whole tasks end to end while keeping reviewable undo steps; deletes and shell commands remain denied unless explicitly relaxed. - **First-match-wins rule table**: each rule matches an action (`edit`, `create`, `delete`, `run`, `code`) and slash-separated file globs (`scenes/**`, `**/*.go`, `**`) or run targets (`game check`, `playtests`, `shell`) to a decision (`allow`, `ask`, `deny`). Every evaluation (`Editor.EvaluatePermission`) records the exact rule index or profile that decided it. - **Settings › Permissions (`PermissionsSettingsView`)**: reachable via `File > Permissions...`, the Command Palette (`CmdPermissionsSettings`), or a blocked step link. Displays the three profile cards (retaining the active profile's name with a **Changed** badge when rules are edited from the preset), the reorderable rule table with an arrow-key-navigable **Allow / Ask / Deny** radio group per row, add/remove controls, and an **Agent on this page** rail with blocked-step links and pending approval cards. - **Blocked step links and Always toast**: a `deny` rule never invokes the MCP tool and records a blocked step whose link (such as `"Settings › Permissions · rule 7 of 7"`) opens **Settings › Permissions** with the matching rule focused. Answering **Always** on an `ask` card inserts an `allow` rule ahead of the asking rule, saves `permissions.yaml`, and shows the `"Always permission rule saved"` toast with **Show** and **Undo**. - **MCP-only scope**: rules govern the editor's MCP server tools only. Agents you start yourself in a terminal can still edit files directly, and those edits surface via the editor's disk watcher; local agents the editor starts from the composer, plans and automations cannot, because the launch policy denies their own file and command tools (an OpenCode row is the exception, as [Local agents over the Agent Client Protocol](http://nsgo.games/docs/editor/#local-agents-over-the-agent-client-protocol-1935) explains). ## Ask the agent in place (`⌘L`) and Agent panel (#1037) Pressing `⌘L` (`Ctrl+L` on Windows and Linux, registered as `CmdAskAgent` in `ScopeGlobal` with `core.KeyNotEditing`) outside any text field opens an anchored in-place composer (`AskInPlaceComposerView`, styled strictly with `design/editor/Spec.dc.html` tokens matching `AskInPlace.dc.html`) directly beside the selected object(s) in the viewport: - **Anchored placement and clamping (`OpenAskInPlace`, `AskInPlacePlacement`, `ComputeAskInPlacePlacement`)**: anchors below the selection's viewport bounds (flipping above when near the bottom edge) and clamps strictly inside the viewport container so it stays on screen and never overlaps the right panel (Inspector / Agent panel). Without a selection, it anchors inside the viewport asking about the open scene. Pressing `Esc` (`CloseAskInPlace`) closes without sending and restores focus to the control that held it before `⌘L`. Pressing `⌘L` while typing in the Inspector or any text input is ignored. - **Announced selection chip, multi-line field, and contextual suggestions**: displays an accessible `RoleStatus` / `LiveRegionPolite` chip announcing the selection count and object names (for example `"2 selected · slime_01, slime_02"`), a real labelled multi-line input (`⇧↵` inserts a newline, `↵` or `⌘↵` sends), up to two contextual suggestions (such as `"Make them a prefab variant"` and `"Space them evenly"` for multi-selection) navigable with `↑`/`↓` and `↵` without blocking free typing, and the localized hint `"⌘L asks about the selection · ⌘K searches · right-click 'Ask the agent'"`. - **Draft and outgoing context**. Dismissing the composer keeps a non-empty draft. Invoking it again for a different selection also saves the current draft for its original targets. Reopening on the same selection and scene restores the draft and announces the restoration to screen readers. Choose **Clear draft** to discard the current target’s draft and return focus to the input. Sending also clears the draft. The `Sends:` line and the dialog’s accessible description show how many target objects remain in the scene, the scene file, and the viewport image when the `ViewportImages` privacy switch allows it. The line updates while the composer is open and uses the same object and privacy checks as sending. - **Context menu wiring**: choosing **Ask the agent about this** (`AskAgentAboutObject`) from either the viewport context menu or the Scene Tree context menu opens the same anchored composer for the target object (or the full multi-selection when the object is part of one). - **Agent panel and MCP context delivery**: sending starts an `AgentTurn` (`SubmitAskInPlace`) flagged `SkipPlan: true` (matching `Plan.dc.html`: *"Small edits with ⌘L skip the plan."*), attaches the resolved targets’ object IDs and names, the open scene path and YAML, and a rendered viewport PNG if viewport images are enabled (`RenderViewportPNG`), switches the right rail (`RightRailView` / `RightRailTab`, toggleable with `⌘1` / `⌘2`) to the **Agent** tab (`AgentPanelView`) showing the turn with context chips, and notifies connected MCP clients through `editormcp`'s `editor://agent/turn` resource and `agent_turn_get` / `agent_turn_reply` tools. - **The pinned selection is the agent's edit target, the live selection only context**: while the turn is open, `object_set_field`, `object_duplicate`, `object_group`, `object_move_under` and `object_visibility` called without `id` edit the objects the turn pinned when it was sent (`Editor.OpenAgentTurnPin`), so selecting something else while the agent works never redirects its write, and the object a parallel task holds is the one it writes. Outside a turn those tools need `id`, and a pinned object that was removed or renamed is refused with its own error ([mcp](http://nsgo.games/docs/mcp/#edit-targets)). - **Which turns pin a selection**. The `⌘L` composer pins the objects it was opened for. Agent panel requests and background tasks pin the selection when sent, including tasks waiting in the queue. A request pins nothing when the selection is empty or it targets another scene. The Agent panel's selection chip and `agent_turn_get` (`selectionIds`, `selectionNames`) show the pin. File, review, export and clock automation triggers carry no object target, so their edits require an explicit ID. ## Background task list with queued and parallel agent requests (#1022) Requests, plan steps, and automations share one background task list in the Agent panel (`TasksPanelView`, styled strictly with `design/editor/Spec.dc.html` tokens matching `Tasks.dc.html`), toggled from the status bar indicator (`status-tasks`), `View > Background Tasks`, or `CmdToggleTasks` (`mod+shift+t`): - **Task model and plain-text thread persistence (`AgentTask`, `AgentThreadDoc`)**: tasks move across five visible groups—**Needs you** (`TaskNeedsYou`), **Running** (`TaskRunning`), **Ready to review** (`TaskReadyToReview`), **Queued** (`TaskQueued`), and **Failed** (`TaskFailed`)—plus completed (`TaskDone`) and stopped/reverted (`TaskStopped`) states. Each project persists its task list in plain-text YAML under `.nsgo/threads/.thread.yaml` (`AgentThreadVersion = 1`, deterministic output, unknown fields and duplicate keys refused via `ParseAgentThread` / `EncodeAgentThread`, round-trip lossless). - **Task selection chip**. Each task row shows the pinned object names when its request recorded a selection. Thread YAML stores the optional `selectionIds`, `selectionNames`, and `primarySelectionId` alongside the task's scene. Tasks loaded from older files without those fields have no pin. - **Queue vs Run in parallel (`SubmitTask`)**: - **Queue** (`TaskStartQueue`): waits behind the running or unreviewed turn and starts **only after** that turn is kept (`KeepTask`) or reverted (`RevertTask`), so queued requests always build on the reviewed scene. - **Run in parallel** (`TaskStartParallel`): starts immediately as a separate agent session with its own numbered overlay (`1`, `2`, …). - **Default runner and Connect guard**: when `Editor.AgentTaskRunner` is nil, `SubmitTask`, `SubmitComposerTask`, `tasks_submit`, and `advanceTaskQueue` run each task through the same agent route as the agent composer (`resolveRouteAndRunner` — external CLI or built-in API key runner) in a fresh session with its own `AgentTurn`, streaming steps, `Needs you` permission asks, `Ready to review`, and `Failed` transitions. Submitting a runnable task when no agent is connected opens the Connect dialog and creates no task. - **Object holds and permissions in `editormcp` (`Server.ConnectTask`, `CompleteTaskTurn`, `ReleaseTaskHolds`, `TaskReviewSnapshot`)**: each parallel task runs on its own MCP session bound to its task ID (automatically via `NSGO_EDITOR_TASK_ID` for CLI subprocesses through `go tool game mcp` and via `WithTaskToolContext` for the built-in runner). Editing an object (via `scene_edit`, `object_set_field`, object menu tools, or tile edit tools) holds that object for the task's active turn; another parallel session trying to edit the same object holds cleanly in FIFO order, updates its step and overlay to `"waiting on "` naming the holding task, and automatically resumes once the first task finishes its turn or releases holds—producing separate `TaskReview` entries per turn. Tools matching an `Ask` permission rule pause the task in **Needs you** (`BeginTaskPermissionAsk`) until the person's **Allow once** or **Deny** (`ResolveTaskPermission`) resolves it. - **Numbered overlays in the viewport and scene tree**: active tasks draw solid violet (`theme.Palette.Agent`) outlines with numbered pills (`1 placing the jump arc`) on objects they are editing and 45%-opacity dashed outlines with a clock glyph and `"2 waiting on slime_02"` pill on objects they are holding, paired with a compact bottom-left viewport legend and `"1 · editing"` / `"2 · holding"` badges on scene tree rows (`ObjectTaskBadge`, `SceneTaskOverlays`). - **Bulk dismiss and summary badge counts**: multiple **Ready to review** tasks can be checked (`ToggleTaskDismissSelection`) and dismissed together (`DismissSelectedTasks` / `DismissTasks`) without reverting anything that was kept. `TaskSummary` and `TaskDockBadgeCount` expose counts for `NeedsYou`, `Running`, `Blocked`, `ReadyToReview`, `Queued`, `Failed`, `MostUrgent`, and `DockBadge = NeedsYou + ReadyToReview + Failed` (excluding running and queued) for both the status bar (`No tasks`, `1 running · 0:38`, urgent-first mixed counts, persistent `Failed`) and downstream notifications/Dock badges (#1023). - **Matching MCP tools (`editormcp`)**: `tasks_list` lists tasks, active holds, and summary counts; `tasks_submit` queues or starts parallel requests; and `tasks_control` runs `retry`, `open`, and `focus`, `stop` and `revert` of the calling session's own task, and `dismiss` of Failed tasks. - **Person-only decisions**. Keeping a task (`KeepTask`), answering its permission prompt (`ResolveTaskPermission`, allow or deny), and dismissing a task that is Ready to review are the person's decisions. Called from an agent's MCP tool call (`RunAsAgent`, which scopes each MCP tool call on the editor goroutine), `KeepTask` and `ResolveTaskPermission` return `ErrTaskDecisionYouOnly` (`ErrAutomationYouOnly` for an automation task's keep), `DismissTasks` skips Ready to review tasks, and `tasks_control` refuses `keep`, `allow`, `deny`, `revert` and `stop` of a task bound to another session, and `stop` or `dismiss` of a Ready to review task. `StopTask` refuses a Ready to review task for every caller, since stopping it would end its review without reverting its edits. ## Game brief and project rules (#1026) Settings (`EditorSettingsDialogView`, matching `design/editor/Settings.dc.html` and styled exclusively with `Spec.dc.html` tokens) adds two shared project pages under **AGENT** that the agent reads before every request: - **Game brief (`brief.yaml`, `OpenBriefSettings`)**: edits the versioned `brief.yaml` file at the project root (`project.Brief`, `project.ParseBrief`, `project.EncodeBrief`, JSON Schema `https://nsgo.games/schemas/brief.v1.json`) with labelled fields for **Pitch**, **Genre**, **Tags**, **Platforms**, **Art direction**, **Feel and difficulty** (including structured playtest targets readable via `playtest.TargetsFromBrief` / `playtest.ApplyBriefTargets` / `Editor.BriefPlaytestTargets`), and **Tone and audio**. Projects without `brief.yaml` show an empty state; filling and saving writes a canonical `brief.yaml` that round-trips byte-for-byte unchanged, unknown fields are refused with their 1-based line number (`loaderr`), missing sections appear as `"1 gap"` / `"N gaps"` in the sidebar, and every edit records an undoable step in `Editor.History` (`EditBrief`). The brief, its `art` and `feel` sections and each feel target take an optional `basis` of `locked` (a decision only the person changes), `target` (an experience goal) or `assumption` (a default an agent may revise), editable from the section and target selectors. **Save brief** applies the section choices. Changing an existing target's basis saves that edit immediately. New targets default to `target`. Every edit that adds, removes or changes a feel target appends an entry to the brief's `changes` list (`project.BriefChange`: the UTC `date`, the `field` such as `feel.targets.floor_03.deaths`, the `from` and `to` bounds and basis, and the edit as the `reason`), and undoing the edit removes the entry with it. - **Project rules (`AGENTS.md`, `OpenRulesSettings`)**: edits the plain Markdown `AGENTS.md` file at the project root (shared by Claude Code, Codex, and the built-in agent) in a monospace code field as undoable steps (`SetProjectRules`), showing the bulleted rule count (`ProjectRulesCount`) in navigation. Patterns of consistently reverted reviews (`RecordReviewOutcome` / `SuggestedProjectRules`) surface suggested rules (such as `"Suggested from your last 30 reviews: you reverted every change that moved the camera bounds."`); pressing **Add as a rule** (`ProposeSuggestedRule`) opens a reviewable diff card (**Keep** / **Revert**) without modifying `AGENTS.md` on disk until kept. - **Reviewable agent edits**: agent proposals through `editormcp`'s `brief_edit` and `rules_edit` queue pending `DocReview` cards (`ProposeBriefReview` / `ProposeProjectRulesReview`, `KeepDocReview` / `RevertDocReview`) without touching disk until kept; kept reviews apply as one undoable step in `Editor.History`. - **Agent on this page and Settings search**: both Agent pages render the right-hand **Agent on this page** card with a contextual note, clickable suggested asks, and an inline composer; clicking a suggested ask or submitting a prompt in the top Settings search bar calls `AskAgentFromSettings`, staging the page-contextualized prompt in `ComposerDraft` and invoking `Editor.OnSettingsAgentRequest` (and `Editor.OnComposerPrompt`). ## History panel: your edits and the agent's turns on one timeline (#1017) The History panel (`HistoryPanelView`), styled with `design/editor/Spec.dc.html` tokens matching `AskInPlace.dc.html` and `Checkpoints.dc.html`, brings manual edits, kept agent turns, external Git reloads, and saved points onto one chronological timeline: - **Rich timeline entries (`History.Entries`, `Editor.HistoryEntries`)**: each `HistoryEntry` records who made the change (`HistoryAuthorYou`, `HistoryAuthorAgent`, or `HistoryAuthorGit`), a concise headline and detail (such as `You · moved Knight` / `x 416 → 452` or `Agent · slimes and coins` / `6 changes · kept 5`), the list of touched files, change/kept counts, and a timestamp driven by an injectable clock (`Editor.SetHistoryClock` / `History.SetClock`) for deterministic testing. Saving records a `HistoryEntrySaved` marker (`Saved · level_01.scene.yaml`) capturing the saved snapshot. - **Unified multi-file agent turns (`Editor.RecordAgentTurn`)**: groups scene, project, and extra touched project files under one undoable `History` step tagged as `HistoryAuthorAgent`, alongside automatic agent attribution for `editormcp` edits (`EnterAgentContext` / `LeaveAgentContext`), `KeepTileReview`, and `KeepCutsceneReview`. - **Opening and filtering**: press `⌘Y` (`Ctrl+Y` on Windows/Linux, `CmdHistoryPanel`), choose **View > History**, or click the toolbar history icon button (tooltip `"History · ⌘Y"`). Entries appear newest-first grouped by day (`TODAY`, `YESTERDAY`, or date) below a **Now** row marked `unsaved` when dirty, with **All** / **You** / **Agent** filter tabs (`Editor.SetHistoryFilter`). - **Read-only point-in-time preview (`PreviewHistoryEntry`, `ExitHistoryPreview`)**: clicking any timeline entry renders that step's snapshot read-only in the 2D and 3D viewports with a `"Previewing · editing is off"` banner, without mutating `Editor.Doc` or moving `History`'s undo cursor. Pressing `Esc`, **Back**, or **Now** exits preview cleanly. - **Non-destructive Restore (`RestoreHistoryEntry`)**: clicking **Restore** rolls the active scene, project, and every extra touched file back to that point as **one new undoable step** in `History`. Later steps remain in the timeline and can still be previewed or restored, and a single `Undo` returns immediately to the latest state. - **Agent read access (`editormcp`)**: the read-only `history_list` tool (`ActionRead`) exposes the same newest-first timeline to connected agents with optional `author` (`all`, `you`, `agent`) and `limit` filters plus unsaved and active preview metadata. ## Persistent per-turn checkpoints (#1018) Agent turns, autonomous tasks, and automations persist across editor restarts inside the project's `.nsgo/checkpoints/` directory and appear alongside session edits in the unified History panel (`⌘Y`, `CmdHistoryPanel`): - **Lazy first-write capture (`.nsgo/checkpoints/`)**: before an agent turn (`BeginCheckpointTurn` / `RunCheckpointTurn`, or any file-mutating `editormcp` `ActionEdit` tool call) first modifies a project file—scenes, prefabs, data tables, `game.yaml`, Go code, or verbatim binary media—the editor snapshots its pre-turn bytes under `.nsgo/checkpoints//files/` and writes a strict versioned YAML manifest (`manifest.yaml`, `editor.CheckpointVersion = 1`, JSON Schema `https://nsgo.games/schemas/checkpoint.v1.json`). Files created by the turn record `existed: false` so restoring deletes them. `.nsgo/checkpoints/.gitignore` and `.nsgo/.gitignore` are written automatically so checkpoints stay ignored by Git, and `Editor.CheckpointMaxBytes` (default `128 MiB`) prunes the oldest completed checkpoints when total size exceeds the cap. - **Tasks and automations**: autonomous background tasks (`TakeCheckpointBeforeTask`, `RunTaskWithCheckpoint`, and `SubmitTask` runners) and automations (`TakeCheckpointBeforeAutomation`, `RunAutomationWithCheckpoint`, `game_playtest`, and automation-mode MCP edits) always persist a checkpoint before they start. - **Security and integrity**: checkpoint capture, writes, and restores strictly exclude `.git/`, `.nsgo/`, and all You-only configuration files (`MatchYouOnlyPath` / `CheckYouOnlyTarget`), refuse symlinks along every path component, cap manifest and file sizes (`2 MiB` / `32 MiB`), and verify both byte length and SHA-256 digests before writing. - **Unified History preview and one-step undoable restore**: `OpenProject` reloads persisted checkpoints into `HistoryPanelView` (`UnifiedHistoryEntries`). Clicking a checkpoint previews its scene snapshot read-only (`PreviewCheckpoint`), and **Restore** (`RestoreCheckpoint`) atomically restores every touched file on disk, synchronizes open tabs and `game.yaml`, and records one undoable step (`checkpointRestoreCmd`) so `Undo` (`⌘Z`) puts the entire turn back byte-for-byte. - **Matching MCP tools (`editormcp`)**: `checkpoint_list` (`ActionRead`) lists unified history and persisted checkpoints; `checkpoint_restore` (`ActionEdit`) evaluates permission rules (`edit`, `code`, `delete`) and You-only boundaries against every file recorded in the checkpoint manifest before restoring as one undoable step. ## You-only trust boundary and proposed deletions (#1015) Settings that govern what an AI agent is allowed to touch — **Permissions** (`permissions.yaml`), **Tools** (`tools.yaml` / `mcp.yaml`), **Models** (`models.yaml`), and **Usage** (`usage.yaml`) — follow the **You-only rule** (`design/editor/Permissions.dc.html`, `Settings.dc.html`): - **Hard MCP refusal (`editormcp`)**: Every non-read tool on the editor's MCP server refuses any write, rename (including bare-stem `refactor_rename`), or deletion targeting a You-only file (`permissions.yaml`, `.nsgo/permissions.yaml`, `tools.yaml`, `models.yaml`, `usage.yaml`, or per-user `editor.yaml`, including through symlinks and case-insensitive host aliases), returning a structured `*editormcp.YouOnlyError` even when the active profile is `Autonomous`. - **Permissions draft card (`permissions_draft` / `PermissionsDraftCardView`)**: The agent can only submit a draft via `permissions_draft` (`Editor.SubmitPermissionsDraft`). The draft opens as its own modal `ui.Dialog` with focus trapping and opener focus restoration, showing each rule's `NOW → DRAFT` decision, a live `permissions.yaml · if applied` YAML diff preview, per-rule checkboxes with **nothing ticked by default**, **Discard draft**, and **Apply n rules**. `⌘↵`, **Keep all**, automations, and every profile (`Autonomous` included) cannot apply the draft. Applied rules are recorded in `History` as the person's (`HistoryActorPerson`) and can be undone byte-for-byte with `⌘Z`. - **External disk changes to `permissions.yaml` (`ReconcileExternalPermissions`)**: When `permissions.yaml` changes on disk outside the editor (a clone, `git pull`, or another tool), **tightened profiles and rules apply at once**, while **loosened profiles or rules** (such as changing `Balanced` to `Autonomous`, turning `Deny` into `Allow`, or removing a `Deny` rule) are **held** and not enforced until the person explicitly confirms each entry in **Settings › Permissions** (`ConfirmHeldPermissionLoosening` / `RejectHeldPermissionLoosening`). - **Proposed deletions that Keep all never applies (`game_delete_file` / `AgentReviewPanelView`)**: `game_delete_file` is off by default (`Editor.ToolEnabled("game_delete_file") == false`) and always proposes a deletion in the **Review changes** panel (`Editor.ProposeFileDeletion`) showing the file's exact line count (or binary summary), a red-tinted preview, and whether any scene uses it (via `Editor.FindUsages`), while refusing symlinks, `.git/**`, `game.yaml`, open scene tabs, and files above 1 MiB. **Keep all** (`Editor.KeepAllReviewChanges` / `⌘↵`) keeps the other changes and leaves pending deletion files untouched on disk; confirming in place (**Delete this file** / `Editor.ConfirmProposedDeletion`) deletes the file through a reversible checkpoint command (`deleteFileCmd`), and **`⌘Z` (`Editor.Undo`)** restores the file byte-for-byte. - **Person actions during automation**. A person can confirm a proposed deletion, adjust settings, or take another review action while a background automation runs. Agent tool calls carry the `Editor.RunAsAgent` marker for the duration of the call. `ApplySettings` returns `ErrAgentSettingsYouOnly` for calls under either `Editor.RunAsAgent` or `Editor.WithAgentActor`. ## Toasts and feedback channels (#1004) Passing feedback in the editor uses one Spec-styled toast component (`ToastView`, `WindowToastView`, and `SpecToastCard`, matching `design/editor/Toasts.dc.html` and `Spec.dc.html` using exclusively `theme.Palette` tokens). Decisions never go in a toast: permission asks and questions stay in Agent panel cards, check failures go to Problems, and finished agent turns open Review. - **Five kinds on one 40 px, radius 12, single-line pill**: - `ToastSuccess` (check-in-circle icon, `Added.Fg`), `ToastInfo` (`i`-in-circle icon, `TextMuted`), `ToastWarning` (triangle icon, `Warning.Fg`, on `Warning.Fill` and `Warning.Edge`), `ToastError` (circle-with-bar icon, `Removed.Fg`), and `ToastProgress` (progress ring + bottom 2 px bar + live percent). - At most one verb action button (with its shortcut hint, such as `Undo ⌘Z`) and a dismiss button on every kind except `ToastProgress`. - **Canonical Spec event API (`Editor.EmitToastEvent`, `ToastHandle`, `SpecFeedbackChannels`)**: screens emit typed `ToastEvent` values (`ToastEventReviewKept`, `ToastEventReviewReverted`, `ToastEventFixApplied`, `ToastEventAgentStopped`, `ToastEventPermissionSaved`, `ToastEventCopied`, `ToastEventDiskChanged`, `ToastEventSaveFailed`, `ToastEventExportRunning`, `ToastEventExportFailed`) instead of inventing ad-hoc tones, durations, or queue keys. `EmitToastEvent` returns a `*ToastHandle` so long-running work such as `export_panel.go` exports can update completion (`SetProgress`), transition in place into a success toast (`Complete`, e.g. `"Exported "` with **Show in Finder**) or persistent error toast (`Fail` with **Retry**), or cancel the running work (`Cancel`). - **Placement**: bottom center of the viewport, 8 px above the viewport bar (never over the scene tree, inspector, or agent panel). When no viewport is on screen (Start screen, Settings, Export, or other full-window views), `WindowToastView` anchors at the bottom center of the window, 24 px up. - **Queue, waiting badge, merging, and ordering**: one toast is shown at a time; others wait in FIFO order and the visible toast displays a `+N` waiting count badge. Repeating the same event merges into the existing queued entry in place without changing order, and nothing jumps ahead of an active error or running progress toast. - **Timing, pause, motion, and accessibility**: - `ToastDuration` enforces Spec lifetimes: success and info stay for 4 s (6 s with an action), warning stays for 8 s, and error and progress stay until retried, dismissed, canceled, or completed. Hover, touch, keyboard focus inside `RegionToast`, or the window leaving `core.LifecycleActive` (going to the background) pauses the countdown (`Editor.ToastTimerPaused`, `Editor.ToastRemaining`). - Enter motion fades in and rises 8 px over 180 ms; exit fades out over 120 ms. With `ReduceMotion` enabled, toasts appear and leave immediately with no fade or movement. - Both toast hosts are polite live regions (`core.RoleStatus`, `core.LiveRegionPolite`). Showing a toast never steals focus; `F6` / `Shift-F6` reaches `RegionToast`, `Tab` moves between its action and dismiss buttons, and `Esc` while focused dismisses the toast and restores focus to the control focused before entering the toast. - **Spec Feedback channels table (`SpecFeedbackChannels`)**: | Event | Channel | Action / Notes | | --- | --- | --- | | Review kept or reverted | Toast | `Undo ⌘Z` | | Fix applied from Problems | Toast | `Undo ⌘Z` | | Agent stopped with `⌘.` | Toast | `Review` | | “Always” permission rule saved | Toast | `Show` | | Copied a config, path or snippet | Toast | Info (routed from Connect, copy YAML, copy objects, web URL, PR description, diagnostics) | | A file changed on disk outside the editor | Toast | Warning · `Show` (routed from disk watcher reload) | | Save or export failed | Toast | Error · `Retry`, stays (explicit `⌘S` / Save and export failures only; failed autosaves stay in the status bar per `Checkpoints.dc.html` and never toast) | | Export running | Progress toast | `Cancel`, stays until done then turns into `"Exported "` with `Show in Finder` | | Agent asks permission or a question | Agent panel card | Never a toast | | Agent finished a request | Review opens | Never a toast | | Check failed, broken reference | Problems | Never a toast | | Agent asks, finishes or stops while the editor is in the background | + System notification | Paired with its in-editor channel | ## Agent automations (#1029) Project automations (`automations.yaml` beside `game.yaml`, schema `https://nsgo.games/schemas/automations.v1.json`) let the agent run follow-up checks and tasks after a change while keeping every result reviewable (`design/editor/Settings.dc.html`, `Tasks.dc.html`, `Checkpoints.dc.html`): - **Versioned YAML format (`AutomationsFile`, `ParseAutomations`, `EncodeAutomations`)**: `version: 1` with an ordered `automations` list of `{id, name, enabled, trigger, instruction}`. Unknown fields, trailing documents, duplicate keys, YAML anchors/aliases, duplicate IDs, and invalid trigger options are refused with `*loaderr.Error` line/column diagnostics; encoding is deterministic and round-trips byte for byte. - **Five triggers**: - `file_changed` (`glob`): fires when a matching project file is saved (manual save, autosave, or tab save), supporting `*`, `**`, and `?`. - `review_kept` (optional `glob`): fires when an edit review is kept (`KeepReview`, `EndReview(true)`, `KeepTileReview`, `KeepCutsceneReview`, `KeepAllReviewChanges`, `KeepAgentTurnReview`), skipping the originating automation ID to avoid recursion. - `file_added` (`kind`, optional `glob`): fires when a new file of kind `prefab`, `scene`, `tileset`, `cutscene`, `material`, `particles`, `rig`, `screen`, `datatable`, `script`, `asset`, or `any` is created (`NewScene`) or detected by disk watching (`PollDiskChanges`). - `before_export` (optional `platform`): fires before `StartExportBuild` or `StartReleaseBuild`. - `daily` (`time` in 24-hour `HH:MM`): fires once per calendar day at or after `time` while the editor is open (driven periodically by the UI scope scheduler and deterministically via `Editor.StepAutomations`). - **Automations that arrive with a project stay off until you allow them**: an `automations.yaml` with enabled rules that came with a clone, template or pack, or that changed outside the editor (for example after `git pull`), does not start any run on this computer. **Settings › Automations** shows the rules with their instructions and an **Allow automations** button (`Editor.AllowProjectAutomations`); allowing records the project folder and the file's SHA-256 under `agent.approvedAutomations` in your `editor.yaml`, never in the project. Changes you make in the editor keep an allowed file allowed, and a file whose contents change elsewhere is held again (`Editor.AutomationsHeld`). - **Pre-run checkpoints, permissions, background tasks, and Ready to review**. Before starting any automation task, the editor snapshots tracked project text/YAML/Go files (excluding You-only and internal state files, bounded by file count and total size, skipping symlinks) into `.nsgo/checkpoints//` (git-ignored, inspectable via `AutomationCheckpoints`, restorable via `RestoreAutomationCheckpoint` with symlink containment checks). Each run executes with bounded concurrency and a timeout. Its tool calls run under `WithAgentActor` and the project's permission rules (`Editor.Permissions` / `CheckAutomationActionPermission`). Each run appears in the shared background task list (`TaskSourceAutomation`) and as an `AgentTurn` in **Ready to review** (`AgentReviewReady`) inside the Agent panel with **Keep**, **Dismiss**, and **Restore checkpoint** controls. `automations.yaml` and `.nsgo/automations-state.yaml` are protected by the You-only trust boundary (`YouOnlyAutomations`), and automations can never apply You-only drafts (`PermissionsDraft`, `AutomationDraft`), confirm held loosenings or proposed deletions, or keep/modify their own reviews (`ErrAutomationYouOnly`). - **Settings › Automations (`SettingsPageAutomations`)**: lists `WHEN → THE AGENT` cards with weekly run counts (`AutomationWeeklyRuns`, stored locally in git-ignored `.nsgo/automations-state.yaml`) and `SpecSwitch` (`core.RoleSwitch`) toggles, **+ New automation, in words** (`DraftAutomationFromWords` -> reviewable YAML card -> human **Keep** via `KeepAutomationDraft`), **Pause all automations for today** (`PauseAutomationsForToday` / `ResumeAutomations` — stops every trigger until the next calendar day), and the **Agent on this page** card, styled exclusively with `theme.Palette` tokens in Dark and Light appearances. ## Change-by-change agent turn review (#1014) When an agent completes a turn (`Editor.StartTurnReview`), the full-window **Review** screen (`ReviewScreenView`, `design/editor/Review.dc.html`, styled strictly with `Spec.dc.html` tokens in both Dark and Light appearances) lets the author inspect every change across scenes, prefabs, data tables, and Go files one by one before keeping them in a single undo step: - **Header and blockers**: displays **← Editor** (`Esc`), the quoted agent request, an optional blocker warning pill (when a conflict, YAML error, or other blocker prevents keeping), **Revert all** (`⌘⌫` / `Ctrl+Backspace`), and **Keep N of M** (`⌘↵` / `Ctrl+Enter`). When any blocker is active, **Keep** refuses to commit and jumps focus straight to the blocking change (`JumpToReviewBlocker`). - **Grouped left list and filters**: pairs a live search input (`SetReviewSearch`, matching name, field, detail, or file path), a `"N of M seen"` counter with progress bar and Previous/Next buttons, and six counted filter chips (**All**, **Added**, **Changed**, **Removed**, **Unseen**, **Notes** via `SetReviewFilter`). Changes are grouped by **file** (path, `+n ~n −n` counts, fold toggle, **Revert file** / **Restore file**), then by **kind** (**ADDED**, **CHANGED**, **REMOVED** with fold and **Revert n** / **Restore n**), then one card per change with a seen mark, semantic kind mark, title, detail, and **Revert** / **Restore** (`X`). Focusing any change marks it seen. - **Keyboard scope (`ScopeReview`) and navigation**: registers `J` (`CmdReviewNext`), `K` (`CmdReviewPrev`), `X` (`CmdReviewToggleRevert`, toggling the focused change, kind group, or file group), `B` (`CmdReviewPeekBefore`, hold `B` to peek at the scene as it was before the request), `⌘↵` (`CmdReviewKeep`), and `⌘⌫` (`CmdReviewRevertAll`) in `ScopeReview`. Every control shows the Spec 2 px focus ring and is reachable via `Tab`, `F6` / `Shift-F6` (cycling Header → List → Preview → Why & YAML), or arrows; typing in the filter field never triggers single-letter shortcuts. - **Adaptive center preview**: - **Scene files**: renders the focused change's scene (`BuiltScene`) with clickable top-left overlay legend toggles (`ToggleReviewOverlayLegend`), draws unfocused changes at `1.5 px` and the focused change in its **own** semantic color and dash at `2.5 px` with an outlined pill (never Spec accent, which remains reserved for selection), draws reverted changes as they were before the request, frames each focused object on `J`/`K`, and shows `"Before this request"` while holding `B`. - **Prefab files**: shows before → after field values with numeric `Δ%` and computes where the change applies across both scenes in the current review and existing project scenes via `Editor.FindUsages`. - **Small data tables**: renders the table (`ReviewDataTablePreviewFor`) with changed rows highlighted and modified cells showing `old → new Δ%`. - **Right pane (Why + YAML)**: shows the agent's reason (**WHY**) above the line-numbered YAML lines touched by the focused change with `+` / `−` signs. - **Esc / Resume pending state**: pressing `Esc` (`PauseReview`) returns to the editor while leaving the review pending—the main viewport renders pending change overlays (`drawPendingReviewOverlay`) and the right-rail **Agent** tab (`AgentPanelView`) shows `"Review waiting · N changes, F files"` with seen count, blockers, and **Resume review** (`ResumeReview`), which returns to the exact same focused change and seen state. - **Keep, Revert all, and one-step Undo**: **Revert all** asks in a focus-trapped confirmation dialog naming every file that goes back and reminding that `⌘Z` / `Ctrl+Z` brings everything back. Both **Keep** (`KeepTurnReview`) and **Revert all** (`ConfirmReviewRevertAll`) execute as **one `Editor.History` step**, update saved YAML files and the open scene, show a Spec toast with **Undo**, and record `"Kept K · reverted R · one undo step"` in the Agent panel; a single `Editor.Undo()` restores every touched file byte for byte. - **MCP read access (`editormcp`)**: the read-only `review_status` tool (`ToolReviewStatus`, `ActionRead`) lets connected agents inspect which changes have been seen or reverted, overlapping conflict choices (`mine`, `agent`, `both`), hand-edited YAML fields and lines tagged `"you"`, active blockers, and keep/revert outcomes (including after Keep for round 2) without granting the agent permission to keep or revert the turn (unsent draft notes are never exposed, and `SceneAndData` / `GoSource` privacy rules are enforced). ### Review notes and second-round redo (#1031) Instead of reverting everything or hand-editing YAML when one or two changes need adjustment, authors can leave change-scoped notes on the active turn and have the agent redo only those changes as **Round 2** within the same review (`design/editor/Review.dc.html`): - **Inline note composer (`C` / `CmdReviewNote`) and viewport pins**: pressing `C` on a focused change (or clicking its speech-bubble button) opens an inline note composer under the card (`"Note for the agent · not sent"`) with **Add note** (`CommitReviewNote`), **Revert and redo with this note** (`RevertAndRedoReviewChange`), and **Cancel** (`CancelReviewNoteComposer`, or `Esc`). Saved notes appear on the card with **Edit** and **Remove** (`RemoveReviewNote`) and as Spec-token speech-bubble pins beside noted objects in both the Review viewport and the paused 2D viewport (`ReviewViewportPins`). Notes live strictly in memory on the turn, are bounded in length and count, and are never written to any scene, prefab, or data file; a note added and removed before sending never reaches the agent. - **Send notes and noted-only redo (`SendReviewNotes`, `ApplyReviewRedo`, `editormcp`)**: clicking **Send N notes** in the header (which becomes the primary accent button while unsent notes exist) dispatches all remaining notes to the agent over MCP (`review_notes_get`), naming each change's `change_id`, `file`, `object`, `field`, `kind`, and `note`. The agent revises only noted changes within the same turn via `review_redo` (un-noted changes and tampered un-noted objects in the same file are refused, You-only/permission/privacy rules are enforced). Redone changes appear unseen again in Round 2+ with `"Redone from your note: …"` in **WHY** and `"Revised in round N. Your note: …"` on the card. - **Round tabs, banner, filters, paused card, and single-step Undo**: once Round 2 exists, the header shows **Round 1 | Round 2** tabs (`SetReviewViewRound`) and a banner below the filter chips (`"Round 2 · the agent redid only the N changes you left notes on. Both rounds keep and undo as one step."`). **Round 1** is read-only (`ErrReviewReadOnlyRound` on edit/revert/note attempts) and shows the agent's first version for comparison; **Keep** (`⌘↵`) always applies the **latest round** as **one `Editor.History` step**, so a single **Undo** (`⌘Z`) restores every touched file to its exact pre-request bytes. The **Notes** chip filters to changes with notes, the paused **Agent** panel card shows unsent note counts (`"N notes not sent"`), and the **Revert all** dialog warns that pending notes will be dropped. ### Review conflicts and in-place YAML hand editing (#1032) Inside the change-by-change Review screen, two cases block **Keep** cleanly without losing either the author's or the agent's work: - **Three-way conflict resolution (`syncReviewAfterMutate`, `SyncReviewPersonEdits`, `ResolveReviewConflict`)**: manual edits made through editor commands (`MoveObject`, `SetProperty`, `SetComponentField`, and so on) while a review turn is pending automatically three-way merge against the turn baseline and agent snapshot via `sceneformat.Merge`. Edits to **different fields** of the same object merge cleanly without asking; overlapping edits to the **same field or list** (such as appending to `door_1`'s `on_open` list) display both sides inside the change card with line authors (`you`, `agent`) and a **Mine / Agent's / Both** segmented control (`ReviewConflictMine`, `ReviewConflictAgent`, `ReviewConflictBoth`), where **Both** keeps both entries with **yours first**. Until every unresolved conflict is chosen, **Keep** is disabled (`*ReviewBlockedError` wrapping `ErrReviewBlocked`) with `"Choose how merges"`, and pressing **Keep** or the header blocker jumps straight to that change. - **In-place YAML editing and live viewport preview (`BeginReviewYAMLEdit`, `SetReviewYAMLDraft`, `FinishReviewYAMLEdit`)**: clicking **Edit** on any non-reverted added or changed scene object makes the right-hand YAML pane editable in place without losing text-input focus or firing single-letter Review shortcuts while typing. Drafts are bounded (256 KiB), strictly decoded with `KnownFields(true)`, checked for duplicate keys and `sceneformat.Validate` (and component registry rules), and checked against You-only boundaries. Valid edits update the Review viewport live (`ReviewEffectiveSceneDoc`) and tag hand-edited lines `you`. - **Parse errors, mechanical one-step fixes, and Undo my typing (`ApplyReviewYAMLFix`, `UndoReviewYAMLTyping`)**: invalid YAML (such as typing `x 444` without a colon) marks the failing scene line, surfaces `"Fix YAML on line N"` in the header blocker and `"Line N isn't valid YAML"` in the alert card, disables **Done** (`ErrReviewYAMLInvalid`) and **Keep**, offers verified one-step fixes when the parser names what is missing (**Add the colon**, **Close the quote**, **Add the closing brace**, **Add the closing bracket**, **Replace tabs with spaces**), and always provides **Undo my typing**. - **Single undo step and round-2 MCP visibility**: conflict merge choices and valid hand edits land with the turn in **one `Editor.History` step** (`KeepTurnReview`)—one `Undo` reverts the agent turn, merge choice, and hand edit together while preserving any concurrent manual edits made outside the review—and remain readable through `editormcp`'s `review_status` tool (`Editor.ReviewStatus`) tagged `"you"` for round 2. ## System notifications, Dock badge, and Play-mode dot for agent tasks (#1023) Agent tasks (both background tasks managed via `tasks.go` / #1022 and foreground Agent panel runs) reach the person outside the editor through NSGo's native notification and badge APIs (`core.Scope.ShowNotification`, `core.Scope.RequestNotificationPermission`, `core.Scope.OnNotificationPress`, and `core.Scope.SetBadge`), matching `design/editor/Tasks.dc.html`, `design/editor/AgentStates.dc.html`, and `design/editor/Spec.dc.html` using exclusively Spec design tokens: - **Only three events notify**: **waiting for permission** (`TaskNeedsYou`), **ready to review** (`TaskReadyToReview`), and **failed** (`TaskFailed`), formatted with `"NSGo Editor · "`, the task title, detail, and primary action (`Allow once`, `Review`, or `Open`) with control-character sanitization and length bounds. Finished steps, queued starts, restored thread entries on load, and agent replies never send system notifications. - **Permission on first need and 30 s rule**: `cx.RequestNotificationPermission` is called only the first time a notification is actually needed (preserving macOS Dock badges before any notification permission check). When the editor window is in the background (`cx.Env().Lifecycle() != core.LifecycleActive`), all three events notify immediately; in the foreground, an unanswered waiting request notifies after `AgentWaitingNotifyDelay` (`30 s`) unless answered first. - **Click opens the task in its scene**: `cx.OnNotificationPress` (delegating to `Editor.HandleNotificationPress` / `Editor.OpenAgentTask`) brings the editor window to the front (also calling `Editor.OnFocusWindow` when set), stops Play if running, dismisses obstructing panels (Settings, History, Problem agent panel, Ask-in-place, Assets mode), switches to or safely opens the task's scene tab strictly confined inside the project root (refusing traversal and symlink escapes), opens the Tasks or Agent panel, and focuses the task and any open request card. - **Dock badge (`cx.SetBadge`)**: `Editor.AgentDockBadgeCount` counts waiting (`TaskNeedsYou`), ready to review (`TaskReadyToReview`), and failed (`TaskFailed`) tasks (`AgentTaskCounts.BadgeCount()`); running and queued tasks never add to the badge, and `0` clears it (including on scope cleanup). - **Play-mode corner dot and deferred notifications (`PlayTaskDotView`)**: while Play mode is active (`Editor.Playing()`), agent task notifications do not pop over the running game and are held (`Editor.HeldAgentNotifications`) until `Editor.Stop()` flushes any tasks still needing attention. A single 8 pt dot with a 3 pt halo stays stably mounted in the top-right corner of the viewport in the Spec color of the most urgent state (**Failed** `Removed.Fg` > **Waiting** `Warning.Fg` > **Ready to review** `Accent.Fg`), revealing its label pill (such as `"1 task needs you · stop Play to open"`) only on hover or keyboard focus. ## Live agent edits in the viewport and scene tree (#1013) While an agent edits a scene through `editormcp` or an active agent turn (`Editor.BeginAgentTurn` / `Editor.RunAsAgent`), the editor shows its pending changes live in both the viewport and scene tree (`design/editor/Working.dc.html`, `Main.dc.html`, and `Spec.dc.html`) without ever moving the 2D or 3D viewport camera on the agent's behalf: - **Live viewport overlays (`ViewportLiveOverlays` / `VisibleViewportLiveOverlays`)**: - **Added**: 1.5 px dashed green outline (`theme.Palette.Added`) and `"+ "` mono pill. - **Changed**: 1.5 px dashed amber outline (`theme.Palette.Changed`) and `" → "` mono pill (also synced into the Inspector's amber review markers). - **Removed**: 25% grey ghost at the object's pre-turn bounds, 1.5 px solid red outline (`theme.Palette.Removed`), and a `" removed"` pill with the object's name struck through. - **Agent working**: 1.5 px solid pulsing violet outline (`theme.Palette.Agent`, 1.6 s pulse between 45% and 100% opacity, held solid at 100% under reduced motion) with no resize handles and a pill carrying the violet sparkle glyph and activity text (for example `playing level_01 headless`). - **Problem**: 2 px solid red outline and filled alert pill for object-scoped diagnostics. - Non-overlapping pill placement automatically stacks colliding pills vertically so adjacent objects stay readable. - **Selection coexistence and read-only step guard**: when the user selects an object the agent is actively touching (`Editor.BeginAgentStep` / `editormcp.Server.BeginStep`), the selection keeps its resize/transform handles and the agent outline sits 3 px further out (`OutsetPx: 6`). Until the agent's step moves on (`EndAgentStep`), manual edits to that object are refused with `ErrAgentTouchingObject` across the viewport, 2D/3D gizmos, inspector (which shows a violet read-only banner), scene tree (rename and reparent), context menu, and direct `Editor` mutation methods, while untouched objects remain freely editable. - **Scene tree markers**: added nodes show a `NEW` badge, changed nodes show a `MOD` badge, removed nodes remain visible as struck-through ghost rows with a `DEL` badge, and currently touched nodes display a violet agent-working dot until **Keep** or **Revert**. - **Header pill**: follows the agent's state (`Editor.SetAgentState` / `Editor.AgentState`): violet working pill (`"Agent is · manual edits stay available"`), warning waiting pill (`"Waiting for you · "`), pending-review pill with **Keep** (`KeepAgentTurn`, collapsing the turn into one undo step) and **Revert** (`RevertAgentTurn`, undoing the turn and restoring removed objects), and hidden while idle. - **Interactive top-left Overlay Legend**: appears automatically whenever live overlays are active (or when `OverlayLegendOpen` is true). Each row (**Selection**, **Agent working**, **Added**, **Changed**, **Removed**, **Problem**) is a `RoleSwitch` toggle (`ToggleOverlayLegendKind` / `SetOverlayLegendKind`) persisted per-user in `EditorSettings.HiddenOverlayKinds` (`hiddenOverlayKinds` in `editor.yaml`, schema `editor-settings.v1.json`) without modifying project files. ## Agent threads per line of work, grouped by scene (#1019) The right rail (`RightRailView`) switches between **Agent** (`AgentPanelView` / `AgentThreadsView`), **Inspector** (`InspectorView`, the default tab), and **History** (`AgentHistoryView`), using `design/editor/Spec.dc.html` tokens matching `Threads.dc.html` across Dark and Light appearances: - **One YAML file per thread under `.nsgo/threads/` (`AgentThread`, `AgentThreadFileVersion = 1`)**: each thread is persisted as a strict versioned YAML document at `.nsgo/threads/.yaml` (with `.nsgo/.gitignore` automatically ignoring the directory from git), storing `id`, `title` (named from its first request), `scenePath`, external agent `sessionId` (`SetAgentThreadSessionID`), timestamps, and chronological `requests` with `steps`, `outcome` (`pending`, `kept`, `reverted`), change counts, changed `objects`, and `historyStep` links. Parsed with `ParseAgentThreadYAML` and written canonically with `EncodeAgentThreadYAML` (JSON Schema `https://nsgo.games/schemas/agent-thread.v1.json`). - **Grouped thread switcher, search, and `⌘N` (`AgentThreadGroups`, `CmdNewAgentThread`)**: the switcher groups threads under ` · OPEN SCENE`, other scenes (``), and `PROJECT · NO SCENE`, each showing relative age and state (`now · 3 changes to review`, `1 h ago · kept 5 of 6`, `yesterday · reverted`, or changed files). Opening or switching scenes enters that scene's most recent thread (or a fresh draft) and never carries another scene's thread along; while the **Agent** tab is active, `mod+n` / `⌘N` (`ScopeAgent`) starts a new empty thread instead of `File > New Project...`. - **Folded earlier requests, History link, and Jump to latest**: earlier reviewed requests fold to one line each (`N EARLIER REQUESTS`) and expand on click to show the full prompt, changed fields, steps, and **Open this step in History** (`OpenHistoryStep`), which opens the unified History timeline highlighted on that step. Expanding an earlier request surfaces a floating **Jump to latest** pill (`JumpToLatestAgentRequest`). - **Empty-thread view (`AgentAlwaysReadItems`, `AgentBriefSuggestions`)**: an empty thread lists what the agent reads with every request (` · whole scene`, `brief.yaml`, `AGENTS.md`, `Viewport image`) and up to three starter prompts read safely from the project's `brief.yaml` (`FROM YOUR BRIEF`). - **Inspector footer attribution (`LastAgentChangeForObject`, `OpenAgentRequest`)**: when a selected object was changed by a non-reverted agent request (via `SendAgentRequestWith`, `RecordAgentStep`, or `editormcp`'s `scene_edit`), the Inspector footer displays `Changed in “” · ` and clicking it opens that thread and expands that request. ## Viewport sketch layer for the agent (#1025) Draw session-only numbered annotations directly over the 2D viewport to point at empty places in a level before asking the agent to build them (`design/editor/Sketch.dc.html`, styled exclusively with `design/editor/Spec.dc.html` tokens): - **Four sketch tools in scene coordinates**: press `D` (`CmdSketchToggle`, or `View > Sketch`) to toggle Sketch mode without adding extra buttons to the compact 2D `editor-toolbar`. Switch between **Pen** (`P`, freehand polyline), **Arrow** (`A`, start → end), **Box** (`B`, rect), and **Text** (`T`, point + label) in `ScopeSketch`, or place a mark at the cursor with `I` (`CmdSketchAddMarkAtCursor`). Every mark gets a sequential numbered badge (`1`, `2`, `3`, …) and an optional label (such as `"3 spikes"`, `"platform, back and forth"`, `"locked until the lever"`). All geometry is converted through `CanvasToWorld` and stored strictly in scene coordinates so marks scale and pan accurately across zoom levels and are **never** written into `SceneDoc`, `*.scene.yaml`, or scene undo `History`. - **Sketch bar, Scene Tree row, and status bar**: the floating sketch bar displays the four tools, **Undo last mark** (`⌘Z` in `ScopeSketch`), **Hide / Show marks** (`H`), `"N marks not saved"`, **Clear**, and **Done**. Pressing `Esc` finishes sketch mode while keeping drawn marks until sent, cleared, or kept. The Scene Tree displays a compact `SKETCH LAYER` row (`N marks · not saved`), and the status bar shows live scene coordinates and the active sketch tool. - **Sending a sketch to the agent (`SendSketch` / `Editor.OnSendSketch`)**: the composer attaches a `"Sketch · N marks"` context chip (clicking toggles a `"Sent with this request"` scene-coordinate preview). Sending delivers `SketchAgentRequest` with structured marks (`number`, `kind`, geometry in scene coordinates, `label`) and a rendered PNG of the viewport with numbered marks overlaid (`RenderSketchViewportPNG`). - **Agent reading card & `scene_edit` confirmation hold**: sending a sketch arms a hold gate (`SketchHoldActive() == true`) that causes `scene_edit` and other mutating scene MCP tools to refuse edits until the person confirms. The agent reads marks via `sketch_read` and posts its restatement (`"I read your sketch as: …"` with numbered items and assumptions) via `sketch_reading` (`PostSketchReading`). Clicking **Go ahead** (`ApproveSketchReading`, `⌘↵`) releases the hold; clicking **Correct a mark** (`CorrectSketchMark`, `⇧M`, or clicking any numbered item) reopens sketch mode with that exact mark selected while keeping the hold active; replying in words (`ReplyToSketchReading`) works too. - **Review overlay & Keep / Revert**: after approval, agent edits open a review card (`SketchReviewOpen`) with a **Sketch overlay** toggle (`O`, `ToggleSketchReviewOverlay`, also available in `TileReview`) that lays the faint dotted sketch over the result. **Keep** (`KeepSketchReview` / `KeepTileReview`) keeps the edits and clears the sketch layer; **Revert** (`RevertSketchReview` / `RevertAllTileReview`) undoes the edits while keeping the sketch marks intact to send again. ## Reference images in the agent composer and pinning to the brief (#1027) Attach PNG, JPEG, or WebP reference images to a single agent request or pin them to the project's game brief, matching `design/editor/Sketch.dc.html` (*Paste or drop an image*, *Pin to brief*) using exclusively `design/editor/Spec.dc.html` tokens: - **Drop, paste, or pick PNG, JPEG, and WebP**: dragging files over the Agent composer shows the Spec-styled **"Drop to attach"** overlay (`SetAgentComposerDragOver`, `DropAgentReferenceFiles`); pasting an image or image files into the composer (`HandleAgentComposerPaste` via `core.Input.OnPaste`, or `PasteAgentReferenceImage`) or clicking the **Attach an image** button (`PickAndAttachAgentReferenceImages` / `CmdAttachReferenceImage`) validates actual PNG, JPEG, or WebP headers and pixels in memory (`DecodeAgentReferenceImage`). Unsupported file types (such as GIF, SVG, BMP, text, or corrupted images) are refused with the exact reason in an accessible error banner (`AgentAttachError`). - **One-shot chips with hover preview**: each attached image appears as a chip with a thumbnail, filename, **Pin to brief** button, and **×** remove button (`RemoveAgentReferenceImage`). Hovering or focusing a chip displays a floating preview card above the composer with the decoded image, format, dimensions, and scope (`Sent with this request only`). Submitting a request (`SubmitAgentPrompt`) delivers attached images in `AgentRequest.AttachedImages` and `AgentRequest.Images` (and records thumbnails on `AgentTurn.Images`), then clears the one-shot chips so the next request does not carry them. - **Pin to brief (`PinAgentReferenceImage`)**: clicking **Pin to brief** copies the image to `art/reference/` (disambiguating collisions without overwriting different files) and adds an entry under `art.references` in `brief.yaml` via YAML AST editing (preserving existing keys and comments) as **one atomic, undoable `Editor.History` step**. Both files immediately appear in Review / Changes (`RefreshChanges`), a confirmation card displays the `+` YAML diff with an **Undo** button (`UndoLastBriefPin`), and a single Undo removes both the copied file and the YAML line (or deletes a freshly created `brief.yaml` and empty `art/reference/` folder). - **Always chip (`brief.yaml`)**: whenever `brief.yaml` exists, the composer shows the **Always** row with a locked `brief.yaml` chip (showing the pinned reference count when non-zero). Hovering or pressing the chip previews every pinned reference image, and every subsequent agent request automatically includes those images via `AgentRequest.BriefImages` and `AgentRequest.Images`. ## Agent turns: multi-file pending changes as one undo step (#1011) Every edit an agent makes through the editor's MCP server between the start and end of one request (started from the Agent panel or opened via `turn_start` and closed via `turn_end`) accumulates into **one pending agent turn** across every file it touches—scenes, prefabs, data tables, `game.yaml`, and animation clips: - **Live in memory, zero disk writes until Keep + Save**: edits apply in memory immediately so the viewport, scene tree, inspector, and `scene_read` show them live (`Editor.StagedFileYAML`), while nothing is written to disk until the person keeps the turn and saves. Saving (`Save` / `SaveAll`) refuses while a turn is still pending, and autosave pauses while a turn is open. - **Derived structural diff with `why`**: rather than logging raw commands, the editor structurally diffs each touched file between its pre-turn state and its current state (per object ID and field/component/property/layer/parent for scenes and prefabs, per record for data tables, per dotted key for `game.yaml`, per header/track/event for clips). Each derived `AgentTurnChange` carries `Kind` (`added`, `changed`, `removed`), `Title`, concise `Detail` (such as `z 10 → 12`), `File`, 1-based YAML `Line`, optional `Why` reason (from MCP edit tools' `why` argument), and `Reverted` flag, alongside exact per-file `+added −removed` line counts. - **Per-change and per-file Revert / Restore while pending**: while a turn is pending or stopped (`⌘.` / `CmdStopAgentTurn`), the person can revert or restore any individual change (`RevertAgentTurnChange` / `RestoreAgentTurnChange` / `ToggleAgentTurnChange`) or every change in a file (`RevertAgentTurnFile` / `RestoreAgentTurnFile`). Reverted changes leave in-memory state immediately and return cleanly on restore, leaving untouched edits (including concurrent person edits on other objects) intact. - **Keep and Revert as one Undo step + Spec toast**: - **Keep** (`KeepAgentTurn` / `⌘↵` / `CmdKeepAgentTurn`) commits all remaining changes across every touched file as **one** `Editor.History` command tagged `AuthorAgent` / `HistoryAuthorAgent` (`History.Entries()`, `History.UndoAuthor()`, `History.RedoAuthor()`). One `⌘Z` restores every touched file byte-for-byte, and `⇧⌘Z` redoes the entire kept turn. A Spec `ToastSuccess` appears with an **Undo (`⌘Z`)** action. - **Revert** (`RevertAgentTurn` / `⌘⌫` / `CmdRevertAgentTurn`) restores every touched file to its exact pre-request state and shows a Spec `ToastInfo` whose **Undo** action (`UndoRevertAgentTurn`) brings the turn back as pending. - **Checkpoints `⌘Z` rules**: while the agent is actively working (`AgentTurnWorking`), `⌘Z` undoes only the person's own edits; inside an open review (`AgentTurnReviewOpen`), `⌘Z` undoes the person's edits made inside the review first and then reverts the review; once kept or idle, `⌘Z` undoes the ordinary history stack. - **Right-panel Agent tab & Summary Card (`RightRailView` / `AgentPanelView`)**: switch between **Agent** (`mod+1` / `CmdAgentTab`) and **Inspector** (`mod+2` / `CmdInspectorTab`) in the right panel header (showing a live pending indicator dot and MCP connection status). Styled exclusively with `Spec.dc.html` tokens matching `Main.dc.html` (localized in English and Chinese), the Agent panel displays the request bubble, progress steps, working **Stop (`⌘.`)** control, completion summary, the small summary card (`"6 changes · 1 file · +38 −0"`, grouped changes with per-change and per-file Revert/Restore, **Keep**, **Review**, **Revert**), Kept/Reverted notes (`"one undo step (⌘Z)"`), and the composer with `"Edits stay unsaved until you keep them"`. - **Navigation, close, and boundary protection**: opening another scene (`RequestOpenScene`), switching scene tabs (`RequestSelectTab`), switching projects (`RequestOpenProject`), closing the window, or quitting with a pending turn prompts **Keep**, **Revert**, or **Cancel** (`pendingTurnDialog`), matching unsaved-changes behavior. Every staged file enforces project-root symlink containment, refuses `.git/**` and You-only files, enforces a 2 MiB per-file limit, and resets cleanly on `OpenProject` and `OpenDemo`. - **MCP surface (`editormcp`)**: `turn_start`, `turn_end`, `turn_status` (read-only, reporting reverted changes), and `file_edit` (validating `game.yaml`, data tables, clips, prefabs, and scenes in memory) work alongside `scene_edit` and `object_set_field`'s `why` support. By design there is no MCP tool that keeps or reverts a turn. ## Agent panel failure, recovery, and offline states (#1024) When an agent request does not simply succeed, `AgentPanelView` renders dedicated `design/editor/AgentStates.dc.html` cards using exclusively `theme.Palette` tokens (both Dark and Light themes) while keeping every manual editing tool (Select, Move, Inspector, `CheckProblems`, and Play) working in every state: - **Partial (`AgentPartialState`)**: displays `"Done N of M · couldn't place "` with the explanation, **Keep these** (keeps partial edits as undoable changes), **Let me point** (`ToggleAgentPointing`, clicking in the 2D viewport picks world coordinates via `PickAgentPointWorld` and `Esc` cancels cleanly), **Try another way** (`TryAnotherWayAgentTurn`), and a change-count review strip (`N changes · 1 file | +X −Y | Review`). - **Stuck (`AgentStuckState`)**: when the same MCP tool (such as `scene_edit`) fails three times in a row (`AgentStuckFailureThreshold = 3`), the editor pauses/cancels the active request instead of guessing again, transitions the header chip to `Waiting for you`, lists all three refused calls with their errors in a recessed monospace log, and offers a **Hint for the agent** input with **Continue with hint** (`ContinueAgentWithHint`) or **Stop here** (`StopStuckAgentTurn`, leaving the scene and disk untouched since refused edits never mutate files). - **Lost (`AgentLostState`)**: when an MCP client disconnects or a model API fails mid-request, completed steps stay intact in an unkept `AgentTurnReview`, the interrupted step is marked `"cut off, nothing written"` with no partly written file on disk, and the card states when and at which step it failed alongside **Reconnect**, **Review N changes**, and **Troubleshoot** (or **Retry now** and fallback switching such as **Use Claude Code** for model errors like 529 overloaded). After reconnecting, the agent asks before picking up at the next step (`ConfirmResumeLostAgentTurn` / `DismissResumeLostAgentTurn`) instead of auto-resuming. - **Stopped (`AgentStoppedState`)**: stopping a running turn records `DONE` and `NOT DONE` step sections, **Resume** (`ResumeAgentTurn`, which starts strictly at the first not-done step and skips steps already done), and **Review N changes**; completed changes stay unkept until explicitly reviewed and kept. - **Mismatch (`AgentMismatchReport`)**: the editor automatically checks every turn summary against the actual diff (`CheckAgentSummaryAgainstDiff`) and displays a `WHAT · SUMMARY · REVIEW` table when they disagree, including the auto-derived reason when known (for example, an object added at step 3 and removed at step 5), **Ask why** (`AskAgentWhyMismatch`), and **Open review** (`OpenAgentTurnReview`). **Keep** always applies the actual review diff, never the prose summary. - **Offline (`AgentStatusOffline`, `SetAgentOffline`)**: displays `"You're offline"` and queues submitted requests with timestamps (`AgentQueuedRequests`, `QueueAgentRequest`, `RemoveQueuedAgentRequest`) while Select, Move, the Inspector, game check, and Play keep working. Returning online never runs queued requests on its own; each queued request waits for an explicit **Send** (`SendQueuedAgentRequest`). ## Spec viewport overlays and toggle legend (#1006) Every semantic overlay drawn over the 2D and 3D viewports passes through one shared helper (`DrawObjectOverlay`) using exclusively `theme.Palette` tokens (`design/editor/Spec.dc.html`, "Overlay legend"), with a non-color second cue (corner handles, pill glyph/prefix, ghost fill, strikethrough, or filled alert badge) so every kind remains distinguishable in greyscale: | Kind (`OverlayKind`) | Token & line style | Second cue | | --- | --- | --- | | **Selection** (`selection`) | `Accent`, 1.5 px solid | Four 8×8 corner handles and an accent name tag (person's selection only) | | **Agent working** (`agent`) | `Agent`, 1.5 px solid, no handles | Pulsing 1.6 s between 100% and 45%, dark pill with 4-point agent glyph (or numbered task badge) saying what the agent is doing | | **Added** (`added`) | `Added`, 1.5 px dashed | Dark pill labelled `"+ "` | | **Changed** (`changed`) | `Changed`, 1.5 px dashed | Dark pill showing field, old, and new value (for example `"z 10 → 12"`) | | **Removed** (`removed`) | `Removed`, 1.5 px solid | 25% grey ghost fill and dark pill with struck-through object name + `"removed"` | | **Problem** (`problem`) | `Problem`, 2 px solid on the live object | Filled pill (`Problem.Fg` / `Problem.OnFill`) with alert triangle icon and message; never resembles a removed ghost | | **Focused change in Review** (`focused`) | Base change kind's own color and dash at 2.5 px (never `Accent`) | Bright outlined pill matching the change kind | - **Pairing, motion, and reduced motion**: When **Selection** and **Agent working** sit on the same object (`PairedWithSelection`), Selection keeps its four corner handles and the Agent outline sits 3 px further out (`OverlaySelectionAgentGap`) with its pill stacked above. Added, Changed, and Removed overlays fade in over 240 ms (`OverlayChangeFadeDuration` / `OverlayFadeAlpha`), and active Agent working outlines pulse on a 1.6 s cycle (`OverlayAgentPulsePeriod` / `OverlayAgentPulseAlpha`). With reduced motion enabled (`core.Environment.ReduceMotion` or `Editor.SetReduceMotion(true)`), change overlays appear immediately at 100% and Agent outlines stay solid at 100% with no animation timer running. - **Top-left toggle legend (`viewport-overlay-legend`)**: Every edit-mode viewport (both 2D and 3D) mounts the same top-left legend card (`viewportOverlayLegendView`) with six accessible `role="switch"` rows (**Selection**, **Agent working**, **Added**, **Changed**, **Removed**, **Problem**), each showing its drawn line style and second cue. Toggling any row (`Editor.ToggleOverlayKind`, `Editor.SetOverlayKindVisible`, `Editor.SetOverlayLegendKinds`) hides or shows that kind across all viewports immediately and persists `overlayLegend` in the per-user `EditorSettings` YAML file (`Editor.SettingsPath`, outside the project, never modifying project or scene files). - **Live scene overlay API and Problems object attribution**: Live agent edits, reviews, and plans attach overlays to objects (or removed ghost bounds) via `Editor.SetSceneOverlays`, `AddSceneOverlay`, `RemoveSceneOverlay`, and `ClearSceneOverlays` (`SceneOverlayEntry`). `assetcheck.Problem` now carries `Object` (also returned by `editormcp`'s `game_check`) for scene object, component, override, and connection diagnostics so Problems naming a live object in the open scene automatically draw the Spec **Problem** overlay on that object in both 2D and 3D viewports. - **Neutral viewport guides**: The camera frame, camera bounds, camera tether, tile grid, and snap grid use neutral `theme.Palette` tokens (`TextMuted` / `TextFaint` 1 px hairline and `2, 4` dotted lines) that no semantic legend kind uses. ## Agent composer: @-mentions, context chips, and context meter (#1020) Inside the unified right-rail **Agent** tab (`RightRailView` / `AgentPanelView`, switchable with `⌘1` / `⌘2` via `CmdAgentTab` / `CmdInspectorTab`), `AgentComposerView` (`design/editor/Threads.dc.html`, styled strictly with `Spec.dc.html` tokens) adds `@`-mentions, explicit context chips, exact hover previews, and a live context meter: - **`@`-mention picker over the project search index**: typing `@` in the composer opens a live picker backed by `search.go` (`ensureProjectIndex`), `Editor.Problems`, `PlaytestSession` / `AddComposerPlaytestRun`, and `Editor.History`, showing a match count and 8 groups (**Objects**, **Files**, **Prefabs**, **Assets**, **Problems**, **Playtest runs**, **History steps**, **Rules**) with 9 tabs (**All** plus each group). Navigate with `↑` / `↓` (`MoveMentionSelection`), add with `↵` (`AcceptActiveMention`), cycle groups with `Tab` / `Shift+Tab` (`CycleMentionPickerGroup`), and close with `Esc` (`CloseMentionPicker`). Already-attached items are filtered out. - **Context chips and exact hover preview**: above the composer, attached chips show what joins the request (removable by clicking `×` via `RemoveComposerChip` or pressing `⌫` in an empty composer via `RemoveLastComposerChip`), **Always** chips show `brief.yaml` and `AGENTS.md` when present in the project root, and **Viewport image** is a toggleable chip (`SetViewportImageIncluded` / `ToggleViewportImage`). Selecting an object in the viewport or scene tree only surfaces a dashed `+ · selected` suggestion chip (`SuggestedChip`)—nothing joins the request unless explicitly added (`AcceptSuggestedChip`). `TriggerAskAgentShortcut` attaches the selected object or, when nothing is selected, the whole open scene (`AttachWholeSceneChip`) and focuses the composer. Hovering any chip (`SetHoveredChip` / `HoveredChipPayload`) displays the exact header (`# level_01.scene.yaml · lines 72–78`) and YAML text or image bytes resolved by `ResolveChipPayload`. - **Single-source request assembly and runner delivery (`RenderAgentModelInput`, #1742)**: `AssembleAgentRequest` builds `AgentRequest` from the active chips and nothing else—calling the exact same `ResolveChipPayload` function used on hover—and feeds both `SendComposerPrompt` (`Editor.OnSendAgentComposerRequest`) and `SubmitAgentPrompt` (`Editor.AgentRunner`). Every production runner renders `AgentRequest` through `RenderAgentModelInput` so the chips previewed on hover reach the model verbatim: - **Claude Code (`CLIAgentRunner`)**: sends **Always** chips (`brief.yaml`, `AGENTS.md`) via `--append-system-prompt`, sends the per-turn context block (compacted/seed summary, explicitly attached chips, viewport header) followed by the prompt after `--`, and materializes the viewport PNG and any ephemeral reference images into a private temporary directory listed under `Reference images:` and cleaned up when the run exits. - **Codex (`CLIAgentRunner`)**: sends the full combined context block (Always chips, compacted/seed summary, attached chips, viewport header) followed by the prompt after `--`, passing validated project image paths and the materialized viewport PNG via `-i ` on fresh `codex exec` runs and listing them under `Reference images:` on `codex exec resume`. - **Built-in Anthropic API runner**: puts the `editormcp.Server` instructions (via `AgentToolInstructionsProvider`) and **Always** chips in the `system` prompt, sends the per-turn context block and prompt alongside base64 `image` blocks for reference images, attached image-asset chips, and the viewport PNG (honoring `PrivacyViewportImages`), and keeps a bounded per-thread conversation history (`user` / `assistant` turns with tool calls/results and earlier base64 images stripped) that carries follow-up turns, truncates/restores with Rewind/Redo, and drops cleanly on **Compact thread** or **Start fresh with summary**. - **Context meter ring, breakdown, Compact, and Start fresh**: a 20×20 circular progress ring reflects reported token usage (`SetAgentTokenUsage` or `AgentResponse.Usage`) across three Spec states (normal `≤ 70%`, amber warning `71–89%`, and critical `≥ 90%` `"compact now"`). Clicking the ring opens a 6-row breakdown (**Conversation**, **Open scene**, **Attached**, **Always**, **Tools and instructions**, **Viewport image**) with **Compact thread** (`CompactAgentThread`, folding earlier requests into a summary while keeping the last request whole and dropping the ring) and **Start fresh with summary** (`StartFreshAgentThread`, opening a new thread seeded with that summary). ## AI-first main layout (#1007) The editor's main window (`main_layout_ui.go`, `ui.go`, `agent_ui.go`, `overlays_ui.go`, `scenetree.go`) implements the AI-first workspace from `design/editor/Main.dc.html` using exclusively `design/editor/Spec.dc.html` tokens, sizing, and accessible controls: - **44 px header (`mainHeaderView`)**: displays the ` / ` breadcrumb (`ProjectDisplayName`, `SceneBreadcrumbName`) with a Scene file menu and unsaved dot (`aria-label: "unsaved changes"` / `"save failed"`), a centered tool `base.RadioGroup` (`Select V`, `Move W`, `Rotate E`, `Scale R`, `Pan Space` as icon-only Lucide 1.8 px@15 px `currentColor` icons with `"Label · key"` tooltips), a `2D / 3D` segmented radio group, `History (⌘Y)` icon button, `Search ⌘K` palette button, and `Play (⌘P)` as the single primary button. - **232 px left rail (`leftRailSceneView`)**: combines the `Scene / Assets` switcher with `SCENE · N nodes` (`SceneNodeCount`), a quick filter toggle (`SceneTreeFilter` / `SetSceneTreeFilter` / `SetSceneTreeFilterOpen`) that narrows the scene tree by name, ID, or kind with auto-expanded ancestors, a quick-add `+` menu (`AddSceneRailObject` for empty object, trigger, or light and `AddSceneRailLayer`, all undoable through `History`), scene tree rows carrying kind color dots (`ObjectKindColor`), kind tags (`SceneRailObjectKind`, `LayerKindLabel`), and `NEW` badges on pending-review proposed objects (`IsObjectProposedNew`, `SetProposedNewObjectIDs`) with ellipsis-safe layout so visibility/lock buttons never clip, and a bottom `FILES` section listing the open scene, prefabs/instanced scenes it uses (`SceneUsedPrefabs`), and `game.yaml`. Picking a scene tree row switches the right rail to **Inspector**. - **Viewport dot grid, non-sprite markers, caption, bottom bar, and overlay legend**: in 2D edit mode, `DrawViewport` draws the neutral Spec 16×16 dot-grid surround (`theme.Palette.ViewportDot`) when no scene background color is set and neutral Spec-token markers for visible non-sprite objects so empty nodes, prefabs without sprites, and triggers stay legible and clickable without colliding with semantic overlay legend hues. `viewportCameraCaptionView` subscribes to `Editor.SubscribeCanvasSize` (`CanvasSizeRevision`) so `Camera · W × H` tracks the camera frame on first layout and every resize and avoids the top-left overlay legend, paired with the bottom bar (`Zoom out`, zoom `%`, `Zoom in`, `Snap` as a `base.Switch` with `RoleSwitch` / `aria-checked`, `Fit`, and `Overlays N`). - **Command Palette (`⌘K`, `PaletteItems`, `ExecutePaletteItem`)**: searches built-in/custom/plugin commands, plugin tools and panels, project scenes and files, **open-scene nodes** (`node:`, selecting, switching to Inspector, and framing the object), and **Settings pages** (`setting:`), with prefix scopes (`>` commands, `@` nodes, `#` files), empty-query **Recent** history (`PaletteRecent`), and an **Ask the agent** entry (`ask:`) that stages natural-language queries directly in the Agent composer. - **380 px right panel (`RightRailView`)**: hosts the `Agent` (`⌘1`) and `Inspector` (`⌘2`) radio tabs alongside the thread History toggle and live agent connection chip (`Connected · MCP`, `Working`, `Waiting for you`, `Reconnecting`, `Disconnected`); choosing a tree row switches directly to **Inspector**. - **32 px status bar (`mainStatusBarView`)**: renders muted text on `bg` with the active layer button (toggling Layers), live 2D pointer coordinates, current tool readout, problem count pill (opening Problems), Output, and Debugger. Secondary views previously hosted on the old toolbar (Settings, Audio Mixer, Input Map, Localization/Strings, Export, Library, Data Table, Project Search, Files, Assets, Animation, Particles, Material, HUD Layout, Terrain, NavMesh) remain reachable through the Command Palette (`⌘K`), Menu bar, Settings, and Status bar. - **Designed empty, loading, and error states (`WorkspaceState`, `SceneOpenError`)**: every region renders a dedicated state for `WorkspaceNoProject`, `WorkspaceNoScene`, `WorkspaceLoading` (`SetProjectLoading`), and `WorkspaceSceneError` (`SceneOpenError`, `RetryOpenScene`, `ClearSceneOpenError`). Opening a missing or malformed scene YAML renders an alert card with file path, line/column, message, fix guidance, **Retry**, and **Dismiss** instead of a blank viewport. - **Spec controls and keyboard navigation**: preserves Spec heights (`28 px` rows/tool buttons, `30–32 px` buttons, `44 px` header, `32 px` status bar, no interactive hit area under `28 × 28`), spacing (`4 / 8 / 12 / 16 / 24`), radii (`6 / 8`), `base.RadioGroup` / `base.Radio` and `base.Switch` semantics, 2 px Spec focus rings, accessible names, and `F6` cycling across all five regions (`Header`, `Scene tree`, `Viewport`, `Agent / Inspector`, `Status bar`). ## Agent panel live steps, permission cards, and Stop (#1012) The **Agent** panel (`AgentPanelView` inside `RightRailView`, `⌘1` / `⌘2`) streams live progress, interactive permission cards, follow-up instructions, and global Stop cancellation using `design/editor/Spec.dc.html` tokens (`Working.dc.html`, `Permissions.dc.html`, `Main.dc.html`, `AgentStates.dc.html`) on top of the project's `permissions.yaml` rules and You-only boundaries: - **Live steps and `agent_report_step`**: starting a request (`Editor.StartAgentRequest` or `Editor.SubmitAgentPrompt`) immediately renders a gray placeholder step (within 300 ms). As `editormcp.Server` executes tool calls, each step streams in plain words with a violet spinner on the single active step and a green check once done. Agents can also call `agent_report_step` (`text`, optional `objects`, optional `status`) to report steps in their own words, name touched scene object IDs, and receive queued `"Add to this request"` follow-ups. - **Interactive permission cards over `permissions.yaml`**: when a tool call evaluates to `ask` against `permissions.yaml` (after You-only boundary enforcement), `editormcp.Server` pauses that call on its goroutine without blocking the editor UI and renders an `alertdialog` permission card (`LiveRegionPolite`) in the Agent panel showing the title, why the agent wants it, its effect (such as *"Nothing is saved."*), the rule preview and source, and **Allow once**, **Always**, and **Deny**. - **Focus and keyboard rules (Spec rules 02, 04, 05)**: a permission card never steals focus unless focus is already inside the Agent panel (`Editor.ShouldFocusAgentPrompt`); clicking the header **Waiting for you** chip focuses it on demand. While focused, `⌘↵` allows once, `⌥↵` persists an **Always** rule to `permissions.yaml` via `Editor.ApproveAlwaysPermission` (with the **Always permission rule saved** toast offering **Show** and **Undo**) so future identical calls run without asking, `⌘⌫` denies, `↑`/`↓` cycle buttons, and `Esc` leaves the card unanswered while the agent keeps waiting. - **No automatic retry after denial**: denying a permission card records its `(action, target)` key on the active request, renders *"You denied … · continued without it"* with an explicit **Allow now** action, notes the unchecked item in the turn's review summary (such as *"Not playtested"*), and immediately returns a structured non-fatal `denied` response for any repeated identical call in the same request without re-opening a card. Starting a new request clears per-request denials. - **Add to this request, Stop (`⌘.`), and concurrent manual editing**: while the agent works or waits, manual edits stay available and the bottom status bar reports what the agent is doing (*"manual edits stay available"*). The working footer keeps the **Add to this request** input focus-stable while steps stream (`Editor.AddToAgentRequest`). Pressing **Stop** or `⌘.` from anywhere—modal dialogs included—cancels the running request and any waiting Ask (`Editor.StopAgent`), keeps completed steps and scene edits pending for review (pausing autosave until kept or reverted), and shows the **Agent stopped** toast with **Review**; `Esc` never stops the agent. ## Dockable panels and layout (#919) `EditorView` builds the workspace on NSGo's `ui.DockArea`, turning the Scene tree, Layers, Asset Browser, Files, Library, Inspector (including the right-rail Agent, Sketch, Tasks, History, Problem Fix, and Tile Review views), Problems, Output, Profiler, Animation, States, Tileset, Terrain, 2D Rig, Particle Emitter, Material Editor, Scene Environment, Data Table, Search, 3D NavMesh, Localization, and every active plugin panel into dockable, resizable panels around the viewport (with `SceneTabsView` above the viewport canvas): - **Drag to resize, move, and tab**: drag any split or dock handle to resize panels, drag any panel tab into another group to tab them together or onto a group's edge to split beside it, and close panels from their tab close button (the `viewport` panel stays open). - **Show, hide, and reset from the menu**: open **View > Panels** to check or uncheck any built-in or active plugin panel (`PanelVisible`, `SetPanelVisible`, `TogglePanel`, `Panels`), or choose **View > Reset Layout** / **View > Panels > Reset Layout** (`CmdResetLayout`, `ResetLayout`) to restore the default arrangement. - **Per-user saved layout (`LayoutFile`, `ParseLayout`, `EncodeLayout`)**: layout changes persist automatically as strict versioned YAML outside any project under `/nsgo-game/layout.yaml` (`DefaultLayoutPath`, configured via `Editor.LayoutPath` / `Editor.SetLayoutPath` and wired automatically by `game editor` and `editorcmd`). Starting the editor again restores saved splits, tab groups, active tabs, sizes, and hidden panels, dropping any panel that no longer exists (for example from a removed plugin). - **Plugin panel placement**: plugin panels (`Plugin.Panels`) appear at their declared default `Dock` (`DockLeft`, `DockRight`, or `DockBottom`) on first use; once moved or tabbed elsewhere by the user, subsequent launches restore them at their moved position. ## Reviewing the agent's Go changes file by file (#1034) When an agent turn proposes Go edits alongside scene, prefab, or data YAML changes, the editor opens a dedicated file-by-file code review (`CodeReviewView`, matching `design/editor/ReviewCode.dc.html` and `Review.dc.html` with exclusively `theme.Palette` tokens in both Dark and Light appearances): - **Pending Go isolation and Go build overlay checks**: Go files proposed during a turn (`ProposeCodeReviewFiles` or `editormcp`'s `code_review_propose`) are held strictly in memory until confirmed and kept—until then, the project on disk and Play keep running the old code. `RunCodeReviewChecks` / `RunCodeReviewChecksAsync` builds a temporary Go build overlay JSON (`BuildGoOverlay`, mapping both cleaned and symlink-resolved project paths so macOS `/var` → `/private/var` works cleanly) and executes `go tool nsgo check ` and `go tool nsgo test -json -count=1` with `GOFLAGS=-overlay=` against the pending code without touching any project file on disk (injectable via `Editor.CodeReviewCheckRunner`). - **Split file list and Unified / Split diff**: the left sidebar splits into **PREFABS · IN KEEP** (YAML/prefab files included in Keep) and **GO · CONFIRM EACH FILE** (each Go file with `+n −n` line counts and a **Needs OK** / **OK** badge), above an explanation card (*"Why Go confirms on its own"*). Go diffs toggle between **Unified** (`u`) and **Split** (`s`) layouts with old and new line numbers, right-aligned line tags (`fails test`, `failed here`, `agent edited`, `round 2`), and **Open in ``** (`Editor.ExternalEditorName`, `OpenCodeReviewInExternalEditor` via `Editor.OnOpenSourceFile`, `Editor.OnOpenFileAtLine`, or the OS opener). - **Checks strip, failing test card, and Round 2 fixes in the same turn**: the live status strip (`RoleStatus` + `LiveRegionPolite`) shows `nsgo check`, `nsgo test` pass/fail counts, elapsed duration and package path, **Run again** (`r`), and live streaming progress (`"nsgo test running · M of N"` / `"Agent is fixing · nsgo test running · M of N"` with an `"Agent edited :"` badge). A failing test displays its name, `file:line` failure message, and the agent's explanation, with **Ask the agent to fix** (`AskAgentToFixCodeReview`, `Editor.OnAskCodeReviewFix`, keeping the fix inside the same turn as Round 2 and rerunning checks) and **Open the test** (`OpenCodeReviewTestFile`). - **Per-file confirmation, Keep, Waiting card, and single-step Undo**: **Confirm ``** (`ConfirmCodeReviewFile`) is disabled and refused with `ErrCodeReviewChecksNotPassed` until both `nsgo check` and `nsgo test` pass for the latest pending code, then toggles to **Confirmed · undo**. **Keep** (`KeepCodeReview` / `⌘↵`) writes kept YAML files and **confirmed** Go files atomically as **one undo step** in `Editor.History` so a single `Editor.Undo()` restores old YAML and Go files and removes newly created Go files. Keeping while Go files remain unconfirmed writes only the YAML changes and leaves a waiting card in the **Agent** panel (`"patrol.go is waiting for your OK"`, explaining what that means in Play, with **Review** to resume directly on the unconfirmed Go file). Pressing `Esc` (`CloseCodeReview`) pauses the review without discarding it, and **Revert all** (`RevertCodeReview` / `⌘⌫`) discards pending changes without touching disk. - **Command and MCP tools**: `CmdReviewCode` (`agent.reviewCode`) opens or resumes an active Go review. `editormcp` exposes `code_review_propose`, `code_review_status`, and `code_review_run_checks` so agents can propose pending Go files, inspect failures, submit Round 2 fixes in the same turn, and rerun overlay checks off the UI goroutine. ## Rewind an agent thread (#1021) Rewind an agent conversation to before any earlier sent message (`design/editor/Checkpoints.dc.html`, styled exclusively with `design/editor/Spec.dc.html` tokens): - **Per-turn file and scene checkpoints**: each composer request (`SubmitAgentPrompt`) snapshots the project's files on disk (skipping `.git`, `.nsgo`, `node_modules`, symlinks, and You-only settings files) alongside the open scene and `game.yaml` before the agent runs, and compacts the diff when the turn finishes (`AgentTurn.ChangedFiles`, `AgentTurn.SessionIDBefore`, `AgentTurn.SessionIDAfter`). - **Hover or focus "Rewind to here" and three choices**: hovering or focusing any sent user message in `AgentPanelView` reveals **Rewind to here** (`OpenAgentRewindPopover` / `ToggleAgentRewindPopover`), opening the `"Rewind to before this message"` popover (`AgentRewindPreview`) with three choices (`AgentRewindMode`), **Cancel** (or `Esc`), and **Rewind** (`ConfirmAgentRewind` / `RewindAgentTurn`): - **Files and conversation (`AgentRewindBoth`)**: restores all files touched by the target and later turns from their checkpoints (synchronizing the open scene, inactive scene tabs, `game.yaml`, and file tree), drops the target and later turns from the thread, and restores `AgentSessionID` to `SessionIDBefore` so the next request continues the session from before the rewound message. - **Files only (`AgentRewindFilesOnly`)**: restores the files from the turns' checkpoints while keeping the conversation thread and session unchanged. - **Conversation only (`AgentRewindConversationOnly`)**: drops the target and later turns and restores the session ID while leaving all files on disk untouched. - **Post-rewind banner, Redo, and composer return**: after rewinding, the rewound message returns to the composer highlighted with the Spec accent ring (`AgentComposerRewound`) so you can edit and ask it differently, and a status banner above the composer (`AgentRewindBanner`) summarizes what was rewound with a **Redo** button (`RedoAgentRewind` / `CanRedoAgentRewind`) that restores the files, conversation turns, session ID, and prior composer draft. ## Agent plans with clarifying questions and planned ghosts (#1035) For larger changes—such as edits touching Go code, creating files, or spanning multiple files under the project's `permissions.yaml` rules (`EvaluatePlanPermissions`, `PlanNeededForEdit`)—an agent proposes a structured plan before modifying any scene or file (`design/editor/Plan.dc.html`, styled strictly with `Spec.dc.html` Dark and Light tokens): - **MCP plan proposal (`plan_propose` & `plan_step_update`)**: calling `editormcp`'s `plan_propose` tool (`ActionRead`, never mutating files before approval) stages an `AgentPlan` in `PlanPhaseDraft` with a title, dynamic summary (`"5 steps · 3 files · 10 objects · about 2 min · ~35k tokens"`), clarifying questions with visual option previews (`room` sketches or `strip` timelines), numbered steps (files, additions, editable numeric `PlanStepField` steppers with min/max limits, permission badges like `Edit Go` or `Run the game`, planned Scene Tree nodes, and viewport ghosts), and waits until the person approves or stops, returning the structured `AgentPlanDecision` (answers, updated step counts, custom step notes, and removed steps). `plan_step_update` reports per-step execution status and attaches the finished `AgentPlanReview` checklist to the turn's review. - **Interactive Plan card in the Agent panel (`agentPlanCardView`)**: - Clarifying questions render as radio option cards with optional previews; picking an option collapses the question to a single summary row with **Change** (`ReopenPlanQuestion`). **Approve (`⌘↵`)** stays disabled and refused (`ApproveAgentPlan`) until every question is answered; **Just do it** (`JustDoItAgentPlan`) selects each question's suggested option and records `"Picked for you: …"`. - Numbered steps support inline editing (`EditPlanStep`, `AdjustPlanStepField`, `SetPlanStepNote`) and removal/restoration (`RemovePlanStep`, `RestorePlanStep`), striking out exclusive files in **FILES IN THIS PLAN**. - The footer states `"Nothing changes until you approve."` along with the permission-derived reason and a clickable **Permissions** link opening **Settings › Permissions** (`SettingsPagePermissions`). - **Planned viewport ghosts and Scene Tree markers**: - `drawPlanGhostsOverlay` draws agent-violet dashed outlines with step-numbered pills (`ResolvedPlanGhosts`), updating live as question answers move ghosts (via `PlanGhostOverride`) or numeric steppers change repeat counts (`RepeatField`), with a top-left legend (`"planned · not in the file yet"`) and a **Plan ghosts** toggle in the bottom floating viewport bar (`TogglePlanGhosts`). - `SceneTreeView` displays a `"{N} planned"` count, step badges on touched existing layers, dashed planned node rows, and the **FILES IN THIS PLAN** footer (`ResolvedPlanFiles`). - **Running, manual-edit pause, Stop, and turn review**: - While `PlanPhaseRunning`, the top header pill shows `"Agent is working · step k of N · manual edits to planned objects are paused"`, the active step's ghost switches from dashed to solid, and manual edits to planned objects (`IsObjectPausedByPlan`) are paused until completion or stop. - Pressing **Stop**, `Esc`, or `⌘.` before step 1 writes anything (`StopAgentPlan`) leaves every file unchanged (`NothingWritten: true`) and shows `"Stopped before step 1. Nothing was written."` with **Edit plan** (`EditStoppedPlan`) and **Run again** (`RunStoppedPlanAgain`). - Once completed (`CompleteAgentPlan` / `plan_step_update` with `complete: true`), the turn's review (`AgentTurn.Plan`, `agentTurnPlanReviewView`) lists every plan step and marks which were done or skipped. Small edits started with `⌘L` continue to set `SkipPlan: true`. ## Design tokens (#1002) Every color, type size, spacing step, corner radius, height, and motion duration in the editor comes from the embedded YAML theme and constants defined in `pkg/editor/theme/theme.yaml` and `pkg/editor/theme/theme.go`, matching `design/editor/Spec.dc.html` and `design/editor/Viewport3D.dc.html`: - **Embedded YAML theme (`theme.yaml`, `theme.Core`, `theme.Palette`)**: loaded with `core.ParseTheme` and attached on `EditorView`'s root scope via `cx.SetTheme(theme.Core())`. Every NSGo `core.Palette` and `ui.ColorsOf` role (`Background`, `Surface`, `Raised`, `Line`, `Border`, `Text`, `TextMuted`, `Accent`, `AccentText`, `Success`, `Warning`, `Danger`, `Focus`) maps directly onto the Spec palette in both dark and light appearances, while `Editor.Palette(cx)` (`theme.Dark()`, `theme.Light()`, `theme.PaletteFor(dark)`) exposes the additional Spec roles (`TextPrimary` / text strong, `TextSecondary` / text, `TextMuted` / text secondary, `TextFaint` / text muted, `OnTextPrimary`, `Viewport`, `ViewportDot`, `PillBg`, `HoverOverlay`, `ActiveOverlay`, `PrimaryHover`, `AccentHover`, `AccentPressed`, `Viewport3DGround`, `Viewport3DGrid`, `Accent`, `Agent`, `Added`, `Changed`, `Removed`/`Problem`, `Warning` with dedicated `Fill` and `Edge`, and 3D axis tokens `AxisX`, `AxisY`, `AxisZ`). - **Dark palette tokens (`Spec.dc.html` & `Viewport3D.dc.html`)**: - Surfaces & borders: `bg #101216`, `panel #12141A`, `raised #171A21`, `line #1F232A`, `line raised #262B35`, `viewport #15181D`, `viewportDot #2A2F38`. - Text ladder: `text strong #FFFFFF`, `text #D9DDE5`, `text secondary #B4BAC6`, `text muted #8B92A0`. The retired `#6F7684`, `#5D6472`, and `#4A505C` are never used for text. - Semantic roles: `accent #3B7BFF` (on-fill ink `#101216` at weight 600; `#FFFFFF` on dark accent or agent is never used), `agent #9B7BFF`, `added #4FD38A`, `changed #E9A84A`, `removed · problem #FF6B6B`, `warning #F2C14E` (on fill `#2A2414`, edge `#4A3F1F`). - 3D axes (`Viewport3D.dc.html`): `axisX #FF6B6B`, `axisY #4FD38A`, `axisZ #3B7BFF` (with WCAG-passing light equivalents `#C92A2A`, `#0D7A43`, `#1D5CE6`). - **Measured WCAG 2.2 contrast table (`theme.ContrastTable`, `theme.ContrastRatio`)**: `TestContrastTableDarkAndLight` computes the WCAG 2.2 luminance contrast ratio of every foreground/background, on-fill, warning-card, pill, overlay, and 3D axis pair directly from `theme.yaml` for both dark and light palettes, failing below `4.5:1` for text/on-fill or `3.0:1` for UI/overlay edges. A dedicated regression test verifies that reverting dark `text_muted` to `#6F7684` fails the check. - **Type, spacing, shape, heights, and motion constants**: - Type scale: Inter title `14 / 600` (`theme.FontTitleSize`, `theme.FontTitleWeight`), body `12.5 / 400` (`theme.FontBodySize`, `theme.FontBodyWeight`), section `11 / 600` at `+6%` tracking (`theme.FontSectionSize`, `theme.FontSectionWeight`, `theme.FontSectionTrack`), JetBrains Mono `11.5` (`theme.FontCodeSize`, `theme.FontFamilyMono`). - Spacing: `4`, `8`, `12`, `16`, `24` px only (`theme.Space4`–`theme.Space24`). - Radii & geometry: `6` controls (`theme.RadiusControl`), `8` buttons (`theme.RadiusButton`), `12` cards and toasts (`theme.RadiusCard`), `18` dialogs (`theme.RadiusDialog`); heights `28` rows/tool buttons (`theme.RowHeight`, minimum hit area `theme.MinHitSize = 28`), `30`–`32` buttons (`theme.ButtonHeight`, `theme.ButtonTallHeight`), `44` header (`theme.HeaderHeight`); `1` px inner borders (`theme.BorderWidth`). - Motion: `120 ms` hover/press (`theme.MotionHover`), `180 ms` panels/popovers/toasts (`theme.MotionPanel`), `240 ms` agent overlays (`theme.MotionOverlay`), `1.6 s` agent pulse (`theme.MotionAgentPulse`, `100%` ↔ `45%` opacity). `theme.MotionDuration` and `theme.AgentPulseOpacity` disable all motion (`0` duration, solid `1.0` opacity) whenever `Env.ReduceMotion` is enabled. - **No hardcoded UI color literals or dark-only package aliases**: every non-test `.go` file in `pkg/editor` outside `theme/theme.go` draws UI chrome, gizmos, overlays, and debug views exclusively from reactive `theme.Palette` tokens (`ed.Palette(cx)` / `e.activePalette()`, keeping scene content data such as `scene.BackgroundColor` as scene data). `TestSpecNoHardcodedColorLiteralsInEditor` rejects any `core.RGB`/`core.RGBA` call or hardcoded UI hex color literal outside `theme/theme.go`, and `TestSpecNoDarkOnlyPackageColorVarsInEditor` rejects package-level color variables initialized from `theme.Dark()` or `theme.Light()` so every editor screen repaints live across Dark and Light appearances. ## Built-in agent provider settings (#1747) `editor.yaml` can set `agent.builtInEndpoint`, `agent.builtInModel` and `agent.builtInFastModel` to point the built-in agent at another Anthropic Messages or OpenAI-compatible Chat Completions server (a gateway, or a local server on loopback) and to pick the model IDs for the default and fast routes (`AgentBuiltInEndpointForSettings`, `AgentBuiltInModelForRoute`). The endpoint must pass the same policy as `Editor.BuiltInAgentEndpoint`, which it takes precedence over: `https://`, or `http://` only to a loopback host. Empty fields keep `DefaultBuiltInAgentEndpoint`, `DefaultBuiltInModel` and `DefaultBuiltInFastModel`. Pasting an API key on the Start Screen validates it against the configured endpoint and fast model. `agent.builtInFormat` accepts `anthropic` (the default) or `openai`; any other value is refused when `editor.yaml` loads. The defaults name Anthropic's endpoint and models, so `openai` also needs `agent.builtInEndpoint` and `agent.builtInModel`, and `editor.yaml` without them is refused; the fast route uses `agent.builtInModel` when `agent.builtInFastModel` is empty. With `openai`, the built-in runner sends OpenAI-compatible Chat Completions requests, including function tools, tool results, bearer authentication, and retry handling. A `/v1` endpoint is resolved to `/v1/chat/completions`; Anthropic endpoints keep their Messages path. These are You-only settings: `ApplySettings` refuses changes made on behalf of an agent. API keys stay in the system keychain and are never written to `editor.yaml`. `pkg/editor/agentdir` (experimental) records local agent discovery in a versioned `agents-cache.yaml`: each agent's path, the version its `--version` call printed, its sign-in state, and its model IDs with their effort levels, without reading agent credentials. `agentdir.Probe` only asks for the version, so it leaves the sign-in state `unknown`. Model IDs and effort levels must match a fixed character set and length on load and on save, so a value read from the cache is safe to pass back to an agent's command line. New project asset helpers (`Editor.NewRigProjectFile`, `Editor.NewGridMapProjectFile`) create and save skeletal rigs and GridMaps with canonical extensions beneath the open project, making the folders the path names. They refuse a path outside the project or one where a file already exists, before opening anything. ## Editor diagnostics Diagnostics logs live in `nsgo-game-editor/logs` under the user cache directory (`os.UserCacheDir`): `~/Library/Caches/nsgo-game-editor/logs` on macOS, `$XDG_CACHE_HOME/nsgo-game-editor/logs` (by default `~/.cache/nsgo-game-editor/logs`) on Linux and `%LocalAppData%\nsgo-game-editor\logs` on Windows; `Editor.DiagnosticsLogDir` overrides it. A `diaglog.Writer` keeps one stream per file, such as `editor.log` or `agent.log`, as JSON lines with `time`, `stream` and `msg`. It cuts a line at 64 KiB (`diaglog.MaxLineBytes`) and rotates a file at 4 MiB into `.log.1` and `.log.2`, keeping three files (`diaglog.DefaultMaxBytes`, `diaglog.DefaultMaxFiles`). As an `io.Writer` it splits a child process's output into lines. The editor routes every child process it starts into a stream: external agent runs write `agent.log`, asset builds `asset-build.log`, device builds and device runs `device-build.log`, exports `export.log`, release builds and store uploads `release-build.log`, code review's `go tool nsgo check` and `go tool nsgo test` runs `code-review.log`, and headless playtests `playtest.log`. Each stream is written through the same redactor as below, so a diagnostics zip carries what a build or an agent printed and none of what it must not. Every line is redacted before it is written, and again on export (`diaglog.Redactor`). The home directory, the open project's root and the editor's data directory become ``, `` and ``, and the built-in agent's stored API key becomes ``. PEM private keys, bearer tokens, `Authorization` and `Cookie` header values, environment values whose names contain `KEY`, `SECRET`, `TOKEN` or `PASSWORD`, common API-key prefixes (`sk-`, `ghp_`, `github_pat_`, `xox…-`, `AKIA`, `AIza`) and email addresses are masked. URLs keep only their scheme and host. Help → Export Diagnostics (`help.exportDiagnostics`) opens the system's save dialog for `nsgo-game-editor-diagnostics-.zip`, which holds the redacted log files and a versioned `manifest.yaml` ([format](http://nsgo.games/docs/formats/#editor-diagnostics-manifest)). Nothing is uploaded. `Editor.WriteDiagnostics` writes the same zip to any `io.Writer`. Agent usage records input, cached-input, output-token, and estimated-cost counters in the local weekly usage state. Model-specific price tables remain tied to the configured provider route. --- Source: http://nsgo.games/docs/entities/ # Entities A small, zero-reflection entity-component-system (ECS) for NSGo games: generational entities, typed sparse-set components, allocation-free queries, topologically ordered systems, prefabs and JSON world snapshots integrated with `game/save`. ```go import "github.com/nsgo-dev/game/pkg/entities" ``` `go tool game generate component `, `system ` and `prefab ` write a new component, system or prefab into a game with its registration and a test; see [Command Line](http://nsgo.games/docs/cli/#generate). ## Architectural decision Before implementing `entities` ([#136](https://github.com/nsgo-dev/game/issues/136)), three designs were compared for representing game objects in `github.com/nsgo-dev/game`: 1. **A small, zero-reflection, generational-index ECS with typed sparse-set storage** (chosen). 2. **An object-oriented scene tree** of heap-allocated nodes with virtual update methods. 3. **A reflection-driven archetype ECS** with dynamic component tables and query planners. Option (1) was chosen for five reasons: - **Zero-allocation hot loops**: entities are 64-bit generational handles (32-bit slot index + 32-bit generation) recycled through a free list, and each component type lives in a contiguous typed sparse set (`Store[T]`). Creating and destroying 100k entities in steady state, accessing components, and iterating queries perform zero heap allocations. - **Zero reflection**: Go generics identify component stores through zero-sized type tags and keep all component access, queries and prefab builders statically typed with no `reflect` imports. - **Safe handle lifetimes**: destroying an entity increments its slot generation before recycling it, so stale `Entity` handles never alias newly spawned entities. - **Explicit, deterministic execution**: systems declare `Before` and `After` constraints resolved once by Kahn's topological sort with registration-order tie-breaking. Cycles and missing targets fail cleanly, and `Order()` exposes the exact execution sequence for debug overlays. - **Clean serialization boundaries**: only component types registered with `RegisterCodec[T]` are written to deterministic `WorldSnapshot` JSON values and saved through `game/save`, keeping transient runtime handles (sprites, audio voices) out of save files while preserving entity IDs and cross-entity references. ## Entities and World An `Entity` is a `uint64` carrying a 32-bit slot index and a 32-bit generation (`entities.Zero` is the invalid handle and is never alive). `World` owns entities and their component stores. - `NewWorld()` returns a fresh world (the zero value of `World` is also ready to use). - `Spawn()`, `Destroy(e)`, `Alive(e)` and `Count()` manage entity lifetimes with free-list recycling. - `Clear()` removes all entities and components while bumping generations and keeping slice capacities for zero-allocation reuse. `Reset()` releases component and active entity backing storage while keeping bumped slot generations, so handles from before `Reset()` stay dead even after new entities are spawned. - `Attach(cx)` binds the world to an NSGo `*core.Scope` so `Dispose()` runs automatically when the scope is disposed. ```go world := entities.NewWorld() world.Attach(cx) hero := world.Spawn() world.Alive(hero) // true world.Destroy(hero) world.Alive(hero) // false, even after the slot is recycled ``` ## Components and queries Each component type `T` is stored in a typed sparse set (`*Store[T]`). Top-level generic functions operate directly on a `*World`, and `Component[T](w)` returns the underlying `*Store[T]` for direct inner-loop access. - `Set[T](w, e, v)`, `Get[T](w, e)`, `Has[T](w, e)` and `Remove[T](w, e)` attach, read, check and detach components in O(1) time. - `Each1[A]`, `Each2[A, B]`, `Each3[A, B, C]` and `Each4[A, B, C, D]` iterate over the smallest sparse set and check O(1) membership in the others, visiting exact matches in deterministic order with zero reflection and zero heap allocations. Returning `false` stops iteration early. The component pointers are valid only inside the callback and only until it adds a component of an iterated type: adding can grow the store and move its values, so collect entities and add components after the loop. A callback may destroy the entity it was handed, but not add or remove other entities of the iterated stores; collect those and act after the loop. ```go type Position struct{ X, Y float64 } type Velocity struct{ DX, DY float64 } entities.Set(world, hero, Position{X: 10, Y: 20}) entities.Set(world, hero, Velocity{DX: 60, DY: 0}) entities.Each2[Position, Velocity](world, func(e entities.Entity, p *Position, v *Velocity) bool { p.X += v.DX * dt.Seconds() p.Y += v.DY * dt.Seconds() return true }) ``` ## Systems and update order `Scheduler` runs named systems in a deterministic topological order on each `game.Loop` fixed step. - `AddSystem(name, fn, opts...)` registers a system with optional `Before(other)` and `After(other)` constraints. Targets may be registered in any order. - `HasSystem(name)` reports whether a system with `name` is already registered on the scheduler. - `Build()` validates constraints and resolves execution order with Kahn's algorithm, breaking ties by registration order. Unknown targets return `ErrUnknownSystem` and cycles return `ErrSystemCycle`. - `Order()` returns the resolved names and `String()` formats them as `"a -> b -> c"` for debug overlays. - `Step(w, dt)` resolves if needed and runs each system in order with zero steady-state allocations. - For reusable plugins, `game/pkg/gameplugin` adds four standard stage anchor pairs (`StageInput` -> `StageUpdate` -> `StagePhysics` -> `StageLate`) once per scheduler so plugin systems can attach to a stage without knowing the game's system names; see [Plugins](http://nsgo.games/docs/plugins/#standard-scheduler-stages). ```go sched := entities.NewScheduler() _ = sched.AddSystem("input", readInput) _ = sched.AddSystem("physics", stepPhysics, entities.After("input")) _ = sched.AddSystem("render", syncSprites, entities.After("physics")) loop := &game.Loop{ Rate: 60, Update: func(dt time.Duration) { _ = sched.Step(world, dt) }, } ``` ## Prefabs A `Prefab` is a named template that stamps a preset group of components onto newly spawned entities. - `NewPrefab(name)` creates a template, and `Clone(name)` derives a variant without mutating the original. - `With[T](p, v)` attaches a value component copied per entity. - `WithFunc[T](p, make)` invokes `make()` on each spawn so slices, maps and pointers are never shared across entities. - `Spawn(w)` and `SpawnN(w, n)` create independent entities from the template. ```go goblin := entities.NewPrefab("goblin") entities.With(goblin, Position{X: 10, Y: 20}) entities.WithFunc(goblin, func() Inventory { return Inventory{Items: []string{"dagger"}} }) squad := goblin.SpawnN(world, 5) ``` ## 2D transform hierarchy `world.Hierarchy2D()` (or `entities.NewHierarchy2D(world)`) attaches a parent-child 2D transform hierarchy to a World. Local transforms live in the `Transform2D` component (`X`, `Y`, `Rotation`, `ScaleX`, `ScaleY`, `Hidden`; build one with `NewTransform2D` or `IdentityTransform2D`, since the zero value has zero scale), and `Sync()` composes them into cached `WorldTransform2D` components that `Each1`/`Each2`/`Each3` can iterate directly. ```go h := world.Hierarchy2D() ship, turret := world.Spawn(), world.Spawn() h.SetLocal(ship, entities.NewTransform2D(100, 50)) h.SetLocal(turret, entities.NewTransform2D(0, -12)) _ = h.SetParent(turret, ship, false) h.SetRotation(ship, 0.5) h.Sync() wt, _ := h.WorldTransform(turret) _ = wt ``` - `SetLocal`, `SetPosition`, `SetRotation`, `SetScale`, `SetVisible` and `entities.Set` with a `Transform2D` mark the entity and its subtree dirty. After writing through a `*Transform2D` from `Get` or a store, call `h.MarkDirty(e)`. - Visibility is inherited: `WorldTransform2D.WorldVisible` is false when the entity or any ancestor is hidden. - `SetParent(child, parent, keepWorld)` and `Detach(child, keepWorld)` keep the child's local transform, or with `keepWorld` recompute it so the child stays where it is on screen. A keep-world reparent whose exact relative transform needs shear (a rotated child under a non-uniformly scaled parent) returns `ErrNotDecomposable` and changes nothing; cycles return `ErrCycle` and dead entities `ErrDeadEntity`. - Destroying a parent applies the hierarchy's `RemovePolicy` (`SetRemovePolicy`): `RemoveDetach` (default) detaches the children keeping their local transforms, `RemoveDetachKeepWorld` detaches them keeping their world transforms, and `RemoveCascade` destroys the whole subtree. `DestroyWithPolicy(e, policy)` overrides it for one call. - Snapshots only include registered components: call `RegisterCodec[entities.Transform2D](w, "transform2d")` to save local transforms. `WorldTransform2D` is derived, so it does not need a codec; the hierarchy reseeds from the restored local transforms. ## Spawning from YAML scenes `game/sceneformat` spawns a self-contained YAML scene directly into a `*World` with `SpawnEntities` (transforms and `ObjectRef` only) or `SpawnEntitiesWith` (also attaching typed ECS components declared on a `ComponentRegistry` via `ComponentType.Spawn`): ```go type Health struct{ HP, Max int } reg := sceneformat.NewComponentRegistry() reg.MustRegister(sceneformat.ComponentType{ Name: "health", Fields: []sceneformat.Field{ {Name: "hp", Kind: sceneformat.FieldInt, Default: 10}, {Name: "max", Kind: sceneformat.FieldInt, Default: 10}, }, Spawn: func(w *entities.World, e entities.Entity, fields map[string]any) error { entities.Set(w, e, Health{HP: fields["hp"].(int), Max: fields["max"].(int)}) return nil }, }) spawned, err := sceneformat.SpawnEntitiesWith(doc, world, sceneformat.SpawnOptions{Components: reg}) ``` - **Pre-spawn validation & defaults**: when `SpawnOptions.Components` is non-nil, every component on every object is validated and resolved with its defaults (`ComponentRegistry.Resolve`) before the first entity is spawned. Registries that only check files may leave `ComponentType.Spawn` nil. - **Deterministic order**: entities spawn in depth-first document order (parents before children, linked into `Hierarchy2D` with `Transform2D` and `ObjectRef`), and within each object components run in ascending component-name order. Hidden layers spawn top-level objects hidden so their subtrees are not world-visible while still running `Spawn`. - **Rollback on error**: if any `ComponentType.Spawn` returns an error, every entity created during the call is destroyed in reverse order (leaving pre-existing entities in `w` untouched) and the error names the layer, object ID and component. - **Connected scenes**: `sceneformat.SpawnConnected(doc, world, reg, ctx)` passes `reg` through `SpawnEntitiesWith`, so connection handlers can immediately read typed components with `entities.Get`. ## Saving and loading a world Worlds serialize to deterministic `WorldSnapshot` JSON values and integrate directly with `game/save`. - `RegisterCodec[T](w, typeName)` registers a JSON codec for component type `T`. Unregistered components are omitted from snapshots. - `w.Snapshot()` emits live entities in ascending slot-index order and components in ascending codec-name order, preserving exact indices and generations so cross-entity `Entity` references stay valid after restore. - `w.Restore(snap)` decodes into a temporary world first and commits atomically, leaving `w` untouched if any codec is missing or decoding fails. Slots omitted from `snap` (including an empty snapshot) keep bumped generations so stale handles from before `Restore` stay dead even after new entities are spawned, and rolling a slot back to an earlier generation keeps a generation floor so destroying the restored entity never re-issues a generation already used before the restore. - `SaveWorld(store, slot, w)` and `LoadWorld(store, slot, w)` persist and restore worlds through `save.Store` (both `save.NewStorageStore` and `save.NewFileStore`, including schema versions and migrations). `LoadWorld` checks the snapshot while the slot decodes, so a snapshot it cannot restore (an unknown codec, a bad parent, a component that does not decode) falls back to the backup copy, and its error names the slot, the line and the field, such as `data.entities[2].parent`. ```go _ = entities.RegisterCodec[Position](world, "position") _ = entities.RegisterCodec[Velocity](world, "velocity") store := save.NewStorageStore(cx.Storage(), "game") if err := entities.SaveWorld(store, "slot1", world); err != nil { return err } fresh := entities.NewWorld() _ = entities.RegisterCodec[Position](fresh, "position") _ = entities.RegisterCodec[Velocity](fresh, "velocity") if err := entities.LoadWorld(store, "slot1", fresh); err != nil { return err } ``` ## Component change detection `World.ChangeTick` returns an observation point and turns the change journal on; the clock advances on every call and before every system `Scheduler.Step` runs, and never goes back, so changes recorded after a tick was taken always carry a later one. `Store.Set` records `ChangeAdded` for a new component and `ChangeChanged` for replacement, `Mut` marks a pointer write before returning it, and `MarkChanged` covers writes through a pointer returned by `Get`. `AddedSince`, `ChangedSince`, `RemovedSince` and the lower-level `EachChange` read the journal after a saved tick in deterministic order. A removal record carries the stale entity handle and a nil component pointer. Callers keep one tick per system when they need independent observations, taking a new one at the end of each run. The journal is an additive observer boundary. Existing `Each*` queries remain unchanged. The journal is only emptied by `Clear` and `Reset`; trimming it, snapshots, system sets and automatic scheduler-owned last-run cursors remain follow-up work. ## Conditional systems Pass `RunIf(func(*World) bool)` to `Scheduler.AddSystem` to gate a system without changing its deterministic resolved order. Compose predicates with `Not`, `And` and `Or`. Each condition runs immediately before its system, so a skipped system does not disturb later systems' order, and `Step` still makes no allocations of its own. A nil condition always holds, so `Not(nil)` never holds, `And` ignores nil conditions and holds when given none, and `Or` ignores them and does not hold when given none. System sets, state enter and exit schedules, state-scoped cleanup and profiler adapters remain follow-up work. ## Exclusion filters `Each1Without[A, X]` visits entities carrying `A` while skipping entities carrying exclusion component `X`, preserving deterministic dense iteration without allocations. This is useful for systems that omit dead or sleeping entities without adding a branch to every caller's query loop. ## Optional query components `Each2Opt[A, B, C]` iterates required `A`/`B` stores while passing a nil `C` pointer when the optional component is absent, preserving smallest-store deterministic traversal without per-entity `Get` lookups. --- Source: http://nsgo.games/docs/epic/ # eos ```go import "github.com/nsgo-dev/game/pkg/online/eos" ``` `eos` is the Go boundary for Epic Online Services: exchange-code login, achievement unlocks and progress, leaderboard scores and queries, and rich presence, with every result delivered on the engine goroutine. The package defines the contract a native adapter implements, `eos.Driver`, and the `eos.Platform` that games call. It does not ship the native adapter yet: binding the EOS SDK shared libraries through purego, `epic` IDs in the achievement and leaderboard files, and shipping the library are tracked in [#1770](https://github.com/nsgo-dev/game/issues/1770). Until then a game passes its own driver, and tests pass a fake. ## Platform `eos.New(cx, cfg, driver)` creates a platform from the product, sandbox and deployment IDs in `eos.Config` and closes it when `cx` is disposed. It returns `eos.ErrInvalidConfig` when an ID is empty and `eos.ErrUnavailable` when `driver` is nil, which is what a native adapter reports when the EOS shared library is missing. ```go platform, err := eos.New(cx, eos.Config{ ProductID: "…", SandboxID: "…", DeploymentID: "…", ExchangeCode: eos.ExchangeCodeFromArgs(os.Args[1:]), }, driver) ``` The Epic launcher starts a game with `-AUTH_PASSWORD= -AUTH_TYPE=exchangecode`; `eos.ExchangeCodeFromArgs` returns that code, or `""` for any other login type. Call `platform.Tick()` every step of the game loop: EOS completes its requests from its tick. Call every other method on the engine goroutine as well: - `Login(done)` signs in with the exchange code; afterwards `Player()` and `SignedIn()` report the account, and they are reactive reads. Without an exchange code it fails with `eos.ErrUnauthenticated`. - `UnlockAchievement(id, done)` and `ProgressAchievement(id, percent, done)`, with `percent` in [0,100]. - `SubmitScore(board, score, done)` and `QueryLeaderboard(board, friends, limit, done)`, global or friends rows, `limit` positive. - `SetPresence(details, status, done)`. Reporting before `Login` succeeds fails with `eos.ErrUnauthenticated`, an empty ID or an out-of-range argument with `eos.ErrInvalidArgument`, and any call after `Close` with `eos.ErrClosed`. `done` never runs inside the call that started the request: the platform posts it to its scope, and drops results that arrive after `Close` or after the scope is disposed. ## Drivers A `Driver` starts each request and returns at once, then calls the request's `done` exactly once, normally from inside its `Tick`, where the EOS SDK dispatches callbacks, or at once when the request cannot start. The platform calls the driver only on the engine goroutine; a driver may call `done` from any goroutine. --- Source: http://nsgo.games/docs/errors/ # File loading errors Every loader and validator in this module returns the same error type when a file cannot be used: `*loaderr.Error` from `github.com/nsgo-dev/game/pkg/loaderr`. It names the file, the line and column, the field, what was wrong, what was expected and how to fix it, so a person, or an agent reading a test or build log, can open the file at that line and correct it without reading the loader's source. ```text levels/cave.scene.yaml:14:7: layers[1].space: layer "hud" has invalid space "iso"; expected "world" or "screen"; fix: set space to world or screen, or remove it for world ``` The message reads `file:line:column: field: problem; expected E; fix: F`, leaving out the parts that are not known. Editors and terminals turn the `file:line:column` prefix into a link. ## The fields | Field | Holds | | --- | --- | | `File` | The file's path or name. A loader that reads a path fills it in; one that is handed bytes leaves it to its caller (see below). | | `Line`, `Column` | 1-based position of the problem, 0 when it is not at one place, such as a file that cannot be read. | | `Field` | Where in the document, as a path: `layers[2].objects[0].id`, or `tilemaps["a.b"].ref` for a key that holds a dot. Empty for the document as a whole. | | `Problem` | What is wrong. | | `Expected` | What the loader expected there, when the problem does not already say it. | | `Fix` | What to change so the file loads. Every error a loader returns has one. | | `Err` | The underlying error: `errors.Is` and `errors.As` see through an `Error`, so sentinels such as `save.ErrCorrupt` and `modding.ErrInvalidManifest` still match. | `loaderr.As(err)` returns the `*Error` in a chain. ## Naming the file A loader that reads a path, such as `particles.LoadConfigFile`, `gltf.LoadFS`, `replay.LoadFile`, `datatable.LoadFile` or `editor.OpenFile`, names that path in its errors. A loader handed bytes, such as `sceneformat.Parse` or `tilemap.LoadTiled`, knows the line but not the file, and writes `` in its place; the code that read the file names it: ```go data, err := fs.ReadFile(assets, "levels/cave.scene.yaml") if err != nil { return err } doc, err := sceneformat.Parse(data) if err != nil { return loaderr.WithFile(err, "levels/cave.scene.yaml") } ``` `WithFile` names the file only on an error that is itself a `*loaderr.Error`, as every loader's entry point returns. An error that wraps one, such as `fmt.Errorf("level 3: %w", err)`, is returned unchanged, so its context and sentinels still match; call `WithFile` before wrapping. Values kept in `core.Storage`, such as input bindings, debug tunables and save slots, name their storage key as the file. A save slot in a `FileBackend` names its file, `/.json` or `/.json.bak` for the backup copy. ## What each loader reports | Package | Loader | Lines | | --- | --- | --- | | `sceneformat` | `Parse`, `ParseWith`, `ParseConflict` | Decode errors and every schema rule, by field; the `*FieldError` `Validate` returns stays in the chain, and `ParseWith` names `ParseOptions.File` | | `project` | `Parse`, `ParseBrief`, `LoadFile` | Project and brief schema rules, by field | | `resource` | `Parse`, `ParseAs`, `Library.Load`, `Library.Reload`, `Library.ReloadFile` | Header, material, curve, gradient, animation, theme, bus layout and physics material rules, by field; `Library` names the resource path | | `importsettings` | `Parse`, `ParseAssetSource` | Sidecar sections, pivots, slices, credits and asset provenance fields, by field | | `tooling/refs` | `ParseIndex` | Project index paths, ordering, UIDs and SHA-256 digests, by field | | `particles` | `UnmarshalConfigYAML`, `UnmarshalConfigJSON`, `LoadConfigFile`, `LoadConfigFS`, `HotConfig` | Decode errors, durations, colors and enumerations, by field or at the value's line | | `skeletal` | `Load` | Bones, slots, skins and keyframes, by field | | `anim3d` | `LoadEventsSidecar`, `LoadEventsFromGLTFExtras` | Decode errors and sidecar schema rules, by field | | `animclip` | `ParseStateMachine` | State machine states, transitions and parameters, by field; `*StateMachineError` stays in the chain | | `sprite` | `LoadAtlas` | Frames, frame tags and nine-slices, by field | | `tilemap` | `LoadTiled`, `LoadLDtk`, `LoadLDtkAll` | Map, tilesets (an external tileset names its own file), layers, objects and properties, by field | | `l10n` | `Catalog.LoadJSON`, `ParseAssetManifest`, `AssetCatalog.LoadAssetManifestYAML` | Keys, asset variants and groups, by field | | `input` | `Actions.Load`, `Haptics.Load` | Stored bindings, by field, under the storage key | | `modding` | `ParseManifest`, `ModManifest.Validate`, `Manager.Discover`, `Manager.DiscoverFS`, `Manager.Reload` | Each manifest field, a game version the mod does not support and a duplicate id, naming `/mod.yaml` | | `gameplugin/manifest` | `Parse` | Plugin manifest fields and capabilities, by field | | `gameui` | `ParseScreen` | Screen layout tree, device classes and widgets, by field | | `replay` | `Decode`, `LoadFile` | Header and steps, by field, such as `steps[3].press[0]` | | `statedump` | `Parse`, `ReadFile` | Header, scene state, values, entities and JSON-incompatible YAML nodes, by field or node line | | `undo` | `DecodeLog` | Version, counts, required keys and moves, by field | | `save` | `Store.Load`, `Store.LoadChecked`, `SettingsStore.Load` | Envelope, data and checks, naming the copy's file or storage key (a custom `Backend`'s copies by slot, `slot (backup)` for the backup) | | `entities` | `LoadWorld`, `World.Restore` | Entity indices, parents and components, by field | | `assets` | `ParsePackManifest`, `Manager.LoadAtlas`, `Group` atlases | Decode errors; atlases name their URI | | `world3d`, `voxel`, `render3d` | `LoadMeshLibraryFromGLTF`, `world3d.Parse*`, `voxel.Parse`, `ParseLightProbeGrid`, `LoadLightProbeGridFS` | Version, bounds, counts, meshes, chunks and probe coefficients, by field; `render3d.ErrInvalidProbe` stays in the chain | | `ai`, `pathfind/navbake`, `pathfind3d/navbake3d` | `ParseGOAP`, `ParseUtility`, `navbake.Parse`, `navbake3d.Parse` | Facts, actions, goals, curves, polygons and off-mesh links, by field | | `quest`, `rooms`, `loot`, `inventory`, `ability`, `stats`, `cards`, `worldmap`, `cutscene`, `vn`, `bullets`, `framedata`, `fighting`, `platformer`, `vehicle`, `rts`, `rhythm`, `idle`, `procgen`, `quality` | Each package's YAML `Parse*` and `Load*` entry points | Decode errors, custom durations/ranges and every validation rule, by field; sentinels such as `quest.ErrInvalidBook`, `rooms.ErrInvalidMap` and `stats.Err*` stay in the chain | | `online/accounts`, `online/accounts/authtoken`, `online/achievements`, `online/cloudsave`, `online/leaderboard`, `online/leaderboard/selfhost`, `online/liveops`, `online/netplay/wire` | Each package's YAML `Parse*` and `Load*` entry points | Service configs, key sets, catalogs, reminders and wire schemas, by field | | `tooling/playtest` | `ParseConfig`, `LoadConfigFile`, `ParseReport`, `LoadReportFile` | Scope, runs, bot config, metrics, goals and report sections, by field | | `editor` | `OpenFile`, `ParseEditorSettings`, `ParsePermissions`, `ParseAutomations`, `ParseLayout`, `ParseRecentProjects`, `ParseCheckpointManifest`, `ParseAgentThread`, `ParseAgentThreadYAML`, `parseViewState` | Editor configs, layouts, checkpoints, threads and view state, by field | | `gltf` | `Load`, `LoadFS` | The top-level item at fault, such as `nodes[3]` | | `text` | `LoadBMFont`, `LoadBMFontImage` | The record at fault, in text and XML fonts | | `dialogue` | `ParseYarn` | The script line at fault | | `datatable` | `LoadCSV`, `LoadJSON`, `LoadYAML`, `LoadFile` | The cell at fault; `CellError` stays in the chain | | `tooling/devstate`, `tooling/hotreload`, `tooling/library`, `tooling/assetbuild` | `Store.LoadSnapshot`, `ParseMaterial`, `ParseIndex`, `ParseManifest`, `parseCache` | Decode errors and manifest, index and material rules, by field | | `tooling/gamedebug` | `Console.LoadTunables` | The tunable at fault, under the storage key | | `tooling/bench`, `tooling/sizecheck` | `bench.Decode`, `bench.LoadFile`, `sizecheck.LoadBudget`, `sizecheck.LoadMobileBudget` | Decode errors, limits and benchmark metrics, by field | A file that cannot be read has no line: its error names the file, keeps the read error in `Err` and still gives a fix. ## Writing a loader 1. Validate the decoded document with `loaderr.Errorf(field, fix, format, args...)`, building `field` with `loaderr.Path("layers", i, "objects", j)` or extending one with `loaderr.Join(at, "alpha")`. A validator does not know lines, so it names the field instead. 2. In the loader's entry point, pass every error through `loaderr.Locate(err, file, data, fix)` once (or `loaderr.LocateJSON(err, file, data, fix)` for JSON-only loaders that do not need YAML support). It finds the field's line and column in the YAML or JSON text, turns decode errors from `encoding/json` and YAML (syntax, unknown fields, wrong types, duplicate keys, an early end) into an `Error` with their line and a fix, names the file, and gives the loader's `fix` to an error that has none. 3. For a line-based format that is neither YAML nor JSON, such as BMFont text or Yarn, set `Line` directly. 4. Write a fix as an instruction: what to write, where, or which tool to export from again. "Set space to world or screen" helps; "invalid value" does not. 5. Walk maps in sorted key order, so the same problem is reported on every run when a file has several. 6. Test with `internal/loaderrtest`: `Expect(t, err, file, line)` checks that the error names the file and line and has a fix, and `ExpectField(t, err, file, data, field)` also checks the field. For YAML formats, `internal/formattest.Run` verifies that unknown fields and missing, zero or future versions return a `*loaderr.Error` with the matching line and a fix, and `internal/repocheck` enforces that every YAML-decoding package runs both `formattest.Run` and `loaderrtest`. A custom `UnmarshalYAML` knows the node it was handed: return a `*loaderr.Error` with the node's `Line` and `Column`, as `particles` does for durations and colors, and `Locate` keeps them. A custom `UnmarshalJSON` cannot say where it failed: the `encoding/json` that `nsgo build` links returns its error without the field's path, so keep the value it refuses and report it from the validator with the field instead. --- Source: http://nsgo.games/docs/farming/ # Farming rules `pkg/farming` contains deterministic rules for farming and life-sim projects. `Calendar` advances through versioned seasons from an explicit duration, rolling to the next season after its configured number of days. `CropKind` and `Crop` model staged growth. A crop advances only when `WateredDay` is called, so an unwatered day cannot silently mature it. Both APIs avoid `time.Now`, which keeps saves, replays and headless tests reproducible. --- Source: http://nsgo.games/docs/fighting/ # fighting `github.com/nsgo-dev/game/pkg/fighting` buffers fighting-game input one fixed step at a time and recognizes motion inputs (quarter circles, dragon punches, charges, double taps), button presses, chords and combos described in a YAML move set. ## Numpad notation Directions use numpad notation, relative to a character facing right: ```text 7 8 9 up-back up up-forward 4 5 6 back neutral forward 1 2 3 down-back down down-forward ``` `Direction` holds one digit, `DirectionOf(x, y)` builds one from signs, and `Mirror` swaps left and right. When a character faces left (`FaceLeft`), the recognizer mirrors every direction before matching, so `6` always means toward the opponent and the same move set works on both sides. ## Move sets A move set is a versioned YAML file. Unknown fields are refused, and `Encode` writes a canonical form (block style, fields in schema order, motion entries as quoted strings), so parsing `Encode`'s output and encoding it again reproduces it byte for byte. ```yaml version: 1 input: up: up down: down left: left right: right axisX: move_x axisY: move_y moves: - name: lp press: - lp - name: hadoken motion: - "2" - "3" - "6" window: 12 press: - lp - hp buffer: 8 priority: 20 - name: sonic_boom motion: - "6" charge: dirs: "147" steps: 40 grace: 6 press: - lp buffer: 6 priority: 25 - name: forward_dash motion: - "6" - "5" - "6" window: 12 priority: 10 - name: throw press: - lp - lk pressAll: true pressWindow: 2 priority: 40 combos: - name: jab_fireball sequence: - lp - hadoken gap: 20 ``` `input` names the actions and axes that make up the stick. Digital actions add ±1 to their axis and analog axes add their value; an axis whose total reaches `deadzone` (default `0.5`) points that way, so holding left and right together is neutral. `axisY` is positive down unless `yUp` is set. Each move has a `name` and a `motion`, a `press`, or both: | Field | Meaning | | --- | --- | | `motion` | Direction entries matched on distinct, increasing steps. An entry is a string of one or more digits, any of which satisfies it, so `"23"` accepts down or down-forward. | | `window` | Most steps from the first to the last motion entry; only for motions of 2 or more entries. | | `charge` | `dirs` held for at least `steps` consecutive steps, ending no more than `grace` steps before the step that precedes the first motion entry. | | `press` | Button actions that finish the move; any one of them, pressed on the current step. | | `pressAll`, `pressWindow` | Require every `press` button within `pressWindow` steps (a chord). | | `buffer` | Most steps the finishing press may come after the last motion entry; needs both `motion` and `press`. | | `priority` | Orders moves finished on the same step, highest first. | All step counts are inclusive and at most `MaxSteps` (600). A motion without `press` finishes on the first step it fits, so holding the last direction does not repeat it. Inputs that finished a move cannot finish it again: a button pressed within `buffer` after a finished quarter circle is not a second fireball, and the next one needs a fresh motion. A move set may name up to 32 buttons. A combo lists at least two moves; each must follow the previous one within `gap` steps, and any other move in between breaks it. ## Recognizing input ```go set, err := fighting.LoadFile("moves.yaml") if err != nil { return err } rec, err := fighting.NewRecognizer(set) if err != nil { return err } loop := &game.Loop{ Rate: 60, Update: func(dt time.Duration) { actions.Step() res := rec.Update(actions, player.Facing) if len(res.Moves) > 0 { player.Perform(res.Moves[0].Name) } for _, c := range res.Combos { hud.Announce(c.Name) } }, } ``` Call `Update` once per fixed step, after the source has stepped. `Result.Moves` holds every move finished on that step, highest priority first, so `Moves[0]` is the one to perform; only that move advances combos. Each `Match` carries the step its inputs started on and the step it finished. The slices are reused by the next call and allocate nothing. `Feed(raw, held, facing)` records a step from an already decoded direction and button mask (bit `i` for `Buttons()[i]`), such as inputs from netcode. Recognition depends only on the frames fed, so a re-simulation from the same inputs gives the same results. For rollback, `AppendState(dst)` appends the recognizer's complete state (buffered frames and the progress of every move and combo) to a snapshot, and `LoadState` restores it on a recognizer built from the same move set before re-simulating; it refuses state from a different move set and leaves the recognizer unchanged. The history itself is a `Buffer`, a ring of `Frame`s (absolute and relative direction, facing, held and newly pressed buttons) sized by `MoveSet.Lookback`, reachable through `Recognizer.Buffer` for input displays and training modes. ## Testing with replays `Recognizer.Update` takes any `Source` (`Pressed` and `Axis`), which `*input.Actions`, `*replay.Recorder` and `*replay.Player` all satisfy, so recorded inputs from [replay](http://nsgo.games/docs/replay/) drive it directly: ```go recording, _ := replay.LoadFile("testdata/session.replay.yaml") p := replay.NewPlayer(recording) for !p.Done() { p.Step() res := rec.Update(p, fighting.FaceRight) // assert on res.Step and res.Moves } ``` The package's own tests record scripted inputs this way and check every motion one step inside and one step outside its window, buffer, charge time, grace and combo gap. --- Source: http://nsgo.games/docs/flow/ # flow `game/flow` holds gameplay control-flow primitives driven exclusively by `game.Loop`'s fixed `dt`: game-clock `Timers`, typed finite state machines (`Machine[S]`), hierarchical state machines (`HSM[S]`), composable step sequences (`Seq`, `Parallel`, `Race`), and a zero-global-state typed event `Bus`. ```go import "github.com/nsgo-dev/game/pkg/flow" ``` Nothing in `flow` reads the wall clock, spawns goroutines, or holds package-level state — every primitive pauses with your loop, replays deterministically, and isolates cleanly per scene. ## Game-clock Timers `Timers` schedules one-shot (`After`) and drift-free repeating (`Every`) callbacks on the game clock. Its zero value is ready to use: ```go var timers flow.Timers // Fire once after 2 seconds of game time invuln := timers.After(2*time.Second, func() { player.Invulnerable = false }) // Repeat every 500ms, carrying overshoot so periods never drift spawner := timers.Every(500*time.Millisecond, spawnWave) // Inside Loop.Update: timers.Update(dt) ``` Pause timers during menus or hit-stop with `timers.SetPaused(true)` (or `timers.Paused = true`), inspect remaining time with `invuln.Remaining()` / `invuln.Active()`, cancel with `spawner.Cancel()`, or cancel all with `timers.Clear()`. ## Finite state machines (`Machine[S]`) `Machine[S]` models character, boss, or match states keyed by any comparable type `S`: ```go type HeroState int const ( StateIdle HeroState = iota StateRun StateHurt ) fsm := flow.NewMachine(StateIdle) fsm.AddState(StateIdle, flow.State{ Enter: func() { playAnim("idle") }, Update: func(dt time.Duration) { recoverStamina(dt) }, }) fsm.AddState(StateRun, flow.State{ Enter: func() { playAnim("run") }, Update: func(dt time.Duration) { moveHero(dt) }, Exit: func() { stopFootsteps() }, }) fsm.AddState(StateHurt, flow.State{ Enter: func() { knockback() }, }) fsm.AddTransition(StateIdle, StateRun, func() bool { return moveSpeed > 0 }) fsm.AddTransition(StateRun, StateIdle, func() bool { return moveSpeed == 0 }) fsm.AddAnyTransition(StateHurt, func() bool { return hitThisStep }) fsm.AddTransition(StateHurt, StateIdle, func() bool { return fsm.TimeInState() >= 400*time.Millisecond }) // Inside Loop.Update: fsm.Update(dt) ``` - `Update(dt)` starts the machine on its first call (or call `fsm.Start()` explicitly), evaluates transitions in declaration order (taking at most one per step), advances `TimeInState()`, and runs the active state's `Update`. - Force an immediate switch with `fsm.SetState(to)`. Inspect `fsm.Current()`, `fsm.Previous()`, `fsm.TimeInState()`, `fsm.Started()`, and `fsm.Step()`. - **Save and restore**: `snap := fsm.Snapshot()` returns a plain `MachineSnapshot[S]` struct (`Version`, `Current`, `Previous`, `TimeInState`, `Started`) that marshals cleanly to YAML and JSON. `fsm.Restore(snap)` validates that `Current` (and any non-zero `Previous`) belongs to the machine before replacing its state, refuses unknown states or invalid timings with `ErrInvalidSnapshot` without mutating the machine, and never runs `Exit` or `Enter` hooks. - **Bounded transition history**: `Machine[S]` keeps the most recent `DefaultHistoryLimit` (32) transitions in a fixed ring buffer (`TransitionRecord[S]{From, To, Step, Transition}`), tunable with `SetHistoryLimit(n)` (`0` disables recording) and cleared with `ClearHistory()`. Label transitions with `AddNamedTransition` / `AddNamedAnyTransition` (unnamed transitions default to `"from->to"` / `"*->to"`, and `SetState` records `"SetState"`). Read history with `History()` or zero-allocation `HistoryInto(dst)`. - **Inspection and `statedump` formatting**: every `*Machine[S]` implements the type-erased `MachineInspector` interface (`Inspect() MachineInspection`, `FormatState() string`) so you can pass any machine to [`game/pkg/tooling/gamedebug`](http://nsgo.games/docs/gamedebug/)'s AI panel or record `fsm.FormatState()` in [`statedump`](http://nsgo.games/docs/statedump/) `Values` to diff transitions between runs. ## Hierarchical state machines (`HSM[S]`) When character or enemy logic outgrows a flat machine, `HSM[S]` nests child machines inside parent states so shared interrupts (such as `stunned` or `dead`) apply across every descendant without duplicating transitions: ```go type EnemyState string const ( StatePatrol EnemyState = "patrol" StateCombat EnemyState = "combat" StateApproach EnemyState = "approach" StateAttack EnemyState = "attack" StateRecover EnemyState = "recover" StateStunned EnemyState = "stunned" ) type StunHit struct{ Poise float64 } combat := flow.NewHSM(StateApproach) combat.SetHistory(true) // re-entering combat resumes its last active sub-state combat.AddState(StateApproach, flow.State{Enter: func() { playAnim("approach") }}) combat.AddState(StateAttack, flow.State{Enter: func() { playAnim("attack") }}) combat.AddState(StateRecover, flow.State{Enter: func() { playAnim("recover") }}) combat.AddTransition(StateApproach, StateAttack, func() bool { return inRange }) combat.AddEventTransition(StateAttack, StateRecover, "attack_done") combat.AddTransition(StateRecover, StateApproach, func() bool { return combat.TimeInState() >= 400*time.Millisecond }) enemy := flow.NewHSM(StatePatrol) enemy.AddState(StatePatrol, flow.State{Enter: func() { playAnim("patrol") }}) enemy.AddState(StateCombat, flow.State{ Enter: func() { drawWeapon() }, Exit: func() { sheatheWeapon() }, }) enemy.AddChild(StateCombat, combat) enemy.AddState(StateStunned, flow.State{Enter: func() { playAnim("stunned") }}) enemy.AddTransition(StatePatrol, StateCombat, func() bool { return spotted }) flow.OnEvent(enemy, StateCombat, StateStunned, func(e StunHit) bool { return e.Poise >= 15 }) enemy.AddTransition(StateStunned, StateCombat, func() bool { return enemy.TimeInState() >= 800*time.Millisecond }) // Optional: forward typed events from a flow.Bus into the HSM queue. unsub := flow.BindBus[StunHit](enemy, &bus) defer unsub() // Inside Loop.Update: enemy.Update(dt) ``` - **Outside-in `Enter` / inside-out `Exit`**: entering `StateCombat` runs `combat`'s `Enter` before its active child's `Enter`; leaving `StateCombat` runs the child's `Exit` before `combat`'s `Exit`. Cross-branch transitions exit up to the lowest common ancestor and enter down to the target leaf. - **Innermost-first transitions**: transitions declared on a parent apply while any descendant is active, with the innermost active state checked first so child states can override parent transitions. - **Deterministic events**: send events with `enemy.Send(ev)` or subscribe a `flow.Bus` event type with `flow.BindBus[E](enemy, &bus)`. Register value-matched transitions with `AddEventTransition` / `AddAnyEventTransition` or typed payload transitions with `flow.OnEvent` / `flow.OnAnyEvent`. Queued events are processed once per `Update` step in FIFO send order; events sent during callbacks wait for the next step. - **Shallow history**: call `child.SetHistory(true)` so re-entering its parent resumes the last active direct child instead of `initial` (reset with `ClearHistory()`). - **Path inspection**: `enemy.Current()` returns the active path from root to leaf (`[]S`), `enemy.Leaf()` returns the innermost active state, `enemy.In(state)` checks whether a state is anywhere on the active path, and `enemy.TimeIn(state)` reports elapsed game time in an active state. ## Step sequences (`Runner`, `Seq`, `Parallel`, `Race`) Compose cutscenes, attack patterns, and scripted encounters without goroutines using `Runner` and `Step` combinators: ```go var runner flow.Runner bossIntro := flow.Seq( flow.Do(func() { lockPlayerInput(true) }), flow.Parallel( flow.Wait(600*time.Millisecond), flow.While(func() bool { return doorOpen < 1 }, func(dt time.Duration) { doorOpen += float32(dt.Seconds()) * 2 }), ), flow.Race( flow.WaitUntil(func() bool { return actions.JustPressed("skip") }), flow.Seq( flow.Do(func() { showBossTitle() }), flow.Wait(2*time.Second), ), ), flow.Do(func() { lockPlayerInput(false) }), ) handle := runner.Start(bossIntro) // Inside Loop.Update: runner.Update(dt) ``` Built-in `Step` combinators: | Combinator | Behavior | | --- | --- | | `Do(fn)` | Calls `fn` once and finishes immediately, passing all remaining `dt` onward. | | `Wait(d)` | Waits for `d` of game time to elapse. | | `WaitUntil(cond)` | Finishes on the first step where `cond()` returns `true`. | | `While(cond, update)` | Runs `update(dt)` each step while `cond()` is `true`. | | `Seq(steps...)` | Runs steps in order, carrying leftover `dt` from a finished step into the next on the same tick. | | `Parallel(steps...)` | Steps all branches each tick until every branch finishes. | | `Race(steps...)` | Steps branches in order until the first finishes, then cancels the rest. | | `Repeat(n, makeStep)` | Repeats the step from `makeStep()` `n` times sequentially. | | `Loop(makeStep)` | Repeats indefinitely until its `Handle` or enclosing `Race` cancels it. | Cancel an in-flight sequence cleanly with `handle.Cancel()` (or `runner.Clear()`), and check `handle.Done()`. ## Typed event Bus `Bus` decouples systems inside a scene without globals or string keys: ```go type EnemyDefeated struct { Kind string Score int } var bus flow.Bus unsub := flow.Subscribe(&bus, func(ev EnemyDefeated) { score += ev.Score }) defer unsub() // Immediate synchronous delivery in subscription order: flow.Publish(&bus, EnemyDefeated{Kind: "slime", Score: 50}) // Or buffer events during physics/collision and flush once per step: flow.Enqueue(&bus, EnemyDefeated{Kind: "bat", Score: 100}) bus.Flush() ``` Use `flow.SubscribeOnce(&bus, fn)` for one-shot listeners, and `bus.Clear()` when tearing down a scene. Subscribing or unsubscribing inside a handler never skips remaining listeners for the event in flight. ## Shared variables and switches (`Vars` and `vars.yaml`) Treat `Vars` as the authoritative project state. `SetFromExpr` accepts expression values only when the declaration's kind and bounds permit them, and returns `ErrUndeclaredVar` for names absent from `vars.yaml`. Register `OnChange` listeners when UI, quests, or scene rules need synchronous updates, and use `Snapshot`/`Restore` for save checkpoints. Declare project-wide switches (`bool`) and typed variables (`int`, `float`, `string`) once in a versioned `vars.yaml` (or `*.vars.yaml`) file so dialogue scripts, quests, scene rules, saves, and the editor's remote inspector share a single source of truth: ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/vars.v1.json version: 1 vars: - name: bridge_repaired kind: bool doc: True once the east bridge has been repaired. - name: gold kind: int default: 50 min: 0 max: 9999 doc: Player gold coins. - name: mira_affinity kind: float default: 0.5 min: 0 max: 1 doc: Relationship score with Mira. - name: hero_name kind: string default: Aria doc: Display name of the protagonist. ``` Load declarations with `flow.LoadVarsFS(fsys, "vars.yaml")` (or `flow.ParseVars(data)`) and construct a runtime store with `flow.NewVars(doc)`: ```go doc, err := flow.LoadVarsFS(assetsFS, flow.VarsFileName) if err != nil { return err } vars, err := flow.NewVars(doc) if err != nil { return err } // Observe mutations synchronously in registration order (empty name observes all variables): unsub := vars.OnChange("bridge_repaired", func(ch flow.VarChange) { unlockEastBridge(ch.New.(bool)) }) defer unsub() // Typed reads and writes enforce declared kinds and [min, max] bounds: _ = vars.SetInt("gold", 120) gold, _ := vars.Int("gold") // Scoped per-object self variables for instance state ("this chest was opened"): vars.Self("chest_01").SetBool("opened", true) opened := vars.Self("chest_01").Bool("opened") ``` - **Shared by dialogue**: pass `dialogue.Options{Vars: vars}` to `dialogue.NewRunner` ([dialogue](http://nsgo.games/docs/dialogue/)) so `<>`, choice guards, `{expr}` interpolations, and `<>` read and write the shared store directly instead of a private map. When `Vars` is set, `<>` and `<>` of an undeclared name return `flow.ErrUndeclaredVar`, and writes enforce declared kinds and bounds. - **Save and restore**: `snap := vars.Snapshot()` returns a plain `flow.VarsSnapshot` (`Version`, `Vars`, `Self`) that marshals cleanly to JSON or YAML for `save.Store`. `vars.Restore(snap)` validates versions, names, kinds, and bounds atomically without invoking `OnChange` listeners, leaving the store unchanged on error (`flow.ErrInvalidSnapshot`). Variables added to `vars.yaml` after an older save keep their declared defaults on restore, and a zero `VarsSnapshot` resets to defaults and clears self variables. - **Static validation**: `go tool game check` validates every `vars.yaml` / `*.vars.yaml` file and checks every `$name` and `{name}` variable reference in `.yarn` dialogue scripts against the project's declarations, reporting undeclared names with their exact file and line. - **Live remote inspection**: pass `Vars: vars` (or `VarsFunc`) to `mcp.Config` to expose `game_vars_list`, `game_var_get`, and `game_var_set`; the editor's Remote Inspector lists declared variables with live editable controls alongside active per-object self variables. ## Map events (`ParseMapEvent`, `EventRunner`) A map event is a chest, sign, door or one-time trigger written as YAML instead of Go: an ordered list of pages, each with conditions, a trigger and a list of commands. ```yaml version: 1 pages: - when: self: opened: false trigger: action commands: - say: text: chest.found_potion - wait: seconds: 0.5 - self: name: opened value: true - when: self: opened: true trigger: action ``` - **Format**: `flow.ParseMapEvent` reads version 1 (`flow.MapEventVersion`) and `flow.EncodeMapEvent` writes its canonical form. Unknown fields and commands, a list entry with no command or more than one, an unknown trigger, a negative, infinite or NaN wait, and a `set` or `self` without a name are refused at load with a `loaderr.Error` that names the field and line. A page without `trigger` reads as `action`. - **Pages**: `doc.ActivePage(self, switches, variables)` returns the last page whose `when` conditions all hold, or -1 when none does: every `self` and `switches` entry equals its value, and every `variables` entry is at least its value. A missing name reads as false or 0. - **Triggers**: a page's trigger is `action`, `touch`, `autorun` or `parallel` (`flow.TriggerAction` and so on). The runner does not watch input or movement; the game starts the page when its trigger fires, for example `action` when the player faces the event and presses the button. - **Commands**: `say` passes its text, usually a localization key, to `EventRunner.Say`; `wait` pauses for game seconds; `set` writes an integer to `EventRunner.Variables`; `self` writes a self switch to `EventRunner.Self`. - **Running**: `flow.NewEventRunner(doc)` is idle until `Start(page)`. `Update(dt)` on each fixed step runs commands until one waits or the page ends, never blocking the loop, and returns true once the runner is idle; time left over when a wait ends carries into the commands after it. - **Saving mid-event**: `Snapshot` returns a `flow.EventSnapshot` (the page, -1 when idle, the next command, the time left on a wait, and the self switches and variables) that marshals to YAML or JSON. `Restore` refuses a snapshot that does not fit the runner's document with `flow.ErrInvalidEventSnapshot` and leaves the runner unchanged. The commands are a first set. Choices, conditional branches, item and transfer commands, game-registered commands and integration with `Vars` are not part of the format yet. --- Source: http://nsgo.games/docs/fog/ # fog `game/fog` tracks fog of war for strategy games on orthogonal, isometric, staggered, and hexagonal tile grids: which cells each team can see now, which it has explored before, and which it has never seen. It draws the fog aligned to the tilemap's projection and saves it with the rest of a game. ```go import "github.com/nsgo-dev/game/pkg/fog" ``` ## Teams, sources and states A `Fog` covers a grid of cells. Each team (`fog.Team`, any `int`) sees through its vision sources: units, buildings or wards, each with a cell and a radius in cells. To each team a cell is one of three `State`s: | State | Meaning | Drawn as | | --- | --- | --- | | `Unseen` | The team has never seen the cell. | `Style.Unseen`, opaque black by default | | `Explored` | The team saw the cell before but cannot see it now. | `Style.Explored`, half-transparent black by default | | `Visible` | One of the team's sources sees the cell now. | Uncovered | ```go f := fog.NewFromTilemap(level, tilemap.TileSolid) // walls block sight scout := f.AddSource(fog.Source{Team: player, Col: 4, Row: 6, Radius: 7}) f.Update() ``` - `NewFromTilemap(m, mask)` copies the map's size, tile size, and projection (`Orientation`, `StaggerAxis`, `StaggerIndex`, `HexSideLength`), and makes every cell whose tilemap flags include a bit of `mask` opaque. `New(width, height, tileWidth, tileHeight)` starts from an empty orthogonal grid (it panics on a negative size, a grid with exactly one zero size, or more than `MaxCells` cells); set `Orientation` and stagger fields if building a non-orthogonal fog without a tilemap, and use `SetOpaque` to change one cell later, such as when a door opens. - On orthogonal and isometric grids, a cell `dx` columns and `dy` rows from a source is in range when `dx*dx+dy*dy <= Radius*Radius+Radius`, which rounds the disc (staggered grids evaluate the same rounded disc in their underlying diamond lattice). On hexagonal grids, a cell is in range when its `HexDistance` from the source is at most `Radius`. Radius 0 sees only the source's own cell, and a source outside the grid sees nothing. - Opaque cells block sight by symmetric shadowcasting with exact integer slopes (4 quadrants on orthogonal/isometric/staggered grids, 6 axial sextants on hexagonal grids): a floor cell A sees a floor cell B exactly when B sees A, and the result never depends on floating-point rounding, so every client in a lockstep match computes the same fog. An opaque cell is itself seen when sight reaches it, so walls show at the edge of vision. - Sources of the same team share vision; other teams' sources reveal nothing to it. ## Updating as units move Move sources during a fixed step and call `Update` once before reading or drawing the fog: ```go loop.Update = func(dt time.Duration) { moveUnits(dt) for _, u := range units { f.MoveTo(u.Vision, u.Pos) // or f.Move(id, col, row) } f.Update() } ``` - `Update` recomputes only the teams whose sources or opaque cells changed since the last call, adds what they see to what they have explored, and reports whether any team's fog changed. - `SetSource` changes a source's team, cell or radius at once; `RemoveSource` drops it when a unit dies, and the team keeps what it explored. - `State`, `Visible` and `Explored` answer for a cell, and `VisibleAt(team, p)` for a world point, such as to hide enemy units in the fog. `CellAt(p)` turns a world point into a cell using the fog's `TileWidth`, `TileHeight`, and projection (`Orientation`, `StaggerAxis`, `StaggerIndex`, `HexSideLength`), matching `tilemap.Tilemap.WorldToTile`. - `Explore`, `ExploreRect` and `ExploreAll` mark cells explored without making them visible (a scouting report or a revealed landmark), `Forget` clears everything a team explored except what it sees now, and `ExploredCount` counts its explored cells. - `Revision(team)` grows whenever a team's visible or explored cells change, and every team gets a fresh one when the fog is loaded, so a minimap or a cached fog image redraws only when it differs. Revisions come from one counter shared by every fog in the program, so a fog loaded in place of another, even through `save.Store.Load`, never repeats a revision a cache has already seen. ## Drawing over the map Draw the fog after the tilemap and the units, under the same camera transform: ```go d.Save() cam.Apply(d) level.Draw(d, cam) drawUnits(d) f.Draw(d, player, cam, fog.DefaultStyle()) d.Restore() ``` `Draw` fills one path over the unseen cells and one over the explored cells and leaves visible cells uncovered: horizontal runs of rectangles on orthogonal grids, aligned tile diamonds on isometric and staggered grids, and aligned pointy-top or flat-top hexagons on hexagonal grids matching `tilemap.Tilemap`'s projection. Like `Tilemap.Draw`, it uses the camera only to skip cells outside `cam.VisibleBounds()`, and a nil camera draws the whole grid. A `Style` color with zero alpha leaves those cells uncovered, such as `fog.Style{Unseen: core.RGB(0x000000)}` for a game without remembered terrain. ## Saving A `Fog` marshals to versioned JSON text, so it goes into a `save.Store` slot inside the game's own state: ```go type saved struct { Units []unitSave `json:"units"` // each unit keeps its fog.SourceID Fog *fog.Fog `json:"fog"` } store.Save("slot1", saved{Units: units, Fog: f}) var s saved store.Load("slot1", &s) // s.Fog sees and has explored exactly what f did ``` ```json {"version":1,"width":3,"height":2,"tileWidth":8,"tileHeight":8,"opaque":[".#.","..."],"nextSource":2,"sources":[{"id":1,"team":2,"col":2,"row":1,"radius":1},{"id":2,"team":1,"col":0,"row":0,"radius":0}],"teams":[{"team":1,"explored":["#..","..."]},{"team":2,"explored":[".##",".##"]}]} ``` - The snapshot holds the grid and tile size, optional projection fields (`orientation`, `staggerAxis`, `staggerIndex`, `hexSideLength`, omitted on orthogonal grids), the opaque cells, the sources with their IDs, and each team's explored cells as rows of `.` and `#`, one string per grid row, so a person reading the save sees each team's explored map. Visible cells are not stored: loading recomputes them from the sources and opaque cells. - The same fog always writes the same bytes: fields in a fixed order, sources by ID, teams in increasing order, and no timestamps. Loading and saving again changes nothing. - Loading keeps source IDs and the next ID to hand out, so a unit's saved `fog.SourceID` still moves its source. - Loading refuses unknown fields, a missing version, a newer version (`ErrFutureVersion`), rows that disagree with the grid size, sources or teams out of order or repeated, a source ID of 0 or above `nextSource`, a source whose team has no explored grid, grids larger than `MaxCells`, and grids with exactly one zero size; every other error wraps `ErrInvalidSnapshot`, and a refused snapshot leaves the fog unchanged. --- Source: http://nsgo.games/docs/formats/ # File Formats Every file a game made with these packages reads or writes, with the names its files go by, the version it declares, the Go functions that read and write it, the guide that describes its fields and an example, so a person or an AI can edit one without reading the code. The files a game's author writes are YAML, apart from those under JSON files and Other tools' formats below. The tests check every example on this page: a YAML example is in its format's canonical form, the bytes its encoder writes, and loads and saves back unchanged, so none shows a key the format refuses or a layout it would rewrite; a JSON or Yarn example loads with the format's reader. ## What every YAML format does - **A version.** The document's top-level `version` key, an integer, says which version of the format it is in; a mod manifest calls it `manifestVersion`. A file without it, with `version: 0` or with a version newer than the code reads is refused. - **Strict keys.** A key the format does not define is refused, as are a second YAML document in the file and a key given twice, with an error that names the file, line and field and says how to fix it ([Errors](http://nsgo.games/docs/errors/)). - **One canonical form.** Saving writes the keys in a fixed order, sorts what has no order of its own and writes no timestamp or random ID, so the same value always gives the same bytes and a file in that form loads and saves back unchanged. The first save of a hand-written file drops its comments and rewrites its layout into that form; every save after that changes only what changed. - **Schemas.** Scene files and import settings sidecars have published JSON Schemas, and a data table's schema is generated from its row type, so an editor completes and checks them as they are written ([Schemas for YAML files](http://nsgo.games/docs/schemas/)). ## Project and assets ### Project file | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `game.yaml` at the project's root | `version: 1` | `project.Parse`, `project.Encode` | [Project File](http://nsgo.games/docs/project/); schema `https://nsgo.games/schemas/game.v1.json` | ```yaml version: 1 name: Cave Run id: dev.nsgo.game.examples.caverun appVersion: 0.1.0 window: title: Cave Run width: 960 height: 540 display: width: 320 height: 180 mode: fit autoload: mainScene: title scenes: - name: title path: scenes/title.scene.yaml ``` ### Game brief | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `brief.yaml` at the project's root | `version: 1` | `project.ParseBrief`, `project.EncodeBrief` | [Editor](http://nsgo.games/docs/editor/#game-brief-and-project-rules-1026); schema `https://nsgo.games/schemas/brief.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/brief.v1.json version: 1 pitch: 'A short, tense dungeon platformer: a knight with one sword and three hearts dives through five floors, each ending in a door that only opens once its lever is found.' genre: [2D platformer, action] tags: [dungeon, pixel-art] platforms: [desktop, 'phones, touch', web] artDirection: 16 px pixel art, 4-colour shading, cold stone with warm torch light. No outlines on tiles; 1 px dark outline on characters. feel: summary: Snappy, forgiving jumps (coyote time). A first-time player clears floor 1 in under a minute and dies 2–4 times on floor 3. targets: - metric: median_time scene: floor_01 summary: first-time player clears floor 1 in under a minute unit: s max: 60 - metric: deaths scene: floor_03 summary: 2–4 deaths on floor 3 min: 2 max: 4 ``` The brief's art direction is also the shared style anchor for editor asset generation. Generated image and sound prompts append the deterministic style summary before the kind-specific framing constraint, so separate generator calls retain the same direction. Reference-byte integrations can use `editor.AssetReferenceHash` to record the lowercase SHA-256 digest of the exact bytes submitted. ### Assets plan | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `assets.plan.yaml` at the project's root | `version: 1` | `project.ParseAssetsPlan`, `project.EncodeAssetsPlan` | Approval-scoped batches of pending image, sound, model and animation work; schema `https://nsgo.games/schemas/assets-plan.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/assets-plan.v1.json version: 1 batches: - id: characters approval: approved-by-ana assets: - id: hero kind: model target: art/hero.glb priority: high placeholder: art/hero-placeholder.png notes: full-body rig ``` ### Template manifest | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `template.yaml` in a project template's directory, read by `game new` and the editor | `version: 1` | `templatemeta.Parse`, `templatemeta.Encode` | [Templates](http://nsgo.games/docs/templates/#template-manifests); schema `https://nsgo.games/schemas/template.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/template.v1.json version: 1 id: puzzle2d title: en: Puzzle zh: 解谜 summary: en: 'A 2D grid puzzle: slide a spark to light every lamp' genre: puzzle dimension: 2d orientation: portrait players: min: 1 max: 1 local: true inputs: [keyboard, touch] platforms: [desktop, web, mobile] controls: en: Arrow keys or swipes. tags: [puzzle, grid] ``` ### Editor settings | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Per-user `editor.yaml` under the user config directory (`editor.DefaultSettingsPath`), outside any project | `version: 1` | `editor.ParseEditorSettings`, `editor.EncodeEditorSettings` | [Editor](http://nsgo.games/docs/editor/#language-and-appearance-settings-921); schema `https://nsgo.games/schemas/editor-settings.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/editor-settings.v1.json version: 1 language: system appearance: system autoSave: true viewportOverlays: - collision_shapes - connections - navigation - triggers overlayLegend: - added - agent - changed - problem - removed - selection shortcuts: view.frame: g seenTips: - first_review.ask_selection - first_review.hold_b - first_review.keep_revert agent: builtInProvider: Anthropic API builtInFormat: anthropic builtInEndpoint: http://127.0.0.1:8080/v1/messages builtInModel: local-main builtInFastModel: local-fast tools: game_delete_file: false mcpServers: - name: nsgo-game title: Running game · nsgo dev description: inspect and drive the live game command: go args: - tool - nsgo - mcp enabled: true weeklyRequestLimit: 300 weeklySpendLimitUSD: 20 privacy: sceneAndData: true viewportImages: true goSource: false artAndAudio: false approvedAutomations: - project: /home/you/games/dungeon-run sha256: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 ``` ### Local agent table | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Per-user `agents.yaml` beside `editor.yaml` under the user config directory (`editor.DefaultAgentDefinitionsPath`), outside any project | `version: 1` | `editor.ParseAgentDefinitions`, `editor.EncodeAgentDefinitions` | [Editor](http://nsgo.games/docs/editor/#local-agents-over-the-agent-client-protocol-1935) | Each row of `agents` is one local agent: `id` (lowercase letters, digits, `-` and `_`), `label`, `bin` (an executable name or absolute path), `aliases` (other names matched against a connected MCP client's name), `adapter` (`acp`, `claude` or `codex`), `acp_args` (required for `acp`: the arguments that start the agent as an ACP server), `acp_fallbacks` (argument sets tried in order when the agent fails before its prompt is sent), `login_args`, `model_flag` (a flag that picks the model at launch) and `explicit_only` (when `true`, the composer runs the row only when a request names it and never tries it as the first installed agent). The rows are saved in the order they are written, which is the order the composer tries them in; a row whose `id` is a built-in row's replaces it, `explicit_only` included. ```yaml version: 1 agents: - id: gemini label: Gemini CLI bin: /opt/gemini/bin/gemini aliases: - gemini-cli adapter: acp acp_args: - --acp acp_fallbacks: - - --experimental-acp model_flag: --model - id: goose label: Goose bin: goose adapter: acp acp_args: - acp login_args: - configure explicit_only: true - id: claude label: Claude Code bin: /usr/local/bin/claude adapter: claude ``` ### Editor MCP permissions | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `permissions.yaml` beside `game.yaml` (tracked in Git and shared across the team) | `version: 1` | `editor.ParsePermissions`, `editor.EncodePermissions` | [Editor](http://nsgo.games/docs/editor/#permissions-and-mcp-enforcement-1010); schema `https://nsgo.games/schemas/permissions.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/permissions.v1.json version: 1 profile: balanced rules: - action: edit patterns: - scenes/** - prefabs/** - data/** decision: allow - action: run patterns: - game check - playtests decision: allow - action: edit patterns: - game.yaml - brief.yaml decision: ask - action: code patterns: - '**/*.go' decision: ask - action: create patterns: - '**' decision: ask - action: delete patterns: - '**' decision: deny - action: run patterns: - shell decision: deny ``` ### Agent background task thread | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `.nsgo/threads/.thread.yaml` under a project root (default `default.thread.yaml`) | `version: 1` | `editor.ParseAgentThread`, `editor.EncodeAgentThread` | [Editor](http://nsgo.games/docs/editor/#background-task-list-with-queued-and-parallel-agent-requests-1022) | A task can store the selection from the moment it was sent. The optional lists `selectionIds` and `selectionNames` are in selection order, and `primarySelectionId` identifies the primary object. The pin belongs to the task's `scene`. ```yaml version: 1 id: default scene: scenes/level_01.scene.yaml tasks: - id: task-1 number: 1 title: slime_02 jumps the gap at x 360 source: you startMode: queue state: running scene: scenes/level_01.scene.yaml selectionIds: - slime_02 selectionNames: - Slime 02 primarySelectionId: slime_02 stepSummary: placing the jump arc editingObjects: - slime_02 - id: task-2 number: 2 title: Coin pickup sound a little higher source: you startMode: queue state: queued startsAfterTaskId: task-1 ``` ### Editor automations | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `automations.yaml` at the project's root beside `game.yaml` | `version: 1` | `editor.ParseAutomations`, `editor.EncodeAutomations` | [Editor](http://nsgo.games/docs/editor/#agent-automations-1029); schema `https://nsgo.games/schemas/automations.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/automations.v1.json version: 1 automations: - id: level-check name: A level file changes enabled: true trigger: event: file_changed glob: scenes/level_*.scene.yaml instruction: runs game check and 5 playtests, reports only problems - id: review-brief name: You keep a review enabled: true trigger: event: review_kept instruction: updates the brief's open questions if the change answers one - id: new-prefab-example name: A new prefab is added enabled: true trigger: event: file_added kind: prefab instruction: writes its example scene and a test - id: before-export-mobile name: Before export enabled: false trigger: event: before_export instruction: checks frame time and memory on a low-end phone profile - id: nightly-balance name: Every night enabled: false trigger: event: daily time: "02:00" instruction: plays all floors 50 times and leaves a balance report ``` ### Import settings sidecar | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `.import.yaml` beside an image, sound, font or model, such as `hero.png.import.yaml` | `version: 1` | `importsettings.Parse`, `importsettings.Encode` | [Command Line](http://nsgo.games/docs/cli/#assets); schema `https://nsgo.games/schemas/import.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/import.v1.json version: 1 image: filter: nearest slice: width: 16 height: 16 count: 6 pivot: default: [0.5, 1] cells: - cell: 2 pivot: [0.25, 0.75] credit: author: Kenney license: CC0-1.0 source: https://kenney.nl/assets/kenney-fonts ``` An image's `format` is any of `project.TextureFormats` (`rgba8`, `bc1`, `bc3`, `bc7`, `etc2`, `etc2-rgba`, `astc4x4`, `uastc`), `maxSize` is a longest side from 1 to 16384 pixels (0 keeps the size), and `targets` maps an export platform name to the `filter`, `format`, `maxSize`, `mipmaps` and `srgb` that replace the image's on that platform. A model may list `clips` (each source animation once, renamed or cut into named, non-overlapping frame `slices`, with a `loop` mode), an `fps`, `materials` mapping glTF material names to material files, and `skipNodes`. `Parse` refuses an unknown platform or format, an out-of-range size, an empty or overlapping slice, a clip name used twice and a material path outside the project. These image and model fields are recorded and checked only: `game assets` and `scenemodel` do not apply them yet. ### Generated asset source sidecar | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `.source.yaml` beside a generated image or sound, such as `slime_frost.png.source.yaml` | `version: 1` | `importsettings.ParseAssetSource`, `importsettings.EncodeAssetSource` | [Editor](http://nsgo.games/docs/editor/); schema `https://nsgo.games/schemas/source.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/source.v1.json version: 1 files: - slime_frost.png - slime_frost.json generator: pixel-gen model: pixflux-1 prompt: ice slime, 16 px pixel art, 4-colour shading, 1 px dark outline, facing right seed: 81515 references: - art/characters/slime.png - brief.yaml#art license: pixellab-commercial-1.2 commercialUse: true approvedBy: kim sha256: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef derivedFrom: asset: art/characters/slime.png sha256: fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210 ``` `files` names each generated output once. `sha256` identifies the picked primary asset, while `derivedFrom` identifies the parent candidate bytes when a variation or refinement was made. ### Project index Merge-game chain data can use `pkg/mergegame`'s versioned YAML document. It keeps each chain's ordered tiers and values canonical and rejects unknown fields, so a template can share the format across tools and runtime. | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `game.index.yaml` beside `game.yaml`, kept by `game index`, `game mv` and the editor | `version: 1` | `refs.ParseIndex`, `refs.EncodeIndex` | [Stable references](http://nsgo.games/docs/project/#stable-references) | ```yaml # The stable IDs of this project's files, kept by game index, game mv and the editor. Keep it in version control. version: 1 files: - path: art/hero.png sha256: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 - path: scenes/room.scene.yaml uid: scene00000001 ``` ### Library pack manifest | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `pack.yaml` at the root of an asset or plugin pack | `version: 1` | `library.ParseManifest`, `library.EncodeManifest` | [Asset and Plugin Library](http://nsgo.games/docs/library/) | ```yaml version: 1 name: coins kind: asset packVersion: 1.0.0 description: A spinning coin. license: CC0-1.0 files: - coin.png autoload: resources: - name: coin path: coin.png ``` ### Library index | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `index.yaml` at the root of a pack library | `version: 1` | `library.ParseIndex`, `library.EncodeIndex` | [Asset and Plugin Library](http://nsgo.games/docs/library/) | ```yaml version: 1 packs: - name: dungeon-tiles kind: asset packVersion: 1.0.0 description: Stone tiles. tags: [2d, tiles] license: CC0-1.0 source: b sha256: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 ``` ### Localized asset manifest | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `assets.yaml` | `version: 1` | `l10n.ParseAssetManifest`, `l10n.EncodeAssetManifest` | [l10n](http://nsgo.games/docs/l10n/) | ```yaml version: 1 base_locale: en assets: ui/title_banner.png: en: ui/title_banner.png zh-Hans: ui/title_banner.zh-Hans.png voice/intro.wav: en: locales/en/voice/intro.wav ja: locales/ja/voice/intro.wav groups: voice: - voice/intro.wav ``` ### Localization string table (YAML) | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | One `.yaml` file per locale, such as `locales/en.yaml` | `version: 1` | `l10n.ParseYAML`, `l10n.EncodeYAML`, `l10n.Catalog.LoadYAML` | [l10n](http://nsgo.games/docs/l10n/) | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/l10n.v1.json version: 1 locale: en strings: hud.score: 'Score: {score}' menu.play: Play menu.quit: Quit plurals: coins: zero: No coins one: '{count} coin' other: '{count} coins' ``` ### Mod manifest | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `mod.yaml` at the root of a mod's directory | `manifestVersion: 1` or `manifestVersion: 2` | `modding.ParseManifest`, `modding.EncodeManifest` | [modding](http://nsgo.games/docs/modding/); schemas `https://nsgo.games/schemas/mod.v1.json`, `https://nsgo.games/schemas/mod.v2.json` | ```yaml manifestVersion: 1 id: com.example.boss-rush name: Boss Rush version: 1.2.0 author: Example Studio description: Spawns a slime every five seconds and shows a HUD badge while the rush runs. entry: mod.tsx gameVersion: '>=0.2.0' capabilities: [readState, spawnEntity, emitEvent, ui] ``` Version 2 adds `optionalDependencies`, `conflicts`, `platforms`, and `contributes` (and allows content-only mods without `entry`): ```yaml manifestVersion: 2 id: com.example.boss-rush name: Boss Rush version: 1.3.0 entry: mod.tsx dependencies: com.example.core: ^1.0.0 optionalDependencies: com.example.music: '>=0.2.0' conflicts: com.example.old-boss: '*' platforms: [linux, macos, windows] contributes: assets: assets scenes: scenes l10n: locales datatables: tables ``` ### Steam Workshop metadata | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `workshop.yaml` beside `mod.yaml` in a mod published to Steam Workshop | `version: 1` | `modding.ParseWorkshopMetadata`, `modding.EncodeWorkshopMetadata` | [modding](http://nsgo.games/docs/modding/) | ```yaml version: 1 appId: 480 publishedFileId: 1001 title: Boss Rush description: Spawns a slime every five seconds. tags: [gameplay, survival] visibility: public preview: preview.png ``` ### Plugin manifest | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `plugin.yaml` at the root of a Go plugin module | `manifestVersion: 1` | `manifest.Parse`, `manifest.ParseFS`, `manifest.Encode` | [Plugins](http://nsgo.games/docs/plugins/) | ```yaml manifestVersion: 1 name: healthkit module: example.com/healthkit description: Health component, ward panel and admit tool license: MIT authors: [Jane Doe] repository: https://github.com/example/healthkit engine: '>=0.4.0 <0.5.0' api: 1 platforms: [all] entries: runtime: example.com/healthkit/health editor: example.com/healthkit/healtheditor cli: - name: healthkit package: example.com/healthkit/cmd/game-healthkit requires: example.com/navkit: ^0.3.0 conflicts: [example.com/oldhealth] contributes: components: [health] editor: panels: [ward] tools: [admit] commands: [heal-all] agentTools: [plugin.healthkit.heal_all] ``` ### 3D shader material | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.material.yaml`, hot-reloaded in `game dev` | `version: 1` | `hotreload.ParseMaterial`, `hotreload.EncodeMaterial` | [render3d](http://nsgo.games/docs/render3d/) | ```yaml version: 1 name: Crate shader: shaders/lit.wgsl blend: opaque cull: back frontFace: ccw depthCompare: less scalars: roughness: 0.4 colors: tint: '#d9c6a5' textures: albedo: textures/crate.png ``` ### Voxel world | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.voxel.yaml` | `version: 1` | `voxel.Parse`, `voxel.Encode` | [voxel](http://nsgo.games/docs/voxel/); schema `https://nsgo.games/schemas/voxel.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/voxel.v1.json version: 1 name: hill chunkSize: 4 voxelSize: 1 palette: - id: 1 name: stone chunks: - x: 0 "y": 0 z: 0 runs: - 1*4 - 0*60 ``` ### 3D grid map | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.gridmap.yaml` | `version: 1` | `world3d.ParseGridMap`, `world3d.EncodeGridMap`, `world3d.LoadGridMapFS` | [world3d](http://nsgo.games/docs/world3d/); schema `https://nsgo.games/schemas/gridmap.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/gridmap.v1.json version: 1 name: Stone Keep cellSize: - 2 - 2 - 2 meshLibrary: models/dungeon_tiles.gltf boxes: - min: - 0 - 0 - 0 max: - 4 - 0 - 4 tile: stone_floor cells: - at: - 0 - 1 - 0 tile: stone_pillar - at: - 4 - 1 - 0 tile: stone_pillar orientation: 1 ``` ### Terrain definition | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.terrain.yaml` | `version: 1` | `world3d.ParseTerrain`, `world3d.EncodeTerrain`, `world3d.LoadTerrainFS` | [world3d](http://nsgo.games/docs/world3d/); schema `https://nsgo.games/schemas/terrain.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/terrain.v1.json version: 1 name: Alpine Valley heightmap: terrain/alpine_height.png cellSize: 2 heightScale: 40 splatMaps: - terrain/alpine_splat0.png heightBlendContrast: 0.65 triplanar: enabled: true slopeThreshold: 0.7 slopeBlend: 0.15 sharpness: 4 scale: 0.25 layers: - name: grass albedo: textures/grass_albedo.png normal: textures/grass_normal.png height: textures/grass_height.png roughness: 0.85 uvScale: - 16 - 16 - name: dirt albedo: textures/dirt_albedo.png normal: textures/dirt_normal.png height: textures/dirt_height.png roughness: 0.9 uvScale: - 12 - 12 heightBias: -0.05 - name: rock albedo: textures/rock_albedo.png normal: textures/rock_normal.png height: textures/rock_height.png roughness: 0.8 uvScale: - 8 - 8 heightBias: 0.1 - name: snow albedo: textures/snow_albedo.png normal: textures/snow_normal.png roughness: 0.5 uvScale: - 10 - 10 heightBias: 0.05 ``` ### 3D foliage layers | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.foliage.yaml` | `version: 1` | `world3d.ParseFoliage`, `world3d.EncodeFoliage`, `world3d.LoadFoliageFS` | [world3d](http://nsgo.games/docs/world3d/); schema `https://nsgo.games/schemas/foliage.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/foliage.v1.json version: 1 name: Alpine Meadow terrain: terrain/alpine.terrain.yaml layers: - name: grass mesh: models/grass_clump.glb material: materials/grass.material.yaml density: 1.5 minScale: 0.8 maxScale: 1.3 alignToNormal: 0.6 maxSlopeDeg: 35 baseMaxDistance: 80 seed: 42 - name: pine_tree mesh: models/pine_tree.glb densityMap: terrain/forest_density.png spacing: 4 minScale: 0.85 maxScale: 1.25 maxSlopeDeg: 28 minHeight: 2 maxHeight: 32 baseMaxDistance: 160 boundingRadius: 3.5 seed: 108 ``` ### Store screenshot plan | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `store/capture.yaml`, read by `go tool game capture` | `version: 1` | `storecapture.Decode`, `storecapture.LoadFile`, `Plan.Encode` | [Store screenshot plan](http://nsgo.games/docs/shipping/#store-screenshot-plan) | ```yaml version: 1 shots: - name: title scene: scenes/title.scene.yaml frame: 30 output: title sizes: - preset: itch_cover - preset: minigame_share - name: boss scene: scenes/boss.scene.yaml recording: recordings/boss.replay.yaml time: 2.5 output: play/boss sizes: - preset: google_play - width: 2796 height: 1290 ``` ## Scenes, resources and animation ### Scene | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.scene.yaml`, such as `scenes/cave_room.scene.yaml` | `version: 1`, `version: 2` (instancing, inheritance, glTF models, particle emitters, layered tilemaps, LDtk levels), `version: 3` (parallax and repeating layers, tilemap offsets), or `version: 4` (3D lights, scene environment, 3D cameras, reflection probes, light probe grids); built-in physics components `version: 1`; built-in 2D lighting components `version: 1`; built-in 2D navigation region component `version: 1` | `sceneformat.Parse`, `sceneformat.Encode` | [Editor & Scene Format](http://nsgo.games/docs/editor/); schemas `https://nsgo.games/schemas/scene.v1.json`, `scene.v2.json`, `scene.v3.json` and `scene.v4.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/scene.v1.json version: 1 name: Cave Room virtualWidth: 320 virtualHeight: 180 layers: - name: actors space: world order: 10 objects: - id: hero x: 48 "y": 40 sprite: atlas: actors frame: hero ``` ### Game UI screen | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.screen.yaml`, such as `screens/hud.screen.yaml` and `screens/pause.screen.yaml` | `version: 1` | `gameui.ParseScreen`, `gameui.EncodeScreen`, `gameui.LoadScreenFS`, `gameui.BuildScreen` | [gameui](http://nsgo.games/docs/gameui/); schema `https://nsgo.games/schemas/screen.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/screen.v1.json version: 1 name: hud designWidth: 640 designHeight: 360 nodes: - id: status type: vbox anchor: top_left offset: x: 12 "y": 12 spacing: 4 children: - id: hearts type: sprite_row width: 52 height: 14 sprite: art/ui/heart.png spriteCount: 3 - id: coins type: label sizeMode: fit_text height: 16 textKey: hud.coins - id: touch type: container deviceClasses: - phone - tablet children: - id: jump type: touch_button anchor: bottom_right offset: x: 24 "y": 28 width: 52 height: 52 textKey: hud.jump touchHitSize: 64 ``` ### Touch control layout | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.touch.yaml`, such as Cave Run's `controls.touch.yaml`, and a player's edited layout in a key of `core.Storage` | `version: 1` | `input.ParseTouchLayout`, `input.EncodeTouchLayout`, `input.TouchControls.Save`, `input.TouchControls.Load` | [input](http://nsgo.games/docs/input/#on-screen-touch-controls); schema `https://nsgo.games/schemas/touchlayout.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/touchlayout.v1.json version: 1 reference: {width: 844, height: 390} maxScale: 1.5 idleAfter: 4s idleAlpha: 0.45 controls: - id: move kind: dpad anchor: bottomLeft offset: {x: 28, "y": 24} size: {width: 150, height: 150} label: Move ways: 8 left: left right: right - id: jump kind: button anchor: bottomRight offset: {x: 36, "y": 32} size: {width: 110, height: 110} label: Jump action: jump text: JUMP ``` ### Glyph sets | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | A YAML file the game loads to map device families and input tokens to button prompts | `version: 1` | `input.ParseGlyphSet`, `input.EncodeGlyphSet` | [input](http://nsgo.games/docs/input/#glyph-sets-and-prompts) | ```yaml version: 1 devices: keyboard: Space: label: '[Space]' icon: key_space glyph: Space xbox: south: label: '[A]' icon: gamepad_xbox_a glyph: A ``` ### Scene merge conflict report | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Written by `game merge` (overwriting the unmerged `*.scene.yaml` or `-conflict-out`) when a three-way scene merge has conflicts | `version: 1` | `sceneformat.ParseConflict`, `sceneformat.EncodeConflict` | [Editor & Scene Format](http://nsgo.games/docs/editor/#merging-scene-files-in-git-1058), [Command Line](http://nsgo.games/docs/cli/#merge) | ```yaml version: 1 path: scenes/level_01.scene.yaml merged: - scope: object target: slime_03 side: ours action: added conflicts: - kind: field scope: object layer: actors object: door field: x base: 584 ours: 560 theirs: 600 - kind: delete-modify scope: object layer: actors object: slime_02 message: modified on ours, deleted on theirs base: id: slime_02 x: 240 "y": 280 ours: components: patrol: speed: 30 id: slime_02 x: 240 "y": 280 theirs: null ``` ### 3D navigation meshes | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.navmesh.yaml`, such as `levels/level1.navmesh.yaml`, which a scene's `navMesh` names | `version: 1` | `navbake3d.Parse`, `navbake3d.Encode`; baked by `game navmesh` | [navbake3d](http://nsgo.games/docs/navbake3d/) | ```yaml version: 1 settings: cellSize: 0.3 cellHeight: 0.2 minRegionArea: 1 maxEdgeLength: 12 maxSimplificationError: 0.4 maxVertsPerPoly: 6 detailSampleDistance: 1.8 detailSampleMaxError: 0.2 layerMask: 4294967295 meshes: - agent: name: humanoid radius: 0.6 height: 2 maxSlope: 45 maxClimb: 0.9 vertices: - [0, 0, 0] - [0, 0, 4] - [4, 1, 4] - [4, 1, 0] - [8, 1, 4] - [8, 1, 0] polygons: - vertices: [0, 1, 2, 3] detail: - [2, 0.75, 2] triangles: - [0, 1, 4] - [1, 2, 4] - [2, 3, 4] - [3, 0, 4] - vertices: [3, 2, 4, 5] triangles: - [0, 1, 2] - [0, 2, 3] ``` ### Baked light probe grids | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.probes.yaml`, such as `probes/room.probes.yaml`, which a scene object's `lightProbeGrid.data` names | `version: 1` | `render3d.ParseLightProbeGrid`, `render3d.EncodeLightProbeGrid`, `render3d.LoadLightProbeGridFS` | [render3d](http://nsgo.games/docs/render3d/); schema `https://nsgo.games/schemas/lightprobes.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/lightprobes.v1.json version: 1 boundsMin: [-4, 0, -4] boundsMax: [4, 4, 4] counts: [2, 1, 1] probes: - sh: - [0.5, 0.4, 0.3] - [0.1, 0.05, 0] - [0, 0, 0] - [0.15, 0.02, 0.02] - [0, 0, 0] - [0, 0, 0] - [0, 0, 0] - [0, 0, 0] - [0, 0, 0] - sh: - [0.3, 0.4, 0.5] - [0.05, 0.05, 0.1] - [0, 0, 0] - [-0.02, 0.02, 0.15] - [0, 0, 0] - [0, 0, 0] - [0, 0, 0] - [0, 0, 0] - [0, 0, 0] ``` ### Tileset | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.tileset.yaml`, such as `tilesets/cave.tileset.yaml`, named by a scene's inline or layered tilemap (`tilesetFile`) | `version: 1` | `tilemap.ParseTileset`, `tilemap.EncodeTileset`, `tilemap.LoadTilesetFS`; `Tilemap.AddTilesetDoc` builds it | [tilemap](http://nsgo.games/docs/tilemap/#yaml-tilesets); schema `https://nsgo.games/schemas/tileset.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/tileset.v1.json version: 1 name: cave tileWidth: 16 tileHeight: 16 image: tiles/cave.png columns: 4 tileCount: 8 terrains: - name: rock mode: cardinal tiles: - id: 0 solid: true terrain: rock - id: 1 solid: true properties: friction: 0.5 terrain: rock neighbors: [east] - id: 2 shapes: - kind: polygon points: [[0, 16], [16, 0], [16, 16]] - id: 4 animation: - tile: 4 duration: 200ms - tile: 5 duration: 200ms ``` ### Shared resource | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `..yaml`, such as `stone.material.yaml`; `type` is `material`, `curve`, `gradient`, `animation`, `theme`, `busLayout` or `physicsMaterial` | `version: 1` | `resource.Parse`, `resource.Encode` | [resource](http://nsgo.games/docs/resources/) | ```yaml type: material version: 1 uid: mat0000000004 name: Stone baseColor: '#8a8f99' texture: textures/stone.png opacity: 0.75 blend: multiply roughness: 0.9 ``` ```yaml type: curve version: 1 name: Jump height keys: - time: 0 value: 0 interp: smooth - time: 0.5 value: 1 - time: 1 value: 0 interp: step ``` ```yaml type: animation version: 1 name: Hero walk length: 0.4 loop: true tracks: - property: sprite.frame frames: - time: 0 frame: hero_walk_0 - time: 0.1 frame: hero_walk_1 - time: 0.2 frame: hero_walk_2 - time: 0.3 frame: hero_walk_3 events: - time: 0.1 name: footstep - time: 0.3 name: footstep ``` ### Sprite state machine | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.states.yaml`, such as `anim/knight.states.yaml` | `version: 1` | `animclip.ParseStateMachine`, `animclip.EncodeStateMachine` | [animclip](http://nsgo.games/docs/animclip/#sprite-state-machines); schema `https://nsgo.games/schemas/states.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/states.v1.json version: 1 name: Knight entry: idle parameters: - name: move.x type: float - name: velocity.y type: float - name: on_floor type: bool default: true - name: jump type: trigger - name: attack type: trigger - name: hurt type: trigger states: - name: idle clip: anim/knight_idle.animation.yaml x: 40 "y": 230 - name: run clip: anim/knight_run.animation.yaml x: 330 "y": 230 - name: jump clip: anim/knight_jump.animation.yaml x: 190 "y": 70 - name: fall clip: anim/knight_fall.animation.yaml x: 430 "y": 70 - name: attack clip: anim/knight_attack.animation.yaml x: 190 "y": 400 - name: hurt clip: anim/knight_hurt.animation.yaml x: 430 "y": 400 transitions: - from: idle to: run label: moving when: '|move.x| > 0.1' - from: run to: idle label: stopped when: '|move.x| <= 0.1' - from: idle to: jump label: jump pressed, on floor when: jump && on_floor - from: run to: jump label: jump pressed, on floor when: jump && on_floor - from: jump to: fall label: falling when: velocity.y > 0 - from: fall to: run label: lands when: on_floor - from: idle to: attack label: attack pressed when: attack - from: run to: attack label: attack pressed when: attack - from: attack to: idle label: clip ends onEnd: true - from: '*' to: hurt label: took damage when: hurt - from: hurt to: idle label: clip ends onEnd: true ``` ### Particle emitter | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.particles.yaml` / `*.emitter.yaml` (or any `.yaml` file the game loads, such as `sparks.yaml`) | `version: 1` | `particles.UnmarshalConfigYAML`, `particles.MarshalConfigYAML`; the same fields as JSON with `UnmarshalConfigJSON` and `MarshalConfigJSON` | [particles](http://nsgo.games/docs/particles/); schema `https://nsgo.games/schemas/particles.v1.json` | ```yaml version: 1 space: local shape: kind: circle radius: 6 rate: 45 maxParticles: 128 lifetimeMin: 300ms lifetimeMax: 700ms speedMin: 20 speedMax: 65 alphaCurve: - t: 0 value: 1 - t: 1 value: 0 frameNames: - spark_0 ``` ### Particle effect | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.effect.yaml` (or any `.yaml` file the game loads as an effect) | `version: 1` | `particles.UnmarshalEffectYAML`, `particles.MarshalEffectYAML` | [particles](http://nsgo.games/docs/particles/#effect-files) | ```yaml version: 1 emitters: - config: space: world shape: kind: circle radius: 6 rate: 45 lifetimeMin: 300ms lifetimeMax: 700ms duration: 200ms - file: fx/sparks.particles.yaml offsetX: 4 offsetY: -2 delay: 50ms minQuality: medium params: speed: type: float float: 1.5 tint: type: color color: "#ff8800ff" ``` ### Skeletal rig | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.skel.yaml` | `version: 1` | `skeletal.Load`, `skeletal.Encode` | [skeletal](http://nsgo.games/docs/skeletal/) | ```yaml version: 1 name: waver bones: - {name: root} - {name: arm, parent: root, y: -14, length: 12} slots: - {name: arm, bone: arm} skins: default: arm: {frame: arm, originX: 3, originY: 2} animations: wave: duration: 0.8 loop: true bones: arm: rotate: - {time: 0, angle: 0.4} - {time: 0.4, angle: -0.4} - {time: 0.8, angle: 0.4} ``` ### Cutscene | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.cutscene.yaml` (or any `.yaml` file the game loads), such as `cutscenes/floor1_intro.cutscene.yaml` | `version: 1` (video), `version: 2` (video or timeline) | `cutscene.Parse`, `cutscene.Encode` | [cutscene](http://nsgo.games/docs/cutscene/) | ```yaml version: 1 source: asset:cutscenes/intro.mp4 group: cutscenes skippable: true skipAfter: 1.5s fit: cover ``` ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/cutscene.v2.json version: 2 kind: timeline scene: scenes/level_01.scene.yaml length: 12s skippable: true skipAfter: 1s tracks: - id: camera name: Camera kind: camera clips: - id: cam1 start: 0s duration: 1.6s easing: hold action: hold target: door - id: cam2 start: 1.6s duration: 2.4s easing: easeInOut action: pan target: knight - id: cam3 start: 4s duration: 8s action: follow target: knight - id: knight name: Knight kind: actor target: knight clips: - id: kn1 start: 1s duration: 2.4s easing: easeOut action: walk fromX: 60 toX: 220 state: run - id: kn2 start: 3.4s duration: 4.6s action: state state: idle - id: dialogue name: Dialogue kind: dialogue clips: - id: dl1 start: 3.6s duration: 2.4s line: intro.knight.01 - id: sfx name: Sound kind: sound group: sfx clips: - id: sx1 start: 200ms duration: 600ms source: audio/door_slam.wav - id: music name: Music kind: music group: music clips: - id: mu1 start: 2s duration: 10s source: audio/cellar_theme.ogg fadeIn: 2s ``` ### Room map | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `castle.rooms.yaml` | `version: 1` | `rooms.Parse`, `rooms.Encode` | [rooms](http://nsgo.games/docs/rooms/) | ```yaml version: 1 transition: kind: slide duration: 300ms rooms: - id: entrance x: 0 "y": 0 width: 320 height: 180 - id: hall x: 320 "y": 0 width: 640 height: 180 transition: kind: fade color: '#102030' ``` ### World map | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `castle.yaml` | `version: 1` | `worldmap.Parse`, `worldmap.Encode` | [worldmap](http://nsgo.games/docs/worldmap/) | ```yaml version: 1 rooms: - id: entrance name: Castle Gate x: 0 "y": 0 width: 320 height: 180 links: [hall] - id: hall name: Great Hall x: 320 "y": 0 width: 320 height: 180 markers: - id: save-gate kind: save room: entrance x: 40 "y": 90 label: Gate shrine ``` ### Card board | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `board.yaml` | `version: 1` | `cards.ParseBoardDoc`, `cards.EncodeBoardDoc` | [cards](http://nsgo.games/docs/cards/) | ```yaml version: 1 card_size: w: 63 h: 88 slots: - id: hand rect: x: 40 "y": 400 w: 560 h: 120 layout: fan: arc: 24 sag: 14 ``` ## Game data ### Data table | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `.yaml` or `.yml`, such as `weapons.yaml`; `.csv` and `.json` exports load too, without a version | `version: 1` | `datatable.LoadYAML`, `datatable.MarshalYAML`; `datatable.LoadFile` picks the reader by extension | [datatable](http://nsgo.games/docs/datatable/); schema generated per row type with `datatable.Schema` | ```yaml version: 1 rows: - id: sword damage: 12 cooldown: 400ms tags: [melee] - id: bow damage: 8 cooldown: 1s tags: [ranged, two-handed] ``` ### Stats | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `hero.yaml` | `version: 1` | `stats.Parse`, `stats.Encode` | [stats](http://nsgo.games/docs/stats/) | ```yaml version: 1 stats: - name: health base: 100 min: 0 - name: attack base: 12 effects: - name: berserk steps: 300 modifiers: - stat: attack op: mul value: 1.5 ``` ### Gameplay tags | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `tags.yaml` | `version: 1` | `tags.Parse`, `tags.Encode` | [tags](http://nsgo.games/docs/tags/) | ```yaml version: 1 tags: - name: ability.fire description: Abilities that deal fire damage - name: ability.ice - name: status.debuff description: Harmful effects an enemy applies - name: status.debuff.stun description: Cannot act until it wears off - name: status.immune.stun ``` ### Ability set | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `hero.abilities.yaml` | `version: 1` | `ability.Parse`, `ability.Encode` | [ability](http://nsgo.games/docs/ability/) | ```yaml version: 1 abilities: - id: fireball name: ability.fireball action: cast costs: - resource: mana amount: 20 cooldown: 2s castTime: 500ms conditions: [grounded, '!silenced'] - id: dash action: dash cooldown: 250ms charges: 3 recharge: 4s ``` ### Gameplay cue set | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `combat.cues.yaml` | `version: 1` | `cues.Parse`, `cues.Encode` | [cues](http://nsgo.games/docs/cues/) | ```yaml version: 1 cues: - tag: cue.hit.fire once: true particles: file: fx/hit.yaml attach: chest offset: x: 0.5 "y": -1 sound: file: sfx/hit.yaml shake: amplitude: 0.5 duration: 100ms flash: color: '#ff8800' duration: 50ms - tag: cue.status.burning whileActive: true particles: file: fx/burning.yaml sound: file: sfx/burning.yaml loop: true animation: burning ``` ### Item catalog | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `items.yaml` | `version: 1` | `inventory.Parse`, `inventory.Catalog.Encode` | [inventory](http://nsgo.games/docs/inventory/) | ```yaml version: 1 items: - id: potion name: items.potion.name icon: asset:icons/potion.png maxStack: 20 tags: [consumable, healing] stats: heal: 25 - id: iron-helm name: items.iron-helm.name equip: head stats: armor: 3 ``` ### Quest book | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `village.yaml` | `version: 1` | `quest.Parse`, `quest.Encode` | [quest](http://nsgo.games/docs/quest/) | ```yaml version: 1 quests: - id: welcome title: quest.welcome.title autoStart: true objectives: - id: meet-elder kind: talk target: elder - id: herbs title: quest.herbs.title requires: [welcome] objectives: - id: moonleaf kind: collect target: moonleaf count: 4 rewards: - kind: xp id: xp amount: 20 ``` ### Loot tables | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `chest.yaml` | `version: 1` | `loot.Parse`, `loot.Encode` | [loot](http://nsgo.games/docs/loot/) | ```yaml version: 1 tables: - name: chest rolls: min: 1 max: 3 entries: - item: sword weight: 2.5 - nothing: true weight: 6.5 ``` ### RPG database | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `rpg.yaml` | `version: 1` | `rpgdata.Parse`, `rpgdata.Encode` | [rpgdata](http://nsgo.games/docs/rpgdata/) | ```yaml version: 1 classes: - id: hero name: Hero maxLevel: 10 levelXP: 100 stats: attack: - 5 - 7 - 9 hp: - 20 - 26 - 32 skills: - id: slash level: 1 - id: cleave level: 3 actors: - id: ren name: Ren class: hero level: 1 skills: - id: slash name: Slash scope: one_enemy formula: a.attack * 2 - b.defense - id: cleave name: Cleave scope: all_enemies formula: a.attack + 4 cost: 4 enemies: - id: slime name: Slime hp: 12 attack: 4 defense: 1 experience: 3 gold: 2 troops: - id: meadow members: - enemy: slime x: 0 "y": 0 - enemy: slime x: 48 "y": 0 ``` ### Achievements | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game embeds, such as `achievements.yaml` | `version: 1` | `achievements.Parse`, `achievements.Encode` | [achievements](http://nsgo.games/docs/achievements/) | ```yaml version: 1 achievements: - id: gem-collector title: Gem Collector description: Clear 500 gems. steps: 500 platforms: gameCenter: dev.nsgo.test.gem_collector playGames: CgkIabc123EAIQAg ``` ### Leaderboards | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game embeds, such as `leaderboards.yaml` | `version: 1` | `leaderboard.Parse`, `leaderboard.Catalog.Encode` | [leaderboard](http://nsgo.games/docs/leaderboard/) | ```yaml version: 1 leaderboards: - name: high-score gameCenter: dev.nsgo.game.example.high_score playGames: CgkI6v7z8vQREAIQAQ miniGame: key: best order: desc ``` ### Local reminders | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game embeds, such as `reminders.yaml` | `version: 1` | `liveops.ParseReminders`, `liveops.LoadRemindersFS`, `liveops.EncodeReminders` | [liveops](http://nsgo.games/docs/liveops/#local-reminders); schema `https://nsgo.games/schemas/reminders.v1.json` | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/reminders.v1.json version: 1 quietHours: start: "22:00" end: "08:00" reminders: - id: energy_full title: reminder.energy.title body: reminder.energy.body delay: 2h0m0s onOpen: keep - id: daily_reward title: reminder.daily.title body: reminder.daily.body at: "09:00" repeat: daily onOpen: cancel - id: weekend_event title: reminder.weekend.title body: reminder.weekend.body at: "18:00" weekday: friday repeat: weekly onOpen: reschedule silent: true ``` ### Mini-game ads | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game embeds, such as `ads.yaml` | `version: 1` | `liveops.ParseAds`, `liveops.EncodeAds` | [liveops](http://nsgo.games/docs/liveops/#mini-game-ads) | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/ads.v1.json version: 1 interstitialInterval: 30s interstitialCap: 3 placements: - name: revive kind: rewarded unitId: adunit-revive - name: level-end kind: interstitial unitId: adunit-level-end - name: menu kind: banner unitId: adunit-menu ``` ### Move set | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `moves.yaml` | `version: 1` | `fighting.Parse`, `fighting.Encode` | [fighting](http://nsgo.games/docs/fighting/) | ```yaml version: 1 input: up: up down: down left: left right: right moves: - name: lp press: - lp - name: hadoken motion: - "2" - "3" - "6" window: 12 press: - lp buffer: 8 priority: 20 ``` ### Frame data | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `fighter.yaml` | `version: 1` | `framedata.Parse`, `framedata.Encode` | [framedata](http://nsgo.games/docs/framedata/) | ```yaml version: 1 moves: - name: idle animation: idle length: 8 loop: true boxes: - kind: hurt start: 1 end: 8 x: -12 "y": -80 width: 24 height: 80 ``` ### Platformer controller | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `hero.yaml` | `version: 1` | `platformer.ParseConfig`, `platformer.EncodeConfig` | [platformer](http://nsgo.games/docs/platformer/) | ```yaml version: 1 coyote_time: 100ms jump_buffer: 100ms jump_speed: 284 jump_cut: 0.55 jump_cut_min_speed: 110 gravity: 720 max_fall_speed: 320 run_speed: 98 ground_accel: 960 ground_decel: 1150 air_accel: 680 wall_slide_speed: 60 wall_coyote_time: 80ms wall_jump_speed_x: 150 wall_jump_speed_y: 260 wall_jump_lock: 150ms ``` ### Vehicle | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `car.yaml` | `version: 1` | `vehicle3d.ParseConfig`, `vehicle3d.EncodeConfig` | [vehicle3d](http://nsgo.games/docs/vehicle3d/) | ```yaml version: 1 name: kart mass: 300 chassisHalfExtents: [0.6, 0.2, 1] chassisOffset: [0, 0, 0] engineForce: 2000 reverseForce: 0 maxSpeed: 20 maxReverseSpeed: 5 brakeForce: 4000 handbrakeGrip: 0 maxSteerAngle: 25 steerRate: 90 drag: 0 rollingResistance: 0 rollInfluence: 0 angularDamping: 0 wheels: - name: front anchor: [0, -0.1, -0.8] radius: 0.25 restLength: 0.2 stiffness: 20000 damping: 2000 maxForce: 10000 friction: 1.2 steer: true brake: true - name: rear anchor: [0, -0.1, 0.8] radius: 0.25 restLength: 0.2 stiffness: 20000 damping: 2000 maxForce: 10000 friction: 1.2 drive: true brake: true ``` ### Bullet patterns | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `patterns.yaml` | `version: 1` | `bullets.Parse`, `bullets.Encode` | [bullets](http://nsgo.games/docs/bullets/) | ```yaml version: 1 patterns: - name: bloom kind: ring frame: orb count: 24 speed: 90 spin: 7.5 shots: 6 interval: 400ms lifetime: 6s radius: 4 ``` ### Formations | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `formations.yaml` | `version: 1` | `rts.ParseFormations`, `rts.Formations.Encode` | [rts](http://nsgo.games/docs/rts/) | ```yaml version: 1 formations: - name: line shape: line spacing: 1.5 - name: wedge shape: wedge spacing: 1.5 ``` ### Utility AI | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `guard.utility.yaml` | `version: 1` | `ai.ParseUtility`, `ai.EncodeUtility` | [ai](http://nsgo.games/docs/ai/#utility-ai) | ```yaml version: 1 momentum: 0.1 actions: - name: attack weight: 1.2 considerations: - name: target_close input: target_distance max: 200 curve: kind: linear slope: -1 shiftY: 1 - name: healthy input: health_ratio curve: kind: logistic slope: 1 exponent: 10 shiftX: 0.35 - name: heal weight: 1.1 considerations: - name: low_health input: health_ratio curve: kind: polynomial slope: -1 exponent: 2 shiftY: 1 - name: has_potion input: potion_count curve: kind: step slope: 1 shiftX: 0.5 ``` ### GOAP action set | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `camp.goap.yaml` | `version: 1` | `ai.ParseGOAP`, `ai.EncodeGOAP` | [ai](http://nsgo.games/docs/ai/#goal-oriented-action-planning-goap) | ```yaml version: 1 nodeBudget: 512 facts: bools: - has_axe - has_fire ints: - wood actions: - name: fetch_axe cost: 1 check: axe_available effects: bools: - fact: has_axe value: true - name: chop_wood cost: 1 preconditions: bools: - fact: has_axe value: true effects: ints: - fact: wood op: add value: 1 - name: gather_sticks cost: 3 effects: ints: - fact: wood op: add value: 1 - name: build_fire cost: 1 preconditions: ints: - fact: wood op: gte value: 2 effects: bools: - fact: has_fire value: true ints: - fact: wood op: add value: -2 goals: - name: light_campfire priority: 10 target: bools: - fact: has_fire value: true ``` ### Behavior tree | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.bt.yaml`, such as `guard.bt.yaml` | `version: 1` | `ai.ParseBehaviorTree`, `ai.EncodeBehaviorTree`, `ai.LoadBehaviorTreeFS`, `ai.BuildBehaviorTree` | [ai](http://nsgo.games/docs/ai/#behavior-trees-in-yaml) · [schema](http://nsgo.games/docs/schemas/) | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/bt.v1.json version: 1 name: guard blackboard: - key: enemy_seen type: bool default: false - key: enemy_distance type: float default: 999 root: type: selector children: - type: blackboard_condition key: enemy_seen op: eq value: true abort: both child: type: selector children: - type: blackboard_condition key: enemy_distance op: lte value: 32 abort: both child: type: cooldown duration: 500ms child: type: action action: attack params: damage: 15 - type: action action: chase params: speed: 120 - type: subtree path: patrol.bt.yaml params: wait: 200ms keys: home: home_pos ``` ### AI state tree | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.statetree.yaml`, such as `boss.statetree.yaml` | `version: 1` | `ai.ParseStateTree`, `ai.EncodeStateTree`, `ai.LoadStateTreeFS` | [ai](http://nsgo.games/docs/ai/#state-trees) · [schema](http://nsgo.games/docs/schemas/) | ```yaml # yaml-language-server: $schema=https://nsgo.games/schemas/statetree.v1.json version: 1 name: guard blackboard: - key: enemy_seen type: bool default: false states: - id: patrol tasks: - action: walk_route transitions: - trigger: condition conditions: - key: enemy_seen op: eq value: true to: combat - id: combat transitions: - trigger: event event: enemy_lost to: patrol children: - id: attack tasks: - action: attack params: damage: 15 transitions: - trigger: completed to: next - id: reposition tasks: - action: move_to_cover transitions: - trigger: completed to: combat/attack restart: true ``` ### Navigation meshes | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `crypt.navmesh.yaml`, usually one per level and agent type | `version: 1` | `navbake.Parse`, `navbake.Mesh.Encode` | [navbake](http://nsgo.games/docs/navbake/) | ```yaml version: 1 agent: small radius: 2 polygons: - [[2.0078125, 2.0078125], [37.992188, 2.0078125], [37.992188, 17.992188], [19.601562, 17.992188]] - [[2.0078125, 2.0078125], [19.601562, 17.992188], [18.863281, 18.296875]] - [[2.0078125, 2.0078125], [18.863281, 18.296875], [18.296875, 18.863281]] - [[2.0078125, 2.0078125], [18.296875, 18.863281], [17.992188, 19.601562]] - [[2.0078125, 2.0078125], [17.992188, 19.601562], [17.992188, 37.992188], [2.0078125, 37.992188]] ``` ### Tile rules | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `ruins.yaml` | `version: 1` | `procgen.ParseRules`, `procgen.EncodeRules` | [procgen](http://nsgo.games/docs/procgen/) | ```yaml version: 1 tiles: - name: floor weight: 6 walkable: true - name: water weight: 2 neighbors: - left: floor right: floor - left: floor right: water - left: water right: floor - left: water right: water - up: floor down: floor - up: floor down: water - up: water down: floor - up: water down: water ``` ### Dungeon room templates | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `rooms.yaml` | `version: 1` | `procgen.ParseRoomTemplates`, `procgen.EncodeRoomTemplates` | [procgen](http://nsgo.games/docs/procgen/) | ```yaml version: 1 rooms: - id: start_hub weight: 1 tags: - start doors: - side: north offset: 3 - side: south offset: 3 - side: east offset: 2 - side: west offset: 2 tiles: - '###.###' - '#.....#' - '.......' - '#.....#' - '###.###' - id: boss_vault tags: - goal width: 7 height: 5 source: rooms/boss_vault.tmj doors: - side: north offset: 3 - side: south offset: 3 - side: east offset: 2 - side: west offset: 2 ``` ### Procedural placement | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.placement.yaml` file the game loads, such as `forest.placement.yaml` | `version: 1` | `procgen.ParsePlacement`, `procgen.EncodePlacement` | [procgen](http://nsgo.games/docs/procgen/) | ```yaml version: 1 seed: 7 steps: - id: trees sampler: grid spacing: 2 count: 6 prefab: tree - id: lamps sampler: grid spacing: 4 prefab: lamp ``` ### Visual novel cast | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `cast.yaml` | `version: 1` | `vn.ParseCast`, `vn.EncodeCast` | [vn](http://nsgo.games/docs/vn/) | ```yaml version: 1 slots: - name: left x: 0.25 characters: - id: aiko name: Aiko color: '#e07a5f' slot: left defaultExpression: neutral expressions: - name: neutral frame: aiko_neutral - name: smile frame: aiko_smile ``` ### Beat map | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | A `.yaml` file next to the track, such as `opening.beatmap.yaml` | `version: 1` | `rhythm.ParseBeatMap`, `rhythm.EncodeBeatMap` | [rhythm](http://nsgo.games/docs/rhythm/) | ```yaml version: 1 title: Opening offsetMs: 120 tempos: - beat: 0 bpm: 120 - beat: 62.5 bpm: 140 meters: - beat: 0 beatsPerBar: 4 ``` ### Number locale | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `de.yaml` | `version: 1` | `idle.ParseLocale`, `idle.EncodeLocale` | [idle](http://nsgo.games/docs/idle/) | ```yaml version: 1 name: de decimal: ',' group: . exponent: E units: - exp: 3 suffix: ' Tsd.' - exp: 6 suffix: ' Mio.' ``` ### Quality presets | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `quality.yaml` | `version: 1` | `quality.ParseConfig`, `quality.EncodeConfig` | [quality](http://nsgo.games/docs/quality/) | ```yaml version: 1 presets: low: resolution_scale: 0.5 particle_scale: 0.25 effects: false shadows: false sampling: nearest medium: resolution_scale: 0.75 particle_scale: 0.6 effects: true shadows: false high: resolution_scale: 1 particle_scale: 1 effects: true shadows: true devices: - model: Samsung SM-A os: android level: low adapt: target_fps: 30 window_frames: 120 upgrade_windows: 3 resolution_steps: - 0.85 - 0.65 ``` ## Servers ### Account service | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `accounts.yaml`, passed to `accountsd -config` | `version: 1` | `accounts.ParseConfig`, `accounts.Config.Marshal` | [accounts](http://nsgo.games/docs/accounts/) | ```yaml version: 1 issuer: https://accounts.example.com audience: my-game tokenTTL: 1h30m30s disableGuests: true password: minLength: 10 argon2id: time: 2 memoryKiB: 19456 threads: 1 allowedOrigins: - https://play.example.com metrics: 127.0.0.1:9101 ``` ### Token key set | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `keys.yaml`, written by `accountsd genkey` | `version: 1` | `authtoken.ParseKeySet`, `authtoken.KeySet.Marshal` | [accounts](http://nsgo.games/docs/accounts/) | ```yaml version: 1 issuer: https://accounts.example.com audience: my-game keys: - id: 2317febd373fcbcd key: hze+0cYruVRddgjkbHzgCeWWJbEsBkn6K8JNHRDf6Wg= ``` ### Cloud save service | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `cloudsave.yaml`, passed to `cloudsaved -config` | `version: 1` | `cloudsave.ParseConfig`, `cloudsave.Config.Marshal` | [cloudsave](http://nsgo.games/docs/cloudsave/) | ```yaml version: 1 maxSlotBytes: 1048576 maxSlots: 32 keepVersions: 5 allowedOrigins: - https://play.example.com metrics: 127.0.0.1:9102 ``` ### Leaderboard service | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `leaderboards.yaml`, passed to `leaderboardd -config` | `version: 1` | `selfhost.ParseConfig`, `selfhost.Config.Marshal` | [leaderboard/selfhost](http://nsgo.games/docs/leaderboard-selfhost/) | ```yaml version: 1 proofTTL: 10m boards: - name: high-score order: descending reset: allTime - name: weekly-sprint order: ascending reset: weekly weekStart: sunday keep: 4 allowedOrigins: - https://play.example.com metrics: 127.0.0.1:9103 ``` ### Operators | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `operators.yaml`, named by the `admin.operators` field of a service daemon's configuration | `version: 1` | `admin.ParseOperators`, `admin.Operators.Marshal`, `game admin operator` | [admin](http://nsgo.games/docs/admin/#operators-and-roles) | ```yaml version: 1 operators: - id: ada role: owner password: $argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaGhhc2g totp: required - id: ci role: viewer tokensNotBefore: "2026-11-30T12:00:00Z" roles: support-lead: - '*.read' - accounts.* ``` `password` is an argon2id hash in the PHC string format, never a plaintext password, and is absent for an operator that uses bearer tokens only; `totp` is `required` or absent. `tokensNotBefore`, absent or a quoted RFC 3339 UTC time in whole seconds, refuses the operator's bearer tokens issued before it. `role` is a built-in role (`viewer`, `support`, `moderator`, `operator`, `owner`) or one under `roles`, a map of role names to permission patterns written sorted by name. The listeners record the TOTP codes they accept as empty files named `@