# catalog
Every choice a crash-test set-up offers, read live from the installed crash parts: `car` (crashCars), `carLook`, `dummy` (crashDummies), `dummyLook`, `belt`, `obstacle` (crashObstacles, with the real test names), `readout` (crashReadouts styles), `cams` (crashCams kinds), plus `mode` (Tow / Drive / Ramp) and `airbag` (None / Front). Rows are `{ id, name, short, detail }`. Also: `ORDER`, `LABEL`, `SHORT` (chip labels, editable), `DEFAULT` / `defaultSetup()`, `SPEED_MIN/MAX/STEP` (10 / 120 / 5 km/h), `mph(kmh)`, `rigConfig(setup)` (what `CrashRig:request("prepare", ...)` takes), `protocol(car, dummy, belt, obstacle, kmh, extra?)` (a full set-up in one line), `key(config)` (stable text key), `everything()` (every id open). Used by `crashSetup.panel`, `crashSession.session` and games.
# session
`Session.new(config)` builds a crash-test game session for the local player: `:start()` registers the screen, the countdown and readout panel and shows the title; `:update(dt)` follows the synced `CrashRig` (state, config, result), runs the debounced prepare, the camera orbit, live telemetry, results, credit and the auto replay; `:callback(id, data)` handles `<prefix>:…` ids (returns true when it was one); `:enter()` opens the lab as the title's Play does; `:state()` snapshots it; `:destroy()` cleans up. Options are in the package README. Used by `crashSession.CrashSession` and games (Crumple Zone's `game.CrashGame`).
# goals
Goal kinds read off a crashRig `CrashResult`, shaped for `unlockLadder`: `KINDS.run` (reached the barrier), `stars` (rating ≥ value), `hic` (head HIC15 < value), `headG` (head peak < value g), `chest3ms` (chest 3 ms < value g). Each is `{ text(goal), met(goal, result) -> (ok, measured) }`. A result the rig marked `invalid` never meets a goal; `invalid(result) -> (bool, note)` reads it. `matches(step, result)` says whether a result is a run of `step.config` (car, dummy, belt, obstacle, speed ±1.5 km/h). Use: `Ladder.new({ goals = Goals.KINDS, match = Goals.matches, ... })`.
# ladder
`Ladder.new({ id, steps, start, goals, match, store? })` makes an unlock ladder. Steps are passed in order; each one's `reward` list of `{ category, id }` pairs unlocks items on top of `start`. API: `done()`, `complete(id, info)`, `level(done?)`, `unlocked(done?)`, `unlockedBy(cat, id)`, `goalText(goal)`, `goalMet(goal, result)`, `matches(step, result)`, `credit(result, activeId?, extra?)`, `savePref(key, v)`, `loadPref(key, default)`, `count()`, `byId`, `steps`, `session` (unsaved scratch). `Ladder.memoryStore()` gives an in-memory store for tests. Saved per player under `<id>/done/` and `<id>/prefs/` in `runtime_data.player(localId)`. Used by `crashSession` and the Crumple Zone game.
# crashSetup
The **set-up side of a crash-test game**, built on the crash parts this world ships (crashCars, crashDummies,
crashObstacles, crashReadouts, crashCams):
- **`crashSetup.catalog`**: every choice a test can use, read live from the installed parts, so a menu never
drifts from what the parts spawn: 9 cars, car looks, 6 dummies, dummy looks, 5 belts, airbags (None /
Front), 11 barriers with their real test names, launch modes (Tow / Drive / Ramp), readout styles and
replay cameras. Plus the default set-up, the 10–120 km/h range, mph, the rig config it sends and
`protocol(...)`, a whole test set-up in one line.
- **`crashSetup.goals`**: goal kinds read off a `CrashResult` (run, stars, HIC15, head g, chest 3 ms) and the
"is this a run of that protocol" rule, ready for an `unlockLadder` programme. Runs the rig marks invalid
never pass.
- **`crashSetup.panel`**: the screen's widget builders: the tabbed **set-up panel** (side panel on desktop,
bottom sheet under 720 pt) with chip grids and padlocks, a big km/h readout with − / + and a chip per
10 km/h up to 120, a numbered replay shot list, the test programme list, RUN TEST / RESET; the **top bar**,
**programme strip**, **live telemetry**, **results / replay action bar** and **toasts**.
`crashSession` runs all of this as a full game loop; use crashSetup directly to build your own.
## First example
Put this in any scene's `entrypoint.luau` and press Play: the set-up panel appears on the left, and the chips,
the tabs and the speed chooser all work.
```lua
local Catalog = require("crashSetup.catalog")
local Panel = require("crashSetup.panel")
local S = Panel.sampleState({ prefix = "demo" }) -- default set-up, every option open
local function draw()
S.W, S.H = ui.screenSize().width, ui.screenSize().height
S.compact = S.W < 720
ui.updateScreen("setupDemo", { type = "vertical", style = { width = "100%", height = "100%" },
children = { (Panel.setupPanel(S)) } })
end
function onLoad()
ui.registerScreen("setupDemo", { type = "vertical", children = {} }, 40)
ui.showScreen("setupDemo")
draw()
end
function onCallback(id: string)
local p = string.split(id, ":") -- "demo:<verb>:<args>"
if p[1] ~= "demo" then return end
if p[2] == "tab" then S.tab = p[3]
elseif p[2] == "pick" then S.setup[p[3]] = p[4]
elseif p[2] == "speedSet" then S.setup.speedKmh = tonumber(p[3])
elseif p[2] == "speed" then
S.setup.speedKmh = math.clamp(S.setup.speedKmh + (p[3] == "up" and 5 or -5), Catalog.SPEED_MIN, Catalog.SPEED_MAX)
elseif p[2] == "run" then print("send to the rig:", Catalog.key(Catalog.rigConfig(S.setup)))
end
draw()
end
```
## The state table `S`
| Field | What |
|---|---|
| `W`, `H`, `compact` | screen size in points; `compact` = phone layout |
| `prefix` | element id / callback id prefix (default `crash`) |
| `brand` | `{ title, sub, lab }` for the top bar and the panel header |
| `setup` | the set-up: `car, carLook, dummy, dummyLook, belt, airbag, obstacle, speedKmh, mode, readout, cams = {..}` |
| `unlocked` | `{ [category] = { [id] = true } }` (nil = everything open) |
| `ladder`, `done`, `level`, `activeTest` | an `unlockLadder` and its progress (optional: no ladder, no programme tab) |
| `tab`, `focus`, `focusArea`, `progFocus`, `actFocus`, `pad` | navigation highlight for keyboard / gamepad |
| `rig` | `{ present, state, message, testId }` from the `CrashRig` |
| `phase`, `live`, `replay`, `players`, `setupShown`, `panelW`, `toastTop` | what the other builders read |
## Ids
Element ids (for tests, `gui.press`, `gui.clickElement`): `<p>_setup`, `<p>_tab_<tab>`, `<p>_row_<cat>`,
`<p>_chip_<cat>_<id>`, `<p>_speed_<10..120>`, `<p>_speed_up`, `<p>_speed_down`, `<p>_cam_<kind>`,
`<p>_test_<stepId>`, `<p>_run`, `<p>_reset`, `<p>_replay`, `<p>_next`, `<p>_change`, `<p>_skip`, `<p>_free`,
`<p>_topbar`, `<p>_progress`, `<p>_live`, `<p>_actions`, `<p>_toast`, `<p>_menu`.
Callback ids: `<p>:tab:<tab>`, `<p>:pick:<cat>:<id>`, `<p>:speed:up|down`, `<p>:speedSet:<kmh>`,
`<p>:cam:<kind>`, `<p>:test:<stepId>`, `<p>:lockedTest`, `<p>:free`, `<p>:run`, `<p>:reset`, `<p>:replay`,
`<p>:next`, `<p>:setup`, `<p>:skip`, `<p>:hideSetup`, `<p>:showSetup`, `<p>:menu`.
## Gallery
`crashSetup/examples/setupGallery.scene` puts the panel's five tabs side by side, each labelled, with the top
bar, programme strip, live telemetry, the results and replay bars and a toast, drawn by
`crashSetup.examples.SetupGallery`.
## Tests
`crashSetup` suite (`zero tests run crashSetup`, edit mode): the catalog matches the installed parts row for
row, defaults and protocols, the goal kinds (and that an invalid run never passes), protocol matching, and
the panel: every documented element id is present with the right callback, locked chips carry a padlock,
the programme tab appears only with a ladder, speed chips run 10 to 120, the phone sheet layout, and that
every builder's screen registers with no validation errors.
# crashSession
The **player-facing loop of a crash-test game**, as a package: everything between "the player opens the
world" and "the player watches their crash back in slow motion", running locally on every peer off one
synced `crashRig.CrashRig`.
- **Title** (menusKit) with Play / Test Programme / Settings / Credits; pause menu on the gear.
- **Set-up** with the `crashSetup` panel: car, look, dummy, look, belt, airbags, barrier, 10–120 km/h,
Tow / Drive / Ramp, readout style and a 2–4 camera replay shot list. Edits are debounced (0.8 s) into
`rig:request("prepare", config)`, so the car and dummy are already in place when RUN TEST is pressed;
RESET rebuilds it. Locked options explain which programme test unlocks them.
- **Run**: a MatchFlow countdown, a chase camera that cuts to the high-speed side camera just before
contact, live km/h and metres to the barrier, an impact sound scaled by speed, juiceKit shake and flash.
- **Results**: the `crashReadouts` ReadoutPanel in the chosen style, then an **automatic slow-motion replay**
(`rig:replay`, ¼ speed) cut between the picked `crashCams` cameras in order, with the camera's render layers
set to `all !crash` (live wreck hidden, recorded ghosts shown) and back to `all` after; REPLAY / NEXT TEST /
SKIP / SET-UP.
- **Programme**: with an `unlockLadder`, each result is credited to the active protocol (or any open one);
passes unlock options, saved per player, with toasts. A run the rig marks `invalid` is never credited:
the toast says "Run invalid: <note>. Run it again."
- **Input**: mouse / touch, keyboard (arrows, Enter, Space = run, Q / E tabs, Backspace), gamepad.
- **Multiplayer**: any player can drive the shared rig; every peer follows its synced state, config and
result, so everyone sees the same test, results and replay.
## First example
`crashSession/examples/sessionDemo.scene` is this, ready to open. In a scene's `build.luau`:
```lua
function content()
require("crashLab.lab").build({ origin = { 0, 0, 0 }, style = "modern" }) -- the hall
entity.spawnSynced("CrashRig").component.add("crashRig.CrashRig", { origin = { 0, 0, 0 }, runup = 46 })
entity.spawn("Game").component.add("crashSession.CrashSession", { title = "MY CRASH LAB" })
end
```
Press Play, press **Play** on the title, press **RUN TEST**: the hatchback is towed into the wall at 50 km/h,
the results appear, and the replay plays from three cameras.
## A game with its own programme
Build a thin component on `crashSession.session` (this is all of Crumple Zone's `game.CrashGame`):
```lua
local Session = require("crashSession.session")
local session
function start()
session = Session.new({
prefix = "cz", screen = "myGame",
ladder = require("myGame.programme"), -- an unlockLadder (crashSetup.goals for the goal kinds)
brand = { title = "MY GAME", sub = "CRASH TEST LAB", lab = "LAB 01" },
sounds = { metal = function() return asset.resolve("myGame.sounds.hit", "soundClip") end },
title = { title = "MY GAME", items = { "play", "settings" } }, -- menusKit showTitle options
})
session:start()
end
function update(dt) session:update(dt) end
function onCallback(id, data) session:callback(id, data) end
function onDestroy() session:destroy() end
```
## Options (`Session.new`)
| Option | Default | |
|---|---|---|
| `rigName` | `CrashRig` | entity with the synced CrashRig |
| `cameraName` | `GameCamera` | local camera entity (made, priority 100, when missing) |
| `screen`, `layer` | `crashSession`, 40 | the game screen |
| `prefix` | `crash` | element / callback id prefix (crashSetup README lists the ids) |
| `brand` | `CRASH LAB` | `{ title, sub, lab }` on the top bar and panel |
| `title` | a generic title | menusKit `showTitle` options (`theme` filled in) |
| `theme`, `showTitle` | `military`, true | menusKit look; open on the title |
| `countdownStyle` | `trafficLight` | MatchFlow countdown look |
| `replaySpeed`, `replayDelay` | 0.25, 2.5 s | replay speed; seconds of results before it starts |
| `replayLayers`, `liveLayers` | `all !crash`, `all` | camera render layers during / after the replay |
| `ladder` | free lab | an `unlockLadder`; without one every option is open and there is no programme tab |
| `saveKey`, `store` | `crashSession`, the player's store | where the free lab saves prefs (`store`: an `unlockLadder` store, e.g. for tests) |
| `sounds` | none | `{ metal, crunch, glass }`: soundClip refs or functions returning them |
| `prepareDebounce` | 0.8 s | wait after the last edit before rebuilding the set-up |
| `getRig`, `clock` | | stand-ins for tests |
Methods: `start`, `update(dt)`, `callback(id, data)`, `enter()`, `state()`, `destroy()`.
## Tests
`crashSession` suite (`zero tests run crashSession`, edit mode), against a stand-in rig: the screen and
title, the debounced prepare and RUN TEST (prepare first, run when ready), following another player's set-up,
locked picks, the shot list's 2–4 limit, loading a protocol, results credited to the programme with unlocks,
an invalid run credited to nothing with its toast, a replay with no recording falling back to the results,
NEXT TEST resetting the rig, and clean-up.
# unlockLadder
An ordered **ladder of challenges** with **unlocks** and **saved progress**, for any game. Each step has a
fixed config, a goal read off whatever result your game produces, and a reward that unlocks items for free
play. Pure rules and data: no UI and no game types, so a racing game, a puzzle game or a crash-test game
uses the same module (Crumple Zone's 15-test programme is built on it, with `crashSetup.goals`).
## First example
Put this in any scene's `entrypoint.luau` and press Play; the Output shows the ladder moving.
```lua
local Ladder = require("unlockLadder.ladder")
function onLoad()
local L = Ladder.new({
id = "demoLadder", -- save key root
store = Ladder.memoryStore(), -- drop this line to save per player
start = { car = { "hatch" } }, -- unlocked from the start
steps = {
{ id = "first", title = "First lap", goal = { kind = "run" }, reward = { { "car", "coupe" } } },
{ id = "fast", title = "Under a minute", goal = { kind = "under", value = 60 }, reward = { { "car", "truck" } } },
},
goals = { under = {
text = function(g) return "Finish under " .. g.value .. " s" end,
met = function(g, r) return r.time < g.value, string.format("%.1f s", r.time) end,
} },
})
print(L:level(), L:goalText(L.steps[2].goal)) -- 1 Finish under 60 s
local c = L:credit({ time = 72 }) -- passes "first" (run)
print(c.step.id, c.met, c.unlocked[1][2]) -- first true coupe
print(L:credit({ time = 55 }).step.id, L:level()) -- fast 3
print(L:unlocked().car.truck, L:unlockedBy("car", "truck").title) -- true Under a minute
end
```
With `store` left out, progress is saved per player: the next session starts at level 3.
## Steps, goals and matching
- A **step** is `{ id, title, sub?, std?, config?, goal = { kind, value? }, reward = { { category, id }, ... } }`.
`index` is filled in. `config` is yours (the set-up the step fixes); the ladder never reads it.
- A **goal kind** is `{ text = function(goal) -> string, met = function(goal, result) -> (boolean, valueText) }`.
`run` (always met) is built in; pass your own in `goals`.
- `match(step, result) -> boolean` says whether a result counts for a step (default: every result does).
`credit(result, activeId?)` tries the active step first, then every open step not yet passed, and returns
`{ step, met, value, already, unlocked, nextStep }` for the first match (nil when none). A met goal is
saved with `complete`.
## API
| Call | Returns |
|---|---|
| `Ladder.new(opts)` | a ladder; `opts`: `id`, `steps`, `start`, `goals`, `match`, `store` |
| `L:done()` | `{ [stepId] = info }` of passed steps |
| `L:complete(id, info?)` | saves a pass |
| `L:level(done?)` | index of the first unpassed step (`count()+1` when all are) |
| `L:unlocked(done?)` | `{ [category] = { [id] = true } }` |
| `L:unlockedBy(cat, id)` | the step that unlocks it, or nil |
| `L:goalText(goal)`, `L:goalMet(goal, result)`, `L:matches(step, result)` | goal rules |
| `L:credit(result, activeId?, extra?)` | the credit record above |
| `L:savePref(key, v)`, `L:loadPref(key, default)` | per-player preferences |
| `Ladder.memoryStore()` | a store for tests (`store = Ladder.memoryStore()`) |
## Saving
`runtime_data.player(runtime_data.localId())`, under `<id>/done/<stepId>` and `<id>/prefs/<key>`. Only the
local player's own store is written, so it works the same on every peer. A guest (no id) keeps progress in
memory for the session. Pass `store` (anything with `get`, `set`, `list`) to keep it elsewhere.
## Tests
`unlockLadder` suite (`zero tests run unlockLadder`, edit mode): levels, unlocks, `unlockedBy`, goals,
matching and crediting (active step first, a failed goal saves nothing, a re-pass is `already`), prefs, a
custom store, and the first example above run as written against a memory store.