Skip to content

A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D

15.4 KB
Raw Blame
import { amounts, type KindId } from "../../src/game/content/index.ts"
import type { Rules } from "../../src/game/rules/config.ts"
import { mealRate, refreshLevel } from "../../src/game/rules/households.ts"
import { parkValue, parkUpkeep } from "../../src/game/world/appeal.ts"
import { recipeCapacity } from "./model/throughput.ts"
import { analyze } from "./model/analyze.ts"
import { searchDistricts } from "./model/search.ts"
import { district } from "./scenario.ts"
import { citizensDistrict, citizenPark } from "./catalog.ts"
import { provenance } from "./provenance.ts"
import type { Scenario } from "./types.ts"
import type { Verification } from "./verify/checks.ts"
import type { verifyBuilds } from "./verify/builds.ts"

export const makeReport = (rules: Rules, verification: ReadonlyArray<Verification>, construction: ReturnType<typeof verifyBuilds>, saved?: Scenario) => {
  const started = performance.now(), industrial = citizensDistrict(rules, false), zoned = citizensDistrict(rules, true)
  const scenarios = [industrial, zoned, district("straight-faith", Array(10).fill(1), ["chapel"], false, rules), district("branched-faith", Array(10).fill(1), ["chapel"], true, rules), ...(saved ? [saved] : [])]
  const analyses = scenarios.map((scenario) => analyze({ rules, scenario }))
  const chain: KindId[] = ["farm", "mill", "bakery", "sheep", "weaver", "chapel"]
  const materials = { ...amounts({}) }
  for (const kind of chain) for (const [g, n] of Object.entries(rules.kinds[kind].cost.materials)) materials[g as keyof typeof materials] += n!
  const workingTools = chain.filter((k) => rules.kinds[k].wear).length
  const capacity = (["fishery", "farm", "mill", "bakery", "sheep", "weaver", "sawmill"] as const).map((kind) => ({ kind,
    staffed: recipeCapacity(rules.kinds[kind], { assigned: rules.kinds[kind].workers, apprentices: 0, nearby: 100 }, 1, rules.conditionMax, null, rules).outputPerMinute,
    apprentices: rules.kinds[kind].crew === "citizens" ? recipeCapacity(rules.kinds[kind], { assigned: rules.kinds[kind].workers, apprentices: rules.kinds[kind].workers, nearby: 0 }, 1, rules.conditionMax, null, rules).outputPerMinute : null,
    apprenticesWithoutTools: rules.kinds[kind].crew === "citizens" ? recipeCapacity(rules.kinds[kind], { assigned: rules.kinds[kind].workers, apprentices: rules.kinds[kind].workers, nearby: 0 }, 0, rules.conditionMax, null, rules).outputPerMinute : null }))
  const winter = (["mild", "normal", "hard"] as const).map((severity) => {
    const k = rules.kinds.fishery, perMinute = recipeCapacity(k, { assigned: k.workers, apprentices: 0, nearby: 100 }, 1, rules.conditionMax, severity, rules).outputPerMinute
    const minimum = mealRate(true) * 60 / (rules.home.lasts.food * rules.stepSeconds)
    const frequent = mealRate(true) * 60 / ((rules.home.lasts.food - refreshLevel("food", rules)) * rules.stepSeconds)
    return { severity, durationMinutesIn60MinuteTerm: 60 / rules.yearsPerTerm * rules.winters[severity].share, fishPerMinute: perMinute, noWasteHomesPerFishery: perMinute / minimum, frequentRefreshHomesPerFishery: perMinute / frequent }
  })
  const parkCells = citizenPark(), amenity = { value: parkValue(parkCells, undefined, rules).value, reach: parkValue(parkCells, undefined, rules).reach,
    coins: parkCells.reduce((n, p) => n + rules.grounds[p.ground].cost.coins + (p.prop === "none" ? 0 : rules.props[p.prop].cost.coins), 0),
    upkeepPerMinute: parkCells.reduce((n, p) => n + parkUpkeep(p, rules), 0),
    layout: "Three adjacent flower cells with one fountain and one lamp; ground before furnishings" }
  const configurations = searchDistricts(rules, 8)
  return { provenance: provenance(rules, [...scenarios, construction.final]), generatedAt: new Date().toISOString(),
    analysisElapsedMs: performance.now() - started, capacity, winter, amenity,
    firstCitizenChain: { coins: chain.reduce((n, k) => n + rules.kinds[k].cost.coins, 0), upkeepPerMinute: chain.reduce((n, k) => n + rules.kinds[k].upkeep, 0), materials,
      workingTools, totalToolsIncludingConstruction: materials.tools + workingTools, fairStartingTools: rules.lands.fair.stock.tools,
      scope: "One of each chain building; excludes homes, roads, market, parks, raw-material industry and risk services" },
    analyses, verification, construction: { ...construction, final: undefined },
    configurations: { evaluated: configurations.length, affordableAtFoundation: configurations.filter((c) => c.affordableAtFoundation).length, cheapest: configurations.slice(0, 5),
      scope: "Fixed-layout resource relaxation; affordability includes installed working tools but excludes initial homes, roads and services" },
    limits: ["Exact functions and planned tour coverage are separated from steady-state ceilings and coarse forecasts.", "The construction fixture establishes first citizens on authored flat land, not victory on every generated seed.", "The forecast's revisit gaps, shelf allocation, field placement and equipment distribution are approximations. Calibration errors are reported, not hidden.", "Wild forest regeneration is bounded in steady-state analysis and excluded from the transient finite-tree forecast. Maintenance and disaster constraints are analyzed; stochastic disasters and repairs are verified in the real game, not reproduced as an exact joint distribution."] }
}
export type Report = ReturnType<typeof makeReport>
const n = (v: number | null) => v === null ? "n/a" : Number(v.toFixed(2)).toString()
export const markdownReport = (r: Report) => {
  const a = r.construction.actual.at(-1)!, p = r.construction.prediction.rows.at(-1)!
  const saved = r.analyses.find((a) => a.name === "pr3-bot-minute-30")
  return `# Balance model results\n\nGenerated from PR #3 at ${r.provenance.referenceSha}. Current shipped parameters, with no report-time overrides. Rules SHA-256: ${r.provenance.rulesSha256}.\n\n## First citizens, with the current rules\n\nAn authored starting district pays for its roads and homes, then uses ordinary construction edits and the UI-supported tool reserve of 10. The real game first reaches citizens at ${r.construction.firstCitizenSecond ?? "never"} seconds; the coarse model estimates ${r.construction.prediction.firstCitizenSecond ?? "never"}. At ten minutes the game has ${a.citizens} citizens, ${a.residents} residents and ${a.coins} coins. The forecast has ${p.citizens} citizens, ${p.residents} residents and ${p.coins} coins. This is a progression fixture, not a generated-map victory claim.\n\n## Production capacity\n\nOutputs per minute with full crews, sufficient inputs, output room and maintained condition. Apprentice rows deliberately include the actual tick alignment. These are workshop ceilings, not delivered food.\n\n| Building | Own crew + tool | Apprentices + tool | Apprentices, no tool |\n|---|---:|---:|---:|\n${r.capacity.map((c) => `| ${c.kind} | ${n(c.staffed)} | ${n(c.apprentices)} | ${n(c.apprenticesWithoutTools)} |`).join("\n")}\n\n## Useful constraints\n\n- The first citizen chain alone costs ${r.firstCitizenChain.coins} coins and ${r.firstCitizenChain.materials.tools} construction tools. Its ${r.firstCitizenChain.workingTools} wearing workshops also need working tools. Total ${r.firstCitizenChain.totalToolsIncludingConstruction}, versus ${r.firstCitizenChain.fairStartingTools} at a fair start. Raw industry adds more tool demand.\n- The verified park uses three adjacent flower cells, one fountain and one lamp: ${r.amenity.coins} coins, ${n(r.amenity.upkeepPerMinute)}/min upkeep, +${r.amenity.value} desirability at the nearest cells, reach ${r.amenity.reach}. Its effects combine with industry and chapel effects; nearby raw industry remains a liability. Place furnishings after the ground exists.\n- Cloth reaches existing citizens and settlers on eligible streets. Eligible settlers request bread independently of their food meter; other settlers prefer fish and use bread as a fallback.\n- Skilled jobs receive native crews first. Surplus citizens can fill rough jobs at full speed, and settlers can fill skilled jobs at apprentice pace. The road commute still constrains both.\n- Build mills/bakeries before farms can plant on their future plots. A previous ordering failed with the real game's “No room there”; the revised verified schedule has ${r.construction.messages.length} rejected-action messages.\n- An unmaintained building loses half speed after about 33 minutes. After it crosses the repair threshold there are ${r.analyses[0]!.repair.graceBeforeHalfSpeedSeconds} seconds before half speed.\n${saved ? `- The captured sensible bot's minute-30 town has ${saved.household.length} completed homes. Its pooled cloth capacity is ${n(saved.availableAfterWorkshops.cloth)}/min against ${n(saved.needBounds.cloth.min)}..${n(saved.needBounds.cloth.frequent)}/min to supply eligible homes. ${saved.household.filter((h) => h.potentialTier >= 2).length} homes satisfy the desirability gate even if all citizen needs were supplied. Even granting burghers wherever desirability permits, citizen housing is capped at ${saved.citizenGoal.housingCeilingAtCurrentDesirability}, versus the ${saved.citizenGoal.minimumAtPopulationGoal} citizens required at the population goal.\n` : ""}\n## Winters\n\nFully staffed, maintained fisheries; homes consume per household. Each figure excludes spoilage and delivery loss.\n\n| Winter | Duration in a 60-minute term | Fish/min/fishery | Homes supported, late refresh | Homes supported, frequent refresh |\n|---|---:|---:|---:|---:|\n${r.winter.map((w) => `| ${w.severity} | ${n(w.durationMinutesIn60MinuteTerm)} min | ${n(w.fishPerMinute)} | ${n(w.noWasteHomesPerFishery)} | ${n(w.frequentRefreshHomesPerFishery)} |`).join("\n")}\n\n## Verification\n\n${r.verification.filter((v) => v.pass).length}/${r.verification.length} controlled comparisons pass. Production tolerances allow one incomplete job at the window boundary; ledger rounding is exact. Service checks compare whole dispatch rotations to the shared planner, with exact visit fractions.\n\n| Check | Expected | Actual | Allowed error | Pass |\n|---|---:|---:|---:|---|\n${r.verification.map((v) => `| ${v.name} | ${n(v.expected)} | ${n(v.actual)} | ${n(v.tolerance)} | ${v.pass} |`).join("\n")}\n\n## Practical suggestions\n\nConcentrate bread, cloth and faith in a small desirable district before scaling the whole town. Budget working tools separately from construction tools. Keep available workers within commuting distance of farms and resource gatherers. Reserve workshop plots before agriculture expands. Size winter food capacity from household demand and storage losses, not resident count or summer fishing. Place repair services before condition crosses the half-speed threshold.\n\nUse static constraints and parameter/configuration search to reject weak designs quickly; verify promising designs and thresholds in the real game. Use the coarse forecast as an estimate with its measured timing and cash errors, not as a precise victory predictor.\n\n## Scope and limitations\n\n${r.limits.map((l) => `- ${l}`).join("\n")}\n`
}

