A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Markers clear the roof, ripples calm down, and the upgrade arrow shows when the town needs it
SandroMaglionee5f5fa7f4e3c
diff --git a/docs/how-to-play.md b/docs/how-to-play.mdindex f829092..a0cd987 100644--- a/docs/how-to-play.md+++ b/docs/how-to-play.md@@ -96,9 +96,13 @@ six months.rises: the crown sends a reward, and play goes on. A rank is never lost.The town panel shows the next rank's goals.- **Upgrades** are made where a building stands, so they need no more- land. A gold arrow floats over every building the town can upgrade now- (the rank reached, the coins in hand). Select the building: its panel- says what the upgrade gives and costs, and its button begins it. The+ land. A gold arrow floats over a building when the town needs its+ upgrade, and can make it: a town hall the next rank asks for, a store+ whose shelves are full, a quarry worked out, a farm whose mills wait on+ wheat, a bakery flat out while homes lack bread, a market or chapel whose+ walkers leave homes out, a fire watch with homes at high fire risk (one+ arrow a kind). Select any upgradable building: its panel says whether it+ is needed now, what the upgrade gives and costs, and its button begins it. Thecoins are paid when the works begin; carriers thenbring the planks, stone, and tools, builders work them in as they come,and scaffolding rises inside its plot. It goes on working meanwhile.diff --git a/scripts/look-ui.ts b/scripts/look-ui.tsindex 88b6df0..d1a65ab 100644--- a/scripts/look-ui.ts+++ b/scripts/look-ui.ts@@ -53,6 +53,18 @@ for (const [name, width, height, phone] of [["desktop", 1440, 1000, false], ["phawait page.locator(".toolbar .pause").click()await page.evaluate(() => (window as any).town.ui.guide.push({ type: "off" }))+ // 0. The problem marker over a lumberjack (paused), clear of its roof.+ const lumber = await find(page, (e) => e.components["Town/Building"]?.kind === "lumberjack" && !e.components["Town/Site"])+ if (lumber) {+ const l: Tile = lumber.components["Town/Tile"]+ await page.evaluate((l) => (window as any).town.ui.edits.push({ type: "pause", cell: { x: l.x, y: l.y }, on: true }), l)+ await page.evaluate(() => (window as any).town.advance(1))+ await look(l.x + 1, l.y + 1, phone ? 2.4 : 3.2)+ await shot("0-marker")+ await page.evaluate((l) => (window as any).town.ui.edits.push({ type: "pause", cell: { x: l.x, y: l.y }, on: false }), l)+ await page.evaluate(() => (window as any).town.advance(1))+ }+// 1. A fishery, its water fished out: its status says so, and what to do; the water beyond it still shows fish.const fishery = await find(page, (e) => e.components["Town/Building"]?.kind === "fishery" && !e.components["Town/Site"])if (fishery) {diff --git a/src/factory.css b/src/factory.cssindex 3608c31..8c55470 100644--- a/src/factory.css+++ b/src/factory.css@@ -451,6 +451,8 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.panel section.state.trouble { border-top: 3px solid #b04a39; }.panel section.state.trouble .line .what { color: #b04a39; }.panel section.upgrade { border-top: 3px solid #b39a61; }+.panel section.upgrade .needed { margin: 0 0 6px; font-size: 11.5px; color: #8a938c; }+.panel section.upgrade .needed.now { color: #8a6418; font-weight: 700; }.panel section.upgrade .chips { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 6px; margin: 2px 0 6px; }.panel section.upgrade .cap { font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase; color: #9aa29b; margin-right: 4px; }.panel .lines .line.dim .count, .panel .lines .line.dim .what { color: #8a938c; font-weight: 400; }diff --git a/src/host.ts b/src/host.tsindex 92f52f2..fc81a6e 100644--- a/src/host.ts+++ b/src/host.ts@@ -419,6 +419,7 @@ export const createHost = async (view: "none",overlay: { key: "", cells: [] },tints: new Map(),+ wanted: new Map(),legend: null,flash: null,// Long enough to read (about 15 letters a second, and a moment to look), and gone as soon as the mayor@@ -1334,14 +1335,18 @@ export const createHost = async (if (now?.type === "building") ui.edits.push({ type: "upgrade", cell: now.cell })}const why = el("p", "sub", "")+ // Why the town needs it now (the gold arrow over it), or that it can wait.+ const needed = el("p", "needed", "")live.push(() => {const now = ui.panelif (now?.type !== "building" || !now.upgrade) return+ needed.textContent = now.upgrade.needed ? `needed now: ${now.upgrade.needed}` : "not needed yet: the gold arrow shows when it is"+ needed.classList.toggle("now", now.upgrade.needed !== null)cost.refresh()begin.disabled = now.upgrade.blocked !== null || now.upgrade.short !== nullwhy.textContent = now.upgrade.blocked ?? now.upgrade.short ?? "the coins are paid now; carriers bring the rest, scaffolding rises, and it goes on working"})- box.append(cost.box, list, begin, why)+ box.append(needed, cost.box, list, begin, why)return box}diff --git a/src/present.ts b/src/present.tsindex a7e0883..5cdc472 100644--- a/src/present.ts+++ b/src/present.ts@@ -355,6 +355,8 @@ const ALERT_PATIENCE = ticks(30)let emptySince: number | null = null/** Once said, it stays said a while, so a handful of fish arriving does not flick it off and on. */let hungryUntil = 0+/** Why each building's upgrade is needed now, by its id, reckoned once a second (see `upgradesWanted`). */+let wanted: { at: number; why: Map<number, string> } = { at: -1, why: new Map() }const HUNGER_PATIENCE = ticks(20)/** A view's colour over a model: pale, so the ink still reads. */const TINT = { good: 0xbcd2ee, fair: 0xf3e3a8, bad: 0xf2b9a0, cool: 0xdccbe8, mark: 0xd5dad3, settlers: 0xead7bd, fine: 0xa9c4e8, plain: 0xffffff }@@ -783,6 +785,62 @@ export const Interact = Game.System(// What stands, for a fix that builds something: it offers the first link of the chain the town lacks, else the last.const standing = new Set<KindId>(buildings.filter((r) => !r.data.site.present).map((r) => r.data.building.get().kind))const fixOf = (f: Fix | undefined): Line["fix"] => f && { text: f.text, build: f.build?.find((k) => !standing.has(k)) ?? f.build?.at(-1) }+ const finished = (row: { readonly data: { readonly site: { readonly present: boolean }; readonly rising: { readonly present: boolean } } }) => !row.data.site.present && !row.data.rising.present+ /** Built homes no food walker reaches: reckoned only until a market stands, as it is a walk from each walker's door. */+ const unreachedHomes = () => {+ const walks = buildings+ .filter((row) => maybe(row.data.service)?.service === "goods" && finished(row))+ .map((row) => ({ way: reach(grid, doors(grid, row.data.tile.get())), range: maybe(row.data.service)!.range }))+ return houses.filter((row) => {+ if (!finished(row)) return false+ const ds = doors(grid, row.data.tile.get())+ return ds.length > 0 && !walks.some((w) => (nearest(w.way, ds)?.distance ?? Infinity) < w.range)+ }).length+ }+ /**+ * The upgrades the town needs now, by the building, each with why: not every one it could make, but those+ * where the building is what holds the town back. A town hall the next rank asks for, or whose shelves are+ * full; a warehouse full; a quarry worked out; a farm whose mills wait on wheat; a bakery working flat out+ * while homes go without bread; a market whose walkers leave homes unreached; a chapel whose priests leave+ * homes without faith; a fire watch with homes on its streets at high fire risk.+ */+ const upgradesWanted = (): ReadonlyMap<number, string> => {+ const tick = resources.time.get().tick+ if (Math.floor(tick / 60) === wanted.at) return wanted.why+ const why = new Map<number, string>()+ const standingRows = buildings.filter((r) => !r.data.site.present && !r.data.rising.present && !maybe(r.data.works))+ const homes = houses.filter((r) => !r.data.site.present && !r.data.rising.present && !r.data.closed.present)+ const full = (r: (typeof buildings)[number]) => {+ const inv = maybe(r.data.inventory)+ return !!inv && goodIds.some((g) => inv.accepts.includes(g) && inv.stock[g] >= inv.cap * 0.9)+ }+ const near = (r: (typeof buildings)[number], tile: TileLike, range: number) => {+ const t = r.data.tile.get()+ return Math.abs(tile.x - (t.x + t.size / 2)) + Math.abs(tile.y - (t.y + t.size / 2)) <= range+ }+ const fishy = (r: (typeof houses)[number], need: "bread" | "faith") => r.data.house.get().tier >= 2 && !met(r.data.house.get(), need)+ const nextHall = ranks[Math.min(resources.fate.get().rank + 1, ranks.length - 1)]!.hall+ const millsWait = standingRows.some((r) => r.data.building.get().kind === "mill" && r.data.status.get() === "starved")+ const breadShort = resources.stock.get().bread < 5 && homes.some((r) => fishy(r, "bread"))+ for (const r of standingRows) {+ const kind = kinds[r.data.building.get().kind], level = maybe(r.data.upgraded)?.level ?? 0, status = r.data.status.get()+ if (!nextUpgrade(kind, level)) continue+ const reach = maybe(r.data.service)?.range ?? 0+ const reason =+ kind.id === "townhall" ? (nextHall > level ? "the next rank asks for it" : full(r) ? "its shelves are full" : null)+ : kind.id === "warehouse" ? (full(r) ? "its shelves are full" : null)+ : kind.id === "quarry" ? (status === "starved" && growingNear(grid, r.data.tile.get(), kind, rockAt) ? "it has worked its rock down" : null)+ : kind.id === "farm" ? (millsWait ? "the mills wait on wheat" : null)+ : kind.id === "bakery" ? (status === "working" && breadShort ? "homes go without bread while it works flat out" : null)+ : kind.id === "market" ? (unreachedHomes() > 0 ? "homes lie beyond every food walker" : null)+ : kind.id === "chapel" ? (homes.some((h) => fishy(h, "faith") && !near(r, h.data.tile.get(), reach)) ? "homes lie beyond its priest" : null)+ : kind.id === "firewatch" ? (homes.some((h) => (maybe(h.data.risk)?.fire ?? 0) >= risk.warn && near(r, h.data.tile.get(), reach + 6)) ? "homes on its streets are at high fire risk" : null)+ : null+ if (reason) why.set(r.entity.id, reason)+ }+ wanted = { at: Math.floor(tick / 60), why }+ return why+ }/** A cause as a row's note and fix. */const told = (c: Cause | null) => (c ? { note: c.why, fix: fixOf(c.fix) } : {})/**@@ -1117,7 +1175,7 @@ export const Interact = Game.System(const works = maybe(pickedBuilding.data.works)const up = works ? undefined : nextUpgrade(kind, level)const upgradeOffer = up && standing- ? { title: up.title, blurb: up.blurb, price: upgradePrice(up), cost: up.cost, changes: upgradeChanges(kind, level),+ ? { title: up.title, blurb: up.blurb, price: upgradePrice(up), cost: up.cost, changes: upgradeChanges(kind, level), needed: upgradesWanted().get(pickedBuilding.entity.id) ?? null,blocked: upgradeBlock(up, resources.fate.get().rank, { ranks }),short: resources.treasury.get().coins < up.cost.coins ? `${up.cost.coins - resources.treasury.get().coins} coins short` : null }: null@@ -1368,10 +1426,27 @@ export const Interact = Game.System(blocked: upgradeBlock(up, rank, { ranks }), ready: r.ready, underway: r.underway, first: r.first}})- // A word when an upgrade is open and nothing is being upgraded: where they are found.- const open = upgrades.find((u) => u.blocked === null && u.ready > 0 && u.first)- if (open && !upgrades.some((u) => u.underway > 0) && resources.treasury.get().coins >= open.coins)- alerts.push({ tone: "hint", text: `the ${open.from} can become ${anA(open.to)}: {tap|click} it (the gold arrow over it) to see what it gives and costs`, at: open.first!.data.tile.get(), size: open.first!.data.tile.get().size, id: open.first!.entity.id })+ // The upgrades the town needs now, where it can make them (the rank reached, the coins in hand): a gold arrow over each,+ // and a word for the first while nothing is being upgraded.+ const coinsNow = resources.treasury.get().coins+ // One arrow a kind: the first building of it that needs it (one farm made an estate is the answer, not all of them).+ const arrowed = new Set<KindId>()+ const due = new Map([...upgradesWanted()].filter(([id]) => {+ const row = buildings.find((b) => b.entity.id === id)+ const kind = row && kinds[row.data.building.get().kind]+ const up = row && kind && nextUpgrade(kind, maybe(row.data.upgraded)?.level ?? 0)+ if (!up || !kind || arrowed.has(kind.id) || upgradeBlock(up, rank, { ranks }) !== null || coinsNow < up.cost.coins) return false+ arrowed.add(kind.id)+ return true+ }))+ ui.wanted = due+ const [firstId, firstWhy] = [...due][0] ?? []+ const dueFirst = firstId === undefined ? undefined : buildings.find((b) => b.entity.id === firstId)+ if (dueFirst && !upgrades.some((u) => u.underway > 0)) {+ const kind = kinds[dueFirst.data.building.get().kind], level = maybe(dueFirst.data.upgraded)?.level ?? 0+ const from = (upgradeAt(kind, level)?.title ?? kind.title).toLowerCase(), to = nextUpgrade(kind, level)!.title.toLowerCase()+ alerts.push({ tone: "hint", text: `${firstWhy}: the ${from} can become ${anA(to)}. {Tap|Click} it, under its gold arrow, to begin`, at: dueFirst.data.tile.get(), size: dueFirst.data.tile.get().size, id: dueFirst.entity.id })+ }const ledger = resources.ledger.get()const charter = resources.charter.get()const t = elapsed(resources.time.get(), charter)@@ -1414,7 +1489,6 @@ export const Interact = Game.System(}const placedKinds = new Set(buildings.map(({ data }) => data.building.get().kind))const standingKinds = new Set(buildings.filter(({ data }) => !data.site.present && !data.rising.present).map(({ data }) => data.building.get().kind))- const finished = (row: { readonly data: { readonly site: { readonly present: boolean }; readonly rising: { readonly present: boolean } } }) => !row.data.site.present && !row.data.rising.presentconst wornRow = buildings.find((row) => finished(row) && !row.data.hall.present && (maybe(row.data.condition)?.value ?? CONDITION_MAX) < wear.mend)// A settlers' home with bread, cloth, and faith, kept from citizens only by its street.const poorRow = houses.find((row) => {@@ -1435,17 +1509,6 @@ export const Interact = Game.System(}return false}- /** Built homes no food walker reaches: reckoned only until a market stands, as it is a walk from each walker's door. */- const unreachedHomes = () => {- const walks = buildings- .filter((row) => maybe(row.data.service)?.service === "goods" && finished(row))- .map((row) => ({ way: reach(grid, doors(grid, row.data.tile.get())), range: maybe(row.data.service)!.range }))- return houses.filter((row) => {- if (!finished(row)) return false- const ds = doors(grid, row.data.tile.get())- return ds.length > 0 && !walks.some((w) => (nearest(w.way, ds)?.distance ?? Infinity) < w.range)- }).length- }const facts: GuideFacts = {homes: houses.length,builtHomes: houses.filter(finished).length,@@ -1805,7 +1868,7 @@ export const Animate = Game.System(fields: Game.Query({ selection: { field: Game.Query.read(Field) } }),water: Game.Query({ selection: { tile: Game.Query.read(Tile), water: Game.Query.read(Water) } })},- resources: { grid: Game.System.readResource(Grid), appeal: Game.System.readResource(Appeal), fate: Game.System.readResource(Fate), treasury: Game.System.readResource(Treasury), time: Game.System.readResource(Time) },+ resources: { grid: Game.System.readResource(Grid), appeal: Game.System.readResource(Appeal), time: Game.System.readResource(Time) },services: {stage: Game.System.service(StageService),ui: Game.System.service(Ui),@@ -1825,7 +1888,6 @@ export const Animate = Game.System(const { hover, danger } = services.ui.previewconst emphasis = (id: number): Emphasis => (danger && hover === id ? "danger" : "normal")const dt = services.clock.deltaSeconds- const rank = resources.fate.get().rank, coins = resources.treasury.get().coins// Fish where the water would give a catch now; none where it rests after one.const tick = resources.time.get().tickservices.stage.setFish(queries.water.each().filter(({ data }) => tick - data.water.get().fished >= RESTOCK_TICKS).map(({ data }) => data.tile.get()))@@ -1833,9 +1895,8 @@ export const Animate = Game.System(for (const { entity, data } of queries.buildings.each()) {const kind = kinds[data.building.get().kind]const status = data.status.get()- // An upgrade it could begin now: its rank reached, its coins in hand, nothing under way.- const up = data.works.present || data.site.present || data.rising.present ? undefined : nextUpgrade(kind, maybe(data.upgraded)?.level ?? 0)- const upgradable = !!up && upgradeBlock(up, rank, { ranks }) === null && coins >= up.cost.coins+ // An upgrade the town needs now, and can make (see `upgradesWanted`).+ const upgradable = services.ui.wanted.has(entity.id)const recipe = maybe(data.recipe)const walkers = maybe(data.walkers)?.length ?? 0const worn = (maybe(data.condition)?.value ?? CONDITION_MAX) < wear.worndiff --git a/src/render3d/fish-effects.ts b/src/render3d/fish-effects.tsindex 10a3de8..e9a315d 100644--- a/src/render3d/fish-effects.ts+++ b/src/render3d/fish-effects.ts@@ -11,7 +11,8 @@ void main(){phase=seed;gl_Position=projectionMatrix*modelViewMatrix*instanceMatrix*vec4(position,1.0);}`-// Two thin ink rings spreading from a point off the middle, now and then, and a fish's back turning in them.+// Now and then (each cell in its own time), one thin ink ring spreads slowly from a point off the middle and+// fades; most of the time the water is still. Calm enough to sit beside the town, plain enough to read.const fragment = `uniform float time;varying vec2 point;@@ -19,22 +20,20 @@ varying float phase;void main(){vec2 at=point-vec2(fract(phase*7.13)-0.5,fract(phase*3.71)-0.5)*0.5;float d=length(at);- float age=fract(time*0.32+phase);- float ring=0.0;- for(int i=0;i<2;i++){- float r=age*0.75-float(i)*0.16;- ring+=(1.0-smoothstep(0.0,0.035,abs(d-r)))*step(0.0,r)*(1.0-age);- }- float back=(1.0-smoothstep(0.05,0.075,length(at*vec2(1.0,2.4))))*(1.0-smoothstep(0.0,0.18,age))*step(0.02,age);+ float age=fract(time*0.058+phase)/0.3;+ if(age>1.0)discard;+ float r=0.08+age*0.5;+ float ring=1.0-smoothstep(0.0,0.03,abs(d-r));+ float fade=smoothstep(0.0,0.15,age)*(1.0-age);float edge=1.0-smoothstep(0.85,1.0,max(abs(point.x),abs(point.y)));- float alpha=clamp(ring*0.55+back*0.7,0.0,1.0)*edge;+ float alpha=ring*fade*edge*0.38;if(alpha<0.01)discard;gl_FragColor=vec4(pow(vec3(0.32,0.45,0.52),vec3(2.2)),alpha);#include <colorspace_fragment>}`/**- * Fish in the water: ripples spreading now and then on every cell of water+ * Fish in the water: a slow ripple now and then on every cell of water* that would give a catch, none on a cell resting after one. A fishery's* shore reads at a glance as stocked or fished out.*/diff --git a/src/render3d/models.ts b/src/render3d/models.tsindex 13f6c96..12c2914 100644--- a/src/render3d/models.ts+++ b/src/render3d/models.ts@@ -72,9 +72,25 @@ export function constructionAsset(size: number, half: number, height: number, bu/** The height a building of a kind is drawn to its eaves at its level of upgrades (see `upgradeHeights`). */export const buildingHeight = (id: KindId, level = 0) =>level > 0 && id === "townhall" ? civicEave(level) : level > 0 && isUpgradable(id) ? upgradeHeights[id].eave : buildingDimensions(id).height-/** Its highest point, for the marker over it. */+/** The highest point of a kind's finished model at a level, measured from what is drawn (once each). */+const drawnTops = new Map<string, number>()+const drawnTop = (id: KindId, level: number): number => {+ const k = `${id}/${level}`+ let top = drawnTops.get(k)+ if (top === undefined) {+ const asset = buildingAsset(id, 1, null, { right: true, left: true, backRight: true, backLeft: true }, 0, {}, level)+ top = 0+ for (const shape of [...asset.faces, ...asset.strokes]) for (const p of shape.points) top = Math.max(top, p[2])+ drawnTops.set(k, top)+ }+ return top+}+/** Its highest point, for the marker over it: never below what is drawn, chimney and all. */export const buildingTop = (id: KindId, level = 0) =>- level > 0 && isUpgradable(id) ? upgradeHeights[id].top : level > 0 && isDressed(id) ? Math.max(buildingDimensions(id).top, dressedTop(id, level, buildingDimensions(id).height)) : buildingDimensions(id).top+ Math.max(+ drawnTop(id, level),+ level > 0 && isUpgradable(id) ? upgradeHeights[id].top : level > 0 && isDressed(id) ? Math.max(buildingDimensions(id).top, dressedTop(id, level, buildingDimensions(id).height)) : buildingDimensions(id).top+ )const isUpgradable = (id: KindId): id is ServiceKind => id === "market" || id === "chapel"export function buildingAsset(id: KindId, build: number, share: number | null, doors: DoorSet, open: number, appearance: Appearance = {}, level = 0) {diff --git a/src/sim/headless.ts b/src/sim/headless.tsindex 1dbbba6..314e220 100644--- a/src/sim/headless.ts+++ b/src/sim/headless.ts@@ -25,7 +25,7 @@ export const headless = (charter: CharterValue, options: { readonly toast?: (mestool: "select", placing: null, upgrading: null, ground: "lawn", prop: "lamp", menu: null, pointer: null, dragFrom: null, selected: null, gestures: [], guide: [],edits: [{ type: "newTown", charter }],preview: emptyPreview(), hits: [], panel: null, centres: new Map(), stats: null, speed: 1, founding: false,- view: "none", overlay: { key: "", cells: [] }, tints: new Map(), legend: null, flash: null,+ view: "none", overlay: { key: "", cells: [] }, tints: new Map(), wanted: new Map(), legend: null, flash: null,toast: options.toast ?? (() => {})}const made = Game.Runtime.make({ services: Game.Runtime.services(Game.Runtime.service(Ui, ui), Game.Runtime.service(Rules, options.rules ?? resolveRules())), resources: blankResources() })diff --git a/src/ui.ts b/src/ui.tsindex fb62215..8c360ea 100644--- a/src/ui.ts+++ b/src/ui.ts@@ -159,6 +159,8 @@ export type Panel =readonly title: stringreadonly blurb: stringreadonly price: string+ /** Why the town needs it now, when it does (the gold arrow over it); `null`: it can wait. */+ readonly needed: string | null/** Coins now, and the materials carriers bring. */readonly cost: { readonly coins: number; readonly materials: Partial<Record<GoodId, number>> }readonly changes: ReadonlyArray<string>@@ -423,6 +425,8 @@ export interface UiValue {overlay: { readonly key: string; readonly cells: ReadonlyArray<OverlayCell> }/** The view's colour for each building and home, washed over the model itself so it reads from above. */tints: ReadonlyMap<number, number>+ /** The buildings whose upgrade the town needs now, with why (the gold arrow over each). */+ wanted: ReadonlyMap<number, string>legend: Legend | null/** A place the page points at (from the ticker): outlined until `until`, in the clock's seconds. */flash: { readonly cell: Point; readonly size: number; readonly until: number } | null