A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Split the presentation into a view layer and a Three.js renderer
SandroMaglioneddf05a942939
diff --git a/scripts/balance.ts b/scripts/balance.tsindex 1e6b3ac..ef1526c 100644--- a/scripts/balance.ts+++ b/scripts/balance.ts@@ -759,7 +759,6 @@ const run = (seed: number) => {roading.clear()resting.clear()const town = headless({ size, term, land, seed }, { rules, toast: (m) => { if (process.env.DEBUG) console.log("toast:", m) } })- const ui = town.uiconst step = town.runconst rows: Array<Row> = []@@ -784,7 +783,7 @@ const run = (seed: number) => {}}if (process.env.DEBUG) console.log(t, JSON.stringify(chosen).slice(0, 200))- ui.edits.push(...chosen)+ town.edit(...chosen)step(DECIDE)w = read(town.snapshot())if (w.fate.goalSince >= 0) longestGoalHold = Math.max(longestGoalHold, (w.tick - w.charter.founded - w.fate.goalSince) / 60)diff --git a/scripts/check-browser.ts b/scripts/check-browser.tsindex 6af959f..37b5461 100644--- a/scripts/check-browser.ts+++ b/scripts/check-browser.ts@@ -7,13 +7,14 @@ import { existsSync } from "node:fs"import { mkdir,readFile,writeFile } from "node:fs/promises"import { execFileSync } from "node:child_process"import { chromium } from "playwright"-import type { UiValue } from "../src/view/contracts.ts"+import type { EditQueue } from "../src/game/edits.ts"+import type { Interaction, Shown } from "../src/view/contracts.ts"import type { GameScene } from "../src/render/three/scene.ts"import type { Snapshot } from "../src/game/headless.ts"declare global {interface Window {- town:{ui:UiValue;view:GameScene;advance:(seconds:number)=>void;runtime:{snapshot:()=>Snapshot}}+ town:{interaction:Interaction;shown:Shown;edits:EditQueue;view:GameScene;advance:(seconds:number)=>void;runtime:{snapshot:()=>Snapshot}}}}const executable=process.env.BROWSER_EXECUTABLE_PATH??["/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"].find(existsSync)@@ -44,13 +45,13 @@ try {await page.waitForFunction(()=>window.town)await page.getByRole("button",{name:"small",exact:true}).click()await page.getByRole("button",{name:"Start new",exact:true}).click()- await page.waitForFunction(()=>!window.town.ui.founding)+ await page.waitForFunction(()=>!window.town.interaction.founding)await page.locator(".toolbar .pause").click()const hall=(await entities("Town/TownHall"))[0]!,tile=hall.components["Town/Tile"]await page.keyboard.press("e")await clickGrid(tile.x+1.5,tile.y+1.5,48)- await page.waitForFunction(id=>window.town.ui.selected===id,hall.id)- assert.equal((await page.evaluate(()=>window.town.ui.panel))?.type,"building")+ await page.waitForFunction(id=>window.town.interaction.selected===id,hall.id)+ assert.equal((await page.evaluate(()=>window.town.shown.town.panel))?.type,"building")facts.rotatedSelection=trueawait tool("road")await dragGrid([tile.x+4.5,tile.y+1.5],[tile.x+8.5,tile.y+1.5])@@ -69,14 +70,14 @@ try {facts.rotatedBuildingPlacement=trueawait capture("construction")await page.evaluate(()=>window.town.advance(90))- await page.waitForFunction(()=>window.town.ui.stats!.settlers>0)+ await page.waitForFunction(()=>window.town.shown.town.stats!.settlers>0)assert.ok((await entities("Town/House")).some(e=>!("Town/Site" in e.components)))facts.liveConstruction=trueawait tool("select")await page.keyboard.press("e")const lt=lumber.components["Town/Tile"]await clickGrid(lt.x+1,lt.y+1,16)- await page.waitForFunction(id=>window.town.ui.selected===id,lumber.id)+ await page.waitForFunction(id=>window.town.interaction.selected===id,lumber.id)const pauseWork=page.getByRole("button",{name:"Pause work",exact:true})await pauseWork.click()await page.waitForFunction(id=>!!window.town.runtime.snapshot().entities.find(e=>e.id===id)?.components["Town/Paused"],lumber.id)@@ -106,7 +107,7 @@ try {await page.getByRole("button",{name:"large",exact:true}).click()await page.getByRole("button",{name:"rich",exact:true}).click()await page.getByRole("button",{name:"Start new",exact:true}).click()- await page.waitForFunction(()=>!window.town.ui.founding&&window.town.ui.stats?.charter.size==="large")+ await page.waitForFunction(()=>!window.town.interaction.founding&&window.town.shown.town.stats?.charter.size==="large")assert.equal((await entities("Town/House")).length,0)assert.equal((await entities("Town/TownHall")).length,1)await page.locator(".toolbar .pause").click()@@ -123,9 +124,10 @@ try {},grown)await page.getByRole("button",{name:"load",exact:true}).click()await page.getByRole("button",{name:"Load without saving",exact:true}).click()- await page.waitForFunction(()=>window.town.ui.stats!.settlers>100)- // The guide puts away what the bot's town has already done on the page's first frame; the rest loads exactly as saved.+ await page.waitForFunction(()=>window.town.shown.town.stats!.settlers>100)+ // The guide puts away what the bot's town has already done (as edits, kept on the next frame without a step of time); the rest loads exactly as saved.const withoutGuide=(w:Snapshot)=>({...w,resources:{...w.resources,"Town/Guide":null}})+ await page.waitForFunction(()=>window.town.runtime.snapshot().resources["Town/Guide"].done.length>0)const loaded=await snapshot()assert.deepEqual(withoutGuide(loaded),withoutGuide(grown.world))assert.ok(["homes","fishery","market"].every(id=>loaded.resources["Town/Guide"].done.includes(id)),"The guide puts away what the town has done")@@ -140,7 +142,7 @@ try {for (let angle=0;angle<8;angle++) {await page.keyboard.press("e")await clickGrid(ht.x+1.5,ht.y+1.5,48)- await page.waitForFunction(id=>window.town.ui.selected===id,grownHall.id)+ await page.waitForFunction(id=>window.town.interaction.selected===id,grownHall.id)await page.locator(".panel .close").click()}facts.selectionAllEightAngles=true@@ -191,7 +193,7 @@ try {await page.getByRole("button",{name:"Load without saving",exact:true}).click()await page.getByRole("button",{name:"Next term",exact:true}).waitFor({state:"visible"})await page.getByRole("button",{name:"Retire: found a new town",exact:true}).waitFor({state:"visible"})- assert.equal(await page.evaluate(()=>window.town.ui.stats!.fate.state),"over")+ assert.equal(await page.evaluate(()=>window.town.shown.town.stats!.fate.state),"over")facts.reckoning=true// Sharing: the card, then a link that opens the town in another browser (a phone), which can play on from there.await page.getByRole("button",{name:"Share the town",exact:true}).click()diff --git a/scripts/look-readme.ts b/scripts/look-readme.tsindex 245c1e4..21671bc 100644--- a/scripts/look-readme.ts+++ b/scripts/look-readme.ts@@ -43,8 +43,8 @@ if (mode === "stills") {await page.locator(".sheet.wide").screenshot({ path: `${out}/charter.png` })}await page.getByRole("button", { name: /Continue/ }).first().click()-await until(() => page.evaluate(() => !(window as any).town.ui.founding))-await page.evaluate(() => (window as any).town.ui.guide.push({ type: "off" }))+await until(() => page.evaluate(() => !(window as any).town.interaction.founding))+await page.evaluate(() => (window as any).town.interaction.guide.push({ type: "off" }))// The news, the overlay list, the camera buttons, and the "loaded" toast stay out of the pictures.await page.addStyleTag({ content: ".ticker, .views, .camera-controls, .toast { display: none !important; }" })await run(1000)@@ -94,7 +94,7 @@ if (mode === "film") {// The page's own loop is held (its speed buttons hidden), and the town is stepped here at twice its pace, exactly// two thirtieths of a second a frame: under Playwright's clock the loop's frames come unevenly.await page.addStyleTag({ content: ".toolbar .speed, .paused-tag { display: none !important; }" })- await page.evaluate(() => { (window as any).town.ui.speed = 0 })+ await page.evaluate(() => { (window as any).town.interaction.speed = 0 })await mkdir(`${out}/frames`, { recursive: true })for (let f = 0; f < fps * seconds; f++) {await camera(at(f / fps))diff --git a/scripts/look-ui.ts b/scripts/look-ui.tsindex 74234fb..d2c0912 100644--- a/scripts/look-ui.ts+++ b/scripts/look-ui.ts@@ -49,19 +49,19 @@ for (const [name, width, height, phone] of [["desktop", 1440, 1000, false], ["phawait page.reload()await page.waitForFunction(() => (window as any).town)await page.getByRole("button", { name: /Continue/ }).first().click()- await page.waitForFunction(() => !(window as any).town.ui.founding)+ await page.waitForFunction(() => !(window as any).town.interaction.founding)await page.locator(".toolbar .pause").click()- await page.evaluate(() => (window as any).town.ui.guide.push({ type: "off" }))+ await page.evaluate(() => (window as any).town.interaction.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((l) => (window as any).town.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((l) => (window as any).town.edits.push({ type: "pause", cell: { x: l.x, y: l.y }, on: false }), l)await page.evaluate(() => (window as any).town.advance(1))}@@ -136,7 +136,7 @@ for (const [name, width, height, phone] of [["desktop", 1440, 1000, false], ["phif (!b) continueconst tile: Tile = b.components["Town/Tile"]picked.push({ kind, tile })- await page.evaluate((t) => (window as any).town.ui.edits.push({ type: "upgrade", cell: { x: t.x, y: t.y } }), tile)+ await page.evaluate((t) => (window as any).town.edits.push({ type: "upgrade", cell: { x: t.x, y: t.y } }), tile)}await page.evaluate(() => (window as any).town.advance(1))const progress = async () => (await town(page)).entities.filter((e: any) => e.components["Town/Works"]).lengthdiff --git a/scripts/look-upgrades.ts b/scripts/look-upgrades.tsindex 275dac1..337fcc3 100644--- a/scripts/look-upgrades.ts+++ b/scripts/look-upgrades.ts@@ -23,7 +23,7 @@ try {await page.waitForFunction(() => (window as any).town)await page.getByRole("button", { name: "small", exact: true }).click()await page.getByRole("button", { name: "Start new", exact: true }).click()- await page.waitForFunction(() => !(window as any).town.ui.founding)+ await page.waitForFunction(() => !(window as any).town.interaction.founding)await page.locator(".toolbar .pause").click()// A town that has reached the town rank, with coins and materials to spare.await page.evaluate(() => {@@ -66,7 +66,7 @@ try {const restored = t.runtime.restore(s)if (!restored.ok) throw new Error(`The changed town did not load: ${JSON.stringify(restored.error)}`)})- await page.evaluate(([x,y])=>(window as any).town.ui.edits.push({type:"upgrade",cell:{x,y}}),[hall.x,hall.y])+ await page.evaluate(([x,y])=>(window as any).town.edits.push({type:"upgrade",cell:{x,y}}),[hall.x,hall.y])await page.evaluate(()=>(window as any).town.advance(80))await page.waitForTimeout(300)await page.screenshot({path:`${out}/5-cityhall-works.png`})@@ -76,7 +76,7 @@ try {await page.screenshot({path:`${out}/5-cityhall.png`})// The new workshop's actual model portrait and upgrade choices must fit a phone.await page.setViewportSize({ width: 390, height: 844 })- await page.evaluate(() => { const ui = (window as any).town.ui; ui.selected = null; ui.menu = "build" })+ await page.evaluate(() => { const ui = (window as any).town.interaction; ui.selected = null; ui.menu = "build" })const carpenter = page.locator(".panel .option").filter({ has: page.locator(".name", { hasText: /^carpenter$/i }) })await carpenter.scrollIntoViewIfNeeded()await carpenter.locator("img").evaluate(async (img: HTMLImageElement) => { if (!img.complete) await new Promise<void>(resolve => img.addEventListener("load", () => resolve(), { once: true })) })diff --git a/src/app/browser.ts b/src/app/browser.tsindex 31e5e50..31f0a91 100644--- a/src/app/browser.ts+++ b/src/app/browser.ts@@ -1,8 +1,10 @@-import { resolveRules } from "../game/rules/config.ts"/**- * A town simulation of line-drawn buildings, homes, roads, and land, on the- * Ritmo ECS with a 3D view. The simulation runs on a fixed step;- * the views follow once a frame.+ * The page: a town simulation of line-drawn buildings, homes, roads, and+ * land, on the Ritmo ECS with a 3D view. This is the one module that knows+ * every layer: it makes the world's runtime (`game`), hands it the view's+ * and the renderer's services, mounts the page's UI (`ui/dom`), and runs the+ * loop: the simulation on a fixed step, then the view and the renderer once+ * a frame.*/import { FixedLoop, HostClock, Result } from "@typeonce/ritmo"import { Effect } from "effect"@@ -10,14 +12,19 @@ import { BrowserHostClock } from "@typeonce/ritmo-browser"import type { BuildingView, FieldView, HouseView, RockView, RuinView, TreeView, WalkerView } from "../render/three/views.ts"import { lands, sizes, step } from "../game/content/index.ts"-import { createHost, type Persistence } from "../ui/dom/host.ts"-import { present } from "../view/present.ts"+import { bookkeeping, editQueue } from "../game/edits.ts"+import { resolveRules } from "../game/rules/config.ts"+import { blankResources, settle, simulate } from "../game/schedule.ts"+import { Edits, Game, Rules } from "../game/schema.ts"import { browserStorage, describe, fileOf, latest, loadLatest, loadText, save, Storage, World } from "../platform/save.ts"-import type { CameraView } from "../render/three/scene.ts"import { download, sharedId } from "../platform/share/client.ts"-import { BuildingNodes, Clock, Edits, FieldNodes, Game, Rules, HouseNodes, RockNodes, RuinNodes, StageService, TreeNodes, Ui, WalkerNodes } from "../game/schema.ts"-import { editsOf } from "../game/headless.ts"-import { blankResources, simulate } from "../game/schedule.ts"+import type { CameraView } from "../render/three/scene.ts"+import { draw } from "../render/three/schedule.ts"+import { BuildingNodes, FieldNodes, HouseNodes, RockNodes, RuinNodes, StageService, TreeNodes, WalkerNodes } from "../render/three/services.ts"+import { createHost, type Persistence } from "../ui/dom/host.ts"+import { blankInteraction, blankShown } from "../view/contracts.ts"+import { project } from "../view/schedule.ts"+import { Clock, Interaction, Outbox, Shown } from "../view/services.ts"/** Minutes of game time between autosaves. */const AUTOSAVE_MINUTES = 2@@ -39,7 +46,11 @@ const start = async () => {// A town saved in this browser before: the founding screen offers to carry on with it.const last = Effect.runSync(Effect.result(latest.pipe(Effect.provideService(Storage, browserStorage(localStorage)))))const saved = last._tag === "Success" && last.success !== null ? { title: last.success.title, savedAt: last.success.savedAt } : null- const { stage, ui, syncPage, resetPage, visit, visitFailed, visiting } = await createHost(mount, () => persistence, { shared: shared !== null, saved })+ // What the player is doing, what the view shows, and the edits waiting for the next step: shared by the UI, the view, and the simulation.+ const interaction = blankInteraction()+ const shown = blankShown()+ const edits = editQueue()+ const { stage, syncPage, resetPage, toast, visit, visitFailed, visiting } = createHost(mount, () => persistence, { interaction, shown, send: edits.push }, { shared: shared !== null, saved })if (shared)download(shared).then((text) => (arriving = text),@@ -63,8 +74,10 @@ const start = async () => {const hostClock = BrowserHostClock.make(window)const made = Game.Runtime.make({services: Game.Runtime.services(- Game.Runtime.service(Ui, ui),- Game.Runtime.service(Edits, editsOf(ui)),+ Game.Runtime.service(Interaction, interaction),+ Game.Runtime.service(Shown, shown),+ Game.Runtime.service(Outbox, edits),+ Game.Runtime.service(Edits, edits),Game.Runtime.service(Rules, resolveRules()),Game.Runtime.service(Clock, clock),Game.Runtime.service(StageService, stage),@@ -86,7 +99,7 @@ const start = async () => {return}const runtime = made.value- // In development, the page's console can reach the town: `town.ui.edits.push(...)`,+ // In development, the page's console can reach the town: `town.edits.push(...)`, `town.interaction`, `town.shown`,// `town.runtime.snapshot()`, and `town.advance(seconds)` to fast-forward the simulation.if (import.meta.env.DEV) {const advance = (seconds: number) => {@@ -95,7 +108,7 @@ const start = async () => {if (!stepped.ok) throw new Error(`A step failed: ${JSON.stringify(stepped.error)}`)}}- Object.assign(window, { town: { ui, runtime, advance, view: stage } })+ Object.assign(window, { town: { interaction, shown, edits, runtime, advance, view: stage } })if (runtime.debug !== undefined) {// Loaded in dev only: the production bundle never includes devtools.const { attachDevtools } = await import("./devtools.ts")@@ -113,7 +126,7 @@ const start = async () => {return restored.ok ? null : restored.error._tag},title: () => {- const s = ui.stats+ const s = shown.town.statsreturn s? `${sizes[s.charter.size].title}, ${lands[s.charter.land].title} land · year ${s.season.year} · ${Math.floor(s.minute)} min in`: "a town"@@ -151,13 +164,13 @@ const start = async () => {/** The page autosaves every `AUTOSAVE_MINUTES` of game time while a term runs. */let autosaved = 0const autosave = () => {- const s = ui.stats- if (!s || s.fate.state !== "playing" || ui.founding || visiting()) return+ const s = shown.town.stats+ if (!s || s.fate.state !== "playing" || interaction.founding || visiting()) returnif (s.minute < autosaved) autosaved = 0if (s.minute < autosaved + AUTOSAVE_MINUTES) returnautosaved = Math.floor(s.minute / AUTOSAVE_MINUTES) * AUTOSAVE_MINUTESconst saved = run(save("auto"))- if (saved._tag === "Failure") ui.toast(describe(saved.failure))+ if (saved._tag === "Failure") toast(describe(saved.failure))}/** A shared town has just loaded and not yet been drawn. */@@ -171,7 +184,7 @@ const start = async () => {// new-town dialog is open, and once the term has ended (an edit, such as// founding a new town, still gets its step).update: () => {- if (arriving !== null && ui.edits.length === 0) {+ if (arriving !== null && edits.queued.length === 0) {const text = arrivingarriving = nullarrive(text)@@ -179,13 +192,16 @@ const start = async () => {}// The town's numbers are still the old town's until the next frame draws the new one: wait for them.if (settling) return Result.success(undefined)- if (ui.edits.some((edit) => edit.type === "newTown")) {+ if (edits.queued.some((edit) => edit.type === "newTown")) {resetPresentation()stage.resetCamera()}- const waiting = ui.speed === 0 || ui.founding || (ui.stats !== null && ui.stats.fate.state !== "playing")- // Guide edits are bookkeeping: they wait for the next step rather than run one while the town waits.- const steps = waiting ? (ui.edits.some((edit) => edit.type !== "guide" && edit.type !== "guideOff") ? 1 : 0) : ui.speed+ const waiting = interaction.speed === 0 || interaction.founding || (shown.town.stats !== null && shown.town.stats.fate.state !== "playing")+ // An edit still gets its step while the town waits; the guide's books are kept without one.+ const pending = edits.queued.length > 0+ const books = pending && edits.queued.every(bookkeeping)+ if (waiting && books) return runtime.tick(settle)+ const steps = waiting ? (pending ? 1 : 0) : interaction.speedfor (let i = 0; i < steps; i++) {const stepped = runtime.tick(simulate)if (!stepped.ok) return stepped@@ -195,8 +211,10 @@ const start = async () => {render: ({ elapsedSeconds }) => {clock.deltaSeconds = elapsedSecondsclock.elapsed += elapsedSeconds- const shown = runtime.tick(present)- if (!shown.ok) throw new Error(`The town view stopped: ${JSON.stringify(shown.error)}`)+ const viewed = runtime.tick(project)+ if (!viewed.ok) throw new Error(`The town view stopped: ${JSON.stringify(viewed.error)}`)+ const drawn = runtime.tick(draw)+ if (!drawn.ok) throw new Error(`The town view stopped: ${JSON.stringify(drawn.error)}`)settling = falsesyncPage()autosave()diff --git a/src/app/devtools.ts b/src/app/devtools.tsindex d94d1c9..db61aa2 100644--- a/src/app/devtools.ts+++ b/src/app/devtools.ts@@ -1,5 +1,5 @@/**- * Dev builds only (`main.ts` imports this behind `import.meta.env.DEV`): the+ * Dev builds only (`browser.ts` imports this behind `import.meta.env.DEV`): the* bevy-ts monitor, and a replay recorder that keeps the last minute of* `simulate` and saves it to `.replays/` (through the dev server, see* `vite.config.ts`) when a step fails, when an invariant breaks, or when the@@ -10,9 +10,10 @@ import { Invariant, Monitor, Replay } from "@typeonce/ritmo-devtools"import * as ReplayViteSink from "@typeonce/ritmo-devtools/ReplayViteSink"import { step } from "../game/content/index.ts"-import { present } from "../view/present.ts"import { Building, Game, Root, Treasury } from "../game/schema.ts"import { simulate } from "../game/schedule.ts"+import { draw } from "../render/three/schedule.ts"+import { project } from "../view/schedule.ts"/** The treasury holds a whole number of coins: a NaN or a fraction means some sum went wrong. */export const CoinsAreWhole = Invariant.fromInspector(Game.Inspector("coins are whole", {@@ -60,6 +61,6 @@ export const attachDevtools = (host: DevtoolsHost) => {hostClock: host.wallClock,saveOn: { failure: true, invariants: host.demo ? [CoinsAreWhole, FewerThanTenBuildings] : [CoinsAreWhole] }})- const monitor = Monitor.attach(host.runtime, { schedules: { simulate, present }, mount: host.mount, host: host.host, replay: recorder })+ const monitor = Monitor.attach(host.runtime, { schedules: { simulate, project, draw }, mount: host.mount, host: host.host, replay: recorder })return { recorder, monitor }}diff --git a/src/game/edits.ts b/src/game/edits.tsindex 47bd3d5..6b1a185 100644--- a/src/game/edits.ts+++ b/src/game/edits.ts@@ -43,6 +43,9 @@ export type Edit =export type TradeMode = "sell" | "buy" | "none"+/** Edits that only keep the guide's books: they never need a step of time (see `settle`). */+export const bookkeeping = (edit: Edit) => edit.type === "guide" || edit.type === "guideOff"+/** Edits waiting for the next step: pushed by the page and the view, taken by the simulation's `Edits` service. */export const editQueue = () => {const queued: Array<Edit> = []diff --git a/src/game/headless.ts b/src/game/headless.tsindex e3cf677..b9f4129 100644--- a/src/game/headless.ts+++ b/src/game/headless.ts@@ -10,8 +10,7 @@ import type * as Replay from "@typeonce/ritmo-devtools/Replay"import { step as simulationStep, type CharterValue } from "./content/index.ts"import { resolveRules, type Rules as RuleInputs } from "./rules/config.ts"import { Edits, Game, Rules, Toast } from "./schema.ts"-import type { Edit } from "./edits.ts"-import { emptyPreview, type UiValue } from "../view/contracts.ts"+import { editQueue, type Edit } from "./edits.ts"import { blankResources, simulate } from "./schedule.ts"/** A saved world, as plain data. */@@ -24,20 +23,15 @@ export interface Snapshot {machines: Record<string, string>}-/** The page's UI state before anything is clicked, with one edit founding the town. */-const blankUi = (charter: CharterValue, toast: (message: string) => void): UiValue => ({- tool: "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(), wanted: new Map(), legend: null, flash: null,- toast-})+/** The edit queue of a town about to be founded: one edit founds it on the first step. */+const founding = (charter: CharterValue) => {+ const edits = editQueue()+ edits.push({ type: "newTown", charter })+ return edits+}const lintCharter: CharterValue = { size: "small", term: 45, land: "fair", seed: 7 }-/** The simulation's input from a page: each step takes the edits queued since the last. */-export const editsOf = (ui: Pick<UiValue, "edits">) => ({ snapshot: (): ReadonlyArray<Edit> => ui.edits.splice(0) })-/** The toasts the last step emitted (an inspector: it reads, and does not hold, the stream). */const Toasts = Game.Inspector("Town/Toasts", { events: { toast: Game.System.readEvent(Toast) } }, ({ events }) => events.toast.all())@@ -59,34 +53,38 @@ export const replayTarget = (playback: Replay.Playback) => {/*** What `ritmo-devtools lint src/game/headless.ts` checks (`pnpm lint:game`,- * part of `pnpm check`): the simulation on a debug runtime, and the page's- * `present` schedule described without running (it needs the renderer).+ * part of `pnpm check`): the simulation on a debug runtime, and the view's+ * `project` and the renderer's `draw` schedules described without running+ * (they need a page).*/export const lintTarget = async () => {- // Loaded here only: tests and bots that use `headless` never load the renderer.- const { present } = await import("../view/present.ts")+ // Loaded here only: tests and bots that use `headless` never load the view or the renderer.+ const { project } = await import("../view/schedule.ts")+ const { draw } = await import("../render/three/schedule.ts")const made = Game.Runtime.make({- services: Game.Runtime.services(Game.Runtime.service(Edits, editsOf(blankUi(lintCharter, () => {}))), Game.Runtime.service(Rules, resolveRules())),+ services: Game.Runtime.services(Game.Runtime.service(Edits, founding(lintCharter)), Game.Runtime.service(Rules, resolveRules())),resources: blankResources(),debug: { hostClock: HostClock.test() }})if (!made.ok) throw new Error(`The town could not start: ${JSON.stringify(made.error)}`)- return { runtime: made.value, schedules: { simulate }, describe: { present } }+ return { runtime: made.value, schedules: { simulate }, describe: { project, draw } }}export const headless = (charter: CharterValue, options: { readonly toast?: (message: string) => void; readonly rules?: RuleInputs; readonly hostClock?: HostClock.HostClock } = {}) => {- const toast = options.toast ?? (() => {})- const ui = blankUi(charter, toast)- const made = Game.Runtime.make({ services: Game.Runtime.services(Game.Runtime.service(Edits, editsOf(ui)), Game.Runtime.service(Rules, options.rules ?? resolveRules())), resources: blankResources(), debug: { hostClock: options.hostClock ?? HostClock.test() } })+ const edits = founding(charter)+ const made = Game.Runtime.make({ services: Game.Runtime.services(Game.Runtime.service(Edits, edits), Game.Runtime.service(Rules, options.rules ?? resolveRules())), resources: blankResources(), debug: { hostClock: options.hostClock ?? HostClock.test() } })if (!made.ok) throw new Error(`The town could not start: ${JSON.stringify(made.error)}`)const runtime = made.valueconst step = () => {const stepped = runtime.tick(simulate)if (!stepped.ok) throw new Error(`A step failed: ${JSON.stringify(stepped.error)}`)- for (const message of runtime.inspect(Toasts)) toast(message)+ for (const message of runtime.inspect(Toasts)) town.toast(message)}const town = {- ui,+ /** The edits waiting for the next step: what `edit` pushes to. */+ edits,+ /** Where the town's messages go ("No room there"): `options.toast`, or set it. */+ toast: options.toast ?? ((_message: string) => {}),/** The runtime itself, for tools (devtools sessions, lints, replays) and type-level checks. */runtime,/** Runs the town on for `seconds` of game time. */@@ -94,8 +92,8 @@ export const headless = (charter: CharterValue, options: { readonly toast?: (mesfor (let i = 0; i < Math.round(seconds / simulationStep.dt); i++) step()},/** Pushes edits, applied on the next step. */- edit: (...edits: ReadonlyArray<Edit>) => {- ui.edits.push(...edits)+ edit: (...queued: ReadonlyArray<Edit>) => {+ edits.push(...queued)},/** The world as plain data (a copy: changing it changes nothing until it is restored). */snapshot: (): Snapshot => JSON.parse(JSON.stringify(runtime.snapshot())),diff --git a/src/game/schedule.ts b/src/game/schedule.tsindex f611bd9..3f8c08b 100644--- a/src/game/schedule.ts+++ b/src/game/schedule.ts@@ -56,6 +56,13 @@ export const simulate = Game.Schedule(Record)+/**+ * The player's edits, applied without a step of time: for edits that may come+ * while the town waits (paused, founding, or a term over) and must not move it+ * on, such as the guide's.+ */+export const settle = Game.Schedule(ApplyEdits, Game.Schedule.applyDeferred())+/** The world's resources before any town is founded (a `newTown` edit fills them in). */export const blankResources = () => ({Time: Clock.start(step),diff --git a/src/game/schema.ts b/src/game/schema.tsindex 791a5af..87da7a8 100644--- a/src/game/schema.ts+++ b/src/game/schema.ts@@ -13,15 +13,11 @@*/import { Clock as SimulationClock, Decode, Descriptor, Schema } from "@typeonce/ritmo"import * as Random from "@typeonce/ritmo-math/Random"-import type { NodeRegistry } from "@typeonce/ritmo-render"import { step } from "./content/index.ts"-import type { BuildingView, FieldView, HouseView, RockView, RuinView, TreeView, WalkerView } from "../render/three/views.ts"-import type { GameScene } from "../render/three/scene.ts"import { goodIds, groundIds, kindIds, landIds, propIds, serviceIds, sizeIds, type Amounts, type GoodId } from "./content/index.ts"import type { Rules as RuleInputs } from "./rules/config.ts"import type { Edit } from "./edits.ts"-import type { UiValue } from "../view/contracts.ts"export const Root = Schema.defineRoot("Town")@@ -420,29 +416,17 @@ export const Handed = Descriptor.TransientResource<HandedValue>()("Town/Handed")export const Rules = Descriptor.Service<RuleInputs>()("Town/Rules")/**- * The page's input to the simulation: each step takes the edits queued since- * the last one (plain data, so a replay can record and play it back).+ * The player's input to the simulation: each step takes the edits queued+ * since the last one (plain data, so a replay can record and play it back).*/export const Edits = Descriptor.Service<{ readonly snapshot: () => ReadonlyArray<Edit> }>()("Town/Edits")-/** The page itself, for the views only: the simulation never reads it (it talks to the page through `Toast` and `Selection`). */-export const Ui = Descriptor.Service<UiValue>()("Town/Ui")-// ── What the simulation tells the page ────────────────────────────────────+// ── What the simulation tells the player ──────────────────────────────────/** A message for the player (an edit refused: "No room there"). */export const Toast = Descriptor.Event<string>()("Town/Toast")/** The panel's selection, changed by an edit: open a new building, or let go of one that is gone. */export const Selection = Descriptor.Event<{ readonly select: number } | { readonly clear: true } | { readonly clearIf: number }>()("Town/Selection")-/** The frame's length, for animation only: the simulation runs on `Time`. */-export const Clock = Descriptor.Service<{ deltaSeconds: number; elapsed: number }>()("Town/Clock")-export const StageService = Descriptor.Service<GameScene>()("Town/Stage")-export const BuildingNodes = Descriptor.Service<NodeRegistry.NodeRegistry<BuildingView>>()("Town/BuildingNodes")-export const HouseNodes = Descriptor.Service<NodeRegistry.NodeRegistry<HouseView>>()("Town/HouseNodes")-export const WalkerNodes = Descriptor.Service<NodeRegistry.NodeRegistry<WalkerView>>()("Town/WalkerNodes")-export const TreeNodes = Descriptor.Service<NodeRegistry.NodeRegistry<TreeView>>()("Town/TreeNodes")-export const RockNodes = Descriptor.Service<NodeRegistry.NodeRegistry<RockView>>()("Town/RockNodes")-export const FieldNodes = Descriptor.Service<NodeRegistry.NodeRegistry<FieldView>>()("Town/FieldNodes")-export const RuinNodes = Descriptor.Service<NodeRegistry.NodeRegistry<RuinView>>()("Town/RuinNodes")export const Game = Schema.bind(Schema.fragment({diff --git a/src/render/three/draw/animate.ts b/src/render/three/draw/animate.tsnew file mode 100644index 0000000..ef02f1c--- /dev/null+++ b/src/render/three/draw/animate.ts@@ -0,0 +1,214 @@+/**+ * Every view follows its entity once a frame: a building's stage of+ * building, work, wear, risks and the map view's tint; a home's tier and+ * troubles; walkers along their routes with what they carry; trees and+ * fields growing; rocks worked down; fish where the water would give a catch.+ */+import { CONDITION_MAX, condition as wear, goodIds, home, kinds, RESTOCK_TICKS, risk, RISK_MAX, total } from "../../../game/content/index.ts"+import { CELL_STEPS } from "../../../game/schedule.ts"+import { Appeal, Errand, Field, Game, Grid, Rescue, Roam, Rock, Route, Tile, Time, Tree, Water, type GridValue } from "../../../game/schema.ts"+import { appealAt } from "../../../game/world/appeal.ts"+import { entrances, isRoad, type TileLike } from "../../../game/world/grid.ts"+import { U, type Point } from "../../../game/world/iso.ts"+import { buildOf, problemOf, siteShare, worksShare } from "../../../view/facts.ts"+import { BuildingRead, HouseRead, RuinRead } from "../../../view/frame.ts"+import { Clock, Shown } from "../../../view/services.ts"+import type { Alert, Emphasis, Load } from "../../art.ts"+import type { DoorSet } from "../models.ts"+import { rockBlocks, type RockPart } from "../rock-blocks.ts"+import { BuildingNodes, FieldNodes, HouseNodes, RockNodes, RuinNodes, StageService, TreeNodes, WalkerNodes } from "../services.ts"+import { hazardStrength } from "../surface-state.ts"++/** Doors follow road entrances on all four sides as the camera turns. */+const doorsOf = (grid: GridValue, tile: TileLike): DoorSet => {+ const open = entrances(tile).filter((c) => isRoad(grid, c.x, c.y))+ return {+ right: open.some((c) => c.side === 0),+ left: open.some((c) => c.side === 1),+ backRight: open.some((c) => c.side === 2),+ backLeft: open.some((c) => c.side === 3)+ }+}++/** The sign over a home or building: what is wrong now, or the risk nearest the top past `risk.warn`. */+const alertOf = (r: { readonly fire: number; readonly health: number; readonly order: number } | undefined, sick: boolean, worn: boolean): Alert | null => {+ if (sick) return "sick"+ if (r) {+ const worst = (["fire", "health", "order"] as const).reduce((a, b) => (r[b] > r[a] ? b : a))+ if (r[worst] >= risk.warn) return worst+ }+ return worn ? "worn" : null+}++/**+ * Where a walker stands, in cells: on the lattice, a little to one side of+ * the road's middle; which way it faces; and which foot is forward.+ */+const walkerAt = (route: { readonly cells: ReadonlyArray<Point>; readonly index: number; readonly step: number }) => {+ const here = route.cells[route.index]!+ const next = route.cells[route.index + 1]+ const before = route.cells[route.index - 1]+ const dir = next ? { x: next.x - here.x, y: next.y - here.y } : before ? { x: here.x - before.x, y: here.y - before.y } : { x: 0, y: 0 }+ const units = next ? Math.floor(route.step / (CELL_STEPS / 16)) : 0+ const along = units * U+ const side = 2 * U+ return {+ x: here.x + 0.5 + dir.x * along - dir.y * side,+ y: here.y + 0.5 + dir.y * along + dir.x * side,+ dir,+ phase: next ? Math.floor(units / 3) % 2 : 0+ }+}++/** Neighbouring rocks drawn as one outcrop, formed again only when a rock runs out (or the land changes). */+const rockShapes: { key: string; parts: Map<number, RockPart> } = { key: "", parts: new Map() }++export const Animate = Game.System(+ "Town/Animate",+ {+ queries: {+ buildings: BuildingRead,+ houses: HouseRead,+ ruins: RuinRead,+ walkers: Game.Query({+ selection: {+ route: Game.Query.read(Route),+ errand: Game.Query.optional(Errand),+ roam: Game.Query.optional(Roam),+ rescue: Game.Query.optional(Rescue)+ }+ }),+ trees: Game.Query({ selection: { tree: Game.Query.read(Tree) } }),+ rocks: Game.Query({ selection: { rock: Game.Query.read(Rock), tile: Game.Query.read(Tile) } }),+ 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), time: Game.System.readResource(Time) },+ services: {+ stage: Game.System.service(StageService),+ shown: Game.System.service(Shown),+ clock: Game.System.service(Clock),+ ruinNodes: Game.System.service(RuinNodes),+ buildingNodes: Game.System.service(BuildingNodes),+ houseNodes: Game.System.service(HouseNodes),+ walkerNodes: Game.System.service(WalkerNodes),+ treeNodes: Game.System.service(TreeNodes),+ rockNodes: Game.System.service(RockNodes),+ fieldNodes: Game.System.service(FieldNodes)+ }+ },+ ({ queries, resources, services }) => {+ const grid = resources.grid.get()+ const cells = resources.appeal.get().cells+ const { hover, danger } = services.shown.scene.preview+ const emphasis = (id: number): Emphasis => (danger && hover === id ? "danger" : "normal")+ const dt = services.clock.deltaSeconds+ // Fish where the water would give a catch now; none where it rests after one.+ const tick = resources.time.get().step+ services.stage.setFish(queries.water.each().filter(({ data }) => tick - data.water.get().fished >= RESTOCK_TICKS).map(({ data }) => data.tile.get()))++ for (const { entity, data } of queries.buildings.each()) {+ const kind = kinds[data.building.get().kind]+ const status = data.status.get()+ // An upgrade the town needs now, and can make (see `upgradesWanted`).+ const upgradable = services.shown.scene.wanted.has(entity.id)+ const recipe = data.recipe.value()+ const walkers = data.walkers.value()?.length ?? 0+ const worn = (data.condition.value()?.value ?? CONDITION_MAX) < wear.worn+ const r = data.risk.value()+ services.buildingNodes.get(entity.id)?.update(+ {+ alert: alertOf(r ? { fire: r.fire, health: 0, order: 0 } : undefined, false, worn),+ burning: data.burning.present,+ worn,+ effects: {+ wear: 1-(data.condition.value()?.value??CONDITION_MAX)/CONDITION_MAX,+ fireRisk: hazardStrength(r?.fire??0,risk.warn,RISK_MAX)+ },+ working: status === "working",+ tint: services.shown.scene.tints.get(entity.id),+ problem: problemOf(kind, status) !== null,+ build: buildOf(data.site.value(), data.rising.value()),+ beat: recipe ? recipe.made : data.service.value() ? walkers : 0,+ doors: doorsOf(grid, data.tile.get()),+ site: siteShare(data.site.value()),+ level: data.upgraded.value()?.level ?? 0,+ works: worksShare(data.works.value()),+ upgradable+ },+ dt,+ emphasis(entity.id)+ )+ }+ for (const { entity, data } of queries.houses.each()) {+ const tile = data.tile.get()+ const worn = (data.condition.value()?.value ?? CONDITION_MAX) < wear.worn+ const desirability = appealAt(cells, tile.x, tile.y)+ services.houseNodes+ .get(entity.id)+ ?.update(+ {+ tier: data.house.get().tier,+ build: buildOf(data.site.value(), data.rising.value()),+ doors: doorsOf(grid, tile),+ site: siteShare(data.site.value()),+ alert: data.site.present ? null : alertOf(data.risk.value(), data.sick.present, worn),+ burning: data.burning.present,+ worn,+ effects: {+ wear: Math.max(desirability<0?0.55:0,1-(data.condition.value()?.value??CONDITION_MAX)/CONDITION_MAX),+ fireRisk: hazardStrength(data.risk.value()?.fire??0,risk.warn,RISK_MAX),+ health: hazardStrength(data.risk.value()?.health??0,risk.warn,RISK_MAX),+ order: hazardStrength(data.risk.value()?.order??0,risk.warn,RISK_MAX),+ sick: Number(data.sick.present)+ },+ band: desirability < 0 ? "poor" : desirability >= home.tiers[2].appeal ? "fine" : "plain",+ closed: data.closed.present,+ tint: services.shown.scene.tints.get(entity.id)+ },+ emphasis(entity.id)+ )+ }+ for (const { entity } of queries.ruins.each()) services.ruinNodes.get(entity.id)?.update(emphasis(entity.id))+ for (const { entity, data } of queries.walkers.each()) {+ const p = walkerAt(data.route.get())+ const errand = data.errand.value()+ const roam = data.roam.value()+ const load: Load = errand+ ? { kind: "cart", good: errand.good, count: !errand.back || errand.count > 0 ? errand.count : 0 }+ : data.rescue.value()+ ? { kind: "service", role: "firefighter" }+ : roam?.service === "fire"+ ? { kind: "service", role: "watchman" }+ : roam?.service === "health"+ ? { kind: "service", role: "physician" }+ : roam?.service === "order"+ ? { kind: "service", role: "constable" }+ : roam?.service === "repair"+ ? { kind: "service", role: "builder" }+ : roam?.service === "faith"+ ? { kind: "bell" }+ : roam && total(roam.basket) > 0+ ? { kind: "basket", goods: goodIds.filter((g) => roam.basket[g] > 0) }+ : { kind: "none" }+ services.walkerNodes.get(entity.id)?.update(p.x, p.y, p.dir, p.phase, load)+ }+ for (const { entity, data } of queries.trees.each())+ services.treeNodes.get(entity.id)?.update(data.tree.get().growth, emphasis(entity.id))+ // Neighbouring rocks are drawn as one big outcrop; the blocks are formed again only when a rock runs out (or the land changes).+ const rocks = queries.rocks.each()+ const rockKey = `${rocks.length}:${rocks.reduce((n, { entity }) => n + entity.id, 0)}`+ if (rockKey !== rockShapes.key) {+ rockShapes.key = rockKey+ rockShapes.parts = rockBlocks(rocks.map(({ entity, data }) => ({ id: entity.id, ...data.tile.get(), ore: data.rock.get().ore })))+ }+ const amounts = new Map<number, number>(rocks.map(({ entity, data }) => [entity.id, data.rock.get().amount]))+ for (const { entity, data } of rocks) {+ const r = data.rock.get()+ const part = rockShapes.parts.get(entity.id)+ if (!part || !part.draws) services.rockNodes.get(entity.id)?.update(r.ore, r.amount, part ? 0 : 1, part ? 0 : 1)+ else services.rockNodes.get(entity.id)?.update(r.ore, part.members.reduce((n, id) => n + (amounts.get(id) ?? 0), 0) / part.members.length, part.w, part.h)+ }+ for (const { entity, data } of queries.fields.each()) services.fieldNodes.get(entity.id)?.update(data.field.get().growth)+ }+)diff --git a/src/render/three/draw/ground.ts b/src/render/three/draw/ground.tsnew file mode 100644index 0000000..6dcfe08--- /dev/null+++ b/src/render/three/draw/ground.ts@@ -0,0 +1,30 @@+import { Game, Park, Paved, Road, Tile, Water } from "../../../game/schema.ts"+import { key, type TileLike } from "../../../game/world/grid.ts"+import { ParkRead } from "../../../view/frame.ts"+import { StageService } from "../services.ts"++/** Roads, water, and parks, each redrawn as one layer whenever one is laid or anything is removed. */+export const DrawGround = Game.System(+ "Town/DrawGround",+ {+ queries: {+ roads: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road] }),+ paved: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road, Paved] }),+ water: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Water] }),+ parks: ParkRead,+ /** A tile laid, a road paved, or a park relaid. */+ laid: Game.Query({ selection: {}, filters: [Game.Query.anyOf(Game.Query.added(Tile), Game.Query.added(Paved), Game.Query.changed(Park))] })+ },+ despawned: { entities: Game.System.readDespawned() },+ services: { stage: Game.System.service(StageService) }+ },+ ({ queries, despawned, services }) => {+ const dirty = services.stage.groundDirty+ if (!dirty && queries.laid.each().length === 0 && despawned.entities.all().length === 0) return+ const cellsOf = (rows: ReadonlyArray<{ readonly data: { readonly tile: { get(): TileLike } } }>) =>+ new Set(rows.map(({ data }) => key(data.tile.get().x, data.tile.get().y)))+ const roads = cellsOf(queries.roads.each())+ services.stage.setGround(roads, cellsOf(queries.water.each()), cellsOf(queries.paved.each()))+ services.stage.setParks(new Map(queries.parks.each().map(({ data }) => [key(data.tile.get().x, data.tile.get().y), { ...data.tile.get(), ...data.park.get() }])), roads)+ }+)diff --git a/src/render/three/draw/land.ts b/src/render/three/draw/land.tsnew file mode 100644index 0000000..0d96c4c--- /dev/null+++ b/src/render/three/draw/land.ts@@ -0,0 +1,18 @@+import { seasonAt, elapsed, termTicks } from "../../../game/schedule.ts"+import { Charter, Fate, Game, Land, Time } from "../../../game/schema.ts"+import { StageService } from "../services.ts"++/** The land, redrawn when a new town is founded (or one loaded), and frosted through winter. */+export const DrawLand = Game.System(+ "Town/DrawLand",+ {+ resources: { land: Game.System.readResource(Land), time: Game.System.readResource(Time), charter: Game.System.readResource(Charter), fate: Game.System.readResource(Fate) },+ services: { stage: Game.System.service(StageService) }+ },+ ({ resources, services }) => {+ const mask = resources.land.get().mask+ const charter = resources.charter.get()+ const t = elapsed(resources.time.get(), charter)+ services.stage.setLand(mask, t > 0 && seasonAt(Math.min(t, resources.fate.get().began + termTicks(charter) - 1), charter).winter)+ }+)diff --git a/src/render/three/draw/overlay.ts b/src/render/three/draw/overlay.tsnew file mode 100644index 0000000..42c7fe0--- /dev/null+++ b/src/render/three/draw/overlay.ts@@ -0,0 +1,12 @@+import { Game } from "../../../game/schema.ts"+import { Shown } from "../../../view/services.ts"+import { StageService } from "../services.ts"++/** The map view, washed over the town. */+export const DrawOverlay = Game.System(+ "Town/DrawOverlay",+ { services: { shown: Game.System.service(Shown), stage: Game.System.service(StageService) } },+ ({ services }) => {+ services.stage.setOverlay(services.shown.scene.overlay.key, services.shown.scene.overlay.cells)+ }+)diff --git a/src/render/three/draw/preview.ts b/src/render/three/draw/preview.tsnew file mode 100644index 0000000..e7cfaf5--- /dev/null+++ b/src/render/three/draw/preview.ts@@ -0,0 +1,12 @@+import { Game } from "../../../game/schema.ts"+import { Clock, Shown } from "../../../view/services.ts"+import { StageService } from "../services.ts"++/** Ghosts, the road being dragged, and outlines, redrawn every frame. */+export const DrawPreview = Game.System(+ "Town/DrawPreview",+ { services: { shown: Game.System.service(Shown), stage: Game.System.service(StageService), clock: Game.System.service(Clock) } },+ ({ services }) => {+ services.stage.setPreview(services.shown.scene.preview, services.clock.elapsed)+ }+)diff --git a/src/render/three/draw/stroll.ts b/src/render/three/draw/stroll.tsnew file mode 100644index 0000000..f5e61e6--- /dev/null+++ b/src/render/three/draw/stroll.ts@@ -0,0 +1,33 @@+import { Game, Grid, Land } from "../../../game/schema.ts"+import { HouseRead } from "../../../view/frame.ts"+import { Clock, Shown } from "../../../view/services.ts"+import { StageService } from "../services.ts"+import { Townsfolk } from "../townsfolk.ts"++/** Residents out walking (see `townsfolk.ts`), on the town's time: still while it waits. */+let townsfolk: { readonly folk: Townsfolk; land: string; generation: number; stage: unknown } | null = null+export const Stroll = Game.System(+ "Town/Stroll",+ {+ queries: { houses: HouseRead },+ resources: { grid: Game.System.readResource(Grid), land: Game.System.readResource(Land) },+ services: { shown: Game.System.service(Shown), clock: Game.System.service(Clock), stage: Game.System.service(StageService) }+ },+ ({ queries, resources, services }) => {+ if (townsfolk?.stage !== services.stage) {+ townsfolk?.folk.clear()+ townsfolk = { folk: new Townsfolk(services.stage), land: "", generation: -1, stage: services.stage }+ }+ const mask = resources.land.get().mask+ if (mask !== townsfolk.land || townsfolk.generation !== services.stage.generation) {+ townsfolk.generation = services.stage.generation+ townsfolk.land = mask+ townsfolk.folk.clear()+ }+ const homes = queries.houses+ .each()+ .filter(({ data }) => !data.site.value() && !data.rising.value())+ .map(({ data }) => ({ ...data.tile.get(), tier: data.house.get().tier, residents: data.house.get().residents }))+ townsfolk.folk.step(services.clock.deltaSeconds * services.shown.scene.pace, homes, resources.grid.get())+ }+)diff --git a/src/render/three/input.ts b/src/render/three/input.tsindex 7ad695d..0be6207 100644--- a/src/render/three/input.ts+++ b/src/render/three/input.ts@@ -1,5 +1,5 @@import type { Point } from "../../game/world/iso.ts"-import type { UiValue } from "../../view/contracts.ts"+import type { Interaction, Shown } from "../../view/contracts.ts"import type { GameScene } from "./scene.ts"/** Camera gestures and game gestures share the canvas, but a pan, orbit or@@ -16,9 +16,19 @@ import type { GameScene } from "./scene.ts"* button) lays it; a tap anywhere else drops it, and dragging again starts a* new one. With any pointer, letting go off the map (over the tool bar, say)* drops the stroke, as a button drops a click released outside it. */+/** What the map input needs from the page around it. */+export interface MapHost {+ /** Says something to the player. */+ readonly toast: (message: string) => void+ /** A dialog is open over the map: the keyboard is not the map's. */+ readonly blocked: () => boolean+}+export class MapInput {private scene: GameScene- private ui: UiValue+ private ui: Interaction+ private shown: Shown+ private host: MapHostprivate pointers = new Map<number, Point>()/** `deferred`: a press while a stroke is held, which is a tap on it until it moves. */private press: { id: number; start: Point; last: Point; mode: "edit" | "pan" | "rotate"; moved: boolean; deferred: boolean } | null = null@@ -33,9 +43,11 @@ export class MapInput {private touch = falsereadonly controls: HTMLElementprivate abort = new AbortController()- constructor(scene: GameScene, ui: UiValue) {+ constructor(scene: GameScene, ui: Interaction, shown: Shown, host: MapHost) {this.scene = scenethis.ui = ui+ this.shown = shown+ this.host = hostconst canvas = scene.canvas,signal = this.abort.signalcanvas.style.touchAction = "none"@@ -209,7 +221,7 @@ export class MapInput {window.addEventListener("keydown",(e) => {- if (ui.founding || document.querySelector(".dialog.open")) return+ if (ui.founding || host.blocked()) returnif (e.target instanceof HTMLElement && e.target.closest("input,select,textarea,button,a,[contenteditable=true]")) returnconst moves: Record<string, [number, number]> = { arrowleft: [40, 0], arrowright: [-40, 0], arrowup: [0, 40], arrowdown: [0, -40] }const key = e.key.toLowerCase()@@ -248,7 +260,7 @@ export class MapInput {const same = armed && armed.tool === tool && (tool === "bulldoze" && hit !== null ? armed.hit === hit : Math.hypot(armed.at.x - at.x, armed.at.y - at.y) < 1.5)if (same) return falsethis.armed = { tool, at, hit }- this.ui.toast(tool === "bulldoze" ? "tap it again to remove it" : "tap it again to build it here")+ this.host.toast(tool === "bulldoze" ? "tap it again to remove it" : "tap it again to build it here")this.updatePointer()return true}@@ -320,7 +332,7 @@ export class MapInput {: "grabbing": this.mode === "rotate"? "ew-resize"- : this.ui.preview.hover !== null || this.ui.tool !== "select"+ : this.shown.scene.preview.hover !== null || this.ui.tool !== "select"? "pointer": "grab"}diff --git a/src/render/three/models.ts b/src/render/three/models.tsindex 832e81b..9f98295 100644--- a/src/render/three/models.ts+++ b/src/render/three/models.ts@@ -6,7 +6,7 @@ import { hash } from "./assets/land.ts"import { kinds, home, type GroundId, type KindId, type PropId, type Tier } from "../../game/content/index.ts"import { GRID, U, type Point } from "../../game/world/iso.ts"import { key, cellOf, DIRS } from "../../game/world/grid.ts"-import type { Preview } from "../../view/contracts.ts"+import type { OverlayCell, Preview } from "../../view/contracts.ts"import { withAppearance, type Appearance } from "./assets/appearance.ts"import { parkAsset, setts } from "./assets/town-props.ts"import { isWorkshop, workshopConstruction } from "./assets/workshops.ts"@@ -368,15 +368,6 @@ export function previewAsset(preview: Preview, time: number) {export const quantizeBuild = (build: number) => Math.min(1, Math.round(build * 32) / 32)/** A footprint washed in a colour, for a map view. */-export interface OverlayCell {- readonly x: number- readonly y: number- readonly size: number- readonly color: number- readonly alpha: number- /** Outlined, for what the view is about (a workplace and its homes). */- readonly ring?: boolean-}export function overlayAsset(cells: ReadonlyArray<OverlayCell>) {const d = new Drawing("overlay", "Map view", "")for (const c of cells) {diff --git a/src/render/three/scene.ts b/src/render/three/scene.tsindex 6b8b770..919d7e2 100644--- a/src/render/three/scene.ts+++ b/src/render/three/scene.ts@@ -7,9 +7,9 @@ import type { InkAsset } from "./assets/primitives.ts"import { GRID, type Point } from "../../game/world/iso.ts"import { key } from "../../game/world/grid.ts"import { kinds } from "../../game/content/index.ts"-import type { Preview, UiValue } from "../../view/contracts.ts"+import type { OverlayCell, Preview, Tool } from "../../view/contracts.ts"import { ModelHandle, ModelPool } from "./pool.ts"-import { groundAsset, landAsset, overlayAsset, previewAsset, type OverlayCell } from "./models.ts"+import { groundAsset, landAsset, overlayAsset, previewAsset } from "./models.ts"import { parkAsset } from "./assets/town-props.ts"import { FishWater } from "./fish-effects.ts"import type { ParkCell } from "../../game/world/appeal.ts"@@ -122,7 +122,7 @@ export class GameScene {const point = this.raycaster.ray.intersectPlane(this.plane, new THREE.Vector3()) ?? this.targetreturn { x: point.x / floorScale, y: point.z / floorScale }}- inputAt(sx: number, sy: number, tool: UiValue["tool"]) {+ inputAt(sx: number, sy: number, tool: Tool) {let at = this.groundAt(sx, sy)let hit: number | null = nullconst intersects = this.raycaster.intersectObjects(this.pool.pickables(), false)diff --git a/src/render/three/schedule.ts b/src/render/three/schedule.tsnew file mode 100644index 0000000..576fc54--- /dev/null+++ b/src/render/three/schedule.ts@@ -0,0 +1,29 @@+/**+ * The renderer's schedule, run once a frame after the view's: the land, the+ * entities' views, the ground layers, the map view, animation, the+ * townsfolk, and the preview, in that order.+ */+import { Game } from "../../game/schema.ts"+import { Animate } from "./draw/animate.ts"+import { DrawGround } from "./draw/ground.ts"+import { DrawLand } from "./draw/land.ts"+import { DrawOverlay } from "./draw/overlay.ts"+import { DrawPreview } from "./draw/preview.ts"+import { Stroll } from "./draw/stroll.ts"+import { RenderBuildings, RenderFields, RenderHouses, RenderRocks, RenderRuins, RenderTrees, RenderWalkers } from "./sync.ts"++export const draw = Game.Schedule(+ DrawLand,+ RenderBuildings,+ RenderHouses,+ RenderWalkers,+ RenderTrees,+ RenderRocks,+ RenderFields,+ RenderRuins,+ DrawGround,+ DrawOverlay,+ Animate,+ Stroll,+ DrawPreview+)diff --git a/src/render/three/services.ts b/src/render/three/services.tsnew file mode 100644index 0000000..625836b--- /dev/null+++ b/src/render/three/services.ts@@ -0,0 +1,18 @@+/**+ * The Three.js renderer's host services: its scene, and a registry of views+ * for each kind of entity it mirrors (see `sync.ts`).+ */+import { Descriptor } from "@typeonce/ritmo"+import type { NodeRegistry } from "@typeonce/ritmo-render"++import type { GameScene } from "./scene.ts"+import type { BuildingView, FieldView, HouseView, RockView, RuinView, TreeView, WalkerView } from "./views.ts"++export const StageService = Descriptor.Service<GameScene>()("Town/Stage")+export const BuildingNodes = Descriptor.Service<NodeRegistry.NodeRegistry<BuildingView>>()("Town/BuildingNodes")+export const HouseNodes = Descriptor.Service<NodeRegistry.NodeRegistry<HouseView>>()("Town/HouseNodes")+export const WalkerNodes = Descriptor.Service<NodeRegistry.NodeRegistry<WalkerView>>()("Town/WalkerNodes")+export const TreeNodes = Descriptor.Service<NodeRegistry.NodeRegistry<TreeView>>()("Town/TreeNodes")+export const RockNodes = Descriptor.Service<NodeRegistry.NodeRegistry<RockView>>()("Town/RockNodes")+export const FieldNodes = Descriptor.Service<NodeRegistry.NodeRegistry<FieldView>>()("Town/FieldNodes")+export const RuinNodes = Descriptor.Service<NodeRegistry.NodeRegistry<RuinView>>()("Town/RuinNodes")diff --git a/src/render/three/sync.ts b/src/render/three/sync.tsnew file mode 100644index 0000000..fc5c30f--- /dev/null+++ b/src/render/three/sync.ts@@ -0,0 +1,79 @@+/**+ * The world's entities mirrored into the Three.js scene: a view for each+ * building, home, walker, tree, rock, ruin, and field, made when it appears,+ * placed on its tile, and removed when it goes (see `@typeonce/ritmo-render`).+ */+import { RenderSync } from "@typeonce/ritmo-render"++import { Building, Field, Figure, Game, House, Rock, Ruin, Tile, Tree } from "../../game/schema.ts"+import { BuildingNodes, FieldNodes, HouseNodes, RockNodes, RuinNodes, StageService, TreeNodes, WalkerNodes } from "./services.ts"+import { BuildingView, FieldView, HouseView, RockView, RuinView, TreeView, WalkerView } from "./views.ts"++export const RenderBuildings = RenderSync.system(Game, {+ name: "Town/RenderBuildings",+ renderable: Building,+ transform: Tile,+ registry: BuildingNodes,+ services: { stage: StageService },+ create: ({ renderable, services, entity }) => new BuildingView(renderable.kind, services.stage, entity),+ apply: (node, { transform }) => node.place(transform.x, transform.y)+})++export const RenderHouses = RenderSync.system(Game, {+ name: "Town/RenderHouses",+ renderable: House,+ transform: Tile,+ registry: HouseNodes,+ services: { stage: StageService },+ create: ({ services, entity }) => new HouseView(services.stage, entity),+ apply: (node, { transform }) => node.place(transform.x, transform.y)+})++export const RenderWalkers = RenderSync.system(Game, {+ name: "Town/RenderWalkers",+ renderable: Figure,+ registry: WalkerNodes,+ services: { stage: StageService },+ create: ({ renderable, services, entity }) => WalkerView.forFigure(renderable.role, renderable.color, services.stage, entity),+ apply: () => {}+})++export const RenderTrees = RenderSync.system(Game, {+ name: "Town/RenderTrees",+ renderable: Tree,+ transform: Tile,+ registry: TreeNodes,+ services: { stage: StageService },+ create: ({ services, entity }) => new TreeView(services.stage, entity),+ apply: (node, { transform }) => node.place(transform.x, transform.y)+})++export const RenderRocks = RenderSync.system(Game, {+ name: "Town/RenderRocks",+ renderable: Rock,+ transform: Tile,+ registry: RockNodes,+ services: { stage: StageService },+ create: ({ services, entity }) => new RockView(services.stage, entity),+ apply: (node, { transform }) => node.place(transform.x, transform.y)+})++export const RenderRuins = RenderSync.system(Game, {+ name: "Town/RenderRuins",+ renderable: Ruin,+ transform: Tile,+ registry: RuinNodes,+ services: { stage: StageService },+ create: ({ renderable, services, entity }) => new RuinView(renderable.cause, services.stage, entity),+ apply: (node, { transform }) => node.place(transform.x, transform.y, transform.size)+})++export const RenderFields = RenderSync.system(Game, {+ name: "Town/RenderFields",+ renderable: Field,+ transform: Tile,+ registry: FieldNodes,+ services: { stage: StageService },+ create: ({ services, entity }) => new FieldView(services.stage, entity),+ apply: (node, { transform }) => node.place(transform.x, transform.y)+})diff --git a/src/ui/dom/host.ts b/src/ui/dom/host.tsindex 8487871..984bdb7 100644--- a/src/ui/dom/host.ts+++ b/src/ui/dom/host.ts@@ -3,8 +3,6 @@* top bar, toolbar, build menu, panel, tooltip, and toasts; the dialog a new* town is founded from, and the reckoning at the end of its term.*/-import { Application, Graphics } from "pixi.js"-import {categoryColor,categoryOrder,@@ -52,9 +50,8 @@ import { GRID } from "../../game/world/iso.ts"import { goodIcon, icon, iconEl, type IconName } from "./kit/icons.ts"import { generate } from "../../game/world/mapgen.ts"import { askOf, priceOf } from "../../game/schedule.ts"-import type { TradeMode } from "../../game/edits.ts"-import type { Group, Line, Panel, Stats, Tool, UiValue, View } from "../../view/contracts.ts"-import { emptyPreview } from "../../view/contracts.ts"+import type { Edit, TradeMode } from "../../game/edits.ts"+import type { Group, Interaction, Line, Panel, Shown, Stats, Tool, View } from "../../view/contracts.ts"import { GameScene, type CameraView } from "../../render/three/scene.ts"import { blobOf, cardFacts, drawCard, metaOf, scaled, verdictOf } from "../../platform/share/card.ts"import { handheld, offerLink, offerPicture, upload } from "../../platform/share/client.ts"@@ -184,16 +181,16 @@ export interface Persistence {* `shared`: the page opened on a shared town's link, so it loads that rather than asking for a charter.* `saved`: the newest town saved in this browser, which the first charter offers to carry on with.*/-export const createHost = async (+export const createHost = (mount: HTMLElement,persistence: () => Persistence,+ view: { readonly interaction: Interaction; readonly shown: Shown; readonly send: (edit: Edit) => void },options: { readonly shared?: boolean; readonly saved?: { readonly title: string; readonly savedAt: number } | null } = {}) => {- const app = new Application()- // Pixi remains an offscreen thumbnail renderer for the unchanged menus.- await app.init({ width: 64, height: 64, antialias: true, resolution: 2, autoStart: false, backgroundAlpha: 0 })- app.stop()const stage = new GameScene(mount)+ const ui = view.interaction+ const townView = view.shown.town+ const queueEdit = view.send// ── DOM ──// Top left: the term's clock and the treasury, the goods in stock below, then the crown's request and any alarm.@@ -251,7 +248,7 @@ export const createHost = async (const send = el("button", "send", "send")send.onclick = (event) => {event.stopPropagation()- ui.edits.push({ type: "deliver" })+ queueEdit({ type: "deliver" })}request.append(requestText, send)const alarm = el("div", "card alarm")@@ -294,7 +291,7 @@ export const createHost = async (let shortCursor = 0jobs.onclick = (event) => {event.stopPropagation()- const short = ui.stats?.shortStaffed ?? []+ const short = townView.stats?.shortStaffed ?? []if (short.length === 0) return toggleMenu("town")const next = short[shortCursor % short.length]!shortCursor += 1@@ -392,43 +389,18 @@ export const createHost = async (let toastTimer = 0/** When the toast showing went up: a press on the map just after does not put it away. */let toastAt = 0- const ui: UiValue = {- tool: "select",- placing: null,- upgrading: null,- ground: "lawn",- prop: "lamp",- menu: null,- pointer: null,- dragFrom: null,- selected: null,- gestures: [],- guide: [],- // A town is founded behind the dialog, so there is land to look at while choosing.- edits: [{ type: "newTown", charter: defaultCharter((Date.now() & 0x7fffffff) >>> 0) }],- preview: emptyPreview(),- hits: [],- panel: null,- centres: new Map(),- stats: null,- speed: 1,- founding: true,- 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- // touches the map again: by then they have read it, or are acting on it.- toast: (message) => {- toastBox.innerHTML = iconize(escapeHtml(message))- toastBox.classList.add("show")- toastAt = Date.now()- window.clearTimeout(toastTimer)- toastTimer = window.setTimeout(() => toastBox.classList.remove("show"), Math.min(8000, Math.max(2200, 1200 + message.length * 65)))- }+ // Long enough to read (about 15 letters a second, and a moment to look), and gone as soon as the mayor+ // touches the map again: by then they have read it, or are acting on it.+ const toast = (message: string) => {+ toastBox.innerHTML = iconize(escapeHtml(message))+ toastBox.classList.add("show")+ toastAt = Date.now()+ window.clearTimeout(toastTimer)+ toastTimer = window.setTimeout(() => toastBox.classList.remove("show"), Math.min(8000, Math.max(2200, 1200 + message.length * 65)))}+ // A town is founded behind the dialog, so there is land to look at while choosing.+ ui.founding = true+ queueEdit({ type: "newTown", charter: defaultCharter((Date.now() & 0x7fffffff) >>> 0) })const tools: ReadonlyArray<{readonly tool: Tool | "build"@@ -553,14 +525,14 @@ export const createHost = async (const guideButton = el("button", "guide-toggle")guideButton.title = "Turn the guide on or off: it tells a new mayor what to do next, and why"guideButton.append(iconEl("hint"), document.createTextNode("guide"))- guideButton.onclick = () => ui.guide.push({ type: ui.stats?.guide.off ? "on" : "off" })+ guideButton.onclick = () => ui.guide.push({ type: townView.stats?.guide.off ? "on" : "off" })system.append(guideButton)action("save", "save", "Save the town in this browser (it also autosaves every two minutes)", () =>- ui.toast(persistence().save() ?? "Saved")+ toast(persistence().save() ?? "Saved"))action("load", "load", "Load the latest save: yours or the autosave, whichever is newer", () =>confirmLeave("load the latest save?", "The town as it is now is replaced by the latest save (yours or the autosave).", "Load", () =>- ui.toast(persistence().load() ?? "Loaded")+ toast(persistence().load() ?? "Loaded")))action("newTown", "new town", "Found a new town on new land", () =>@@ -595,7 +567,7 @@ export const createHost = async (const saveFirst = el("button", "frame", `Save, then ${go.toLowerCase()}`)saveFirst.onclick = () => {const failed = persistence().save()- if (failed) return ui.toast(failed)+ if (failed) return toast(failed)close(true)run()}@@ -637,21 +609,21 @@ export const createHost = async (ui.menu = nullchoose("place")const title = kinds[kind].title.toLowerCase()- ui.toast(touchScreen() ? `Tap a spot for the ${title}, then tap it again to build it` : `Click to place a ${title} · Esc to stop`)+ toast(touchScreen() ? `Tap a spot for the ${title}, then tap it again to build it` : `Click to place a ${title} · Esc to stop`)}const layGround = (ground: GroundId) => {ui.ground = groundui.menu = nullchoose("ground")const title = grounds[ground].title.toLowerCase()- ui.toast(touchScreen() ? `Drag a rectangle to lay ${title}, then tap Build` : `Drag a rectangle to lay ${title} · Esc to stop`)+ toast(touchScreen() ? `Drag a rectangle to lay ${title}, then tap Build` : `Drag a rectangle to lay ${title} · Esc to stop`)}const furnish = (prop: PropId) => {ui.prop = propui.menu = nullchoose("prop")const title = props[prop].title.toLowerCase()- ui.toast(touchScreen() ? `Tap a cell of park for the ${title}, then tap it again to set it` : `Click a cell of park to set a ${title} · Esc to stop`)+ toast(touchScreen() ? `Tap a cell of park for the ${title}, then tap it again to set it` : `Click a cell of park to set a ${title} · Esc to stop`)}choose("select")@@ -699,7 +671,7 @@ export const createHost = async (const SAMPLE_SECONDS = 4const HISTORY = 150window.setInterval(() => {- const s = ui.stats+ const s = townView.statsif (!s) returnhistory.push({ coins: s.coins, residents: s.settlers + s.citizens, stock: s.stock })if (history.length > HISTORY) history.shift()@@ -827,7 +799,7 @@ export const createHost = async (}const lockText = (kind: Pick<Kind, "unlock"> | ParkPiece): string | null => {- const s = ui.stats+ const s = townView.statsif (!s) return nullconst residents = s.settlers + s.citizensif (residents < kind.unlock.residents) return `needs ${kind.unlock.residents} residents`@@ -842,13 +814,13 @@ export const createHost = async (if (cost.coins > 0) {const chip = el("span", "chip")chip.innerHTML = `${icon("coins", 14)}${cost.coins}`- chips.push({ chip, short: () => (ui.stats?.coins ?? 0) < cost.coins })+ chips.push({ chip, short: () => (townView.stats?.coins ?? 0) < cost.coins })}for (const [g, n] of Object.entries(cost.materials) as Array<[GoodId, number]>) {const chip = el("span", "chip")chip.title = goods[g].titlechip.innerHTML = `${goodIcon(g, 14)}${n}`- chips.push({ chip, short: () => (ui.stats?.stock[g] ?? 0) < n })+ chips.push({ chip, short: () => (townView.stats?.stock[g] ?? 0) < n })}box.append(...chips.map((c) => c.chip))const refresh = () => {@@ -1022,23 +994,23 @@ export const createHost = async (name.innerHTML = icon(tier, 16)name.append(document.createTextNode(tier))line.append(name, value)- const rate = slider(TAX_STEPS[0], TAX_STEPS.at(-1)!, 5, (to) => ui.edits.push({ type: "tax", tier, rate: to }))+ const rate = slider(TAX_STEPS[0], TAX_STEPS.at(-1)!, 5, (to) => queueEdit({ type: "tax", tier, rate: to }))rate.input.classList.add("tax")rate.input.title = "Drag to set the rate; double-click for the usual 100%"- rate.input.ondblclick = () => ui.edits.push({ type: "tax", tier, rate: 100 })+ rate.input.ondblclick = () => queueEdit({ type: "tax", tier, rate: 100 })const effect = el("p", "effect")const outlook = el("p", "effect outlook")outlook.title = "Taxes a minute from every home if this rate stayed there and the homes settled: residents move away above 100%, and approval follows the rate"levers.append(line, rate.input, effect, outlook)live.push(() => {- const now = ui.stats?.policy[tier] ?? 100+ const now = townView.stats?.policy[tier] ?? 100rate.sync(now)value.textContent = `${now}%`const sway = Math.round((100 - now) * moodRules.perTaxPoint)const grudge = now > moodRules.grudge.above ? " · a grudge builds while it stays this high, and fades slowly" : ""effect.textContent = (sway === 0 ? "the usual rate" : `${signed(sway)} approval`) + grudgeeffect.className = `effect ${sway > 0 ? "up" : sway < 0 ? "down" : ""}`- const steps = ui.stats?.taxOutlook[tier] ?? []+ const steps = townView.stats?.taxOutlook[tier] ?? []const best = steps.reduce<{ rate: number; taxes: number } | null>((b, o) => (b === null || o.taxes > b.taxes ? o : b), null)const text = steps.length === 0 || best === null? ""@@ -1111,7 +1083,7 @@ export const createHost = async (const reserveLine = el("div", "row lever")const reserveValue = el("span", "rate")reserveLine.append(el("span", "label", "keep in store"), reserveValue)- const reserve = slider(0, RESERVE_MAX, 5, (amount) => ui.edits.push({ type: "reserve", amount }))+ const reserve = slider(0, RESERVE_MAX, 5, (amount) => queueEdit({ type: "reserve", amount }))reserve.input.title = "How much of each good the town keeps: it sells only beyond this, and buys only up to it"store.append(reserveLine, reserve.input, el("p", "effect", "of each good: sold only above this, bought only up to it"))/** Collections a minute: the traders come at every ledger. */@@ -1130,11 +1102,11 @@ export const createHost = async (top.append(name, right)// Left of the middle sells, right of it buys, the middle neither; how far out is how much a collection.const deal = slider(-TRADE_LOAD, TRADE_LOAD, 1, (v) =>- ui.edits.push(v === 0 ? { type: "trade", good: g, mode: "none" } : { type: "trade", good: g, mode: v < 0 ? "sell" : "buy", amount: Math.abs(v) })+ queueEdit(v === 0 ? { type: "trade", good: g, mode: "none" } : { type: "trade", good: g, mode: v < 0 ? "sell" : "buy", amount: Math.abs(v) }))deal.input.classList.add("deal")deal.input.title = `Drag left to sell ${goods[g].title}, right to buy it; the further, the more each time the traders call. Double-click to stop trading it.`- deal.input.ondblclick = () => ui.edits.push({ type: "trade", good: g, mode: "none" })+ deal.input.ondblclick = () => queueEdit({ type: "trade", good: g, mode: "none" })const mode = el("span", "mode")const bottom = el("div", "deal-line")bottom.append(deal.input, mode)@@ -1150,7 +1122,7 @@ export const createHost = async (panel.append(chronicle)live.push(() => {- const s = ui.stats+ const s = townView.statsif (!s) returnsub.textContent = `${sizes[s.charter.size].title}, ${lands[s.charter.land].title} land · a ${s.fate.rankTitle} · term ${s.fate.term}, ${s.charter.term} minutes`sub.title = `seed ${s.charter.seed}`@@ -1340,16 +1312,16 @@ export const createHost = async (syncLines(gets, getRows, offer.changes.filter((c) => c !== upkeep).map(gainLine))const begin = el("button", "frame primary", `Begin the ${offer.title.toLowerCase()}`)begin.onclick = () => {- const now = ui.panel- if (now?.type === "building") ui.edits.push({ type: "upgrade", cell: now.cell })+ const now = townView.panel+ if (now?.type === "building") queueEdit({ type: "upgrade", cell: now.cell })}const why = el("p", "sub", "")live.push(() => {- const now = ui.panel+ const now = townView.panelif (now?.type !== "building" || !now.upgrade) returnneeded.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)- const coins = ui.stats?.coins ?? 0, stock = ui.stats?.stock+ const coins = townView.stats?.coins ?? 0, stock = townView.stats?.stockconst materials = (Object.entries(offer.cost.materials) as Array<[GoodId, number]>).filter(([, n]) => n > 0)const lacking = materials.filter(([g, n]) => (stock?.[g] ?? 0) < n).map(([g, n]) => `${n - (stock?.[g] ?? 0)} ${goods[g].title}`)syncLines(pays, payRows, [@@ -1371,7 +1343,7 @@ export const createHost = async (}const buildPanel = () => {- const p = ui.panel+ const p = townView.panellive = []panel.replaceChildren()if (!p) return@@ -1406,7 +1378,7 @@ export const createHost = async (box.classList.add("lines", "state")const rows: Array<HTMLElement> = []live.push(() => {- const now = ui.panel+ const now = townView.panelif (now?.type !== "building") returnbox.classList.toggle("trouble", now.problem !== null)syncLines(box, rows, [now.state])@@ -1438,7 +1410,7 @@ export const createHost = async (for (const extra of slots.slice(groups.length)) extra.box.style.display = "none"}live.push(() => {- const now = ui.panel+ const now = townView.panelif (!now || now.type === "build" || now.type === "town" || now.type !== p.type) returnif (now.type === "building") {status.textContent = now.problem ?? now.status@@ -1465,11 +1437,11 @@ export const createHost = async (const pause = el("button", "frame", "Pause work")pause.title = "A paused building has no workers and pays a quarter of its upkeep"pause.onclick = () => {- const now = ui.panel- if (now?.type === "building") ui.edits.push({ type: "pause", cell: now.cell, on: !now.paused })+ const now = townView.panel+ if (now?.type === "building") queueEdit({ type: "pause", cell: now.cell, on: !now.paused })}live.push(() => {- const now = ui.panel+ const now = townView.panelif (now?.type !== "building") returnpause.textContent = now.paused ? "Resume work" : "Pause work"pause.style.display = now.pausable ? "" : "none"@@ -1480,11 +1452,11 @@ export const createHost = async (const close = el("button", "frame", "Close home")close.title = "A closed home stands empty: no taxes, and no cost to the town hall's administration. Reopen it and settlers move back in."close.onclick = () => {- const now = ui.panel- if (now?.type === "house") ui.edits.push({ type: "pause", cell: now.cell, on: !now.closed })+ const now = townView.panel+ if (now?.type === "house") queueEdit({ type: "pause", cell: now.cell, on: !now.closed })}live.push(() => {- const now = ui.panel+ const now = townView.panelif (now?.type !== "house") returnclose.textContent = now.closed ? "Reopen home" : "Close home"close.style.display = now.closable ? "" : "none"@@ -1492,9 +1464,9 @@ export const createHost = async (actions.append(close)}const remove = el("button", "frame danger", "Remove")- remove.onclick = () => ui.edits.push({ type: "remove", cell: p.cell })+ remove.onclick = () => queueEdit({ type: "remove", cell: p.cell })live.push(() => {- const now = ui.panel+ const now = townView.panelremove.title = now?.type === "building" || now?.type === "house" ? now.salvage : ""})actions.append(remove)@@ -1504,7 +1476,7 @@ export const createHost = async (/** Rebuilds the panel when what it shows changes, and refreshes its numbers every frame. */const syncPanel = () => {- const p = ui.panel+ const p = townView.panelconst next =p === null? ""@@ -1662,7 +1634,7 @@ export const createHost = async (const found = el("button", "frame primary", "Start new")found.onclick = () => {if (visiting) endVisit()- ui.edits.push({ type: "newTown", charter: { ...choice } })+ queueEdit({ type: "newTown", charter: { ...choice } })history.length = 0ui.selected = nullui.menu = null@@ -1679,7 +1651,7 @@ export const createHost = async (resume.title = `Carry on with the town saved in this browser: ${saved.title}${saved.savedAt > 0 ? `, saved ${ago(saved.savedAt)}` : ""}`resume.onclick = () => {const said = persistence().load() ?? "Loaded"- ui.toast(said)+ toast(said)if (!said.startsWith("Loaded")) returnhistory.length = 0ui.selected = null@@ -1719,7 +1691,7 @@ export const createHost = async (if (event.target === shareBox) closeShare()}const openShare = async () => {- const s = ui.stats+ const s = townView.statsif (!s || shareBox.classList.contains("open")) returnshareSpeed = ui.speedsetSpeed(0)@@ -1730,7 +1702,7 @@ export const createHost = async (png = await blobOf(card, "image/png")} catch (error) {setSpeed(shareSpeed)- return ui.toast(error instanceof Error ? error.message : "The picture could not be made")+ return toast(error instanceof Error ? error.message : "The picture could not be made")}const name = `inkline-town-${s.fate.state === "playing" ? `year-${s.season.year}` : `term-${s.fate.term}`}.png`const caption = `${metaOf(facts).title} · ${metaOf(facts).description}`@@ -1746,7 +1718,7 @@ export const createHost = async (const actions = el("div", "actions")const picture = el("button", "frame primary", "")picture.append(iconEl("picture", 15), document.createTextNode(handheld() ? "Share the picture" : "Save the picture"))- picture.onclick = async () => ui.toast(await offerPicture(png, name, caption))+ picture.onclick = async () => toast(await offerPicture(png, name, caption))const link = el("button", "frame", "")link.append(iconEl("link", 15), document.createTextNode("Make a link"))const linkRow = el("div", "link-row")@@ -1762,7 +1734,7 @@ export const createHost = async (field.value = made.urlfield.onfocus = () => field.select()const copy = el("button", "frame primary", handheld() ? "Share the link" : "Copy the link")- copy.onclick = async () => ui.toast(await offerLink(made.url, metaOf(facts).title))+ copy.onclick = async () => toast(await offerLink(made.url, metaOf(facts).title))const open = el("a", "frame", "Open")open.setAttribute("href", made.url)open.setAttribute("target", "_blank")@@ -1773,7 +1745,7 @@ export const createHost = async (} catch (error) {link.disabled = falselink.lastChild!.textContent = "Try the link again"- ui.toast(error instanceof Error ? error.message : "Could not share the town")+ toast(error instanceof Error ? error.message : "Could not share the town")}}const close = el("button", "frame", "Close")@@ -1812,7 +1784,7 @@ export const createHost = async (play.title = "Make this town yours: build, govern, and it autosaves in this browser"play.onclick = () => {endVisit()- ui.toast("The town is yours: it autosaves as you play")+ toast("The town is yours: it autosaves as you play")}const own = el("button", "frame", "Found your own")own.onclick = () => openCharter(true)@@ -1826,7 +1798,7 @@ export const createHost = async (const visitFailed = (message: string) => {window.history.replaceState(null, "", "/")openCharter(false)- ui.toast(message)+ toast(message)}// ── The end of the term ──@@ -1863,7 +1835,7 @@ export const createHost = async (let reckoningOpen = falseconst showReckoning = (open: boolean) => {reckoningOpen = open- reckoning.classList.toggle("open", open && ui.stats !== null && ui.stats.fate.state !== "playing")+ reckoning.classList.toggle("open", open && townView.stats !== null && townView.stats.fate.state !== "playing")}const syncReckoning = (s: Stats) => {const over = s.fate.state !== "playing"@@ -1911,7 +1883,7 @@ export const createHost = async (const stand = el("button", "frame primary", "Next term")stand.title = `Stand for another ${s.charter.term} minutes: the same town, new winters, and the crown's requests start small again`stand.onclick = () => {- ui.edits.push({ type: "nextTerm" })+ queueEdit({ type: "nextTerm" })showReckoning(false)}actions.append(stand)@@ -1932,7 +1904,7 @@ export const createHost = async (showReckoning(true)}- const input = new MapInput(stage, ui)+ const input = new MapInput(stage, ui, view.shown, { toast, blocked: () => document.querySelector(".dialog.open") !== null })// A road, a row of homes, or a patch of park let go of on a touch screen is held here until built or// dropped; the tooltip says what it lays and costs.const strokeBar = el("div", "stroke-bar")@@ -1986,7 +1958,7 @@ export const createHost = async (// On a phone: tuck the step away into the bulb, or open the guide in full.if (target.closest("[data-tuck]")) {tucked = stepNow- if (!toldWhere) ui.toast("The guide is in the bulb at the top right")+ if (!toldWhere) toast("The guide is in the bulb at the top right")toldWhere = truereturn}@@ -2004,7 +1976,7 @@ export const createHost = async (}if (target.closest("[data-guide-off]")) {ui.guide.push({ type: "off" })- ui.toast("Guide off · turn it back on from the bottom right")+ toast("Guide off · turn it back on from the bottom right")return}// A building the line is about: go to it.@@ -2049,8 +2021,9 @@ export const createHost = async (let toldWhere = false/** Copies the town's numbers and preview into the page, once a frame. */const syncPage = () => {+ for (const message of townView.toasts.splice(0)) toast(message)syncPanel()- const s = ui.stats+ const s = townView.statsif (s) {// The treasury as the goods are shown: which way it went over the last minute, and by how much; the steady rate until a minute is counted.const cf = s.flow?.coins ?? null@@ -2211,11 +2184,11 @@ export const createHost = async (const latest = s.chronicle.at(-1)const seen = `${s.charter.seed}|${latest?.tick ?? -1}|${s.chronicle.length}`if (seen !== lastNews) {- if (lastNews !== "" && latest?.alarm && minute - latest.tick < 120) ui.toast(latest.text)+ if (lastNews !== "" && latest?.alarm && minute - latest.tick < 120) toast(latest.text)lastNews = seen}// The map view's legend.- const l = ui.legend+ const l = townView.legendconst legendHtml = l? `<b>${l.title}</b>${l.keys.map((k) => `<span class="key"><i style="background:${hex(k.color)}"></i>${k.label}</span>`).join("")}<small>${l.note}</small>`: ""@@ -2229,9 +2202,9 @@ export const createHost = async (input.sync()const screenPointer = input.tip// A stroke being drawn says what it lays and costs.- const text = ui.dragFrom && ui.stroke !== "cancel" && ui.preview.stroke ? ui.preview.stroke : ui.preview.tooltip+ const text = ui.dragFrom && ui.stroke !== "cancel" && townView.stroke ? townView.stroke : townView.tooltip// A held touch stroke waits for its build button.- const held = ui.stroke === "held" && ui.preview.stroke !== null+ const held = ui.stroke === "held" && townView.stroke !== nullstrokeBar.classList.toggle("open", held)document.body.classList.toggle("stroke-held", held)if (text && screenPointer) {@@ -2242,7 +2215,7 @@ export const createHost = async (} else tooltip.style.display = "none"}- return { app, stage, ui, syncPage, resetPage, input, visit, visitFailed, visiting: () => visiting }+ return { stage, syncPage, resetPage, toast, input, visit, visitFailed, visiting: () => visiting }}/** Which way a good (or the treasury) went over the last minute: made and bought against used and sold, past a tenth of the traffic either way. */diff --git a/src/ui/dom/kit/icons.ts b/src/ui/dom/kit/icons.tsindex 554840b..2cfd837 100644--- a/src/ui/dom/kit/icons.ts+++ b/src/ui/dom/kit/icons.ts@@ -4,12 +4,13 @@* two line weights as the town, so they sit beside it as part of one drawing.*/import { goods, type GoodId } from "../../../game/content/index.ts"+import type { IconName } from "../../../view/icons.ts"const ink = "#3d4943"const hex = (color: number) => `#${color.toString(16).padStart(6, "0")}`/** Shapes inside a 16 × 16 box: `s` strokes in ink, `f(color)` fills with an ink outline. */-const paths: Record<string, string> = {+const paths = {// ── Goods ──wood: `<path d="M3 6.5h8.5v5H3z" fill="#d9b98c"/><ellipse cx="11.5" cy="9" rx="2" ry="2.5" fill="#f1dcb4"/><circle cx="11.5" cy="9" r=".8" fill="none"/><path d="M3 6.5a2 2.5 0 0 0 0 5" fill="none"/>`,planks: `<path d="M2 10.5l7 3 5-2.5-7-3z" fill="#f0c59a"/><path d="M2 10.5v1.5l7 3v-1.5" fill="#e2a873"/><path d="M9 15v-1.5l5-2.5V12.5z" fill="#d2945c"/><path d="M2 6.5l7 3 5-2.5-7-3z" fill="#f0c59a"/><path d="M2 6.5V8l7 3V9.5" fill="#e2a873"/><path d="M9 11V9.5L14 7v1.5z" fill="#d2945c"/>`,@@ -78,9 +79,10 @@ const paths: Record<string, string> = {condition: `<path d="M2.5 14.5v-8l5.5-4 5.5 4v8z" fill="#f5f6f2"/><path d="M6 6.5l2 2.5-1.5 2 2 3" fill="none" stroke="#b04a39" stroke-width="1.2"/>`,view: `<path d="M1.5 8s2.5-4.5 6.5-4.5S14.5 8 14.5 8s-2.5 4.5-6.5 4.5S1.5 8 1.5 8z" fill="#f7f8f4"/><circle cx="8" cy="8" r="2.3" fill="#c9d6ee"/>`,workers: `<circle cx="8" cy="5" r="2.3" fill="#f5f6f2"/><path d="M5.3 4.5c0-2 1.2-3 2.7-3s2.7 1 2.7 3z" fill="#e3c25a" stroke-width="1"/><path d="M3.5 14c0-3.5 2-5.5 4.5-5.5s4.5 2 4.5 5.5z" fill="#e9c48a"/>`-}+} satisfies Record<IconName, string>-export type IconName = keyof typeof paths | GoodId+export type { IconName }+/** Every icon the page draws, in the order they are drawn above. */export const iconNames = Object.keys(paths) as ReadonlyArray<IconName>/** An icon as an SVG string, `size` px a side. */diff --git a/src/view/alerts.ts b/src/view/alerts.tsnew file mode 100644index 0000000..b12fc32--- /dev/null+++ b/src/view/alerts.ts@@ -0,0 +1,84 @@+/**+ * What needs looking at now, a line each: fires, sickness, workshops idle+ * for want of their input, workplaces no one can reach, and food running+ * out. A shelf runs empty for a moment all the time, so idleness and hunger+ * are only said once they have lasted (see `Patience`).+ */+import { COMMUTE, kinds, stepsOf, type KindId } from "../game/content/index.ts"+import { larder } from "../game/schedule.ts"+import type { TileLike } from "../game/world/grid.ts"+import type { Point } from "../game/world/iso.ts"+import type { Alert } from "./contracts.ts"+import type { Frame } from "./frame.ts"++/** How long things have been wrong, so the ticker waits before saying so. Not saved; it starts over on a load. */+export interface Patience {+ /** When each workshop began waiting for its input: the ticker only says so after `ALERT_PATIENCE`. */+ readonly starvedSince: Map<number, number>+ /** Since when the store has held no food (`null`: it has some). Fish comes in and goes out in handfuls, so the ticker waits `HUNGER_PATIENCE` before saying so. */+ emptySince: number | null+ /** Once said, it stays said a while, so a handful of fish arriving does not flick it off and on. */+ hungryUntil: number+}+export const freshPatience = (): Patience => ({ starvedSince: new Map(), emptySince: null, hungryUntil: 0 })+const ALERT_PATIENCE = stepsOf(30)+const HUNGER_PATIENCE = stepsOf(20)++/** The alerts this frame; the workplaces short of workers; and the town hall's row. */+export const alertsOf = (frame: Frame, patience: Patience) => {+ const { buildings, houses, tick } = frame+ const alerts: Array<Alert> = []+ const census = frame.world.census+ const stock = frame.world.stock+ /** A building of this kind stands (built, not a site). */+ const stands = (k: KindId) => buildings.some(({ data }) => data.building.get().kind === k && !data.site.present && !data.rising.present)+ // Each line says what is wrong, then what to do about it.+ const burningRow = [...buildings, ...houses].find(({ data }) => data.burning.present)+ const fireText = `${census.burning} on fire: ${stands("firewatch") ? "the fire watch's firefighters are on their way" : "build a fire watch nearby, whose firefighters put fires out"}`+ if (census.burning > 0) alerts.push({ tone: "bad", text: fireText, at: burningRow?.data.tile.get() ?? null, size: burningRow?.data.tile.get().size ?? 1, id: burningRow?.entity.id ?? null })+ const sickRow = houses.find(({ data }) => data.sick.present)+ const sickText = `${census.sick} home${census.sick > 1 ? "s" : ""} sick, holding half as many people: ${stands("healer") || stands("hospital") ? "a healer within reach of its road cures it" : "build a healer among the homes"}`+ if (census.sick > 0) alerts.push({ tone: "warn", text: sickText, at: sickRow?.data.tile.get() ?? null, size: 1, id: sickRow?.entity.id ?? null })+ const waiting = new Map<string, { n: number; at: TileLike; id: number; kind: KindId }>()+ const remote = new Map<string, { n: number; at: TileLike; id: number; kind: KindId }>()+ const shortStaffed: Array<{ id: number; title: string; cell: Point; size: number; assigned: number; needed: number; nobodyNear: boolean }> = []+ const seen = new Set<number>()+ for (const { entity, data } of buildings) {+ if (data.site.present || data.rising.present || data.paused.present) continue+ const kind = kinds[data.building.get().kind]+ const status = data.status.get()+ const staff = data.staff.get()+ const tile = data.tile.get()+ if (status === "starved" && kind.recipe?.input) {+ seen.add(entity.id)+ const since = patience.starvedSince.get(entity.id) ?? tick+ if (!patience.starvedSince.has(entity.id)) patience.starvedSince.set(entity.id, tick)+ if (tick - since >= ALERT_PATIENCE) {+ const label = `${kind.title.toLowerCase()} needs ${kind.recipe.input}`+ const was = waiting.get(label)+ waiting.set(label, was ? { ...was, n: was.n + 1 } : { n: 1, at: tile, id: entity.id, kind: kind.id })+ }+ }+ if (staff.needed > 0 && staff.assigned < staff.needed) shortStaffed.push({ id: entity.id, title: kind.title.toLowerCase(), cell: tile, size: tile.size, assigned: staff.assigned, needed: staff.needed, nobodyNear: staff.nearby === 0 })+ if (status === "unstaffed" && staff.nearby === 0) {+ const label = kind.title.toLowerCase()+ const was = remote.get(label)+ remote.set(label, was ? { ...was, n: was.n + 1 } : { n: 1, at: tile, id: entity.id, kind: kind.id })+ }+ }+ for (const id of [...patience.starvedSince.keys()]) if (!seen.has(id)) patience.starvedSince.delete(id)+ const list = (m: Map<string, { n: number }>) => [...m].map(([k, v]) => `${k}${v.n > 1 ? ` ×${v.n}` : ""}`).join(", ")+ const first = (m: Map<string, { at: TileLike; id: number }>) => [...m.values()][0]+ const placesOf = (m: Map<string, { at: TileLike; id: number; kind: KindId }>) =>+ Object.fromEntries([...m.values()].map((v) => [v.kind, { at: v.at, size: v.at.size, id: v.id }]))+ if (waiting.size > 0) alerts.push({ tone: "warn", text: `idle: the ${list(waiting)}. Build more of what makes it, or buy it in the [town] panel`, at: first(waiting)?.at ?? null, size: first(waiting)?.at.size ?? 1, id: first(waiting)?.id ?? null, places: placesOf(waiting) })+ if (remote.size > 0) alerts.push({ tone: "warn", text: `no workers for the ${list(remote)}: lay [homes] within ${COMMUTE} road cells of it, or a road to homes nearby`, at: first(remote)?.at ?? null, size: first(remote)?.at.size ?? 1, id: first(remote)?.id ?? null, places: placesOf(remote) })+ const hallRow = buildings.find(({ data }) => data.hall.present)+ const empty = census.homes > 0 && larder(stock) === 0+ if (!empty || (patience.emptySince !== null && patience.emptySince > tick)) patience.emptySince = null+ if (empty && patience.emptySince === null) patience.emptySince = tick+ if (empty && tick - patience.emptySince! >= HUNGER_PATIENCE) patience.hungryUntil = tick + HUNGER_PATIENCE+ if (patience.hungryUntil > tick + HUNGER_PATIENCE) patience.hungryUntil = 0+ if (census.homes > 0 && tick < patience.hungryUntil) alerts.push({ tone: "bad", text: "no food in store, so homes go hungry and pay no taxes: build another fishery, or buy fish in the [town] panel", at: hallRow?.data.tile.get() ?? null, size: hallRow?.data.tile.get().size ?? 1, id: hallRow?.entity.id ?? null })+ return { alerts, shortStaffed, hallRow }+}diff --git a/src/view/contracts.ts b/src/view/contracts.tsindex e3482d5..e93c76a 100644--- a/src/view/contracts.ts+++ b/src/view/contracts.ts@@ -1,15 +1,15 @@/**- * The bridge between the page and the town. The page writes the pointer and- * gestures; the town's present systems turn gestures into a selection, a- * preview, and edits; the simulation applies the edits on its next step.- * None of it is saved: it is host state, handed to systems as a service.+ * What the view layer trades with every UI and renderer, as plain data: no+ * page, no Three.js. A UI (the page in `ui/dom`, or any other) and the map+ * input write the `Interaction`; the view's systems read the world and it,+ * move the selection and drags on, and fill in what is `Shown`: a+ * `TownView` for the UI and a `SceneView` for the renderer. Player actions+ * go to the simulation as edits (`game/edits.ts`). None of it is saved.*/import type { Amounts, CharterValue, GoodId, GroundId, KindId, PropId, Tier, WinterId } from "../game/content/index.ts"-import type { IconName } from "../ui/dom/kit/icons.ts"import type { Point } from "../game/world/iso.ts"import type { Status } from "../game/schema.ts"-import type { OverlayCell } from "../render/three/models.ts"-import type { Edit } from "../game/edits.ts"+import type { IconName } from "./icons.ts"/** How a line of a panel reads: fine, worth a look, wrong, or an aside. */export type Tone = "ok" | "warn" | "bad" | "dim"@@ -171,13 +171,6 @@ export type Panel =readonly lines: ReadonlyArray<Line>}-/** A thing's hit area for the pointer, nearest first. */-export interface HitBox {- readonly id: number- readonly depth: number- readonly contains: (at: Point) => boolean-}-/** The town's numbers for the top bar and the panels. */export interface Stats {readonly coins: number@@ -358,7 +351,27 @@ export interface Legend {readonly note: string}-export interface UiValue {+/** A map view's cell: a colour washed over it, and whether it is outlined. */+export interface OverlayCell {+ readonly x: number+ readonly y: number+ readonly size: number+ readonly color: number+ readonly alpha: number+ /** Outlined, for what the view is about (a workplace and its homes). */+ readonly ring?: boolean+}++/** What the mayor tells the guide: put a step away, or turn the guide off or on (see `Guide`). */+export type GuideAction = { readonly type: "skip"; readonly id: string } | { readonly type: "off" | "on" }++/**+ * What the player is doing with the map. The UI sets the tool, the menu, the+ * speed, and the map view; the map input sets the pointer and queues+ * gestures; the view's systems turn gestures into a selection, drags, and+ * edits.+ */+export interface Interaction {tool: Tool/** The kind being placed with the `place` tool, and the kind whose buildings the `upgrade` tool upgrades. */placing: KindId | null@@ -378,28 +391,57 @@ export interface UiValue {stroke?: "held" | "cancel" | nullselected: number | nullgestures: Array<Gesture>- edits: Array<Edit>- preview: Preview- hits: ReadonlyArray<HitBox>- panel: Panel | null- /** Where each building and home stands on the grid, for the camera to look at. */- centres: ReadonlyMap<number, Point>- stats: Stats | null+ /** What the mayor told the guide since the last frame. */+ guide: Array<GuideAction>/** Steps of the simulation a fixed step: 0 (paused), 1, 2, or 4. */speed: number/** The new-town dialog is open: the town waits. */founding: boolean- /** The map view shown over the town, its cells (rebuilt as the town changes), and its legend. */+ /** The map view shown over the town. */view: View+ /** A place the page points at (from the ticker): outlined until `until`, in milliseconds of the wall clock. */+ flash: { readonly cell: Point; readonly size: number; readonly until: number } | null+}++/** What the UI shows, filled in by the view once a frame. */+export interface TownView {+ panel: Panel | null+ stats: Stats | null+ legend: Legend | null+ /** What the pointer is over, or what the stroke being dragged lays and costs. */+ tooltip: string | null+ stroke: string | null+ /** Messages for the player since the last frame: the UI takes them. */+ toasts: Array<string>+}++/** What the renderer draws besides the world's entities, filled in by the view once a frame. */+export interface SceneView {+ preview: Preview+ /** The map view's cells (rebuilt as the town changes, `key` says when). */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- /** What the mayor told the guide since the last frame: put a step away, or turn the guide off or on (see `Guide`). */- guide: Array<{ readonly type: "skip"; readonly id: string } | { readonly type: "off" | "on" }>- toast: (message: string) => void+ /** How fast the town's people move about: the speed, or 0 while the town waits. */+ pace: number}++/** Everything the view shows, in two parts: the UI's and the renderer's. */+export interface Shown {+ readonly town: TownView+ readonly scene: SceneView+}++/** The map before anything is clicked. */+export const blankInteraction = (): Interaction => ({+ tool: "select", placing: null, upgrading: null, ground: "lawn", prop: "lamp", menu: null, pointer: null, dragFrom: null, selected: null, gestures: [], guide: [],+ speed: 1, founding: false, view: "none", flash: null+})++/** Nothing shown yet. */+export const blankShown = (): Shown => ({+ town: { panel: null, stats: null, legend: null, tooltip: null, stroke: null, toasts: [] },+ scene: { preview: emptyPreview(), overlay: { key: "", cells: [] }, tints: new Map(), wanted: new Map(), pace: 1 }+})diff --git a/src/view/facts.ts b/src/view/facts.tsnew file mode 100644index 0000000..c77deb8--- /dev/null+++ b/src/view/facts.ts@@ -0,0 +1,109 @@+/**+ * What the view reads off a building or a home, for its panel, its tooltip,+ * and its model alike: why it is not working, how far up it is, and how its+ * risks read.+ */+import { BUILD_TICKS, COMMUTE, kindOrder, kinds, RESTOCK_TICKS, risk, RISK_MAX, step, total, worksNeeded, type Amounts, type GoodId, type Kind, type KindId } from "../game/content/index.ts"+import type { Cause } from "../game/rules/explain.ts"+import { salvageOf, salvageText, withWorks } from "../game/rules/salvage.ts"+import type { Status as StatusValue, GridValue } from "../game/schema.ts"+import { SITE_SHARE } from "../game/schedule.ts"+import { around, key, useAt, type TileLike } from "../game/world/grid.ts"+import { percent } from "./text.ts"++/** How far a kind's work reaches, if it works the land around it. */+export const reachOf = (kind: Kind): number | null => kind.gathers?.radius ?? kind.plants?.radius ?? null++const sourceTitle = { tree: "grown trees", stone: "stone", ore: "ore", field: "ripe fields", water: "water" } as const++/** What a building's crew is short of, for its problem line. */+interface Crewing {+ readonly nearby: number+ readonly crew: "settlers" | "citizens"+}++/** Why a building is not working: in a word or two, why in a line, and what to do; `null` when it is fine. */+export interface Problem extends Cause {+ readonly label: string+}++/** The kind that makes a good, for a fix that builds it. */+const makerOf = (good: GoodId): KindId | undefined => kindOrder.find((id) => kinds[id].recipe?.output === good)++export const problemOf = (kind: Kind, status: StatusValue, growing = false, crewing?: Crewing): Problem | null => {+ switch (status) {+ case "unconnected":+ return { label: "no road", why: "it needs a road at the middle of one of its sides", fix: { text: "lay a road along one of its sides" } }+ case "unstaffed":+ if (crewing && crewing.nearby === 0)+ return { label: "no workers", why: `no ${crewing.crew === "citizens" ? "citizens' (or settlers') homes" : "settlers' cottages"} within ${COMMUTE} road cells`, fix: { text: "lay homes nearer, or a road to homes nearby" } }+ return { label: "no workers", why: "every one nearby already has a job", fix: { text: `lay more homes within ${COMMUTE} road cells` } }+ case "blocked":+ return { label: "full", why: "nowhere to take what it makes", fix: { text: "build a warehouse nearby, or sell the surplus in the [town] panel", build: ["warehouse"] } }+ case "paused":+ return { label: "paused", why: "no workers, a quarter of its upkeep", fix: { text: "resume work below" } }+ case "starved":+ if (kind.gathers?.source === "water")+ return growing+ ? { label: "no fish", why: `the water in reach is fished out: each stretch rests ${Math.round(RESTOCK_TICKS * step.dt)} s after a catch`, fix: { text: "give it a longer shore of its own, or fewer fisheries on this water" } }+ : { label: "no water", why: `no water within ${kind.gathers.radius} cells`, fix: { text: "rebuild it by the shore" } }+ if (kind.gathers && growing && (kind.gathers.source === "stone" || kind.gathers.source === "ore"))+ return { label: "worked out", why: `the worked faces in reach give a little ${kind.gathers.source} now and then`, fix: { text: `build it by fresh rock, or buy ${kind.gathers.source} in the [town] panel` } }+ if (kind.gathers && growing) return { label: "waiting", why: `the ${kind.gathers.source === "tree" ? "trees" : "fields"} in reach are still growing` }+ if (kind.gathers)+ return kind.gathers.source === "tree"+ ? { label: "no trees", why: `no grown trees within ${kind.gathers.radius} cells`, fix: { text: "build a forester nearby: it replants", build: ["forester"] } }+ : { label: `no ${sourceTitle[kind.gathers.source]}`, why: `no ${sourceTitle[kind.gathers.source]} within ${kind.gathers.radius} cells`, fix: { text: "rebuild it nearer" } }+ if (kind.recipe?.input) {+ const maker = makerOf(kind.recipe.input)+ return { label: `no ${kind.recipe.input}`, why: `waiting for ${kind.recipe.input}`, fix: maker ? { text: `build a ${kinds[maker].title.toLowerCase()}, or buy ${kind.recipe.input} in the [town] panel`, build: [maker] } : { text: `buy ${kind.recipe.input} in the [town] panel` } }+ }+ if (kind.service?.service === "goods") return { label: "nothing to hand out", why: "no fish, bread, or cloth here", fix: { text: "fill the store: it takes from storage" } }+ if (kind.service?.service === "repair") return { label: "no planks", why: "nothing to mend with", fix: { text: "build a sawmill", build: ["lumberjack", "sawmill"] } }+ return { label: "waiting", why: "waiting" }+ default:+ return null+ }+}++/**+ * A tree or field gatherer has young ones within reach: it is waiting on+ * them to grow, not on a forester. A quarry or mine has rocks in reach,+ * worked down to their faces: it is waiting on the next one.+ */+export const growingNear = (grid: GridValue, tile: TileLike, kind: Kind, rocks: ReadonlyMap<number, { readonly ore: boolean }>): boolean => {+ const g = kind.gathers+ if (!g) return false+ // Water in reach, fished out: it rests, and gives again.+ if (g.source === "water") return around(tile, g.radius).some((c) => useAt(grid, c.x, c.y) === "water")+ if (g.source === "stone" || g.source === "ore") return around(tile, g.radius).some((c) => rocks.get(key(c.x, c.y))?.ore === (g.source === "ore"))+ return around(tile, g.radius).some((c) => useAt(grid, c.x, c.y) === g.source)+}++/** How far up a building or home is: a site rises to its frame as materials come in, then the rest of the way. */+export const buildOf = (+ site: { readonly owed: Parameters<typeof total>[0]; readonly total: number } | undefined,+ rising: { readonly ticks: number } | undefined+) => (site ? PLATE_SHARE + (SITE_SHARE - PLATE_SHARE) * delivered(site) : rising ? rising.ticks / BUILD_TICKS : 1)++/** An upgrade under way: the share of its work done (see `Works`), else `null`. */+export const worksShare = (works: { readonly total: number; readonly done: number } | undefined) =>+ works ? Math.min(1, works.done / worksNeeded(works.total)) : null+export const siteShare = (site: { readonly owed: Parameters<typeof total>[0]; readonly total: number } | undefined) =>+ site ? delivered(site) : null++/** A site's plate is marked out the moment it is placed. */+const PLATE_SHARE = 0.12+/** The share of a site's materials that has arrived. */+const delivered = (site: { readonly owed: Parameters<typeof total>[0]; readonly total: number }) =>+ 1 - total(site.owed) / Math.max(1, site.total)++/** How a risk reads: "low", "40%", or "high: 85%". */+export const riskText = (value: number) => (value < RISK_MAX * 0.35 ? "ok" : value >= risk.warn ? `high, ${percent(value, RISK_MAX)}` : percent(value, RISK_MAX))++/** What pulling a building or home down would cost and give back, for the bulldozer and the panel. */+export const salvageFor = (cost: Kind["cost"], site: { readonly owed: Amounts } | undefined, works?: { readonly kind: Kind; readonly owed: Amounts; readonly level: number }) => {+ const s = withWorks(salvageOf(cost, site?.owed ?? null), works?.kind ?? {}, works)+ const said = salvageText(s)+ return `${site ? "cancel" : "pull down"}${said ? `: ${said}` : ""}`+}diff --git a/src/view/feedback.ts b/src/view/feedback.tsnew file mode 100644index 0000000..f10fb35--- /dev/null+++ b/src/view/feedback.ts@@ -0,0 +1,20 @@+/** What the simulation told the player this step: toasts to show, and the panel's selection. */+import { Game, Selection, Toast } from "../game/schema.ts"+import { Interaction, Shown } from "./services.ts"++export const ShowFeedback = Game.System(+ "Town/ShowFeedback",+ {+ events: { toast: Game.System.readEvent(Toast), selection: Game.System.readEvent(Selection) },+ services: { interaction: Game.System.service(Interaction), shown: Game.System.service(Shown) }+ },+ ({ events, services }) => {+ const ui = services.interaction+ for (const message of events.toast.all()) services.shown.town.toasts.push(message)+ for (const change of events.selection.all()) {+ if ("select" in change) ui.selected = change.select+ else if ("clear" in change) ui.selected = null+ else if (ui.selected === change.clearIf) ui.selected = null+ }+ }+)diff --git a/src/view/frame.ts b/src/view/frame.tsnew file mode 100644index 0000000..7f5d635--- /dev/null+++ b/src/view/frame.ts@@ -0,0 +1,243 @@+/**+ * The world as the view reads it, once a frame: every row it looks at and+ * every resource value, taken in one pass by `Project` and handed to the+ * modules that turn it into a preview, a panel, the map views, alerts, and+ * the town's numbers. The lookups that cost a walk of the town (the homes no+ * food walker reaches, the neighbourhood's sources) are reckoned once, when+ * first asked.+ */+import type { Descriptor } from "@typeonce/ritmo"+import type { Query, QueryMatch } from "@typeonce/ritmo/Query"++import { buildingSource, homeSource, landSource, parkSources, parksOf, type AppealSource, type ParkCell, type ParkValue } from "../game/world/appeal.ts"+import { condition as wear, CONDITION_MAX, type KindId } from "../game/content/index.ts"+import type { Fix } from "../game/rules/explain.ts"+import {+ Appeal, Building, Burning, Census, Charter, Chronicle, Condition, Crown, Fate, Flow, Game, Grid, Guide, Handed, History, House, Inventory, Ledger, Market, Mood,+ Pantry, Park, Paused, Paved, Policy, Rebuilt, Recipe, Rising, Risk, Road, Rock, Ruin, Service, Sick, Site, Staff, Status, Stock, Tile, Time, TownHall, Treasury, Tree,+ Upgraded, Water, WalkerOf, Works+} from "../game/schema.ts"+import { doors, isRoad, key, nearest, reach, type TileLike } from "../game/world/grid.ts"+import type { Point } from "../game/world/iso.ts"+import type { Line } from "./contracts.ts"++export const BuildingRead = Game.Query({+ selection: {+ tile: Game.Query.read(Tile),+ building: Game.Query.read(Building),+ status: Game.Query.read(Status),+ staff: Game.Query.read(Staff),+ site: Game.Query.optional(Site),+ rising: Game.Query.optional(Rising),+ recipe: Game.Query.optional(Recipe),+ inventory: Game.Query.optional(Inventory),+ service: Game.Query.optional(Service),+ walkers: Game.Query.optionalRelated(WalkerOf),+ hall: Game.Query.optional(TownHall),+ paused: Game.Query.optional(Paused),+ upgraded: Game.Query.optional(Upgraded),+ works: Game.Query.optional(Works),+ risk: Game.Query.optional(Risk),+ condition: Game.Query.optional(Condition),+ burning: Game.Query.optional(Burning)+ }+})+export const HouseRead = Game.Query({+ selection: {+ tile: Game.Query.read(Tile),+ house: Game.Query.read(House),+ rebuilt: Game.Query.optional(Rebuilt),+ site: Game.Query.optional(Site),+ rising: Game.Query.optional(Rising),+ risk: Game.Query.optional(Risk),+ condition: Game.Query.optional(Condition),+ burning: Game.Query.optional(Burning),+ sick: Game.Query.optional(Sick),+ closed: Game.Query.optional(Paused)+ }+})+export const RuinRead = Game.Query({ selection: { tile: Game.Query.read(Tile), ruin: Game.Query.read(Ruin) } })+export const ParkRead = Game.Query({ selection: { tile: Game.Query.read(Tile), park: Game.Query.read(Park) } })+const TreeRead = Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Tree] })+const WaterRead = Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Water] })+const RockRead = Game.Query({ selection: { tile: Game.Query.read(Tile), rock: Game.Query.read(Rock) } })+const PavedRead = Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road, Paved] })++type Row<Q extends Query.Any> = QueryMatch<typeof Game.schema, Q>+export type BuildingRow = Row<typeof BuildingRead>+export type HouseRow = Row<typeof HouseRead>+export type RuinRow = Row<typeof RuinRead>+export type ParkRow = Row<typeof ParkRead>+export type RockRow = Row<typeof RockRead>++/** What `Project` declares to read: the queries and resources a frame is made of. */+export const frameAccess = {+ queries: { buildings: BuildingRead, houses: HouseRead, ruins: RuinRead, parks: ParkRead, trees: TreeRead, water: WaterRead, rocks: RockRead, paved: PavedRead },+ resources: {+ grid: Game.System.readResource(Grid),+ census: Game.System.readResource(Census),+ treasury: Game.System.readResource(Treasury),+ ledger: Game.System.readResource(Ledger),+ stock: Game.System.readResource(Stock),+ flow: Game.System.readResource(Flow),+ handed: Game.System.readResource(Handed),+ policy: Game.System.readResource(Policy),+ time: Game.System.readResource(Time),+ charter: Game.System.readResource(Charter),+ market: Game.System.readResource(Market),+ mood: Game.System.readResource(Mood),+ crown: Game.System.readResource(Crown),+ fate: Game.System.readResource(Fate),+ history: Game.System.readResource(History),+ chronicle: Game.System.readResource(Chronicle),+ appeal: Game.System.readResource(Appeal),+ pantry: Game.System.readResource(Pantry),+ guide: Game.System.readResource(Guide)+ }+}++const worldResources = {+ grid: Grid, census: Census, treasury: Treasury, ledger: Ledger, stock: Stock, flow: Flow, handed: Handed, policy: Policy, time: Time, charter: Charter,+ market: Market, mood: Mood, crown: Crown, fate: Fate, history: History, chronicle: Chronicle, appeal: Appeal, pantry: Pantry, guide: Guide+}+/** Every resource the view reads, as its value this frame. */+export type World = { readonly [K in keyof typeof worldResources]: Descriptor.Descriptor.Value<(typeof worldResources)[K]> }+type FrameRows = { readonly [K in keyof typeof frameAccess.queries]: Row<(typeof frameAccess.queries)[K]> }++/** A thing's hit area for the pointer, nearest first. */+interface HitBox {+ readonly id: number+ readonly depth: number+ readonly contains: (at: Point) => boolean+}++/** A thing's hit area: its footprint on the floor. */+const hitBox = (id: number, tile: TileLike): HitBox => ({+ id,+ depth: tile.x + tile.y + tile.size,+ contains: (at) => at.x >= tile.x && at.x <= tile.x + tile.size && at.y >= tile.y && at.y <= tile.y + tile.size+})+const hitAt = (hits: ReadonlyArray<HitBox>, at: Point, entity?: number | null) =>+ entity === undefined ? (hits.find((h) => h.contains(at))?.id ?? null) : entity++/** Rows with a site's plate down or still rising are not built yet. */+type Raised = { readonly data: { readonly site: { readonly present: boolean }; readonly rising: { readonly present: boolean } } }++/**+ * Reads the frame: `queries` and `resources` as `Project`'s callback receives+ * them (see `frameAccess`).+ */+export const frameOf = (+ queries: { readonly [K in keyof FrameRows]: { each(): ReadonlyArray<FrameRows[K]> } },+ resources: { readonly [K in keyof World]: { get(): World[K] } }+) => {+ const world: World = {+ grid: resources.grid.get(), census: resources.census.get(), treasury: resources.treasury.get(), ledger: resources.ledger.get(), stock: resources.stock.get(),+ flow: resources.flow.get(), handed: resources.handed.get(), policy: resources.policy.get(), time: resources.time.get(), charter: resources.charter.get(),+ market: resources.market.get(), mood: resources.mood.get(), crown: resources.crown.get(), fate: resources.fate.get(), history: resources.history.get(),+ chronicle: resources.chronicle.get(), appeal: resources.appeal.get(), pantry: resources.pantry.get(), guide: resources.guide.get()+ }+ const grid = world.grid+ const buildings = queries.buildings.each()+ const houses = queries.houses.each()+ const ruins = queries.ruins.each()+ const parkRows = queries.parks.each()+ const rocks = queries.rocks.each()+ const parkCells: Array<ParkCell> = parkRows.map(({ data }) => ({ ...data.tile.get(), ...data.park.get() }))+ const parkAt = new Map(parkRows.map((row) => [key(row.data.tile.get().x, row.data.tile.get().y), row] as const))+ const road = (x: number, y: number) => isRoad(grid, x, y)+ const hits: Array<HitBox> = [+ ...buildings.map(({ entity, data }) => hitBox(entity.id, data.tile.get())),+ ...houses.map(({ entity, data }) => hitBox(entity.id, data.tile.get())),+ ...ruins.map(({ entity, data }) => hitBox(entity.id, data.tile.get())),+ ...parkRows.map(({ entity, data }) => hitBox(entity.id, data.tile.get()))+ ].sort((l, r) => r.depth - l.depth)+ // 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 finished = (row: Raised) => !row.data.site.present && !row.data.rising.present+ let unreached: number | null = null+ let sources: Array<AppealSource> | null = null+ const frame = {+ world,+ grid,+ rates: world.policy,+ approval: world.mood.approval,+ cells: world.appeal.cells,+ tick: world.time.step,+ buildings,+ houses,+ ruins,+ parkRows,+ rocks,+ trees: queries.trees.each(),+ water: queries.water.each(),+ paved: queries.paved.each(),+ /** The rocks by cell: which are ore, and which are worked down to their faces. */+ rockAt: new Map(rocks.map(({ data }) => [key(data.tile.get().x, data.tile.get().y), data.rock.get()])),+ parkCells,+ parkAt,+ road,+ /** The park a cell belongs to, as it is, or as it would be with `changed` cells laid over it. */+ parkOf: (cell: Point, changed: ReadonlyArray<ParkCell> = []): ParkValue | undefined => {+ const over = new Map(parkCells.map((c) => [key(c.x, c.y), c]))+ for (const c of changed) over.set(key(c.x, c.y), c)+ return parksOf([...over.values()], road).find((p) => p.cells.some((c) => c.x === cell.x && c.y === cell.y))+ },+ /** How far a park reaches, as one square around it. */+ reachPlots: (p: ParkValue) => {+ const xs = p.cells.map((c) => c.x)+ const ys = p.cells.map((c) => c.y)+ const x = Math.min(...xs)+ const y = Math.min(...ys)+ const size = Math.max(Math.max(...xs) - x, Math.max(...ys) - y) + 1+ return [{ x: x - p.reach, y: y - p.reach, size: size + 2 * p.reach, look: "reach" as const }]+ },+ /** What the pointer is on: the model the camera ray hit, or else (parks have nothing standing to hit) the park on the cell. */+ pickAt: (at: Point, entity?: number | null) => {+ const hit = hitAt(hits, at, entity)+ return hit ?? parkAt.get(key(Math.floor(at.x), Math.floor(at.y)))?.entity.id ?? null+ },+ tileOf: (id: number) => [...buildings, ...houses, ...ruins, ...parkRows].find((row) => row.entity.id === id)?.data.tile.get(),+ standing,+ finished,+ fixOf: (f: Fix | undefined): Line["fix"] => f && { text: f.text, build: f.build?.find((k) => !standing.has(k)) ?? f.build?.at(-1) },+ /** Built homes no food walker reaches: a walk from each walker's door, so reckoned once a frame, when asked. */+ unreachedHomes: () => {+ if (unreached !== null) return unreached+ const walks = buildings+ .filter((row) => row.data.service.value()?.service === "goods" && finished(row))+ .map((row) => ({ way: reach(grid, doors(grid, row.data.tile.get())), range: row.data.service.value()!.range }))+ unreached = 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+ return unreached+ },+ /** Everything that makes a street nicer or worse (only when a home's panel asks). */+ appealSources: () => {+ if (sources) return sources+ sources = []+ for (const { data } of buildings) {+ if (data.site.present || data.rising.present) continue+ const s = buildingSource(data.building.get().kind, data.tile.get(), undefined, data.upgraded.value()?.level ?? 0)+ if (s) sources.push(s)+ }+ for (const { data } of queries.trees.each()) sources.push(landSource("forest", data.tile.get()))+ for (const { data } of queries.water.each()) sources.push(landSource("water", data.tile.get()))+ for (const { data } of queries.paved.each()) sources.push(landSource("paved", data.tile.get()))+ sources.push(...parkSources(parkCells, road))+ for (const { data } of ruins) sources.push(landSource("ruin", data.tile.get()))+ for (const { data } of houses) {+ if (data.site.present || data.rising.present) continue+ if ((data.condition.value()?.value ?? CONDITION_MAX) < wear.worn) sources.push(landSource("worn", data.tile.get()))+ const fine = data.closed.present ? null : homeSource(data.house.get().tier, data.tile.get())+ if (fine) sources.push(fine)+ }+ return sources+ }+ }+ return frame+}+export type Frame = ReturnType<typeof frameOf>+diff --git a/src/view/guide.ts b/src/view/guide.tsnew file mode 100644index 0000000..2df958e--- /dev/null+++ b/src/view/guide.ts@@ -0,0 +1,177 @@+/**+ * The mayor's guide: the step to take now, chosen from what the town has done+ * and what it needs (see `rules/guide.ts`). Only the simulation writes the+ * guide: what the mayor says and what the town completes go to it as edits,+ * and count here until it has applied them (`pending`), so the guide moves on+ * at once.+ */+import { CONDITION_MAX, condition as wear, goodIds, home, kinds, RISK_MAX } from "../game/content/index.ts"+import type { Edit } from "../game/edits.ts"+import { courseCount, GUIDE_QUIET, guideDone, guideStep, guideSteps, lockedNote, upcoming, type GuideFacts, type GuideFocus } from "../game/rules/guide.ts"+import { met, steadyNet } from "../game/schedule.ts"+import { appealAt } from "../game/world/appeal.ts"+import { useAt, type TileLike } from "../game/world/grid.ts"+import { GRID } from "../game/world/iso.ts"+import type { Interaction, Stats } from "./contracts.ts"+import type { BuildingRow, Frame } from "./frame.ts"+import type { Numbers } from "./stats.ts"++/** The guide's state on the page's side (not saved): edits not yet applied, and its pace. */+export interface GuideState {+ readonly pending: { readonly done: Set<string>; off: boolean | null }+ /** The step it is showing, and until when it keeps quiet. */+ readonly pace: { shown: string | null; since: number; quietUntil: number }+}+export const freshGuide = (): GuideState => ({ pending: { done: new Set(), off: null }, pace: { shown: null, since: 0, quietUntil: 0 } })++/** The guide's part of the town's numbers; `hallRow`: the town hall, which several steps point at. */+export const guideOf = (frame: Frame, ui: Interaction, send: (edit: Edit) => void, state: GuideState, numbers: Numbers, hallRow: BuildingRow | undefined): Stats["guide"] => {+ const { grid, buildings, houses, cells, rates } = frame+ const census = frame.world.census+ const stock = frame.world.stock+ const pace = state.pace+ const { season, crown, mood, net, coins, f, t, seconds } = numbers+ // The page writes what the mayor told it; then the guide puts away what the town has done, and picks the step to show.+ // Only the simulation writes the guide: both go to it as edits, and count here until it has applied them.+ const pending = state.pending+ for (const action of ui.guide.splice(0)) {+ if (action.type === "skip") {+ pending.done.add(action.id)+ send({ type: "guide", done: [action.id] })+ } else {+ pending.off = action.type === "off"+ send({ type: "guideOff", off: pending.off })+ }+ }+ 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 wornRow = buildings.find((row) => frame.finished(row) && !row.data.hall.present && (row.data.condition.value()?.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) => {+ const h = row.data.house.get()+ if (h.tier !== 1 || !frame.finished(row)) return false+ const tile = row.data.tile.get()+ return met(h, "bread") && met(h, "cloth") && met(h, "faith") && appealAt(cells, tile.x, tile.y) < home.tiers[2].appeal+ })+ const saved = frame.world.guide+ for (const id of saved.done) pending.done.delete(id)+ if (pending.off === saved.off) pending.off = null+ const guide = { done: [...saved.done, ...pending.done], off: pending.off ?? saved.off }+ const put = new Set(guide.done)+ /** A road within two cells of water: reckoned only until the guide's road step is put away. */+ const roadNearWater = () => {+ for (let y = 0; y < GRID; y++) {+ for (let x = 0; x < GRID; x++) {+ if (useAt(grid, x, y) !== "road") continue+ for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) if (useAt(grid, x + dx, y + dy) === "water") return true+ }+ }+ return false+ }+ const facts: GuideFacts = {+ homes: houses.length,+ builtHomes: houses.filter(frame.finished).length,+ residents: census.settlers + census.citizens,+ citizens: census.citizens,+ finerHomes: houses.filter((row) => row.data.house.get().tier > 1).length,+ placed: placedKinds,+ standing: standingKinds,+ stock,+ sick: census.sick,+ burning: census.burning,+ winter: season.winter,+ winterIn: season.coming === null ? null : seconds(season.left),+ worn: wornRow !== undefined,+ poorStreet: poorRow !== undefined,+ crown: { open: crown.open, met: crown.met },+ net: steadyNet(frame.world.history.samples, net),+ approval: mood.approval,+ trading: rates.sells.length > 0 || rates.buys.length > 0,+ buysTools: rates.buys.includes("tools"),+ taxed: rates.settlers !== 100 || rates.citizens !== 100,+ most: Math.max(...goodIds.map((g) => stock[g])),+ sawTown: ui.menu === "town",+ sawHome: houses.some((row) => row.entity.id === ui.selected),+ sawBuilding: buildings.some((row) => row.entity.id === ui.selected && !row.data.hall.present),+ roadToWater: put.has("road") || roadNearWater(),+ coins,+ unreached: put.has("market") || standingKinds.has("market") ? 0 : frame.unreachedHomes(),+ rank: f.rank,+ upgraded: new Set(buildings.filter((row) => row.data.upgraded.present).map((row) => row.data.building.get().kind)),+ risk: {+ fire: houses.some((row) => (row.data.risk.value()?.fire ?? 0) >= RISK_MAX * 0.35),+ health: houses.some((row) => (row.data.risk.value()?.health ?? 0) >= RISK_MAX * 0.35),+ order: houses.some((row) => (row.data.risk.value()?.order ?? 0) >= RISK_MAX * 0.35)+ },+ fewTrees: buildings.some((row) => {+ if (row.data.building.get().kind !== "lumberjack" || !frame.finished(row)) return false+ const tile = row.data.tile.get()+ const reach = kinds.lumberjack.gathers!.radius+ return frame.trees.map(({ data }) => data.tile.get()).filter((t) => t.x >= tile.x - reach && t.x < tile.x + tile.size + reach && t.y >= tile.y - reach && t.y < tile.y + tile.size + reach).length < 6+ })+ }+ const playing = f.state === "playing" && !ui.founding+ const newly = playing ? guideDone(facts, put) : []+ if (newly.length > 0) {+ send({ type: "guide", done: newly })+ for (const id of newly) {+ put.add(id)+ pending.done.add(id)+ }+ }+ // The guide keeps quiet a while after a step is put away; a new town (the clock gone back) starts it afresh.+ if (t < pace.since) Object.assign(pace, { shown: null, since: 0, quietUntil: 0 })+ if (pace.shown !== null && put.has(pace.shown)) Object.assign(pace, { shown: null, quietUntil: t + GUIDE_QUIET * 60 })+ const step = guide.off || !playing ? null : guideStep(facts, put, { shown: pace.shown, quiet: t < pace.quietUntil })+ if (step && !step.urgent?.(facts)) pace.shown = step.id+ pace.since = t+ const hallTile = hallRow?.data.tile.get()+ /** Of some tiles, the one nearest the town hall. */+ const nearestHall = (tiles: ReadonlyArray<TileLike>): TileLike | undefined => {+ if (!hallTile) return tiles[0]+ let best: TileLike | undefined+ let far = Infinity+ for (const tile of tiles) {+ const d = Math.abs(tile.x - hallTile.x) + Math.abs(tile.y - hallTile.y)+ if (d < far) [best, far] = [tile, d]+ }+ return best+ }+ const focusOf = (focus: GuideFocus | null): { at: TileLike | null; id: number | null } => {+ if (focus === null) return { at: null, id: null }+ if (focus === "hall") return { at: hallTile ?? null, id: null }+ if (focus === "water") return { at: nearestHall(frame.water.map(({ data }) => data.tile.get())) ?? null, id: null }+ if (focus === "trees") return { at: nearestHall(frame.trees.map(({ data }) => data.tile.get())) ?? null, id: null }+ if (focus === "stone" || focus === "ore") {+ const ore = focus === "ore"+ return { at: nearestHall(frame.rocks.filter(({ data }) => data.rock.get().ore === ore).map(({ data }) => data.tile.get())) ?? null, id: null }+ }+ const row = focus === "worn" ? wornRow : focus === "poorStreet" ? poorRow : buildings.find(({ data }) => data.building.get().kind === focus.kind)+ return row ? { at: row.data.tile.get(), id: row.entity.id } : { at: null, id: null }+ }+ const shown = step ? focusOf(step.focus) : null+ return {+ step:+ step && shown+ ? {+ key: step.id,+ chapter: step.chapter,+ goal: step.goal,+ text: step.action,+ why: step.why,+ waiting: step.waiting?.(facts) ?? null,+ locked: lockedNote(step, facts),+ next: upcoming(facts, put),+ asks: step.asks ?? [],+ near: step.focus !== null && typeof step.focus === "object" && shown.id !== null ? step.focus.kind : null,+ count: courseCount(step),+ at: shown.at,+ size: shown.at?.size ?? 1,+ id: shown.id+ }+ : null,+ done: guideSteps.filter((s) => put.has(s.id)).length,+ total: guideSteps.length,+ off: guide.off+ }+}diff --git a/src/view/icons.ts b/src/view/icons.tsnew file mode 100644index 0000000..e877323--- /dev/null+++ b/src/view/icons.ts@@ -0,0 +1,15 @@+/**+ * Every icon the view can name. The view says which icon a line or a tool+ * shows; each UI draws them its own way (the page: `ui/dom/kit/icons.ts`,+ * which must draw every one).+ */+import type { GoodId } from "../game/content/index.ts"++export const iconIds = [+ "coins", "settlers", "citizens", "people", "jobs", "approval", "clock", "winter", "summer", "crown", "hint", "caution", "locate", "warning", "goal",+ "faith", "food", "trade", "treasury", "taxes", "chronicle", "select", "road", "homes", "build", "bulldoze", "town", "pause", "play", "save", "load",+ "newTown", "close", "more", "layers", "share", "picture", "link", "info", "upkeep", "burghers", "decor", "pave", "fire", "health", "order", "repair",+ "appeal", "condition", "view", "workers"+] as const+/** An icon: one of the town's own, or a good's. */+export type IconName = (typeof iconIds)[number] | GoodIddiff --git a/src/view/interaction/geometry.ts b/src/view/interaction/geometry.tsnew file mode 100644index 0000000..ff2e826--- /dev/null+++ b/src/view/interaction/geometry.ts@@ -0,0 +1,18 @@+/** Cells under the pointer, footprints around it, and the cells a drag covers. */+import type { Point } from "../../game/world/iso.ts"++export const cellAt = (at: Point): Point => {+ return { x: Math.floor(at.x), y: Math.floor(at.y) }+}++/** The footprint `size` cells a side centred on a point, by its top cell. */+export const footprintAt = (at: Point, size: number): Point => {+ return { x: Math.floor(at.x - (size - 1) / 2), y: Math.floor(at.y - (size - 1) / 2) }+}++/** Every cell between two corners, both included. */+export const rectangle = (a: Point, b: Point): Array<Point> => {+ const out: Array<Point> = []+ for (let y = Math.min(a.y, b.y); y <= Math.max(a.y, b.y); y++) for (let x = Math.min(a.x, b.x); x <= Math.max(a.x, b.x); x++) out.push({ x, y })+ return out+}diff --git a/src/view/interaction/gestures.ts b/src/view/interaction/gestures.tsnew file mode 100644index 0000000..52f783e--- /dev/null+++ b/src/view/interaction/gestures.ts@@ -0,0 +1,90 @@+/**+ * The pointer's gestures, turned into what the tool does: a drag lays roads,+ * homes, paving, or park ground; a click places a building, furnishes a park,+ * starts an upgrade, bulldozes, or selects. What changes the town goes to the+ * simulation as an edit.+ */+import { kinds, upgradeAt } from "../../game/content/index.ts"+import type { Edit } from "../../game/edits.ts"+import { lPath } from "../../game/world/grid.ts"+import { inside } from "../../game/world/iso.ts"+import type { Interaction } from "../contracts.ts"+import type { Frame } from "../frame.ts"+import { cellAt, footprintAt, rectangle } from "./geometry.ts"+import { placeProblem } from "./placing.ts"++export const applyGestures = (frame: Frame, ui: Interaction, send: (edit: Edit) => void, toast: (message: string) => void) => {+ const buildings = frame.buildings+ for (const gesture of ui.gestures.splice(0)) {+ const cell = cellAt(gesture.at)+ if (gesture.type === "press") {+ ui.dragFrom = (ui.tool === "road" || ui.tool === "home" || ui.tool === "pave" || ui.tool === "ground") && inside(cell.x, cell.y) ? cell : null+ continue+ }+ switch (ui.tool) {+ case "road":+ case "pave":+ case "home": {+ if (ui.dragFrom) {+ const cells = lPath(ui.dragFrom, cell).filter((c) => inside(c.x, c.y))+ send(ui.tool === "road" ? { type: "roads", cells } : ui.tool === "pave" ? { type: "pave", cells } : { type: "homes", cells })+ }+ ui.dragFrom = null+ break+ }+ case "ground": {+ if (ui.dragFrom) send({ type: "ground", ground: ui.ground, cells: rectangle(ui.dragFrom, cell).filter((c) => inside(c.x, c.y)) })+ ui.dragFrom = null+ break+ }+ case "prop": {+ if (gesture.panned) break+ send({ type: "prop", prop: ui.prop, cell })+ break+ }+ case "place": {+ if (gesture.panned || !ui.placing) break+ const kind = kinds[ui.placing]+ const at = footprintAt(gesture.at, kind.size)+ const problem = placeProblem(frame, kind, { ...at, size: kind.size })+ if (problem?.refuse) {+ toast(`A ${kind.title.toLowerCase()} ${problem.text}`)+ break+ }+ send({ type: "building", kind: ui.placing, cell: at, open: false })+ break+ }+ case "upgrade": {+ // A click on a building of the kind being upgraded begins its works.+ if (gesture.panned) break+ const hit = frame.pickAt(gesture.at, gesture.hit)+ const row = hit !== null ? buildings.find((b) => b.entity.id === hit) : undefined+ const kind = row ? kinds[row.data.building.get().kind] : undefined+ if (!row || !kind || (ui.upgrading && kind.id !== ui.upgrading)) {+ const wanted = ui.upgrading ? (upgradeAt(kinds[ui.upgrading], 0) ? kinds[ui.upgrading].title.toLowerCase() : "building") : "building"+ toast(`Pick a ${wanted} to upgrade`)+ break+ }+ if (row.data.works.present) {+ toast(`The ${kind.title.toLowerCase()} is already being upgraded`)+ break+ }+ send({ type: "upgrade", cell: row.data.tile.get() })+ break+ }+ case "bulldoze": {+ if (gesture.panned) break+ const hit = frame.pickAt(gesture.at, gesture.hit)+ send({ type: "remove", cell: (hit !== null ? frame.tileOf(hit) : undefined) ?? cell })+ break+ }+ case "select": {+ if (gesture.panned) break+ ui.selected = frame.pickAt(gesture.at, gesture.hit)+ if (ui.selected !== null) ui.menu = null+ break+ }+ }+ }+ if (ui.selected !== null && frame.tileOf(ui.selected) === undefined) ui.selected = null+}diff --git a/src/view/interaction/placing.ts b/src/view/interaction/placing.tsnew file mode 100644index 0000000..21bb694--- /dev/null+++ b/src/view/interaction/placing.ts@@ -0,0 +1,27 @@+/** Whether a building may be laid where the pointer is, and why not. */+import type { Kind } from "../../game/content/index.ts"+import { lockReason } from "../../game/schedule.ts"+import { around, canPlace, doors, useAt, type TileLike } from "../../game/world/grid.ts"+import type { Frame } from "../frame.ts"++/**+ * What is wrong with a building where it would stand, before it is laid: no road at the middle of a side (it is+ * not laid: nobody could bring its materials or work there), or nothing in reach to gather (laid, but said).+ */+export const placeProblem = (frame: Frame, kind: Kind, tile: TileLike): { readonly refuse: boolean; readonly text: string } | null => {+ const grid = frame.grid+ if (!canPlace(grid, tile) || lockReason(kind, frame.world.census)) return null+ if (doors(grid, tile).length === 0) return { refuse: true, text: "needs a road at the middle of one side" }+ const source = kind.gathers?.source+ if (!source || source === "field") return null+ const reachCells = around(tile, kind.gathers!.radius)+ const found =+ source === "stone" || source === "ore"+ ? frame.rocks.some(({ data }) => {+ const t = data.tile.get()+ return data.rock.get().ore === (source === "ore") && reachCells.some((c) => c.x >= t.x && c.x < t.x + t.size && c.y >= t.y && c.y < t.y + t.size)+ })+ : reachCells.some((c) => useAt(grid, c.x, c.y) === source)+ const what = { tree: "trees", stone: "pale stone rocks", ore: "dark ore rocks", water: "water" }[source]+ return found ? null : { refuse: false, text: `no ${what} within ${kind.gathers!.radius} cells` }+}diff --git a/src/view/overlay.ts b/src/view/overlay.tsnew file mode 100644index 0000000..46b0271--- /dev/null+++ b/src/view/overlay.ts@@ -0,0 +1,187 @@+/**+ * The map views: desirability, workers, fire, health, order, and condition,+ * each a reading washed over the town cell by cell and over each model, with+ * a legend saying what its colours mean.+ */+import { COMMUTE, condition as wear, home, risk, RISK_MAX } from "../game/content/index.ts"+import { appealAt } from "../game/world/appeal.ts"+import { doors, key, reach, useAt, type TileLike } from "../game/world/grid.ts"+import { GRID } from "../game/world/iso.ts"+import type { Interaction, Legend, OverlayCell, SceneView, TownView, View } from "./contracts.ts"+import type { Frame } from "./frame.ts"++// Blue for fine, sand for worth a look, vermilion for wrong: a scale that still reads with+// red-green colour blindness, unlike green to red.+const GOOD = 0x3a78c2+const FAIR = 0xe2c25c+const BAD = 0xc8553d+/** Citizens' homes, in the workers view. */+const COOL = 0x8a58a8+/** The buildings that serve a view (its fire watch, its healer), and a workplace's reach: ink, apart from the scale. */+const MARK = 0x3d4943+/** A meter 0 → `of` as a colour: blue when low, sand, vermilion past the warning line. */+const meterColor = (value: number, of: number, warn: number) => (value >= warn ? BAD : value >= of * 0.35 ? FAIR : GOOD)++const legends: Readonly<Record<Exclude<View, "none">, Legend>> = {+ appeal: {+ title: "desirability",+ keys: [+ { color: 0x1f4f8f, label: `${home.tiers[3].appeal}+: townhouses` },+ { color: GOOD, label: `${home.tiers[2].appeal}+: citizens` },+ { color: 0xc6d4e4, label: "0 to 4: settlers only" },+ { color: 0xeaa26a, label: "below 0: fewer people, less tax" },+ { color: BAD, label: `${home.squalid} or less: squalid` }+ ],+ note: "Every point counts: a cottage holds fewer and pays less for each point below 0, and pays more above it. Industry pushes homes away; parks (the more they hold, the further they reach), a chapel, a market, and paved streets draw them in."+ },+ workers: {+ title: "workers",+ keys: [+ { color: GOOD, label: "fully staffed" },+ { color: FAIR, label: "short of workers" },+ { color: BAD, label: "no workers" },+ { color: 0xd6b48a, label: "settlers' homes" },+ { color: COOL, label: "citizens' homes" }+ ],+ note: `Residents walk at most ${COMMUTE} road cells to work. Select a workplace to see its reach and the homes inside it.`+ },+ fire: {+ title: "fire",+ keys: [+ { color: GOOD, label: "watched" },+ { color: FAIR, label: "rising" },+ { color: BAD, label: "at risk, or burning" }+ ],+ note: "Buildings take the colour too. A fire watch's watchman resets the risk of every home and workshop along the way; vermilion means past half way, so there is still time. Wooden cottages, ovens, forges, and crowding raise it."+ },+ health: {+ title: "health",+ keys: [+ { color: GOOD, label: "visited" },+ { color: FAIR, label: "rising" },+ { color: BAD, label: "at risk, or sick" }+ ],+ note: "A healer's physician resets the risk and cures the sick. Hunger, crowding, squalor, quarry dust, and still water raise it."+ },+ order: {+ title: "order",+ keys: [+ { color: GOOD, label: "kept" },+ { color: FAIR, label: "rising" },+ { color: BAD, label: "thieves about" }+ ],+ note: "A watch house's constable keeps order. Low approval, squalor, and homes not full raise it; theft first, then the home is left derelict."+ },+ condition: {+ title: "condition",+ keys: [+ { color: GOOD, label: "well kept" },+ { color: FAIR, label: "needs mending" },+ { color: BAD, label: "run down: half pace" }+ ],+ note: "A builder's yard mends what its builder passes with planks and stone. At nothing it falls down."+ }+}+/** 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 }++const appealColor = (v: number) =>+ v >= home.tiers[3].appeal ? 0x1f4f8f : v >= home.tiers[2].appeal ? GOOD : v >= 0 ? 0xc6d4e4 : v > home.squalid ? 0xeaa26a : BAD++/** Rebuilds the map view over the town when what it shows changes (the view, the picked thing, the town, every half second). */+export const drawOverlay = (frame: Frame, ui: Interaction, scene: SceneView, town: TownView) => {+ const { grid, buildings, houses, ruins, cells, tick } = frame+ const pickedBuilding = ui.selected !== null ? buildings.find((row) => row.entity.id === ui.selected) : undefined+ const view = ui.view+ const overlayKey = `${view}|${Math.floor(tick / 30)}|${ui.selected}|${buildings.length}|${houses.length}`+ if (view === "none") {+ if (scene.overlay.key !== "none") scene.overlay = { key: "none", cells: [] }+ if (scene.tints.size > 0) scene.tints = new Map()+ town.legend = null+ } else if (scene.overlay.key !== overlayKey) {+ const out: Array<OverlayCell> = []+ // The same reading washed over each model, so the view is legible where buildings hide the ground.+ const tints = new Map<number, number>()+ const tintOf = (color: number) => (color === GOOD ? TINT.good : color === FAIR ? TINT.fair : color === BAD ? TINT.bad : color === COOL ? TINT.cool : TINT.plain)+ const standing = <T extends { readonly data: { readonly site: { readonly present: boolean }; readonly rising: { readonly present: boolean } } }>(rows: ReadonlyArray<T>) =>+ rows.filter(({ data }) => !data.site.present && !data.rising.present)+ if (view === "appeal") {+ for (let y = 0; y < GRID; y++)+ for (let x = 0; x < GRID; x++) {+ const use = useAt(grid, x, y)+ if (use === "void" || use === "water") continue+ out.push({ x, y, size: 1, color: appealColor(appealAt(cells, x, y)), alpha: 0.32 })+ }+ for (const { entity, data } of standing(houses)) {+ const t = data.tile.get()+ const d = appealAt(cells, t.x, t.y)+ tints.set(entity.id, d >= home.tiers[2].appeal ? TINT.fine : d >= 0 ? TINT.plain : d > home.squalid ? TINT.fair : TINT.bad)+ }+ } else if (view === "workers") {+ const picked = pickedBuilding && pickedBuilding.data.staff.get().needed > 0 ? pickedBuilding : undefined+ let inReach: ((t: TileLike) => boolean) | null = null+ if (picked) {+ const roads = reach(grid, doors(grid, picked.data.tile.get()))+ for (let k = 0; k < roads.distance.length; k++) {+ const d = roads.distance[k]!+ if (d >= 0 && d <= COMMUTE) out.push({ x: k % GRID, y: Math.floor(k / GRID), size: 1, color: MARK, alpha: 0.14 })+ }+ inReach = (t) => doors(grid, t).some((c) => {+ const n = roads.distance[key(c.x, c.y)]!+ return n >= 0 && n <= COMMUTE+ })+ }+ for (const { entity, data } of standing(houses)) {+ const t = data.tile.get()+ const h = data.house.get()+ const ring = inReach !== null && inReach(t)+ out.push({ ...t, color: h.tier === 1 ? 0xd6b48a : COOL, alpha: ring ? 0.75 : 0.45, ...(ring ? { ring: true } : {}) })+ tints.set(entity.id, h.tier === 1 ? TINT.settlers : TINT.cool)+ }+ for (const { entity, data } of standing(buildings)) {+ const s = data.staff.get()+ if (s.needed === 0) continue+ const color = s.assigned >= s.needed ? GOOD : s.assigned > 0 ? FAIR : BAD+ out.push({ ...data.tile.get(), color, alpha: 0.45, ...(entity.id === picked?.entity.id ? { ring: true } : {}) })+ tints.set(entity.id, tintOf(color))+ }+ } else if (view === "fire" || view === "health" || view === "order") {+ for (const { entity, data } of standing(houses)) {+ const r = data.risk.value()+ if (!r) continue+ const struck = view === "fire" ? data.burning.present : view === "health" ? data.sick.present : r.thefts > 0+ const color = struck ? BAD : meterColor(r[view], RISK_MAX, risk.warn)+ out.push({ ...data.tile.get(), color, alpha: struck ? 0.8 : 0.5 })+ tints.set(entity.id, tintOf(color))+ }+ for (const { entity, data } of standing(buildings)) {+ const service = data.service.value()?.service+ const r = data.risk.value()+ if (service === view) {+ out.push({ ...data.tile.get(), color: MARK, alpha: 0.55, ring: true })+ tints.set(entity.id, TINT.mark)+ } else if (view === "fire" && r) {+ const color = data.burning.present ? BAD : meterColor(r.fire, RISK_MAX, risk.warn)+ out.push({ ...data.tile.get(), color, alpha: 0.4 })+ tints.set(entity.id, tintOf(color))+ }+ }+ } else if (view === "condition") {+ for (const row of [...standing(houses), ...standing(buildings)]) {+ const c = row.data.condition.value()+ if (!c) continue+ const color = c.value < wear.worn ? BAD : c.value < wear.mend ? FAIR : GOOD+ out.push({ ...row.data.tile.get(), color, alpha: 0.5 })+ tints.set(row.entity.id, tintOf(color))+ }+ for (const { entity, data } of standing(buildings)) if (data.service.value()?.service === "repair") {+ out.push({ ...data.tile.get(), color: MARK, alpha: 0.55, ring: true })+ tints.set(entity.id, TINT.mark)+ }+ for (const { data } of ruins) out.push({ ...data.tile.get(), color: BAD, alpha: 0.8 })+ }+ scene.overlay = { key: overlayKey, cells: out }+ scene.tints = tints+ town.legend = legends[view]+ }+}diff --git a/src/view/panels/building.ts b/src/view/panels/building.tsnew file mode 100644index 0000000..0ce6681--- /dev/null+++ b/src/view/panels/building.ts@@ -0,0 +1,180 @@+/** A building's panel: what it is doing and what it costs, its upgrade, and what pulling it down gives back. */+import {+ amounts, builtCost, COMMUTE, condition as wear, CONDITION_MAX, goodIds, goods, kinds, nextUpgrade, provisions, ranks, risk, RISK_MAX, upgradeAt, upkeepOf, anA, costText, type GoodId+} from "../../game/content/index.ts"+import type { Cause } from "../../game/rules/explain.ts"+import { upgradeChanges, upgradePrice } from "../../game/rules/upgrades.ts"+import { upgradeBlock } from "../../game/schedule.ts"+import type { Group, Line, Panel } from "../contracts.ts"+import { growingNear, problemOf, riskText, salvageFor, worksShare, type Problem } from "../facts.ts"+import type { BuildingRow, Frame } from "../frame.ts"+import { percent, signed } from "../text.ts"++/** A cause as a row's note and fix. */+export const told = (frame: Frame, c: Cause | null) => (c ? { note: c.why, fix: frame.fixOf(c.fix) } : {})++/**+ * A building, for its panel: what it is doing (workers, what it makes, what it holds), then what it costs to run+ * (upkeep, wear, fire, its street). Each row is a value; a note only when something wants doing.+ */+export const describeBuilding = (frame: Frame, row: BuildingRow) => {+ const grid = frame.grid+ const kind = kinds[row.data.building.get().kind]+ const status = row.data.status.get()+ const site = row.data.site.value()+ if (site) {+ const owed = (Object.entries(site.owed) as Array<[GoodId, number]>).filter(([, n]) => n > 0)+ const line: Line =+ owed.length > 0+ ? { icon: "build", label: "waiting for", goods: owed.map(([good, count]) => ({ good, count })), tone: "warn", note: "carriers bring them from storage: buy what the town lacks in the town panel" }+ : { icon: "build", label: "builders", value: "at work", tone: "ok" }+ return { kind, status, problem: null, state: { icon: "build", label: "being built", tone: "warn" } as Line, groups: [{ title: "being built", icon: "build", lines: [line] }] as Array<Group> }+ }+ const staff = row.data.staff.get()+ const work: Array<Line> = []+ if (staff.needed > 0) {+ const crew = kind.crew+ const short = staff.assigned < staff.needed+ work.push({+ icon: "workers",+ label: "workers",+ value: `${staff.assigned} of ${staff.needed}`,+ tone: !short ? "ok" : staff.assigned > 0 ? "warn" : "bad",+ note: short+ ? staff.nearby === 0+ ? `no ${crew} live within ${COMMUTE} road cells: lay homes nearer`+ : `everyone nearby has a job: lay more homes within ${COMMUTE} road cells`+ : staff.apprentices > 0+ ? `settlers stand in for citizens, at three-quarters pace`+ : undefined+ })+ }+ const recipe = row.data.recipe.value()+ if (recipe)+ work.push({ icon: recipe.output, label: "makes", value: recipe.input ? `${goods[recipe.input].title} → ${goods[recipe.output].title}` : goods[recipe.output].title })+ const service = row.data.service.value()+ if (service)+ work.push({+ icon: service.service === "goods" ? "trade" : service.service === "faith" ? "faith" : service.service === "repair" ? "repair" : service.service,+ label: "walkers out",+ value: `${row.data.walkers.value()?.length ?? 0}`+ })+ // A provisions walker's building: what its walkers handed to homes over the last minute, which its shelf+ // alone cannot say (food leaves in the basket as soon as it comes; furniture mostly comes back).+ if (service?.service === "goods") {+ const log = frame.world.handed.log.filter((l) => l.from === row.entity.id)+ const given: Record<GoodId, number> = { ...amounts({}) }+ for (const l of log) for (const [g, n] of Object.entries(l.goods) as Array<[GoodId, number]>) given[g] += n+ const homesFed = new Set(log.map((l) => l.to)).size+ work.push(+ homesFed > 0+ ? { icon: "people", label: "handed out, last minute", goods: provisions.filter((g) => given[g] > 0).map((g) => ({ good: g, count: given[g] })),+ note: `to ${homesFed} home${homesFed === 1 ? "" : "s"} on its walks` }+ : { icon: "people", label: "handed out, last minute", value: "nothing", tone: "dim", note: "no home on its walks needed what it had" }+ )+ }+ const inventory = row.data.inventory.value()+ if (inventory) {+ const held = inventory.accepts.filter((g) => inventory.stock[g] > 0).map((g) => ({ good: g, count: inventory.stock[g] }))+ // A market's shelf is only what waits for the next walker.+ const label = kind.id === "market" ? "on the shelf now" : "holds"+ work.push(held.length > 0 ? { icon: "jobs", label, goods: held } : { icon: "jobs", label, value: "nothing", tone: "dim" })+ }+ if (kind.wear && inventory)+ work.push(+ inventory.stock.tools > 0+ ? { icon: "tools", label: "tools", value: `${inventory.stock.tools}`, tone: "ok" }+ : { icon: "tools", label: "tools", value: "none", tone: "bad", note: "half pace until one comes: a smithy makes them, or buy them in the town panel" }+ )+ const running: Array<Line> = []+ const level = row.data.upgraded.value()?.level ?? 0+ const upkeep = upkeepOf(kind, level)+ if (upkeep > 0) running.push({ icon: "upkeep", label: "upkeep", value: `${upkeep} coins a minute` })+ const condition = row.data.condition.value()+ if (condition)+ running.push({+ icon: "condition",+ label: "condition",+ value: percent(condition.value, CONDITION_MAX),+ tone: condition.value < wear.worn ? "bad" : condition.value < wear.mend ? "warn" : "ok",+ note: condition.value < wear.worn ? "half pace, and it may fall: a builder's yard mends it" : condition.value < wear.mend ? "a builder's yard mends it as its builder passes" : undefined+ })+ const r = row.data.risk.value()+ if (r)+ running.push({+ icon: "fire",+ label: "fire risk",+ value: riskText(r.fire),+ tone: r.fire >= risk.warn ? "bad" : r.fire >= RISK_MAX * 0.35 ? "warn" : "ok",+ note: r.fire >= RISK_MAX * 0.35 ? "a fire watch's watchman lowers it as he passes" : undefined+ })+ const appealHere = upgradeAt(kind, level)?.appeal ?? kind.appeal+ if (appealHere) running.push({ icon: "appeal", label: "desirability nearby", value: signed(appealHere.value) })+ const help = [+ upkeep > 0 ? "Upkeep is paid every minute it stands, a quarter of it while paused." : "",+ condition ? "Everything wears down; a builder's yard mends it." : "",+ kind.hot ? "An oven or a forge: a fire risk to itself and to homes within 2 cells." : "",+ appealHere ? `It changes how nice the streets are out to ${appealHere.reach} cells${appealHere.value < 0 ? ": homes close by hold fewer people and pay less" : ""}.` : ""+ ]+ .filter((t) => t !== "")+ .join(" ")+ const groups: Array<Group> = [+ ...(work.length > 0 ? [{ title: "at work", icon: "jobs", lines: work } as Group] : []),+ ...(running.length > 0 ? [{ title: "running it", icon: "coins", help, lines: running } as Group] : [])+ ]+ const growing = status === "starved" && growingNear(grid, row.data.tile.get(), kind, frame.rockAt)+ const trouble: Problem | null = row.data.burning.present+ ? { label: "on fire!", why: "its crew has fled", fix: { text: "a fire watch's watchmen put fires out", build: ["firewatch"] } }+ : problemOf(kind, status, growing, { nearby: staff.nearby, crew: kind.crew })+ const state: Line = trouble+ ? { icon: "warning", label: trouble.label, tone: "bad", note: trouble.why, fix: frame.fixOf(trouble.fix) }+ : { icon: status === "working" ? "jobs" : "clock", label: status === "working" ? "working" : status, tone: status === "working" ? "ok" : undefined }+ return { kind, status, problem: trouble ? `${trouble.label}: ${trouble.why}` : null, state, groups }+}++/** The panel of a building that is picked; `needed`: why the town needs its upgrade now, if it does. */+export const buildingPanel = (frame: Frame, row: BuildingRow, needed: string | null): Panel => {+ const { kind, status, problem, state, groups } = describeBuilding(frame, row)+ const standing = !row.data.site.present && !row.data.rising.present+ const pausable = kind.id !== "townhall" && standing+ const level = row.data.upgraded.value()?.level ?? 0+ const now = upgradeAt(kind, level)+ const works = row.data.works.value()+ const up = works ? undefined : nextUpgrade(kind, level)+ const coins = frame.world.treasury.coins+ const upgradeOffer = up && standing+ ? { title: up.title, blurb: up.blurb, price: upgradePrice(up), cost: up.cost, changes: upgradeChanges(kind, level), needed,+ blocked: upgradeBlock(up, frame.world.fate.rank, { ranks }),+ short: coins < up.cost.coins ? `${up.cost.coins - coins} coins short` : null }+ : null+ // An upgrade under way: what it is to become, and what carriers still have to bring.+ const worksOf = works+ ? { title: upgradeAt(kind, works.level)!.title, share: worksShare(works)!,+ left: costText({ coins: 0, materials: Object.fromEntries(goodIds.filter((g) => works.owed[g] > 0).map((g) => [g, works.owed[g]])) }) }+ : null+ if (worksOf)+ groups.unshift({+ title: `becoming ${anA(worksOf.title.toLowerCase())}`,+ icon: "build",+ lines: [{ icon: "build", label: "built", value: `${Math.round(worksOf.share * 100)}%`, tone: "warn", note: worksOf.left ? `carriers still bring ${worksOf.left}; it works on meanwhile` : "every material is in; the builders are working it in, and it works on meanwhile" }]+ })+ return {+ type: "building",+ id: row.entity.id,+ cell: row.data.tile.get(),+ kind: kind.id,+ title: now?.title ?? kind.title,+ blurb: now?.blurb ?? kind.blurb,+ status,+ problem,+ state,+ groups,+ pausable,+ paused: row.data.paused.present,+ salvage: salvageFor(builtCost(kind, level), row.data.site.value(), works && { kind, ...works }),+ level,+ upgraded: level > 0,+ upgrade: upgradeOffer,+ works: worksOf+ }+}diff --git a/src/view/panels/house.ts b/src/view/panels/house.tsnew file mode 100644index 0000000..b108084--- /dev/null+++ b/src/view/panels/house.ts@@ -0,0 +1,216 @@+/** A home's panel: its household, what it needs and why it lacks it, and its risks and wear. */+import { COMMUTE, condition as wear, CONDITION_MAX, costText, crewOf, home, kinds, RISK_MAX, risk, type Need, type Tier } from "../../game/content/index.ts"+import { needTitle } from "../../game/content/index.ts"+import { blockers as blockersOf, causeOf, servicesCause, streetAdvice, streetShort, type InTown, type Served, type Street } from "../../game/rules/explain.ts"+import { shortOf, suppliedTaxOf } from "../../game/rules/households.ts"+import { capacity, met, taxOf } from "../../game/schedule.ts"+import { appealAt, appealParts } from "../../game/world/appeal.ts"+import { doors, key, nearest, reach, type TileLike } from "../../game/world/grid.ts"+import type { Group, Line, Panel } from "../contracts.ts"+import { riskText, salvageFor } from "../facts.ts"+import type { Frame, HouseRow } from "../frame.ts"+import { percent, signed } from "../text.ts"+import { told } from "./building.ts"++const needIcons = { food: "food", bread: "bread", cloth: "cloth", faith: "faith", furniture: "furniture" } as const++/** Where a home's residents work: the nearest workplace of their crew in reach that has them. */+const workOf = (frame: Frame, tile: TileLike, tier: Tier) => {+ const { grid, buildings } = frame+ const ds = doors(grid, tile)+ if (ds.length === 0) return null+ const roads = reach(grid, ds)+ let best: { title: string; distance: number } | null = null+ for (const { data } of buildings) {+ const kind = kinds[data.building.get().kind]+ const staff = data.staff.get()+ if (staff.needed === 0 || staff.assigned === 0 || (kind.crew !== crewOf(tier) && !(tier === 1 && staff.apprentices > 0))) continue+ for (const d of doors(grid, data.tile.get())) {+ const n = roads.distance[key(d.x, d.y)]!+ if (n >= 0 && n <= COMMUTE && (best === null || n < best.distance)) best = { title: kind.title.toLowerCase(), distance: n }+ }+ }+ return best+}+/** What the town has of each provision, in storage and on market shelves. */+const inTown = (frame: Frame): InTown => {+ const stock = frame.world.stock+ const sum = { fish: stock.fish, smoked: stock.smoked, bread: stock.bread, cloth: stock.cloth, furniture: stock.furniture }+ for (const { data } of frame.buildings) {+ const inv = data.inventory.value()+ if (!inv || data.service.value()?.service !== "goods" || data.site.present || data.rising.present) continue+ sum.fish += inv.stock.fish+ sum.smoked += inv.stock.smoked+ sum.bread += inv.stock.bread+ sum.cloth += inv.stock.cloth+ sum.furniture += inv.stock.furniture+ }+ return sum+}+/** Which services have a walker that can reach a home: a standing market (or the town hall), and a chapel, within their walks of its door. */+const servedAt = (frame: Frame, tile: TileLike): Served => {+ const { grid, buildings } = frame+ const ds = doors(grid, tile)+ if (ds.length === 0) return { goods: false, faith: false }+ const way = reach(grid, ds)+ const served = { goods: false, faith: false }+ for (const { data } of buildings) {+ const service = data.service.value()+ if (!service || data.site.present || data.rising.present || data.burning.present) continue+ if (service.service !== "goods" && service.service !== "faith") continue+ if (served[service.service]) continue+ const found = nearest(way, doors(grid, data.tile.get()))+ if (found && found.distance < service.range) served[service.service] = true+ }+ return served+}+/**+ * A home, for its panel: its household (who lives there, what it pays, where they work); what it needs, as one+ * checklist with what it lacks now in red and what it lacks to grow in amber, each with its cause; and its risks+ * and wear. Each row is a value; a note only when something wants doing.+ */+export const describeHouse = (frame: Frame, row: HouseRow) => {+ const { cells, approval, rates } = frame+ const h = row.data.house.get()+ const site = row.data.site.value()+ const quiet = (summary: string, line: Line) => ({ h, summary, trouble: false, groups: [{ title: "household", icon: "homes", lines: [line] }] as Array<Group> })+ if (site) return quiet("being built", { icon: "planks", label: "builders", value: "waiting for its plank", tone: "warn" })+ if (row.data.closed.present)+ return quiet("closed", { icon: "settlers", label: "closed", value: "empty", tone: "warn", note: "it pays no taxes and costs the town hall nothing: reopen it and settlers move back in" })+ const tile = row.data.tile.get()+ const tier = home.tiers[h.tier]+ const nextTier = h.tier < 3 ? ((h.tier + 1) as Tier) : null+ const there = appealParts(frame.appealSources(), tile)+ const desirability = appealAt(cells, tile.x, tile.y)+ const street: Street = { desirability, parts: there.parts }+ const r = row.data.risk.value()+ const work = workOf(frame, tile, h.tier)+ const condition = row.data.condition.value()+ const town = inTown(frame)+ const served = servedAt(frame, tile)+ const rate = h.tier === 1 ? rates.settlers : rates.citizens+ const cap = capacity(h, approval, desirability, undefined, rate)+ const whyFewer =+ cap >= tier.residents+ ? undefined+ : row.data.sick.present+ ? "half as many while it is sick"+ : approval < 0+ ? "fewer while the town disapproves of its mayor"+ : desirability < 0+ ? `fewer on a poor street: ${streetAdvice(street)}`+ : rate > 100 && capacity(h, approval, desirability) > cap+ ? `fewer while taxed at ${rate}%: some move away`+ : "fewer until every need is met"+ const hungry = h.food <= 0+ const pays = Math.round(taxOf(h, rates, undefined, desirability))+ const could = Math.round(suppliedTaxOf(h, rates, undefined, desirability))+ const household: Array<Line> = [+ ...(row.data.burning.present ? [{ icon: "fire", label: "on fire", value: "everyone fled", tone: "bad" } as Line] : []),+ ...(row.data.sick.present ? [{ icon: "health", label: "sick", value: "half as many", tone: "bad", note: "it passes in a minute, or when a healer's physician calls" } as Line] : []),+ { icon: "people", label: "residents", value: `${h.residents} of ${cap}`, tone: whyFewer ? "warn" : "ok", note: whyFewer },+ {+ icon: "coins",+ label: "pays",+ value: `${pays} coins a minute`,+ tone: hungry ? "bad" : undefined,+ note: hungry ? "hungry: no food, no taxes" : could > pays ? `${could} coins a minute with every need met` : undefined+ },+ work ? { icon: "jobs", label: "works at", value: `${work.title.toLowerCase()}` } : { icon: "jobs", label: "works at", value: "nothing nearby", tone: "dim" }+ ]+ // What it needs: what it must have now, then what it must have to grow, in the order the town makes them.+ const needs: Array<Line> = []+ const nowNeeds = new Set<Need>(tier.needs)+ const growNeeds = new Set<Need>(nextTier ? home.tiers[nextTier].needs : [])+ for (const n of ["food", "bread", "cloth", "faith", "furniture"] as const) {+ if (!nowNeeds.has(n) && !growNeeds.has(n)) continue+ if (met(h, n)) {+ needs.push({ icon: needIcons[n], label: needTitle[n], value: "✓", tone: "ok" })+ continue+ }+ const now = nowNeeds.has(n)+ needs.push({+ icon: needIcons[n],+ label: needTitle[n],+ value: now ? "missing" : `for ${home.tiers[nextTier!].title}`,+ tone: now ? "bad" : "warn",+ ...told(frame, causeOf(n, h, street, town, served))+ })+ }+ const blocks = blockersOf(h, street, town, served, r)+ const streetBlock = blocks.find((b) => b.what === "street")+ if (nextTier)+ needs.push({+ icon: "appeal",+ label: "street",+ value: streetBlock ? `${signed(desirability)} of ${home.tiers[nextTier].appeal}` : "✓",+ tone: streetBlock ? "warn" : "ok",+ ...(streetBlock ? { note: streetShort(street, home.tiers[nextTier].appeal), fix: { text: streetAdvice(street) } } : {})+ })+ else needs.push({ icon: "appeal", label: "street", value: signed(desirability), tone: "ok" })+ if (blocks.some((b) => b.what === "services")) needs.push({ icon: "order", label: "services", value: `for ${home.tiers[3].title}`, tone: "warn", ...told(frame, servicesCause(r)) })+ // Rising is a rebuilding, paid at once from the treasury and the store, once.+ const rebuilt = nextTier !== null && (row.data.rebuilt.value()?.tier ?? 1) >= nextTier+ const short = nextTier && !rebuilt ? shortOf(home.tiers[nextTier].rise, frame.world.treasury.coins, frame.world.stock) : null+ if (nextTier)+ needs.push({+ icon: "upkeep", label: "rebuilding", value: rebuilt ? "done ✓" : costText(home.tiers[nextTier].rise), tone: short ? "warn" : "ok",+ ...(short+ ? { note: `the town is short of ${short}`, fix: { text: "it waits at its tier until the store holds it: make it, or buy it in the [town] panel" } }+ : rebuilt ? { note: "rebuilt already: it rises back for nothing" } : {})+ })+ if (nextTier && blocks.length === 0 && !short)+ needs.push({ icon: "citizens", label: `ready for ${home.tiers[nextTier].title}`, value: "✓", tone: "ok", note: "it grows as the next resident moves in, and pays for its rebuilding then" })+ const risky = r ? (["fire", "health", "order"] as const).filter((k) => r[k] >= RISK_MAX * 0.35) : []+ const cure = { fire: "a fire watch's watchman lowers it", health: "a healer's physician lowers it", order: "a watch house's constable lowers it" } as const+ const safety: Array<Line> = [+ ...(r && risky.length === 0 ? [{ icon: "fire", label: "risks", value: "all low", tone: "ok" } as Line] : []),+ ...risky.map(+ (k): Line => ({+ icon: k,+ label: `${k === "order" ? "theft" : k} risk`,+ value: riskText(r![k]),+ tone: r![k] >= risk.warn ? "bad" : "warn",+ note: cure[k]+ })+ ),+ ...(r && r.thefts > 0 ? [{ icon: "order", label: "robbed", value: `${r.thefts}×`, tone: "warn" } as Line] : []),+ ...(condition+ ? [{+ icon: "condition",+ label: "condition",+ value: percent(condition.value, CONDITION_MAX),+ tone: condition.value < wear.worn ? "bad" : condition.value < wear.mend ? "warn" : "ok",+ note: condition.value < wear.worn ? "it drags the street down and may fall: a builder's yard mends it" : condition.value < wear.mend ? "a builder's yard mends it as its builder passes" : undefined+ } as Line]+ : [])+ ]+ const needHelp =+ h.tier === 1+ ? `Red: it needs this now. Amber: it needs this to become a citizens' home, which holds and pays twice as much. Bread alone already makes a cottage pay half again. Walkers bring needs along the road; the street is how nice the place is (desirability ${home.tiers[2].appeal} for citizens).`+ : h.tier === 2+ ? `Red: it needs this now, or goes back to settlers. Amber: it needs this to become a townhouse of burghers, on a street of ${home.tiers[3].appeal} with a fire watch, a healer, and a watch house all calling.`+ : "Red: it needs this now, or goes back to citizens."+ const summary = row.data.burning.present ? "on fire" : row.data.sick.present ? "sick" : hungry ? "hungry" : `${h.residents} resident${h.residents === 1 ? "" : "s"}`+ return {+ h,+ summary,+ trouble: row.data.burning.present || row.data.sick.present || hungry,+ groups: [+ { title: "household", icon: "homes", lines: household },+ { title: "needs", icon: "citizens", help: needHelp, lines: needs },+ { title: "risks and wear", icon: "condition", help: "Every home's risk of fire, sickness, and theft rises slowly; a walker from the matching service lowers it as it passes.", lines: safety }+ ] as Array<Group>+ }+}++/** The panel of a home that is picked. */+export const housePanel = (frame: Frame, row: HouseRow): Panel => {+ const { h, summary, trouble, groups } = describeHouse(frame, row)+ return {+ type: "house", id: row.entity.id, cell: row.data.tile.get(), tier: h.tier, summary, trouble, groups,+ closable: !row.data.site.present && !row.data.rising.present && !row.data.burning.present,+ closed: row.data.closed.present,+ salvage: salvageFor(home.cost, row.data.site.value())+ }+}diff --git a/src/view/panels/index.ts b/src/view/panels/index.tsnew file mode 100644index 0000000..9034f18--- /dev/null+++ b/src/view/panels/index.ts@@ -0,0 +1,26 @@+/**+ * The side panel: what is picked (a building, a home, a park, a ruin), or+ * else the menu the toolbar opened.+ */+import type { Interaction, Panel } from "../contracts.ts"+import type { Frame } from "../frame.ts"+import { buildingPanel } from "./building.ts"+import { housePanel } from "./house.ts"+import { parkPanel } from "./park.ts"+import { ruinPanel } from "./ruin.ts"++/** `wanted`: why the town needs each building's upgrade now (see `upgradesWanted`). */+export const panelOf = (frame: Frame, ui: Interaction, wanted: () => ReadonlyMap<number, string>): Panel | null => {+ const picked = ui.selected+ if (picked === null) return ui.menu ? { type: ui.menu } : null+ const building = frame.buildings.find((row) => row.entity.id === picked)+ if (building) return buildingPanel(frame, building, wanted().get(building.entity.id) ?? null)+ const house = frame.houses.find((row) => row.entity.id === picked)+ if (house) return housePanel(frame, house)+ const park = frame.parkRows.find((row) => row.entity.id === picked)+ const parkShown = park ? parkPanel(frame, park) : null+ if (parkShown) return parkShown+ const ruin = park ? undefined : frame.ruins.find((row) => row.entity.id === picked)+ if (ruin) return ruinPanel(ruin)+ return ui.menu ? { type: ui.menu } : null+}diff --git a/src/view/panels/park.ts b/src/view/panels/park.tsnew file mode 100644index 0000000..4518d83--- /dev/null+++ b/src/view/panels/park.ts@@ -0,0 +1,43 @@+/** A park's panel: what it is worth, why, and what would make it better. */+import { grounds, propIds, props } from "../../game/content/index.ts"+import type { ParkValue } from "../../game/world/appeal.ts"+import type { Line, Panel } from "../contracts.ts"+import type { Frame, ParkRow } from "../frame.ts"+import { signed } from "../text.ts"++/** What a park does for the streets around it. */+export const parkText = (p: ParkValue) => `desirability ${signed(p.value)} out to ${p.reach} cells`++/** A park, for its panel: what it is worth, why, and what would make it better. */+const describePark = (p: ParkValue): Array<Line> => {+ const has = new Set(p.cells.map((c) => c.prop))+ const missing = propIds.filter((id) => !has.has(id)).map((id) => props[id].title.toLowerCase())+ const upkeep = p.cells.reduce((n, c) => n + grounds[c.ground].upkeep + (c.prop === "none" ? 0 : props[c.prop].upkeep), 0)+ const placed = p.cells.filter((c) => c.prop !== "none").length - p.crowded+ return [+ { icon: "decor", label: "size", value: `${p.cells.length} cell${p.cells.length === 1 ? "" : "s"} · beauty ${p.beauty}` },+ { icon: "appeal", label: "made of", value: p.parts.map((part) => `${part.label} ${part.value}`).join(", ") || "nothing yet" },+ { icon: "homes", label: "the streets around", value: parkText(p), tone: "ok" },+ p.entrances > 0+ ? { icon: "road", label: "ways in from the street", value: `${p.entrances}${p.entrances > 2 ? " (2 count)" : ""}` }+ : { icon: "road", label: "ways in from the street", value: "none", tone: "warn", note: "lay a gravel walk or a paved square out to a road: +1.5 each, two count" },+ { icon: "decor", label: "furnishings that count", value: `${placed} of ${Math.floor(p.cells.length / 2)}`, tone: p.crowded > 0 ? "warn" : undefined, note: p.crowded > 0 ? `${p.crowded} too many: one counts for every 2 cells of park, so lay more ground` : undefined },+ ...(missing.length > 0 ? [{ icon: "info", label: "nicer with", value: missing.join(", "), tone: "dim" } as Line] : []),+ { icon: "upkeep", label: "upkeep", value: `${Math.round(upkeep * 10) / 10} coins a minute` }+ ]+}++/** The panel of a park that is picked: the whole park the cell belongs to, or `null` if it is not one. */+export const parkPanel = (frame: Frame, row: ParkRow): Panel | null => {+ const picked = frame.parkOf(row.data.tile.get())+ if (!picked) return null+ return {+ type: "park",+ id: row.entity.id,+ cell: row.data.tile.get(),+ cells: picked.cells.length,+ value: picked.value,+ reach: picked.reach,+ lines: describePark(picked)+ }+}diff --git a/src/view/panels/ruin.ts b/src/view/panels/ruin.tsnew file mode 100644index 0000000..5564646--- /dev/null+++ b/src/view/panels/ruin.ts@@ -0,0 +1,17 @@+/** A ruin's panel: what happened to it, and what it does to the streets until it is cleared. */+import type { Panel } from "../contracts.ts"+import type { RuinRow } from "../frame.ts"++export const ruinPanel = (row: RuinRow): Panel => {+ const r = row.data.ruin.get()+ return {+ type: "ruin",+ id: row.entity.id,+ cell: row.data.tile.get(),+ cause: r.cause,+ lines: [+ { icon: "condition", label: "what happened", value: r.cause === "burnt" ? "it burned down" : r.cause === "collapsed" ? "it fell down for want of mending" : "it was left derelict after its thefts", tone: "bad" },+ { icon: "appeal", label: "desirability nearby", value: "−3", tone: "warn", note: "until it is cleared: bulldoze it" }+ ]+ }+}diff --git a/src/view/present.ts b/src/view/present.tsdeleted file mode 100644index cb05705..0000000--- a/src/view/present.ts+++ /dev/null@@ -1,2111 +0,0 @@-/**- * What runs once a frame, after the simulation's steps: the pointer's- * gestures become a selection, a preview, and edits for the next step; the- * panel, tooltip, top bar, map views, and the town's alerts are filled in;- * and the views follow the world.- */-import { RenderSync } from "@typeonce/ritmo-render"-import { hazardStrength } from "../render/three/surface-state.ts"--import { appealAt, appealParts, buildingSource, homeSource, landSource, parkSources, parksOf, type AppealSource, type ParkCell, type ParkValue } from "../game/world/appeal.ts"-import { homeHeight, topOf, type Alert, type Load, type Emphasis } from "../render/art.ts"-import { BuildingView, HouseView, WalkerView, TreeView, RockView, FieldView, RuinView } from "../render/three/views.ts"-import type { DoorSet, OverlayCell } from "../render/three/models.ts"-import {- amounts, BUILD_TICKS, builtCost, COMMUTE, provisions, RESTOCK_TICKS, step, condition as wear, CONDITION_MAX, costText, crewOf, crown as crownRules, fate, goodIds, goods, grounds, home, kinds, needTitle,- kindOrder, nextUpgrade, worksNeeded, PAVE_COST, propIds, props, ranks, risk, RISK_MAX, ROAD_COST, tierHome, total, upgradeAt, upkeepOf, winters, type Amounts, type GoodId, type Kind, type KindId, type Need, type Tier-} from "../game/content/index.ts"-import { around, canPlace, cellOf, doors, entrances, isRoad, key, lPath, nearest, reach, useAt, type TileLike } from "../game/world/grid.ts"-import { GRID, inside, U, type Point } from "../game/world/iso.ts"-import {- Appeal,- Building,- BuildingNodes,- Selection,- Toast,- Burning,- Census,- Charter,- Chronicle,- Clock,- Condition,- Crown,- Errand,- Fate,- Field,- FieldNodes,- Figure,- Game,- Grid,- Guide,- History,- House,- HouseNodes,- Inventory,- Land,- Ledger,- Market,- Mood,- Pantry,- Park,- Paused,- Upgraded,- Works,- Paved,- Policy,- Recipe,- Rescue,- Rebuilt, Rising,- Risk,- Road,- Roam,- Rock,- RockNodes,- Route,- Ruin,- RuinNodes,- Service,- Sick,- Site,- Staff,- StageService,- Status,- Stock,- Flow,- Handed,- Tile,- Time,- TownHall,- Treasury,- Tree,- TreeNodes,- Ui,- WalkerNodes,- WalkerOf,- Water,- type GridValue,- type Status as StatusValue-} from "../game/schema.ts"-import { capacity, CELL_STEPS, elapsed, goalsOf, larder, lockReason, met, seasonAt, SITE_SHARE, steadyNet, taxOf, termTicks, upgradeBlock, winterOf } from "../game/schedule.ts"-import { Townsfolk } from "../render/three/townsfolk.ts"-import { emptyPreview, type Alert as Notice, type Group, type HitBox, type Legend, type Line, type View } from "./contracts.ts"-import { blockers as blockersOf, causeOf, servicesCause, streetAdvice, streetShort, type Cause, type Fix, type InTown, type Served, type Street } from "../game/rules/explain.ts"-import { upgradeChanges, upgradePrice } from "../game/rules/upgrades.ts"-import { breadBonus, moreAdmin, shortOf, streetTax, suppliedTaxOf, taxOutlook, type TaxedHome } from "../game/rules/households.ts"-import { approvalTarget } from "../game/rules/approval.ts"-import { salvageOf, salvageText, withWorks } from "../game/rules/salvage.ts"-import { rockBlocks, type RockPart } from "../render/three/rock-blocks.ts"-import { courseCount, GUIDE_QUIET, guideDone, guideStep, guideSteps, lockedNote, upcoming, type GuideFacts, type GuideFocus } from "../game/rules/guide.ts"-import { anA, TAX_STEPS, stepsOf } from "../game/content/index.ts"--const cellAt = (at: Point): Point => {- return { x: Math.floor(at.x), y: Math.floor(at.y) }-}--/** The footprint `size` cells a side centred on a point, by its top cell. */-const footprintAt = (at: Point, size: number): Point => {- return { x: Math.floor(at.x - (size - 1) / 2), y: Math.floor(at.y - (size - 1) / 2) }-}--/** A thing's hit area: its footprint on the floor, or its body as drawn. */-const hitBox = (id: number, tile: TileLike, _half: number, _height: number): HitBox => ({- id,- depth: tile.x + tile.y + tile.size,- contains: (at) => at.x >= tile.x && at.x <= tile.x + tile.size && at.y >= tile.y && at.y <= tile.y + tile.size-})-const hitAt = (hits: ReadonlyArray<HitBox>, at: Point, entity?: number | null) =>- entity === undefined ? (hits.find((h) => h.contains(at))?.id ?? null) : entity--/** Doors follow road entrances on all four sides as the camera turns. */-const doorsOf = (grid: GridValue, tile: TileLike): DoorSet => {- const open = entrances(tile).filter((c) => isRoad(grid, c.x, c.y))- return {- right: open.some((c) => c.side === 0),- left: open.some((c) => c.side === 1),- backRight: open.some((c) => c.side === 2),- backLeft: open.some((c) => c.side === 3)- }-}--/** How far a kind's work reaches, if it works the land around it. */-const reachOf = (kind: Kind): number | null => kind.gathers?.radius ?? kind.plants?.radius ?? null--const sourceTitle = { tree: "grown trees", stone: "stone", ore: "ore", field: "ripe fields", water: "water" } as const--/** What a building's crew is short of, for its problem line. */-interface Crewing {- readonly nearby: number- readonly crew: "settlers" | "citizens"-}--/** Why a building is not working: in a word or two, why in a line, and what to do; `null` when it is fine. */-interface Problem extends Cause {- readonly label: string-}--/** The kind that makes a good, for a fix that builds it. */-const makerOf = (good: GoodId): KindId | undefined => kindOrder.find((id) => kinds[id].recipe?.output === good)--const problemOf = (kind: Kind, status: StatusValue, growing = false, crewing?: Crewing): Problem | null => {- switch (status) {- case "unconnected":- return { label: "no road", why: "it needs a road at the middle of one of its sides", fix: { text: "lay a road along one of its sides" } }- case "unstaffed":- if (crewing && crewing.nearby === 0)- return { label: "no workers", why: `no ${crewing.crew === "citizens" ? "citizens' (or settlers') homes" : "settlers' cottages"} within ${COMMUTE} road cells`, fix: { text: "lay homes nearer, or a road to homes nearby" } }- return { label: "no workers", why: "every one nearby already has a job", fix: { text: `lay more homes within ${COMMUTE} road cells` } }- case "blocked":- return { label: "full", why: "nowhere to take what it makes", fix: { text: "build a warehouse nearby, or sell the surplus in the [town] panel", build: ["warehouse"] } }- case "paused":- return { label: "paused", why: "no workers, a quarter of its upkeep", fix: { text: "resume work below" } }- case "starved":- if (kind.gathers?.source === "water")- return growing- ? { label: "no fish", why: `the water in reach is fished out: each stretch rests ${Math.round(RESTOCK_TICKS * step.dt)} s after a catch`, fix: { text: "give it a longer shore of its own, or fewer fisheries on this water" } }- : { label: "no water", why: `no water within ${kind.gathers.radius} cells`, fix: { text: "rebuild it by the shore" } }- if (kind.gathers && growing && (kind.gathers.source === "stone" || kind.gathers.source === "ore"))- return { label: "worked out", why: `the worked faces in reach give a little ${kind.gathers.source} now and then`, fix: { text: `build it by fresh rock, or buy ${kind.gathers.source} in the [town] panel` } }- if (kind.gathers && growing) return { label: "waiting", why: `the ${kind.gathers.source === "tree" ? "trees" : "fields"} in reach are still growing` }- if (kind.gathers)- return kind.gathers.source === "tree"- ? { label: "no trees", why: `no grown trees within ${kind.gathers.radius} cells`, fix: { text: "build a forester nearby: it replants", build: ["forester"] } }- : { label: `no ${sourceTitle[kind.gathers.source]}`, why: `no ${sourceTitle[kind.gathers.source]} within ${kind.gathers.radius} cells`, fix: { text: "rebuild it nearer" } }- if (kind.recipe?.input) {- const maker = makerOf(kind.recipe.input)- return { label: `no ${kind.recipe.input}`, why: `waiting for ${kind.recipe.input}`, fix: maker ? { text: `build a ${kinds[maker].title.toLowerCase()}, or buy ${kind.recipe.input} in the [town] panel`, build: [maker] } : { text: `buy ${kind.recipe.input} in the [town] panel` } }- }- if (kind.service?.service === "goods") return { label: "nothing to hand out", why: "no fish, bread, or cloth here", fix: { text: "fill the store: it takes from storage" } }- if (kind.service?.service === "repair") return { label: "no planks", why: "nothing to mend with", fix: { text: "build a sawmill", build: ["lumberjack", "sawmill"] } }- return { label: "waiting", why: "waiting" }- default:- return null- }-}--/**- * A tree or field gatherer has young ones within reach: it is waiting on- * them to grow, not on a forester. A quarry or mine has rocks in reach,- * worked down to their faces: it is waiting on the next one.- */-const growingNear = (grid: GridValue, tile: TileLike, kind: Kind, rocks: ReadonlyMap<number, { readonly ore: boolean }>): boolean => {- const g = kind.gathers- if (!g) return false- // Water in reach, fished out: it rests, and gives again.- if (g.source === "water") return around(tile, g.radius).some((c) => useAt(grid, c.x, c.y) === "water")- if (g.source === "stone" || g.source === "ore") return around(tile, g.radius).some((c) => rocks.get(key(c.x, c.y))?.ore === (g.source === "ore"))- return around(tile, g.radius).some((c) => useAt(grid, c.x, c.y) === g.source)-}--const BuildingRead = Game.Query({- selection: {- tile: Game.Query.read(Tile),- building: Game.Query.read(Building),- status: Game.Query.read(Status),- staff: Game.Query.read(Staff),- site: Game.Query.optional(Site),- rising: Game.Query.optional(Rising),- recipe: Game.Query.optional(Recipe),- inventory: Game.Query.optional(Inventory),- service: Game.Query.optional(Service),- walkers: Game.Query.optionalRelated(WalkerOf),- hall: Game.Query.optional(TownHall),- paused: Game.Query.optional(Paused),- upgraded: Game.Query.optional(Upgraded),- works: Game.Query.optional(Works),- risk: Game.Query.optional(Risk),- condition: Game.Query.optional(Condition),- burning: Game.Query.optional(Burning)- }-})-const HouseRead = Game.Query({- selection: {- tile: Game.Query.read(Tile),- house: Game.Query.read(House),- rebuilt: Game.Query.optional(Rebuilt),- site: Game.Query.optional(Site),- rising: Game.Query.optional(Rising),- risk: Game.Query.optional(Risk),- condition: Game.Query.optional(Condition),- burning: Game.Query.optional(Burning),- sick: Game.Query.optional(Sick),- closed: Game.Query.optional(Paused)- }-})-const RuinRead = Game.Query({ selection: { tile: Game.Query.read(Tile), ruin: Game.Query.read(Ruin) } })-const ParkRead = Game.Query({ selection: { tile: Game.Query.read(Tile), park: Game.Query.read(Park) } })--/** Every cell between two corners, both included. */-const rectangle = (a: Point, b: Point): Array<Point> => {- const out: Array<Point> = []- for (let y = Math.min(a.y, b.y); y <= Math.max(a.y, b.y); y++) for (let x = Math.min(a.x, b.x); x <= Math.max(a.x, b.x); x++) out.push({ x, y })- return out-}--/** How far up a building or home is: a site rises to its frame as materials come in, then the rest of the way. */-const buildOf = (- site: { readonly owed: Parameters<typeof total>[0]; readonly total: number } | undefined,- rising: { readonly ticks: number } | undefined-) => (site ? PLATE_SHARE + (SITE_SHARE - PLATE_SHARE) * delivered(site) : rising ? rising.ticks / BUILD_TICKS : 1)--/** An upgrade under way: the share of its work done (see `Works`), else `null`. */-const worksShare = (works: { readonly total: number; readonly done: number } | undefined) =>- works ? Math.min(1, works.done / worksNeeded(works.total)) : null-const siteShare = (site: { readonly owed: Parameters<typeof total>[0]; readonly total: number } | undefined) =>- site ? delivered(site) : null--/** A site's plate is marked out the moment it is placed. */-const PLATE_SHARE = 0.12-/** The share of a site's materials that has arrived. */-const delivered = (site: { readonly owed: Parameters<typeof total>[0]; readonly total: number }) =>- 1 - total(site.owed) / Math.max(1, site.total)--const percent = (n: number, of: number) => `${Math.round((n / of) * 100)}%`-const signed = (n: number) => `${n > 0 ? "+" : n < 0 ? "−" : ""}${Math.abs(n)}`--/** The sign over a home or building: what is wrong now, or the risk nearest the top past `risk.warn`. */-const alertOf = (r: { readonly fire: number; readonly health: number; readonly order: number } | undefined, sick: boolean, worn: boolean): Alert | null => {- if (sick) return "sick"- if (r) {- const worst = (["fire", "health", "order"] as const).reduce((a, b) => (r[b] > r[a] ? b : a))- if (r[worst] >= risk.warn) return worst- }- return worn ? "worn" : null-}--/** How a risk reads: "low", "40%", or "high: 85%". */-const riskText = (value: number) => (value < RISK_MAX * 0.35 ? "ok" : value >= risk.warn ? `high, ${percent(value, RISK_MAX)}` : percent(value, RISK_MAX))--// ── Map views ─────────────────────────────────────────────────────────────--// Blue for fine, sand for worth a look, vermilion for wrong: a scale that still reads with-// red-green colour blindness, unlike green to red.-const GOOD = 0x3a78c2-const FAIR = 0xe2c25c-const BAD = 0xc8553d-/** Citizens' homes, in the workers view. */-const COOL = 0x8a58a8-/** The buildings that serve a view (its fire watch, its healer), and a workplace's reach: ink, apart from the scale. */-const MARK = 0x3d4943-/** A meter 0 → `of` as a colour: blue when low, sand, vermilion past the warning line. */-const meterColor = (value: number, of: number, warn: number) => (value >= warn ? BAD : value >= of * 0.35 ? FAIR : GOOD)--const legends: Readonly<Record<Exclude<View, "none">, Legend>> = {- appeal: {- title: "desirability",- keys: [- { color: 0x1f4f8f, label: `${home.tiers[3].appeal}+: townhouses` },- { color: GOOD, label: `${home.tiers[2].appeal}+: citizens` },- { color: 0xc6d4e4, label: "0 to 4: settlers only" },- { color: 0xeaa26a, label: "below 0: fewer people, less tax" },- { color: BAD, label: `${home.squalid} or less: squalid` }- ],- note: "Every point counts: a cottage holds fewer and pays less for each point below 0, and pays more above it. Industry pushes homes away; parks (the more they hold, the further they reach), a chapel, a market, and paved streets draw them in."- },- workers: {- title: "workers",- keys: [- { color: GOOD, label: "fully staffed" },- { color: FAIR, label: "short of workers" },- { color: BAD, label: "no workers" },- { color: 0xd6b48a, label: "settlers' homes" },- { color: COOL, label: "citizens' homes" }- ],- note: `Residents walk at most ${COMMUTE} road cells to work. Select a workplace to see its reach and the homes inside it.`- },- fire: {- title: "fire",- keys: [- { color: GOOD, label: "watched" },- { color: FAIR, label: "rising" },- { color: BAD, label: "at risk, or burning" }- ],- note: "Buildings take the colour too. A fire watch's watchman resets the risk of every home and workshop along the way; vermilion means past half way, so there is still time. Wooden cottages, ovens, forges, and crowding raise it."- },- health: {- title: "health",- keys: [- { color: GOOD, label: "visited" },- { color: FAIR, label: "rising" },- { color: BAD, label: "at risk, or sick" }- ],- note: "A healer's physician resets the risk and cures the sick. Hunger, crowding, squalor, quarry dust, and still water raise it."- },- order: {- title: "order",- keys: [- { color: GOOD, label: "kept" },- { color: FAIR, label: "rising" },- { color: BAD, label: "thieves about" }- ],- note: "A watch house's constable keeps order. Low approval, squalor, and homes not full raise it; theft first, then the home is left derelict."- },- condition: {- title: "condition",- keys: [- { color: GOOD, label: "well kept" },- { color: FAIR, label: "needs mending" },- { color: BAD, label: "run down: half pace" }- ],- note: "A builder's yard mends what its builder passes with planks and stone. At nothing it falls down."- }-}--/** When each workshop began waiting for its input: a shelf runs empty for a moment all the time, so the ticker only says so after `ALERT_PATIENCE`. */-const starvedSince = new Map<number, number>()-const ALERT_PATIENCE = stepsOf(30)-/** Since when the store has held no food (`null`: it has some). Fish comes in and goes out in handfuls, so the ticker waits `HUNGER_PATIENCE` before saying so. */-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 = stepsOf(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 }-const needIcons = { food: "food", bread: "bread", cloth: "cloth", faith: "faith", furniture: "furniture" } as const--const appealColor = (v: number) =>- v >= home.tiers[3].appeal ? 0x1f4f8f : v >= home.tiers[2].appeal ? GOOD : v >= 0 ? 0xc6d4e4 : v > home.squalid ? 0xeaa26a : BAD--/** What the simulation told the page this step: toasts to show, and the panel's selection. */-export const ShowFeedback = Game.System(- "Town/ShowFeedback",- {- events: { toast: Game.System.readEvent(Toast), selection: Game.System.readEvent(Selection) },- services: { ui: Game.System.service(Ui) }- },- ({ events, services }) => {- const ui = services.ui- for (const message of events.toast.all()) ui.toast(message)- for (const change of events.selection.all()) {- if ("select" in change) ui.selected = change.select- else if ("clear" in change) ui.selected = null- else if (ui.selected === change.clearIf) ui.selected = null- }- }-)--export const Interact = Game.System(- "Town/Interact",- {- queries: {- buildings: BuildingRead,- houses: HouseRead,- ruins: RuinRead,- parks: ParkRead,- trees: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Tree] }),- water: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Water] }),- rocks: Game.Query({ selection: { tile: Game.Query.read(Tile), rock: Game.Query.read(Rock) } }),- paved: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road, Paved] })- },- resources: {- grid: Game.System.readResource(Grid),- census: Game.System.readResource(Census),- treasury: Game.System.readResource(Treasury),- ledger: Game.System.readResource(Ledger),- stock: Game.System.readResource(Stock),- flow: Game.System.readResource(Flow),- handed: Game.System.readResource(Handed),- policy: Game.System.readResource(Policy),- time: Game.System.readResource(Time),- charter: Game.System.readResource(Charter),- market: Game.System.readResource(Market),- mood: Game.System.readResource(Mood),- crown: Game.System.readResource(Crown),- fate: Game.System.readResource(Fate),- history: Game.System.readResource(History),- chronicle: Game.System.readResource(Chronicle),- appeal: Game.System.readResource(Appeal),- pantry: Game.System.readResource(Pantry),- guide: Game.System.readResource(Guide)- },- services: { ui: Game.System.service(Ui) },- /** Guide edits sent but not yet applied by the simulation: they count at once, so the guide moves on before the next step. */- local: () => ({ guide: { done: new Set<string>(), off: null as boolean | null } })- },- ({ queries, resources, services, local }) => {- const ui = services.ui- const grid = resources.grid.get()- const rates = resources.policy.get()- const approval = resources.mood.get().approval- const cells = resources.appeal.get().cells- // The rocks by cell: which are ore, and which are worked down to their faces.- const rockAt = new Map(queries.rocks.each().map(({ data }) => [key(data.tile.get().x, data.tile.get().y), data.rock.get()]))- const tick = resources.time.get().step- const buildings = queries.buildings.each()- const houses = queries.houses.each()- const ruins = queries.ruins.each()- const parkRows = queries.parks.each()- const parkCells: Array<ParkCell> = parkRows.map(({ data }) => ({ ...data.tile.get(), ...data.park.get() }))- const parkAt = new Map(parkRows.map((row) => [key(row.data.tile.get().x, row.data.tile.get().y), row] as const))- const road = (x: number, y: number) => isRoad(grid, x, y)- /** The park a cell belongs to, as it is, or as it would be with `changed` cells laid over it. */- const parkOf = (cell: Point, changed: ReadonlyArray<ParkCell> = []): ParkValue | undefined => {- const over = new Map(parkCells.map((c) => [key(c.x, c.y), c]))- for (const c of changed) over.set(key(c.x, c.y), c)- return parksOf([...over.values()], road).find((p) => p.cells.some((c) => c.x === cell.x && c.y === cell.y))- }- /** How far a park reaches, as one square around it. */- const reachPlots = (p: ParkValue) => {- const xs = p.cells.map((c) => c.x)- const ys = p.cells.map((c) => c.y)- const x = Math.min(...xs)- const y = Math.min(...ys)- const size = Math.max(Math.max(...xs) - x, Math.max(...ys) - y) + 1- return [{ x: x - p.reach, y: y - p.reach, size: size + 2 * p.reach, look: "reach" as const }]- }- /** A park, for its panel: what it is worth, why, and what would make it better. */- const describePark = (p: ParkValue): Array<Line> => {- const has = new Set(p.cells.map((c) => c.prop))- const missing = propIds.filter((id) => !has.has(id)).map((id) => props[id].title.toLowerCase())- const upkeep = p.cells.reduce((n, c) => n + grounds[c.ground].upkeep + (c.prop === "none" ? 0 : props[c.prop].upkeep), 0)- const placed = p.cells.filter((c) => c.prop !== "none").length - p.crowded- return [- { icon: "decor", label: "size", value: `${p.cells.length} cell${p.cells.length === 1 ? "" : "s"} · beauty ${p.beauty}` },- { icon: "appeal", label: "made of", value: p.parts.map((part) => `${part.label} ${part.value}`).join(", ") || "nothing yet" },- { icon: "homes", label: "the streets around", value: parkText(p), tone: "ok" },- p.entrances > 0- ? { icon: "road", label: "ways in from the street", value: `${p.entrances}${p.entrances > 2 ? " (2 count)" : ""}` }- : { icon: "road", label: "ways in from the street", value: "none", tone: "warn", note: "lay a gravel walk or a paved square out to a road: +1.5 each, two count" },- { icon: "decor", label: "furnishings that count", value: `${placed} of ${Math.floor(p.cells.length / 2)}`, tone: p.crowded > 0 ? "warn" : undefined, note: p.crowded > 0 ? `${p.crowded} too many: one counts for every 2 cells of park, so lay more ground` : undefined },- ...(missing.length > 0 ? [{ icon: "info", label: "nicer with", value: missing.join(", "), tone: "dim" } as Line] : []),- { icon: "upkeep", label: "upkeep", value: `${Math.round(upkeep * 10) / 10} coins a minute` }- ]- }- /** What the pointer is on: the model the camera ray hit, or else (parks have nothing standing to hit) the park on the cell. */- const pickAt = (at: Point, entity?: number | null) => {- const hit = hitAt(hits, at, entity)- return hit ?? parkAt.get(key(Math.floor(at.x), Math.floor(at.y)))?.entity.id ?? null- }- const parkText = (p: ParkValue) => `desirability ${signed(p.value)} out to ${p.reach} cells`- /**- * What new cottages would bring in, fed, at the settlers' rate on their streets, less what they add to the- * town hall's administration for their residents (see `moreAdmin`): the sum that turns once a town is large.- */- const homesWorth = (at: ReadonlyArray<Point>) => {- if (at.length === 0) return ""- const standing = houses.filter((row) => !row.data.closed.present).reduce((n, row) => n + row.data.house.get().residents, 0)- const fed = { tier: 1 as Tier, food: 1, bread: 0, cloth: 0, faith: 0, furniture: 0, residents: home.tiers[1].residents }- let people = 0- const pays = at.reduce((sum, c) => {- const d = appealAt(cells, c.x, c.y), residents = capacity(fed, approval, d, undefined, rates.settlers)- people += residents- return sum + taxOf({ ...fed, residents }, rates, undefined, d)- }, 0)- const worth = Math.round(pays - moreAdmin(standing, people))- return worth > 0 ? ` · ${signed(worth)} coins a minute once fed` : " · costs more to run than it pays: finer homes pay better"- }-- const hits: Array<HitBox> = [- ...buildings.map(({ entity, data }) => {- const kind = kinds[data.building.get().kind]- return hitBox(entity.id, data.tile.get(), kind.half, topOf(kind))- }),- ...houses.map(({ entity, data }) => hitBox(entity.id, data.tile.get(), home.half, homeHeight(data.house.get().tier))),- ...ruins.map(({ entity, data }) => hitBox(entity.id, data.tile.get(), 0, 0)),- ...parkRows.map(({ entity, data }) => hitBox(entity.id, data.tile.get(), 0, 0))- ].sort((l, r) => r.depth - l.depth)- ui.hits = hits- const tileOf = (id: number) => [...buildings, ...houses, ...ruins, ...parkRows].find((row) => row.entity.id === id)?.data.tile.get()-- /**- * What is wrong with a building where it would stand, before it is laid: no road at the middle of a side (it is- * not laid: nobody could bring its materials or work there), or nothing in reach to gather (laid, but said).- */- const placeProblem = (kind: Kind, tile: TileLike): { readonly refuse: boolean; readonly text: string } | null => {- if (!canPlace(grid, tile) || lockReason(kind, resources.census.get())) return null- if (doors(grid, tile).length === 0) return { refuse: true, text: "needs a road at the middle of one side" }- const source = kind.gathers?.source- if (!source || source === "field") return null- const reachCells = around(tile, kind.gathers!.radius)- const found =- source === "stone" || source === "ore"- ? queries.rocks.each().some(({ data }) => {- const t = data.tile.get()- return data.rock.get().ore === (source === "ore") && reachCells.some((c) => c.x >= t.x && c.x < t.x + t.size && c.y >= t.y && c.y < t.y + t.size)- })- : reachCells.some((c) => useAt(grid, c.x, c.y) === source)- const what = { tree: "trees", stone: "pale stone rocks", ore: "dark ore rocks", water: "water" }[source]- return found ? null : { refuse: false, text: `no ${what} within ${kind.gathers!.radius} cells` }- }-- // ── Gestures ──- for (const gesture of ui.gestures.splice(0)) {- const cell = cellAt(gesture.at)- if (gesture.type === "press") {- ui.dragFrom = (ui.tool === "road" || ui.tool === "home" || ui.tool === "pave" || ui.tool === "ground") && inside(cell.x, cell.y) ? cell : null- continue- }- switch (ui.tool) {- case "road":- case "pave":- case "home": {- if (ui.dragFrom) {- const cells = lPath(ui.dragFrom, cell).filter((c) => inside(c.x, c.y))- ui.edits.push(ui.tool === "road" ? { type: "roads", cells } : ui.tool === "pave" ? { type: "pave", cells } : { type: "homes", cells })- }- ui.dragFrom = null- break- }- case "ground": {- if (ui.dragFrom) ui.edits.push({ type: "ground", ground: ui.ground, cells: rectangle(ui.dragFrom, cell).filter((c) => inside(c.x, c.y)) })- ui.dragFrom = null- break- }- case "prop": {- if (gesture.panned) break- ui.edits.push({ type: "prop", prop: ui.prop, cell })- break- }- case "place": {- if (gesture.panned || !ui.placing) break- const kind = kinds[ui.placing]- const at = footprintAt(gesture.at, kind.size)- const problem = placeProblem(kind, { ...at, size: kind.size })- if (problem?.refuse) {- ui.toast(`A ${kind.title.toLowerCase()} ${problem.text}`)- break- }- ui.edits.push({ type: "building", kind: ui.placing, cell: at, open: false })- break- }- case "upgrade": {- // A click on a building of the kind being upgraded begins its works.- if (gesture.panned) break- const hit = pickAt(gesture.at, gesture.hit)- const row = hit !== null ? buildings.find((b) => b.entity.id === hit) : undefined- const kind = row ? kinds[row.data.building.get().kind] : undefined- if (!row || !kind || (ui.upgrading && kind.id !== ui.upgrading)) {- const wanted = ui.upgrading ? (upgradeAt(kinds[ui.upgrading], 0) ? kinds[ui.upgrading].title.toLowerCase() : "building") : "building"- ui.toast(`Pick a ${wanted} to upgrade`)- break- }- if (row.data.works.present) {- ui.toast(`The ${kind.title.toLowerCase()} is already being upgraded`)- break- }- ui.edits.push({ type: "upgrade", cell: row.data.tile.get() })- break- }- case "bulldoze": {- if (gesture.panned) break- const hit = pickAt(gesture.at, gesture.hit)- ui.edits.push({ type: "remove", cell: (hit !== null ? tileOf(hit) : undefined) ?? cell })- break- }- case "select": {- if (gesture.panned) break- ui.selected = pickAt(gesture.at, gesture.hit)- if (ui.selected !== null) ui.menu = null- break- }- }- }- if (ui.selected !== null && tileOf(ui.selected) === undefined) ui.selected = null-- // ── Preview ──- const preview = emptyPreview()- const pointer = ui.pointer- const cell = pointer ? cellAt(pointer) : null- preview.hover = pointer && (ui.tool === "select" || ui.tool === "bulldoze" || ui.tool === "upgrade") ? pickAt(pointer, ui.pointerHit) : null- const showReach = (tile: TileLike, kind: Kind) => {- const r = reachOf(kind)- if (r !== null) preview.plots.push({ x: tile.x - r, y: tile.y - r, size: tile.size + 2 * r, look: "reach" })- }- const pavedCells = new Set(queries.paved.each().map(({ data }) => key(data.tile.get().x, data.tile.get().y)))- /** The road cells within `limit` of a tile's doors: what a service's walkers, or a commute, would reach from here. */- const rangeFrom = (tile: TileLike, limit: number, note: string) => {- const ds = doors(grid, tile)- if (ds.length === 0) return- const roads = reach(grid, ds)- for (let k = 0; k < roads.distance.length; k++) {- const d = roads.distance[k]!- if (d >= 0 && d < limit) preview.range.push(cellOf(k))- }- preview.rangeNote = note- }- const rangeOfKind = (tile: TileLike, kind: Kind, range = kind.service?.range) => {- if (kind.service && range !== undefined) rangeFrom(tile, range, `its walkers reach ${range} road cells from the door`)- else if (kind.workers > 0) rangeFrom(tile, COMMUTE + 1, `its workers come from homes within ${COMMUTE} road cells`)- }- // Where the page is pointing (from the ticker): outlined for a few seconds.- if (ui.flash) {- if (Date.now() < ui.flash.until) preview.plots.push({ x: ui.flash.cell.x, y: ui.flash.cell.y, size: ui.flash.size, look: "picked" })- else ui.flash = null- }-- /** A cost `n` times over. */- const times = (cost: Kind["cost"], n: number): Kind["cost"] => ({- coins: cost.coins * n,- materials: Object.fromEntries(Object.entries(cost.materials).map(([g, m]) => [g, (m ?? 0) * n]))- })- const counted = (n: number, what: string) => `${n} ${what}${n === 1 ? "" : "s"}`- // Let go off the map (over the tool bar, say) and the stroke is dropped: it shows as blocked.- const dropping = ui.stroke === "cancel" && ui.dragFrom !== null- if (dropping && cell && (ui.tool === "road" || ui.tool === "home" || ui.tool === "pave" || ui.tool === "ground")) {- for (const c of ui.tool === "ground" ? rectangle(ui.dragFrom!, cell) : lPath(ui.dragFrom!, cell))- if (inside(c.x, c.y)) preview.plots.push({ ...c, size: 1, look: "blocked" })- preview.tooltip = "let go here to cancel"- } else if (ui.tool === "road" || ui.tool === "home" || ui.tool === "pave") {- const cells = cell === null ? [] : ui.dragFrom ? lPath(ui.dragFrom, cell) : [cell]- for (const c of cells) {- if (!inside(c.x, c.y)) continue- const free = canPlace(grid, { ...c, size: 1 })- if (ui.tool === "road") {- if (free) preview.roads.push(c)- else if (useAt(grid, c.x, c.y) !== "road") preview.plots.push({ ...c, size: 1, look: "blocked" })- } else if (ui.tool === "pave") {- const road = useAt(grid, c.x, c.y) === "road"- if (road && !pavedCells.has(key(c.x, c.y))) preview.plots.push({ ...c, size: 1, look: "reach" })- else if (!road) preview.plots.push({ ...c, size: 1, look: "blocked" })- } else if (free) preview.ghosts.push({ what: "home", cell: c })- else preview.plots.push({ ...c, size: 1, look: "blocked" })- }- if (ui.tool === "home" && cell && inside(cell.x, cell.y)) {- rangeFrom({ ...(ui.dragFrom ?? cell), size: 1 }, COMMUTE + 1, `residents walk to work within ${COMMUTE} road cells`)- preview.tooltip = `homes · ${costText(home.cost)} each${preview.rangeNote ? homesWorth(preview.ghosts.map((g) => g.cell)) : " · lay them beside a road"}`- }- if (ui.tool === "road" && cell) preview.tooltip = `road · ${ROAD_COST} coins a cell`- if (ui.dragFrom && cell) {- const n = ui.tool === "road" ? preview.roads.length : ui.tool === "home" ? preview.ghosts.length : preview.plots.filter((p) => p.look === "reach").length- preview.stroke =- ui.tool === "road"- ? `${counted(n, "road cell")} · ${costText({ coins: n * ROAD_COST, materials: {} })}`- : ui.tool === "home"- ? `${counted(n, "home")} · ${costText(times(home.cost, n))}${homesWorth(preview.ghosts.map((g) => g.cell))}`- : `pave ${counted(n, "cell")} · ${costText({ coins: n * PAVE_COST.coins, materials: { stone: n * PAVE_COST.stone } })}`- }- } else if (ui.tool === "ground" && cell) {- const laid: Array<ParkCell> = []- for (const c of ui.dragFrom ? rectangle(ui.dragFrom, cell) : [cell]) {- if (!inside(c.x, c.y)) continue- const there = parkAt.get(key(c.x, c.y))?.data.park.get()- if (there ? there.ground !== ui.ground : canPlace(grid, { ...c, size: 1 })) laid.push({ ...c, ground: ui.ground, prop: there?.prop ?? "none" })- else if (!there) preview.plots.push({ ...c, size: 1, look: "blocked" })- }- preview.parks.push(...laid)- const after = laid.length > 0 ? parkOf(laid[0]!, laid) : undefined- const cost = costText(times(grounds[ui.ground].cost, laid.length))- if (ui.dragFrom) preview.stroke = `${grounds[ui.ground].title.toLowerCase()} · ${counted(laid.length, "cell")} · ${cost}`- preview.tooltip = `${grounds[ui.ground].title.toLowerCase()} · ${cost}${after ? ` · park ${signed(after.value)} desirability` : ""}`- if (after) preview.plots.push(...reachPlots(after))- } else if (ui.tool === "prop" && cell && inside(cell.x, cell.y)) {- const there = parkAt.get(key(cell.x, cell.y))?.data.park.get()- if (there) {- const placed = { ...cell, ground: there.ground, prop: ui.prop }- preview.parks.push(placed)- const before = parkOf(cell)- const after = parkOf(cell, [placed])- preview.tooltip = `${props[ui.prop].title.toLowerCase()} · ${costText(props[ui.prop].cost)}${after ? ` · park ${signed(after.value)} desirability${before && before.value !== after.value ? ` (now ${signed(before.value)})` : ""}` : ""}${after && after.crowded > 0 ? " · too crowded" : ""}`- if (after) preview.plots.push(...reachPlots(after))- } else {- preview.plots.push({ ...cell, size: 1, look: "blocked" })- preview.tooltip = `${props[ui.prop].title.toLowerCase()} · lay park ground first`- }- } else if (ui.tool === "place" && ui.placing && pointer) {- const kind = kinds[ui.placing]- const at = footprintAt(pointer, kind.size)- const tile = { ...at, size: kind.size }- showReach(tile, kind)- rangeOfKind(tile, kind)- if (kind.appeal) preview.plots.push({ x: tile.x - kind.appeal.reach, y: tile.y - kind.appeal.reach, size: tile.size + 2 * kind.appeal.reach, look: kind.appeal.value > 0 ? "reach" : "hover" })- if (lockReason(kind, resources.census.get())) preview.plots.push({ ...tile, look: "blocked" })- else if (canPlace(grid, tile)) {- preview.ghosts.push({ what: ui.placing, cell: at })- // No road at a side's middle: shown red under the ghost, as it will not be laid there.- if (placeProblem(kind, tile)?.refuse) preview.plots.push({ ...tile, look: "blocked" })- } else preview.plots.push({ ...tile, look: "blocked" })- } else if (ui.tool === "upgrade" && ui.upgrading) {- // Every building the upgrade can go to, outlined; the one under the pointer says what it would give and cost.- const rank = resources.fate.get().rank, coins = resources.treasury.get().coins- for (const row of buildings) {- const { data } = row- if (data.building.get().kind !== ui.upgrading || data.site.present || data.rising.present) continue- const kind = kinds[ui.upgrading], level = data.upgraded.value()?.level ?? 0, up = nextUpgrade(kind, level)- const tile = data.tile.get()- if (!up) continue- const blocked = upgradeBlock(up, rank, { ranks })- const hovered = preview.hover === row.entity.id- preview.plots.push({ ...tile, look: data.works.present || blocked ? "blocked" : hovered ? "picked" : "reach" })- if (!hovered) continue- const from = (upgradeAt(kind, level)?.title ?? kind.title).toLowerCase()- preview.tooltip = data.works.present- ? `${from} → ${up.title.toLowerCase()} · under way: carriers are bringing its materials`- : [`${from} → ${up.title.toLowerCase()}`, upgradePrice(up), ...upgradeChanges(kind, level).map((c) => `· ${c}`),- blocked ?? (coins < up.cost.coins ? `${up.cost.coins - coins} coins short` : "click to begin: it goes on working meanwhile")].join("\n")- }- if (!preview.tooltip) preview.tooltip = `upgrade: pick a ${kinds[ui.upgrading].title.toLowerCase()} · Esc to stop`- } else if (ui.tool === "bulldoze") {- preview.danger = true- if ((preview.hover === null || useAt(grid, cell?.x ?? -1, cell?.y ?? -1) === "park") && cell && ["road", "tree", "field", "park"].includes(useAt(grid, cell.x, cell.y)))- preview.plots.push({ ...cell, size: 1, look: "blocked" })- const there = cell ? parkAt.get(key(cell.x, cell.y))?.data.park.get() : undefined- if (there) preview.tooltip = there.prop !== "none" ? `remove the ${props[there.prop].title.toLowerCase()}` : `remove the ${grounds[there.ground].title.toLowerCase()}`- const rock = cell ? rockAt.get(key(cell.x, cell.y)) : undefined- if (rock && cell) {- const worked = rock.amount <= 1- if (worked) preview.plots.push({ ...cell, size: 1, look: "blocked" })- preview.tooltip = worked ? `worked ${rock.ore ? "ore" : "stone"} face · bulldoze to clear it` : `${rock.ore ? "ore" : "stone"} · ${rock.amount} left`- }- }- if (ui.selected !== null) {- const row = buildings.find((b) => b.entity.id === ui.selected)- const tile = tileOf(ui.selected)- const whole = tile && useAt(grid, tile.x, tile.y) === "park" ? parkOf(tile) : undefined- if (whole) {- // A park is picked whole: every cell of it, and how far it reaches.- for (const c of whole.cells) preview.plots.push({ x: c.x, y: c.y, size: 1, look: "hover" })- preview.plots.push(...reachPlots(whole))- } else if (tile) preview.plots.push({ ...tile, look: "picked" })- if (row && tile) {- showReach(tile, kinds[row.data.building.get().kind])- rangeOfKind(tile, kinds[row.data.building.get().kind], row.data.service.value()?.range)- }- }-- // ── The neighbourhood, explained (only when a home asks) ──- let sources: Array<AppealSource> | null = null- const appealSources = () => {- if (sources) return sources- sources = []- for (const { data } of buildings) {- if (data.site.present || data.rising.present) continue- const s = buildingSource(data.building.get().kind, data.tile.get(), undefined, data.upgraded.value()?.level ?? 0)- if (s) sources.push(s)- }- for (const { data } of queries.trees.each()) sources.push(landSource("forest", data.tile.get()))- for (const { data } of queries.water.each()) sources.push(landSource("water", data.tile.get()))- for (const { data } of queries.paved.each()) sources.push(landSource("paved", data.tile.get()))- sources.push(...parkSources(parkCells, road))- for (const { data } of ruins) sources.push(landSource("ruin", data.tile.get()))- for (const { data } of houses) {- if (data.site.present || data.rising.present) continue- if ((data.condition.value()?.value ?? CONDITION_MAX) < wear.worn) sources.push(landSource("worn", data.tile.get()))- const fine = data.closed.present ? null : homeSource(data.house.get().tier, data.tile.get())- if (fine) sources.push(fine)- }- return sources- }- /** Where a home's residents work: the nearest workplace of their crew in reach that has them. */- const workOf = (tile: TileLike, tier: Tier) => {- const ds = doors(grid, tile)- if (ds.length === 0) return null- const roads = reach(grid, ds)- let best: { title: string; distance: number } | null = null- for (const { data } of buildings) {- const kind = kinds[data.building.get().kind]- const staff = data.staff.get()- if (staff.needed === 0 || staff.assigned === 0 || (kind.crew !== crewOf(tier) && !(tier === 1 && staff.apprentices > 0))) continue- for (const d of doors(grid, data.tile.get())) {- const n = roads.distance[key(d.x, d.y)]!- if (n >= 0 && n <= COMMUTE && (best === null || n < best.distance)) best = { title: kind.title.toLowerCase(), distance: n }- }- }- return best- }-- // ── Tooltip and panel ──- // 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) => row.data.service.value()?.service === "goods" && finished(row))- .map((row) => ({ way: reach(grid, doors(grid, row.data.tile.get())), range: row.data.service.value()!.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().step- 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 && !r.data.works.value())- 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 = r.data.inventory.value()- 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 = r.data.upgraded.value()?.level ?? 0, status = r.data.status.get()- if (!nextUpgrade(kind, level)) continue- const reach = r.data.service.value()?.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) => (h.data.risk.value()?.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) } : {})- /**- * A building, for its panel: what it is doing (workers, what it makes, what it holds), then what it costs to run- * (upkeep, wear, fire, its street). Each row is a value; a note only when something wants doing.- */- const describeBuilding = (row: (typeof buildings)[number]) => {- const kind = kinds[row.data.building.get().kind]- const status = row.data.status.get()- const site = row.data.site.value()- if (site) {- const owed = (Object.entries(site.owed) as Array<[GoodId, number]>).filter(([, n]) => n > 0)- const line: Line =- owed.length > 0- ? { icon: "build", label: "waiting for", goods: owed.map(([good, count]) => ({ good, count })), tone: "warn", note: "carriers bring them from storage: buy what the town lacks in the town panel" }- : { icon: "build", label: "builders", value: "at work", tone: "ok" }- return { kind, status, problem: null, state: { icon: "build", label: "being built", tone: "warn" } as Line, groups: [{ title: "being built", icon: "build", lines: [line] }] as Array<Group> }- }- const staff = row.data.staff.get()- const work: Array<Line> = []- if (staff.needed > 0) {- const crew = kind.crew- const short = staff.assigned < staff.needed- work.push({- icon: "workers",- label: "workers",- value: `${staff.assigned} of ${staff.needed}`,- tone: !short ? "ok" : staff.assigned > 0 ? "warn" : "bad",- note: short- ? staff.nearby === 0- ? `no ${crew} live within ${COMMUTE} road cells: lay homes nearer`- : `everyone nearby has a job: lay more homes within ${COMMUTE} road cells`- : staff.apprentices > 0- ? `settlers stand in for citizens, at three-quarters pace`- : undefined- })- }- const recipe = row.data.recipe.value()- if (recipe)- work.push({ icon: recipe.output, label: "makes", value: recipe.input ? `${goods[recipe.input].title} → ${goods[recipe.output].title}` : goods[recipe.output].title })- const service = row.data.service.value()- if (service)- work.push({- icon: service.service === "goods" ? "trade" : service.service === "faith" ? "faith" : service.service === "repair" ? "repair" : service.service,- label: "walkers out",- value: `${row.data.walkers.value()?.length ?? 0}`- })- // A provisions walker's building: what its walkers handed to homes over the last minute, which its shelf- // alone cannot say (food leaves in the basket as soon as it comes; furniture mostly comes back).- if (service?.service === "goods") {- const log = resources.handed.get().log.filter((l) => l.from === row.entity.id)- const given: Record<GoodId, number> = { ...amounts({}) }- for (const l of log) for (const [g, n] of Object.entries(l.goods) as Array<[GoodId, number]>) given[g] += n- const homesFed = new Set(log.map((l) => l.to)).size- work.push(- homesFed > 0- ? { icon: "people", label: "handed out, last minute", goods: provisions.filter((g) => given[g] > 0).map((g) => ({ good: g, count: given[g] })),- note: `to ${homesFed} home${homesFed === 1 ? "" : "s"} on its walks` }- : { icon: "people", label: "handed out, last minute", value: "nothing", tone: "dim", note: "no home on its walks needed what it had" }- )- }- const inventory = row.data.inventory.value()- if (inventory) {- const held = inventory.accepts.filter((g) => inventory.stock[g] > 0).map((g) => ({ good: g, count: inventory.stock[g] }))- // A market's shelf is only what waits for the next walker.- const label = kind.id === "market" ? "on the shelf now" : "holds"- work.push(held.length > 0 ? { icon: "jobs", label, goods: held } : { icon: "jobs", label, value: "nothing", tone: "dim" })- }- if (kind.wear && inventory)- work.push(- inventory.stock.tools > 0- ? { icon: "tools", label: "tools", value: `${inventory.stock.tools}`, tone: "ok" }- : { icon: "tools", label: "tools", value: "none", tone: "bad", note: "half pace until one comes: a smithy makes them, or buy them in the town panel" }- )- const running: Array<Line> = []- const level = row.data.upgraded.value()?.level ?? 0- const upkeep = upkeepOf(kind, level)- if (upkeep > 0) running.push({ icon: "upkeep", label: "upkeep", value: `${upkeep} coins a minute` })- const condition = row.data.condition.value()- if (condition)- running.push({- icon: "condition",- label: "condition",- value: percent(condition.value, CONDITION_MAX),- tone: condition.value < wear.worn ? "bad" : condition.value < wear.mend ? "warn" : "ok",- note: condition.value < wear.worn ? "half pace, and it may fall: a builder's yard mends it" : condition.value < wear.mend ? "a builder's yard mends it as its builder passes" : undefined- })- const r = row.data.risk.value()- if (r)- running.push({- icon: "fire",- label: "fire risk",- value: riskText(r.fire),- tone: r.fire >= risk.warn ? "bad" : r.fire >= RISK_MAX * 0.35 ? "warn" : "ok",- note: r.fire >= RISK_MAX * 0.35 ? "a fire watch's watchman lowers it as he passes" : undefined- })- const appealHere = upgradeAt(kind, level)?.appeal ?? kind.appeal- if (appealHere) running.push({ icon: "appeal", label: "desirability nearby", value: signed(appealHere.value) })- const help = [- upkeep > 0 ? "Upkeep is paid every minute it stands, a quarter of it while paused." : "",- condition ? "Everything wears down; a builder's yard mends it." : "",- kind.hot ? "An oven or a forge: a fire risk to itself and to homes within 2 cells." : "",- appealHere ? `It changes how nice the streets are out to ${appealHere.reach} cells${appealHere.value < 0 ? ": homes close by hold fewer people and pay less" : ""}.` : ""- ]- .filter((t) => t !== "")- .join(" ")- const groups: Array<Group> = [- ...(work.length > 0 ? [{ title: "at work", icon: "jobs", lines: work } as Group] : []),- ...(running.length > 0 ? [{ title: "running it", icon: "coins", help, lines: running } as Group] : [])- ]- const growing = status === "starved" && growingNear(grid, row.data.tile.get(), kind, rockAt)- const trouble: Problem | null = row.data.burning.present- ? { label: "on fire!", why: "its crew has fled", fix: { text: "a fire watch's watchmen put fires out", build: ["firewatch"] } }- : problemOf(kind, status, growing, { nearby: staff.nearby, crew: kind.crew })- const state: Line = trouble- ? { icon: "warning", label: trouble.label, tone: "bad", note: trouble.why, fix: fixOf(trouble.fix) }- : { icon: status === "working" ? "jobs" : "clock", label: status === "working" ? "working" : status, tone: status === "working" ? "ok" : undefined }- return { kind, status, problem: trouble ? `${trouble.label}: ${trouble.why}` : null, state, groups }- }- /** What the town has of each provision, in storage and on market shelves. */- const inTown = (): InTown => {- const stock = resources.stock.get()- const sum = { fish: stock.fish, smoked: stock.smoked, bread: stock.bread, cloth: stock.cloth, furniture: stock.furniture }- for (const { data } of buildings) {- const inv = data.inventory.value()- if (!inv || data.service.value()?.service !== "goods" || data.site.present || data.rising.present) continue- sum.fish += inv.stock.fish- sum.smoked += inv.stock.smoked- sum.bread += inv.stock.bread- sum.cloth += inv.stock.cloth- sum.furniture += inv.stock.furniture- }- return sum- }- /** Which services have a walker that can reach a home: a standing market (or the town hall), and a chapel, within their walks of its door. */- const servedAt = (tile: TileLike): Served => {- const ds = doors(grid, tile)- if (ds.length === 0) return { goods: false, faith: false }- const way = reach(grid, ds)- const served = { goods: false, faith: false }- for (const { data } of buildings) {- const service = data.service.value()- if (!service || data.site.present || data.rising.present || data.burning.present) continue- if (service.service !== "goods" && service.service !== "faith") continue- if (served[service.service]) continue- const found = nearest(way, doors(grid, data.tile.get()))- if (found && found.distance < service.range) served[service.service] = true- }- return served- }- /**- * A home, for its panel: its household (who lives there, what it pays, where they work); what it needs, as one- * checklist with what it lacks now in red and what it lacks to grow in amber, each with its cause; and its risks- * and wear. Each row is a value; a note only when something wants doing.- */- const describeHouse = (row: (typeof houses)[number]) => {- const h = row.data.house.get()- const site = row.data.site.value()- const quiet = (summary: string, line: Line) => ({ h, summary, trouble: false, groups: [{ title: "household", icon: "homes", lines: [line] }] as Array<Group> })- if (site) return quiet("being built", { icon: "planks", label: "builders", value: "waiting for its plank", tone: "warn" })- if (row.data.closed.present)- return quiet("closed", { icon: "settlers", label: "closed", value: "empty", tone: "warn", note: "it pays no taxes and costs the town hall nothing: reopen it and settlers move back in" })- const tile = row.data.tile.get()- const tier = home.tiers[h.tier]- const nextTier = h.tier < 3 ? ((h.tier + 1) as Tier) : null- const there = appealParts(appealSources(), tile)- const desirability = appealAt(cells, tile.x, tile.y)- const street: Street = { desirability, parts: there.parts }- const r = row.data.risk.value()- const work = workOf(tile, h.tier)- const condition = row.data.condition.value()- const town = inTown()- const served = servedAt(tile)- const rate = h.tier === 1 ? rates.settlers : rates.citizens- const cap = capacity(h, approval, desirability, undefined, rate)- const whyFewer =- cap >= tier.residents- ? undefined- : row.data.sick.present- ? "half as many while it is sick"- : approval < 0- ? "fewer while the town disapproves of its mayor"- : desirability < 0- ? `fewer on a poor street: ${streetAdvice(street)}`- : rate > 100 && capacity(h, approval, desirability) > cap- ? `fewer while taxed at ${rate}%: some move away`- : "fewer until every need is met"- const hungry = h.food <= 0- const pays = Math.round(taxOf(h, rates, undefined, desirability))- const could = Math.round(suppliedTaxOf(h, rates, undefined, desirability))- const household: Array<Line> = [- ...(row.data.burning.present ? [{ icon: "fire", label: "on fire", value: "everyone fled", tone: "bad" } as Line] : []),- ...(row.data.sick.present ? [{ icon: "health", label: "sick", value: "half as many", tone: "bad", note: "it passes in a minute, or when a healer's physician calls" } as Line] : []),- { icon: "people", label: "residents", value: `${h.residents} of ${cap}`, tone: whyFewer ? "warn" : "ok", note: whyFewer },- {- icon: "coins",- label: "pays",- value: `${pays} coins a minute`,- tone: hungry ? "bad" : undefined,- note: hungry ? "hungry: no food, no taxes" : could > pays ? `${could} coins a minute with every need met` : undefined- },- work ? { icon: "jobs", label: "works at", value: `${work.title.toLowerCase()}` } : { icon: "jobs", label: "works at", value: "nothing nearby", tone: "dim" }- ]- // What it needs: what it must have now, then what it must have to grow, in the order the town makes them.- const needs: Array<Line> = []- const nowNeeds = new Set<Need>(tier.needs)- const growNeeds = new Set<Need>(nextTier ? home.tiers[nextTier].needs : [])- for (const n of ["food", "bread", "cloth", "faith", "furniture"] as const) {- if (!nowNeeds.has(n) && !growNeeds.has(n)) continue- if (met(h, n)) {- needs.push({ icon: needIcons[n], label: needTitle[n], value: "✓", tone: "ok" })- continue- }- const now = nowNeeds.has(n)- needs.push({- icon: needIcons[n],- label: needTitle[n],- value: now ? "missing" : `for ${home.tiers[nextTier!].title}`,- tone: now ? "bad" : "warn",- ...told(causeOf(n, h, street, town, served))- })- }- const blocks = blockersOf(h, street, town, served, r)- const streetBlock = blocks.find((b) => b.what === "street")- if (nextTier)- needs.push({- icon: "appeal",- label: "street",- value: streetBlock ? `${signed(desirability)} of ${home.tiers[nextTier].appeal}` : "✓",- tone: streetBlock ? "warn" : "ok",- ...(streetBlock ? { note: streetShort(street, home.tiers[nextTier].appeal), fix: { text: streetAdvice(street) } } : {})- })- else needs.push({ icon: "appeal", label: "street", value: signed(desirability), tone: "ok" })- if (blocks.some((b) => b.what === "services")) needs.push({ icon: "order", label: "services", value: `for ${home.tiers[3].title}`, tone: "warn", ...told(servicesCause(r)) })- // Rising is a rebuilding, paid at once from the treasury and the store, once.- const rebuilt = nextTier !== null && (row.data.rebuilt.value()?.tier ?? 1) >= nextTier- const short = nextTier && !rebuilt ? shortOf(home.tiers[nextTier].rise, resources.treasury.get().coins, resources.stock.get()) : null- if (nextTier)- needs.push({- icon: "upkeep", label: "rebuilding", value: rebuilt ? "done ✓" : costText(home.tiers[nextTier].rise), tone: short ? "warn" : "ok",- ...(short- ? { note: `the town is short of ${short}`, fix: { text: "it waits at its tier until the store holds it: make it, or buy it in the [town] panel" } }- : rebuilt ? { note: "rebuilt already: it rises back for nothing" } : {})- })- if (nextTier && blocks.length === 0 && !short)- needs.push({ icon: "citizens", label: `ready for ${home.tiers[nextTier].title}`, value: "✓", tone: "ok", note: "it grows as the next resident moves in, and pays for its rebuilding then" })- const risky = r ? (["fire", "health", "order"] as const).filter((k) => r[k] >= RISK_MAX * 0.35) : []- const cure = { fire: "a fire watch's watchman lowers it", health: "a healer's physician lowers it", order: "a watch house's constable lowers it" } as const- const safety: Array<Line> = [- ...(r && risky.length === 0 ? [{ icon: "fire", label: "risks", value: "all low", tone: "ok" } as Line] : []),- ...risky.map(- (k): Line => ({- icon: k,- label: `${k === "order" ? "theft" : k} risk`,- value: riskText(r![k]),- tone: r![k] >= risk.warn ? "bad" : "warn",- note: cure[k]- })- ),- ...(r && r.thefts > 0 ? [{ icon: "order", label: "robbed", value: `${r.thefts}×`, tone: "warn" } as Line] : []),- ...(condition- ? [{- icon: "condition",- label: "condition",- value: percent(condition.value, CONDITION_MAX),- tone: condition.value < wear.worn ? "bad" : condition.value < wear.mend ? "warn" : "ok",- note: condition.value < wear.worn ? "it drags the street down and may fall: a builder's yard mends it" : condition.value < wear.mend ? "a builder's yard mends it as its builder passes" : undefined- } as Line]- : [])- ]- const needHelp =- h.tier === 1- ? `Red: it needs this now. Amber: it needs this to become a citizens' home, which holds and pays twice as much. Bread alone already makes a cottage pay half again. Walkers bring needs along the road; the street is how nice the place is (desirability ${home.tiers[2].appeal} for citizens).`- : h.tier === 2- ? `Red: it needs this now, or goes back to settlers. Amber: it needs this to become a townhouse of burghers, on a street of ${home.tiers[3].appeal} with a fire watch, a healer, and a watch house all calling.`- : "Red: it needs this now, or goes back to citizens."- const summary = row.data.burning.present ? "on fire" : row.data.sick.present ? "sick" : hungry ? "hungry" : `${h.residents} resident${h.residents === 1 ? "" : "s"}`- return {- h,- summary,- trouble: row.data.burning.present || row.data.sick.present || hungry,- groups: [- { title: "household", icon: "homes", lines: household },- { title: "needs", icon: "citizens", help: needHelp, lines: needs },- { title: "risks and wear", icon: "condition", help: "Every home's risk of fire, sickness, and theft rises slowly; a walker from the matching service lowers it as it passes.", lines: safety }- ] as Array<Group>- }- }-- /** What pulling a building or home down would cost and give back, for the bulldozer and the panel. */- const salvageFor = (cost: Kind["cost"], site: { readonly owed: Amounts } | undefined, works?: { readonly kind: Kind; readonly owed: Amounts; readonly level: number }) => {- const s = withWorks(salvageOf(cost, site?.owed ?? null), works?.kind ?? {}, works)- const said = salvageText(s)- return `${site ? "cancel" : "pull down"}${said ? `: ${said}` : ""}`- }- const hovered = preview.hover- const hoveredBuilding = hovered !== null ? buildings.find((row) => row.entity.id === hovered) : undefined- const hoveredHouse = hovered !== null ? houses.find((row) => row.entity.id === hovered) : undefined- const hoveredRuin = hovered !== null ? ruins.find((row) => row.entity.id === hovered) : undefined- // The upgrade tool says what an upgrade gives and costs instead (see above).- if (ui.tool === "upgrade") {- } else if (hoveredBuilding) {- const { kind, status, problem } = describeBuilding(hoveredBuilding)- const level = hoveredBuilding.data.upgraded.value()?.level ?? 0, works = hoveredBuilding.data.works.value()- const title = (upgradeAt(kind, level)?.title ?? kind.title).toLowerCase()- preview.tooltip = ui.tool === "bulldoze"- ? `${title} · ${hoveredBuilding.data.hall.present ? "the town hall stays" : salvageFor(builtCost(kind, level), hoveredBuilding.data.site.value(), works && { kind, ...works })}`- : `${title} · ${problem ?? status}${works ? ` · becoming ${anA(upgradeAt(kind, works.level)!.title.toLowerCase())}, ${Math.round(worksShare(works)! * 100)}% built` : ""}`- } else if (hoveredHouse) {- const h = hoveredHouse.data.house.get()- const t = hoveredHouse.data.tile.get()- preview.tooltip = ui.tool === "bulldoze"- ? `${tierHome[h.tier]} · ${salvageFor(home.cost, hoveredHouse.data.site.value())}`- : hoveredHouse.data.closed.present- ? `${tierHome[h.tier]} · closed`- : `${tierHome[h.tier]} · ${h.residents} resident${h.residents === 1 ? "" : "s"} · desirability ${appealAt(cells, t.x, t.y)}${hoveredHouse.data.burning.present ? " · on fire!" : hoveredHouse.data.sick.present ? " · sick" : ""}`- } else if (hoveredRuin) {- preview.tooltip = `ruin · ${hoveredRuin.data.ruin.get().cause} · bulldoze to clear`- } else if (hovered !== null && ui.tool === "select" && parkRows.some((row) => row.entity.id === hovered)) {- const row = parkRows.find((r) => r.entity.id === hovered)!- const p = parkOf(row.data.tile.get())- const here = row.data.park.get()- preview.tooltip = `park · ${here.prop !== "none" ? props[here.prop].title.toLowerCase() : grounds[here.ground].title.toLowerCase()}${p ? ` · ${p.cells.length} cells · ${parkText(p)}` : ""}`- } else if (ui.tool === "place" && ui.placing) {- const kind = kinds[ui.placing]- const lock = lockReason(kind, resources.census.get())- const tile = pointer ? { ...footprintAt(pointer, kind.size), size: kind.size } : null- const problem = tile ? placeProblem(kind, tile) : null- if (lock) preview.tooltip = `${kind.title.toLowerCase()} · ${lock}`- else if (tile && !canPlace(grid, tile)) preview.tooltip = `${kind.title.toLowerCase()} · no room here`- else if (problem) preview.tooltip = `${kind.title.toLowerCase()} · ${problem.text}`- else preview.tooltip = `${kind.title.toLowerCase()} · ${costText(kind.cost)}`- } else if (ui.tool === "pave" && !dropping) preview.tooltip = `pave · ${PAVE_COST.coins} coins and a stone a cell · faster walking`- else if (cell && ui.view === "appeal" && inside(cell.x, cell.y)) preview.tooltip = `desirability ${appealAt(cells, cell.x, cell.y)}`- ui.preview = preview-- const pickedBuilding = ui.selected !== null ? buildings.find((row) => row.entity.id === ui.selected) : undefined- const pickedHouse = ui.selected !== null ? houses.find((row) => row.entity.id === ui.selected) : undefined- const pickedRuin = ui.selected !== null ? ruins.find((row) => row.entity.id === ui.selected) : undefined- const pickedPark = ui.selected !== null ? parkRows.find((row) => row.entity.id === ui.selected) : undefined- const picked = pickedPark ? parkOf(pickedPark.data.tile.get()) : undefined- if (pickedBuilding) {- const { kind, status, problem, state, groups } = describeBuilding(pickedBuilding)- const standing = !pickedBuilding.data.site.present && !pickedBuilding.data.rising.present- const pausable = kind.id !== "townhall" && standing- const level = pickedBuilding.data.upgraded.value()?.level ?? 0- const now = upgradeAt(kind, level)- const works = pickedBuilding.data.works.value()- 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), 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- // An upgrade under way: what it is to become, and what carriers still have to bring.- const worksOf = works- ? { title: upgradeAt(kind, works.level)!.title, share: worksShare(works)!,- left: costText({ coins: 0, materials: Object.fromEntries(goodIds.filter((g) => works.owed[g] > 0).map((g) => [g, works.owed[g]])) }) }- : null- if (worksOf)- groups.unshift({- title: `becoming ${anA(worksOf.title.toLowerCase())}`,- icon: "build",- lines: [{ icon: "build", label: "built", value: `${Math.round(worksOf.share * 100)}%`, tone: "warn", note: worksOf.left ? `carriers still bring ${worksOf.left}; it works on meanwhile` : "every material is in; the builders are working it in, and it works on meanwhile" }]- })- ui.panel = {- type: "building",- id: pickedBuilding.entity.id,- cell: pickedBuilding.data.tile.get(),- kind: kind.id,- title: now?.title ?? kind.title,- blurb: now?.blurb ?? kind.blurb,- status,- problem,- state,- groups,- pausable,- paused: pickedBuilding.data.paused.present,- salvage: salvageFor(builtCost(kind, level), pickedBuilding.data.site.value(), works && { kind, ...works }),- level,- upgraded: level > 0,- upgrade: upgradeOffer,- works: worksOf- }- } else if (pickedHouse) {- const { h, summary, trouble, groups } = describeHouse(pickedHouse)- ui.panel = {- type: "house", id: pickedHouse.entity.id, cell: pickedHouse.data.tile.get(), tier: h.tier, summary, trouble, groups,- closable: !pickedHouse.data.site.present && !pickedHouse.data.rising.present && !pickedHouse.data.burning.present,- closed: pickedHouse.data.closed.present,- salvage: salvageFor(home.cost, pickedHouse.data.site.value())- }- } else if (pickedPark && picked) {- ui.panel = {- type: "park",- id: pickedPark.entity.id,- cell: pickedPark.data.tile.get(),- cells: picked.cells.length,- value: picked.value,- reach: picked.reach,- lines: describePark(picked)- }- } else if (pickedRuin) {- const r = pickedRuin.data.ruin.get()- ui.panel = {- type: "ruin",- id: pickedRuin.entity.id,- cell: pickedRuin.data.tile.get(),- cause: r.cause,- lines: [- { icon: "condition", label: "what happened", value: r.cause === "burnt" ? "it burned down" : r.cause === "collapsed" ? "it fell down for want of mending" : "it was left derelict after its thefts", tone: "bad" },- { icon: "appeal", label: "desirability nearby", value: "−3", tone: "warn", note: "until it is cleared: bulldoze it" }- ]- }- } else ui.panel = ui.menu ? { type: ui.menu } : null-- const centres = new Map<number, Point>()- for (const { entity, data } of [...buildings, ...houses]) {- const t = data.tile.get()- centres.set(entity.id, { x: t.x + t.size / 2, y: t.y + t.size / 2 })- }- ui.centres = centres-- // ── Map views ──- const view = ui.view- const overlayKey = `${view}|${Math.floor(tick / 30)}|${ui.selected}|${buildings.length}|${houses.length}`- if (view === "none") {- if (ui.overlay.key !== "none") ui.overlay = { key: "none", cells: [] }- if (ui.tints.size > 0) ui.tints = new Map()- ui.legend = null- } else if (ui.overlay.key !== overlayKey) {- const out: Array<OverlayCell> = []- // The same reading washed over each model, so the view is legible where buildings hide the ground.- const tints = new Map<number, number>()- const tintOf = (color: number) => (color === GOOD ? TINT.good : color === FAIR ? TINT.fair : color === BAD ? TINT.bad : color === COOL ? TINT.cool : TINT.plain)- const standing = <T extends { readonly data: { readonly site: { readonly present: boolean }; readonly rising: { readonly present: boolean } } }>(rows: ReadonlyArray<T>) =>- rows.filter(({ data }) => !data.site.present && !data.rising.present)- if (view === "appeal") {- for (let y = 0; y < GRID; y++)- for (let x = 0; x < GRID; x++) {- const use = useAt(grid, x, y)- if (use === "void" || use === "water") continue- out.push({ x, y, size: 1, color: appealColor(appealAt(cells, x, y)), alpha: 0.32 })- }- for (const { entity, data } of standing(houses)) {- const t = data.tile.get()- const d = appealAt(cells, t.x, t.y)- tints.set(entity.id, d >= home.tiers[2].appeal ? TINT.fine : d >= 0 ? TINT.plain : d > home.squalid ? TINT.fair : TINT.bad)- }- } else if (view === "workers") {- const picked = pickedBuilding && pickedBuilding.data.staff.get().needed > 0 ? pickedBuilding : undefined- let inReach: ((t: TileLike) => boolean) | null = null- if (picked) {- const roads = reach(grid, doors(grid, picked.data.tile.get()))- for (let k = 0; k < roads.distance.length; k++) {- const d = roads.distance[k]!- if (d >= 0 && d <= COMMUTE) out.push({ x: k % GRID, y: Math.floor(k / GRID), size: 1, color: MARK, alpha: 0.14 })- }- inReach = (t) => doors(grid, t).some((c) => {- const n = roads.distance[key(c.x, c.y)]!- return n >= 0 && n <= COMMUTE- })- }- for (const { entity, data } of standing(houses)) {- const t = data.tile.get()- const h = data.house.get()- const ring = inReach !== null && inReach(t)- out.push({ ...t, color: h.tier === 1 ? 0xd6b48a : COOL, alpha: ring ? 0.75 : 0.45, ...(ring ? { ring: true } : {}) })- tints.set(entity.id, h.tier === 1 ? TINT.settlers : TINT.cool)- }- for (const { entity, data } of standing(buildings)) {- const s = data.staff.get()- if (s.needed === 0) continue- const color = s.assigned >= s.needed ? GOOD : s.assigned > 0 ? FAIR : BAD- out.push({ ...data.tile.get(), color, alpha: 0.45, ...(entity.id === picked?.entity.id ? { ring: true } : {}) })- tints.set(entity.id, tintOf(color))- }- } else if (view === "fire" || view === "health" || view === "order") {- for (const { entity, data } of standing(houses)) {- const r = data.risk.value()- if (!r) continue- const struck = view === "fire" ? data.burning.present : view === "health" ? data.sick.present : r.thefts > 0- const color = struck ? BAD : meterColor(r[view], RISK_MAX, risk.warn)- out.push({ ...data.tile.get(), color, alpha: struck ? 0.8 : 0.5 })- tints.set(entity.id, tintOf(color))- }- for (const { entity, data } of standing(buildings)) {- const service = data.service.value()?.service- const r = data.risk.value()- if (service === view) {- out.push({ ...data.tile.get(), color: MARK, alpha: 0.55, ring: true })- tints.set(entity.id, TINT.mark)- } else if (view === "fire" && r) {- const color = data.burning.present ? BAD : meterColor(r.fire, RISK_MAX, risk.warn)- out.push({ ...data.tile.get(), color, alpha: 0.4 })- tints.set(entity.id, tintOf(color))- }- }- } else if (view === "condition") {- for (const row of [...standing(houses), ...standing(buildings)]) {- const c = row.data.condition.value()- if (!c) continue- const color = c.value < wear.worn ? BAD : c.value < wear.mend ? FAIR : GOOD- out.push({ ...row.data.tile.get(), color, alpha: 0.5 })- tints.set(row.entity.id, tintOf(color))- }- for (const { entity, data } of standing(buildings)) if (data.service.value()?.service === "repair") {- out.push({ ...data.tile.get(), color: MARK, alpha: 0.55, ring: true })- tints.set(entity.id, TINT.mark)- }- for (const { data } of ruins) out.push({ ...data.tile.get(), color: BAD, alpha: 0.8 })- }- ui.overlay = { key: overlayKey, cells: out }- ui.tints = tints- ui.legend = legends[view]- }-- // ── What needs looking at ──- const alerts: Array<Notice> = []- const census = resources.census.get()- const stock = resources.stock.get()- /** A building of this kind stands (built, not a site). */- const stands = (k: KindId) => buildings.some(({ data }) => data.building.get().kind === k && !data.site.present && !data.rising.present)- // Each line says what is wrong, then what to do about it.- const burningRow = [...buildings, ...houses].find(({ data }) => data.burning.present)- const fireText = `${census.burning} on fire: ${stands("firewatch") ? "the fire watch's firefighters are on their way" : "build a fire watch nearby, whose firefighters put fires out"}`- if (census.burning > 0) alerts.push({ tone: "bad", text: fireText, at: burningRow?.data.tile.get() ?? null, size: burningRow?.data.tile.get().size ?? 1, id: burningRow?.entity.id ?? null })- const sickRow = houses.find(({ data }) => data.sick.present)- const sickText = `${census.sick} home${census.sick > 1 ? "s" : ""} sick, holding half as many people: ${stands("healer") || stands("hospital") ? "a healer within reach of its road cures it" : "build a healer among the homes"}`- if (census.sick > 0) alerts.push({ tone: "warn", text: sickText, at: sickRow?.data.tile.get() ?? null, size: 1, id: sickRow?.entity.id ?? null })- const waiting = new Map<string, { n: number; at: TileLike; id: number; kind: KindId }>()- const remote = new Map<string, { n: number; at: TileLike; id: number; kind: KindId }>()- const shortStaffed: Array<{ id: number; title: string; cell: Point; size: number; assigned: number; needed: number; nobodyNear: boolean }> = []- const seen = new Set<number>()- for (const { entity, data } of buildings) {- if (data.site.present || data.rising.present || data.paused.present) continue- const kind = kinds[data.building.get().kind]- const status = data.status.get()- const staff = data.staff.get()- const tile = data.tile.get()- if (status === "starved" && kind.recipe?.input) {- seen.add(entity.id)- const since = starvedSince.get(entity.id) ?? tick- if (!starvedSince.has(entity.id)) starvedSince.set(entity.id, tick)- if (tick - since >= ALERT_PATIENCE) {- const label = `${kind.title.toLowerCase()} needs ${kind.recipe.input}`- const was = waiting.get(label)- waiting.set(label, was ? { ...was, n: was.n + 1 } : { n: 1, at: tile, id: entity.id, kind: kind.id })- }- }- if (staff.needed > 0 && staff.assigned < staff.needed) shortStaffed.push({ id: entity.id, title: kind.title.toLowerCase(), cell: tile, size: tile.size, assigned: staff.assigned, needed: staff.needed, nobodyNear: staff.nearby === 0 })- if (status === "unstaffed" && staff.nearby === 0) {- const label = kind.title.toLowerCase()- const was = remote.get(label)- remote.set(label, was ? { ...was, n: was.n + 1 } : { n: 1, at: tile, id: entity.id, kind: kind.id })- }- }- for (const id of [...starvedSince.keys()]) if (!seen.has(id)) starvedSince.delete(id)- const list = (m: Map<string, { n: number }>) => [...m].map(([k, v]) => `${k}${v.n > 1 ? ` ×${v.n}` : ""}`).join(", ")- const first = (m: Map<string, { at: TileLike; id: number }>) => [...m.values()][0]- const placesOf = (m: Map<string, { at: TileLike; id: number; kind: KindId }>) =>- Object.fromEntries([...m.values()].map((v) => [v.kind, { at: v.at, size: v.at.size, id: v.id }]))- if (waiting.size > 0) alerts.push({ tone: "warn", text: `idle: the ${list(waiting)}. Build more of what makes it, or buy it in the [town] panel`, at: first(waiting)?.at ?? null, size: first(waiting)?.at.size ?? 1, id: first(waiting)?.id ?? null, places: placesOf(waiting) })- if (remote.size > 0) alerts.push({ tone: "warn", text: `no workers for the ${list(remote)}: lay [homes] within ${COMMUTE} road cells of it, or a road to homes nearby`, at: first(remote)?.at ?? null, size: first(remote)?.at.size ?? 1, id: first(remote)?.id ?? null, places: placesOf(remote) })- const hallRow = buildings.find(({ data }) => data.hall.present)- const empty = census.homes > 0 && larder(stock) === 0- if (!empty || (emptySince !== null && emptySince > tick)) emptySince = null- if (empty && emptySince === null) emptySince = tick- if (empty && tick - emptySince! >= HUNGER_PATIENCE) hungryUntil = tick + HUNGER_PATIENCE- if (hungryUntil > tick + HUNGER_PATIENCE) hungryUntil = 0- if (census.homes > 0 && tick < hungryUntil) alerts.push({ tone: "bad", text: "no food in store, so homes go hungry and pay no taxes: build another fishery, or buy fish in the [town] panel", at: hallRow?.data.tile.get() ?? null, size: hallRow?.data.tile.get().size ?? 1, id: hallRow?.entity.id ?? null })- // ── Upgrades: what the town could upgrade, kind by kind and level by level ──- const rank = resources.fate.get().rank- const upgradeRows = new Map<string, { kind: KindId; level: number; ready: number; underway: number; first: (typeof buildings)[number] | null }>()- // Every buildable kind's first upgrade is listed, built or not, so the menu says what is to come; the town hall's by where it stands.- for (const id of kindOrder) if (kinds[id].upgrade) upgradeRows.set(`${id}:0`, { kind: id, level: 0, ready: 0, underway: 0, first: null })- for (const row of buildings) {- const { data } = row- if (data.site.present || data.rising.present) continue- const kind = kinds[data.building.get().kind]- const level = data.upgraded.value()?.level ?? 0- const works = data.works.value()- const from = works ? works.level - 1 : level- if (!nextUpgrade(kind, from)) continue- const k = `${kind.id}:${from}`- const entry = upgradeRows.get(k) ?? { kind: kind.id, level: from, ready: 0, underway: 0, first: null }- if (works) entry.underway += 1- else {- entry.ready += 1- entry.first ??= row- }- upgradeRows.set(k, entry)- }- const upgrades = [...upgradeRows.values()].map((r) => {- const kind = kinds[r.kind], up = nextUpgrade(kind, r.level)!- return {- kind: r.kind, level: r.level, from: (upgradeAt(kind, r.level)?.title ?? kind.title).toLowerCase(), to: up.title.toLowerCase(), blurb: up.blurb,- coins: up.cost.coins, materials: up.cost.materials, price: upgradePrice(up), changes: upgradeChanges(kind, r.level),- blocked: upgradeBlock(up, rank, { ranks }), ready: r.ready, underway: r.underway, first: r.first- }- })- // 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, row.data.upgraded.value()?.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 = dueFirst.data.upgraded.value()?.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)- let suppliedTaxes = 0- for (const { data } of houses) {- if (data.site.present || data.rising.present || data.burning.present) continue- const tile = data.tile.get()- suppliedTaxes += suppliedTaxOf(data.house.get(), rates, undefined, appealAt(cells, tile.x, tile.y))- }- const coins = resources.treasury.get().coins- const net = ledger.taxes + ledger.trade - ledger.upkeep - ledger.admin- const mood = resources.mood.get()- const crown = resources.crown.get()- // What the homes would pay at each step of each tier's rate, once settled there (see `taxOutlook`).- const taxed: Array<TaxedHome> = []- for (const { data } of houses) {- if (data.site.present || data.rising.present || data.burning.present || data.closed.present) continue- const tile = data.tile.get()- taxed.push({ ...data.house.get(), desirability: appealAt(cells, tile.x, tile.y), paying: true })- }- const f = resources.fate.get()- const pantry = resources.pantry.get()- const season = seasonAt(Math.min(Math.max(0, t), f.began + termTicks(charter) - 1), charter)- const approvalAt = (r: { readonly settlers: number; readonly citizens: number }, memory: number) =>- approvalTarget(taxed, r, coins, crown.snubs.length, season.winter, undefined, memory).target- const outlookOf = (tier: "settlers" | "citizens") => taxed.some((h) => (h.tier === 1) === (tier === "settlers"))- ? TAX_STEPS.map((rate) => ({ rate, taxes: Math.round(taxOutlook(taxed, rates, tier, rate, approvalAt)) }))- : []- const seconds = (steps: number) => Math.max(0, Math.ceil(steps / 60))- const danger = (since: number, minutes: number) => (since < 0 ? null : seconds(since + minutes * 3600 - t))- // The winter after the coming one, for the almanac.- const comingYear = season.winter || winterOf(charter, season.year) === null ? season.year + 1 : season.year-- // ── The mayor's guide ──- // The page writes what the mayor told it; then the guide puts away what the town has done, and picks the step to show.- // Only the simulation writes the guide: both go to it as edits, and count here until it has applied them.- const pending = local.guide- for (const action of ui.guide.splice(0)) {- if (action.type === "skip") {- pending.done.add(action.id)- ui.edits.push({ type: "guide", done: [action.id] })- } else {- pending.off = action.type === "off"- ui.edits.push({ type: "guideOff", off: pending.off })- }- }- 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 wornRow = buildings.find((row) => finished(row) && !row.data.hall.present && (row.data.condition.value()?.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) => {- const h = row.data.house.get()- if (h.tier !== 1 || !finished(row)) return false- const tile = row.data.tile.get()- return met(h, "bread") && met(h, "cloth") && met(h, "faith") && appealAt(cells, tile.x, tile.y) < home.tiers[2].appeal- })- const saved = resources.guide.get()- for (const id of saved.done) pending.done.delete(id)- if (pending.off === saved.off) pending.off = null- const guide = { done: [...saved.done, ...pending.done], off: pending.off ?? saved.off }- const put = new Set(guide.done)- /** A road within two cells of water: reckoned only until the guide's road step is put away. */- const roadNearWater = () => {- for (let y = 0; y < GRID; y++) {- for (let x = 0; x < GRID; x++) {- if (useAt(grid, x, y) !== "road") continue- for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) if (useAt(grid, x + dx, y + dy) === "water") return true- }- }- return false- }- const facts: GuideFacts = {- homes: houses.length,- builtHomes: houses.filter(finished).length,- residents: census.settlers + census.citizens,- citizens: census.citizens,- finerHomes: houses.filter((row) => row.data.house.get().tier > 1).length,- placed: placedKinds,- standing: standingKinds,- stock,- sick: census.sick,- burning: census.burning,- winter: season.winter,- winterIn: season.coming === null ? null : seconds(season.left),- worn: wornRow !== undefined,- poorStreet: poorRow !== undefined,- crown: { open: crown.open, met: crown.met },- net: steadyNet(resources.history.get().samples, net),- approval: mood.approval,- trading: rates.sells.length > 0 || rates.buys.length > 0,- buysTools: rates.buys.includes("tools"),- taxed: rates.settlers !== 100 || rates.citizens !== 100,- most: Math.max(...goodIds.map((g) => stock[g])),- sawTown: ui.menu === "town",- sawHome: houses.some((row) => row.entity.id === ui.selected),- sawBuilding: buildings.some((row) => row.entity.id === ui.selected && !row.data.hall.present),- roadToWater: put.has("road") || roadNearWater(),- coins,- unreached: put.has("market") || standingKinds.has("market") ? 0 : unreachedHomes(),- rank: f.rank,- upgraded: new Set(buildings.filter((row) => row.data.upgraded.present).map((row) => row.data.building.get().kind)),- risk: {- fire: houses.some((row) => (row.data.risk.value()?.fire ?? 0) >= RISK_MAX * 0.35),- health: houses.some((row) => (row.data.risk.value()?.health ?? 0) >= RISK_MAX * 0.35),- order: houses.some((row) => (row.data.risk.value()?.order ?? 0) >= RISK_MAX * 0.35)- },- fewTrees: buildings.some((row) => {- if (row.data.building.get().kind !== "lumberjack" || !finished(row)) return false- const tile = row.data.tile.get()- const reach = kinds.lumberjack.gathers!.radius- return queries.trees.each().map(({ data }) => data.tile.get()).filter((t) => t.x >= tile.x - reach && t.x < tile.x + tile.size + reach && t.y >= tile.y - reach && t.y < tile.y + tile.size + reach).length < 6- })- }- const playing = f.state === "playing" && !ui.founding- const newly = playing ? guideDone(facts, put) : []- if (newly.length > 0) {- ui.edits.push({ type: "guide", done: newly })- for (const id of newly) {- put.add(id)- pending.done.add(id)- }- }- // The guide keeps quiet a while after a step is put away; a new town (the clock gone back) starts it afresh.- if (t < guidePace.since) Object.assign(guidePace, { shown: null, since: 0, quietUntil: 0 })- if (guidePace.shown !== null && put.has(guidePace.shown)) Object.assign(guidePace, { shown: null, quietUntil: t + GUIDE_QUIET * 60 })- const step = guide.off || !playing ? null : guideStep(facts, put, { shown: guidePace.shown, quiet: t < guidePace.quietUntil })- if (step && !step.urgent?.(facts)) guidePace.shown = step.id- guidePace.since = t- const hallTile = hallRow?.data.tile.get()- /** Of some tiles, the one nearest the town hall. */- const nearestHall = (tiles: ReadonlyArray<TileLike>): TileLike | undefined => {- if (!hallTile) return tiles[0]- let best: TileLike | undefined- let far = Infinity- for (const tile of tiles) {- const d = Math.abs(tile.x - hallTile.x) + Math.abs(tile.y - hallTile.y)- if (d < far) [best, far] = [tile, d]- }- return best- }- const focusOf = (focus: GuideFocus | null): { at: TileLike | null; id: number | null } => {- if (focus === null) return { at: null, id: null }- if (focus === "hall") return { at: hallTile ?? null, id: null }- if (focus === "water") return { at: nearestHall(queries.water.each().map(({ data }) => data.tile.get())) ?? null, id: null }- if (focus === "trees") return { at: nearestHall(queries.trees.each().map(({ data }) => data.tile.get())) ?? null, id: null }- if (focus === "stone" || focus === "ore") {- const ore = focus === "ore"- return { at: nearestHall(queries.rocks.each().filter(({ data }) => data.rock.get().ore === ore).map(({ data }) => data.tile.get())) ?? null, id: null }- }- const row = focus === "worn" ? wornRow : focus === "poorStreet" ? poorRow : buildings.find(({ data }) => data.building.get().kind === focus.kind)- return row ? { at: row.data.tile.get(), id: row.entity.id } : { at: null, id: null }- }- const shown = step ? focusOf(step.focus) : null- const flowNow = resources.flow.get().last- const flowHeld = resources.flow.get().held- ui.stats = {- coins,- taxes: ledger.taxes,- suppliedTaxes: Math.round(suppliedTaxes),- taxOutlook: { settlers: outlookOf("settlers"), citizens: outlookOf("citizens") },- trade: ledger.trade,- upkeep: ledger.upkeep,- admin: ledger.admin,- net,- homes: census.homes,- needs: { food: census.food, bread: census.bread, cloth: census.cloth, faith: census.faith, furniture: census.furniture },- townhouses: houses.filter(({ data }) => data.house.get().tier === 3).length,- policy: rates,- stock,- prices: resources.market.get().prices,- settlers: census.settlers,- citizens: census.citizens,- burghers: census.burghers,- jobs: census.jobs,- employed: census.employed,- shortStaffed,- charter: { size: charter.size, term: charter.term, land: charter.land, seed: charter.seed },- minute: t / 3600,- season: {- year: season.year,- winter: season.winter,- left: seconds(season.left),- severity: season.severity,- coming: season.coming,- after: winterOf(charter, comingYear + 1)- },- mood: {- approval: mood.approval,- target: mood.target,- parts: [- { label: "mood of the town", value: mood.base },- { label: "needs met", value: mood.needs },- { label: "taxes now", value: mood.taxes },- { label: "a grudge over taxes past", value: mood.grudge },- { label: "unpaid wages", value: mood.debt },- { label: "the crown's displeasure", value: mood.crown },- { label: "a hungry winter", value: mood.winter }- ].filter((p) => p.value !== 0)- },- crown: {- open: crown.open,- good: crown.good,- amount: crown.amount,- left: seconds(crown.due - t),- reward: crown.reward,- met: crown.met,- missed: crown.missed,- streak: crown.streak,- patience: crownRules.patience,- next: seconds(crown.next - t)- },- fate: {- state: f.state,- reason: f.reason,- at: f.at / 3600,- term: f.term,- began: f.began / 3600,- rank: f.rank,- rankTitle: ranks[f.rank]?.title ?? "",- nextTitle: f.rank + 1 < ranks.length ? ranks[f.rank + 1]!.title : null,- score: f.score,- bankrupt: danger(f.debtSince, fate.debt),- revolt: danger(f.revoltSince, fate.revolt),- rises: danger(f.goalSince, fate.hold),- peak: f.peak- },- goals: goalsOf(- charter,- { settlers: census.settlers, citizens: census.citizens, burghers: census.burghers, coins, net: steadyNet(resources.history.get().samples, net), approval: mood.approval,- hall: hallRow ? hallRow.data.upgraded.value()?.level ?? 0 : 0 },- undefined,- f.rank- ),- larder: larder(stock),- flow: flowNow === null ? null : { ...flowNow, elsewhere: amounts(Object.fromEntries(goodIds.map((g) => [g, Math.max(0, flowHeld[g] - stock[g])]))) },- eaten: pantry.eatenLast,- rotted: pantry.rottedLast,- sick: census.sick,- burning: census.burning,- history: resources.history.get().samples,- chronicle: resources.chronicle.get().lines,- alerts,- upgrades: upgrades.map(({ first: _first, ...u }) => u),- guide: {- step:- step && shown- ? {- key: step.id,- chapter: step.chapter,- goal: step.goal,- text: step.action,- why: step.why,- waiting: step.waiting?.(facts) ?? null,- locked: lockedNote(step, facts),- next: upcoming(facts, put),- asks: step.asks ?? [],- near: step.focus !== null && typeof step.focus === "object" && shown.id !== null ? step.focus.kind : null,- count: courseCount(step),- at: shown.at,- size: shown.at?.size ?? 1,- id: shown.id- }- : null,- done: guideSteps.filter((s) => put.has(s.id)).length,- total: guideSteps.length,- off: guide.off- }- }- }-)--// ── Views ─────────────────────────────────────────────────────────────────--export const RenderBuildings = RenderSync.system(Game, {- name: "Town/RenderBuildings",- renderable: Building,- transform: Tile,- registry: BuildingNodes,- services: { stage: StageService },- create: ({ renderable, services, entity }) => new BuildingView(renderable.kind, services.stage, entity),- apply: (node, { transform }) => node.place(transform.x, transform.y)-})--export const RenderHouses = RenderSync.system(Game, {- name: "Town/RenderHouses",- renderable: House,- transform: Tile,- registry: HouseNodes,- services: { stage: StageService },- create: ({ services, entity }) => new HouseView(services.stage, entity),- apply: (node, { transform }) => node.place(transform.x, transform.y)-})--export const RenderWalkers = RenderSync.system(Game, {- name: "Town/RenderWalkers",- renderable: Figure,- registry: WalkerNodes,- services: { stage: StageService },- create: ({ renderable, services, entity }) => WalkerView.forFigure(renderable.role, renderable.color, services.stage, entity),- apply: () => {}-})--export const RenderTrees = RenderSync.system(Game, {- name: "Town/RenderTrees",- renderable: Tree,- transform: Tile,- registry: TreeNodes,- services: { stage: StageService },- create: ({ services, entity }) => new TreeView(services.stage, entity),- apply: (node, { transform }) => node.place(transform.x, transform.y)-})--export const RenderRocks = RenderSync.system(Game, {- name: "Town/RenderRocks",- renderable: Rock,- transform: Tile,- registry: RockNodes,- services: { stage: StageService },- create: ({ services, entity }) => new RockView(services.stage, entity),- apply: (node, { transform }) => node.place(transform.x, transform.y)-})--export const RenderRuins = RenderSync.system(Game, {- name: "Town/RenderRuins",- renderable: Ruin,- transform: Tile,- registry: RuinNodes,- services: { stage: StageService },- create: ({ renderable, services, entity }) => new RuinView(renderable.cause, services.stage, entity),- apply: (node, { transform }) => node.place(transform.x, transform.y, transform.size)-})--export const RenderFields = RenderSync.system(Game, {- name: "Town/RenderFields",- renderable: Field,- transform: Tile,- registry: FieldNodes,- services: { stage: StageService },- create: ({ services, entity }) => new FieldView(services.stage, entity),- apply: (node, { transform }) => node.place(transform.x, transform.y)-})--/** The land, redrawn when a new town is founded (or one loaded), and frosted through winter. */-export const DrawLand = Game.System(- "Town/DrawLand",- {- resources: { land: Game.System.readResource(Land), time: Game.System.readResource(Time), charter: Game.System.readResource(Charter), fate: Game.System.readResource(Fate) },- services: { stage: Game.System.service(StageService) }- },- ({ resources, services }) => {- const mask = resources.land.get().mask- const charter = resources.charter.get()- const t = elapsed(resources.time.get(), charter)- services.stage.setLand(mask, t > 0 && seasonAt(Math.min(t, resources.fate.get().began + termTicks(charter) - 1), charter).winter)- }-)--/** The map view, washed over the town. */-export const DrawOverlay = Game.System(- "Town/DrawOverlay",- { services: { ui: Game.System.service(Ui), stage: Game.System.service(StageService) } },- ({ services }) => {- services.stage.setOverlay(services.ui.overlay.key, services.ui.overlay.cells)- }-)--/** Roads, water, and parks, each redrawn as one layer whenever one is laid or anything is removed. */-export const DrawGround = Game.System(- "Town/DrawGround",- {- queries: {- roads: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road] }),- paved: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road, Paved] }),- water: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Water] }),- parks: ParkRead,- /** A tile laid, a road paved, or a park relaid. */- laid: Game.Query({ selection: {}, filters: [Game.Query.anyOf(Game.Query.added(Tile), Game.Query.added(Paved), Game.Query.changed(Park))] })- },- despawned: { entities: Game.System.readDespawned() },- services: { stage: Game.System.service(StageService) }- },- ({ queries, despawned, services }) => {- const dirty = services.stage.groundDirty- if (!dirty && queries.laid.each().length === 0 && despawned.entities.all().length === 0) return- const cellsOf = (rows: ReadonlyArray<{ readonly data: { readonly tile: { get(): TileLike } } }>) =>- new Set(rows.map(({ data }) => key(data.tile.get().x, data.tile.get().y)))- const roads = cellsOf(queries.roads.each())- services.stage.setGround(roads, cellsOf(queries.water.each()), cellsOf(queries.paved.each()))- services.stage.setParks(new Map(queries.parks.each().map(({ data }) => [key(data.tile.get().x, data.tile.get().y), { ...data.tile.get(), ...data.park.get() }])), roads)- }-)--/**- * Where a walker stands, in cells: on the lattice, a little to one side of- * the road's middle; which way it faces; and which foot is forward.- */-const walkerAt = (route: { readonly cells: ReadonlyArray<Point>; readonly index: number; readonly step: number }) => {- const here = route.cells[route.index]!- const next = route.cells[route.index + 1]- const before = route.cells[route.index - 1]- const dir = next ? { x: next.x - here.x, y: next.y - here.y } : before ? { x: here.x - before.x, y: here.y - before.y } : { x: 0, y: 0 }- const units = next ? Math.floor(route.step / (CELL_STEPS / 16)) : 0- const along = units * U- const side = 2 * U- return {- x: here.x + 0.5 + dir.x * along - dir.y * side,- y: here.y + 0.5 + dir.y * along + dir.x * side,- dir,- phase: next ? Math.floor(units / 3) % 2 : 0- }-}--export const Animate = Game.System(- "Town/Animate",- {- queries: {- buildings: BuildingRead,- houses: HouseRead,- ruins: RuinRead,- walkers: Game.Query({- selection: {- route: Game.Query.read(Route),- errand: Game.Query.optional(Errand),- roam: Game.Query.optional(Roam),- rescue: Game.Query.optional(Rescue)- }- }),- trees: Game.Query({ selection: { tree: Game.Query.read(Tree) } }),- rocks: Game.Query({ selection: { rock: Game.Query.read(Rock), tile: Game.Query.read(Tile) } }),- 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), time: Game.System.readResource(Time) },- services: {- stage: Game.System.service(StageService),- ui: Game.System.service(Ui),- clock: Game.System.service(Clock),- ruinNodes: Game.System.service(RuinNodes),- buildingNodes: Game.System.service(BuildingNodes),- houseNodes: Game.System.service(HouseNodes),- walkerNodes: Game.System.service(WalkerNodes),- treeNodes: Game.System.service(TreeNodes),- rockNodes: Game.System.service(RockNodes),- fieldNodes: Game.System.service(FieldNodes)- }- },- ({ queries, resources, services }) => {- const grid = resources.grid.get()- const cells = resources.appeal.get().cells- const { hover, danger } = services.ui.preview- const emphasis = (id: number): Emphasis => (danger && hover === id ? "danger" : "normal")- const dt = services.clock.deltaSeconds- // Fish where the water would give a catch now; none where it rests after one.- const tick = resources.time.get().step- services.stage.setFish(queries.water.each().filter(({ data }) => tick - data.water.get().fished >= RESTOCK_TICKS).map(({ data }) => data.tile.get()))-- for (const { entity, data } of queries.buildings.each()) {- const kind = kinds[data.building.get().kind]- const status = data.status.get()- // An upgrade the town needs now, and can make (see `upgradesWanted`).- const upgradable = services.ui.wanted.has(entity.id)- const recipe = data.recipe.value()- const walkers = data.walkers.value()?.length ?? 0- const worn = (data.condition.value()?.value ?? CONDITION_MAX) < wear.worn- const r = data.risk.value()- services.buildingNodes.get(entity.id)?.update(- {- alert: alertOf(r ? { fire: r.fire, health: 0, order: 0 } : undefined, false, worn),- burning: data.burning.present,- worn,- effects: {- wear: 1-(data.condition.value()?.value??CONDITION_MAX)/CONDITION_MAX,- fireRisk: hazardStrength(r?.fire??0,risk.warn,RISK_MAX)- },- working: status === "working",- tint: services.ui.tints.get(entity.id),- problem: problemOf(kind, status) !== null,- build: buildOf(data.site.value(), data.rising.value()),- beat: recipe ? recipe.made : data.service.value() ? walkers : 0,- doors: doorsOf(grid, data.tile.get()),- site: siteShare(data.site.value()),- level: data.upgraded.value()?.level ?? 0,- works: worksShare(data.works.value()),- upgradable- },- dt,- emphasis(entity.id)- )- }- for (const { entity, data } of queries.houses.each()) {- const tile = data.tile.get()- const worn = (data.condition.value()?.value ?? CONDITION_MAX) < wear.worn- const desirability = appealAt(cells, tile.x, tile.y)- services.houseNodes- .get(entity.id)- ?.update(- {- tier: data.house.get().tier,- build: buildOf(data.site.value(), data.rising.value()),- doors: doorsOf(grid, tile),- site: siteShare(data.site.value()),- alert: data.site.present ? null : alertOf(data.risk.value(), data.sick.present, worn),- burning: data.burning.present,- worn,- effects: {- wear: Math.max(desirability<0?0.55:0,1-(data.condition.value()?.value??CONDITION_MAX)/CONDITION_MAX),- fireRisk: hazardStrength(data.risk.value()?.fire??0,risk.warn,RISK_MAX),- health: hazardStrength(data.risk.value()?.health??0,risk.warn,RISK_MAX),- order: hazardStrength(data.risk.value()?.order??0,risk.warn,RISK_MAX),- sick: Number(data.sick.present)- },- band: desirability < 0 ? "poor" : desirability >= home.tiers[2].appeal ? "fine" : "plain",- closed: data.closed.present,- tint: services.ui.tints.get(entity.id)- },- emphasis(entity.id)- )- }- for (const { entity } of queries.ruins.each()) services.ruinNodes.get(entity.id)?.update(emphasis(entity.id))- for (const { entity, data } of queries.walkers.each()) {- const p = walkerAt(data.route.get())- const errand = data.errand.value()- const roam = data.roam.value()- const load: Load = errand- ? { kind: "cart", good: errand.good, count: !errand.back || errand.count > 0 ? errand.count : 0 }- : data.rescue.value()- ? { kind: "service", role: "firefighter" }- : roam?.service === "fire"- ? { kind: "service", role: "watchman" }- : roam?.service === "health"- ? { kind: "service", role: "physician" }- : roam?.service === "order"- ? { kind: "service", role: "constable" }- : roam?.service === "repair"- ? { kind: "service", role: "builder" }- : roam?.service === "faith"- ? { kind: "bell" }- : roam && total(roam.basket) > 0- ? { kind: "basket", goods: goodIds.filter((g) => roam.basket[g] > 0) }- : { kind: "none" }- services.walkerNodes.get(entity.id)?.update(p.x, p.y, p.dir, p.phase, load)- }- for (const { entity, data } of queries.trees.each())- services.treeNodes.get(entity.id)?.update(data.tree.get().growth, emphasis(entity.id))- // Neighbouring rocks are drawn as one big outcrop; the blocks are formed again only when a rock runs out (or the land changes).- const rocks = queries.rocks.each()- const rockKey = `${rocks.length}:${rocks.reduce((n, { entity }) => n + entity.id, 0)}`- if (rockKey !== rockShapes.key) {- rockShapes.key = rockKey- rockShapes.parts = rockBlocks(rocks.map(({ entity, data }) => ({ id: entity.id, ...data.tile.get(), ore: data.rock.get().ore })))- }- const amounts = new Map<number, number>(rocks.map(({ entity, data }) => [entity.id, data.rock.get().amount]))- for (const { entity, data } of rocks) {- const r = data.rock.get()- const part = rockShapes.parts.get(entity.id)- if (!part || !part.draws) services.rockNodes.get(entity.id)?.update(r.ore, r.amount, part ? 0 : 1, part ? 0 : 1)- else services.rockNodes.get(entity.id)?.update(r.ore, part.members.reduce((n, id) => n + (amounts.get(id) ?? 0), 0) / part.members.length, part.w, part.h)- }- for (const { entity, data } of queries.fields.each()) services.fieldNodes.get(entity.id)?.update(data.field.get().growth)- }-)--/** The guide's pace (page-side, not saved): the step it is showing, and until when it keeps quiet. */-const guidePace: { shown: string | null; since: number; quietUntil: number } = { shown: null, since: 0, quietUntil: 0 }--const rockShapes: { key: string; parts: Map<number, RockPart> } = { key: "", parts: new Map() }--/** Ghosts, the road being dragged, and outlines, redrawn every frame. */-export const DrawPreview = Game.System(- "Town/DrawPreview",- { services: { ui: Game.System.service(Ui), stage: Game.System.service(StageService), clock: Game.System.service(Clock) } },- ({ services }) => {- services.stage.setPreview(services.ui.preview, services.clock.elapsed)- }-)--/** Residents out walking (see `townsfolk.ts`), on the town's time: still while it waits. */-let townsfolk: { readonly folk: Townsfolk; land: string; generation: number; stage: unknown } | null = null-export const Stroll = Game.System(- "Town/Stroll",- {- queries: { houses: HouseRead },- resources: { grid: Game.System.readResource(Grid), land: Game.System.readResource(Land) },- services: { ui: Game.System.service(Ui), clock: Game.System.service(Clock), stage: Game.System.service(StageService) }- },- ({ queries, resources, services }) => {- const ui = services.ui- if (townsfolk?.stage !== services.stage) {- townsfolk?.folk.clear()- townsfolk = { folk: new Townsfolk(services.stage), land: "", generation: -1, stage: services.stage }- }- const mask = resources.land.get().mask- if (mask !== townsfolk.land || townsfolk.generation !== services.stage.generation) {- townsfolk.generation = services.stage.generation- townsfolk.land = mask- townsfolk.folk.clear()- }- const waiting = ui.founding || (ui.stats !== null && ui.stats.fate.state !== "playing")- const homes = queries.houses- .each()- .filter(({ data }) => !data.site.value() && !data.rising.value())- .map(({ data }) => ({ ...data.tile.get(), tier: data.house.get().tier, residents: data.house.get().residents }))- townsfolk.folk.step(waiting ? 0 : services.clock.deltaSeconds * ui.speed, homes, resources.grid.get())- }-)--export const present = Game.Schedule(- ShowFeedback,- Interact,- DrawLand,- RenderBuildings,- RenderHouses,- RenderWalkers,- RenderTrees,- RenderRocks,- RenderFields,- RenderRuins,- DrawGround,- DrawOverlay,- Animate,- Stroll,- DrawPreview-)diff --git a/src/view/preview.ts b/src/view/preview.tsnew file mode 100644index 0000000..7691082--- /dev/null+++ b/src/view/preview.ts@@ -0,0 +1,201 @@+/**+ * What the map shows besides the world while the player works: ghosts of+ * what would be laid, the road being dragged, outlines of what is picked and+ * what it reaches, and cells that will not take it.+ */+import { COMMUTE, costText, grounds, home, kinds, nextUpgrade, PAVE_COST, props, ranks, ROAD_COST, upgradeAt, type Kind, type Tier } from "../game/content/index.ts"+import { upgradeChanges, upgradePrice } from "../game/rules/upgrades.ts"+import { capacity, lockReason, taxOf, upgradeBlock } from "../game/schedule.ts"+import { moreAdmin } from "../game/rules/households.ts"+import { appealAt, type ParkCell } from "../game/world/appeal.ts"+import { canPlace, cellOf, doors, key, lPath, reach, useAt, type TileLike } from "../game/world/grid.ts"+import { inside, type Point } from "../game/world/iso.ts"+import { emptyPreview, type Interaction } from "./contracts.ts"+import { reachOf } from "./facts.ts"+import type { Frame } from "./frame.ts"+import { cellAt, footprintAt, rectangle } from "./interaction/geometry.ts"+import { placeProblem } from "./interaction/placing.ts"+import { counted, signed } from "./text.ts"++/**+ * What new cottages would bring in, fed, at the settlers' rate on their streets, less what they add to the+ * town hall's administration for their residents (see `moreAdmin`): the sum that turns once a town is large.+ */+const homesWorth = (frame: Frame, at: ReadonlyArray<Point>) => {+ const { houses, cells, approval, rates } = frame+ if (at.length === 0) return ""+ const standing = houses.filter((row) => !row.data.closed.present).reduce((n, row) => n + row.data.house.get().residents, 0)+ const fed = { tier: 1 as Tier, food: 1, bread: 0, cloth: 0, faith: 0, furniture: 0, residents: home.tiers[1].residents }+ let people = 0+ const pays = at.reduce((sum, c) => {+ const d = appealAt(cells, c.x, c.y), residents = capacity(fed, approval, d, undefined, rates.settlers)+ people += residents+ return sum + taxOf({ ...fed, residents }, rates, undefined, d)+ }, 0)+ const worth = Math.round(pays - moreAdmin(standing, people))+ return worth > 0 ? ` · ${signed(worth)} coins a minute once fed` : " · costs more to run than it pays: finer homes pay better"+}++/** The preview for this frame, and whether a stroke is being let go off the map (`dropping`). */+export const previewOf = (frame: Frame, ui: Interaction) => {+ const { grid, buildings } = frame++ const preview = emptyPreview()+ const pointer = ui.pointer+ const cell = pointer ? cellAt(pointer) : null+ preview.hover = pointer && (ui.tool === "select" || ui.tool === "bulldoze" || ui.tool === "upgrade") ? frame.pickAt(pointer, ui.pointerHit) : null+ const showReach = (tile: TileLike, kind: Kind) => {+ const r = reachOf(kind)+ if (r !== null) preview.plots.push({ x: tile.x - r, y: tile.y - r, size: tile.size + 2 * r, look: "reach" })+ }+ const pavedCells = new Set(frame.paved.map(({ data }) => key(data.tile.get().x, data.tile.get().y)))+ /** The road cells within `limit` of a tile's doors: what a service's walkers, or a commute, would reach from here. */+ const rangeFrom = (tile: TileLike, limit: number, note: string) => {+ const ds = doors(grid, tile)+ if (ds.length === 0) return+ const roads = reach(grid, ds)+ for (let k = 0; k < roads.distance.length; k++) {+ const d = roads.distance[k]!+ if (d >= 0 && d < limit) preview.range.push(cellOf(k))+ }+ preview.rangeNote = note+ }+ const rangeOfKind = (tile: TileLike, kind: Kind, range = kind.service?.range) => {+ if (kind.service && range !== undefined) rangeFrom(tile, range, `its walkers reach ${range} road cells from the door`)+ else if (kind.workers > 0) rangeFrom(tile, COMMUTE + 1, `its workers come from homes within ${COMMUTE} road cells`)+ }+ // Where the page is pointing (from the ticker): outlined for a few seconds.+ if (ui.flash) {+ if (Date.now() < ui.flash.until) preview.plots.push({ x: ui.flash.cell.x, y: ui.flash.cell.y, size: ui.flash.size, look: "picked" })+ else ui.flash = null+ }++ /** A cost `n` times over. */+ const times = (cost: Kind["cost"], n: number): Kind["cost"] => ({+ coins: cost.coins * n,+ materials: Object.fromEntries(Object.entries(cost.materials).map(([g, m]) => [g, (m ?? 0) * n]))+ })+ // Let go off the map (over the tool bar, say) and the stroke is dropped: it shows as blocked.+ const dropping = ui.stroke === "cancel" && ui.dragFrom !== null+ if (dropping && cell && (ui.tool === "road" || ui.tool === "home" || ui.tool === "pave" || ui.tool === "ground")) {+ for (const c of ui.tool === "ground" ? rectangle(ui.dragFrom!, cell) : lPath(ui.dragFrom!, cell))+ if (inside(c.x, c.y)) preview.plots.push({ ...c, size: 1, look: "blocked" })+ preview.tooltip = "let go here to cancel"+ } else if (ui.tool === "road" || ui.tool === "home" || ui.tool === "pave") {+ const cells = cell === null ? [] : ui.dragFrom ? lPath(ui.dragFrom, cell) : [cell]+ for (const c of cells) {+ if (!inside(c.x, c.y)) continue+ const free = canPlace(grid, { ...c, size: 1 })+ if (ui.tool === "road") {+ if (free) preview.roads.push(c)+ else if (useAt(grid, c.x, c.y) !== "road") preview.plots.push({ ...c, size: 1, look: "blocked" })+ } else if (ui.tool === "pave") {+ const road = useAt(grid, c.x, c.y) === "road"+ if (road && !pavedCells.has(key(c.x, c.y))) preview.plots.push({ ...c, size: 1, look: "reach" })+ else if (!road) preview.plots.push({ ...c, size: 1, look: "blocked" })+ } else if (free) preview.ghosts.push({ what: "home", cell: c })+ else preview.plots.push({ ...c, size: 1, look: "blocked" })+ }+ if (ui.tool === "home" && cell && inside(cell.x, cell.y)) {+ rangeFrom({ ...(ui.dragFrom ?? cell), size: 1 }, COMMUTE + 1, `residents walk to work within ${COMMUTE} road cells`)+ preview.tooltip = `homes · ${costText(home.cost)} each${preview.rangeNote ? homesWorth(frame, preview.ghosts.map((g) => g.cell)) : " · lay them beside a road"}`+ }+ if (ui.tool === "road" && cell) preview.tooltip = `road · ${ROAD_COST} coins a cell`+ if (ui.dragFrom && cell) {+ const n = ui.tool === "road" ? preview.roads.length : ui.tool === "home" ? preview.ghosts.length : preview.plots.filter((p) => p.look === "reach").length+ preview.stroke =+ ui.tool === "road"+ ? `${counted(n, "road cell")} · ${costText({ coins: n * ROAD_COST, materials: {} })}`+ : ui.tool === "home"+ ? `${counted(n, "home")} · ${costText(times(home.cost, n))}${homesWorth(frame, preview.ghosts.map((g) => g.cell))}`+ : `pave ${counted(n, "cell")} · ${costText({ coins: n * PAVE_COST.coins, materials: { stone: n * PAVE_COST.stone } })}`+ }+ } else if (ui.tool === "ground" && cell) {+ const laid: Array<ParkCell> = []+ for (const c of ui.dragFrom ? rectangle(ui.dragFrom, cell) : [cell]) {+ if (!inside(c.x, c.y)) continue+ const there = frame.parkAt.get(key(c.x, c.y))?.data.park.get()+ if (there ? there.ground !== ui.ground : canPlace(grid, { ...c, size: 1 })) laid.push({ ...c, ground: ui.ground, prop: there?.prop ?? "none" })+ else if (!there) preview.plots.push({ ...c, size: 1, look: "blocked" })+ }+ preview.parks.push(...laid)+ const after = laid.length > 0 ? frame.parkOf(laid[0]!, laid) : undefined+ const cost = costText(times(grounds[ui.ground].cost, laid.length))+ if (ui.dragFrom) preview.stroke = `${grounds[ui.ground].title.toLowerCase()} · ${counted(laid.length, "cell")} · ${cost}`+ preview.tooltip = `${grounds[ui.ground].title.toLowerCase()} · ${cost}${after ? ` · park ${signed(after.value)} desirability` : ""}`+ if (after) preview.plots.push(...frame.reachPlots(after))+ } else if (ui.tool === "prop" && cell && inside(cell.x, cell.y)) {+ const there = frame.parkAt.get(key(cell.x, cell.y))?.data.park.get()+ if (there) {+ const placed = { ...cell, ground: there.ground, prop: ui.prop }+ preview.parks.push(placed)+ const before = frame.parkOf(cell)+ const after = frame.parkOf(cell, [placed])+ preview.tooltip = `${props[ui.prop].title.toLowerCase()} · ${costText(props[ui.prop].cost)}${after ? ` · park ${signed(after.value)} desirability${before && before.value !== after.value ? ` (now ${signed(before.value)})` : ""}` : ""}${after && after.crowded > 0 ? " · too crowded" : ""}`+ if (after) preview.plots.push(...frame.reachPlots(after))+ } else {+ preview.plots.push({ ...cell, size: 1, look: "blocked" })+ preview.tooltip = `${props[ui.prop].title.toLowerCase()} · lay park ground first`+ }+ } else if (ui.tool === "place" && ui.placing && pointer) {+ const kind = kinds[ui.placing]+ const at = footprintAt(pointer, kind.size)+ const tile = { ...at, size: kind.size }+ showReach(tile, kind)+ rangeOfKind(tile, kind)+ if (kind.appeal) preview.plots.push({ x: tile.x - kind.appeal.reach, y: tile.y - kind.appeal.reach, size: tile.size + 2 * kind.appeal.reach, look: kind.appeal.value > 0 ? "reach" : "hover" })+ if (lockReason(kind, frame.world.census)) preview.plots.push({ ...tile, look: "blocked" })+ else if (canPlace(grid, tile)) {+ preview.ghosts.push({ what: ui.placing, cell: at })+ // No road at a side's middle: shown red under the ghost, as it will not be laid there.+ if (placeProblem(frame, kind, tile)?.refuse) preview.plots.push({ ...tile, look: "blocked" })+ } else preview.plots.push({ ...tile, look: "blocked" })+ } else if (ui.tool === "upgrade" && ui.upgrading) {+ // Every building the upgrade can go to, outlined; the one under the pointer says what it would give and cost.+ const rank = frame.world.fate.rank, coins = frame.world.treasury.coins+ for (const row of buildings) {+ const { data } = row+ if (data.building.get().kind !== ui.upgrading || data.site.present || data.rising.present) continue+ const kind = kinds[ui.upgrading], level = data.upgraded.value()?.level ?? 0, up = nextUpgrade(kind, level)+ const tile = data.tile.get()+ if (!up) continue+ const blocked = upgradeBlock(up, rank, { ranks })+ const hovered = preview.hover === row.entity.id+ preview.plots.push({ ...tile, look: data.works.present || blocked ? "blocked" : hovered ? "picked" : "reach" })+ if (!hovered) continue+ const from = (upgradeAt(kind, level)?.title ?? kind.title).toLowerCase()+ preview.tooltip = data.works.present+ ? `${from} → ${up.title.toLowerCase()} · under way: carriers are bringing its materials`+ : [`${from} → ${up.title.toLowerCase()}`, upgradePrice(up), ...upgradeChanges(kind, level).map((c) => `· ${c}`),+ blocked ?? (coins < up.cost.coins ? `${up.cost.coins - coins} coins short` : "click to begin: it goes on working meanwhile")].join("\n")+ }+ if (!preview.tooltip) preview.tooltip = `upgrade: pick a ${kinds[ui.upgrading].title.toLowerCase()} · Esc to stop`+ } else if (ui.tool === "bulldoze") {+ preview.danger = true+ if ((preview.hover === null || useAt(grid, cell?.x ?? -1, cell?.y ?? -1) === "park") && cell && ["road", "tree", "field", "park"].includes(useAt(grid, cell.x, cell.y)))+ preview.plots.push({ ...cell, size: 1, look: "blocked" })+ const there = cell ? frame.parkAt.get(key(cell.x, cell.y))?.data.park.get() : undefined+ if (there) preview.tooltip = there.prop !== "none" ? `remove the ${props[there.prop].title.toLowerCase()}` : `remove the ${grounds[there.ground].title.toLowerCase()}`+ const rock = cell ? frame.rockAt.get(key(cell.x, cell.y)) : undefined+ if (rock && cell) {+ const worked = rock.amount <= 1+ if (worked) preview.plots.push({ ...cell, size: 1, look: "blocked" })+ preview.tooltip = worked ? `worked ${rock.ore ? "ore" : "stone"} face · bulldoze to clear it` : `${rock.ore ? "ore" : "stone"} · ${rock.amount} left`+ }+ }+ if (ui.selected !== null) {+ const row = buildings.find((b) => b.entity.id === ui.selected)+ const tile = frame.tileOf(ui.selected)+ const whole = tile && useAt(grid, tile.x, tile.y) === "park" ? frame.parkOf(tile) : undefined+ if (whole) {+ // A park is picked whole: every cell of it, and how far it reaches.+ for (const c of whole.cells) preview.plots.push({ x: c.x, y: c.y, size: 1, look: "hover" })+ preview.plots.push(...frame.reachPlots(whole))+ } else if (tile) preview.plots.push({ ...tile, look: "picked" })+ if (row && tile) {+ showReach(tile, kinds[row.data.building.get().kind])+ rangeOfKind(tile, kinds[row.data.building.get().kind], row.data.service.value()?.range)+ }+ }+ return { preview, dropping }+}diff --git a/src/view/project.ts b/src/view/project.tsnew file mode 100644index 0000000..81130c0--- /dev/null+++ b/src/view/project.ts@@ -0,0 +1,58 @@+/**+ * The view, once a frame: the world read in one pass (see `frame.ts`), then+ * the pointer's gestures become a selection and edits; the preview, the+ * tooltip, the panel, the map view, the alerts, the upgrades, the guide, and+ * the town's numbers are filled in for the UI (`TownView`) and the renderer+ * (`SceneView`). It never writes the world: what changes the town goes to the+ * simulation as an edit.+ */+import { Game } from "../game/schema.ts"+import { alertsOf, freshPatience } from "./alerts.ts"+import { frameAccess, frameOf } from "./frame.ts"+import { freshGuide, guideOf } from "./guide.ts"+import { applyGestures } from "./interaction/gestures.ts"+import { drawOverlay } from "./overlay.ts"+import { panelOf } from "./panels/index.ts"+import { previewOf } from "./preview.ts"+import { Interaction, Outbox, Shown } from "./services.ts"+import { numbersOf, statsOf } from "./stats.ts"+import { tooltipOf } from "./tooltip.ts"+import { noneWanted, upgradesOf, upgradesWanted } from "./upgrades.ts"++export const Project = Game.System(+ "Town/Project",+ {+ queries: frameAccess.queries,+ resources: frameAccess.resources,+ services: { interaction: Game.System.service(Interaction), shown: Game.System.service(Shown), outbox: Game.System.service(Outbox) },+ /** The view's own state, not saved (rebuilt after a load): the guide's, the alerts' patience, and the upgrades the town needs. */+ local: () => ({ guide: freshGuide(), patience: freshPatience(), wanted: noneWanted() })+ },+ ({ queries, resources, services, local }) => {+ const ui = services.interaction+ const { town, scene } = services.shown+ const send = services.outbox.push+ const toast = (message: string) => town.toasts.push(message)+ const frame = frameOf(queries, resources)++ applyGestures(frame, ui, send, toast)+ const { preview, dropping } = previewOf(frame, ui)+ tooltipOf(frame, ui, preview, dropping)+ scene.preview = preview+ town.tooltip = preview.tooltip+ town.stroke = preview.stroke++ const wanted = () => upgradesWanted(frame, local.wanted)+ town.panel = panelOf(frame, ui, wanted)+ drawOverlay(frame, ui, scene, town)++ const { alerts, shortStaffed, hallRow } = alertsOf(frame, local.patience)+ const { upgrades, due, hint } = upgradesOf(frame, wanted())+ if (hint) alerts.push(hint)+ scene.wanted = due+ const numbers = numbersOf(frame)+ const guide = guideOf(frame, ui, send, local.guide, numbers, hallRow)+ town.stats = statsOf(frame, numbers, { alerts, shortStaffed, upgrades, guide, hallRow })+ scene.pace = ui.founding || town.stats.fate.state !== "playing" ? 0 : ui.speed+ }+)diff --git a/src/view/schedule.ts b/src/view/schedule.tsnew file mode 100644index 0000000..405ab74--- /dev/null+++ b/src/view/schedule.ts@@ -0,0 +1,6 @@+/** The view's schedule, run once a frame after the simulation's steps and before the renderer's. */+import { Game } from "../game/schema.ts"+import { ShowFeedback } from "./feedback.ts"+import { Project } from "./project.ts"++export const project = Game.Schedule(ShowFeedback, Project)diff --git a/src/view/services.ts b/src/view/services.tsnew file mode 100644index 0000000..a14aa02--- /dev/null+++ b/src/view/services.ts@@ -0,0 +1,19 @@+/**+ * The host state the view's systems are handed. None of it is saved, and the+ * simulation never reads it: the view talks to the simulation through edits+ * (`Outbox`, applied at the next step) and hears back through `Toast` and+ * `Selection` events.+ */+import { Descriptor } from "@typeonce/ritmo"++import type { Edit } from "../game/edits.ts"+import type { Interaction as InteractionValue, Shown as ShownValue } from "./contracts.ts"++/** What the player is doing with the map (see `Interaction`). */+export const Interaction = Descriptor.Service<InteractionValue>()("Town/Interaction")+/** What the view shows the UI and the renderer, filled in once a frame. */+export const Shown = Descriptor.Service<ShownValue>()("Town/Shown")+/** Edits for the simulation's next step: the same queue the UI pushes to. */+export const Outbox = Descriptor.Service<{ readonly push: (...edits: ReadonlyArray<Edit>) => void }>()("Town/Outbox")+/** The frame's length, for animation only: the simulation runs on `Time`. */+export const Clock = Descriptor.Service<{ deltaSeconds: number; elapsed: number }>()("Town/Clock")diff --git a/src/view/stats.ts b/src/view/stats.tsnew file mode 100644index 0000000..ddb08fa--- /dev/null+++ b/src/view/stats.ts@@ -0,0 +1,159 @@+/**+ * The town's numbers for the top bar and the panels: money, people, the+ * season and the almanac, the crown, the term, the goods' flow, history, and+ * what the alerts, the upgrades, and the guide say.+ */+import { amounts, crown as crownRules, fate, goodIds, ranks, TAX_STEPS } from "../game/content/index.ts"+import { approvalTarget } from "../game/rules/approval.ts"+import { suppliedTaxOf, taxOutlook, type TaxedHome } from "../game/rules/households.ts"+import { elapsed, goalsOf, larder, seasonAt, steadyNet, termTicks, winterOf } from "../game/schedule.ts"+import { appealAt } from "../game/world/appeal.ts"+import type { Alert, Stats } from "./contracts.ts"+import type { BuildingRow, Frame } from "./frame.ts"++/** What the numbers are reckoned from, shared with the guide. */+export const numbersOf = (frame: Frame) => {+ const { houses, rates, cells } = frame+ const ledger = frame.world.ledger+ const charter = frame.world.charter+ const t = elapsed(frame.world.time, charter)+ let suppliedTaxes = 0+ for (const { data } of houses) {+ if (data.site.present || data.rising.present || data.burning.present) continue+ const tile = data.tile.get()+ suppliedTaxes += suppliedTaxOf(data.house.get(), rates, undefined, appealAt(cells, tile.x, tile.y))+ }+ const coins = frame.world.treasury.coins+ const net = ledger.taxes + ledger.trade - ledger.upkeep - ledger.admin+ const mood = frame.world.mood+ const crown = frame.world.crown+ // What the homes would pay at each step of each tier's rate, once settled there (see `taxOutlook`).+ const taxed: Array<TaxedHome> = []+ for (const { data } of houses) {+ if (data.site.present || data.rising.present || data.burning.present || data.closed.present) continue+ const tile = data.tile.get()+ taxed.push({ ...data.house.get(), desirability: appealAt(cells, tile.x, tile.y), paying: true })+ }+ const f = frame.world.fate+ const pantry = frame.world.pantry+ const season = seasonAt(Math.min(Math.max(0, t), f.began + termTicks(charter) - 1), charter)+ const approvalAt = (r: { readonly settlers: number; readonly citizens: number }, memory: number) =>+ approvalTarget(taxed, r, coins, crown.snubs.length, season.winter, undefined, memory).target+ const outlookOf = (tier: "settlers" | "citizens") => taxed.some((h) => (h.tier === 1) === (tier === "settlers"))+ ? TAX_STEPS.map((rate) => ({ rate, taxes: Math.round(taxOutlook(taxed, rates, tier, rate, approvalAt)) }))+ : []+ const seconds = (steps: number) => Math.max(0, Math.ceil(steps / 60))+ const danger = (since: number, minutes: number) => (since < 0 ? null : seconds(since + minutes * 3600 - t))+ // The winter after the coming one, for the almanac.+ const comingYear = season.winter || winterOf(charter, season.year) === null ? season.year + 1 : season.year+ return { ledger, charter, t, suppliedTaxes, coins, net, mood, crown, f, pantry, season, outlookOf, seconds, danger, comingYear }+}+export type Numbers = ReturnType<typeof numbersOf>++/** The rest of what `Stats` shows, reckoned elsewhere. */+interface Said {+ readonly alerts: ReadonlyArray<Alert>+ readonly shortStaffed: Stats["shortStaffed"]+ readonly upgrades: Stats["upgrades"]+ readonly guide: Stats["guide"]+ readonly hallRow: BuildingRow | undefined+}++export const statsOf = (frame: Frame, numbers: Numbers, { alerts, shortStaffed, upgrades, guide, hallRow }: Said): Stats => {+ const { houses, rates } = frame+ const census = frame.world.census+ const stock = frame.world.stock+ const { ledger, charter, t, suppliedTaxes, coins, net, mood, crown, f, pantry, season, outlookOf, seconds, danger, comingYear } = numbers+ const flowNow = frame.world.flow.last+ const flowHeld = frame.world.flow.held+ return {+ coins,+ taxes: ledger.taxes,+ suppliedTaxes: Math.round(suppliedTaxes),+ taxOutlook: { settlers: outlookOf("settlers"), citizens: outlookOf("citizens") },+ trade: ledger.trade,+ upkeep: ledger.upkeep,+ admin: ledger.admin,+ net,+ homes: census.homes,+ needs: { food: census.food, bread: census.bread, cloth: census.cloth, faith: census.faith, furniture: census.furniture },+ townhouses: houses.filter(({ data }) => data.house.get().tier === 3).length,+ policy: rates,+ stock,+ prices: frame.world.market.prices,+ settlers: census.settlers,+ citizens: census.citizens,+ burghers: census.burghers,+ jobs: census.jobs,+ employed: census.employed,+ shortStaffed,+ charter: { size: charter.size, term: charter.term, land: charter.land, seed: charter.seed },+ minute: t / 3600,+ season: {+ year: season.year,+ winter: season.winter,+ left: seconds(season.left),+ severity: season.severity,+ coming: season.coming,+ after: winterOf(charter, comingYear + 1)+ },+ mood: {+ approval: mood.approval,+ target: mood.target,+ parts: [+ { label: "mood of the town", value: mood.base },+ { label: "needs met", value: mood.needs },+ { label: "taxes now", value: mood.taxes },+ { label: "a grudge over taxes past", value: mood.grudge },+ { label: "unpaid wages", value: mood.debt },+ { label: "the crown's displeasure", value: mood.crown },+ { label: "a hungry winter", value: mood.winter }+ ].filter((p) => p.value !== 0)+ },+ crown: {+ open: crown.open,+ good: crown.good,+ amount: crown.amount,+ left: seconds(crown.due - t),+ reward: crown.reward,+ met: crown.met,+ missed: crown.missed,+ streak: crown.streak,+ patience: crownRules.patience,+ next: seconds(crown.next - t)+ },+ fate: {+ state: f.state,+ reason: f.reason,+ at: f.at / 3600,+ term: f.term,+ began: f.began / 3600,+ rank: f.rank,+ rankTitle: ranks[f.rank]?.title ?? "",+ nextTitle: f.rank + 1 < ranks.length ? ranks[f.rank + 1]!.title : null,+ score: f.score,+ bankrupt: danger(f.debtSince, fate.debt),+ revolt: danger(f.revoltSince, fate.revolt),+ rises: danger(f.goalSince, fate.hold),+ peak: f.peak+ },+ goals: goalsOf(+ charter,+ { settlers: census.settlers, citizens: census.citizens, burghers: census.burghers, coins, net: steadyNet(frame.world.history.samples, net), approval: mood.approval,+ hall: hallRow ? hallRow.data.upgraded.value()?.level ?? 0 : 0 },+ undefined,+ f.rank+ ),+ larder: larder(stock),+ flow: flowNow === null ? null : { ...flowNow, elsewhere: amounts(Object.fromEntries(goodIds.map((g) => [g, Math.max(0, flowHeld[g] - stock[g])]))) },+ eaten: pantry.eatenLast,+ rotted: pantry.rottedLast,+ sick: census.sick,+ burning: census.burning,+ history: frame.world.history.samples,+ chronicle: frame.world.chronicle.lines,+ alerts,+ upgrades,+ guide+ }+}diff --git a/src/view/text.ts b/src/view/text.tsnew file mode 100644index 0000000..46d4acc--- /dev/null+++ b/src/view/text.ts@@ -0,0 +1,5 @@+/** Small ways the view puts numbers into words. */++export const percent = (n: number, of: number) => `${Math.round((n / of) * 100)}%`+export const signed = (n: number) => `${n > 0 ? "+" : n < 0 ? "−" : ""}${Math.abs(n)}`+export const counted = (n: number, what: string) => `${n} ${what}${n === 1 ? "" : "s"}`diff --git a/src/view/tooltip.ts b/src/view/tooltip.tsnew file mode 100644index 0000000..520775e--- /dev/null+++ b/src/view/tooltip.ts@@ -0,0 +1,64 @@+/**+ * What the pointer is over, said in a line: a building's state, a home's+ * residents, a park's worth, or (bulldozing) what pulling it down gives back.+ * It takes over from the preview's own line only where the preview has none+ * to say (the upgrade tool says what an upgrade gives instead).+ */+import { anA, builtCost, costText, grounds, home, kinds, PAVE_COST, props, tierHome, upgradeAt } from "../game/content/index.ts"+import { lockReason } from "../game/schedule.ts"+import { appealAt } from "../game/world/appeal.ts"+import { canPlace } from "../game/world/grid.ts"+import { inside } from "../game/world/iso.ts"+import type { Interaction, Preview } from "./contracts.ts"+import { salvageFor, worksShare } from "./facts.ts"+import type { Frame } from "./frame.ts"+import { cellAt, footprintAt } from "./interaction/geometry.ts"+import { placeProblem } from "./interaction/placing.ts"+import { describeBuilding } from "./panels/building.ts"+import { parkText } from "./panels/park.ts"++/** Sets the preview's tooltip for what is hovered; `dropping`: a stroke is being let go off the map. */+export const tooltipOf = (frame: Frame, ui: Interaction, preview: Preview, dropping: boolean) => {+ const { grid, buildings, houses, ruins, parkRows, cells } = frame+ const pointer = ui.pointer+ const cell = pointer ? cellAt(pointer) : null+ const hovered = preview.hover+ const hoveredBuilding = hovered !== null ? buildings.find((row) => row.entity.id === hovered) : undefined+ const hoveredHouse = hovered !== null ? houses.find((row) => row.entity.id === hovered) : undefined+ const hoveredRuin = hovered !== null ? ruins.find((row) => row.entity.id === hovered) : undefined+ // The upgrade tool says what an upgrade gives and costs instead (see above).+ if (ui.tool === "upgrade") {+ } else if (hoveredBuilding) {+ const { kind, status, problem } = describeBuilding(frame, hoveredBuilding)+ const level = hoveredBuilding.data.upgraded.value()?.level ?? 0, works = hoveredBuilding.data.works.value()+ const title = (upgradeAt(kind, level)?.title ?? kind.title).toLowerCase()+ preview.tooltip = ui.tool === "bulldoze"+ ? `${title} · ${hoveredBuilding.data.hall.present ? "the town hall stays" : salvageFor(builtCost(kind, level), hoveredBuilding.data.site.value(), works && { kind, ...works })}`+ : `${title} · ${problem ?? status}${works ? ` · becoming ${anA(upgradeAt(kind, works.level)!.title.toLowerCase())}, ${Math.round(worksShare(works)! * 100)}% built` : ""}`+ } else if (hoveredHouse) {+ const h = hoveredHouse.data.house.get()+ const t = hoveredHouse.data.tile.get()+ preview.tooltip = ui.tool === "bulldoze"+ ? `${tierHome[h.tier]} · ${salvageFor(home.cost, hoveredHouse.data.site.value())}`+ : hoveredHouse.data.closed.present+ ? `${tierHome[h.tier]} · closed`+ : `${tierHome[h.tier]} · ${h.residents} resident${h.residents === 1 ? "" : "s"} · desirability ${appealAt(cells, t.x, t.y)}${hoveredHouse.data.burning.present ? " · on fire!" : hoveredHouse.data.sick.present ? " · sick" : ""}`+ } else if (hoveredRuin) {+ preview.tooltip = `ruin · ${hoveredRuin.data.ruin.get().cause} · bulldoze to clear`+ } else if (hovered !== null && ui.tool === "select" && parkRows.some((row) => row.entity.id === hovered)) {+ const row = parkRows.find((r) => r.entity.id === hovered)!+ const p = frame.parkOf(row.data.tile.get())+ const here = row.data.park.get()+ preview.tooltip = `park · ${here.prop !== "none" ? props[here.prop].title.toLowerCase() : grounds[here.ground].title.toLowerCase()}${p ? ` · ${p.cells.length} cells · ${parkText(p)}` : ""}`+ } else if (ui.tool === "place" && ui.placing) {+ const kind = kinds[ui.placing]+ const lock = lockReason(kind, frame.world.census)+ const tile = pointer ? { ...footprintAt(pointer, kind.size), size: kind.size } : null+ const problem = tile ? placeProblem(frame, kind, tile) : null+ if (lock) preview.tooltip = `${kind.title.toLowerCase()} · ${lock}`+ else if (tile && !canPlace(grid, tile)) preview.tooltip = `${kind.title.toLowerCase()} · no room here`+ else if (problem) preview.tooltip = `${kind.title.toLowerCase()} · ${problem.text}`+ else preview.tooltip = `${kind.title.toLowerCase()} · ${costText(kind.cost)}`+ } else if (ui.tool === "pave" && !dropping) preview.tooltip = `pave · ${PAVE_COST.coins} coins and a stone a cell · faster walking`+ else if (cell && ui.view === "appeal" && inside(cell.x, cell.y)) preview.tooltip = `desirability ${appealAt(cells, cell.x, cell.y)}`+}diff --git a/src/view/upgrades.ts b/src/view/upgrades.tsnew file mode 100644index 0000000..da8f825--- /dev/null+++ b/src/view/upgrades.ts@@ -0,0 +1,122 @@+/**+ * The town's upgrades: every one it could make, kind by kind and level by+ * level, for the town panel; the ones it needs now, for the gold arrows; and+ * a word for the first of those while nothing is being upgraded.+ */+import { anA, goodIds, kindOrder, kinds, nextUpgrade, ranks, risk, upgradeAt, type KindId } from "../game/content/index.ts"+import { upgradeChanges, upgradePrice } from "../game/rules/upgrades.ts"+import { met, upgradeBlock } from "../game/schedule.ts"+import type { TileLike } from "../game/world/grid.ts"+import type { Alert } from "./contracts.ts"+import { growingNear } from "./facts.ts"+import type { BuildingRow, Frame, HouseRow } from "./frame.ts"++/** Why each building's upgrade is needed now, by its id, reckoned once a second (see `upgradesWanted`). */+export interface Wanted {+ at: number+ why: ReadonlyMap<number, string>+}+export const noneWanted = (): Wanted => ({ at: -1, why: new Map() })++/**+ * 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.+ */+export const upgradesWanted = (frame: Frame, wanted: Wanted): ReadonlyMap<number, string> => {+ const { grid, buildings, houses } = frame+ const tick = frame.world.time.step+ 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 && !r.data.works.value())+ const homes = houses.filter((r) => !r.data.site.present && !r.data.rising.present && !r.data.closed.present)+ const full = (r: BuildingRow) => {+ const inv = r.data.inventory.value()+ return !!inv && goodIds.some((g) => inv.accepts.includes(g) && inv.stock[g] >= inv.cap * 0.9)+ }+ const near = (r: BuildingRow, 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: HouseRow, need: "bread" | "faith") => r.data.house.get().tier >= 2 && !met(r.data.house.get(), need)+ const nextHall = ranks[Math.min(frame.world.fate.rank + 1, ranks.length - 1)]!.hall+ const millsWait = standingRows.some((r) => r.data.building.get().kind === "mill" && r.data.status.get() === "starved")+ const breadShort = frame.world.stock.bread < 5 && homes.some((r) => fishy(r, "bread"))+ for (const r of standingRows) {+ const kind = kinds[r.data.building.get().kind], level = r.data.upgraded.value()?.level ?? 0, status = r.data.status.get()+ if (!nextUpgrade(kind, level)) continue+ const reach = r.data.service.value()?.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, frame.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" ? (frame.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) => (h.data.risk.value()?.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)+ wanted.why = why+ return why+}++/** Every upgrade the town could make; the buildings to arrow (`due`); and the hint for the first, if it is time for one. */+export const upgradesOf = (frame: Frame, needed: ReadonlyMap<number, string>) => {+ const { buildings } = frame+ const rank = frame.world.fate.rank+ let hint: Alert | null = null+ const upgradeRows = new Map<string, { kind: KindId; level: number; ready: number; underway: number; first: (typeof buildings)[number] | null }>()+ // Every buildable kind's first upgrade is listed, built or not, so the menu says what is to come; the town hall's by where it stands.+ for (const id of kindOrder) if (kinds[id].upgrade) upgradeRows.set(`${id}:0`, { kind: id, level: 0, ready: 0, underway: 0, first: null })+ for (const row of buildings) {+ const { data } = row+ if (data.site.present || data.rising.present) continue+ const kind = kinds[data.building.get().kind]+ const level = data.upgraded.value()?.level ?? 0+ const works = data.works.value()+ const from = works ? works.level - 1 : level+ if (!nextUpgrade(kind, from)) continue+ const k = `${kind.id}:${from}`+ const entry = upgradeRows.get(k) ?? { kind: kind.id, level: from, ready: 0, underway: 0, first: null }+ if (works) entry.underway += 1+ else {+ entry.ready += 1+ entry.first ??= row+ }+ upgradeRows.set(k, entry)+ }+ const upgrades = [...upgradeRows.values()].map((r) => {+ const kind = kinds[r.kind], up = nextUpgrade(kind, r.level)!+ return {+ kind: r.kind, level: r.level, from: (upgradeAt(kind, r.level)?.title ?? kind.title).toLowerCase(), to: up.title.toLowerCase(), blurb: up.blurb,+ coins: up.cost.coins, materials: up.cost.materials, price: upgradePrice(up), changes: upgradeChanges(kind, r.level),+ blocked: upgradeBlock(up, rank, { ranks }), ready: r.ready, underway: r.underway, first: r.first+ }+ })+ // 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 = frame.world.treasury.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([...needed].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, row.data.upgraded.value()?.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+ }))+ 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 = dueFirst.data.upgraded.value()?.level ?? 0+ const from = (upgradeAt(kind, level)?.title ?? kind.title).toLowerCase(), to = nextUpgrade(kind, level)!.title.toLowerCase()+ hint = { 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 }+ }+ return { upgrades: upgrades.map(({ first: _first, ...u }) => u), due, hint }+}diff --git a/tools/balance/verify/builds.ts b/tools/balance/verify/builds.tsindex 6739e30..5157389 100644--- a/tools/balance/verify/builds.ts+++ b/tools/balance/verify/builds.ts@@ -7,7 +7,7 @@ import type { BuildAction, Inputs } from "../types.ts"export const verifyBuilds = (inputs: Inputs, builds: ReadonlyArray<BuildAction>, seconds = 600) => {const started = performance.now(), prediction = project(inputs, { seconds, builds }), messages: string[] = []const town = fixture(inputs.scenario, inputs.rules)- town.ui.toast = (message) => messages.push(message)+ town.toast = (message) => messages.push(message)const actions = [...builds].sort((a, b) => a.at - b.at)const actual: Array<{ second: number; coins: number; residents: number; citizens: number; completed: number }> = []let firstCitizenSecond: number | null = null