const escape = (s: unknown) => String(s).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;")
export const htmlReport = (r: Report) => {
  const end = r.construction.actual.at(-1)!, predicted = r.construction.prediction.rows.at(-1)!
  const saved = r.analyses.find((a) => a.name === "pr3-bot-minute-30")
  const table = (headers: string[], rows: unknown[][]) => `<div class="scroll"><table><thead><tr>${headers.map((h) => `<th>${escape(h)}</th>`).join("")}</tr></thead><tbody>${rows.map((row) => `<tr>${row.map((c) => `<td>${escape(c)}</td>`).join("")}</tr>`).join("")}</tbody></table></div>`
  return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Current-rule balance results</title><style>:root{color-scheme:light dark}body{margin:0;font:14px system-ui;color:var(--foreground,CanvasText)}h2{font-size:17px;font-weight:500;margin:24px 0 12px}h3{font-size:15px;font-weight:500}p{line-height:1.5}table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}th,td{text-align:left;padding:10px 6px;border-bottom:1px solid var(--border,GrayText);font-size:12px}th{font-weight:500}.scroll{overflow-x:auto}.muted{color:var(--muted-foreground,GrayText)}details{margin:16px 0}summary{cursor:pointer}code{overflow-wrap:anywhere}ul{padding-left:20px;line-height:1.55}.lead{font-weight:500}</style></head><body><h2>First citizens with the current game parameters</h2><p class="lead">${end.citizens} citizens verified in the real game. First citizen at ${r.construction.firstCitizenSecond ?? "never"} seconds on the authored construction fixture.</p><p class="muted">PR #3 · shared game rules · ${r.verification.filter((v) => v.pass).length}/${r.verification.length} controlled comparisons passed. This establishes a working progression example, not a full-term victory.</p>
