# adoptParts
Keeps a shared (synced) object whole on every player's machine. A scene record under a synced entity is built by
each peer, but a peer that receives the synced entity over the network loads its authored children at the scene
root, detached at the origin. The owner publishes its children's ids in a synced string field; every other peer
re-attaches those entities under the shared one, keeping their authored local transforms.
```luau
local adopt = require("stations.adoptParts")
-- in update(): public.partIds is a Field.string("", Sync, ...)
public.partIds = adopt.keep(rootEntity, public.partIds)
```
# focus
One interaction target at a time, chosen by aim. Every interactable (door, light switch, seat, TV, controller, the
Game Boy) offers itself each frame while the player is in its range; the focus picker takes the one the middle of the
screen looks at (turning counts fully, the follow camera's pitch only partly, since it cannot look straight down at a
table), and only when nothing is under the reticle the nearest one, favouring what is in front and bigger things. Only
the winner shows a prompt and only the winner acts on Interact.
Input contexts, innermost first (`Focus.context()`): `shelf` (cartridge shelf open: its own map `stations.shelf`
stands the player's and the held console's controls down; Back = Backspace / pad B closes it), `pad` (a controller in
hand: `stations.gamepad` stands the player's and hangout maps down; its own `pad_watch` frames the TV), `handheld` (the
Game Boy in hand: `stations.handheld`), `holding`, `seated`, `free`. With something in hand only an offer made with a
`press` callback is considered (a seat: sit with the item kept in hand; a held controller's "Cartridges"): it shows the
prompt and the `stations.holdInteract` map (E / pad right-stick click / touch "Use", live only then) calls `press`.
Seated, look (mouse / right stick) turns the seated view (`stations.seatView`), so the reticle picks among what lies on
the table. With a Game Boy in hand and standing, its close-up looks back at the player, so a `press` offer (a seat) is
found from the body instead: within reach of the chest, nearest first — walk up to a seat and press Interact to sit
with the Game Boy kept in hand.
The player's Carrier picks nothing up by itself (`stations.hands` binds its control to no device): each holdable's
own component offers itself here and picks itself up when it is the target.
```luau
local Focus = require("stations.focus")
-- update(): offer while in range (player-facing verb and object, aim radius in metres), withdraw otherwise
Focus.offer(public.entityId, targetEntity, "Open", "Door", 0.5)
Focus.withdraw(public.entityId)
-- in the Interact handler:
if not Focus.isTarget(public.entityId) then return end
```
# hui
The hangout's interface kit: one look for every screen, and the shared pieces each object draws through instead of
registering screens of its own.
- Look: warm frosted glass panels, cream ink, an amber accent for the hangout and a phosphor green for anything a
console shows. Headings in Bricolage Grotesque, text in Arimo, keys in JetBrains Mono on raised keycaps, small
retro kickers in Press Start 2P.
- `Hui.prompt(owner, key, verb, object?)` / `Hui.unprompt(owner)`: the one interaction prompt on screen. The most
recent offer wins; withdrawing it brings back the one under it, so prompts never stack or stick.
- `Hui.controls(owner, title, items)` / `Hui.uncontrols(owner)`: the controls bar for whatever the player is doing
(holding the Game Boy, a controller, seated). `items` = `{ { keys = { "Z" }, label = "A" }, ... }`.
- `Hui.toast(kicker, title, body?)`: a card that drops in at the top and leaves by itself.
- Building blocks for screens: `Hui.glass`, `Hui.text`, `Hui.keycap`, `Hui.keys`, `Hui.kicker`, `Hui.bar`,
`Hui.button`, `Hui.T` (tokens).
# ConsoleStation
A shared television console: any emulator core in the world (NES, CHIP-8, Neo Geo, ...) running on one
screen that the whole room sees, with two controllers. Put it on an entity at the screen's centre, facing
out of the screen (+Z), whose screen mesh draws the material bound to `texGuid`.
- **Choosing a game.** Near it with empty hands, Interact (E / pad west / touch) opens the cartridge
library (`stations.cartlib`): every built-in cartridge and every cartridge anyone in the session has
uploaded, for the consoles in `consoles`, plus "Upload from your computer".
- **Where it runs.** On the peer that holds the cartridge's bytes (the *runner*): the uploader, or the one
who picked a built-in cart. That peer emulates at full speed, hears the sound, and streams the picture to
everyone else (`stations.framecodec` delta frames, `streamHz` a second within `streamBudget` bytes a
second). It restates what is inserted every few seconds, so a late joiner sees it too.
- **Two players.** A `PadControl` controller sends its buttons here as one word (bit 0-3 right, left,
up, down; 4-7 A, B, C, D; 8 Start; 9 Select/Coin). The runner applies player 1 and 2 to the core
(NES pads, CHIP-8 keypad, Neo Geo `setPad`).
Methods: `padInput(slot, word)` (from a controller on this peer), `insert(entry)`, `eject()`, `cart()`,
`isRunner()`. Fields: `consoles`, `texGuid`, `streamHz`, `streamBudget`, `volume`, `promptRange`,
`seatOffset` (where a player's view sits while holding a controller, in this entity's frame), `status`.
- **The screen's light.** While a picture runs, the picture's drawn colour lights the room on every peer: a
shadowed spot out of the glass (`glowIntensity`, `glowRange`, `glowShadows`), a small point on the tube,
and a broad shadowless fill (`fillIntensity`, `fillBack` metres behind the glass so its falloff from set
to seats is gentle, `fillAngle`, `fillPitch` down toward the floor and seats). All go dark on eject.
# progress
Each player's hangout progression, kept on their own machine (runtime data, survives restarts) and shared
with the room as a small card.
- **Play time:** per console and per game, while you are the one playing (holding the Game Boy, or a
controller on a TV game with a game running).
- **XP and level:** playing earns 10 XP a minute (15 when two people play the TV together), hanging out with
at least one other person earns 2 a minute, milestones add a bonus. Level *n* needs `100 + 60 (n-1)` XP.
- **Milestones:** real things done in the room (first game, co-op on the TV, passing the Game Boy on,
uploading a cartridge, an hour on a console, playing every console, playing from the sofa...).
```lua
local Progress = require("stations.progress")
Progress.playing(consoleId, title, dt, coop) -- each frame you play
Progress.event("upload") -- "upload", "handover", "seated", "watched", "pinned"
Progress.photo() -- a photo taken with the instant camera
Progress.tick(dt) -- once a frame (HangoutHud does it)
Progress.level() -> (level, xpIntoLevel, xpForLevel)
Progress.cards() -> { {peer, name, level, xp, minutes, top, milestones} } -- everyone, you first
Progress.milestones() -> { {id, title, text, done} }
Progress.onToast(fn(title, text)) -- a milestone or level up
```
Channel: `progress.card` (each peer's card, on change and every 15 s; answered on `progress.hello`).
# seats
What this peer knows about every `Seat` (`seating.Seat`): which seat the local player sits on, the seat each avatar sits on as the room heard it, and which free seat is nearest (the one seat that shows the "Sit" prompt). Seat components keep it up to date; other code reads it.
```luau
local seats = require("seating.seats")
seats.isSeatedLocal() -- is the local player sitting?
seats.localSeat() -- the seat entity they sit on, or nil
seats.seatOf(avatar) -- the seat entity any avatar sits on, or nil
seats.occupantOf(seatId) -- the avatar on a seat, or nil
seats.all() -- every Seat entity this peer runs
```
# RetroStation
Makes a console prop playable and shared. Put it on the root of a console model that carries a
`Holdable` (a handheld) and a child entity whose `Model` draws the screen material bound to `texGuid`.
- **Runs where it is held.** The emulator core named by `core` (any `emulatorCore` in the world: the
Game Boy, NES, CHIP-8, ...) runs only on the peer whose avatar holds the console, at the console's own
frame rate, so the player's input has no network delay. Its sound plays for that player.
- **Shares the picture.** That peer streams the screen to everyone else about `streamHz` times a
second as delta frames (only what changed; a full frame each second), within `streamBudget` bytes a
second. Every other peer draws the frames into its copy of the screen.
- **Shares the buttons.** `pad` holds the held buttons (bits 0–3: right, left, up, down; bits 4–7: A, B,
select, start), written by whatever plays the console (`HandheldPlay`) and synced, so every peer can
press the model's buttons (`GbButtons`).
- **Passes the game on.** When the console changes hands the outgoing peer sends the whole machine
(`snapshot()` on the core's machine) to the new holder, who resumes the same game. A core without
snapshots restarts from its battery save.
Fields: `core`, `romPath`, `texGuid`, `streamHz`, `streamBudget`, `volume`, `pad` (Sync), `status`.
Methods: `isRunning()`, `setPad(bits)` (the holder's peer), `machine()`.
# cartlib — the session cartridge library
`require("stations.cartlib")` gives every console station one shared list of the cartridges in the room: each core's committed demo carts, the local player's own uploads, and what every other player in the session holds. Players upload ROMs from their computer and anyone in the room can play them; the bytes are copied peer to peer on demand.
Uploaded ROMs are **never** written to `/zero/source`: they live in the uploader's runtime-data library (chunked under the 256 KB value cap, the `retro.host` RomLibrary layout, so a console's own loader lists them too) and in memory. Carts copied from another player live in memory for the session only.
## API
```lua
local Cartlib = require("stations.cartlib")
Cartlib.list(consoleId?) -> { Entry } -- sorted by console, BIOS first, then title
-- Entry = { id, console, title, size, holders = {peerId}, builtin, isBios }
-- id = console .. ":" .. filename .. ":" .. size (stable across peers)
Cartlib.has(id) -> boolean -- bytes available on this peer
Cartlib.bytes(id) -> string? -- committed file, runtime library, or session cache
Cartlib.upload(consoleId?) -> (Entry?, why?) -- yields; system file picker, validate, store, announce
Cartlib.fetch(id, function(ok, why) end) -- copy from a holder peer (<= 8 MB)
Cartlib.onChanged(cb) -> unsubscribe
Cartlib.biosFor(consoleId) -> id? -- a locally held BIOS (e.g. neogeo.zip)
Cartlib.openLoader({ title, consoles = {"gameboy", ...}, onPick = function(entry) end })
Cartlib.closeLoader()
Cartlib.handleCallback(id, data) -> boolean -- forward a UI callback (see below)
Cartlib.tick() -- prune players who left (CartLoader calls it)
```
Extras: `Cartlib.get(id)`, `Cartlib.progress(id)` (0..1 while copying), `Cartlib.consoles()`, `Cartlib.formatSize(n)`, `Cartlib.refresh()` (rescan disk and the runtime library), `Cartlib.isLoaderOpen()`, `Cartlib.isUploading()`.
Consoles come from every installed `emulatorCore` (`retro.host.registry`). Any `.zip` is a Neo Geo set (console `neogeo`); `neogeo.zip` is the Neo Geo BIOS (`isBios = true`, validation skipped). If no core claims `neogeo`, the library still files zips under it. `builtin` entries are the files in each core's `romsDir`, held by everyone.
## Neo Geo system files
The Neo Geo core reads its BIOS from a zip (`neogeo.package` romset): a system ROM (`sp-s2.sp1`, `sp-s3.sp1`, `sp-u2.sp1`, `sp-j2.sp1`, `uni-bios*.rom`, … the romset's `BIOS_NAMES`), `sfix.sfix`, `sm1.sm1`, and optionally `000-lo.lo`. Players don't have to build that zip themselves:
- Loose files (`.sp1 .sfix .sm1 .rom .bin .lo`, renamed copies like `sp-s2 (1).sp1` included; `Cartlib._biosPart(name)` names each one's role) are kept in the player's runtime-data library under `neogeo_bios/`. Once a system ROM, sfix and sm1 are all held, they are packed (stored, uncompressed, `Cartlib._storeZip`) into `neogeo.zip`, which becomes the BIOS entry.
- A zip of system files under any name is the BIOS when it holds all three; otherwise its files join the loose parts.
- `Cartlib.neoSetup()` answers what is here: `{ ready, system, sfix, sm1, lo, missing, games }`.
The picker takes several files at once on the All and Neo Geo tabs.
## Help on the shelf
Every tab opens with an *Adding games* strip: the file types it takes and that uploads stay in the player's library and are shared with the room while they are here. The Neo Geo tab adds a setup card: step 1 *System files* (each file ✓/○, an *Upload system files* button while any is missing) and step 2 *Your game zip*. PLAY on a Neo Geo game without the system files keeps the shelf open, switches to that tab, says what is missing and puts focus on the upload button.
## The loader panel
`openLoader` shows a centred card over a dimmed backdrop: console tabs (All + the consoles you pass), one row per cart (console tag, BIOS tag, title, console, size, who has it, and an action: PLAY when the bytes are here, GET to copy them, COPYING n%, TOO BIG past 8 MB), a close button (Esc) and an **Upload from your computer** button that filters the picker to the current tab's extensions. Everything is a button, so arrows / d-pad / stick move focus, Enter / south press, and touch taps. Picking a cart that is elsewhere copies it first and then calls `onPick`; an upload calls `onPick` with the new entry.
UI callbacks run in play. `openLoader` registers its own callback env, so callbacks reach it when it is opened from a component's code. A component that wants to be sure can forward its own `onCallback(id, data)` to `Cartlib.handleCallback(id, data)` (repeats within the same frame are ignored), or carry the `stations/CartLoader` component, which does that and calls `Cartlib.tick()`.
## Session sync
- `cartlib.announce {v=1, carts={meta...}}` — each peer broadcasts the metadata (never bytes) of what it holds beyond the built-in carts: on load, after any upload or copy, and in answer to a hello.
- `cartlib.hello` — sent on load and when a loader opens; every peer answers with an announce, so a late joiner learns the room.
- Players who leave are dropped from every list (`multiplayer.getPeers()` checked on each `list()` and each `tick()`).
## Transfer protocol
All messages are broadcasts that name their target peer first; other peers ignore them.
1. requester → `cartlib.req (holder, reqId, cartId)`
2. holder → `cartlib.head (requester, reqId, chunkCount, byteLen)` or `cartlib.deny (requester, reqId, why)`
3. holder → `cartlib.chunk (requester, reqId, i, base64)` — 12 000 characters each, paced by a 150 KB/s budget shared by all transfers it serves; the budget halves when `multiplayer.getDiagnostics().refusals` rises and recovers by 10 % every half second.
4. holder → `cartlib.done`; requester → `cartlib.nack (holder, reqId, {missing})` for any gaps (also after 4 s without a chunk), up to 6 times.
5. requester reassembles, checks the decoded length, caches in memory, announces itself as a holder. A holder that does not answer in 6 s, stalls or denies is swapped for the next holder (lowest latency first).
Carts over 8 MB never move (requester and holder both refuse); players upload their own copy.
## Testing hook
`Cartlib._addLocal(name, bytes, consoleHint?, { persist = false, share = false }?)` is the path the picker uses after it reads the file (`persist = false`: session only; `share = false`: kept off the room's list); `Cartlib._addFiles(files, consoleHint?, opts?)` is the same for a picker's whole selection. `_split`, `_assembler`, `_encode`, `_decode`, `_classify` and `_fetchFrom(peer, id, meta, onDone)` are exposed for tests.