# rng
The game's only source of chance: a small seeded generator, so a run can be replayed.
```
Every system that rolls (scatter of a paint gun, a Warden's aim, an arrangement found out, which variants a
board offers today) takes a generator from here, forked by name so one system's rolls do not shift another's.
local Rng = require("metropolisGame.logic.rng")
local rng = Rng.new(20261122)
rng:next() -- [0, 1)
rng:int(1, 6) -- whole number, both ends included
rng:pick(list) -- one element (nil for an empty list)
rng:shuffle(list) -- a shuffled copy
local f = rng:fn() -- a plain function () -> [0, 1) on the same stream (what the kits take)
local arms = rng:fork("arms") -- an independent stream derived from this one's seed and a label
Rng.hash("old_quay:3") -- a stable whole number for a string (seeding by name)
rng:serialise() Rng.restore(data)
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# interfaces
Everything the game needs from the scene, as thirteen narrow interfaces, with a
```
checker the host runs once at start so a missing function is an error with a name on it and not a nil call
three minutes into play.
The game's rules (logic.game, logic.session) are engine-free and are fed plain data. `logic.driver` is the
engine-free half of the host: every tick it reads these interfaces, builds each player's frame, runs the game,
moves the Wardens, flies nothing itself (paint in the air is logic.gunplay, through `physics`), and turns hub
events into animation, sound, camera and UI calls. A scene supplies one small adapter per interface;
`metropolisGame.fake.world` supplies all thirteen over a simulated city, for tests.
They are cut where the published kits the project adopts already end (s3/notes/kits-scout.md), so each adapter
is thin: vehicles = vehiclesKit (seats, ownership, cameras) with aiDrivers driving the Wardens' cars; fx.shot =
projectileKit (a shot is replayed from its launch, not pushed every frame); interact = interactKit (the kit owns
"press E", prompts and holds; it TELLS the game what was used); dialogue = dialogueKit; save.player = saveKit
(flat keys); clock = the shared-anchor model of worldClockKit; input glyphs = controlsKit.
local Interfaces = require("metropolisGame.interfaces")
local ok, missing = Interfaces.checkAll(host) -- false, { "actors.play", ... }
Interfaces.check("actors", host.actors) Interfaces.describe("vehicles") Interfaces.names()
Interfaces.ACTIONS -- the input action names the game reads (the host's input maps bind them)
Interfaces.GESTURES -- the gestures the game asks actors to play
Interfaces.SOUNDS -- the audio events the game raises
Interfaces.SHOTS -- the staged camera shots it asks for
Conventions for every interface: positions are world metres, +x east, +z south, +y up (the engine's frame);
`{ x, y, z }` tables or engine vectors both work wherever a position is taken (fields x, y, z are read);
ids are strings the host chooses and keeps stable while the thing exists; nothing here yields.
city the generated city as the game reads it (the host adapts cityGen.query)
districtAt(x, z) -> districtId | nil one of content.districts' ids
place(id) -> { x, y, z, fx?, fz? } | nil where a place of content.places really is
walls() -> { { id, district, x, y, z, nx, nz, width, height } } paintable walls (the middle of each wall's foot,
its outward normal on the ground plane, its clear size)
roadGraph() -> { nodes = { [id] = { x, z } }, edges = { { id, a, b, class, bridge?, name? } } }
roadAt(x, z) -> { class, edge, fx, fz } | nil the road under a point (class: highway, boulevard, avenue,
street, lane, alley, stairs, path, pedestrian, track)
route(from, to, mode, avoid?) -> { { x, z } } | nil mode "car" | "foot"; avoid(edgeId) -> true to keep off an edge
fixtures(x, z, radius) -> { { id, kind, x, y, z, fx, fz, relay? } } fixed observers and relays near a point:
kind camera | curtain | lamp | callbox | doorman | searchlight
hideSpots(x, z, radius) -> { { id, kind, x, z } } doorways, bins, hedges, stalls, laundry lines
groundAt(x, z) -> y
actors people: the players' bodies, Wardens, security, passers-by, contacts
spawn(kind, at, opts) -> id kind: warden | security | watchman | inspector | plain | informer |
neighbour | guests | crew | rival | repair_crew | warden_off_duty | ...
at = { x, y, z, yaw? }; opts = { id?, count?, walks_to?, leaves?, stays? }
despawn(id)
pose(id) -> { x, y, z, fx, fz, speed, vx, vz, onGround } | nil
move(id, intent) intent = { mode, x, z, speed, hold } (pursuitKit pursuer): the host
writes its mover (CharacterController bus: Pursuer.characterBus)
play(id, gesture, opts?) one of Interfaces.GESTURES
ambient(x, z, radius) -> { { id, x, y, z, fx, fz, seed, atRelay?, relay? } } passers-by near a point (the host's
crowd); seed is a stable number the game deals their sympathies from
playerActor(playerId) -> id the body of a player
state(playerId) -> { hidden, concealment = { tag }, jacket, stand, mounted, blocked, facts = {} } what only the
body knows: in a hide spot, in a crowd, how high its feet are
above the street, why its hands are busy (blocked = "swimming" |
"climbing" | nil), extra mission facts (on_roof, aboard:tram, load)
teleport(id, at) the released stand on the steps of a post
vehicles everything with wheels (the host adapts vehiclesKit: spawn, of, enter, exit, setIntent, info)
spawn(type, at, opts) -> id type: a content.vehicles id; opts = { id?, colour?, plate?, state? }
despawn(id)
pose(id) -> { x, y, z, fx, fz, speed } | nil speed = forward metres a second
info(id) -> { type, colour, plate, state, driver = actorId | nil } state: parked | locked | occupied | lent | service
nearest(x, z, radius) -> id | nil the vehicle a player could take the wheel of
enter(id, actorId) -> boolean exit(actorId) -> boolean for AI crews and forced exits (an arrest); players
take a wheel through `interact`
driving(actorId) -> vehicleId | nil the vehicle an actor is at the wheel of now. The kit decides who
gets a seat; the driver notices the change and tells the session
drive(id, intent) AI driving: intent = { mode, x, z, speed, hold, ram?, slot?, path? }
(pursuitKit pursuer / vehiclePursuit). With aiDrivers: setPath(path
or the point), speedLimit = speed, driving = not hold. Without:
Pursuer.vehicleBus(intent, ...) gives throttle, steer, brake
setLook(id, { colour?, plate? })
stop(id, seconds) the driver cannot see: brake to a halt for that long
slide(id, seconds) its tyres are in paint: grip falls for that long
physics queries only (the same shape paintKit's ballistics take)
raycast(origin, dir, distance, exclude?) -> { x, y, z, nx, ny, nz, distance, kind, target?, part?, lx?, ly?, lz? } | nil
overlap(centre, radius) -> { { target, kind, part?, x, y, z } }
lineOfSight(from, to, exclude?) -> boolean
fx what paint looks like
splats(delta) paintKit splats' drain(): { added, changed, removed }
shot(shot) a projectile was launched: { id, x, y, z, vx, vy, vz, gravity, range,
pigment | hostile, arm }. Its flight is deterministic: replay it
(projectileKit PK.fire with logic = false)
shotEnd(id, hit | nil) it ended: on something (hit = { x, y, z, nx, ny, nz, kind, target }) or spent
mural(siteId, canvas) a canvas changed (draw fill / pigment)
effect(name, at, opts) a one-off: "muzzle", "burst", "slick", "smoke", "wash_hit", "wipe" ...
colour(drain) 0..1 how grey the player's picture is
audio events by name (Interfaces.SOUNDS), spoken lines by catalog key
play(event, at?, opts?) say(lineKey, speakerId?, opts?) radio(lineKey) music(state)
camera
aim(playerId) -> { origin = { x, y, z }, dir = { x, y, z }, site?, u?, v?, distance?, target?, yaw }
the reticle's ray, what it is on (a mural site with the point on it,
or a thing), and the camera's yaw in degrees
shot(name, subjects, seconds) a staged shot (Interfaces.SHOTS)
mode(playerId, name) "foot" | "aim" | "scope" | "vehicle" | "menu"
shake(playerId, amount)
input actions by name (Interfaces.ACTIONS), per player
held(playerId, action) -> boolean pressed(playerId, action) -> boolean (true on the tick it went down)
axis(playerId, action) -> number
glyph(playerId, action) -> any | nil (optional) what to draw for the control now in hand (controlsKit)
interact the things a player can use (interactKit: Interactable + its owner-decided request path)
offer(id, spec) make something usable: spec = { kind, at = { x, y, z } | nil, entity = id | nil,
range, hold (seconds, 0 = press), label = { key, values }, player = id | nil }
kinds: talk | shop | rest | garage | pick_up | hand_over | sketch | stash |
wardrobe | arrange. When a player uses it the host calls
driver:interacted(playerId, id)
withdraw(id)
dialogue conversations (dialogueKit; its presentation is metropolisUi's)
start(playerId, conversation, ctx) conversation: a content.talk id; ctx = { who, trust, band, facts, options? }.
The host reports picks with driver:choose(playerId, option) and
anything a line emits with driver:event(playerId, name, payload)
stop(playerId)
save the stores (logic.save's accessors: get(path, default), set(path, value), getTree(prefix))
world() -> accessor the shared store (runtime_data.world): needs getTree (a leaf per wall)
player(playerId) -> accessor | nil one player's own (runtime_data.player(id), or saveKit: get / set by
key are enough, getTree is not used; its migrations may stay off, the
tree carries its own version and logic.save migrates it)
clock
now() -> seconds monotonic time (for autosave cadence only)
shared() -> seconds | nil (optional, several players) a timeline every peer agrees on. With it the
game clock runs on an ANCHOR record, not on dt: every peer computes the same hour
anchor(record?) -> record | nil (optional) read, or as the clock's owner write, the synced anchor record
{ t0, total0, dayMinutes }
owner() -> boolean (optional) whether this peer may write the anchor
ui metropolisUi's app
setHud(playerId, view) show(playerId, screen, data) hide(playerId, screen) notify(playerId, note)
banner(playerId, data)
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# dispatch
Who is sent where: the response to a heat level as assignments, not as spawns.
```
Pure planning over plain tables. The host owns the units (people, cars), the road junctions and the places a
unit may enter the world; dispatch chooses among them.
local Dispatch = require("~.modules.dispatch")
local orders = Dispatch.plan(cfg, level, incidentView, units)
-- units: { { id, kind = "foot" | "car", x, z, available = true } }
-- orders: { [id] = { role = "investigate" | "pursue" | "sweep" | "cordon" | "stand", x, z } }
-- in "reported": the nearest go to the last known position; in "pursuit": every assigned unit
-- pursues it; in "search": they sweep points spread over the search area. Units beyond the level's
-- counts are told to stand (return to their beat).
Dispatch.sweepPoints(x, z, radius, n, turn) -- n points over a disc, a different spread each `turn`
Dispatch.cordon(junctions, x, z, radius, n) -- the n junctions nearest the ring of that radius
Dispatch.entry(candidates, sx, sz, minDistance, canSee?) -- where a new unit may appear: far enough, unseen
Dispatch.wanted(cfg, level) -- { foot, cars, cordon, checkpoints } for a level
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# pursuit
This game's configuration of pursuitKit: Verrane's Wardens and New Tide's
```
private security, the people and lenses that watch, what counts as an offence, how the Wardens escalate
(greywash, cars, road blocks), what taking a vehicle costs, and what an arrest takes away.
local PursuitContent = require("metropolisGame.content.pursuit")
local cfg = PursuitConfig.merge(PursuitConfig.DEFAULTS, PursuitContent.config) -- pursuitKit.modules.config
PursuitContent.bill -- rules for pursuitKit's Arrest.bill (the Wardens' bill)
PursuitContent.eject -- the bill when security throws Wren off New Tide
PursuitContent.escapeRenown -- renown per heat level for getting away
PursuitContent.breakFree -- { tins } paint spent spraying a way out of a grab
PursuitContent.units -- response unit kinds: actor / vehicle the host spawns, pursuer profile, observer kind
PursuitContent.actFor(tool, permitted, tolerated) -- the act name for painting with a tool
PursuitContent.fireAct -- the act while a paint arm is being fired
Numbers follow GAME_DESIGN.md §4.2 and s3/design/game_direction.md §1-2. Offence names are catalog key parts
(`pm_ui.offence.<name>`), so they are snake_case.
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# game
The game assembled: the WORLD every player shares (clock, districts' colour and
```
vigilance, murals and the crews that scrub them, paint in the air, cover, marks) and one SESSION per player
(logic.session: her paint, colour, money, crew, vehicles, heat and record, missions, activities, chronicle).
It owns no entity and reads no device. Each tick the host (logic.driver, or a test) hands it one frame per
player; it returns one view per player and emits every moment on its hub. The same code runs one player or
several: heat, saves and progress are each player's own; walls are everyone's.
local Game = require("metropolisGame.logic.game")
local game = Game.new({
city = city, -- interfaces: city (districtAt, walls, place, roadGraph ...)
query = physicsQuery, -- interfaces: physics (raycast, overlap) for paint in the air
hasLine = function(observer, suspect) return true end, -- line of sight for observers
light = nil, -- function(x, z) -> 0..1; default follows the game clock
clock = nil, -- interfaces: clock, when it offers `shared` and `anchor` (several players: the
-- game clock then follows the synced anchor instead of ticking)
seed = 20261122,
})
local session = game:session("p1") -- makes it on first use (a new game for that player)
local views = game:frame(dt, { p1 = {
actor = "actor:p1", -- the id her body has in physics hits (so solvent finds her)
pose = { x, y, z, fx, fz, speed, vx, vz, onGround },
roadClass = "street", -- the class of road she is on (nil off the road)
hidden = false, concealment = {}, jacket = "ochre", stand = 0, mounted = false,
aim = { origin = { x, y, z }, dir = { x, y, z }, site = "old_quay:piece:1", u, v, distance, target = id },
input = { paint, fire, sign, breakHeld, skip },
observers = { [id] = { kind, x, y, z, fx, fz, relay, atRelay, knows, active } },
van = { x, z }, -- where her van stands (for the bill), or nil
route = function(unit, x, z) ... end, -- the host's router for response units (optional)
facts = {}, audience = nil,
} })
views.p1 -- everything her HUD and map draw: data and ids, no text
game:view("p1") -- the same again
game.hub -- every event of every session (e.player says whose) and the world's
game:save() -> { v, world = {...}, players = { [id] = {...} } } game:load(data) -> ok, why
game:saveWorld() game:savePlayer(id) -- the two halves on their own (logic.save writes them)
World parts, all public: clock, districts (districtState), sites, places, murals, gunplay, party, graph.
World hub events: "hour", "dayPassed", "colour", "threshold", "vigilance", "districtPainted", the murals'
("scrubComing" ...), the gunplay's ("shotsFired", "paintedOut", "washed" ...), "relayJammed" { id }, "lensOut" { id }.
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# save
The save: versioned, migratable, split into what the WORLD holds and what each
```
PLAYER holds, and the stores they are kept in.
The world (clock, districts, murals, marks, persistent cover) is one save everybody shares; each player has a
save of her own (money, paint, crew, vehicles, record, missions, activities, chronicle, settings). Both are
plain trees assembled from each system's own serialise(), written leaf by leaf so that a wall signed during a
chase does not rewrite everything, and read back as one tree.
local Save = require("metropolisGame.logic.save")
Save.VERSION -- 2
local data = Save.pack(world, players) -- { v, world = {...}, players = { [id] = {...} } } (what game:save returns)
Save.check(data) -> ok, why -- shape and version (a save newer than the game is refused)
Save.migrate(data) -> data -- older versions forward: v1 (the single-player prototype) -> v2
Save.MIGRATIONS -- { [fromVersion] = function(data) -> data } applied in order
local store = Save.store(accessor, "pm/world") -- accessor: { get(path, default), set(path, value), getTree(prefix) }
store:write(tree) -- every top-level part under "<root>/<part>"; parts named in
-- Save.LEAVES are written one leaf per key ("murals/canvases/<site>")
store:writePart("districts", tree.districts) store:writeLeaf("murals", "canvases", siteId, text)
store:read() -> tree | nil -- nil when there is none
Save.engineStores(playerId?) -> { world = store, player = store } -- on the engine's runtime_data
A player's tree and the world's tree each carry their own `v`, so one can be migrated without the other.
What v1 held that cannot come forward is dropped and listed in the migrated tree's `dropped` (old-city site
ids, splat positions and stashes: the city they were in is gone).
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# talk
What a contact says when she talks to one: which written lines, in which order,
```
and what she can answer. The words are in the catalog `pm_story` (`talk.<contact>.<line>`); this module is the
rule that picks them, so the host's dialogue system only plays a script.
local Talk = require("metropolisGame.content.talk")
Talk.LINES -- every line a contact has written: the five trust bands' greetings,
-- "work", "no_work", "good_job", "bad_job", "idle_a".."idle_c"
Talk.key("odile", "warm") -- "pm_story.talk.odile.warm"
local script = Talk.conversation("odile", {
band = "warm", -- logic.crew's band of her trust
offers = { { kind = "mission", id = "proper_piece", titleKey = "pm_story.missions.proper_piece.title" } },
last = "good" | "bad" | nil, -- how the last job she gave went, said once
turn = 3, -- how many times they have talked (rotates the idle lines)
})
-- { speaker = "odile", lines = { key, ... } (said in order),
-- options = { { id = "mission:proper_piece", labelKey }, ..., { id = "leave", labelKey } } }
-- the host reports a pick with driver:choose(playerId, option.id)
The rule: the verdict on the last job comes first; then the greeting of the trust band; a contact who is wary
(trust below nothing) says only that and offers nothing; with work she says her "work" line and each job is an
option; without, "no_work" and one of her three idle lines in turn.
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# contacts
The people Wren works with and the one she works against: where each is
```
found, how far each trusts her at the start, and what their trust opens.
local Contacts = require("metropolisGame.content.contacts")
Contacts.list Contacts.byId("pim") Contacts.services -- [serviceId] = what a system does with it
Entry fields (text in catalog `pm_story`: `people.<id>.name`, `.role`, `.about`; their lines under `lines.<id>.*`):
id, role who, and what they are to her ("craft", "wheels", "heights", "files", ...)
district, place where they are found (a place id of content.places)
known = true met before the game starts
trust trust at the start (-100..100)
services = { { id, at } } what they do for her, and the trust it takes (logic.crew)
Services (read by the system in brackets):
stencils cuts stencils at the studio [session]
cheap_paint tins at a discount at any shop [scoring]
garage_key the Ironside yard takes the van for repairs and a respray [fleet]
driver a driver who brings the van to a corner she names [driver]
fence takes borrowed vehicles for sous [fleet]
routes rooftop routes shown on the map [map]
cradle window-cleaner cradles left unlocked [missions]
beats Wardens' beats and shifts shown on the map [map, roster]
files leverage on named Wardens (blackmail) [roster]
lookout posts herself at a corner and whistles when a Warden nears [session]
decoy a false report that pulls a district's patrols away, once a day [response]
doctor restores colour at once, for sous [session]
safe_door a back door in her district that hides Wren during a search [session]
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# districts
The thirteen districts of Verrane as game boards: who watches, who polices,
```
what the roads allow, what the walls are, and the one rule that makes each a different problem.
Geography (where each district is, its street grain, its landmarks) belongs to the city template
(`s3/design/verrane_geography.md`, the cityGen plan); the ids here are the ids the city must report from
`city.districtAt`. Everything below is rules, read by the systems named in brackets. Text for a district is in
the catalog `pm_world`: `districts.<id>.name`, `.rule` (one line), `.line` (a voice), `.card.<part>` for each
part named in `card` (the district rule card).
local Districts = require("metropolisGame.content.districts")
Districts.list Districts.byId("old_quay") Districts.order Districts.thresholds Districts.colourTarget
Entry fields:
id, contact the district's id and the contact who works it
act the story act it opens in (1..3)
risk multiplies renown earned here [scoring]
police = { faction, foot, cars, beat } who patrols at heat 0: faction "wardens" | "security"; counts; beat =
"wander" | "clockwork" | "watchman" | "posts" | "none" [response, host]
citizens = { informer, sympathiser } shares of passers-by who report / who cheer at colour 0 [districtState]
turn = { at, informer } at this colour the informer share has fallen to this (linear from 0)
crowd = { day, night } 0..1 how full the streets are (cover and witnesses both) [host population]
eyes = { camera, curtain, doorman, lamp } fixed observers per 100 m of street front [host population]
witness = { day, night } the observer kind a reporting passer-by is, by time of day [session]
cars = { [roadClass] = m/s } Warden car speeds here by class of road (others: the kit's) [response]
noCars = { [roadClass] = true } classes no car fits here (the crew dismounts) [response]
sites = { tag, piece, wall } mural sites to deal (logic.sites)
rules = { ... } flags a system reads (each is explained on the district's card):
renownAudience cheering sympathisers raise renown here [scoring]
reportsFade = { share } that share of night reports is forgotten before it lands [session]
beat = { period, gap } clockwork beats: seconds a round, seconds between passes [host]
curtainsSleep = { from, to } window observers only watch outside these hours [host]
freight = { every, lasts } a train passes: full concealment behind it while it does [host]
paintTolerated = factor painting here is this much quieter to observers [session]
checkpointAt = level from this heat level the ways out are checked [response]
noWitnesses nobody lives here: only patrols see [host population]
detainOnly its police detain and call; they cannot arrest [content.pursuit]
impound / scrubDepot / hall / colourworks the place of that name stands here [missions, activities]
tramPass = colour the colour at which the district's tram pass is given [districtState]
shop = { discount } paint is cheaper here by this share [scoring]
card = { "eyes", "roads", ... } the parts of its rule card, in order (catalog keys)
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# missions
The eighteen story missions, as data the mission runner runs.
```
A mission is a list of steps. A step has a goal (a condition), may have a fail condition and a time limit, may
be a checkpoint (where a retry returns to), may be a DECISION (`choose`) and may exist only on the branch one
option opened (`when = { chose = "x" }`). One step carries the twist: a condition that, the first time it holds,
fires the mission's "twist" moment. `bonus` objectives pay extra. `rewards` are paid on completion,
`rewardsBy[choice]` on top for each choice made. Every word is in the catalog `pm_story`:
`missions.<id>.title`, `.giver_line`, `.brief`, `.twist`, `.done`, `.failed`, `.steps.s<n>`, `.options.<choice>`.
Conditions (logic.missionRunner):
{ fact = "near:studio" } { fact = "level", atLeast = 3 } { fact = "tins", atMost = 0 } { fact = "state", is = "clear" }
{ event = "signed", match = { site = "fishmarket" }, min = { rank = 2 }, count = 1 }
{ after = 30 } { all = { ... } } { any = { ... } } { never = cond }
Facts (logic.session supplies them every tick; the host adds its own through the frame's `facts`):
near:<place or named site> in:<district> colour:<district> trust:<contact> flag:<name> has:<upgrade>
driving:<vehicle type> state level heat hour night weekday day in_vehicle hot speed
tins van_tins painting firing colour (0..1, Wren's own) washed_out strikes rank sous blocks
hidden on_ground painted:<site> (0..1) tier:<site> (0 none, 1 rough, 2 clean, 3 masterwork)
host: load (0..1 of a carried load left) aboard:<tram | ferry | cradle> on_roof height (m above the street)
Events (the game reports the first group; the host reports the second with session:event):
signed { site, tier, rank, district, size } bought { tins, pigment } upgraded { id } escaped { level }
arrested ejected reported noticed scrubbed { site } scrub_stopped { site, how } jammed { id }
blinded { id } fouled { id } painted_out { kind } washed_out fired { arm } boarded { type, owned }
alighted stored retrieved fenced shed { what }
talked { who } delivered { to } arrived { at } patrol_passed { at } freight_gone inspector_returned
panels_filled picked_up { what } float_painted convoy_stalled convoy_passed cut_loose file_burnt map_copied
`stage` directions (a list on a step or a twist). GAME verbs are applied by logic.session; HOST verbs by the
driver's stage director through actors, vehicles, camera and audio (Missions.VERBS lists both):
game: { give = "tins", pigment, n } { set_hour = h } { scrub = site, in_seconds, unstoppable } { heat = level }
{ van_tins = n, pigment } { flag = name } { grant = upgrade } { scrub_call = district, in_seconds, crew }
host: { spawn = kind, at = place, id, count, walks_to, leaves, stays, returns_in } { despawn = id }
{ crowd = name, at } { patrol = "reverse" | "double", at } { shut = "bridges" | "roads", district }
{ vehicle = type, at, id, state } { convoy = name, from, to } { load = name } { trail = true }
{ show = name, district } { say = line, who } { shot = name } { freight = "pass" }
{ searchlights = pattern } { winch = true } { doors = "open", held_by } { marker = place }
{ item = what, at = place } something to pick up there (reports picked_up { what })
{ handover = to, at = place } someone to hand a thing to there (reports delivered { to })
{ sketch = place } a place to draw from (reports sketched { at })
local Missions = require("metropolisGame.content.missions")
Missions.list Missions.byId("first_coat") Missions.order Missions.sites Missions.VERBS
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# activities
The replayable work of the city: thirteen activity TYPES, each a small
```
authored job shape with a real decision in it and a consequence that lasts, and the written VARIANTS of each
(content.activityRows: one row per variant, where it is, for whom, with what numbers).
A type is a template: given a variant's row it builds a job in the mission runner's shape (steps, a `choose`
step, bonus objectives, rewards by choice, fail rewards). The board (logic.board) deals a district's variants
by the day. Text is in the catalog `pm_work`: per type `types.<type>.name`, `.pitch`, `.steps.s<n>`,
`.options.<choice>`, `.done`, `.failed`; per variant `<type>.<district>.<key>.title` and `.brief`.
local Activities = require("metropolisGame.content.activities")
Activities.types -- { { id, unlock, perDay, rest, once? } } in board order
Activities.variants -- { variant } built from the rows; each is a job for logic.missionRunner
Activities.byId(id) -- a variant by id ("<type>_<district>_<key>")
Activities.sites -- named mural sites the variants need ({ [name] = { district, size, design, near, permit, carrier } })
Activities.ofType("getaway") Activities.count() -- { [type] = { [district] = n } }
Type fields: unlock (Runner.meets requirements), perDay (variants a district shows a day), rest (days a variant
rests after it is done or failed), once (a collectible: never again once done).
Row fields (content.activityRows): { type, district, key, ...numbers and places the type's template reads }.
Every type's template is documented where it is defined below: what the row may carry, the decision, and what
each outcome changes for good.
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# crew
The people Wren knows: how far each trusts her, and what that trust opens.
```
A contact (content.contacts) has a trust from -100 (they cross the street) to 100. Trust moves when jobs go
well or badly and when choices favour or betray them; every change carries a reason the UI can show. At
thresholds a contact offers SERVICES (a lookout at a corner, a driver, a decoy, a doctor who restores colour,
a fence who takes borrowed cars, cheaper paint): `crew:has("lookout")` is what the rest of the game asks.
Below zero a contact gives no work and no service until trust is rebuilt.
local Crew = require("metropolisGame.logic.crew")
local crew = Crew.new(Contacts, hub?) -- Contacts: content.contacts
crew:meet("pim") -- first met (appears in the list); returns false if known
crew:trust("pim") -- number (the contact's start value before any change)
crew:change("pim", 10, "job_clean") -- returns the new trust; emits "trust", and "service" for
-- each service the change opened or closed
crew:has("lookout") crew:provider("lookout") -- is the service open, and who gives it
crew:gives("pim") -- false while trust is below zero
crew:view() -- { { id, met, trust, band = "wary" | "cool" | "warm" | "close" | "sworn", services = { { id, at, open } } } }
crew:serialise() crew:restore(data)
Hub events: "trust" { contact, value, delta, why }, "service" { contact, service, open }, "met" { contact }.
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# voices
What people say in the street and what the Wardens' radio says: which
```
situations have lines, and how many written variants each has. The words are in the catalog `pm_street`
(`barks.<speaker>.<situation>.<a|b|c|d>`, `radio.<event>.<a|b>`); this module is the index the driver picks
from (never the same variant twice running) and the content cases check against the catalog.
local Voices = require("metropolisGame.content.voices")
Voices.barks.warden.suspicious -- 4 (variants a..d)
Voices.radio.level_hunted -- 2
Voices.key("barks", "warden", "alert", 2) -- "pm_street.barks.warden.alert.b"
Voices.radioKey("roadblock_ordered", 1) -- "pm_street.radio.roadblock_ordered.a"
Voices.speakerOf(actorKind) -- the bark set an actor kind speaks with ("warden", "security", ...)
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# pursuitKit
Being noticed, being hunted, getting away, getting caught: as data-configured, engine-free logic any game can
drive. Nothing in it names a game, a city, a guard or a crime. The host says where observers and the suspect are
and whether the line between them is clear; the kit answers with states, timers and events, and with intents for
pursuers on foot and in vehicles.
**Status:** every module's logic is covered by case modules that run in the engine's Luau VM in edit mode
(`tests/cases/{core,response,standing}`, 92 cases; see "Tests"). The kit has NOT been run against a scene: the
raycast adapter and everything a host stages (animation, vehicles, sound) are untested here.
## What is in it
| Module (`require("pursuitKit.modules.<name>")`) | What it does |
|-|-|
| `config` | `DEFAULTS`, `merge(base, over)` (`Config.NONE` drops a default), `validate(cfg)`: the whole kit's behaviour as one table |
| `hub` | named events: `on`, `onAny`, `emit` |
| `perception` | view cone in 2D or 3D (`inView3`, `vertical`), range by light, fill rate, panning (`sweep`) |
| `awareness` | one 0..1 meter per observer with suspicious/alert thresholds and events |
| `reports` | pending reports with delays, holds, relays that can be jammed |
| `heat` | offences → points → named levels; pursuit tick; decay after a grace; escape factor |
| `incident` | the state machine: clear, noticed, reported, pursuit, search, escaped, arrest, released; last known position; search area |
| `grab` | the telegraphed reach on foot (`reach`) and the vehicle box-in (`box`) |
| `arrest` | the staged arrest with hooks, break-free and skip; several `sequences` (arrest, detain-and-eject, hand-over); `Arrest.bill(rules, facts)` |
| `dispatch` | who is sent where for a heat level: `plan`, `sweepPoints`, `cordon`, `entry` |
| `pursuer` | one pursuer's intent by profile (`cfg.pursuer[name]`: speeds, leash, home, look-round on arrival); writers for the character bus and the vehicle bus |
| `description` | what the pursuers know the suspect looks like (`strength` 0..1), shedding it |
| `firefight` | pursuers who shoot back: who is armed at a level, the aim telegraph, bursts, led and spread shots. Holds no projectile |
| `roadblocks` | blocks and bridge checkpoints on a road GRAPH the host supplies: ordered, standing, lifted; `plan` forecasts |
| `vehiclePursuit` | pursuit cars that work together: shadow, chase, box, ram, block, dismount where a car cannot go |
| `theft` | taking a vehicle: the offence by its state, the owner's delayed report, the hot list, lawful kinds |
| `roster` | pursuers as named people: beats, shifts, bribes and leverage, arrangements found out, faces remembered |
| `record` | strikes that fade; confiscated things in an impound with a growing fee and a sale date |
| `party` | several suspects in one world: heat is each one's own, shared with accomplices standing close |
| `director` | perception, awareness, reports, heat, incident, grab, arrest and description assembled behind `setObserver` / `setSuspect` / `tick` |
| `engineAdapters` | `lineOfSight` on `Physics.raycast`; `lightAt` / `lightByHour` (the only module that calls the engine) |
Every module's header comment is its reference: the calls, the shapes they return, and its section of the config.
## Using it
```lua
local Config = require("pursuitKit.modules.config")
local Director = require("pursuitKit.modules.director")
local Adapters = require("pursuitKit.modules.engineAdapters")
local Arrest = require("pursuitKit.modules.arrest")
local cfg = Config.merge(Config.DEFAULTS, myGameConfig) -- see the schema in modules/config
assert(Config.validate(cfg))
local dir = Director.new(cfg, {
hasLine = Adapters.lineOfSight({ pass = isGlassOrCrowd }),
light = Adapters.lightByHour(function() return clock.hour end),
bill = function(level, ctx) return Arrest.bill(myBillRules, factsFor(level)) end,
})
dir.hub:on("state", function(e) hud.setPursuit(e.to) end)
dir.hub:on("arrestStage", function(e) cast.play(e.stage); camera.cut(e.stage); hud.arrest(e) end)
-- every frame
dir:setObserver(id, { kind = "guard", x = x, y = y, z = z, fx = fx, fz = fz })
dir:setSuspect({ x = px, y = py, z = pz, act = currentAct, concealment = tags, hidden = inHide,
appearance = { jacket = jacket }, inVehicle = driving, speed = speed, charges = slips })
dir:input({ breakHeld = interactHeld, skip = confirmPressed })
local view = dir:tick(dt) -- everything a HUD draws
dir:offence("fired_arm") -- something the game saw her do
dir:report({ offence = "stolen_vehicle", x = x, z = z, delay = 8, appearance = tags }) -- a report from outside
dir:noise({ x = x, z = z, radius = 30 }) -- observers in earshot grow suspicious
```
Pursuers (the host owns their entities):
```lua
local Dispatch = require("pursuitKit.modules.dispatch")
local Pursuer = require("pursuitKit.modules.pursuer")
local orders = Dispatch.plan(cfg, view.level, view, units) -- units: { { id, kind, x, z, available } }
for _, u in units do
local senses = dir:senses(u.id) -- sees, sx, sz, stunned, grabbing
senses.x, senses.z, senses.order, senses.path = u.x, u.z, orders[u.id], route(u, orders[u.id])
local intent = u.brain:decide(dt, senses) -- u.brain = Pursuer.new(cfg, "foot")
if u.kind == "foot" then
u.controller.inputX, u.controller.inputZ = Pursuer.characterBus(intent, u.x, u.z)
else
u.vehicle.inputThrottle, u.vehicle.inputSteer, u.vehicle.inputBrake, u.vehicle.inputHandbrake =
Pursuer.vehicleBus(intent, u.x, u.z, u.fx, u.fz, u.forwardSpeed, cfg.frame.right)
end
end
```
The response beyond the chase (each is independent; use what the game needs):
```lua
local ff = Firefight.new(cfg.firefight, rng) -- rng() -> [0, 1): the kit ships no generator
for _, e in ff:tick(dt, { level = view.level, suspect = s, shooters = shooters }) do
-- "aim" (stage the telegraph), "shot" { from, at, wash, speed, gravity, ... } (fly it), "lower"
end
local rb = Roadblocks.new(cfg.roadblocks, graph) -- graph = { nodes = { [id] = { x, z } }, edges = { { id, a, b, class, bridge } } }
for _, e in rb:update(dt, { level = view.level, state = view.state, x = lkp.x, z = lkp.z, radius = r }) do end
Roadblocks.plan(cfg.roadblocks, graph, { level = view.level + 1, x = x, z = z, radius = r }) -- forecast for a map
local vp = VehiclePursuit.new(cfg.vehiclePursuit, cfg.frame.right)
local intents = vp:tick(dt, { level = view.level, target = car, units = cars }) -- shadow | chase | box | ram | block | dismount
local theft = Theft.new(cfg.theft)
local r = theft:take(vehicle, { witnessed = seen, x = x, z = z }) -- the offence now, the owner's report later
for _, landed in theft:tick(dt) do dir:report(landed) end
local roster = Roster.new(cfg.roster, people, rng) -- named pursuers: onDuty, cover, arrange, use, sawFace
local record = Record.new(cfg.record) -- strike, confiscate, impounded, fee, release, dayPassed
local party = Party.new(cfg.party) -- join, place, together, charge, reported
```
## Interfaces the host provides
- **Line of sight** `hasLine(observer, suspect) -> boolean`. `engineAdapters.lineOfSight` is one implementation.
- **Light** `light(x, z) -> 0..1` (optional).
- **The bill** `bill(level, ctx) -> table` (optional; `Arrest.bill` builds one from rules).
- **A generator** `rng() -> [0, 1)` for firefight spread and roster rolls. Seed it: the kit is deterministic for a
given sequence of inputs and rolls.
- **A road graph** for road blocks, and a `path = { { x, z }, ... }` per pursuer per order (roads for cars, a nav
path on foot). The kit does not pathfind.
- **Movers**: a character with `inputX`, `inputZ`, `inputJump` and a vehicle with `inputThrottle`, `inputSteer`,
`inputBrake`, `inputHandbrake`, or any AI driver that accepts the intent (`mode`, a point, a speed).
- **Projectiles**: whatever flies a `shot` event from `from` towards `at` and reports what it hit.
- **Staging**: animation, camera and UI for `grabWindup`, `grabMissed`, firefight `aim`, and each `arrestStage`;
the kit gives the moments and durations and waits for nobody.
## Frame
Positions are `(x, y, z)` with y up; where only the ground matters `(x, z)`. `cfg.frame.right` is the sign of x
on the right of someone facing +z: `-1` in the Zero engine's frame (+x east, +z south), `1` in a z-north frame.
It decides flank sides and steering.
## Events (on `dir.hub`)
| Event | Payload | When |
|-|-|-|
| `state` | `from, to, level` | the incident changes state |
| `heat` / `heatLevel` | `value, level, name, delta, offence` / `from, to, name` | heat changes / crosses a level |
| `observer` | `type = suspicious, alert or calm; id; kind` | an observer crosses a threshold |
| `cheer` | `id` | an observer whose kind answers alert with "cheer" becomes certain |
| `reportOpened` / `reportLanded` | `id, delay, via, relay` / `id, offence, x, z` | a report starts its delay / arrives |
| `lkp` | `x, z` | the last known position moves by more than a metre outside a pursuit |
| `searchStarted` | `x, z, radius, duration` | a search begins |
| `escaped` | `level, name, heatBefore` | a search ran out |
| `grabWindup` / `grabMissed` | `by` | a pursuer starts / fails a reach |
| `arrested` | `level` | a grab landed |
| `arrestStage` | `stage, control, duration, ctx` | each stage of the sequence begins |
| `arrestBroke` / `arrestDone` | `{}` / `bill, level, sequence, outcome` | the suspect broke free / the sequence ended |
| `released` | `{}` | the incident is over after an arrest |
`firefight`, `roadblocks`, `vehiclePursuit`, `theft` and `record` return their events from `tick` / `update` /
`dayPassed` instead of emitting: the host decides which hub they go on.
## Rules the config must keep
`acts.wanted` (what a certain observer takes the suspect to be doing), `heat.offences.seen`, the offence named by
`arrest.breakOffence`, one `response` entry per heat level, `heat.levels[1].at == 0`, a `firefight.levels`,
`roadblocks.levels` and `vehiclePursuit.levels` entry per heat level when those sections are used.
`Config.validate` checks the structural ones and names what is wrong.
## Tests
The cases are modules (`tests/cases/*.module`, each returns `function(Test)`), registered by
`tests/pursuitKit.testSuite` for the engine's runner. The engine's runner closes and reloads the open scene, so
while a scene is being worked on run them in-process instead with `caseBench` (see its README): same cases, no
scene touched.