A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Lay parks out cell by cell instead of placing ornament buildings
SandroMaglione9b7ce7336a18
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.mdindex c8672d5..fc56fad 100644--- a/DEVELOPMENT.md+++ b/DEVELOPMENT.md@@ -157,7 +157,7 @@ That is how the README's screenshots of grown towns were made.- `src/art.ts`: all drawing: buildings and their yards, homes, the land, roads, carts, and figures.- `src/render3d/`: live world renderer, model instances, camera and map input,overlays, ruins, surface shaders and roof particle emitters.-- `src/asset-lab/town-props.ts`: gardens, furniture, stone paving and ruins.+- `src/asset-lab/town-props.ts`: parks (ground and furnishings, drawn cell by cell), stone paving and ruins.- `src/asset-lab/services.ts`: grain hoist, fish racks, watch tower, herbs,medical signs, street noticeboard and builder's equipment.- `src/asset-lab/appearance.ts`: material state metadata for catalogue presets.@@ -167,7 +167,7 @@ That is how the README's screenshots of grown towns were made.### Reviewing the new town modelsOpen [`/model-review.html`](http://localhost:5232/model-review.html) for-the models added for PR #3. Collections cover buildings, gardens and squares,+the models added for PR #3. Collections cover buildings, parks,home tiers and neighbourhoods, winter, hazards, people/cargo and buildingcondition. Drag any model or use the rotation slider to turn the collection.**Inspect** opens the full asset viewer. **Download GLB** exports one model;@@ -226,7 +226,7 @@ averaged over the seeds still in office every few minutes.```shpnpm balance -- --size large --term 90 --land harshpnpm balance -- --bot greedy # sensible (default), greedy (taxes at 200%, sells everything, ignores the crown), idle,- # crowded (homes packed beside industry, no ornaments), uncovered (no fire, health, or order services)+ # crowded (homes packed beside industry, no parks), uncovered (no fire, health, or order services)pnpm balance -- --versus crowded # the bot against another on the same seeds: citizens, burghers, homes lostpnpm balance -- --versus uncoveredpnpm balance -- --set kinds.sawmill.crew=settlers --set risk.fire.wooden=0 # content changes, numbers or wordsdiff --git a/README.md b/README.mdindex 71a8524..4338988 100644--- a/README.md+++ b/README.md@@ -50,8 +50,9 @@ in the colour of its roof.## A town that looks and works like a real oneEvery street has a desirability. A smithy or a quarry drags it down for-several cells around; gardens, parks, fountains, statues, a chapel, and-paved streets lift it. Citizens will only live on a decent street, and the+several cells around; parks you lay out yourself (lawns, flower beds,+walks in from the street, lamps, a fountain, a statue), a chapel, and paved streets+lift it. Citizens will only live on a decent street, and thefinest streets, with every service calling, grow three-storey townhouses.Settlers do the rough work and citizens the skilled, and nobody walks morethan fifteen road cells to a job, so the far-off mine needs its owndiff --git a/docs/how-to-play.md b/docs/how-to-play.mdindex 5238119..8cdbf30 100644--- a/docs/how-to-play.md+++ b/docs/how-to-play.md@@ -77,10 +77,23 @@ Nobody tells you to build it that way; it works best that way.take from it, fading with distance: a smithy, quarry, or mine takes 8beside it and less out to four cells; a sawmill, bakery, mill, orsmokehouse 4; warehouses, farms, a granary, a builder's yard 2. Water and- woods give 2, a garden 3, a park or fountain 6, a statue or plaza 10, a- market 2 and a chapel 4, the town hall 4, and a paved street 1 beside it.- Ruins and run-down homes take a little. Ornaments cost upkeep: a fine- centre is something you choose to pay for.+ woods give 2, a market 2 and a chapel 4, the town hall 4, and a paved+ street 1 beside it. Ruins and run-down homes take a little.+- **Parks** are laid out cell by cell from the build menu. Drag a+ rectangle of ground (lawn, flower beds, gravel walks, a paved square),+ then click a cell of it to set a furnishing (a lamp, a fountain once 30+ live in town, a statue once 20 are citizens). Ground that touches is one+ park, and the whole park is what the streets around it feel: its beauty+ adds up from its ground (at most 4), its furnishings (the first of a+ kind in full, each more of it half as much, and one for every two+ cells), and its ways in from the street (a walk or a square beside a+ road: 1.5 each, two count), up to 15, out to 2 cells and one more for+ every 6 cells of park, up to 5. A lone statue is worth little; a lawn+ with walks in from the street, lamps, and a statue is worth a street of+ citizens.+ Parks cost upkeep by the cell and by the furnishing: a fine centre is+ something you choose to pay for. Bulldozing a cell takes its furnishing+ first, then its ground.- **Tiers.** Settlers live anywhere. A citizens' home needs desirability 5as well as bread, cloth, and faith; a home whose street drops below 5goes back to settlers even with every need met. A **townhouse** of@@ -160,7 +173,7 @@ store) and the latest news, which also pops up as it happens.and pays twice as much, and on a fine street (15) with every servicecalling, a three-story townhouse.- **Buildings** need a road at the middle of a side and workers of their- crew from homes within 15 road cells. Ornaments need no road and no+ crew from homes within 15 road cells. Parks need no road and noworkers; their stone comes straight out of storage. Gatherers work the land within their reach (trees, rocks, water,fields); workshops turn one good into another.- **Carriers** walk every good along the roads: producers send to whoeverdiff --git a/scripts/balance.ts b/scripts/balance.tsindex c29b507..189dfca 100644--- a/scripts/balance.ts+++ b/scripts/balance.ts@@ -20,11 +20,11 @@* ignoring the crown;* - idle: founds the basics, then leaves the town to itself;* - crowded: the sensible mayor, but homes packed in beside the industry,- * and no gardens, parks, statues, or paving;+ * and no parks or paving;* - uncovered: the sensible mayor, but no fire watch, healer, or watch house.** The sensible mayor also keeps homes off squalid streets and dirty- * workshops a little way from homes, plants gardens and paves streets where+ * workshops a little way from homes, lays out parks and paves streets where* homes are just short of the next tier, sends for a fire watch, a healer,* or a watch house when warning signs go up over a few homes and for a* builder when homes start to run down, clears ruins, and puts workers'@@ -38,10 +38,10 @@* wants at each decision, and `DEBUG=1` every edit it pushes. The bot only does what a player* could: it reads the world, then pushes the same edits the page does.*/-import { goodIds, home, kinds, landIds, ROAD_COST, sizeIds, type Amounts, type CharterValue, type GoodId, type Kind, type KindId } from "../src/content.ts"+import { goodIds, home, kinds, landIds, ROAD_COST, sizeIds, type Amounts, type CharterValue, type GoodId, type GroundId, type Kind, type KindId, type PropId } from "../src/content.ts"import * as content from "../src/content.ts"import { around, canPlace, DIRS, entrances, GridBuilder, isRoad, key, useAt, type Use } from "../src/grid.ts"-import { ringOf } from "../src/appeal.ts"+import { parksOf, ringOf } from "../src/appeal.ts"import { GRID, inside, type Point } from "../src/iso.ts"import type { GridValue } from "../src/schema.ts"import { headless, type Snapshot } from "../src/sim/headless.ts"@@ -73,7 +73,7 @@ const verbose = args.includes("--verbose")const snapshotAt = Number(option("snapshot", "0"))const out = option("out", "snapshots")if (!sizeIds.includes(size) || !landIds.includes(land) || !bots.includes(bot) || (versus !== "" && !bots.includes(versus))) throw new Error("Unknown --size, --land, --bot, or --versus")-/** Mayors who look after the neighbourhood: gardens, paving, homes away from industry. */+/** Mayors who look after the neighbourhood: parks, paving, homes away from industry. */const zoned = () => bot !== "crowded" && bot !== "idle"/** Mayors who keep fire watches, healers, and watch houses. */const covered = () => bot !== "uncovered" && bot !== "idle"@@ -103,6 +103,8 @@ interface World {/** Desirability by cell (see `appeal.ts`), paved road cells, and ruins. */readonly appeal: ReadonlyArray<number>readonly paved: ReadonlySet<number>+ /** Cells of park, by `key`: their ground and furnishing. */+ readonly parks: ReadonlyMap<number, { readonly x: number; readonly y: number; readonly ground: GroundId; readonly prop: PropId | "none" }>readonly ruins: ReadonlyArray<{ readonly id: number; readonly tile: Tile }>/** Cells of ore rocks (other rocks are stone). */readonly ore: ReadonlySet<number>@@ -139,15 +141,17 @@ const read = (snapshot: Snapshot): World => {const stock: Record<string, number> = Object.fromEntries(goodIds.map((g) => [g, 0]))const ore = new Set<number>()const paved = new Set<number>()+ const parks = new Map<number, { x: number; y: number; ground: GroundId; prop: PropId | "none" }>()const ruins: Array<World["ruins"][number]> = []for (const e of snapshot.entities) {const c = e.componentsconst tile = c["Town/Tile"] as Tile | undefinedif (!tile) continue- const use: Use = c["Town/Road"] ? "road" : c["Town/House"] ? "house" : c["Town/Tree"] ? "tree" : c["Town/Rock"] ? "rock" : c["Town/Water"] ? "water" : c["Town/Field"] ? "field" : c["Town/Ruin"] ? "ruin" : "building"+ const use: Use = c["Town/Road"] ? "road" : c["Town/Park"] ? "park" : c["Town/House"] ? "house" : c["Town/Tree"] ? "tree" : c["Town/Rock"] ? "rock" : c["Town/Water"] ? "water" : c["Town/Field"] ? "field" : c["Town/Ruin"] ? "ruin" : "building"builder.claim(tile, e.id, use)if (c["Town/Rock"]?.ore) ore.add(key(tile.x, tile.y))if (c["Town/Paved"]) paved.add(key(tile.x, tile.y))+ if (c["Town/Park"]) parks.set(key(tile.x, tile.y), { x: tile.x, y: tile.y, ...c["Town/Park"] })if (c["Town/Ruin"]) ruins.push({ id: e.id, tile })if (c["Town/Building"]) buildings.push({ kind: c["Town/Building"].kind, tile, status: c["Town/Status"], site: !!c["Town/Site"], nearby: c["Town/Staff"]?.nearby ?? 0 })if (c["Town/House"])@@ -166,6 +170,7 @@ const read = (snapshot: Snapshot): World => {grid: builder.value(),appeal: r["Town/Appeal"].cells,paved,+ parks,ruins,ore,buildings,@@ -285,30 +290,55 @@ const homeSpots = (w: World, n: number, near?: Tile): Array<Point> => {}/**- * Where a garden (or park, or statue) helps most: the free cell off the+ * Where a new park helps most: the free square of `size` cells off the* lanes with the most homes within its reach that fall just short of the- * next tier's desirability.+ * next tier's desirability (a furnished park of `size` gives about `value`).*/-const ornamentFor = (w: World, kind: Kind): Point | null => {+const parkFor = (w: World, size: number, value: number): Point | null => {const short = w.homes.filter((h) => {if (h.site || h.tier === 3 || !h.provided) return falseconst v = w.appeal[key(h.tile.x, h.tile.y)] ?? 0const goal = content.home.tiers[h.tier === 1 ? 2 : 3].appeal- return v < goal && v >= goal - kind.appeal!.value+ return v < goal && v >= goal - value})if (short.length < 3) return null+ const reach = content.park.reach[0] + Math.floor((size * size) / content.park.reach[1])let best: { cell: Point; value: number } | null = null- for (let y = 0; y + kind.size <= GRID; y++) {- for (let x = 0; x + kind.size <= GRID; x++) {- const tile = { x, y, size: kind.size }+ for (let y = 0; y + size <= GRID; y++) {+ for (let x = 0; x + size <= GRID; x++) {+ const tile = { x, y, size }if (!canPlace(w.grid, tile) || offPlan(tile)) continue- const value = short.filter((h) => ringOf(tile, h.tile.x, h.tile.y) <= Math.max(1, kind.appeal!.reach - 1)).length+ const value = short.filter((h) => ringOf(tile, h.tile.x, h.tile.y) <= Math.max(1, reach - 1)).lengthif (value >= 3 && (!best || value > best.value)) best = { cell: { x, y }, value }}}return best?.cell ?? null}+/**+ * The next furnishing for the town's parks: on a bare cell of a park with+ * room for more, the finest the town can afford that the park lacks+ * (a statue, a fountain, a lamp).+ */+const furnishing = (w: World): Edit | null => {+ const parks = parksOf([...w.parks.values()])+ for (const p of parks) {+ const placed = p.cells.filter((c) => c.prop !== "none")+ if (placed.length >= Math.ceil(p.cells.length / content.park.cellsPerProp)) continue+ const bare = p.cells.find((c) => c.prop === "none")+ if (!bare) continue+ const has = new Set(placed.map((c) => c.prop))+ const wanted: ReadonlyArray<PropId> = w.coins > 1500 ? ["statue", "fountain", "lamp"] : w.coins > 300 ? ["fountain", "lamp"] : ["lamp"]+ for (const id of wanted) {+ const piece = content.props[id]+ if (has.has(id) && id !== "lamp") continue+ if (residents(w) < piece.unlock.residents || w.census.citizens! < piece.unlock.citizens || !affordable(w, piece.cost)) continue+ return { type: "prop", prop: id, cell: { x: bare.x, y: bare.y } }+ }+ }+ return null+}+/** Homes whose sign for a risk is up, or nearly. */const atRisk = (w: World, r: "fire" | "health" | "order") => w.homes.filter((h) => !h.site && h.risk[r] >= content.risk.warn * 0.8).length@@ -518,16 +548,17 @@ const decide = (w: World): ReadonlyArray<Edit> => {roading.delete(want.kind)resting.set(want.kind, w.tick + 5 * 3600)}- // Ornaments, then (with stone to spare) paving, where homes fall a little short of the next tier: a- // garden is cheap; parks and statues once the treasury is comfortable.+ // Parks, then (with stone to spare) paving, where homes fall a little short of the next tier: furnish+ // the parks there are first, then lay a small lawn (a bigger one once the treasury is comfortable).if (zoned() && w.coins > 150) {- // A fountain in the middle of a block lifts all eight homes around it past what citizens need.- const options: ReadonlyArray<KindId> = w.coins > 1500 ? ["statue", "fountain", "garden"] : w.coins > 300 ? ["fountain", "garden"] : ["garden"]- for (const id of options) {- const kind = kinds[id]- if (!unlocked(w, kind) || !affordable(w, kind.cost)) continue- const spot = ornamentFor(w, kind)- if (spot) return [...edits, { type: "building", kind: id, cell: spot, open: false }]+ const furnish = furnishing(w)+ if (furnish) return [...edits, furnish]+ const size = w.coins > 1500 ? 3 : 2+ const spot = parkFor(w, size, size === 3 ? 12 : 6)+ if (spot && affordable(w, { coins: size * size * content.grounds.lawn.cost.coins, materials: {} })) {+ const cells: Array<Point> = []+ for (let dy = 0; dy < size; dy++) for (let dx = 0; dx < size; dx++) cells.push({ x: spot.x + dx, y: spot.y + dy })+ return [...edits, { type: "ground", ground: "lawn", cells }]}if (w.stock.stone >= 15 && w.coins > 400) {const cells: Array<Point> = []@@ -594,8 +625,8 @@ const run = (seed: number) => {const chosen = decide(w)if (process.env.SPEND) {for (const e of chosen) {- const k = e.type === "building" ? kinds[e.kind].category === "services" || kinds[e.kind].decor ? e.kind : kinds[e.kind].category : e.type- const cost = e.type === "building" ? kinds[e.kind].cost.coins : e.type === "homes" ? e.cells.length * home.cost.coins : e.type === "roads" ? e.cells.length * ROAD_COST : e.type === "pave" ? e.cells.length * 3 : 0+ const k = e.type === "building" ? kinds[e.kind].category === "services" ? e.kind : kinds[e.kind].category : e.type === "prop" ? e.prop : e.type+ const cost = e.type === "building" ? kinds[e.kind].cost.coins : e.type === "homes" ? e.cells.length * home.cost.coins : e.type === "roads" ? e.cells.length * ROAD_COST : e.type === "pave" ? e.cells.length * 3 : e.type === "ground" ? e.cells.length * content.grounds[e.ground].cost.coins : e.type === "prop" ? content.props[e.prop].cost.coins : 0if (cost > 0) spend[k] = (spend[k] ?? 0) + cost}if ((t + DECIDE) % 300 === 0) {diff --git a/scripts/check-town-models.ts b/scripts/check-town-models.tsindex b72db59..759c2da 100644--- a/scripts/check-town-models.ts+++ b/scripts/check-town-models.ts@@ -14,7 +14,7 @@ page.on("console", e => { if (e.type() === "error") errors.push(e.text()) })page.on("response", r => { if (r.status() >= 400) errors.push(`${r.status()} ${r.url()}`) })const output = "output/inkline-3d/town-review"await mkdir(output, { recursive: true })-const groups = ["Review fixes", "Buildings", "Gardens & squares", "Homes & neighbourhoods", "Winter", "Ruins", "People & cargo", "Building condition"]+const groups = ["Review fixes", "Buildings", "Parks", "Homes & neighbourhoods", "Winter", "Ruins", "People & cargo", "Building condition"]const captureSheet = async () => {const previous = await page.locator("#sheet-link").getAttribute("href")await page.getByRole("button", { name: "Save model sheet", exact: true }).click()@@ -50,7 +50,7 @@ try {console.log(`ok ${collection}: ${await page.locator(".model-view").count()} models, rotation, elevation, PNG export`)}await page.setViewportSize({ width: 390, height: 844 })- await page.getByRole("button", { name: "Gardens & squares", exact: true }).click()+ await page.getByRole("button", { name: "Parks", exact: true }).click()assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "Phone preview must fit the viewport")await page.screenshot({ path: `${output}/phone.png` })assert.deepEqual(errors, [])diff --git a/scripts/check.ts b/scripts/check.tsindex ec03984..c346213 100644--- a/scripts/check.ts+++ b/scripts/check.ts@@ -22,12 +22,12 @@* - a workplace with no homes within reach stays unstaffed;* - a home nobody mends falls down, and a builder keeps it standing;* - citizens will not take settlers' work, and settlers stand in for citizens as apprentices;- * - and homes with every need met become citizens on a street with fountains, not packed beside industry.+ * - and homes with every need met become citizens on a street with a park behind it, not packed beside industry.*/-import { amounts, CONDITION_MAX, goodIds, kinds, RISK_MAX, ticks, type CharterValue, type KindId } from "../src/content.ts"+import { amounts, CONDITION_MAX, goodIds, kinds, RISK_MAX, ticks, type CharterValue, type GroundId, type KindId, type PropId } from "../src/content.ts"import { canPlace, DIRS, entrances, GridBuilder, isRoad, key, type Use } from "../src/grid.ts"import { inside } from "../src/iso.ts"-import { ringOf } from "../src/appeal.ts"+import { parkValue, ringOf, type ParkCell } from "../src/appeal.ts"import { headless, type Snapshot } from "../src/sim/headless.ts"const town = (charter: CharterValue = { size: "small", term: 45, land: "fair", seed: 7 }) => {@@ -52,27 +52,43 @@ const building = (s: Snapshot, kind: string, x: number, y: number, size: number,return id}-/** Citizens' homes, every need met for good, on free cells beside the roads; every third free cell a statue, so the street is fine enough for them. */+/** A cell of park on a snapshot: its ground, and what stands on it. */+const parkCell = (s: Snapshot, x: number, y: number, ground: GroundId, prop: PropId | "none" = "none") => {+ s.entities.push({ id: s.nextEntity++, components: { "Town/Tile": { x, y, size: 1 }, "Town/Park": { ground, prop } } })+}++/**+ * Citizens' homes, every need met for good, on free cells beside the roads;+ * every fifth spot a small park instead (a statue, a fountain, and a lamp on+ * flower beds and lawn), so the street is fine enough for them.+ */const settle = (s: Snapshot, homes: number) => {const grid = new GridBuilder(s.resources["Town/Land"].mask)for (const e of s.entities) {const tile = e.components["Town/Tile"]- if (tile) grid.claim(tile, e.id, e.components["Town/Road"] ? "road" : "building")+ if (tile) grid.claim(tile, e.id, e.components["Town/Road"] ? "road" : e.components["Town/Park"] ? "park" : "building")}const g = grid.value()let placed = 0- let statues = 0+ let parks = 0for (let k = 0; k < g.use.length && placed < homes; k++) {if (g.use[k] !== "empty") continueconst x = k % 64const y = Math.floor(k / 64)if (!DIRS.some((d) => inside(x + d.x, y + d.y) && g.use[key(x + d.x, y + d.y)] === "road")) continueconst forever = 10_000_000- if ((placed + statues) % 3 === 2) {- building(s, "statue", x, y, 1)- statues += 1+ // Any square of four free cells this one is in.+ const corner = (placed + parks) % 5 === 4 ? [{ x, y }, { x: x - 1, y }, { x, y: y - 1 }, { x: x - 1, y: y - 1 }].find((c) => canPlace(g, { ...c, size: 2 })) : undefined+ if (corner) {+ parkCell(s, corner.x, corner.y, "square", "statue")+ parkCell(s, corner.x + 1, corner.y, "flowers", "fountain")+ parkCell(s, corner.x, corner.y + 1, "flowers", "lamp")+ parkCell(s, corner.x + 1, corner.y + 1, "lawn")+ grid.claim({ ...corner, size: 2 }, -1, "park")+ parks += 1continue}+ grid.claim({ x, y, size: 1 }, -1, "house")s.entities.push({id: s.nextEntity++,components: {@@ -199,7 +215,7 @@ const gridOf = (s: Snapshot) => {const c = e.componentsconst tile = c["Town/Tile"]if (!tile) continue- const use: Use = c["Town/Road"] ? "road" : c["Town/House"] ? "house" : c["Town/Tree"] ? "tree" : c["Town/Rock"] ? "rock" : c["Town/Water"] ? "water" : c["Town/Field"] ? "field" : c["Town/Ruin"] ? "ruin" : "building"+ const use: Use = c["Town/Road"] ? "road" : c["Town/Park"] ? "park" : c["Town/House"] ? "house" : c["Town/Tree"] ? "tree" : c["Town/Rock"] ? "rock" : c["Town/Water"] ? "water" : c["Town/Field"] ? "field" : c["Town/Ruin"] ? "ruin" : "building"builder.claim(tile, e.id, use)}return builder@@ -255,10 +271,8 @@ const standing = (s: Snapshot, kind: KindId, x: number, y: number, stock: Partia} else if (k.recipe) c["Town/Inventory"] = { stock: amounts(stock), accepts: [k.recipe.output, ...tools], cap: 8 }if (k.carriers) c["Town/Carriers"] = { count: k.carriers }if (k.service) c["Town/Service"] = { service: k.service.service, interval: ticks(k.service.seconds), cooldown: 0, range: k.service.range }- if (!k.decor) {- c["Town/Risk"] = { fire: 0, health: 0, order: 0, thefts: 0 }- c["Town/Condition"] = { value: CONDITION_MAX }- }+ c["Town/Risk"] = { fire: 0, health: 0, order: 0, thefts: 0 }+ c["Town/Condition"] = { value: CONDITION_MAX }const id = s.nextEntity++s.entities.push({ id, components: c })return id@@ -275,9 +289,12 @@ const entity = (t: ReturnType<typeof town>, id: number) => t.snapshot().entities// Room for a smithy right beside it.spot = find(g, 1, (x, y) => besideRoad(g)(x, y) && [[1, 0], [-2, 0], [0, 1], [0, -2]].some(([dx, dy]) => canPlace(g.value(), { x: x + dx!, y: y + dy!, size: 2 })), "house")home = homeAt(s, spot.x, spot.y, 2, 8)- // A statue two cells off makes the street fine enough for citizens.- const statue = find(g, 1, (x, y) => ringOf({ x, y, size: 1 }, spot.x, spot.y) === 2 && !isRoad(g.value(), x, y))- building(s, "statue", statue.x, statue.y, 1)+ // A small park two cells off (a statue and a fountain on it) makes the street fine enough for citizens.+ const park = find(g, 2, (x, y) => ringOf({ x, y, size: 2 }, spot.x, spot.y) === 2, "park")+ parkCell(s, park.x, park.y, "square", "statue")+ parkCell(s, park.x + 1, park.y, "flowers", "fountain")+ parkCell(s, park.x, park.y + 1, "lawn", "lamp")+ parkCell(s, park.x + 1, park.y + 1, "lawn")})t.run(10)const before = entity(t, home)?.components["Town/House"]?.tier@@ -413,7 +430,8 @@ const entity = (t: ReturnType<typeof town>, id: number) => t.snapshot().entitiesfor (let i = 0; i < 3; i++) {const c = find(g, 1, besideRoad(g), "house")homeAt(s, c.x, c.y, 2, 8)- building(s, "statue", ...(() => { const st = find(g, 1, () => true); return [st.x, st.y] as const })(), 1)+ const p = find(g, 1, () => true, "park")+ parkCell(s, p.x, p.y, "flowers", "statue")}})t.run(3)@@ -464,7 +482,7 @@ const entity = (t: ReturnType<typeof town>, id: number) => t.snapshot().entitiescheck("wear and mending", fell && kept > 900, `the neglected home ${fell ? "fell down" : "still stands"}; the one by the builder's yard is at ${Math.round(kept / 10)}%`)}-// Zoned against crowded: the same homes, every need met, on a street with fountains away from industry,+// Zoned against crowded: the same homes, every need met, on a street with a park behind it away from industry,// and packed in beside a smithy and a quarry. Only the first become citizens.{const t = town()@@ -492,10 +510,11 @@ const entity = (t: ReturnType<typeof town>, id: number) => t.snapshot().entities;(y < hall.y ? zoned : crowded).push(id)}if (y < hall.y) {- // Fountains behind the zoned homes.- for (const x of [hall.x - 1, hall.x + 3]) if (empty(x, besideAt)) {- building(s, "fountain", x, besideAt, 1)- lay(x, besideAt, "building")+ // A strip of park behind the zoned homes: lawn, a fountain, and lamps.+ const furnished: Record<number, PropId> = { [hall.x - 1]: "lamp", [hall.x + 1]: "fountain", [hall.x + 3]: "lamp" }+ for (let x = hall.x - 2; x <= hall.x + 4; x++) if (empty(x, besideAt)) {+ parkCell(s, x, besideAt, "lawn", furnished[x] ?? "none")+ lay(x, besideAt, "park")}} else {// A smithy and a quarry right behind the crowded ones.@@ -519,5 +538,15 @@ const entity = (t: ReturnType<typeof town>, id: number) => t.snapshot().entities)}+// A park with walks out to the street is worth more than the same park shut in behind homes.+{+ const cells: Array<ParkCell> = []+ for (let y = 0; y < 3; y++) for (let x = 0; x < 3; x++) cells.push({ x, y, ground: x === 1 ? "path" : "lawn", prop: x === 1 && y === 1 ? "fountain" : "none" })+ const shut = parkValue(cells)+ // A road runs past both ends of the walk.+ const open = parkValue(cells, (x, y) => x === 1 && (y === -1 || y === 3))+ check("park entrances", open.entrances === 2 && open.value === shut.value + 3, `shut in: ${shut.value}; two walks out to the road: ${open.value}`)+}+console.log(failures === 0 ? "\nall ends hold" : `\n${failures} failed`)if (failures > 0) process.exit(1)diff --git a/src/appeal.ts b/src/appeal.tsindex e7afa6d..dc7540e 100644--- a/src/appeal.ts+++ b/src/appeal.ts@@ -1,15 +1,16 @@/*** Desirability: how pleasant each cell is to live on. Buildings and the land* add to it or take from it, fading with distance (see `Kind.appeal` and- * `appeal` in content): industry pushes homes away, parks, fountains, and a- * chapel draw them in. Buildings' effects add up; water and woods count+ * `appeal` in content): industry pushes homes away, parks and a chapel+ * draw them in. A park is its cells of ground taken together (see+ * `parkSources`): its reach is measured from its nearest cell. Buildings' effects add up; water and woods count* once however many are near, and so do paved streets. Plain functions,* shared by the simulation (which keeps the whole grid, see `Appraise`) and* the page (which explains one cell).*/-import { appeal, kinds, type KindId } from "./content.ts"-import { key } from "./grid.ts"-import { GRID } from "./iso.ts"+import { appeal, grounds, kinds, park, props, type GroundId, type KindId, type PropId } from "./content.ts"+import { cellOf, DIRS, key } from "./grid.ts"+import { GRID, inside, type Point } from "./iso.ts"/** Something that makes the cells around it nicer or worse to live on. */export interface AppealSource {@@ -22,12 +23,22 @@ export interface AppealSource {readonly label: string/** `sum`: adds up with others; `nature` and `paved`: only the strongest of their kind counts. */readonly mode: "sum" | "nature" | "paved"+ /** A park: the cells it covers, inside the square (x, y, size) around them. */+ readonly cells?: ReadonlyArray<Point>}/** How far a cell is from a footprint, in rings: 0 on it, 1 beside it. */export const ringOf = (s: { readonly x: number; readonly y: number; readonly size: number }, x: number, y: number) =>Math.max(0, s.x - x, x - (s.x + s.size - 1), s.y - y, y - (s.y + s.size - 1))+/** How far a cell is from a source: from its nearest cell, for a park. */+const ringTo = (s: AppealSource, x: number, y: number) => {+ if (!s.cells) return ringOf(s, x, y)+ let best = Infinity+ for (const c of s.cells) best = Math.min(best, Math.max(Math.abs(c.x - x), Math.abs(c.y - y)))+ return best+}+/** What a source does at `ring` cells from its footprint: all of it beside it, fading to a little at its reach. */export const effectAt = (source: { readonly value: number; readonly reach: number }, ring: number): number => {if (ring > source.reach) return 0@@ -60,7 +71,7 @@ export const appealGrid = (sources: ReadonlyArray<AppealSource>): Array<number>const into = s.mode === "sum" ? sum : s.mode === "nature" ? nature : pavedfor (let y = Math.max(0, s.y - s.reach); y < Math.min(GRID, s.y + s.size + s.reach); y++) {for (let x = Math.max(0, s.x - s.reach); x < Math.min(GRID, s.x + s.size + s.reach); x++) {- const e = effectAt(s, ringOf(s, x, y))+ const e = effectAt(s, ringTo(s, x, y))if (e === 0) continueconst k = key(x, y)if (s.mode === "sum") into[k] = into[k]! + e@@ -76,7 +87,7 @@ export const appealParts = (sources: ReadonlyArray<AppealSource>, cell: { readonconst parts = new Map<string, number>()const best = { nature: { label: "", value: 0 }, paved: { label: "", value: 0 } }for (const s of sources) {- const e = effectAt(s, ringOf(s, cell.x, cell.y))+ const e = effectAt(s, ringTo(s, cell.x, cell.y))if (e === 0) continueif (s.mode === "sum") parts.set(s.label, (parts.get(s.label) ?? 0) + e)else if (Math.abs(e) > Math.abs(best[s.mode].value)) best[s.mode] = { label: s.label, value: e }@@ -89,3 +100,115 @@ export const appealParts = (sources: ReadonlyArray<AppealSource>, cell: { readon/** A cell's desirability from a reckoned grid (0 before the first reckoning). */export const appealAt = (cells: ReadonlyArray<number>, x: number, y: number): number => cells[key(x, y)] ?? 0++// ── Parks ─────────────────────────────────────────────────────────────────++/** A cell of park, as the town knows it. */+export interface ParkCell {+ readonly x: number+ readonly y: number+ readonly ground: GroundId+ readonly prop: PropId | "none"+}++/** A whole park: its cells, its beauty and what makes it, and what it does to the streets around it. */+export interface ParkValue {+ readonly cells: ReadonlyArray<ParkCell>+ readonly beauty: number+ readonly parts: ReadonlyArray<{ readonly label: string; readonly value: number }>+ /** Furnishings past what its size holds, which add nothing. */+ readonly crowded: number+ /** Walks and squares beside a road: its ways in from the street. */+ readonly entrances: number+ readonly value: number+ readonly reach: number+}++const tenth = (n: number) => Math.round(n * 10) / 10++/**+ * One park's worth: its ground (each cell a little, flower beds more, up to+ * `park.groundMost`), and its furnishings, the best first: one for every+ * `park.cellsPerProp` cells counts, and each one of a kind after the first+ * counts `park.repeat` of the one before; and its entrances, each walk or+ * square beside a road (`road`), up to `park.entrances`. A lawn is+ * pleasant; a lawn with walks in from the street, lamps, and a statue is a+ * park.+ */+export const parkValue = (cells: ReadonlyArray<ParkCell>, road: (x: number, y: number) => boolean = () => false): ParkValue => {+ const groundRaw = cells.reduce((n, c) => n + grounds[c.ground].beauty, 0)+ const ground = Math.min(park.groundMost, groundRaw)+ const room = Math.ceil(cells.length / park.cellsPerProp)+ const placed = cells.filter((c) => c.prop !== "none").map((c) => c.prop as PropId)+ // Each furnishing's worth given those of its kind before it; the best count first.+ const seen = new Map<PropId, number>()+ const worths = placed+ .sort((a, b) => props[b].beauty - props[a].beauty)+ .map((p) => {+ const n = seen.get(p) ?? 0+ seen.set(p, n + 1)+ return { prop: p, worth: props[p].beauty * park.repeat ** n }+ })+ .sort((a, b) => b.worth - a.worth)+ const counted = worths.slice(0, room)+ const byKind = new Map<string, number>()+ for (const w of counted) byKind.set(props[w.prop].title.toLowerCase(), (byKind.get(props[w.prop].title.toLowerCase()) ?? 0) + w.worth)+ const entrances = cells.filter((c) => (c.ground === "path" || c.ground === "square") && DIRS.some((d) => road(c.x + d.x, c.y + d.y))).length+ const welcome = Math.min(entrances, park.entrances) * park.entrance+ const beauty = ground + welcome + counted.reduce((n, w) => n + w.worth, 0)+ const parts = [+ { label: groundRaw > ground ? "ground (all it counts for)" : "ground", value: tenth(ground) },+ { label: `way${Math.min(entrances, park.entrances) === 1 ? "" : "s"} in from the street`, value: welcome },+ ...[...byKind].map(([label, value]) => ({ label, value: tenth(value) }))+ ].filter((p) => p.value > 0)+ return {+ cells,+ beauty: tenth(beauty),+ parts,+ crowded: worths.length - counted.length,+ entrances,+ value: Math.min(park.most, Math.round(beauty)),+ reach: Math.min(park.reach[2], park.reach[0] + Math.floor(cells.length / park.reach[1]))+ }+}++/** The town's parks: cells of park that touch (side by side) are one park. */+export const parksOf = (cells: ReadonlyArray<ParkCell>, road?: (x: number, y: number) => boolean): Array<ParkValue> => {+ const at = new Map<number, ParkCell>()+ for (const c of cells) at.set(key(c.x, c.y), c)+ const seen = new Set<number>()+ const out: Array<ParkValue> = []+ for (const start of at.keys()) {+ if (seen.has(start)) continue+ seen.add(start)+ const queue = [start]+ const members: Array<ParkCell> = []+ for (let head = 0; head < queue.length; head++) {+ const k = queue[head]!+ members.push(at.get(k)!)+ const c = cellOf(k)+ for (const d of DIRS) {+ if (!inside(c.x + d.x, c.y + d.y)) continue+ const n = key(c.x + d.x, c.y + d.y)+ if (seen.has(n) || !at.has(n)) continue+ seen.add(n)+ queue.push(n)+ }+ }+ out.push(parkValue(members, road))+ }+ return out+}++/** Each park as a desirability source, measured from its nearest cell. */+export const parkSources = (cells: ReadonlyArray<ParkCell>, road?: (x: number, y: number) => boolean): Array<AppealSource> =>+ parksOf(cells, road)+ .filter((p) => p.value > 0)+ .map((p) => {+ 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, y, size, value: p.value, reach: p.reach, label: "park", mode: "sum", cells: p.cells }+ })diff --git a/src/archetypes.ts b/src/archetypes.tsindex 5e7d693..476a6e7 100644--- a/src/archetypes.ts+++ b/src/archetypes.ts@@ -5,10 +5,10 @@* costs materials starts as a `Site`, anything else starts `Rising`; the* land is a `Tile` and its own marker.*/-import { amounts, CONDITION_MAX, goodIds, home, total, type Kind } from "./content.ts"+import { amounts, CONDITION_MAX, goodIds, home, total, type GroundId, type Kind } from "./content.ts"import type { Point } from "./iso.ts"import {- Building, Carriers, Condition, Field, Game, Gatherer, House, Inventory, Planter, Recipe, Rising, Risk, Road, Rock, Ruin, Service, Site,+ Building, Carriers, Condition, Field, Game, Gatherer, House, Inventory, Park, Planter, Recipe, Rising, Risk, Road, Rock, Ruin, Service, Site,Staff, Status, Storage, Tile, Tree, Water} from "./schema.ts"import { ticks } from "./content.ts"@@ -65,8 +65,8 @@ export const rolesOf = (kind: Kind) => {const s = kind.serviceroles.push(Game.Command.entry(Service, { service: s.service, interval: ticks(s.seconds), cooldown: 0, range: s.range }))}- // Ornaments and the town hall neither burn nor wear.- if (!kind.decor && kind.id !== "townhall") roles.push(...wearOf())+ // The town hall neither burns nor wears.+ if (kind.id !== "townhall") roles.push(...wearOf())return roles}@@ -79,6 +79,7 @@ export const houseStart = () => [site(home.cost), ...wearOf()]export const ruinDraft = (tile: { readonly x: number; readonly y: number; readonly size: number }, cause: "burnt" | "collapsed" | "derelict") =>Game.Command.spawn([Tile, { x: tile.x, y: tile.y, size: tile.size }], [Ruin, { cause }])+export const parkDraft = (cell: Point, ground: GroundId) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Park, { ground, prop: "none" }])export const roadDraft = (cell: Point) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Road, {}])export const treeDraft = (cell: Point, growth: number) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Tree, { growth }])export const rockDraft = (cell: Point, ore: boolean, amount: number) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Rock, { ore, amount }])diff --git a/src/art.ts b/src/art.tsindex 3b497e4..4b11ff1 100644--- a/src/art.ts+++ b/src/art.ts@@ -22,7 +22,7 @@import { Container, Graphics } from "pixi.js"import type { SurfaceState } from "./render3d/surface-state.ts"-import { goods, GROWN, home, kinds, ROCK_AMOUNT, type GoodId, type Kind, type KindId, type Tier } from "./content.ts"+import { goods, GROWN, home, kinds, ROCK_AMOUNT, type GoodId, type GroundId, type Kind, type KindId, type PropId, type Tier } from "./content.ts"import { cellOf, DIRS, key } from "./grid.ts"import { flat, GRID, toScreen, U, type Point } from "./iso.ts"@@ -638,12 +638,7 @@ const dresses: Readonly<Record<KindId, Dress>> = {healer: { accent: 0x4f9a8a },hospital: { accent: 0x4f9a8a, glass: glassCool },watchhouse: { accent: 0x3d4f6e, flag: 0x3d4f6e },- builder: { accent: 0x8a6a45, roof: roofOf(0xb08a5a) },- garden: { accent: 0x4f9a6a },- park: { accent: 0x4f9a6a },- fountain: { accent: 0x5f8fb0 },- statue: { accent: 0x8f9891 },- plaza: { accent: 0x8f9891 }+ builder: { accent: 0x8a6a45, roof: roofOf(0xb08a5a) }}/**@@ -652,36 +647,57 @@ const dresses: Readonly<Record<KindId, Dress>> = {* and grey, as a ghost.*//**- * An ornament (a garden, park, fountain, statue, or plaza), drawn simply: a- * placeholder until each has a drawing of its own.+ * A piece of park for the build menu, on a cell of its ground: lawn, a+ * flower bed, a gravel walk, a paved square, or a furnishing (a lamp on+ * lawn, a statue or a fountain on a square).*/-export const drawDecor = (g: Graphics, kind: Kind) => {- const p = plateHalf(kind.size)+export const drawParkPiece = (g: Graphics, what: GroundId | PropId) => {+ const p = plateHalf(1)const green = 0xd8e6c9const stone = 0xe4e6e0- quad(g, square(0, 0, p), kind.id === "plaza" ? stone : green)- if (kind.id === "garden" || kind.id === "park") {- const spots = kind.id === "garden" ? [[-0.2, -0.2], [0.2, 0.2]] : [[-0.5, -0.5], [0.5, -0.4], [-0.4, 0.5], [0.45, 0.45]]- for (const [u, v] of spots) {- const c = at(u!, v!, 0)- g.ellipse(c.x, c.y - 9, 6, 6).fill({ color: 0xa9c79a }).stroke({ color: ink, width: DETAIL })- line(g, c, { x: c.x, y: c.y - 4 }, LINE, 0x6b5a45)- }- if (kind.id === "garden") for (const [u, v] of [[0.25, -0.25], [-0.25, 0.25]]) g.circle(at(u!, v!, 0).x, at(u!, v!, 0).y - 1, 1.6).fill({ color: 0xe89a7c })- return+ quad(g, square(0, 0, p), what === "square" || what === "statue" || what === "fountain" ? stone : green)+ const tree = (u: number, v: number, r = 6) => {+ const c = at(u, v, 0)+ line(g, c, { x: c.x, y: c.y - 4 }, LINE, 0x6b5a45)+ g.ellipse(c.x, c.y - 4 - r, r, r).fill({ color: 0xa9c79a }).stroke({ color: ink, width: DETAIL })}- if (kind.id === "fountain") {- cylinder(g, 0, 0, 5 * U, 0, 4, 0xdfe3dc, 0xc9dde6)- cylinder(g, 0, 0, 1.2 * U, 4, 8, 0xdfe3dc, 0xeef0ea)- return+ switch (what) {+ case "lawn":+ for (const [u, v] of [[-0.2, -0.1], [0.15, 0.2], [0.25, -0.25], [-0.25, 0.25]]) {+ const c = at(u!, v!, 0)+ line(g, { x: c.x - 1.5, y: c.y }, { x: c.x, y: c.y - 3 }, DETAIL, 0x8fae80)+ line(g, { x: c.x + 1.5, y: c.y }, { x: c.x, y: c.y - 3 }, DETAIL, 0x8fae80)+ }+ return+ case "flowers":+ quad(g, square(0, 0, p * 0.65), 0xd9c7a6)+ for (const [i, [u, v]] of [[-0.2, -0.2], [0.2, -0.2], [0, 0], [-0.2, 0.2], [0.2, 0.2]].entries())+ g.circle(at(u!, v!, 0).x, at(u!, v!, 0).y - 1.5, 2.2).fill({ color: [0xc78374, 0xd6ba69, 0xb29ac2, 0xe0a0a8][i % 4]! })+ return+ case "path":+ quad(g, [at(-0.5, -0.2, 0), at(0.5, -0.2, 0), at(0.5, 0.2, 0), at(-0.5, 0.2, 0)], 0xece4d3)+ return+ case "square":+ for (const u of [-0.25, 0, 0.25]) line(g, at(u, -0.45, 0), at(u, 0.45, 0), DETAIL, 0xc6ccc3)+ for (const v of [-0.25, 0, 0.25]) line(g, at(-0.45, v, 0), at(0.45, v, 0), DETAIL, 0xc6ccc3)+ return+ case "lamp": {+ line(g, at(0, 0, 0), at(0, 0, 18), LINE)+ g.rect(at(0, 0, 22).x - 2.5, at(0, 0, 22).y, 5, 5).fill({ color: 0xf6e6a8 }).stroke({ color: ink, width: DETAIL })+ return+ }+ case "fountain":+ cylinder(g, 0, 0, 5 * U, 0, 4, 0xdfe3dc, 0xc9dde6)+ cylinder(g, 0, 0, 1.2 * U, 4, 8, 0xdfe3dc, 0xeef0ea)+ return+ case "statue":+ cylinder(g, 0, 0, 2.5 * U, 0, 6, 0xdfe3dc, stone)+ cylinder(g, 0, 0, 1.2 * U, 6, 16, 0xc9ccc4, 0xb9beb5)+ return}- // A statue (on its own, or in the middle of a plaza).- cylinder(g, 0, 0, 2.5 * U, 0, 6, 0xdfe3dc, stone)- cylinder(g, 0, 0, 1.2 * U, 6, 16, 0xc9ccc4, 0xb9beb5)}export const drawBuilding = (g: Graphics, kind: Kind, build: number, door: number, wave: number, doors: Doors, plain = false) => {- if (kind.decor) return drawDecor(g, kind)const dress: Dress = plain ? { accent: 0xb9beb5 } : dresses[kind.id]const color = dress.accentconst a = kind.half * Udiff --git a/src/asset-lab/assets.ts b/src/asset-lab/assets.tsindex 76714dd..adbf799 100644--- a/src/asset-lab/assets.ts+++ b/src/asset-lab/assets.ts@@ -1,6 +1,6 @@/** Portable polygon-and-stroke assets. Floor coordinates remain in cells;* heights remain in the original drawing's pixels. No renderer types here. */-import { kindIds, goodIds, kinds, home } from "../content.ts"+import { kindIds, goodIds, kinds, home, propIds } from "../content.ts"import { withAppearance } from "./appearance.ts"import { groundAsset } from "../render3d/models.ts"import { key } from "../grid.ts"@@ -10,7 +10,7 @@ import { U } from "../iso.ts"import { makeTree, makeRock, makeField, makeRoadPatch, makeWater } from "./land.ts"import { personCatalogue, makeCarrier, makeGoods, makeCrate } from "./people.ts"import { makeSite, makeConstruction, makeMarker, makeSmoke, makePlot } from "./construction.ts"-import { makeRuin } from "./town-props.ts"+import { makeParkProp, makeRuin, makeSamplePark } from "./town-props.ts"import { Drawing, mix, pale, square, sides, palette, type InkAsset, type Vertex } from "./primitives.ts"export * from "./primitives.ts"@@ -148,6 +148,7 @@ additional.push(makeRoadPatch(), makeWater(), ...personCatalogue())asset.id = "paved-street"; asset.title = "Paved street"; asset.note = "Raised stone setts with staggered joints and joined edges."; asset.category = "land"; asset.reference = { type: "roads" }; asset.footprint = 3additional.push(asset)}+additional.push(makeSamplePark(), ...propIds.map(makeParkProp))for (const barrow of [false, true]) {additional.push(makeCarrier(null, barrow))for (const good of goodIds) for (const count of [1, 4]) additional.push(makeCarrier(good, barrow, count))diff --git a/src/asset-lab/buildings.ts b/src/asset-lab/buildings.tsindex 6a82391..b24768c 100644--- a/src/asset-lab/buildings.ts+++ b/src/asset-lab/buildings.ts@@ -1,7 +1,6 @@import { kinds, type KindId } from "../content.ts"import { U } from "../iso.ts"import { Drawing, palette, pale, square, sides, type Vertex, type Side } from "./primitives.ts"-import { makeDecor } from "./town-props.ts"import { finishTownBuilding, townBuildingNotes, institutionDoor, makeQuarry } from "./services.ts"const dresses: Record<KindId, { accent: number; roof?: number; glass?: number }> = {@@ -28,12 +27,7 @@ const dresses: Record<KindId, { accent: number; roof?: number; glass?: number }>healer: { accent: 0x4f9a8a },hospital: { accent: 0x4f9a8a, glass: 0xc9d6ee },watchhouse: { accent: 0x3d4f6e },- builder: { accent: 0x8a6a45, roof: 0xb08a5a },- garden: { accent: 0x4f9a6a },- park: { accent: 0x4f9a6a },- fountain: { accent: 0x5f8fb0 },- statue: { accent: 0x8f9891 },- plaza: { accent: 0x8f9891 }+ builder: { accent: 0x8a6a45, roof: 0xb08a5a }}export interface BuildingOptions {@@ -44,7 +38,6 @@ export interface BuildingOptions {motion?: boolean}export function makeBuilding(id: KindId, options: BuildingOptions = {}) {- if (kinds[id].decor) return makeDecor(id)if (id === "quarry") return makeQuarry(options)const fit = options.fit ?? 1const kind = kinds[id],diff --git a/src/asset-lab/town-props.ts b/src/asset-lab/town-props.tsindex 7f54c4a..0ad95a0 100644--- a/src/asset-lab/town-props.ts+++ b/src/asset-lab/town-props.ts@@ -1,11 +1,14 @@/*** Town models for what the town gained with desirability, services,- * and decay: ornaments (garden, park, fountain, statue, plaza) and ruins.+ * and decay: parks (ground and furnishings, laid cell by cell) and ruins.* They are built from the same primitives as everything else so they* have complete rotatable geometry in the same pale ink palette.*/-import { kinds, type KindId } from "../content.ts"+import type { ParkCell } from "../appeal.ts"+import { props, type GroundId, type PropId } from "../content.ts"+import { cellOf, DIRS, key } from "../grid.ts"import { U } from "../iso.ts"+import { hash } from "./land.ts"import { Drawing, palette, square, type Vertex } from "./primitives.ts"const green = 0xd8e6c9@@ -13,12 +16,6 @@ const leaves = 0xa9c79aconst stone = 0xe4e6e0const water = 0xc9dde6-const tree = (d: Drawing, u: number, v: number, size = 1) => {- d.cylinder(u, v, 0.5 * U * size, 0, 8 * size, 0xb08a5e, 0xb08a5e, 1, 8)- for (const [x, y, z, r] of [[-2, 0, 11, 4], [2, 1, 13, 4.5], [0, -2, 16, 3.5]] as const)- d.ellipsoid(u + x * U * size, v + y * U * size, z * size, r * U * size, r * U * size, r * size, 0xb7cbaa, 1, 0xe2ead4, 12)-}-export function flowerBed(d: Drawing, u: number, v: number, width = 3, color = 0xc78374) {d.box(u, v, width * U, 1.2 * U, 0, 2, 0xbac9a4, 0xe4d7bd, 0xd0c2a8, 1)for (let i = -1; i <= 1; i++) {@@ -61,57 +58,152 @@ const figure = (d: Drawing, u: number, v: number, z: number) => {d.face([[u + 2.8 * U, v, z + 19], [u + 5 * U, v, z + 17], [u + 2.8 * U, v, z + 16]], 0xc9d2c7, 1)}-/** An ornament of `id`, `size` cells a side, on its plate. */-export function makeDecor(id: KindId) {- const kind = kinds[id],- p = (kind.size * 8 - 1) * U- const d = new Drawing(id, kind.title, "Planting beds, carved stone and timber furniture in the town's pale ink palette.")- d.asset.category = "buildings"- d.asset.reference = { type: "building", kind: id }- d.asset.footprint = kind.size- d.face(square(0, 0, p, -0.15), id === "plaza" || id === "statue" || id === "fountain" ? stone : green)- if (id === "garden") {- d.box(0, 0, p, U, 0, 0.3, 0xeee9de, 0xe3ddcf, 0xd5d0c4, 0.75)- tree(d, -2*U, -2*U, 0.6)- tree(d, 2*U, 2*U, 0.6)- flowerBed(d, p / 2, -p / 2, 2, 0xc78374)- flowerBed(d, -p / 2, p / 2, 2, 0xd6ba69)- } else if (id === "park") {- tree(d, -p / 2, -p / 2, 1.1)- tree(d, p / 2, -p / 3, 0.9)- tree(d, -p / 3, p / 2, 1)- d.box(0, 0, p, U, 0, 0.3, 0xeee9de, 0xe3ddcf, 0xd5d0c4, 0.75)- bench(d, p / 2, p / 2)- flowerBed(d, p / 2, p * 0.8, 3, 0xb29ac2)- } else if (id === "fountain") {- d.cylinder(0, 0, 5.5 * U, 0, 4, 0xdfe3dc, water, 1, 16)- d.cylinder(0, 0, 1.2 * U, 4, 7, 0xdfe3dc, stone, 1, 10)- d.cylinder(0, 0, 2.5 * U, 11, 2, 0xdfe3dc, water, 1, 12)- d.cylinder(0, 0, 4.6 * U, 4.03, 0.2, water, 0xd8e8ee, 0.75, 24)- d.ellipsoid(0, 0, 15, U, U, 1.8, stone, 1, undefined, 12)- for (let i = 0; i < 4; i++) {- const a = i * Math.PI / 2- d.line(Array.from({ length: 9 }, (_, j): Vertex => { const t = j / 8; return [Math.cos(a) * (1 + 3 * t) * U, Math.sin(a) * (1 + 3 * t) * U, 13 + 2 * Math.sin(t * Math.PI) - 8 * t] }), 1, 0x8faebd)- }- for (const r of [2.5, 3.5]) d.line(Array.from({ length: 25 }, (_, i): Vertex => [Math.cos(i * Math.PI / 12) * r * U, Math.sin(i * Math.PI / 12) * r * U, 4.3]), 0.75, 0xa9c5d0)- } else if (id === "statue") {- setts(d, 0, 0, p - 0.02, 0)- figure(d, 0, 0, 6)- } else if (id === "plaza") {- setts(d, 0, 0, p - 0.02, 0)- figure(d, 0, 0, 6)- tree(d, -p * 0.65, -p * 0.65, 0.65)- tree(d, p * 0.65, p * 0.65, 0.65)- bench(d, p * 0.6, -p * 0.7)- bench(d, -p * 0.6, p * 0.7)+/** A fountain's basin, column, and jets, centred on (u, v). */+function fountain(d: Drawing, u: number, v: number) {+ d.cylinder(u, v, 5.5 * U, 0, 4, 0xdfe3dc, water, 1, 16)+ d.cylinder(u, v, 1.2 * U, 4, 7, 0xdfe3dc, stone, 1, 10)+ d.cylinder(u, v, 2.5 * U, 11, 2, 0xdfe3dc, water, 1, 12)+ d.cylinder(u, v, 4.6 * U, 4.03, 0.2, water, 0xd8e8ee, 0.75, 24)+ d.ellipsoid(u, v, 15, U, U, 1.8, stone, 1, undefined, 12)+ for (let i = 0; i < 4; i++) {+ const a = i * Math.PI / 2+ d.line(Array.from({ length: 9 }, (_, j): Vertex => { const t = j / 8; return [u + Math.cos(a) * (1 + 3 * t) * U, v + Math.sin(a) * (1 + 3 * t) * U, 13 + 2 * Math.sin(t * Math.PI) - 8 * t] }), 1, 0x8faebd)}- if (id === "garden" || id === "park") for (const y of [-p + U, p - U]) {- for (let x = -p + U; x <= p - U; x += 2 * U) d.box(x, y, 0.25 * U, 0.25 * U, 0, 5, 0xe9d2a8, 0xd0b58c, 0xb08a5e, 0.75)- d.line([[-p + U, y, 3], [p - U, y, 3]], 1, 0xb08a5e)+ for (const r of [2.5, 3.5]) d.line(Array.from({ length: 25 }, (_, i): Vertex => [u + Math.cos(i * Math.PI / 12) * r * U, v + Math.sin(i * Math.PI / 12) * r * U, 4.3]), 0.75, 0xa9c5d0)+}++/** An iron lamp post with a lantern. */+function lamp(d: Drawing, u: number, v: number) {+ d.cylinder(u, v, 1.2 * U, 0, 1.5, 0x8d9589, 0xaeb5ab, 1, 8)+ d.cylinder(u, v, 0.35 * U, 1.5, 15, palette.ink, palette.ink, 0.75, 6)+ d.box(u, v, 1.1 * U, 1.1 * U, 16.5, 4, 0xf6e6a8, 0xf1d98a, 0xe2c46e, 1)+ d.box(u, v, 1.5 * U, 1.5 * U, 20.5, 1.2, 0x5b665f, 0x46514b, 0x3d4943, 1)+ d.cylinder(u, v, 0.4 * U, 21.7, 1.5, palette.ink, palette.ink, 0.75, 6)+}++/** A park's furnishing on a cell centred on (u, v). */+export function parkProp(d: Drawing, prop: PropId, u: number, v: number) {+ if (prop === "lamp") lamp(d, u + 4 * U, v - 4 * U)+ else if (prop === "statue") {+ d.box(u, v, 4.5 * U, 4.5 * U, 0, 2, 0xe9ebe5, 0xd5d9d0, 0xbec5bb, 1)+ figure(d, u, v, 8)+ } else fountain(d, u, v)+}++const lawn = 0xdce8cd+const lawnDark = 0xd3e1c2+const gravel = 0xece4d3++/**+ * Parks laid on the ground, cell by cell (by `key`): lawn with its blades,+ * flower beds, gravel walks that join their neighbours (and the roads they+ * meet), paved squares, a stone kerb where the park ends, and each cell's+ * furnishing. `roads` lets a walk run out to the street.+ */+export function parkAsset(cells: ReadonlyMap<number, ParkCell>, roads: ReadonlySet<number> = new Set(), preview = false) {+ const d = new Drawing("parks", "Parks", "")+ const z = preview ? 0.17 : -0.12+ const isPark = (x: number, y: number) => cells.has(key(x, y))+ const walk = (x: number, y: number) => {+ const c = cells.get(key(x, y))+ return c !== undefined && (c.ground === "path" || c.ground === "square")+ }+ for (const [k, c] of cells) {+ const { x, y } = cellOf(k), u = x + 0.5, v = y + 0.5+ const h = hash(x, y)+ if (c.ground === "square") setts(d, u, v, 0.5, z)+ else d.face(square(u, v, 0.5, z), h < 0.5 ? lawn : lawnDark, 0)+ if (c.ground === "lawn" || c.ground === "flowers")+ for (let i = 0; i < 4; i++) {+ const a = u - 0.35 + hash(x * 5 + i, y * 3) * 0.7, b = v - 0.35 + hash(y * 7 + i, x * 2) * 0.7+ d.line([[a - 0.03, b, z + 0.02], [a, b, z + 2], [a + 0.03, b, z + 0.02]], 0.75, 0xa9c79a)+ }+ if (c.ground === "flowers") {+ d.face(square(u, v, 0.34, z + 0.03), 0xd9c7a6, 1, 0xb6a27f)+ const colors = [0xc78374, 0xd6ba69, 0xb29ac2, 0xe0a0a8]+ for (let i = 0; i < 9; i++) {+ const a = u + ((i % 3) - 1) * 0.2, b = v + (Math.floor(i / 3) - 1) * 0.2+ d.ellipsoid(a, b, 1.2, 1.1 * U, 1.1 * U, 1.3, 0xa9c79a, 0, undefined, 8)+ d.ellipsoid(a, b, 2.4, 0.7 * U, 0.7 * U, 0.8, colors[(i + Math.floor(h * 4)) % 4]!, 0.5, undefined, 8)+ }+ }+ if (c.ground === "path") {+ // A walk: a square in the middle, and a strip out to each walk or road beside it.+ const w = 0.2+ d.face(square(u, v, w, z + 0.02), gravel, 0)+ const out: Array<Vertex> = []+ for (const { x: dx, y: dy } of DIRS) {+ const joined = walk(x + dx, y + dy) || roads.has(key(x + dx, y + dy))+ const q = (along: number, across: number): Vertex => [u + dx * along - dy * across, v + dy * along + dx * across, z + 0.03]+ if (joined) {+ d.face([q(w, -w), q(0.5, -w), q(0.5, w), q(w, w)], gravel, 0)+ d.line([q(w, -w), q(0.5, -w)], 1, 0xc2b79f)+ d.line([q(w, w), q(0.5, w)], 1, 0xc2b79f)+ } else d.line([q(w, -w), q(w, w)], 1, 0xc2b79f)+ out.push(q(0.1 + hash(x * 3 + dx, y * 3 + dy) * 0.08, 0.05))+ }+ for (const p of out) d.line([p, [p[0] + 0.02, p[1], p[2]]], 1, 0xb8ad95)+ }+ // A low stone kerb where the park ends.+ for (const { x: dx, y: dy } of DIRS) {+ if (isPark(x + dx, y + dy)) continue+ const q = (along: number, across: number): Vertex => [u + dx * along - dy * across, v + dy * along + dx * across, z]+ const centre = q(0.47, 0)+ d.box(centre[0], centre[1], dx ? 0.03 : 0.5, dy ? 0.03 : 0.5, z, 1.2, 0xeceee8, 0xd7dbd2, 0xc9cec4, 0.75)+ }+ if (c.prop !== "none") parkProp(d, c.prop, u, v)}return d.asset}+/** One furnishing on a cell of lawn (or square), for the catalogue and the build menu. */+export function makeParkProp(prop: PropId) {+ const ground: GroundId = prop === "statue" || prop === "fountain" ? "square" : "lawn"+ const asset = parkAsset(new Map([[key(0, 0), { x: 0, y: 0, ground, prop }]]))+ const shift = ([u, v, z]: Vertex): Vertex => [u - 0.5, v - 0.5, z]+ asset.faces.forEach((f) => { f.points = f.points.map(shift) })+ asset.strokes.forEach((s) => { s.points = s.points.map(shift) })+ asset.id = `park-${prop}`+ asset.title = `Park · ${props[prop].title.toLowerCase()}`+ asset.note = props[prop].blurb+ asset.category = "land"+ asset.reference = { type: "none" }+ asset.footprint = 1+ return asset+}++/** A small park laid out the way a player would: lawn, walks, flower beds, lamps, a fountain, and a statue. */+export const samplePark: ReadonlyArray<ParkCell> = (() => {+ const plan = [+ "FLPLF",+ "LAPAL",+ "PPWPP",+ "LAPSL",+ "FLPLF"+ ]+ const out: Array<ParkCell> = []+ plan.forEach((row, y) => [...row].forEach((ch, x) => {+ const ground: GroundId = ch === "P" || ch === "A" ? "path" : ch === "S" || ch === "W" ? "square" : ch === "F" ? "flowers" : "lawn"+ const prop: PropId | "none" = ch === "A" ? "lamp" : ch === "S" ? "statue" : ch === "W" ? "fountain" : "none"+ out.push({ x, y, ground, prop })+ }))+ return out+})()++export function makeSamplePark() {+ const asset = parkAsset(new Map(samplePark.map((c) => [key(c.x, c.y), c])))+ const shift = ([u, v, z]: Vertex): Vertex => [u - 2.5, v - 2.5, z]+ asset.faces.forEach((f) => { f.points = f.points.map(shift) })+ asset.strokes.forEach((s) => { s.points = s.points.map(shift) })+ asset.id = "park-sample"+ asset.title = "Park · laid out"+ asset.note = "A five-by-five park built piece by piece: lawn, a cross of walks, flower beds in the corners, lamps, a fountain, and a statue on paved squares."+ asset.category = "land"+ asset.reference = { type: "none" }+ asset.footprint = 5+ return asset+}+/** What is left of a home or building: charred, tumbled down, or boarded up. */export function makeRuin(size: number, cause: "burnt" | "collapsed" | "derelict") {const d = new Drawing(`ruin-${cause}-${size}`, `Ruin · ${cause}`, "Exposed masonry, fallen rafters, roof tiles and weeds; each cause leaves a different silhouette.")diff --git a/src/content.ts b/src/content.tsindex d258107..753e62a 100644--- a/src/content.ts+++ b/src/content.ts@@ -68,8 +68,8 @@ export const SPOIL_TICKS = 600// ── Buildings ─────────────────────────────────────────────────────────────-export type Category = "storage" | "gathering" | "crafts" | "food" | "services" | "decor"-export const categoryOrder: ReadonlyArray<Category> = ["storage", "gathering", "crafts", "food", "services", "decor"]+export type Category = "storage" | "gathering" | "crafts" | "food" | "services"+export const categoryOrder: ReadonlyArray<Category> = ["storage", "gathering", "crafts", "food", "services"]/** Awnings are coloured by what a building is for. */export const categoryColor: Readonly<Record<Category, number>> = {@@ -77,8 +77,7 @@ export const categoryColor: Readonly<Record<Category, number>> = {gathering: 0x6e8f36,crafts: 0xd27a34,food: 0xd6ae2e,- services: 0x3d6db5,- decor: 0x4f9a6a+ services: 0x3d6db5}export const homeColor = 0xc4523f@@ -94,8 +93,7 @@ export type Topper = "none" | "chimney" | "flag" | "cupola" | "sails" | "crates"export const kindIds = ["townhall", "warehouse", "lumberjack", "forester", "quarry", "mine", "fishery", "sawmill","smithy", "farm", "mill", "bakery", "sheep", "weaver", "market", "chapel",- "granary", "smokehouse", "firewatch", "healer", "hospital", "watchhouse", "builder",- "garden", "park", "fountain", "statue", "plaza"+ "granary", "smokehouse", "firewatch", "healer", "hospital", "watchhouse", "builder"] as constexport type KindId = (typeof kindIds)[number]@@ -150,8 +148,6 @@ export interface Kind {readonly dusty?: boolean/** A storage that keeps food this many times longer. */readonly keeps?: number- /** An ornament: no workers, no road, no wear; only its desirability. */- readonly decor?: boolean}const free = { residents: 0, citizens: 0 }@@ -310,48 +306,76 @@ export const kinds: Readonly<Record<KindId, Kind>> = {cost: { coins: 90, materials: { planks: 4 } }, upkeep: 3, workers: 2, crew: "settlers", unlock: free, buildable: true,holds: { accepts: ["planks", "stone"], cap: 6 },service: { service: "repair", seconds: 8, range: 20 }, appeal: { value: -2, reach: 2 }- },- garden: {- id: "garden", title: "Garden", blurb: "a row of trees and flowers: the street around it is nicer to live on",- category: "decor", size: 1, half: 6, stories: 1, roof: "flat", bays: 2, window: 4, topper: "none",- cost: { coins: 15, materials: {} }, upkeep: 0.5, workers: 0, crew: "settlers", unlock: free, buildable: true,- appeal: { value: 3, reach: 2 }, decor: true- },- park: {- id: "park", title: "Park", blurb: "lawns, trees, and a bench",- category: "decor", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 4, topper: "none",- cost: { coins: 60, materials: { planks: 1 } }, upkeep: 2, workers: 0, crew: "settlers", unlock: free, buildable: true,- appeal: { value: 6, reach: 3 }, decor: true- },- fountain: {- id: "fountain", title: "Fountain", blurb: "a stone basin of fresh water",- category: "decor", size: 1, half: 6, stories: 1, roof: "flat", bays: 2, window: 4, topper: "none",- cost: { coins: 80, materials: { stone: 3 } }, upkeep: 2, workers: 0, crew: "settlers", unlock: { residents: 30, citizens: 0 }, buildable: true,- appeal: { value: 6, reach: 3 }, decor: true- },- statue: {- id: "statue", title: "Statue", blurb: "a founder in stone, for the town's best street",- category: "decor", size: 1, half: 6, stories: 1, roof: "flat", bays: 2, window: 4, topper: "none",- cost: { coins: 180, materials: { stone: 6 } }, upkeep: 3, workers: 0, crew: "settlers", unlock: { residents: 0, citizens: 20 }, buildable: true,- appeal: { value: 10, reach: 4 }, decor: true- },- plaza: {- id: "plaza", title: "Plaza", blurb: "a paved square with a statue in the middle",- category: "decor", size: 2, half: 12, stories: 1, roof: "flat", bays: 2, window: 4, topper: "none",- cost: { coins: 260, materials: { stone: 10 } }, upkeep: 4, workers: 0, crew: "settlers", unlock: { residents: 0, citizens: 40 }, buildable: true,- appeal: { value: 10, reach: 4 }, decor: true}}export const kindOrder: ReadonlyArray<KindId> = ["warehouse", "granary", "lumberjack", "forester", "quarry", "mine", "sawmill", "smithy", "sheep", "weaver",- "fishery", "smokehouse", "farm", "mill", "bakery", "market", "chapel", "firewatch", "healer", "hospital", "watchhouse", "builder",- "garden", "park", "fountain", "statue", "plaza"+ "fishery", "smokehouse", "farm", "mill", "bakery", "market", "chapel", "firewatch", "healer", "hospital", "watchhouse", "builder"]export const costText = (cost: Kind["cost"]): string =>[cost.coins > 0 ? `${cost.coins} coins` : "", ...Object.entries(cost.materials).map(([g, n]) => `${n} ${g}`)].filter((s) => s !== "").join(" · ")+// ── Parks ─────────────────────────────────────────────────────────────────++/**+ * A park is laid out cell by cell: ground painted on empty land (lawn,+ * flower beds, gravel paths, a paved square), and on any of its cells one+ * furnishing (a lamp, a fountain, a statue). Cells of ground that touch+ * make one park, and the whole park is what the street around it feels+ * (see `parkSources` in `appeal.ts`): its `beauty` adds up from its+ * ground, its furnishings, and its entrances (a walk or a square beside a+ * road), and that is the desirability it gives the cells around it, out to+ * a reach that grows with its size. Nobody walks through it: it is not a+ * road.+ */+export const groundIds = ["lawn", "flowers", "path", "square"] as const+export type GroundId = (typeof groundIds)[number]+export const propIds = ["lamp", "fountain", "statue"] as const+export type PropId = (typeof propIds)[number]++export interface ParkPiece {+ readonly title: string+ readonly blurb: string+ readonly cost: Kind["cost"]+ /** Coins a minute. */+ readonly upkeep: number+ /** What it adds to its park's beauty. */+ readonly beauty: number+ readonly unlock: { readonly residents: number; readonly citizens: number }+}++export const grounds: Readonly<Record<GroundId, ParkPiece>> = {+ lawn: { title: "Lawn", blurb: "grass to lay a park out on", cost: { coins: 2, materials: {} }, upkeep: 0.05, beauty: 0.25, unlock: free },+ flowers: { title: "Flower bed", blurb: "planted borders: prettier than lawn", cost: { coins: 5, materials: {} }, upkeep: 0.15, beauty: 0.75, unlock: free },+ path: { title: "Gravel path", blurb: "a walk through the park", cost: { coins: 3, materials: {} }, upkeep: 0.05, beauty: 0.25, unlock: free },+ square: { title: "Paved square", blurb: "stone setts, for a statue or a fountain to stand on", cost: { coins: 3, materials: { stone: 1 } }, upkeep: 0.05, beauty: 0.25, unlock: free }+}++export const props: Readonly<Record<PropId, ParkPiece>> = {+ lamp: { title: "Lamp", blurb: "an iron lamp post along the walk", cost: { coins: 12, materials: { tools: 1 } }, upkeep: 0.2, beauty: 1.5, unlock: free },+ fountain: { title: "Fountain", blurb: "a stone basin of fresh water", cost: { coins: 70, materials: { stone: 3 } }, upkeep: 2, beauty: 4, unlock: { residents: 30, citizens: 0 } },+ statue: { title: "Statue", blurb: "a founder in stone, the pride of the park", cost: { coins: 160, materials: { stone: 6 } }, upkeep: 3, beauty: 5, unlock: { residents: 0, citizens: 20 } }+}++/** How a park's beauty adds up (see `parkSources`). */+export const park = {+ /** Ground counts for this much beauty at most, however big the park. */+ groundMost: 4,+ /** One furnishing counts for every this many cells: a park crowded with benches is no nicer. */+ cellsPerProp: 2,+ /** Each furnishing of a kind after the first counts this share of the one before. */+ repeat: 0.5,+ /** A walk or a square beside a road is a way in from the street: each adds this, up to `entrances` of them. */+ entrance: 1.5,+ entrances: 2,+ /** The most a park gives the streets around it. */+ most: 15,+ /** How far it reaches: `reach[0]` cells, and one more for every `reach[1]` cells of park, up to `reach[2]`. */+ reach: [2, 6, 5] as const+}+// ── Homes ─────────────────────────────────────────────────────────────────export type Tier = 1 | 2 | 3diff --git a/src/host.ts b/src/host.tsindex 6ed1127..d92b779 100644--- a/src/host.ts+++ b/src/host.ts@@ -5,7 +5,7 @@*/import { Application, Graphics } from "pixi.js"-import { drawBuilding, drawHouse, homeVariant, plate, plateHalf } from "./art.ts"+import { drawBuilding, drawHouse, drawParkPiece, homeVariant, plate, plateHalf } from "./art.ts"import {categoryColor,categoryOrder,@@ -13,8 +13,13 @@ import {defaultCharter,goodIds,goods,+ groundIds,+ grounds,home,kindOrder,+ park as parkRules,+ propIds,+ props,PAVE_COST,tierHome,winters,@@ -32,8 +37,11 @@ import {type Category,type CharterValue,type GoodId,+ type GroundId,type Kind,type KindId,+ type ParkPiece,+ type PropId,type Tier} from "./content.ts"import { GRID } from "./iso.ts"@@ -140,6 +148,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst ui: UiValue = {tool: "select",placing: null,+ ground: "lawn",+ prop: "lamp",menu: null,pointer: null,dragFrom: null,@@ -309,7 +319,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst refreshTools = () => {for (const { tool, button } of buttons) {- const on = tool.tool === "build" ? ui.menu === "build" || ui.tool === "place" : tool.tool === ui.tool+ const on = tool.tool === "build" ? ui.menu === "build" || ui.tool === "place" || ui.tool === "ground" || ui.tool === "prop" : tool.tool === ui.toolbutton.classList.toggle("on", on)}townButton.classList.toggle("on", ui.menu === "town")@@ -332,6 +342,18 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistechoose("place")ui.toast(`Click to place a ${kinds[kind].title.toLowerCase()} · Esc to stop`)}+ const layGround = (ground: GroundId) => {+ ui.ground = ground+ ui.menu = null+ choose("ground")+ ui.toast(`Drag a rectangle to lay ${grounds[ground].title.toLowerCase()} · Esc to stop`)+ }+ const furnish = (prop: PropId) => {+ ui.prop = prop+ ui.menu = null+ choose("prop")+ ui.toast(`Click a cell of park to set a ${props[prop].title.toLowerCase()} · Esc to stop`)+ }choose("select")window.addEventListener("keydown", (event) => {@@ -398,7 +420,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste// ── Pictures of buildings, for the build menu and the panel ──const pictures = new Map<string, Promise<string>>()/** A building (or a home of a tier) drawn as the town draws it, as an image. */- const picture = (what: KindId | Tier): HTMLImageElement => {+ const picture = (what: KindId | Tier | `park:${GroundId | PropId}`): HTMLImageElement => {const img = document.createElement("img")img.className = "thumb"img.alt = ""@@ -406,12 +428,14 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistelet url = pictures.get(id)if (!url) {const g = new Graphics()- if (what === 1 || what === 2 || what === 3) {+ if (typeof what === "string" && what.startsWith("park:")) drawParkPiece(g, what.slice(5) as GroundId | PropId)+ else if (what === 1 || what === 2 || what === 3) {plate(g, plateHalf(1))drawHouse(g, what, 1, { right: true, left: false }, homeVariant(0.1))} else {- plate(g, plateHalf(kinds[what].size))- drawBuilding(g, kinds[what], 1, 0, 0.6, { right: true, left: true })+ const kind = kinds[what as KindId]+ plate(g, plateHalf(kind.size))+ drawBuilding(g, kind, 1, 0, 0.6, { right: true, left: true })}url = app.renderer.extract.base64({ target: g, resolution: 2 })void url.finally(() => g.destroy())@@ -458,7 +482,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistereturn head}- const lockText = (kind: Kind): string | null => {+ const lockText = (kind: Pick<Kind, "unlock"> | ParkPiece): string | null => {const s = ui.statsif (!s) return nullconst residents = s.settlers + s.citizens@@ -500,8 +524,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistegathering: "wood",crafts: "tools",food: "bread",- services: "faith",- decor: "decor"+ services: "faith"}const buildMenu = () => {@@ -509,7 +532,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistefor (const category of categoryOrder) {const options = kindOrder.filter((id) => kinds[id].category === category && kinds[id].buildable)if (options.length === 0) continue- const box = section(category === "decor" ? "decorations" : category, categoryIcon[category], category === "decor" ? "Ornaments raise the desirability of the streets around them: citizens need 5, townhouses 15." : undefined)+ const box = section(category, categoryIcon[category])box.style.borderTop = `3px solid ${hex(categoryColor[category])}`for (const id of options) {const kind = kinds[id]@@ -533,6 +556,40 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste}panel.append(box)}+ // Parks are laid out piece by piece: ground first, then what stands on it.+ const parks = section(+ "parks",+ "decor",+ `Lay ground, then set furnishings on it. Ground that touches is one park: the more it holds the nicer the streets around it (citizens need 5, townhouses 15). One furnishing counts for every ${parkRules.cellsPerProp} cells.`+ )+ parks.style.borderTop = "3px solid #4f9a6a"+ const pieces: ReadonlyArray<{ readonly id: GroundId | PropId; readonly piece: ParkPiece; readonly pick: () => void; readonly ground: boolean }> = [+ ...groundIds.map((id) => ({ id, piece: grounds[id], pick: () => layGround(id), ground: true })),+ ...propIds.map((id) => ({ id, piece: props[id], pick: () => furnish(id), ground: false }))+ ]+ for (const { id, piece, pick, ground } of pieces) {+ if (ground && id === "lawn") parks.append(el("p", "empty", "ground · drag a rectangle"))+ if (!ground && id === "lamp") parks.append(el("p", "empty", "furnishings · click a cell of park"))+ const option = el("button", "option")+ const cost = costChips(piece.cost)+ const terms = el("span", "chips")+ terms.innerHTML = `<span class="chip dim" title="beauty it adds to its park">${icon("appeal", 14)}+${piece.beauty}</span><span class="chip dim" title="upkeep, coins a minute">${icon("upkeep", 14)}${piece.upkeep}/min</span>`+ const blurb = el("span", "blurb", piece.blurb)+ option.append(picture(`park:${id}`), el("span", "name", piece.title.toLowerCase()), cost.box, blurb)+ option.title = `${piece.title}: ${piece.blurb} · beauty +${piece.beauty}${ground ? " a cell" : ""} · ${piece.upkeep} coins a minute`+ cost.box.append(terms)+ option.onclick = pick+ live.push(() => {+ const lock = lockText(piece)+ const short = cost.refresh()+ option.disabled = lock !== null+ option.classList.toggle("short", lock === null && short)+ option.classList.toggle("on", (ground ? ui.tool === "ground" && ui.ground === id : ui.tool === "prop" && ui.prop === id))+ blurb.textContent = lock ?? piece.blurb+ })+ parks.append(option)+ }+ panel.append(parks)}const row = (box: HTMLElement, label: string, glyph?: IconName | GoodId) => {@@ -863,7 +920,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteif (p.type === "build") return buildMenu()if (p.type === "town") return townPanel()- const title = p.type === "building" ? kinds[p.kind].title.toLowerCase() : p.type === "house" ? tierHome[p.tier] : "ruin"+ const title = p.type === "building" ? kinds[p.kind].title.toLowerCase() : p.type === "house" ? tierHome[p.tier] : p.type === "park" ? "park" : "ruin"const status = el("span", "pill")const about = el("p",@@ -872,6 +929,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste? kinds[p.kind].blurb: p.type === "ruin"? "bulldoze it to clear the plot"+ : p.type === "park"+ ? "every cell of ground that touches this one: lay more, or set furnishings on it, to make the streets around it nicer": p.tier === 1? "settlers: fish or bread from a market keeps them; they do the rough work": p.tier === 2@@ -880,8 +939,8 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste)const below = el("div", "")below.append(status, about)- panel.append(header(title, p.type === "ruin" ? iconEl("condition", 30) : picture(p.type === "building" ? p.kind : p.tier), below))- const box = section(p.type === "building" ? "at work" : p.type === "ruin" ? "what is left" : "household", p.type === "building" ? "jobs" : "homes")+ panel.append(header(title, p.type === "ruin" ? iconEl("condition", 30) : p.type === "park" ? iconEl("decor", 30) : picture(p.type === "building" ? p.kind : p.tier), below))+ const box = section(p.type === "building" ? "at work" : p.type === "ruin" ? "what is left" : p.type === "park" ? "what makes it" : "household", p.type === "building" ? "jobs" : p.type === "park" ? "appeal" : "homes")box.classList.add("lines")const rows: Array<HTMLElement> = []panel.append(box)@@ -894,6 +953,9 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste} else if (now.type === "house") {status.textContent = `${home.tiers[now.tier].residents} at most`status.className = "pill working"+ } else if (now.type === "park") {+ status.textContent = `${now.value > 0 ? "+" : ""}${now.value} out to ${now.reach} cells`+ status.className = "pill working"} else {status.textContent = now.causestatus.className = "pill problem"diff --git a/src/map-lab/map.ts b/src/map-lab/map.tsindex 5341dde..2111334 100644--- a/src/map-lab/map.ts+++ b/src/map-lab/map.ts@@ -121,7 +121,7 @@ const layout: Array<[string, number, number]> = [["fishery", 13, 1]]for (const [id, x, y] of layout) place(id, x, y)-// Services, food stores and ornaments along the south-west street.+// Services, food stores and a park along the south-west street.const quarter: Array<[string, number, number]> = [["firewatch", -17, -2],["healer", -17, 1],@@ -130,11 +130,10 @@ const quarter: Array<[string, number, number]> = [["granary", -9.5, 1],["smokehouse", 10, 1],["hospital", 9.5, -11],- ["garden", -15, -8],- ["park", -16.5, -8],- ["fountain", 0.5, -8],- ["statue", 4.5, -8],- ["plaza", 9, -8]+ ["park-sample", 2.5, -8],+ ["park-lamp", -13.5, -8],+ ["park-statue", 9.5, -8],+ ["park-fountain", 11, -8]]for (const [id, x, y] of quarter) place(id, x, y)// The review annex gives seasonal/condition variants their own ground,diff --git a/src/model-review/main.ts b/src/model-review/main.tsindex 81b79c7..62b14a7 100644--- a/src/model-review/main.ts+++ b/src/model-review/main.ts@@ -6,7 +6,7 @@ import "./style.css"const families = {fixes: { title: "Review fixes", ids: ["mill","bakery","weaver","warehouse","mine","farm","chapel","hospital","smokehouse","builder","townhouse","quarry","stone-full","stone-quarried","ore-full","problem-marker","smoke","firewatch"] },buildings: { title: "Buildings", ids: ["granary", "smokehouse", "firewatch", "healer", "hospital", "watchhouse", "builder"] },- ornaments: { title: "Gardens & squares", ids: ["garden", "park", "fountain", "statue", "plaza", "paved-street"] },+ ornaments: { title: "Parks", ids: ["park-sample", "park-lamp", "park-fountain", "park-statue", "paved-street"] },homes: { title: "Homes & neighbourhoods", ids: ["cottage", "citizen", "townhouse", "cottage-fine", "citizen-fine", "townhouse-fine", "cottage-poor", "citizen-worn", "townhouse-worn"] },winter: { title: "Winter", ids: ["cottage-winter", "citizen-winter", "townhouse-winter", "granary-winter", "smokehouse-winter", "firewatch-winter", "healer-winter", "hospital-winter", "watchhouse-winter", "builder-winter"] },hazards: { title: "Ruins", ids: ["ruin-burnt-1", "ruin-collapsed-1", "ruin-derelict-1"] },@@ -16,7 +16,7 @@ const families = {type Family = keyof typeof familiesconst root = document.querySelector<HTMLElement>("#review")!root.innerHTML = `<header><a href="/">Inkline Town</a><span>PR 03 / MODEL REVIEW</span><a href="/map-lab.html">Town map ↗</a></header>- <section class="intro"><div><p class="eyebrow">A town with a little more life</p><h1>New places.<br>The same ink.</h1><p>Inspect the models together, turn them around, then open any one for a closer look.</p></div><aside>7 buildings<br>5 ornaments<br>3 home tiers<br><span>Plus people, hazards, paving,<br>snow and signs of wear.</span></aside></section>+ <section class="intro"><div><p class="eyebrow">A town with a little more life</p><h1>New places.<br>The same ink.</h1><p>Inspect the models together, turn them around, then open any one for a closer look.</p></div><aside>7 buildings<br>3 park furnishings<br>3 home tiers<br><span>Plus people, hazards, paving,<br>snow and signs of wear.</span></aside></section><nav aria-label="Model collections"></nav><section class="camera"><label>Turn the models <input aria-label="Model rotation" type="range" min="-180" max="180" value="0"><output>0°</output></label><button id="rear">See the back</button><button id="reset">Reset view</button><button id="sheet">Save model sheet</button><a id="sheet-link" hidden download>Download sheet ↗</a><label>View <select aria-label="View elevation"><option value="30">Street angle</option><option value="50">From above</option><option value="15">Near the ground</option></select></label></section><section class="grid" aria-label="3D models"></section><footer><a href="/effects-lab.html">Animated house effects ↗</a> · Drag a model to turn the collection · <a href="/asset-lab.html">Full asset catalogue ↗</a> · <a href="/">Play this town ↗</a></footer>`const nav = root.querySelector("nav")!, grid = root.querySelector<HTMLElement>(".grid")!, rotation = root.querySelector<HTMLInputElement>("input")!, elevation = root.querySelector<HTMLSelectElement>("select")!diff --git a/src/places.ts b/src/places.tsindex 339f581..978aaa3 100644--- a/src/places.ts+++ b/src/places.ts@@ -10,8 +10,7 @@ const streetOf: Readonly<Record<KindId, string>> = {townhall: "Hall", warehouse: "Warehouse", granary: "Granary", lumberjack: "Timber", forester: "Forest", quarry: "Quarry",mine: "Mine", fishery: "Fisher", smokehouse: "Smokehouse", sawmill: "Sawmill", smithy: "Smithy", farm: "Farm", mill: "Mill",bakery: "Baker", sheep: "Shepherd", weaver: "Weaver", market: "Market", chapel: "Chapel", firewatch: "Watch", healer: "Healer",- hospital: "Hospital", watchhouse: "Constable", builder: "Builder", garden: "Garden", park: "Park", fountain: "Fountain",- statue: "Statue", plaza: "Plaza"+ hospital: "Hospital", watchhouse: "Constable", builder: "Builder"}const suffixes = ["Lane", "Street", "Row", "Way", "Close", "Walk"] as constdiff --git a/src/present.ts b/src/present.tsindex d4cd351..2a80f1e 100644--- a/src/present.ts+++ b/src/present.ts@@ -7,13 +7,13 @@import { RenderSync } from "@typeonce/bevy-ts-render"import { hazardStrength } from "./render3d/surface-state.ts"-import { appealAt, appealParts, buildingSource, landSource, type AppealSource } from "./appeal.ts"+import { appealAt, appealParts, buildingSource, landSource, parkSources, parksOf, type AppealSource, type ParkCell, type ParkValue } from "./appeal.ts"import { homeHeight, topOf, type Alert, type Load, type Emphasis } from "./art.ts"import { BuildingView, HouseView, WalkerView, TreeView, RockView, FieldView, RuinView } from "./render3d/views.ts"import type { DoorSet, OverlayCell } from "./render3d/models.ts"import {- BUILD_TICKS, COMMUTE, condition as wear, CONDITION_MAX, crewOf, crown as crownRules, fate, goodIds, goods, home, kinds, needTitle, risk,- RISK_MAX, tierHome, total, winters, type Kind, type Tier+ BUILD_TICKS, COMMUTE, condition as wear, CONDITION_MAX, costText, crewOf, crown as crownRules, fate, goodIds, goods, grounds, home, kinds, needTitle,+ propIds, props, risk, RISK_MAX, tierHome, total, winters, type Kind, type Tier} from "./content.ts"import { around, canPlace, doors, entrances, isRoad, key, lPath, reach, useAt, type TileLike } from "./grid.ts"import { GRID, inside, U, type Point } from "./iso.ts"@@ -44,6 +44,7 @@ import {Market,Mood,Pantry,+ Park,Paused,Paved,Policy,@@ -188,6 +189,14 @@ const HouseRead = Game.Query({}})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 = (@@ -239,7 +248,7 @@ const legends: Readonly<Record<Exclude<View, "none">, Legend>> = {{ color: 0xe0a060, label: "below 0" },{ color: BAD, label: `${home.squalid} or less: squalid` }],- note: "Industry pushes homes away; gardens, parks, fountains, statues, a chapel, and paved streets draw them in."+ note: "Industry pushes homes away; parks (the more they hold, the further they reach), a chapel, and paved streets draw them in."},workers: {title: "workers",@@ -300,6 +309,7 @@ export const Interact = Game.System(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] }),paved: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road, Paved] })@@ -333,6 +343,46 @@ export const Interact = Game.System(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) => {+ 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)+ return [+ `${p.cells.length} cell${p.cells.length === 1 ? "" : "s"} · beauty ${p.beauty}`,+ `made of: ${p.parts.map((part) => `${part.label} ${part.value}`).join(", ") || "nothing yet"}`,+ parkText(p),+ p.entrances > 0 ? `ways in from the street: ${p.entrances}${p.entrances > 2 ? " (2 count)" : ""}` : "no way in: lay a walk or a square out to a road for +1.5 (two count)",+ `one furnishing counts for every 2 cells: ${p.cells.filter((c) => c.prop !== "none").length - p.crowded} of ${Math.ceil(p.cells.length / 2)}${p.crowded > 0 ? ` (${p.crowded} too many)` : ""}`,+ ...(missing.length > 0 ? [`nicer with: ${missing.join(", ")}`] : []),+ `upkeep ${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`const hits: Array<HitBox> = [...buildings.map(({ entity, data }) => {@@ -340,16 +390,17 @@ export const Interact = Game.System(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))+ ...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].find((row) => row.entity.id === id)?.data.tile.get()+ const tileOf = (id: number) => [...buildings, ...houses, ...ruins, ...parkRows].find((row) => row.entity.id === id)?.data.tile.get()// ── 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") && inside(cell.x, cell.y) ? cell : null+ ui.dragFrom = (ui.tool === "road" || ui.tool === "home" || ui.tool === "pave" || ui.tool === "ground") && inside(cell.x, cell.y) ? cell : nullcontinue}switch (ui.tool) {@@ -363,6 +414,16 @@ export const Interact = Game.System(ui.dragFrom = nullbreak}+ 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) breakui.edits.push({ type: "building", kind: ui.placing, cell: footprintAt(gesture.at, kinds[ui.placing].size), open: false })@@ -370,13 +431,13 @@ export const Interact = Game.System(}case "bulldoze": {if (gesture.panned) break- const hit = hitAt(hits, gesture.at, gesture.hit)+ 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 = hitAt(hits, gesture.at, gesture.hit)+ ui.selected = pickAt(gesture.at, gesture.hit)if (ui.selected !== null) ui.menu = nullbreak}@@ -388,7 +449,7 @@ export const Interact = Game.System(const preview = emptyPreview()const pointer = ui.pointerconst cell = pointer ? cellAt(pointer) : null- preview.hover = pointer && (ui.tool === "select" || ui.tool === "bulldoze") ? hitAt(hits, pointer, ui.pointerHit) : null+ preview.hover = pointer && (ui.tool === "select" || ui.tool === "bulldoze") ? pickAt(pointer, ui.pointerHit) : nullconst 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" })@@ -410,6 +471,34 @@ export const Interact = Game.System(} else if (free) preview.ghosts.push({ what: "home", cell: c })else preview.plots.push({ ...c, size: 1, look: "blocked" })}+ } 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+ // What the park it joins gives now, if it joins one.+ const before = laid.map((c) => parkOf(c)).find((p) => p !== undefined)+ const cost = grounds[ui.ground].cost+ preview.tooltip = `${grounds[ui.ground].title.toLowerCase()} · ${laid.length} cell${laid.length === 1 ? "" : "s"}, ${costText({ coins: cost.coins * laid.length, materials: Object.fromEntries(Object.entries(cost.materials).map(([g, n]) => [g, (n ?? 0) * laid.length])) })}${after ? ` · the park: ${parkText(after)}${before && before.value !== after.value ? ` (now ${signed(before.value)})` : ""}` : ""} · drag a rectangle`+ 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 ? ` · the park: ${parkText(after)}${before && before.value !== after.value ? ` (now ${signed(before.value)})` : ""}` : ""}${after && after.crowded > 0 ? " · too crowded: lay more ground for it to count" : ""}`+ 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)@@ -420,13 +509,20 @@ export const Interact = Game.System(else preview.plots.push({ ...tile, look: "blocked" })} else if (ui.tool === "bulldoze") {preview.danger = true- if (preview.hover === null && cell && ["road", "tree", "field"].includes(useAt(grid, cell.x, cell.y)))+ 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()}`}if (ui.selected !== null) {const row = buildings.find((b) => b.entity.id === ui.selected)const tile = tileOf(ui.selected)- if (tile) preview.plots.push({ ...tile, look: "picked" })+ 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])}@@ -443,6 +539,7 @@ export const Interact = Game.System(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 ((maybe(data.condition)?.value ?? CONDITION_MAX) < wear.worn) sources.push(landSource("worn", data.tile.get()))return sources@@ -548,6 +645,11 @@ export const Interact = Game.System(preview.tooltip = `${tierHome[h.tier]} · ${h.residents} residents · 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 r = reachOf(kind)@@ -560,9 +662,11 @@ export const Interact = Game.System(const pickedBuilding = ui.selected !== null ? buildings.find((row) => row.entity.id === ui.selected) : undefinedconst pickedHouse = ui.selected !== null ? houses.find((row) => row.entity.id === ui.selected) : undefinedconst 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()) : undefinedif (pickedBuilding) {const { kind, status, problem, lines } = describeBuilding(pickedBuilding)- const pausable = kind.id !== "townhall" && !kind.decor && !pickedBuilding.data.site.present && !pickedBuilding.data.rising.present+ const pausable = kind.id !== "townhall" && !pickedBuilding.data.site.present && !pickedBuilding.data.rising.presentui.panel = {type: "building",id: pickedBuilding.entity.id,@@ -577,6 +681,16 @@ export const Interact = Game.System(} else if (pickedHouse) {const { h, lines } = describeHouse(pickedHouse)ui.panel = { type: "house", id: pickedHouse.entity.id, cell: pickedHouse.data.tile.get(), tier: h.tier, lines }+ } 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 = {@@ -872,7 +986,7 @@ export const DrawOverlay = Game.System(})-/** Roads and water, each redrawn as one layer whenever one is laid or anything is removed. */+/** Roads, water, and parks, each redrawn as one layer whenever one is laid or anything is removed. */export const DrawGround = Game.System("Town/DrawGround",{@@ -881,16 +995,21 @@ export const DrawGround = Game.System(paved: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road, Paved] }),added: Game.Query({ selection: { paved: Game.Query.read(Paved) }, filters: [Game.Query.added(Paved)] }),water: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Water] }),+ parks: ParkRead,+ relaid: Game.Query({ selection: { park: Game.Query.read(Park) }, filters: [Game.Query.changed(Park)] }),laid: Game.Query({ selection: { tile: Game.Query.read(Tile) }, filters: [Game.Query.added(Tile)] })},despawned: { entities: Game.System.readDespawned() },services: { stage: Game.System.service(StageService) }},({ queries, despawned, services }) => {- if (!services.stage.groundDirty && queries.laid.each().length === 0 && queries.added.each().length === 0 && despawned.entities.all().length === 0) return+ const dirty = services.stage.groundDirty+ if (!dirty && queries.laid.each().length === 0 && queries.added.each().length === 0 && queries.relaid.each().length === 0 && despawned.entities.all().length === 0) returnconst cellsOf = (rows: ReadonlyArray<{ readonly data: { readonly tile: { get(): TileLike } } }>) =>new Set(rows.map(({ data }) => key(data.tile.get().x, data.tile.get().y)))- services.stage.setGround(cellsOf(queries.roads.each()), cellsOf(queries.water.each()), cellsOf(queries.paved.each()))+ 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/render3d/input.ts b/src/render3d/input.tsindex cdc70d1..29fcabf 100644--- a/src/render3d/input.ts+++ b/src/render3d/input.ts@@ -46,7 +46,7 @@ export class MapInput {? "pan": this.mode === "rotate"? "rotate"- : ui.tool === "road" || ui.tool === "home"+ : ui.tool === "road" || ui.tool === "home" || ui.tool === "pave" || ui.tool === "ground"? "edit": "pan"this.press = { id: e.pointerId, start: p, last: p, mode, moved: false }@@ -131,7 +131,7 @@ export class MapInput {this.controls = document.createElement("nav")this.controls.className = "camera-controls"this.controls.setAttribute("aria-label", "Map camera")- this.controls.innerHTML = `<button data-mode="pan" aria-pressed="true" title="Drag to pan; road and home tools drag to build">Pan</button><button data-mode="rotate" aria-pressed="false" title="Drag to rotate instead of placing. Right-drag also rotates.">Rotate</button><button data-action="left" aria-label="Rotate map left" title="Rotate left (Q)">↶</button><button data-action="right" aria-label="Rotate map right" title="Rotate right (E)">↷</button><button data-action="out" aria-label="Zoom out">−</button><output aria-label="Camera zoom"></output><button data-action="in" aria-label="Zoom in">+</button><button data-action="reset" aria-label="Reset camera" title="Original angle and centre (Home)">⌂</button>`+ this.controls.innerHTML = `<button data-mode="pan" aria-pressed="true" title="Drag to pan; the road, pave, home, and park ground tools drag to build">Pan</button><button data-mode="rotate" aria-pressed="false" title="Drag to rotate instead of placing. Right-drag also rotates.">Rotate</button><button data-action="left" aria-label="Rotate map left" title="Rotate left (Q)">↶</button><button data-action="right" aria-label="Rotate map right" title="Rotate right (E)">↷</button><button data-action="out" aria-label="Zoom out">−</button><output aria-label="Camera zoom"></output><button data-action="in" aria-label="Zoom in">+</button><button data-action="reset" aria-label="Reset camera" title="Original angle and centre (Home)">⌂</button>`this.controls.querySelectorAll<HTMLButtonElement>("button").forEach((button) =>(button.onclick = () => {diff --git a/src/render3d/models.ts b/src/render3d/models.tsindex 92e5a44..aeaa04e 100644--- a/src/render3d/models.ts+++ b/src/render3d/models.ts@@ -65,8 +65,6 @@ export function constructionAsset(size: number, half: number, height: number, buexport function buildingAsset(id: KindId, build: number, share: number | null, doors: DoorSet, open: number, appearance: Appearance = {}) {const kind = kinds[id],stage = buildStages(build)- // An ornament is laid out at once.- if (kind.decor) return makeBuilding(id)if (build < 0.78) return constructionAsset(kind.size, kind.half, kind.roof === "gable" ? 20 : kind.stories * 32, build, share)const asset = makeBuilding(id, { doors, open, fit: stage.fit, plate: false, motion: false } satisfies BuildingOptions)return build >= 1 ? withAppearance(asset, kind.half * U, kind.roof === "gable" ? 20 : kind.stories * 32, appearance) : assetdiff --git a/src/render3d/scene.ts b/src/render3d/scene.tsindex 0cf1d98..846cae9 100644--- a/src/render3d/scene.ts+++ b/src/render3d/scene.ts@@ -10,6 +10,8 @@ import { kinds } from "../content.ts"import type { Preview, UiValue } from "../ui.ts"import { ModelHandle, ModelPool } from "./pool.ts"import { groundAsset, landAsset, overlayAsset, previewAsset, type OverlayCell } from "./models.ts"+import { parkAsset } from "../asset-lab/town-props.ts"+import type { ParkCell } from "../appeal.ts"export interface SceneNode {readonly group: THREE.Group@@ -40,6 +42,9 @@ export class GameScene {private previewKey = ""private land: BuiltAsset | null = nullprivate ground: BuiltAsset | null = null+ private parks: BuiltAsset | null = null+ private parksKey = ""+ private parkPreview: BuiltAsset | null = nullprivate overlays: BuiltAsset | null = nullprivate roadPreview: BuiltAsset | null = nullprivate ghostHandles: Array<ModelHandle> = []@@ -211,6 +216,13 @@ export class GameScene {this.groundKey = idthis.ground = this.replace(this.ground, groundAsset(roads, water, false, paved))}+ /** The parks, redrawn whenever a cell of one (or a road beside one) changes. */+ setParks(cells: ReadonlyMap<number, ParkCell>, roads: ReadonlySet<number>) {+ const id = [...cells].map(([k, c]) => `${k}:${c.ground}:${c.prop}`).join(",") + "|" + [...roads].join(",")+ if (id === this.parksKey) return+ this.parksKey = id+ this.parks = this.replace(this.parks, parkAsset(cells, roads))+ }/** A map view: each cell (or footprint) washed in a colour, or nothing. */setOverlay(id: string, cells: ReadonlyArray<OverlayCell>) {if (id === this.overlayKey) return@@ -219,11 +231,12 @@ export class GameScene {}setPreview(preview: Preview, time: number) {const beat = preview.plots.some((p) => p.look === "picked" || p.look === "blocked") ? Math.floor(time * 8) : 0- const id = JSON.stringify([preview.plots, preview.ghosts, preview.roads, beat])+ const id = JSON.stringify([preview.plots, preview.ghosts, preview.roads, preview.parks, beat])if (id === this.previewKey) returnthis.previewKey = idthis.overlays = this.replace(this.overlays, previewAsset(preview, time))this.roadPreview = this.replace(this.roadPreview, groundAsset(new Set(preview.roads.map((p) => key(p.x, p.y))), new Set(), true))+ this.parkPreview = this.replace(this.parkPreview, parkAsset(new Map(preview.parks.map((c) => [key(c.x, c.y), c])), new Set(), true))for (const handle of this.ghostHandles) handle.dispose()this.ghostHandles = []for (const ghost of preview.ghosts) {@@ -240,6 +253,7 @@ export class GameScene {this.generation++this.landKey = nullthis.groundDirty = true+ this.parksKey = ""this.previewKey = ""for (const node of [...this.nodes]) node.destroy()this.nodes.clear()@@ -249,6 +263,7 @@ export class GameScene {this.overlayKey = ""this.overlay = this.replace(this.overlay, { id: "empty", title: "", note: "", faces: [], strokes: [] })this.roadPreview = this.replace(this.roadPreview, { id: "empty", title: "", note: "", faces: [], strokes: [] })+ this.parkPreview = this.replace(this.parkPreview, { id: "empty", title: "", note: "", faces: [], strokes: [] })}subscribe(onTick: (tick: { deltaMS: number }) => void) {this.previous = 0@@ -289,7 +304,7 @@ export class GameScene {this.renderer.setAnimationLoop(null)this.observer.disconnect()this.resetPresentation()- for (const model of [this.land, this.ground]) model?.dispose()+ for (const model of [this.land, this.ground, this.parks]) model?.dispose()this.pool.dispose()this.renderer.dispose()}diff --git a/src/render3d/views.ts b/src/render3d/views.tsindex c05b0e2..58164ff 100644--- a/src/render3d/views.ts+++ b/src/render3d/views.ts@@ -139,7 +139,7 @@ export class BuildingView extends WorldView {this.marker.root.visible = look.problem && look.build >= 1 && !signedconst state = structureState(look,this.stage.frost)this.body.effects = build >= 1 ? state : surfaceState()- this.body.effectBounds.set(kind.half * U * 32 * Math.SQRT2,H/Math.cos(Math.PI/6),this.entity%97/97,Number(!kind.decor))+ this.body.effectBounds.set(kind.half * U * 32 * Math.SQRT2,H/Math.cos(Math.PI/6),this.entity%97/97,1)if(!this.effects&&build>=1&&(state.burning||state.fireRisk)){this.effects = new StructureEffects(buildingAsset(this.kindId,1,null,noDoors,0),H)this.group.add(this.effects.group)diff --git a/src/save.ts b/src/save.tsindex 2620d1e..c55eb2d 100644--- a/src/save.ts+++ b/src/save.ts@@ -15,7 +15,7 @@ export const SAVE_FORMAT = "inkline-town/save"* 2: the charter's towns. 3: neighbourhoods and their dangers (desirability, crews, risks, wear, ruins,* winters). Older saves cannot be loaded.*/-export const SAVE_VERSION = 3+export const SAVE_VERSION = 4export type Slot = "manual" | "auto"export const slots: ReadonlyArray<Slot> = ["manual", "auto"]diff --git a/src/schema.ts b/src/schema.tsindex 07796f2..d6f4d19 100644--- a/src/schema.ts+++ b/src/schema.ts@@ -2,7 +2,7 @@* The town's world. Every entity is assembled from small components (see* `archetypes.ts`): a `Tile` on the grid, then whichever roles it has. The* land is `Tree`s, `Rock`s, `Water`, and a farm's `Field`s; the town is- * `Road`s, `House`s, and `Building`s that may hold an `Inventory`, follow a+ * `Road`s, `Park` cells, `House`s, and `Building`s that may hold an `Inventory`, follow a* `Recipe`, gather from the land (`Gatherer`), plant (`Planter`), send* `Carriers`, or offer a `Service`. A building still owed materials is a* `Site`; one going up is `Rising`. Walkers follow a `Route` on an `Errand`@@ -17,7 +17,7 @@ import type { NodeRegistry } from "@typeonce/bevy-ts-render"import type { BuildingView, FieldView, HouseView, RockView, RuinView, TreeView, WalkerView } from "./render3d/views.ts"import type { GameScene } from "./render3d/scene.ts"-import { goodIds, kindIds, landIds, serviceIds, sizeIds, type Amounts } from "./content.ts"+import { goodIds, groundIds, kindIds, landIds, propIds, serviceIds, sizeIds, type Amounts } from "./content.ts"import type { UiValue } from "./ui.ts"export const Root = Schema.defineRoot("Town")@@ -45,6 +45,8 @@ export const Tile = Descriptor.ConstructedComponent(Decode.struct({ x: integer,export const Road = Descriptor.Tag("Town/Road")/** A road paved with stone: a little nicer to live on (see `appeal.ts`). */export const Paved = Descriptor.Tag("Town/Paved")+/** A cell of park: its ground, and what stands on it (see `parks` in content). */+export const Park = Descriptor.ConstructedComponent(Decode.struct({ ground: Decode.literal(...groundIds), prop: Decode.literal("none", ...propIds) }))("Town/Park")/** What is left of a home or building that burned, fell down, or was left derelict, until it is cleared. */export const Ruin = Descriptor.ConstructedComponent(Decode.struct({ cause: Decode.literal("burnt", "collapsed", "derelict") }))("Town/Ruin")/** Materials still owed before it can go up, out of `total`. */@@ -305,7 +307,7 @@ export const Fires = Descriptor.ConstructedResource(Decode.struct({/** What stands on each cell, rebuilt every step from the tiles (see `grid.ts`). *//** `void`: off the land, past the coast. */-export type Use = "empty" | "road" | "house" | "building" | "tree" | "rock" | "water" | "field" | "ruin" | "void"+export type Use = "empty" | "road" | "park" | "house" | "building" | "tree" | "rock" | "water" | "field" | "ruin" | "void"export interface GridValue {/** Entity id on each cell (by `key`), or 0. */readonly owner: ReadonlyArray<number>@@ -336,7 +338,7 @@ export const RuinNodes = Descriptor.Service<NodeRegistry.NodeRegistry<RuinView>>export const Game = Schema.bind(Schema.fragment({components: {- Tile, Road, Paved, Ruin, Site, Rising, Tree, Rock, Water, Field, House, Risk, Condition, Burning, Sick, Building, TownHall, Status,+ Tile, Road, Paved, Park, Ruin, Site, Rising, Tree, Rock, Water, Field, House, Risk, Condition, Burning, Sick, Building, TownHall, Status,Paused, Staff, Inventory, Storage, Recipe, Gatherer, Planter, Carriers, Service, Figure, Route, Errand, Rescue, Roam},resources: {diff --git a/src/sim/edits.ts b/src/sim/edits.tsindex 3bb93db..97a91c4 100644--- a/src/sim/edits.ts+++ b/src/sim/edits.ts@@ -1,28 +1,28 @@/*** The player's edits, applied at the start of a step: building, laying- * roads and homes, bulldozing, pausing, the town's policy, answering the+ * roads and homes, laying out parks, bulldozing, pausing, the town's policy, answering the* crown, and founding a new town. Costs are checked against the treasury* and the town's stock and paid up front in coins; the materials are* carried to the site afterwards. Once the term has ended, only a new town* (or carrying on after completing this one) is taken.*/import {- buildingDraft, houseDraft, houseStart, roadDraft, rockDraft, rolesOf, startOf, treeDraft, waterDraft+ buildingDraft, houseDraft, houseStart, parkDraft, roadDraft, rockDraft, rolesOf, startOf, treeDraft, waterDraft} from "../archetypes.ts"import * as Random from "@typeonce/bevy-ts-math/Random"-import { amounts, goodIds, goods, home, kinds, lands, PAVE_COST, ROAD_COST, sizes, trade, type Amounts, type Kind } from "../content.ts"+import { amounts, goodIds, goods, grounds, home, kinds, lands, PAVE_COST, props, ROAD_COST, sizes, trade, type Amounts, type Kind, type ParkPiece } from "../content.ts"import { canPlace, cellsOf, GridBuilder, ownerAt, useAt } from "../grid.ts"import { inside } from "../iso.ts"import { generate } from "../mapgen.ts"import {- Appeal, Building, Census, Charter, Chronicle, Crown, Fate, Fires, Game, History, Inventory, Land, Ledger, Market, Mood, Pantry, Paved, Paused,- Policy, Rising, Rng, Status, Stock, Storage, Time, TownHall, Treasury, Ui+ Appeal, Building, Census, Charter, Chronicle, Crown, Fate, Fires, Game, History, Inventory, Land, Ledger, Market, Mood, Pantry, Park, Paved, Paused,+ Policy, Rng, Status, Stock, Storage, Time, TownHall, Treasury, Ui} from "../schema.ts"import { elapsed, rollWinters, TileRead, useOf, write } from "./shared.ts"import { crownGap, foundedFate } from "./term.ts"-export const unlocked = (kind: Kind, census: { readonly settlers: number; readonly citizens: number }) =>+export const unlocked = (kind: Pick<Kind, "unlock"> | ParkPiece, census: { readonly settlers: number; readonly citizens: number }) =>census.settlers + census.citizens >= kind.unlock.residents && census.citizens >= kind.unlock.citizensexport const ApplyEdits = Game.System(@@ -31,6 +31,7 @@ export const ApplyEdits = Game.System(queries: {tiles: TileRead,paved: Game.Query({ selection: { paved: Game.Query.read(Paved) } }),+ parks: Game.Query({ selection: { park: Game.Query.write(Park) } }),halls: Game.Query({ selection: { hall: Game.Query.read(TownHall) } }),buildings: Game.Query({ selection: { building: Game.Query.read(Building), paused: Game.Query.optional(Paused) } }),stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage] })@@ -103,7 +104,7 @@ export const ApplyEdits = Game.System(if (tree !== undefined) commands.despawn(tree)}}- const spawn = (draft: Parameters<typeof commands.spawn>[0], tile: { x: number; y: number; size: number }, use: "building" | "house" | "road") => {+ const spawn = (draft: Parameters<typeof commands.spawn>[0], tile: { x: number; y: number; size: number }, use: "building" | "house" | "road" | "park") => {fell(tile)const id = commands.spawn(draft)grid.claim(tile, id, use)@@ -136,11 +137,7 @@ export const ApplyEdits = Game.System(}pay(kind.cost)const id = spawn(buildingDraft(kind, edit.cell), tile, "building")- if (kind.decor) {- // An ornament needs no road: its materials come out of storage at once, and it goes straight up.- take(kind.cost.materials)- commands.insert(id, Game.Command.entry(Rising, { ticks: 0 }), ...rolesOf(kind))- } else commands.insert(id, startOf(kind), ...rolesOf(kind))+ commands.insert(id, startOf(kind), ...rolesOf(kind))if (edit.open) ui.selected = idbreak}@@ -194,6 +191,51 @@ export const ApplyEdits = Game.System(if (short) ui.toast(short)break}+ case "ground": {+ // Park needs no road: it is laid at once, its materials straight out of storage.+ const piece = grounds[edit.ground]+ const parks = new Map(queries.parks.each().map((row) => [row.entity.id as number, row] as const))+ let short: string | null = null+ const spent: Record<string, number> = {}+ for (const cell of edit.cells) {+ const tile = { ...cell, size: 1 }+ const relay = useAt(grid.value(), cell.x, cell.y) === "park" ? parks.get(ownerAt(grid.value(), cell.x, cell.y)) : undefined+ if (relay ? relay.data.park.get().ground === edit.ground : !canPlace(grid.value(), tile)) continue+ short = afford(piece.cost)+ if (short) break+ pay(piece.cost)+ for (const [g, n] of Object.entries(piece.cost.materials)) spent[g] = (spent[g] ?? 0) + (n ?? 0)+ if (relay) relay.data.park.set({ ...relay.data.park.get(), ground: edit.ground })+ else spawn(parkDraft(cell, edit.ground), tile, "park")+ }+ take(spent)+ if (short) ui.toast(short)+ break+ }+ case "prop": {+ const piece = props[edit.prop]+ if (!unlocked(piece, resources.census.get())) {+ ui.toast(`${piece.title} needs a bigger town`)+ break+ }+ const row = useAt(grid.value(), edit.cell.x, edit.cell.y) === "park"+ ? queries.parks.each().find((r) => r.entity.id === ownerAt(grid.value(), edit.cell.x, edit.cell.y))+ : undefined+ if (!row) {+ ui.toast("Lay park ground first")+ break+ }+ if (row.data.park.get().prop === edit.prop) break+ const short = afford(piece.cost)+ if (short) {+ ui.toast(short)+ break+ }+ pay(piece.cost)+ take(piece.cost.materials)+ row.data.park.set({ ...row.data.park.get(), prop: edit.prop })+ break+ }case "remove": {if (!inside(edit.cell.x, edit.cell.y)) breakconst use = useAt(grid.value(), edit.cell.x, edit.cell.y)@@ -203,6 +245,12 @@ export const ApplyEdits = Game.System(ui.toast("The town hall stays")break}+ // A park's furnishing goes before its ground.+ const furnished = use === "park" ? queries.parks.each().find((r) => r.entity.id === owner && r.data.park.get().prop !== "none") : undefined+ if (furnished) {+ furnished.data.park.set({ ...furnished.data.park.get(), prop: "none" })+ break+ }// A building's walkers and a farm's fields are its children, and go with it.commands.despawn(owner)entities.delete(owner)diff --git a/src/sim/hazards.ts b/src/sim/hazards.tsindex 3ca47b0..602293a 100644--- a/src/sim/hazards.ts+++ b/src/sim/hazards.ts@@ -10,14 +10,14 @@*/import * as Random from "@typeonce/bevy-ts-math/Random"-import { appealGrid, appealAt, buildingSource, landSource, type AppealSource } from "../appeal.ts"+import { appealGrid, appealAt, buildingSource, landSource, parkSources, type AppealSource } from "../appeal.ts"import { ruinDraft } from "../archetypes.ts"import { appeal, condition as wear, goodIds, goods, home, kinds, risk, RISK_MAX, winters, type GoodId } from "../content.ts"import { doors, nearest, pathTo, reach, useAt } from "../grid.ts"import { counted, placeName, type Landmark } from "../places.ts"import type { Point } from "../iso.ts"import {- Appeal, Building, Burning, Charter, Chronicle, Condition, Figure, Fires, Game, Grid, House, Inventory, Mood, Paved, Rescue, Rising, Risk, Rng,+ Appeal, Building, Burning, Charter, Chronicle, Condition, Figure, Fires, Game, Grid, House, Inventory, Mood, Park, Paved, Rescue, Rising, Risk, Rng,Road, Route, Ruin, Service, Sick, Site, Staff, Storage, Tile, Time, Tree, Treasury, WalkerOf, Water, maybe} from "../schema.ts"import { elapsed, seasonAt, write } from "./shared.ts"@@ -33,6 +33,8 @@ export const Appraise = Game.System(trees: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Tree] }),water: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Water] }),paved: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road, Paved] }),+ parks: Game.Query({ selection: { tile: Game.Query.read(Tile), park: Game.Query.read(Park) } }),+ roads: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Road] }),ruins: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Ruin] }),homes: Game.Query({ selection: { tile: Game.Query.read(Tile), condition: Game.Query.read(Condition) }, with: [House], without: [Site, Rising] })},@@ -48,6 +50,8 @@ export const Appraise = Game.System(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()))+ const roads = new Set(queries.roads.each().map(({ data }) => `${data.tile.get().x},${data.tile.get().y}`))+ sources.push(...parkSources(queries.parks.each().map(({ data }) => ({ ...data.tile.get(), ...data.park.get() })), (x, y) => roads.has(`${x},${y}`)))for (const { data } of queries.ruins.each()) sources.push(landSource("ruin", data.tile.get()))for (const { data } of queries.homes.each()) if (data.condition.get().value < wear.worn) sources.push(landSource("worn", data.tile.get()))resources.appeal.set({ cells: appealGrid(sources) })diff --git a/src/sim/headless.ts b/src/sim/headless.tsindex 5b8999e..c246613 100644--- a/src/sim/headless.ts+++ b/src/sim/headless.ts@@ -21,7 +21,7 @@ export interface Snapshot {export const headless = (charter: CharterValue, options: { readonly toast?: (message: string) => void } = {}) => {const ui: UiValue = {- tool: "select", placing: null, menu: null, pointer: null, dragFrom: null, selected: null, gestures: [],+ tool: "select", placing: null, ground: "lawn", prop: "lamp", menu: null, pointer: null, dragFrom: null, selected: null, gestures: [],edits: [{ type: "newTown", charter }],preview: emptyPreview(), hits: [], panel: null, centres: new Map(), stats: null, speed: 1, founding: false,view: "none", overlay: { key: "", cells: [] }, legend: null,diff --git a/src/sim/shared.ts b/src/sim/shared.tsindex ce1cf2e..5b7a868 100644--- a/src/sim/shared.ts+++ b/src/sim/shared.ts@@ -1,13 +1,14 @@/** Queries and small helpers the simulation's systems share. */import { ticks, winters, YEARS_PER_TERM, type WinterId } from "../content.ts"import { doors, type TileLike, type Use } from "../grid.ts"-import { Field, Game, House, Road, Rock, Ruin, Tile, Tree, Water, type GridValue } from "../schema.ts"+import { Field, Game, House, Park, Road, Rock, Ruin, Tile, Tree, Water, type GridValue } from "../schema.ts"/** Every tile, with enough to tell what it is. */export const TileRead = Game.Query({selection: {tile: Game.Query.read(Tile),road: Game.Query.optional(Road),+ park: Game.Query.optional(Park),house: Game.Query.optional(House),tree: Game.Query.optional(Tree),rock: Game.Query.optional(Rock),@@ -19,6 +20,7 @@ export const TileRead = Game.Query({export const useOf = (data: {readonly road: { readonly present: boolean }+ readonly park: { readonly present: boolean }readonly house: { readonly present: boolean }readonly tree: { readonly present: boolean }readonly rock: { readonly present: boolean }@@ -27,6 +29,7 @@ export const useOf = (data: {readonly ruin: { readonly present: boolean }}): Use =>data.road.present ? "road"+ : data.park.present ? "park": data.house.present ? "house": data.tree.present ? "tree": data.rock.present ? "rock"diff --git a/src/sim/town.ts b/src/sim/town.tsindex 2bb66ea..8e972d3 100644--- a/src/sim/town.ts+++ b/src/sim/town.ts@@ -1,15 +1,15 @@/*** The town: homes grow, level up, or empty depending on what reaches them;* taxes are collected from homes connected to the town hall and upkeep paid- * for every standing building; and the census counts it all.+ * for every standing building and park; and the census counts it all.*/import { appealAt } from "../appeal.ts"import {- admin, goodIds, goods, home, kinds, LEDGER_TICKS, market, PAUSED_UPKEEP, risk, TRADE_LOAD, type GoodId, type Need, type Tier+ admin, goodIds, goods, grounds, home, kinds, LEDGER_TICKS, market, PAUSED_UPKEEP, props, risk, TRADE_LOAD, type GoodId, type Need, type Tier} from "../content.ts"import { doors, key, reach } from "../grid.ts"import {- Appeal, Building, Burning, Census, Charter, Game, Grid, House, Inventory, Ledger, Market, Mood, Paused, Policy, Rising, Risk, Sick, Site,+ Appeal, Building, Burning, Census, Charter, Game, Grid, House, Inventory, Ledger, Market, Mood, Park, Paused, Policy, Rising, Risk, Sick, Site,Staff, Storage, Tile, Time, TownHall, Treasury, maybe} from "../schema.ts"import { connected, elapsed, seasonAt } from "./shared.ts"@@ -159,7 +159,8 @@ export const Collect = Game.System(homes: Game.Query({ selection: { tile: Game.Query.read(Tile), house: Game.Query.read(House) }, without: [Site, Rising] }),buildings: Game.Query({ selection: { building: Game.Query.read(Building), paused: Game.Query.optional(Paused) }, without: [Site] }),halls: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [TownHall] }),- stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage], without: [Site, Rising] })+ stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage], without: [Site, Rising] }),+ parks: Game.Query({ selection: { park: Game.Query.read(Park) } })},resources: {time: Game.System.readResource(Time),@@ -186,6 +187,10 @@ export const Collect = Game.System(}let upkeep = 0for (const { data } of queries.buildings.each()) upkeep += kinds[data.building.get().kind].upkeep * (data.paused.present ? PAUSED_UPKEEP : 1)+ for (const { data } of queries.parks.each()) {+ const p = data.park.get()+ upkeep += grounds[p.ground].upkeep + (p.prop === "none" ? 0 : props[p.prop].upkeep)+ }const admin = adminOf(homes)// Trade.diff --git a/src/ui.ts b/src/ui.tsindex d94294a..9cc8774 100644--- a/src/ui.ts+++ b/src/ui.ts@@ -4,12 +4,12 @@* 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.*/-import type { Amounts, CharterValue, GoodId, KindId, Tier, WinterId } from "./content.ts"+import type { Amounts, CharterValue, GoodId, GroundId, KindId, PropId, Tier, WinterId } from "./content.ts"import type { Point } from "./iso.ts"import type { Status } from "./schema.ts"import type { OverlayCell } from "./render3d/models.ts"-export type Tool = "select" | "road" | "pave" | "home" | "bulldoze" | "place"+export type Tool = "select" | "road" | "pave" | "home" | "bulldoze" | "place" | "ground" | "prop"/** What the map shows over the town: nothing, or one of its views, cell by cell. */export const viewIds = ["none", "appeal", "workers", "fire", "health", "order", "condition"] as const@@ -23,7 +23,11 @@ export type Edit =| { readonly type: "roads"; readonly cells: ReadonlyArray<Point> }/** Paves the road on each cell (coins, and stone from storage). */| { readonly type: "pave"; readonly cells: ReadonlyArray<Point> }- /** Removes whatever stands on a cell (not rocks, water, or the town hall). */+ /** Lays park ground on each empty cell (or relays a park cell's ground). */+ | { readonly type: "ground"; readonly ground: GroundId; readonly cells: ReadonlyArray<Point> }+ /** Sets a furnishing on a cell of park. */+ | { readonly type: "prop"; readonly prop: PropId; readonly cell: Point }+ /** Removes whatever stands on a cell (not rocks, water, or the town hall); on a park, its furnishing first. */| { readonly type: "remove"; readonly cell: Point }/** Sets a tier's tax rate, in percent of the usual. */| { readonly type: "tax"; readonly tier: "settlers" | "citizens"; readonly rate: number }@@ -57,6 +61,8 @@ export interface Preview {ghosts: Array<{ readonly what: KindId | "home"; readonly cell: Point }>/** Road cells about to be laid. */roads: Array<Point>+ /** Park cells about to be laid or furnished, as they will look. */+ parks: Array<{ readonly x: number; readonly y: number; readonly ground: GroundId; readonly prop: PropId | "none" }>/** The entity under the pointer. */hover: number | null/** Bulldozing: the hovered thing is tinted. */@@ -64,7 +70,7 @@ export interface Preview {tooltip: string | null}-export const emptyPreview = (): Preview => ({ plots: [], ghosts: [], roads: [], hover: null, danger: false, tooltip: null })+export const emptyPreview = (): Preview => ({ plots: [], ghosts: [], roads: [], parks: [], hover: null, danger: false, tooltip: null })/** The side panel: the build menu, the town's numbers and taxes, a building, or a home. */export type Panel =@@ -90,6 +96,16 @@ export type Panel =readonly tier: Tierreadonly lines: ReadonlyArray<string>}+ | {+ readonly type: "park"+ readonly id: number+ readonly cell: Point+ /** Cells, and the desirability it gives out to how far. */+ readonly cells: number+ readonly value: number+ readonly reach: number+ readonly lines: ReadonlyArray<string>+ }| {readonly type: "ruin"readonly id: number@@ -211,13 +227,16 @@ export interface UiValue {tool: Tool/** The kind being placed with the `place` tool. */placing: KindId | null+ /** The ground laid with the `ground` tool, and the furnishing set with the `prop` tool. */+ ground: GroundId+ prop: PropId/** Which side panel the toolbar opened, when nothing is selected. */menu: "build" | "town" | null/** The pointer on the grid, or `null` off the canvas. */pointer: Point | null/** Camera-ray entity hit. Undefined allows grid-only headless interaction. */pointerHit?: number | null- /** Where a road or a row of homes being dragged started. */+ /** Where a road, a row of homes, or a patch of park being dragged started. */dragFrom: Point | nullselected: number | nullgestures: Array<Gesture>diff --git a/test/model.test.ts b/test/model.test.tsindex 11cf57b..2bcd2d5 100644--- a/test/model.test.ts+++ b/test/model.test.ts@@ -15,7 +15,7 @@ import { test } from "node:test"import { Arbitrary, Data, Effect, Schema } from "effect"import {- CONDITION_MAX, crown, goodIds, home, kindOrder, kinds, landIds, market, RESERVES, RISK_MAX, TAX_STEPS, type CharterValue+ CONDITION_MAX, crown, goodIds, groundIds, home, kindOrder, kinds, landIds, market, propIds, RESERVES, RISK_MAX, TAX_STEPS, type CharterValue} from "../src/content.ts"import { canPlace, cellsOf, DIRS, entrances, GridBuilder, isRoad, key, type Use } from "../src/grid.ts"import { GRID, inside, type Point } from "../src/iso.ts"@@ -49,6 +49,9 @@ const Command = Schema.Union([Schema.TaggedStruct("Road", { pick: Pick, toward: Direction, length: between(1, 10) }),// Paving a stretch of road (or whatever lies along it).Schema.TaggedStruct("Pave", { pick: Pick, toward: Direction, length: between(1, 8) }),+ // A patch of park ground from a free cell, and a furnishing anywhere at all (on park or not).+ Schema.TaggedStruct("Park", { pick: Pick, ground: Schema.Literals(groundIds), width: between(1, 4), depth: between(1, 4) }),+ Schema.TaggedStruct("Furnish", { prop: Schema.Literals(propIds), x: Cell, y: Cell }),// A row of homes from a free cell beside a road.Schema.TaggedStruct("Homes", { pick: Pick, toward: Direction, length: between(1, 6) }),// A building on a spot with room and a road at one of its doors.@@ -56,7 +59,7 @@ const Command = Schema.Union([// Anywhere at all, valid or not.Schema.TaggedStruct("BuildAnywhere", { kind: Schema.Literals(kindOrder), x: Cell, y: Cell }),// One of the buildings, homes, or roads that stand.- Schema.TaggedStruct("Remove", { pick: Pick, what: Schema.Literals(["building", "house", "road"]) }),+ Schema.TaggedStruct("Remove", { pick: Pick, what: Schema.Literals(["building", "house", "road", "park"]) }),Schema.TaggedStruct("Tax", { tier: Schema.Literals(["settlers", "citizens"]), rate: Schema.Literals(TAX_STEPS) }),Schema.TaggedStruct("Trade", { good: Schema.Literals(goodIds), mode: Schema.Literals(["sell", "buy", "none"]) }),Schema.TaggedStruct("Reserve", { amount: Schema.Literals(RESERVES) }),@@ -76,7 +79,7 @@ type Command = typeof Command.Type* policy levers now and then; running the term out rarely.*/const weights: Readonly<Record<Command["_tag"], number>> = {- Build: 20, Homes: 15, Road: 12, Pave: 3, Season: 10, Wait: 8, Trade: 5, Tax: 4, Remove: 4, Pause: 4, Deliver: 4, SaveAndLoad: 3,+ Build: 20, Homes: 15, Road: 12, Pave: 3, Park: 4, Furnish: 4, Season: 10, Wait: 8, Trade: 5, Tax: 4, Remove: 4, Pause: 4, Deliver: 4, SaveAndLoad: 3,Windfall: 3, Reserve: 2, BuildAnywhere: 2, Govern: 2, ToTheEnd: 1}const table = Object.entries(weights).flatMap(([tag, n]) => Array.from({ length: n }, () => tag as Command["_tag"]))@@ -103,14 +106,14 @@ const line = (from: Point, length: number, toward: keyof typeof steps) =>/** The town as the commands see it: what stands where, and the places each could go. */const look = (s: Snapshot) => {const builder = new GridBuilder(s.resources["Town/Land"].mask)- const standing: Array<{ id: number; what: "building" | "house" | "road"; tile: Point & { size: number } }> = []+ const standing: Array<{ id: number; what: "building" | "house" | "road" | "park"; tile: Point & { size: number } }> = []for (const e of s.entities) {const tile = e.components["Town/Tile"]if (!tile) continueconst c = e.components- const use: Use = c["Town/Road"] ? "road" : c["Town/House"] ? "house" : c["Town/Tree"] ? "tree" : c["Town/Rock"] ? "rock" : c["Town/Water"] ? "water" : c["Town/Field"] ? "field" : c["Town/Ruin"] ? "ruin" : "building"+ const use: Use = c["Town/Road"] ? "road" : c["Town/Park"] ? "park" : c["Town/House"] ? "house" : c["Town/Tree"] ? "tree" : c["Town/Rock"] ? "rock" : c["Town/Water"] ? "water" : c["Town/Field"] ? "field" : c["Town/Ruin"] ? "ruin" : "building"builder.claim(tile, e.id, use)- if (use === "building" || use === "house" || use === "road") standing.push({ id: e.id, what: use, tile })+ if (use === "building" || use === "house" || use === "road" || use === "park") standing.push({ id: e.id, what: use, tile })// A ruin is cleared like a building.if (use === "ruin") standing.push({ id: e.id, what: "building", tile })}@@ -156,6 +159,16 @@ const apply = (town: Headless, command: Command): string | null => {if (from) edit({ type: "pave", cells: line(from, command.length, command.toward) })break}+ case "Park": {+ const from = pick(look(town.snapshot()).free(), command.pick)+ const cells: Array<Point> = []+ if (from) for (let dy = 0; dy < command.depth; dy++) for (let dx = 0; dx < command.width; dx++) if (inside(from.x + dx, from.y + dy)) cells.push({ x: from.x + dx, y: from.y + dy })+ if (from) edit({ type: "ground", ground: command.ground, cells })+ break+ }+ case "Furnish":+ edit({ type: "prop", prop: command.prop, cell: { x: command.x, y: command.y } })+ breakcase "Homes": {const from = pick(look(town.snapshot()).free(), command.pick)if (from) edit({ type: "homes", cells: line(from, command.length, command.toward) })@@ -301,7 +314,7 @@ const broken = (s: Snapshot, before: Memory | null, last: Command): Array<stringif (kind && kinds[kind].crew === "settlers" && staff.apprentices > 0) fail(`${kind} ${e.id} has apprentices`)assigned += staff.assigned}- // Risks and wear stay within their bounds; ruins and decorations neither burn nor wear.+ // Risks and wear stay within their bounds; ruins and parks neither burn nor wear.for (const e of s.entities) {const r = e.components["Town/Risk"]if (r) for (const k of ["fire", "health", "order"] as const) if (r[k] < 0 || r[k] > RISK_MAX) fail(`entity ${e.id} has ${k} risk ${r[k]}`)@@ -309,6 +322,8 @@ const broken = (s: Snapshot, before: Memory | null, last: Command): Array<stringif (c && (c.value < 0 || c.value > CONDITION_MAX)) fail(`entity ${e.id} is in condition ${c.value}`)if (e.components["Town/Sick"] && !e.components["Town/House"]) fail(`entity ${e.id} is sick but no home`)if (e.components["Town/Ruin"] && (e.components["Town/House"] || e.components["Town/Building"])) fail(`ruin ${e.id} still stands`)+ // A cell of park is only park: nothing else stands on it, and nothing burns or wears there.+ if (e.components["Town/Park"] && (e.components["Town/Road"] || e.components["Town/House"] || e.components["Town/Building"] || e.components["Town/Risk"])) fail(`park ${e.id} is something else too`)}const cells = r["Town/Appeal"].cells as Array<number>if (cells.length !== 0 && cells.length !== GRID * GRID) fail(`desirability for ${cells.length} cells`)