${table(["At 10 minutes", "Model estimate", "Real game"], [["Citizens", predicted.citizens, end.citizens], ["Residents", predicted.residents, end.residents], ["Coins", predicted.coins, end.coins], ["First citizen, seconds", r.construction.prediction.firstCitizenSecond ?? "none", r.construction.firstCitizenSecond ?? "none"]])}
<h2>Economic constraints worth acting on</h2><ul><li>First citizen chain: ${r.firstCitizenChain.coins} coins; ${r.firstCitizenChain.materials.tools} construction tools + ${r.firstCitizenChain.workingTools} working tools. Fair land starts with ${r.firstCitizenChain.fairStartingTools} tools.</li><li>The three-cell park with a fountain and lamp costs ${r.amenity.coins} coins and ${n(r.amenity.upkeepPerMinute)}/min. It contributes +${r.amenity.value} nearby desirability; industry can cancel that benefit.</li><li>Citizen goods go to eligible households. Start with a small, desirable district.</li><li>Surplus citizens can fill rough jobs at full pace. Keep workshops within road commuting distance.</li><li>Place workshops before farms can plant over their future plots.</li><li>Repair services have a ${r.analyses[0]!.repair.graceBeforeHalfSpeedSeconds}-second window between the repair threshold and half speed.</li></ul>
${saved ? `<h2>Captured bot town · minute 30</h2><p>Only ${saved.household.filter((h) => h.potentialTier >= 2).length} of ${saved.household.length} homes pass the current desirability gate. Even granting unlimited needs and services, those homes hold at most ${saved.citizenGoal.housingCeilingAtCurrentDesirability} citizens/burghers, versus ${saved.citizenGoal.minimumAtPopulationGoal} required at the population goal.</p><p>Cloth capacity is ${n(saved.availableAfterWorkshops.cloth)}/min; supplying eligible homes needs at least ${n(saved.needBounds.cloth.min)}/min. Compare those constraints with the observed staffing, deliveries and goal-hold duration.</p>` : ""}
<h2>Workshop ceilings · output per minute</h2>${table(["Building", "Own crew + tool", "Apprentices + tool", "Apprentices, no tool"], r.capacity.map((c) => [c.kind, n(c.staffed), n(c.apprentices), n(c.apprenticesWithoutTools)]))}
<h2>Winter fishing · household capacity before losses</h2>${table(["Winter", "Fish/min", "Homes, late refresh", "Homes, frequent refresh"], r.winter.map((w) => [w.severity, n(w.fishPerMinute), n(w.noWasteHomesPerFishery), n(w.frequentRefreshHomesPerFishery)]))}
<details><summary>Verification and limitations</summary>${table(["Check", "Expected", "Actual", "Pass"], r.verification.map((v) => [v.name, n(v.expected), n(v.actual), v.pass]))}<ul>${r.limits.map((l) => `<li>${escape(l)}</li>`).join("")}</ul></details><p class="muted">Rules SHA-256 <code>${r.provenance.rulesSha256}</code></p></body></html>`
}