# engineAdapters
The director's adapters written against the Zero engine.
```
The rest of pursuitKit is engine-free and is what the test suite covers. This module is the only place that
calls the engine, and it is small on purpose. NOT YET RUN IN THE ENGINE (2026-11-19): the calls are the ones
documented in the physics guide (`Physics.raycast(origin, direction, maxDistance)` returning
`{ entityId, distance }` or nil, answering from colliders only).
local Adapters = require("~.modules.engineAdapters")
local hasLine = Adapters.lineOfSight({ eye = 1.6, chest = 1.1, pass = function(entityId) return false end })
-- hasLine(observer, suspect): observer and suspect are the tables given to director:setObserver / setSuspect,
-- with optional `y` (ground height, default 0) and `entityId` (their own collider, never counted as a wall).
-- `pass(entityId)` lets the host name colliders a line may cross (glass, a crowd, the suspect's own vehicle).
local light = Adapters.lightByHour(function() return hour end, { dawn = 6, dusk = 20, blend = 1 }, lamps?)
-- light(x, z): 1 by day, 0 at night, blended over `blend` hours; `lamps(x, z)` may return a 0..1 floor
-- (a street lamp's pool) so lit pavements stay visible at night.
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# 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.
# hub
A small event hub: named events, plain payload tables, no engine.
```
Every pursuitKit system reports what happened through a hub the host passes in, so animation, camera, sound and
UI subscribe to moments instead of polling state.
local Hub = require("~.modules.hub")
local hub = Hub.new()
local off = hub:on("state", function(e) print(e.from, e.to) end)
hub:emit("state", { from = "clear", to = "noticed" })
off() -- disconnect
hub:onAny(function(name, e) ... end) -- every event (a log, a recorder, a test)
A handler that errors does not stop the others; its message is kept in hub.lastError.
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# murals
The city's murals: one canvas per site, who painted it, how good it is, and the
```
scrub crews that come for them. This is WORLD state: every player sees and paints the same walls.
local Murals = require("metropolisGame.logic.murals")
local murals = Murals.new({ paintCfg, sites, sizes = PaintContent.sizes, designs = PaintContent,
economy = Economy, hub })
murals:canvas(siteId) -- the site's canvas (made on first use), or nil for an unknown site
local r = murals:paint(painter, siteId, dt, { u, v, distance, stand, stencil }) -- paintKit painter.paint's result
local s = murals:sign(siteId, author) -- { tier, rank, site } or nil when it is below the lowest tier / signed
murals:quality(siteId) -- the canvas's quality (coverage, accuracy, overspray, tier ...) or nil
murals:author(siteId) -- the player id that signed it
murals:signedCount(author?) -- signed walls (of one author)
murals:queueScrub(siteId, seconds, { unstoppable = false, crew = "crew1" })
murals:stopScrub(siteId, "block" | "windscreen" | "foul") -- true if a crew was stopped or delayed
murals:tick(dt) -- crews arrive and work; emits what happens
murals:scrubs() -- { { site, state = "coming" | "working", startsIn, left } }
murals:serialise() murals:restore(data) -- canvases (text per site), authors, the crews' queue
Hub events: "scrubComing" { site, seconds }, "scrubStarted" { site }, "scrubbed" { site, district, author },
"scrubStopped" { site, how }, "scrubDelayed" { site, seconds }.
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# session
One player: everything that is hers alone. Her paint and tools and arms, her
```
colour, her money and renown, her crew's trust, her vehicles, her heat and record with the Wardens, her
missions and activities, what the city remembers of her. The world she paints in (murals, district colour,
the clock, paint in the air) belongs to logic.game and is shared by every session.
local session = game:session("p1") -- made by the game (Session.new(game, id))
session:frame(dt, pf) -> view -- once a tick; `pf` is this player's frame (see logic.game)
session.hub -- her own hub: pursuitKit's events and this module's; the game
-- forwards every event to game.hub with e.player = id
Parts, all public: satchel, vanStock, painter, arms, colour, progression, crew, fleet, response (director,
theft, roster, record, roadblocks ...), runner (missions), board (activities), chronicle.
What the player does (the host calls these when the matching control is used; each returns ok, why):
session:buyTins(pigment, n) session:buyUpgrade(id) session:buyService("doctor" | "respray" | "plates" | "wash_down", arg)
session:cycleTool(step) session:cycleArm(step) session:selectArm(id) session:cyclePigment(step)
session:loadFromVan(pigment, n) session:placeStash(x, z, pigment, n) session:takeStash(index)
session:shed("jacket" | "plates", newValue) -- out of sight; needs the upgrade; once an incident
session:takeVehicle({ id, type, colour, plate, state }, witnessed) session:leaveVehicle()
session:storeVehicle(district) session:retrieveVehicle(district) session:fenceVehicle()
session:arrange(wardenId, { how, weekday }) -- bribe or lean on a named Warden
session:startMission(id) session:retryMission() session:startActivity(id) session:choose(option)
session:event(name, payload) -- something the host saw happen (talked, delivered ...)
session:rest(hour) -- pass time at a safehouse
session:serialise() session:restore(data)
Hub events added here (all carry what the UI needs to say it): "signed", "paintRefused", "fireRefused",
"billApplied", "seized", "escapeAward", "shop", "shedDone", "teach" (first time only), "districtEntered",
"vehicleTaken", "vehicleLeft", "washedOut", "revived", "reward", "stipend", "arranged", "arrangementUsed",
"ejected", plus those of progression, crew, fleet, the runner ("mission...") and the board ("activity...").
```
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.
# party
Several suspects in one world: heat stays each one's own, shared when they act together.
```
Every suspect has a director of its own (its own awareness, heat, incident, arrest). The party joins them with
one rule: suspects standing within cfg.party.radius of each other are ACTING TOGETHER, so an offence one of
them is charged with also charges the others a share of its points, and a report that lands on one opens the
others' eyes to where it happened. Apart, nothing one does touches another.
local Party = require("~.modules.party")
local party = Party.new(cfg.party)
party:join("p1", director1) party:join("p2", director2) party:leave("p2")
party:place("p1", x, z) -- where each suspect is (every tick)
party:together("p1") -- ids acting with p1 now, sorted (p1 itself excluded)
local shared = party:charge("p1", "paintGuard", 15)
-- p1 was charged 15 points for an offence: accomplices get cfg.share of them; returns { [id] = points }
party:reported("p1", x, z) -- a report on p1 landed there: accomplices' pursuers are told
-- the place too (their incidents get the report without heat)
party:members() -- ids, sorted
Config (cfg.party): radius (metres), share (0..1 of an accomplice's offence points).
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# districtState
What the city remembers: each district's colour and vigilance, the
```
signed walls in it, how its people feel, and which walls the scrub crews come for.
local DistrictState = require("metropolisGame.logic.districtState")
local ds = DistrictState.new(Districts, PaintContent.sizes, Economy, hub?)
ds:signed("oldquay", "fishmarket", "piece", "clean", day) -- a wall was signed (or re-signed better)
ds:lost("oldquay", "fishmarket") -- scrubbed away
ds:colour("oldquay") -> 0..100 ds:vigilance("oldquay") -> 0..3 ds:isPainted("oldquay")
ds:incident("oldquay", peakLevel) -- an incident ended there; Wanted or worse raises vigilance
ds:paint("oldquay") -- its landmark was signed: the district is painted
ds:dayPassed(day) -> { { district, vigilance } } quiet districts cool; returns the ones that changed
ds:citizens("oldquay") -> { informer, sympathiser } shares of passers-by, turned by colour
ds:decayFactor("oldquay") -> number -- how fast heat cools there (1.5 at colour 50 and over)
ds:scrubTargets("oldquay") -> { site, ... } the walls tomorrow's crews will come for, in order
ds:paintedCount() -> number ds:walls("oldquay") -> { [site] = { size, tier, day } }
ds:view("oldquay") -> { id, colour, vigilance, painted, signed, thresholds = { tags, door, landmark } }
ds:quiet(days) -- no scrub crews anywhere for that many days (Dry Tank)
ds:serialise() ds:restore(data)
Hub events: "colour" { district, value, delta }, "threshold" { district, name }, "vigilance" { district, value,
delta }, "districtPainted" { district }.
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# economy
Prices, payouts, ranks, and everything that can be bought: tools, paint arms,
```
what the van carries, what the crew does for trust rather than sous.
local Economy = require("metropolisGame.content.economy")
Economy.paint -- { tin, nightTin, shopOpens, shopShuts, stencil }
Economy.carry -- { satchel, slots, van, stash = { max, tins }, slips, stencils } what a new player has
Economy.tiers -- [tier] = { renown, colour, sous } multipliers on a size's base awards
Economy.audience -- { each, max } renown share per friend watching, and its cap
Economy.underNoses -- { level, factor } signing while this hunted multiplies renown
Economy.ranks -- renown thresholds; rank r (0-based) is reached at ranks[r + 1]
Economy.upgrades -- { { id, track, sous, rank, needs?, grants = { ... } } } in shop order
Economy.upgrade(id)
Economy.commission -- sous for legal work by size, before the tier multiplier
Economy.stipend -- { sous, everyDays } what a painted district sends
Economy.garages -- { opensAt, districts } colour at which a district's garage opens; which have one
Economy.safehouse -- { locker } tins a safehouse locker holds
Economy.services -- prices of things done for sous: { respray, plates, doctor, fence = { share }, bribeTip }
Economy.clock -- { dayMinutes, start, dawn, dusk, blend }
Economy.scrub -- how the scrub crews work
Economy.signHold -- seconds the sign control is held to sign a wall
Economy.near -- metres within which a named place or site counts as "here"
`track` is the progression track an upgrade belongs to, for the shop's tabs: "tools" (what paints walls),
"arms" (what fires paint), "carry" (satchel, slots, slips), "van" (the only vehicle that keeps upgrades),
"craft" (things that change how a job is done).
`grants` is read by logic.progression: satchel (capacity), slots (pigments loaded), slips (grabs broken per
incident), tool (a paintKit tool name), arm (a paintKit arm name), van (tins the van carries), flags (named
abilities a system checks: "jacket", "ladder", "roof_rack", "compartment", "plates", "stencils", "scope").
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# clock
The city's day: hours that pass, and the moments other systems wait for.
```
local Clock = require("metropolisGame.logic.clock")
local clock = Clock.new({ dayMinutes = 36, start = 5.5, dawn = 6, dusk = 20, blend = 1 }, hub?)
clock:tick(dt) -- real seconds; returns the hours crossed this tick, e.g. { 6 } (empty most ticks)
clock.hour clock.day -- 0..24 and days since the start (0-based)
clock:weekday() -- 1..7 (day 0 is weekday 1)
clock:phase() -- "dawn" | "day" | "dusk" | "night"
clock:isNight() clock:text() -> "06:15"
clock:skipTo(22) -- rest until an hour (crosses the hours between; returns them)
clock:set(hour) -- a mission sets the scene (no hours are "crossed")
clock:secondsUntil(6) -- real seconds until an hour next comes round
clock:serialise() clock:restore(data)
Several players, one clock (the shared-anchor model): nobody ticks. The clock's owner publishes an ANCHOR record
and every peer computes the hour from it and a timeline they all agree on, so nothing drifts:
local record = clock:anchor(sharedNow) -- { t0, total0, dayMinutes } for the host to sync (owner only)
clock:follow(record, sharedNow) -- every peer, every tick: advances to where the record says (hours
-- crossed fire as usual); returns the hours crossed
clock.moved -- true after skipTo / set / restore: the owner publishes a new anchor
Hub events: "hour" { hour, day }, "dayPassed" { day } (at midnight).
```
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.
# places
The named places the game needs the city to have: where the story happens,
```
where contacts are found, the beats Wardens walk, the doors that open as a district is painted.
This is a REQUIREMENT LIST for the city, not a map. The game refers to a place by id; the host's city adapter
answers `city.place(id)` with where it really is (interfaces: city). `at` is a hint in world metres from the
geography brief (`s3/design/verrane_geography.md`: +x east, +z south), for whoever seats the place in the
template; the game never reads it except through `Places.hint`, which the headless fake city uses.
local Places = require("metropolisGame.content.places")
Places.list Places.byId("studio") Places.ofKind("post") Places.inDistrict("old_quay") Places.hint("studio")
Entry: { id, district, kind, at = { x, z } }. Text in catalog `pm_world`: `places.<id>`.
Kinds: studio, safehouse, shop, cafe, post (a Wardens' post: where the released stand), hall, depot, yard,
garage, fort, clinic, school, market, station, pier, bridgehead, viewpoint, tram_stop, beat (a street a named
Warden walks), home, tower, gate, stage, works, square, lift, wall (a landmark surface).
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# sites
Where the murals go: mural sites dealt onto the walls the city offers.
```
The city (interfaces: city.walls) lists paintable walls: where each is, which way it faces, how wide and high,
which district it stands in. This module deals the game's sites onto them: per district the numbers of tags,
pieces and walls its rule asks for (content.districts[..].sites), spread evenly through the district's walls,
biggest first so the rare big walls are not spent on tags. A site named by a mission or an activity is seated
on the fitting free wall nearest a named place. The same walls always give the same sites; it knows nothing
about how the city was made.
local Sites = require("metropolisGame.logic.sites")
local s = Sites.new(walls)
-- walls: { { id, district, x, y, z, nx, nz, width, height } } (x, y, z: the middle of the wall's foot)
Sites.named(s, ...) Sites.mobile(s, ...) -- FIRST the sites that must exist (a story's walls)
Sites.deal(s, Districts.list, PaintContent.sizes) -- THEN every district's own sites on the walls that are left
s.list -- { site } in id order
s.byId["old_quay:piece:1"] -- { id, district, size, n, wall, x, y, z, nx, nz, width, height, name?, design?, permit? }
s.inDistrict.old_quay.piece -- { site, ... } (n order)
Sites.named(s, "fishmarket", { district = "old_quay", size = "piece", design = "fish", permit = false }, { x, z }, sizes)
-- seats a named site on the free fitting wall nearest that point; returns the site (nil when no wall fits)
s.named.fishmarket -- the site (also reachable as s.byId[site.id]); site.name = "fishmarket"
Sites.mobile(s, "tram_7_side", { district = "northgate", size = "piece", design = "kite", carrier = "tram" }, sizes)
-- a named site that is not on a wall: the side of a tram, a parade float. The host says where it is each
-- tick by writing site.x / site.z; everything else treats it as any other site
Sites.near(s, x, z, radius) -- sites within radius of a point, nearest first
Sites.fits(wall, size) -- whether a wall can carry a size
```
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.
# gunplay
Paint in the air and what it does when it lands: Wren's shots, the Wardens'
```
greywash coming back, cover on everything paintable, and the marks left behind. WORLD state, shared by every
player: one sky of projectiles, one cover tracker, one splat store, one field of timed effects.
It joins paintKit's arms / ballistics / impact / cover / splats to the game: who fired a shot (so the offence
goes to the right player), which hits are solvent on a painter (so the right player's colour is washed), and
the moments the rest of the game and the host care about, on the hub.
local Gunplay = require("metropolisGame.logic.gunplay")
local g = Gunplay.new({ paintCfg = cfg, query = physicsQuery, hub = hub })
g.cover g.splats g.field g.air -- paintKit stores (drawn by the host through fx)
local r = g:fire("p1", arms, { origin, dir, mount, owner = actorId }) -- paintKit arms:fire's result; the shots fly
g:hostile({ by, arm, from, at, wash, speed, gravity, range, radius, splash }) -- a pursuer's shot (pursuitKit firefight)
local out = g:step(dt, { [actorId] = playerId }) -- fly everything; resolve what landed
-- out = { { type = "paint", player, report }, paintKit impact's report for a player's shot (cover, offences ...)
-- { type = "washed", player, amount, by }, solvent hit a painter
-- { type = "stripped", x, z, removed } } solvent on a surface took marks off it
g:tick(dt) -- cover wipes and returns, effects run out, marks fade
g:effectOn(id, "slow") g:slickAt(x, z) -- queries the host's movers ask each tick
g:serialise() g:restore(data) -- world splats, persistent cover (lenses, relays), effects
Hub events: "shotsFired" { player, arm, pigment, n, loudness, heard, x, z }, "shotLaunched" { shot } (every
projectile, with its id, start, velocity, gravity and range: enough to replay its flight), "shotEnded" { id, hit }
(hit nil when it was spent), "paintLanded" { player, report },
"coverEffect" { id, kind, part, effect, seconds, by }, "paintedOut" { id, kind, seconds, by }, "coverBack" { id, kind },
"hostileShot" { by, arm, from, at }, "washed" { player, amount, by }, "effectEnded" { id, effect }.
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# config
Paint tools, paint arms, pigments, cover, colour and surface effects as one data table.
```
paintKit holds no numbers of its own. `Config.DEFAULTS` is a complete neutral set; a game overrides it:
local Config = require("~.modules.config")
local cfg = Config.merge(Config.DEFAULTS, { tools = { spray = { coverage = 1 } } })
local ok, problems = Config.validate(cfg)
Schema (the module that reads each part is in brackets):
cell metres per canvas cell (the grain of every mural) [canvas]
tools[name] = { what paints a canvas [painter]
mode = "stream" paints while held
radius metres of the mark on the surface
coverage square metres per second
tinPer square metres one tin covers
reach metres above the painter's feet the tool reaches
range metres from the surface it works at
spill 0..1: extra radius, as a share, painted at half strength (sloppy edges)
loudness how visible using it is (the game feeds this to whatever watches)
masked = true paints only the cells of the region it was prepared for (a stencil)
}
arms[name] = { what fires paint at things [arms]
mode = "pellet" | "lob" | "stream" | "cone"
pellet: `pellets` projectiles a shot, flying flat and fast; lob: one heavy projectile on a high arc
that bursts over `splash` metres; stream: droplets while held; cone: no projectile, everything in a
short cone gets `cover` per second (a spray can in a face)
pellets, spread projectiles a shot, and the half-angle of their scatter in degrees
speed, gravity, range metres a second at the muzzle, m/s2 pulling down, metres before it is spent
radius metres of the mark one projectile leaves
cover cover one projectile adds to what it hits (cone: per second)
splash metres round the impact that also take cover and marks (lob)
shotsPerTin shots one tin gives (stream and cone: seconds of fire a tin gives)
interval seconds between shots (stream: between droplets)
halfAngle cone only: half-angle in degrees
loudness, heard how visible firing it is, and how far away its report is heard (metres)
mount nil = carried; a name = only usable from that mount (the host says which)
scope zoom factor when aimed (nil = none)
}
ballistics = { step, maxShots } longest sub-step in seconds; projectiles alive at once [ballistics]
pigments[id] = { tactical properties; a pigment with no entry is plain [pigments]
cover multiplies the cover a hit adds (default 1)
blind multiplies the seconds of any "blind" effect it causes (default 1)
fade multiplies how long its marks last where marks fade (default 1)
effects = { { effect, on = { kind, ... }, seconds?, radius?, factor? } }
extra effects when it lands on a thing of one of those kinds
}
cover = { kinds[kind] = { what can be painted out [cover]
parts[part] = { capacity, effects = { { at, effect, seconds?, offence? } } }
capacity: cover that fills the part (1 = one full-strength hit);
effects fire when the part's cover rises through `at` (0..1)
defaultPart the part a hit lands on when the host names none
out = { part?, at, seconds?, effect?, offence? }
painted out when `part` (or, with no part, the mean of all parts) reaches
`at`; for `seconds` (nil: until repaired)
wipe = { after, rate } parts lose `rate` cover a second once `after` seconds pass without a hit
persist = true kept in a save (fixed things: lenses, relays)
} }
colour = { the painter's own colour, stripped by solvent [colour]
recover = { delay, rate, friendly } seconds unseen before it returns, share per second, and the extra
factor at full `friendly` ground (rate * (1 + friendly * ground))
edges the colour below which the picture starts to drain (for the screen)
washedOut = { reviveAt, speed, canPaint, canFire, grabWindow }
at zero colour the painter is washed out until colour is back to reviveAt:
speed factor, what the hands can do, and the factor on a pursuer's grab window
}
quality = { fillAt, overAt, tiers = { { name, coverage, accuracy?, overspray? } best first } } [canvas]
repaint = { keep } painting a different pigment over a cell keeps this share of its fill [canvas]
scrub = { gone } a canvas whose painted share falls below this is "scrubbed" [canvas]
surfaces[kind][arm|tool|"any"] = { effect, seconds?, radius?, offence? } [surfaces, impact]
what paint does to plain surfaces ("mark" leaves a splat)
splats = { max, bucket, mergeWithin, maxRadius, maxPerTarget,
rules[surface] = { life?, scrub? } } life: seconds a mark lasts there (nil: until scrubbed) [splats]
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# paint
This game's configuration of paintKit: the tools that paint walls, the paint
```
ARMS that fire the same tins, the eight pigments and what each does in a fight, cover for everything that can
be painted out, Wren's own colour, the mural sizes and the designs that go on the walls.
local PaintContent = require("metropolisGame.content.paint")
PaintContent.config -- overrides for paintKit.modules.config
PaintContent.pigments -- { { id, hex, safe, pattern } } in shop order (safe: colour-blind safe hex)
PaintContent.pigment("ochre") -- one of them
PaintContent.arms -- { id, ... } arm ids in wheel order
PaintContent.sizes.piece -- { scale, cols, rows, renown, colour, width, height } (width/height in metres)
PaintContent.designs.piece -- { { id, rows }, ... } authored pictures for that size
PaintContent.design("piece", 2) -- a paintKit design built from the nth picture (wraps round)
PaintContent.designById("piece", "fish")
Numbers follow s3/design/game_direction.md §1 (arms) and GAME_DESIGN.md §4.1 (tools); every one is here, none
in code. Designs are text: one character per block of `scale` x `scale` cells; a cell is 0.25 m. Letters:
o ochre v viridian m vermilion c ultramarine k white b lampblack s saffron h heather . bare wall
```
The interface is documented in the header of `init.luau`; this file repeats it for the asset browser.
# config
The whole kit's behaviour as one data table.
```
Nothing in pursuitKit holds a number of its own: observers, what counts as an offence, how heat becomes levels,
how long a search lasts, how an arrest is staged, how fast a pursuer runs, are all read from a config the game
passes in. `Config.DEFAULTS` is a complete, neutral starting point; a game overrides what it needs:
local Config = require("~.modules.config")
local cfg = Config.merge(Config.DEFAULTS, { heat = { max = 150 }, observers = { guard = { halfAngle = 70 } } })
local ok, problems = Config.validate(cfg)
Schema (every key is read by the module named in brackets):
observers[kind] [perception, awareness]
range = { day, night } metres at full light and in the dark (light 0..1 blends between them)
halfAngle degrees either side of where it faces
nearRange metres within which it notices whatever way it faces (0 for none)
fill, minFill, drain awareness per second at point-blank, the least while in view, and lost unseen
suspiciousAt, alertAt awareness thresholds (0..1)
onAlert "pursue" | "report" | "cheer" | "none"
report = { delay, via } for onAlert = "report": seconds to make it, and via "direct" | "relay" (a relay,
such as a call box, can be jammed by the host cancelling the report)
pursuer true when this kind can chase and grab
vertical = { up, down } degrees above and below level it can look (nil: any)
faction the name of the body it belongs to (carried on arrest events)
sequence the arrest sequence its grab starts (cfg.arrest.sequences[name]; nil: the main one)
acts[name] = { loudness, illegal } what the suspect is doing; loudness scales fill [perception]
concealment[tag] = factor multiplies fill; several tags multiply together [perception]
described = { fillFactor } fill multiplier while the suspect matches a whole description; a part
match scales toward it [perception]
known = { fillFactor } fill multiplier for an observer that knows the suspect's face [perception]
noise = { awareness } the awareness an observer in earshot of a noise rises to [director]
frame = { right } the sign of x on the right of someone facing +z: -1 in the engine's
frame (x east, z south, y up), +1 where z points north [pursuer, vehiclePursuit]
strikes = { fillPerStrike, max } standing record: each strike adds this share to fill [perception]
heat = { max, levels = { { at, name } }, offences[name] = points,
pursuitTick = { every, points }, decay = { grace, perSecond }, escape = { factor } } [heat]
incident = { noticeAt, clearBelow, reportedTimeout, loseSight, escapedHold,
search = { base, perLevel, radius, grow, radiusMax = { base, perLevel }, outsideRate, hiddenRate } }
grab = { range, windup, escapeDistance, recovery, vehicle = { speedBelow, within, hold } } [grab]
arrest = { stages = { { name, duration, breakable?, breakHold?, skippableAfter?, control? } }, breakOffence,
sequences[name] = { stages, breakOffence?, outcome?, handover = { atLevel }? } } [arrest, director]
response[level + 1] = { foot, cars, cordon, checkpoints, searchFactor } [dispatch]
pursuer = { foot = { patrol, investigate, chase, tired, stamina, recover, arrive, leash? },
car = { street, avenue, arrive, wheels = true }, <any other profile>, minSpawnDistance } [pursuer, dispatch]
firefight, roadblocks, vehiclePursuit, theft, roster, record, party: see the header of the module of that name
```
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.
# paintKit
Paint as a game system: what you carry, what the tools do, what a mural is meant to be and how well it was done;
and paint as a weapon: arms that fire pigment as real projectiles, cover as the health of everything paintable,
"painted out" instead of dead, the painter's own colour stripped by solvent, and marks that stay on walls, cars
and people. Engine-free logic configured by data; nothing in it names a game.
**Status (2026-11-22): logic run in the engine through `caseBench` (62 cases pass). `engineAdapters` (decal
splats, the `Physics.raycast` query) is written against the documented API and has NOT been run in a scene.**
## What is in it
| Module (`require("paintKit.modules.<name>")`) | What it does | Engine calls |
|-|-|-|
| `config` | `DEFAULTS`, `merge` (with `NONE` to drop a default), `validate`: the whole kit as one table | none |
| `supply` | tins by pigment with a capacity and pigment slots: a satchel, a shelf, a stash | none |
| `design` | a mural's intended picture from rows of characters and a legend, scaled to cells | none |
| `canvas` | cells with fill and pigment: `stroke`, `quality`, `sign`, `scrub`, `nextGap`, `serialise` / `restore` | none |
| `painter` | tool and pigment in hand; one tick of painting a canvas, with reasons for refusal | none |
| `arms` | paint arms: owned, selected, cadence, paint per shot; builds a shot's projectiles (seeded scatter) or a cone pulse | none |
| `ballistics` | projectiles under gravity in fixed sub-steps, hits through an injected query; `cone`, `splash`, `arc`, `lobVelocity`, `lead` | none |
| `pigments` | tactical properties of pigments: cover / blind / fade factors and extra effects by target kind | none |
| `cover` | cover per part of a thing, threshold effects, painted out and back, wiping, repair, save of fixed things | none |
| `colour` | the painter's own colour: `wash`, washed out, recovery unseen and on friendly ground, `effects` | none |
| `impact` | what a hit does: cover or a mark, surface rule, pigment effects, splash; reports offences | none |
| `splats` | marks on the world and on moving things: merge, budgets, fading, spatial lookup, change feed, save | none |
| `surfaces` | rule lookup for paint on a kind of surface; a field of timed and area effects | none |
| `engineAdapters` | `splatView` (decal projectors, also parented to things), `query` (the ballistics query on `Physics.raycast`) | `entity.spawn`, `@builtin::modules.decals`, `Physics.raycast` |
`tests/cases/core` (canvas, supply, painter, splats, surfaces) and `tests/cases/arms` (arms, ballistics, cover,
colour, pigments, impact, splats on things): 62 cases of pure logic. `tests/paintKit.testSuite` hands the same
cases to the engine's framework.
## Config schema
The header of `modules/config` is the schema. In short:
```lua
{
cell = 0.25,
tools = { spray = { mode = "stream", radius, coverage, tinPer, reach, range, spill, loudness, masked? } },
arms = { pistol = { mode = "pellet" | "lob" | "stream" | "cone", pellets, spread, speed, gravity, range, radius,
cover, splash?, shotsPerTin, interval, halfAngle?, loudness, heard, mount?, scope? } },
ballistics = { step, maxShots },
pigments = { white = { cover?, blind?, fade?, effects = { { effect, on = { kind }, seconds?, radius?, factor? } } } },
cover = { kinds = { guard = { parts = { visor = { capacity, effects = { { at, effect, seconds?, offence? } } } },
defaultPart, out = { part?, at, seconds?, effect?, offence? }, wipe?, persist? } } },
colour = { recover = { delay, rate, friendly }, edges, washedOut = { reviveAt, speed, canPaint, canFire, grabWindow } },
quality = { fillAt, overAt, tiers = { { name, coverage, accuracy?, overspray? }, ... } },
repaint = { keep }, scrub = { gone },
surfaces = { [kind] = { [arm | tool] | any = { effect, seconds?, radius?, offence? } } },
splats = { max, bucket, mergeWithin, maxRadius, maxPerTarget, rules = { [surface] = { life?, scrub? } } },
}
```
## Using it: a mural
```lua
local Config = require("paintKit.modules.config")
local Supply = require("paintKit.modules.supply")
local Design = require("paintKit.modules.design")
local Canvas = require("paintKit.modules.canvas")
local Painter = require("paintKit.modules.painter")
local cfg = Config.merge(Config.DEFAULTS, myPaintConfig)
local bag = Supply.new({ capacity = 12, slots = 3 }); bag:add("ochre", 6)
local hand = Painter.new(cfg, bag, { tools = { "spray" } })
local wall = Canvas.new(cfg, Design.fromRows({ rows = { ".oo.", "oooo" }, legend = { o = "ochre" }, scale = 4 }))
local r = hand:paint(wall, dt, { u = u, v = v, distance = d, stand = feetAboveWallFoot })
if not r.ok then hud.say(r.reason) end -- "empty", "too far", "out of reach", "signed", ...
local tier = wall:sign() -- fixes it; nil if below the lowest tier
```
## Using it: a firefight
```lua
local Arms = require("paintKit.modules.arms")
local Ballistics = require("paintKit.modules.ballistics")
local Cover = require("paintKit.modules.cover")
local Splats = require("paintKit.modules.splats")
local Surfaces = require("paintKit.modules.surfaces")
local Impact = require("paintKit.modules.impact")
local arms = Arms.new(cfg, bag, { arms = { "pistol" }, rng = seededRng }) -- same tins as the murals
local air = Ballistics.new(cfg.ballistics, query) -- query: see below
local cover, splats, field = Cover.new(cfg.cover), Splats.new(cfg.splats), Surfaces.field()
local impact = Impact.new(cfg, { cover = cover, splats = splats, field = field, query = query })
-- trigger pulled
local fired = arms:fire({ origin = muzzle, dir = aimDirection, owner = "player" })
if fired.ok then
for _, shot in fired.shots or {} do air:spawn(shot) end
if fired.cone then for _, report in impact:pulse(fired.cone) do handle(report) end end
witnesses.heard(fired.heard, fired.loudness)
end
-- every tick
arms:tick(dt)
for _, e in air:step(dt) do
if e.type == "impact" then
local report = impact:land(e.shot, e.hit) -- cover, mark, effects, offences, splash
for _, c in report.cover do
if c.type == "out" then guards.paintedOut(c.id, c.seconds) end
if c.type == "effect" and c.effect == "blind" then guards.blind(c.id, c.seconds) end
end
for _, offence in report.offences do crimes.report(offence) end
end
end
for _, e in cover:tick(dt) do guards.back(e.id) end
splats:tick(dt); view:sync(splats:drain())
```
Solvent coming the other way is the same machinery with a different consequence: the host flies the pursuers'
shots through its own `Ballistics`, and a hit on the painter calls `colour:wash(amount)`;
`colour:effects()` then says how slow the painter is and whether the hands still work.
## Interfaces the host provides
- **Physics query** (for `ballistics` and `impact`):
`query.raycast(origin, dir, distance, exclude) -> { x, y, z, nx, ny, nz, distance, kind, target?, part?, lx?, ly?, lz? } | nil`
and, for splash and cone arms, `query.overlap(centre, radius) -> { { target, kind, part?, x, y, z } }`.
`kind` is a surface kind (`cfg.surfaces`) or a cover kind (`cfg.cover.kinds`); `target` is the id of a thing.
`engineAdapters.query{ classify, entityOf, things }` builds it on `Physics.raycast`.
- **A seeded generator** `rng() -> [0, 1)` for scatter (the kit ships none, so every random number is the host's).
- **Where a tool points on a canvas**: `(u, v)` in metres from its lower-left corner, the painter's distance and
the height of its feet above the wall's foot.
- **Drawing**: canvases, shots in flight (`air:each`), splats (`store:drain()`; `engineAdapters.splatView`), cover
meters (`cover:view(id)`), the screen draining with `colour:effects().drain`.
## Events
paintKit returns results instead of emitting events: every call that changes something returns what changed
(`fire` → shots or a cone, `step` → impacts and spent shots, `land` / `pulse` → reports, `hit` → cover events,
`tick` → things back, `wash` → value and washed out, `stroke` → touched and added, `sign` → tier, `Field:tick` →
ended effects, `Splats:drain` → added / changed / removed). The host turns those into its own events.
## Example config for a pump gun and a blinding pigment
```lua
local cfg = Config.merge(Config.DEFAULTS, {
arms = { scatter = { mode = "pellet", pellets = 8, spread = 7, speed = 45, gravity = 9.8, range = 12,
radius = 0.14, cover = 0.14, shotsPerTin = 4, interval = 0.9, loudness = 2.5, heard = 60 } },
pigments = { white = { blind = 1.75 } },
})
```