# ValleyGame
The Torque Valley game layer, and only glue: it wires installed kits together and holds no game
logic of its own. On the host it spawns the AI field (synced torqueCars cars, each with an AiDriver
personality and an EngineVoice) along the country loop. On every peer, for its own player: the
navUiKit minimap with valley landmarks, the controlsKit racing scheme (touch and gamepad), a
gaugeClusters dash, juiceKit crash shake scaled by impact speed, soundstage music, and driver
progression from **driveProgress** — a `DriverProgress` component added to the same entity with the
valley's four challenges (150 km/h on the west straight, a 4 s drift, 1.5 s of air in the stunt park,
60 km/h into the crash wall), a barsKit XP bar and damage bar, and toasts. Put it on one scene
entity. Fields: `aiCount`, `music`, `gaugeStyle`, `progressStyle` (arcade, career, stunt, drift,
zen; switches live). Methods: `progress()` (the driver's progression), `driver()` (the
DriverProgress component).
# driveProgress.styles
The five driver progression styles as data — `arcade`, `career`, `stunt`, `drift`, `zen`. Each holds
its level curve (flat, linear, steep or quadratic), whether only personal bests count, per-event
tuning for speed, drift (slip angle, chain window, combo bonus), air, crash and distance, rank names,
toast wording templates and spacing, the barsKit looks for the XP and damage bars, and its default
challenges. `S.ids()`, `S.get(id)`, `S.has(id)`, `S.need(style, level)`, `S.rank(style, level)`,
`S.fill(template, t)`. Read by `driveProgress.score`, the components and anyone tuning a style.
# torqueValley.layout
Where everything in Torque Valley stands, as data: terrain size, the country loop, spur and dirt
loop control points, the proving-ground lanes, feature zones (stunt park, crash zone, frozen lake,
skid pad, car park), player spawn slots and the AI field (kind, personality, look). Read by the
valley scene's build and by ValleyGame.
# valley
Torque Valley, the driving sandbox: a 720 m valley of meadow-painted terrain ringed by hills,
assembled entirely from installed parts. Every joining player gets their own car (a rally car
by default; G opens the garage to change kind, look, paint, engine, gearbox, diff and tyres).
- A 1.3 km country-road loop with a roundabout, a highway spur and a dirt rally loop (roadPieces).
- A proving ground of eleven 128 m surface lanes (tarmac to ice) with puddles, an oil patch and
rumble strips on its apron (driveSurfaces) — the braking-distance test bed.
- A frozen lake on a snow field, a concrete skid pad, a stunt park (ramps, kicker, banked turn,
sand landing pit) and a crash zone (wall, guardrail, tyre wall).
- Seven AI cars with different personalities on the loop (aiDrivers), engine voices on every
car (engineVoices), switchable cameras (driveCams), a gauge cluster (gaugeClusters), minimap
(navUiKit), touch/gamepad racing controls (controlsKit), crash shake (juiceKit), music
(soundstage) and driver progression (driveProgress: XP, levels, the valley's challenges, a barsKit
XP bar and damage bar).
`build.luau` states all of it; `torqueValley.layout` holds the positions.
## Performance
Measured on the native desktop engine **inside the editor**, in a freshly restarted engine,
with the player car and seven AI cars driving the loop: **29–45 fps, typically ~35 (a 27 ms
frame)**. Where it goes: physics 5.4 ms (soft-body shells 1.8 of it), the eight car
controllers in the physics step 3.7 ms (AI cars beyond 60 m run theirs every other step),
scripts 3.7 ms (cars 1.2, AI drivers 1.0, minimap 0.6, gauges 0.5, engine voices 0.45),
rendering 11.4 ms of which 4.4 ms is UI preparation that includes the editor's own panels.
60 fps with eight cars is **not reached in the editor**; a standalone player without the editor
panels saves part of the render and UI time, but that was not measured here.
**Web (#20946, not run here):** open the published world in a desktop browser with WebGPU,
let the AI field spread out (about 20 s), then read the frame rate with `renderer.framePacing()`
in the console (or the browser's FPS meter). Check also: engine voices start after the first click
(browser audio unlock), the touch controls appear on a phone, and `Physics.worldState().step.softBodyMs`
stays under ~5 ms.
# torqueValley
**Torque Valley**, a BeamNG-spirited driving sandbox, as one package that only puts other packages
together. Drive, drift, jump and crash a dozen drivetrain-simulated cars around a 720 m valley;
everything that drives, sounds, films, scores or draws comes from an installed kit, and this package
holds the place and the glue.
## What it holds
| Part | What it is |
|---|---|
| `valley` (scene) | The sandbox: meadow valley ringed by hills, a 1.3 km country loop with a roundabout, highway spur and dirt rally loop, an eleven-lane surface proving ground (tarmac to ice), a frozen lake, skid pad, stunt park and crash zone. Every joining player gets their own car. |
| `ValleyGame` (component) | The glue: AI field on the host, and per player the minimap + landmarks, racing controls, gauge cluster, crash shake, music and driver progression. |
| `layout` (module) | Where everything stands, as data: loop and spur points, zones, spawns, the AI field. |
| `landscapes/valley` (terrain data) | The valley's heightfield and paint. |
| `cover.jpg` | The world cover. |
## The kits it puts together
| Kit | What it brings to the valley |
|---|---|
| `torqueCars` | The cars (12 kinds × 3 looks, real drivetrains, soft-body dents) and the garage (G). |
| `driveSurfaces` | Grip per ground: tarmac, wet, gravel, mud, sand, snow, ice… |
| `roadPieces` | The roads, roundabout and kerbs. |
| `aiDrivers` | Seven AI drivers with personalities on the loop. |
| `engineVoices` | Engine, shift, skid and crash sounds for every car. |
| `driveCams` | Chase, cockpit, hood, bumper, orbit, TV, heli and rear cameras (C). |
| `gaugeClusters` | The dash (`gaugeStyle`). |
| `driveProgress` | Driver XP and levels for speed, drift chains, air and crashes, the valley's challenges, toasts (`progressStyle`). |
| `barsKit` | The XP bar and body-damage bar driveProgress draws. |
| `navUiKit` | Minimap with landmarks, objective tracker, toasts. |
| `controlsKit`, `juiceKit`, `soundstage`, `groundMaterials` | Touch/gamepad racing scheme, crash shake, music, ground looks. |
The package itself is glue: 325 lines of its own code against about 16 200 lines of the
kits above that the game actually runs, a 98 % reuse share. `REUSE.md` at the world's root
rates each kit by how much of it the game uses.
## Play it
The world's startup scene is `torqueValley.valley`. To open it elsewhere:
```lua
layers.load(asset.ref("torqueValley.valley", "scene"))
```
Tune the game on the `ValleyGame` entity in the scene: `aiCount` (7), `music` (`synthwave`),
`gaugeStyle` (`digital`), `progressStyle` (`arcade`; also `career`, `stunt`, `drift`, `zen`).
In play, `ValleyGame:progress()` answers the driver's XP, level, bests and challenges.
Controls: W/S throttle and brake, A/D steer, Space brake, Ctrl handbrake, E/Q shift, M auto/manual,
R reset, Backspace respawn, G garage, C camera.
## Tests
`tests/torqueValley` checks the layout data and the glue: `asset.resolve("torqueValley", "testSuite"):run()`
in edit mode.
## Known limits
- Driver progression is local and not saved between sessions (see driveProgress).
- The editor build runs about 35 fps with eight cars (see the valley scene's README for where the
time goes); a second real client has not been connected yet.
# driveProgress
Driver progression for driving games: **XP and levels earned by how you drive**,
plus challenges, in **five styles switched by one setting**. It reads only the
driving contract's shared values (`car.kmh`, `car.impactCount`,
`car.impactSpeed`, `car.damage`, see `torqueCars.package/CONTRACT.md`) and the
chassis' own motion, so it works with any car that writes them.
What scores:
- **Top speed**: milestones (every 10–40 km/h above a floor, per style).
- **Drifts**: the rear sliding out (slip angle between where the car points and
where it travels) at speed. Slides close together **chain into a combo** that
multiplies; a hard crash can wipe a running chain.
- **Air time**: seconds with no ground under the car, scored on landing.
- **Crashes**: closing speed of each hard hit.
- **Distance**: every few hundred metres driven.
- **Challenges**: speed / drift / air / crash / distance / level / combo targets,
or `custom` ones your game completes, each with an XP reward.
On screen it draws an **XP bar** (and a **body-damage bar** from `car.damage`)
with **barsKit**, and announces awards, level-ups and challenges as
**navUiKit** toasts and objectives. Both are optional: without them it still
scores and writes values.
## First example
In a world with **torqueCars** (for a car), **navUiKit** and **barsKit**
installed, paste this into your scene's `entrypoint.luau`:
```lua
local Assemble = require("torqueCars.assemble")
function onLoad()
Assemble.spawn({ kind = "rally", position = vector.create(0, 0.3, 6) }) -- your car (W/S/A/D)
local hud = entity.spawn("progress")
hud.component.add("driveProgress.DriverProgress", { style = "arcade" })
end
```
Press Play and drive: the XP bar sits at the bottom centre with your level and
rank, a damage bar above it, toasts pop for speed, drifts, jumps and crashes,
and the style's challenges appear in the objective tracker. Switch the style
live, any time (XP is kept, the level follows the new curve):
```lua
entity.find("progress").component.get("driveProgress.DriverProgress").style = "career"
```
With `car` left empty the component follows **the local player's own car**
(torqueCars' registry, else the player's avatar, else what the camera follows).
## The styles
| style | curve | what scores | feel |
|---|---|---|---|
| `arcade` (default) | linear, 250 XP + 60 per level | everything, every time | big numbers, a toast for every trick, bubbly bar |
| `career` | steep, 400 XP × 1.3 per level | **personal bests only**; crashes score nothing and break the drift chain | formal wording, ranks Novice → Hall of Fame, segmented bar |
| `stunt` | quadratic, 120 × level² | air ×2 and crashes ×2, speed barely | "WRECKED at 92 km/h", hologram bar, blood damage bar |
| `drift` | linear, 300 + 80 per level | drift chains only (multiplier up to ×9.4), a crash wipes the combo | combo-chasing, thin bar, no damage bar |
| `zen` | flat, 500 per level | kilometres driven and smooth slides; no crash scoring | quiet: only level-ups and challenges are announced |
Each style is plain data in `driveProgress.styles` (`S.get("stunt")`): the
curve, the per-event tuning (thresholds, XP rates, chain window and bonus), the
rank names, toast wording with `{value} {xp} {links} {level} {rank} {text}`
tokens, toast spacing, the barsKit looks and its default challenges.
## DriverProgress settings
| Setting | Default | What it does |
|---|---|---|
| `style` | `arcade` | `arcade`, `career`, `stunt`, `drift`, `zen`. Switches live. |
| `car` | empty | The car to score. Empty = the local player's own car. |
| `manual` | `false` | Read no car; score only what you `feed(sample, dt)`. |
| `xpBar` | `true` | barsKit XP bar on screen. |
| `damageBar` | `auto` | `auto` (the style decides), `on`, `off`. |
| `barAnchor` | `bottomCenter` | barsKit anchor for both bars (clear of navUiKit's compass and minimap). |
| `barSize` | `1` | Extra bar scale. |
| `toasts` | `true` | navUiKit toasts for awards, level-ups, challenges. |
| `objectives` | `true` | Challenges in navUiKit's objective tracker (personal to this player). |
| `defaultChallenges` | `true` | Start with the style's challenges; off = only yours. |
| `writeValues` | `true` | Write the `driver.*` values. |
Methods (colon calls): `progress()`, `reset()`, `setStyle(id)`,
`addChallenge(def)`, `removeChallenge(id)`, `completeChallenge(id)`,
`challenges()`, `bonus(xp, why?)`, `feed(sample, dt)`, `recent()`, `target()`.
`progress()` answers `{ style, xp, level, into, need, frac, rank, best = { speed,
drift, air, crash, links }, totals, live = { drift, combo, air, damage,
distance }, challenges, car }`.
A challenge: `{ id, text, kind, target, xp }` with `kind` `speed` / `crash`
(km/h), `drift` / `air` (seconds), `distance` (metres), `combo` (links),
`level`, or `custom` (completes only through `completeChallenge`).
```lua
local dp = entity.find("progress").component.get("driveProgress.DriverProgress")
dp:addChallenge({ id = "ice", text = "Drift 3 s on the frozen lake", kind = "custom", xp = 300 })
-- later, from your own zone check:
dp:completeChallenge("ice")
```
## Values it writes
On the component's entity and on the car being scored (the `topics/values`
guide): `driver.xp`, `driver.level`, `driver.levelFrac` (0..1 into the level),
`driver.combo` (links in the running drift chain), `driver.drift` (seconds in
it), `driver.air` (seconds airborne now), `driver.distance` (metres).
## Without the component
`driveProgress.score` is the whole scoring core as pure functions, for a HUD of
your own, a server, or tests:
```lua
local Score = require("driveProgress.score")
local st = Score.new("career")
Score.addChallenge(st, { id = "fast", text = "Reach 150 km/h", kind = "speed", target = 150, xp = 250 })
local events = Score.step(st, { kmh = 152, speed = 42, slip = 3, airborne = false,
impactCount = 0, impactSpeed = 0, damage = 0 }, 1 / 60)
for _, ev in events do print(ev.kind, ev.xp, ev.text) end
print(Score.levelInfo(st).level)
```
`driveProgress.reader` turns a car into that sample (`Reader.resolve(car)`,
`Reader.sample(id)`).
## Gallery
`gallery` (a scene) shows all five styles side by side, each scoring the same
scripted drive (flat out to 170 km/h, a three-slide drift chain, a jump, a
75 km/h crash), with its level, rank, barsKit XP bar, event feed in its own
wording and its challenges:
```lua
layers.load(asset.ref("driveProgress.gallery", "scene"), { additive = true })
```
Or put `driveProgress.ProgressGallery` on any entity.
## What is inside
| Part | What it is |
|---|---|
| `DriverProgress` (component) | Scores a car, writes values, toasts, objectives, XP + damage bars. |
| `ProgressGallery` (component) | All styles scoring one scripted drive, side by side. |
| `score` (module) | The pure scoring core. |
| `styles` (module) | The five styles as data. |
| `reader` (module) | Car → sample (contract values, slip angle, airborne ray). |
| `gallery` (scene) | The gallery, ready to load. |
| `tests/driveProgress` (test suite) | Scoring, styles, challenges and the component API. |
## Multiplayer
Progression is per player and local: each peer scores **its own** car and draws
its own bars and toasts; objectives are personal (`player = "local"`). Nothing
is synced. `car.kmh`, `car.damage` and slip are written on the car's owner, so
pointing `car` at someone else's car only gets the replicated values (crashes)
there.
## Known limits
- **Progress is not saved** between sessions; persist `progress().xp` yourself
(for example with a save kit) and restore it with `bonus(xp)` on load.
- **Air time uses a 2.2 m ground ray** under the chassis unless the car
publishes `car.airborne`; a car over a deep gap counts as airborne, a very
tall vehicle may not be detected airborne on small hops.
- **Slip angle is measured from the chassis velocity**, not the tyres, unless
the car publishes `car.slip`: a car sliding backwards past 110° does not
count as a drift.
- Crash scoring needs `car.impactCount` / `car.impactSpeed`; a plain
`VehicleController` car without them scores no crashes.
- Toasts and objectives need **navUiKit** (the component starts its HUD in play
if nothing has yet); bars need **barsKit**. Without them the component still
scores and writes values.
- The XP and damage bars share one barsKit anchor (`barAnchor`); move them if
your game already has a bar there.