# 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).
# valley
The Torque Valley landscape: a 720 m square at 2.5 m a cell, with a flat-to-gently-rolling valley floor about 460 m across (flattened pads for the proving ground, car park, skid pad, stunt park, crash zone and a frozen lake bed) ringed by grassy and rocky hills rising 55 to 95 m. Painted with the groundMaterials meadow mix (short and long grass, dry grass on tops, dirt on banks). Built by groundMaterials GroundLandscape; stands under the torqueValley.valley scene with a Terrain and GroundTerrain component.
# 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.
# torqueValley tests
Checks the torqueValley package: its identities still resolve after it became a package (the
`torqueValley.valley` scene, `torqueValley.layout`, `torqueValley.ValleyGame`) and the world's startup
scene names the valley; the layout data is sane (loop inside the terrain, eight spawn slots, seven AI
slots, zones on the valley floor, eleven proving-ground lanes); and ValleyGame is glue — its fields
and defaults, a progression style driveProgress knows, and no scoring logic of its own. It leaves
alone what needs play (AI spawning, HUD, scoring), which the valley's play test covers.
Run it in edit mode:
```lua
return asset.resolve("torqueValley", "testSuite"):run()
```
# 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.
# AiDriver
An AI driver for the car it sits on. Put it on a car's chassis: a torqueCars `Car` (driven through `Car:setIntent`) or a builtin `VehicleController` (driven through its own `setIntent`, throttle -1..1). It only thinks on the peer that owns the car (`entity:isLocal()`), at the personality's rate (15-40 Hz), and keeps its inputs between ticks.
What it does each tick: finds where it is along its line (nearest point, searched in a window around the last one; a whole-path search only after a knock), steers by pure pursuit at a lookahead that grows with speed plus yaw-rate feedback (damps the weave and catches oversteer), takes a target speed from the curvature ahead (`v = sqrt(latG * 9.81 / k)`, pulled down before corners by its braking deceleration), keeps a gap to the car ahead (a cone in front of it, against a car list shared by every driver and refreshed once a second), overtakes or goes round a stopped car, gets itself unstuck (under 1.5 m/s for 2 s, for any reason: 1.6 s reverse with the nose swinging toward the path, the other lock on each retry; still slow at 5 s, or 8 s without gaining 6 m along the path, 4 s when far off the road: respawned on its line at the nearest clear point ahead, no other car within 8 m, drift or tourist manoeuvre cancelled), resets upright when flipped for 2 s, and drives back to its line after being knocked off. It learns the car: the braking it plans for drops to what it measures, and the cornering g drops a little each time it runs wide.
**Fields:** `personality` (commuter, aggressive, racer, drifter, tourist), `path` (a roadPieces road, or an entity whose children are waypoints in order), `loop`, `autoPath` (follow the nearest roadPieces road when nothing else is given), `roadWidth`, `laneOffset` (-1 = the personality's lane), `speedLimit` (m/s, 0 = none), `driving`, `seed`, `aimOffset` (metres right of its own line to aim for, kept inside the road: a pickup to grab), `pace` (0.3 to 1.6, multiplier on the speed it plans, read every tick: rubber-banding).
**vehiclesKit vehicles:** on a vehiclesKit `Vehicle` (whose VehicleController is stepped from the Vehicle's own intent every physics step) the driver drives through `Vehicle:setIntent`, braking at a stop to reverse. When a person sits in the driver's seat it hands the controls back (`setIntent(nil)`) and waits until the seat is free again.
**Methods:** `setPath(points, loop)`, `clearPath()`, `setPersonality(name)` (any name defined in `aiDrivers.personalities`), `laps()` → `{ count, last, best, times, current }` (physics seconds, start-line crossing to crossing), `state()` (mode, index, offPath, speed, targetSpeed, pedals, drift phase, body `slip`, `rearSlipAngle`/`rearSlipMean`/`rearSlipMax`, tourist state, stuck/reset counts, `slowTime`/`noProgressTime`/`reverseTries`/`lastRecovery`, learned `planGrip`/`planDecel`), `stats()` → `{ avgTickMs, maxTickMs, ticks, rate, msPerSecond }`, `resetStats()`, `linePoints()`, `respawnOnPath()` (nearest clear point on its line).
**Values it publishes** on the chassis: `ai.hazard` (stopped or lost; replicated), `ai.lap`.
```luau
local Assemble = require("torqueCars.assemble")
local car = Assemble.spawn({ kind = "coupe", position = vector.create(0, 0.3, 0), control = "script" })
local ai = car.component.add("AiDriver", { personality = "racer", roadWidth = 9 })
ai:setPath({ vector.create(0, 0, 0), vector.create(0, 0, -120), vector.create(60, 0, -150), vector.create(80, 0, -20) }, true)
```
# torqueCars.assemble
Builds a whole car under one chassis entity from a kind and part names: dynamic chassis with its centre of mass at the kind's height and weight split, four `WheelCollider` wheels with the tyre set's grip curve and drawn wheels, the `ShaftNetwork` drivetrain for the drive layout, and the plastic `SoftBody` shell held along the cabin floor. Idempotent: running `build` again updates the car in place (a live part swap). `spawn` builds a car and adds the `Car` component (synced in play).
```luau
local Assemble = require("torqueCars.assemble")
local car = Assemble.spawn({ kind = "pickup", look = "toy", position = vector.create(0, 0.2, 0), yaw = 0 })
```
# roads (roadPieces.roads)
Procedural road and track pieces with real geometry: straight, curve, T and X junctions (filleted corners, stop lines), roundabout (kerbed island, arms clipped to the ring, give-way lines), ramp, kicker jump with table-top landing, banked turn (inside kerb, outside wall), guardrail, concrete wall, tyre wall, and a Catmull-Rom spline road through any list of points that follows their heights. Three styles switched by one name: country (narrow two-lane tarmac, faded dashed centre line, grass verges, marker posts), highway (four lanes, edge lines, double centre line, concrete barriers) and dirt (rutted dirt track with gravel shoulders and a grass crown, no markings). `build(spec)` makes the mesh data, `realize(root, built, style)` stands it up as temporary children with static exact MeshColliders and driveSurfaces Surfaces, `spawn(kind, opts)` and `spline(points, opts)` place a RoadPiece, `pathOf(road, offset?)` returns its centreline in world space for AI drivers, and `gallery(parent)` lays out every piece in every style.
# EngineVoice
The sound of a car. Put it on a car's chassis entity, the one that carries the driving contract's `car.*` named values, and it plays the engine, gear changes, rev limiter, turbo, tyre skids and crashes from those values. It needs no sibling component: any entity that writes `car.rpm`, `car.load` and the rest gets a voice, a `torqueCars` car, another car kit, or the `EngineVoiceDemo` stand-in.
It spawns local child entities, each with a spatial `Audio` source at `doppler = 1`, so passing cars drop in pitch:
- six engine layers, three rpm bands times on-load and off-load. They crossfade by rpm (equal power, in log rpm) and by `car.load`, and each is pitched to `rpm / band reference rpm`;
- an aux layer: the turbo whistle that follows `car.boost` (turbo, diesel) or the inverter whine (electric);
- a skid loop whose volume follows `car.skid` and whose clip changes with `car.surfaceId`: tarmac squeal, gravel crunch, soft scrub;
- a one-shot host for gear changes (`car.shiftCount`), overrun pops, blow-off on lift, limiter stutter pops and crash crunches (`car.impactCount`, scaled by `car.impactSpeed`).
The values replicate and the component runs on every peer, so every player hears every car.
## Fields
| field | default | meaning |
|---|---|---|
| `voice` | `auto` | `auto` follows `car.voiceId`. Set a name to force a voice: `four`, `v8`, `v12`, `diesel`, `rotary`, `turbo`, `electric`, `kart`. It can be changed live. |
| `volume` | 1 | multiplier for everything this car sounds |
| `maxDistance` | 160 | metres to silence |
| `shiftStyle` | `auto` | `auto` reads the `Car` component's gearbox mode, falling back to the voice's default; or `manual`, `sequential`, `automatic`, `none` |
| `skids`, `crashes` | true | turn those sounds off |
| `doppler` | 1 | Doppler scale on every source |
`:mix()` returns what the voice is doing this frame: the voice, the smoothed rpm, load and boost, the band weights, the on-load and off-load gains, the level, the skid level and kind, and the ids of its sources. Read those ids with `audio.voice(id)`.
```lua
car.component.add("EngineVoice") -- voice from car.voiceId
car.component.get("EngineVoice").voice = "rotary" -- switch it live
print(car.component.get("EngineVoice"):mix().bands[2])
```
# GaugeCluster
Puts one car gauge cluster (speed, revs with redline zone, gear) on the local
player's screen in one of ten styles: `analog`, `digital`, `rally`,
`retro80s`, `scifi`, `minimal`, `arcade`, `pixel`, `hud`, `truck`. `style`
switches the look live. Attach it to any entity (an empty one is fine); it
needs no sibling components.
It reads the driving contract's values (`car.kmh`, `car.rpm`, `car.gear`,
`car.rpmRedline`, `car.rpmMax`, ...) from `car`, or, with `car` empty, from the
local player's own car (their avatar or what it sits in, else what the main
camera follows). A plain `VehicleController` car shows speed, 0 rpm, gear `-`.
```lua
entity.spawn("hud").component.add("GaugeCluster", { style = "rally", units = "mph" })
entity.find("hud").component.get("GaugeCluster"):cycleStyle()
```
Fields: `style`, `units` (kmh|mph), `car`, `anchor` (auto, bottomRight,
bottomCenter, bottomLeft, topRight, topCenter, topLeft, hud), `size`,
`maxSpeed`, `offsetX`, `offsetY`, `visible`. All NoSync: the cluster is a
personal overlay. Methods: `setStyle(id)`, `cycleStyle(dir?)`, `target()`,
`reading()`. The screen it registers (`gaugecluster_<entity id>`) goes when
the component does.
# torqueCars.cars
The live torqueCars cars on this peer: `all()` returns every chassis id, `localPlayer()` the chassis this peer's player drives. The `Car` component registers and unregisters itself; gauges, cameras, the garage and AI use it to find cars cheaply.
```luau
local Cars = require("torqueCars.cars")
print(#Cars.all(), Cars.localPlayer())
```
# DriverProgress
Gives a driver XP, levels and challenges. Put it on any entity (an empty one is fine; it needs no
sibling components). Each frame in play it reads a car — the `car` field, or the local player's own
car when empty — through `driveProgress.reader`, scores top speed, chained drifts, air time, crashes
and distance with `driveProgress.score` under its `style` (arcade, career, stunt, drift, zen; switch
live, XP kept), writes `driver.xp`, `driver.level`, `driver.levelFrac`, `driver.combo`,
`driver.drift`, `driver.air` and `driver.distance` values, announces awards, level-ups and
challenges as navUiKit toasts and personal objectives, and keeps a barsKit XP bar (and a
body-damage bar from `car.damage`) on screen. navUiKit and barsKit are optional.
Methods: `progress()`, `reset()`, `setStyle(id)`, `addChallenge(def)`, `removeChallenge(id)`,
`completeChallenge(id)`, `challenges()`, `bonus(xp, why?)`, `feed(sample, dt)` (score a sample by
hand; with `manual = true` it reads no car), `recent()` (the last events), `target()`.
# 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.
# Garage
The in-game parts panel. Put it on any scene entity; it opens when the local player's car asks (G, d-pad up, or the touch Garage button) and lists every car kind, look, paint, engine, gearbox, diff and tyre set, plus switches for ABS/traction control and auto shift and a repair button. A click applies the part to the car at once through `Car:setPart`.
```luau
entity.spawn("Garage").component.add("Garage", { startOpen = true })
```
# surfaces (driveSurfaces.surfaces)
The table of driving surfaces and the per-wheel lookup. Fourteen surfaces in a fixed order (tarmac, wetTarmac, concrete, cobbles, gravel, dirt, mud, grass, sand, snow, ice, rumble, puddle, oil; the index is the driving contract's `car.surfaceId`), each with grip, slide grip, stiffness, rolling resistance, bogging drag, roughness, dust colour, skid sound, tyre class and the material it wears. `sample(hitEntityId, position)` answers the surface under a wheel contact: a SurfacePatch zone there first, else the Surface component on the hit entity or its nearest ancestor, else tarmac, cached per entity id so it costs about 0.25 µs. Also `names`, `list`, `get`, `byId`, `ofEntity`, `patchAt`, `material`, and authoring helpers `paint(entity, kind)`, `pad(kind, position, opts)`, `patch(kind, position, opts)` and `gallery(parent)`. Called by torqueCars' cars per wheel per physics tick, and by anything that wants to know the ground (skid sounds, dust, AI caution).
# DriveCam
Switches the camera it sits on between eight car views with one setting,
`mode`: `chase`, `cockpit`, `hood`, `bumper`, `orbit`, `tv`, `heli`, `rear`.
Attach it to an entity with a `Camera` (the player prototype's camera rig
included). It writes the Camera's `behavior` to the right rig (the builtin
chase, mount or orbital_follow, or this package's TvCam / HeliCam), tunes it
for the car (distance from the car's size, mount points from
`car.mountSeat` / `car.mountHood` / `car.mountBumper`), sets the field of view,
and in chase widens it with speed.
```lua
cam.component.add("DriveCam", { mode = "chase", car = myCar })
cam.component.get("DriveCam"):cycle()
```
With `cycleKey` on, the `cycleCamera` control of `driveCams.cameraControls`
(C, right-stick press / d-pad up, a CAM touch button) steps through
`cycleModes` (all eight when empty). Fields: `mode`, `car`, `cycleKey`,
`cycleModes`, `speedFov`, `fovBoost`, `fovSpeed`, `orbitSpin`, `inputMap`.
Methods: `cycle(dir?)`, `setMode(mode)`, `info()`.
# Car
The driver of a torqueCars car. Sits on the chassis `torqueCars.assemble` builds (with its `Physics`, `CompoundCollider`, `ShaftNetwork`, four `WheelCollider` children and the `SoftBody` body). Each physics step on the owning peer it runs the engine (throttle, idle governor, turbo, rev limiter), the automatic clutch, the gearbox (auto or manual shifts, reverse), brakes with ABS, traction control, speed-sensitive steering, per-wheel ground grip from driveSurfaces, drag and rolling resistance, and counts crashes. It publishes the driving contract's named values every frame (see the package's CONTRACT.md).
Fields: `kind`, `look`, `paint`, `engine`, `gearbox`, `diff`, `tyres` (changing any rebuilds the car in place), `control` (player / script / none), `autoShift`, `assists`, and the script intent fields.
Methods: `setIntent{throttle, brake, steer, handbrake, reverse}`, `shiftUp()`, `shiftDown()`, `setPart(slot, name)`, `reset()`, `respawn(pos?, yaw?)`, `setSpawn(pos, yaw)`, `gearLabel()`, `info()`, `telemetry()`.
```luau
local car = require("torqueCars.assemble").spawn({ kind = "drift", position = vector.create(0, 0.2, 0), control = "script" })
car.component.get("Car"):setIntent({ throttle = 0.5, steer = 0.3 })
```
# Surface
Says which driving surface an entity is (`kind`: tarmac, wetTarmac, concrete, cobbles, gravel, dirt, mud, grass, sand, snow, ice, rumble, puddle or oil; synced). Every descendant without a Surface of its own reads the same, so a road's deck, a car park or a field needs it once on its root. `driveSurfaces.surfaces.sample` reads it for a wheel's hit entity; `Surfaces.paint(entity, kind)` adds it together with the surface's material. Needs no sibling component; a collider somewhere in the hierarchy is what wheels actually hit.
# RoadPiece
Turns its entity into a road or track piece: `kind` (straight, curve, tJunction, xJunction, roundabout, ramp, kicker, bankedTurn, guardrail, wall, tyreWall, spline), `style` (country, highway, dirt) and size fields (`length`, `radius`, `angle`, `bank`, `slope`, `height`, `gap`, `width`, `arms`, `verge`, `rails`, `points`, `loop`), all synced. It builds the geometry locally on every peer as temporary child entities (one per material, each with a static exact MeshCollider, verges/kerbs/walls with their own driveSurfaces Surface) and rebuilds whenever a field changes, so one setting restyles the piece. It also gives the entity a Surface matching the style (tarmac or dirt). Inside a scene build it records itself and builds right after, so scenes store only the fields. `:path(offset?)` returns the centreline in world space.
# SurfacePatch
A zone of one driving surface laid over whatever ground is under it: a puddle, an oil spill, a rumble strip, a patch of mud on tarmac. The zone is the entity's unit box times its world scale, turned with the entity, with the entity's origin on the ground; wheels inside it read this surface before anything they hit. It registers itself into driveSurfaces' flat patch list on awake, follows its entity, and unregisters on destroy. It also draws its own look flush on the ground (`showLook`): dark glossy water for a puddle, a black film with a thin-film rainbow sheen for oil, raised red/white ribbed kerb stripes along local Z for rumble, a thin slab of the surface's material for anything else. Fields `kind` and `showLook` are synced. Needs no sibling component and no collider.