game-village-politics-frontend/app/diorama/scene.ts

1124 lines
53 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The village diorama: a stretch of land seen from a raised camera, in the layout of a
// classic village overview. The village core sits in the middle: the headquarters on a
// dirt plaza, with storage, hiding places and the rally point around it, inside the wall
// when there is one. Resource sites stand outside in their own zones of the surrounding
// land: iron mines below a rocky hill (top left), clay pits on clay ground (bottom left),
// timber camps at the forest edge (bottom right) and farms with their fields (right).
// Dirt paths run from the plaza through the gates to every zone; forest fills the rest.
//
// The server only says which buildings exist; where they stand is decided here,
// deterministically and in id order, so buildings stay put when new ones are added.
import type { BuildingType, VillageState } from '~/types/game'
import { box, DOOR, type Face, hash, mix, ngon, plane, type Poly, prism, project, pyramid, scale, toPolys, type V2, type V3 } from './iso'
import type { Tool } from './life'
import { blot, broadleaf, buildingModel, bush, C, conifer, crane, deadTree, gallows, grave, rock, ruin, scaffold, stump, well } from './models'
/** World units per unit of building space, roughly. */
export const U = 24
const GOLDEN = Math.PI * (3 - Math.sqrt(5))
const deg = (d: number) => (d * Math.PI) / 180
const dir = (a: number): V2 => [Math.cos(a), Math.sin(a)]
// World angles seen on screen: 0° lower right, 90° lower left, 180° upper left,
// 270° upper right. 45° points at the viewer: the main gate and road.
const FRONT = deg(45)
const PATH_HALF = U * 0.5
const ZONE_PATH_HALF = U * 0.38
type Zone = 'iron' | 'clay' | 'timber' | 'farm'
const ZONE_OF: Partial<Record<BuildingType, Zone>> = { iron_mine: 'iron', clay_pit: 'clay', timber_camp: 'timber', farm: 'farm' }
/** Centre angle, half the angle it spans, model scale, and slot spacing in model sizes. */
const ZONES: Record<Zone, { angle: number; half: number; scale: number; gap: number; ground: string | null }> = {
iron: { angle: deg(196), half: deg(26), scale: 1.15, gap: 2.5, ground: '#716d66' },
clay: { angle: deg(102), half: deg(24), scale: 1.1, gap: 2.4, ground: '#7d543b' },
timber: { angle: deg(8), half: deg(22), scale: 1.1, gap: 2.4, ground: '#716345' },
farm: { angle: deg(-62), half: deg(27), scale: 1.3, gap: 2.6, ground: null },
}
const ZONE_NAMES = Object.keys(ZONES) as Zone[]
/** Tired grass, trodden and yellowed in places; roads and the plaza are mud. */
const GRASS = ['#6a7049', '#666c46', '#6e714c', '#73704b']
const DIRT = '#6b563f'
const PLAZA = '#735e45'
const VILLAGE_GROUND = '#6a6646'
const WALL_EARTH = '#5e4c38'
/** Ruts cut by cart wheels, and the rain standing in them. */
const RUT = '#4e3f2f'
const PUDDLE = '#59646a'
/** The land darkens towards the edges, into the forest. */
const DUSK = '#14170f'
/** A ground colour darkened from `r0` out to `r1`, at most by `max`. */
export function fade(color: string, r: number, r0: number, r1: number, max = 0.25): string {
const k = Math.min(1, Math.max(0, (r - r0) / (r1 - r0)))
return k ? mix(color, DUSK, k * max) : color
}
export interface SceneBuilding {
id: number
type: BuildingType
level: number
upgrading: boolean
/** Screen point above the roof, for the level badge. */
label: V2
/** Screen ellipse of its ground footprint. */
ring: { cx: number; cy: number; rx: number; ry: number }
/** Only one part of the wall takes keyboard focus. */
focusable: boolean
/** Click target: the outline round everything drawn for it and its ground, a little wider. */
hit?: string
}
export interface SceneObject {
key: string
polys: Poly[]
building?: SceneBuilding
planned?: boolean
/** A villager who stays put, sorted in among the buildings: chatting, building, drilling. */
life?: SceneLife
/** A villager going somewhere and back, sorted in among the buildings: out of a door, a porter. */
walker?: SceneWalker
}
export interface SceneWalker {
/** Screen path from where they start (a door, a store) to where they go. */
d: string
walk: number
work: number
rest: number
/** Out of sight while resting: they live in the building they come out of. */
indoors: boolean
/** A soldier: helmet and shield. */
soldier?: boolean
tool: Tool | null
carry: string | null
shirt: number
begin: number
}
export interface SceneLife {
/** Screen point at their feet. */
at: V2
facing: 1 | -1
tool: Tool | null
shirt: number
/** A recruit thrusting the spear in drill, instead of a tool at work. */
drill?: boolean
/** A soldier standing guard: helmet, shield and spear, standing still. */
guard?: boolean
}
/** What each zone's workers work with and bring home. */
const WORK: Record<Zone, { tool: Tool; carry: string }> = {
timber: { tool: 'axe', carry: C.wood },
clay: { tool: 'shovel', carry: C.clay },
iron: { tool: 'pick', carry: C.ore },
farm: { tool: 'sickle', carry: C.wheat },
}
/**
* Ground kept free for a building type that doesn't stand yet: nothing is drawn there,
* but the spot opens that type's build card, like the empty plots in Die Stämme.
*/
export interface ScenePlot {
key: string
type: BuildingType
/** Room for one more of a type that already stands (zone plots). */
another: boolean
/** Screen ellipse of the plot, the click target. */
ring: { cx: number; cy: number; rx: number; ry: number }
}
/** A running build order's countdown, anchored above what it works on. */
export interface SceneTimer {
orderId: number
finishesAt: string
/** Screen point above the roof or scaffold. */
at: V2
/** The building whose level badge sits at this spot; the timer goes above that badge. */
buildingId: number | null
}
/** A rectangle in viewBox units. */
export interface View {
x: number
y: number
w: number
h: number
}
export interface Scene {
viewBox: string
/** viewBox size, for keeping badges a fixed size on screen. */
width: number
height: number
/** The view that fits the whole village into the free part of the stage (the viewBox). */
home: View
/** Where the land is drawn: the camera pans and zooms out inside it. */
bounds: View
terrain: Poly[]
decals: Poly[]
objects: SceneObject[]
plots: ScenePlot[]
timers: SceneTimer[]
/** Chimneys, forges and kilns that smoke, as screen points. */
smoke: V2[]
/** Roads villagers walk to work and back: a screen path, how many walk it, seconds per round trip. */
walks: { d: string; count: number; walk: number; work: number; tool: Tool | null; carry: string | null }[]
/** Sheep by the farms and chickens on the plaza, wandering small loops. */
herds: { kind: 'sheep' | 'chicken'; d: string; dur: number; begin: number }[]
/** Crows crossing the land now and then, and circling over the graves and the gallows. */
birds: { d: string; dur: number; begin: number }[]
/** A wide click band along the wall ring, so the thin wall is easy to hit. */
wallBand: { id: number; ring: { cx: number; cy: number; rx: number; ry: number }; width: number } | null
}
/** Units in the village (own and support) from which every other door gets a guard, and two. */
const DOOR_GUARDS_FROM = 100
const DOUBLE_GUARDS_FROM = 400
/** Units standing in the village: its own and support from elsewhere. */
export function garrisonOf(village: Pick<VillageState, 'troops' | 'support'>): number {
const count = (units: Partial<Record<string, number>>) => Object.values(units).reduce((n: number, c) => n + (c ?? 0), 0)
return count(village.troops ?? {}) + village.support.here.reduce((n, g) => n + count(g.units), 0)
}
/**
* Soldiers standing guard at a building's door: two at the headquarters as soon as there
* are troops, one at every other door from a big army on, two from a bigger one.
*/
export function guardsAt(type: BuildingType, garrison: number): number {
if (garrison <= 0 || ZONE_OF[type]) return 0
if (type === 'headquarters') return 2
return garrison >= DOUBLE_GUARDS_FROM ? 2 : garrison >= DOOR_GUARDS_FROM ? 1 : 0
}
/** Where guards stand from the point outside a door (facing +x): a step out, to either side. */
export function guardSpots(type: BuildingType, [x, y]: V2, n: number, unit: number): V2[] {
const out = type === 'headquarters' ? 0.55 : 0.3
const side = type === 'headquarters' ? 0.75 : 0.6
return [
[x + unit * out, y + unit * side],
[x + unit * out, y - unit * side],
].slice(0, n) as V2[]
}
/** Buildings that smoke, from this level on. */
const SMOKY: Partial<Record<BuildingType, number>> = { headquarters: 1, barracks: 1, workshop: 1, academy: 1, clay_pit: 1, iron_mine: 5 }
const WATER = '#4a5b5d'
/** A scene object with its painter order (x + y of its ground point). */
type Ordered = SceneObject & { depth: number }
interface Slot {
key: string
x: number
y: number
/** Clearance radius on the ground. */
r: number
/** Model half-size. */
s: number
}
const footRadius = (space: number) => Math.sqrt(Math.max(space, 1)) * U * 0.7
const halfSize = (space: number) => Math.sqrt(Math.max(space, 1)) * U * 0.52
/** Distance from a ray that starts at the centre and runs along angle `a`. */
function rayDistance(x: number, y: number, a: number) {
const [dx, dy] = dir(a)
const along = x * dx + y * dy
return along < 0 ? Math.hypot(x, y) : Math.abs(x * dy - y * dx)
}
/** Convex outline round a building's polygons and ground ring, grown by `grow` around its middle. */
function hitOutline(polys: Poly[], ring: { cx: number; cy: number; rx: number; ry: number }, grow = 1.12): string {
const pts: V2[] = polys.flatMap((p) => p.points.split(' ').map((xy) => xy.split(',').map(Number) as V2))
if (ring.rx) pts.push([ring.cx - ring.rx, ring.cy], [ring.cx + ring.rx, ring.cy], [ring.cx, ring.cy - ring.ry], [ring.cx, ring.cy + ring.ry])
if (pts.length < 3) return ''
pts.sort((a, b) => a[0] - b[0] || a[1] - b[1])
const cross = (o: V2, a: V2, b: V2) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
const half = (list: V2[]) => {
const out: V2[] = []
for (const p of list) {
while (out.length >= 2 && cross(out[out.length - 2]!, out[out.length - 1]!, p) <= 0) out.pop()
out.push(p)
}
return out.slice(0, -1)
}
const hull = [...half(pts), ...half([...pts].reverse())]
const cx = hull.reduce((n, p) => n + p[0], 0) / hull.length
const cy = hull.reduce((n, p) => n + p[1], 0) / hull.length
return hull.map(([x, y]) => `${(cx + (x - cx) * grow).toFixed(1)},${(cy + (y - cy) * grow).toFixed(1)}`).join(' ')
}
/** Distance from point p to the segment a–b. */
function segmentDistance([px, py]: V2, [ax, ay]: V2, [bx, by]: V2): number {
const dx = bx - ax
const dy = by - ay
const t = Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy || 1)))
return Math.hypot(px - ax - dx * t, py - ay - dy * t)
}
/** A footpath along the points: a strip per stretch and a round patch at every bend. */
function trail(pts: V2[], half: number, seed: number): Face[] {
const faces: Face[] = []
for (let i = 0; i < pts.length - 1; i++) {
const [ax, ay] = pts[i]!
const [bx, by] = pts[i + 1]!
const l = Math.hypot(bx - ax, by - ay) || 1
const nx = (-(by - ay) / l) * half
const ny = ((bx - ax) / l) * half
faces.push(plane([[ax + nx, ay + ny, 1.1], [bx + nx, by + ny, 1.1], [bx - nx, by - ny, 1.1], [ax - nx, ay - ny, 1.1]], DIRT))
}
for (const [i, [x, y]] of pts.slice(1, -1).entries()) faces.push(plane(disc(x, y, half * 1.05, 8, seed + i, 1.1), DIRT))
return faces
}
function screenRing(x: number, y: number, r: number) {
const [cx, cy] = project([x, y, 0])
return { cx, cy, rx: r * Math.SQRT2, ry: r * Math.SQRT1_2 }
}
// Layout
/** Inside the village: a golden-angle spiral around the headquarters, keeping the roads free. */
function layoutCore(items: { key: string; space: number }[], hqRadius: number, roads: number[]): Slot[] {
const slots: Slot[] = [{ key: 'hq', x: 0, y: 0, r: hqRadius, s: 0 }]
for (const item of items) {
const r = footRadius(item.space)
for (let i = 1; i < 8000; i++) {
const d = U * 0.3 * Math.sqrt(i)
const x = Math.cos(i * GOLDEN) * d
const y = Math.sin(i * GOLDEN) * d
if (roads.some((a) => rayDistance(x, y, a) < r + PATH_HALF)) continue
if (slots.some((s) => Math.hypot(x - s.x, y - s.y) < r + s.r + U * 0.3)) continue
slots.push({ key: item.key, x, y, r, s: halfSize(item.space) })
break
}
}
return slots
}
/**
* A zone outside the wall: rows of slots along an arc, nearest row first, filled from
* the zone's road outwards on both sides. `count` slots, however many buildings exist,
* so an empty zone still shows its ground.
*/
function layoutZone(zone: Zone, space: number, count: number, Rv: number): Slot[] {
const z = ZONES[zone]
const s = halfSize(space) * z.scale
const slots: Slot[] = []
for (let row = 0; slots.length < count && row < 20; row++) {
const r = Rv + U * 1.7 + s * 1.3 + row * s * z.gap
const step = (s * z.gap) / r
for (let k = 0; slots.length < count; k++) {
const offset = (k % 2 ? -1 : 1) * (Math.floor(k / 2) + 0.5)
if (Math.abs(offset) * step > z.half) break
const [x, y] = dir(z.angle + offset * step)
slots.push({ key: `${zone}-${slots.length}`, x: x * r, y: y * r, r: s * 1.15, s })
}
}
return slots
}
// Ground
function inverse([X, Y]: V2): V2 {
return [Y + X / 2, Y - X / 2]
}
/**
* A low-poly ground mesh that covers the view; vertices hash from their grid index, so it
* never shifts. With `dark`, the land darkens from radius r0 out to r1.
*/
export function ground(view: { x: number; y: number; w: number; h: number }, dark?: { r0: number; r1: number }): Poly[] {
const g = U * 2.6
const corners = [
inverse([view.x, view.y]),
inverse([view.x + view.w, view.y]),
inverse([view.x, view.y + view.h]),
inverse([view.x + view.w, view.y + view.h]),
]
const i0 = Math.floor(Math.min(...corners.map((c) => c[0])) / g) - 1
const i1 = Math.ceil(Math.max(...corners.map((c) => c[0])) / g) + 1
const j0 = Math.floor(Math.min(...corners.map((c) => c[1])) / g) - 1
const j1 = Math.ceil(Math.max(...corners.map((c) => c[1])) / g) + 1
const vertex = (i: number, j: number): V3 => [
(i + (hash(i, j, 1) - 0.5) * 0.6) * g,
(j + (hash(i, j, 2) - 0.5) * 0.6) * g,
(hash(i, j, 3) - 0.5) * 4,
]
const faces: Face[] = []
for (let i = i0; i < i1; i++) {
for (let j = j0; j < j1; j++) {
const a = vertex(i, j)
const b = vertex(i + 1, j)
const c = vertex(i + 1, j + 1)
const d = vertex(i, j + 1)
const xs = [a, b, c, d].map((p) => project(p))
const minX = Math.min(...xs.map((p) => p[0]))
const maxX = Math.max(...xs.map((p) => p[0]))
const minY = Math.min(...xs.map((p) => p[1]))
const maxY = Math.max(...xs.map((p) => p[1]))
if (maxX < view.x || minX > view.x + view.w || maxY < view.y || minY > view.y + view.h) continue
const tone = (k: number, p: V3, q: V3) => {
const color = GRASS[Math.floor(hash(i, j, k) * GRASS.length)]!
return dark ? fade(color, Math.hypot((a[0] + p[0] + q[0]) / 3, (a[1] + p[1] + q[1]) / 3), dark.r0, dark.r1) : color
}
faces.push({ pts: [a, b, c], color: tone(4, b, c), twoSided: true }, { pts: [a, c, d], color: tone(5, c, d), twoSided: true })
}
}
return toPolys(faces).map((p) => ({ ...p, stroke: p.fill }))
}
export function disc(cx: number, cy: number, r: number, n: number, seed: number, z = 0.6): V3[] {
return ngon(cx, cy, r, n, hash(seed, 1) * 6).map(([x, y], i): V3 => {
const k = 0.82 + 0.3 * hash(seed, i)
return [cx + (x - cx) * k, cy + (y - cy) * k, z]
})
}
/** The winding centre line of a road from radius r0 to r1 along angle `a`, with each point's distance out. */
function roadLine(a: number, r0: number, r1: number, seed: number): { x: number; y: number; t: number; k: number }[] {
const [dx, dy] = dir(a)
const px = -dy
const py = dx
const steps = Math.max(2, Math.ceil((r1 - r0) / (U * 1.4)))
return Array.from({ length: steps + 1 }, (_, k) => {
const t = r0 + ((r1 - r0) * k) / steps
const wobble = k === 0 ? 0 : (hash(seed, k, 5) - 0.5) * U * 0.4
return { x: dx * t + px * wobble, y: dy * t + py * wobble, t, k }
})
}
/** A dirt road from radius r0 to r1 along angle `a`, gently winding. */
function road(a: number, r0: number, r1: number, half: number, seed: number): Face {
const [dx, dy] = dir(a)
const px = -dy
const py = dx
const left: V3[] = []
const right: V3[] = []
for (const { x, y, k } of roadLine(a, r0, r1, seed)) {
const w = half * (0.85 + 0.3 * hash(seed, k, 6))
left.push([x + px * w, y + py * w, 1.2])
right.push([x - px * w, y - py * w, 1.2])
}
return plane([...left, ...right.reverse()], DIRT)
}
/** Two wheel ruts along a road, and rain standing in them here and there. */
function ruts(a: number, r0: number, r1: number, half: number, seed: number): Face[] {
const [dx, dy] = dir(a)
const line = roadLine(a, r0, r1, seed)
const faces: Face[] = []
const color = mix(DIRT, RUT, 0.6)
for (const side of [-1, 1]) {
const off = side * half * 0.36
const w = U * 0.03
const left: V3[] = line.map((p): V3 => [p.x - dy * (off - w), p.y + dx * (off - w), 1.3])
const right: V3[] = line.map((p): V3 => [p.x - dy * (off + w), p.y + dx * (off + w), 1.3])
faces.push(plane([...left, ...right.reverse()], color))
}
// Now and then the rain stands in a rut.
for (let i = 1; i < line.length - 1; i++) {
if (hash(seed, i, 7) > 0.22) continue
const side = hash(seed, i, 8) > 0.5 ? 1 : -1
const p = line[i]!
const off = side * half * 0.3
faces.push(blot(p.x - dy * off, p.y + dx * off, U * (0.2 + 0.12 * hash(seed, i, 9)), 7, seed * 31 + i, 1.4, PUDDLE))
}
return faces
}
/** The screen path along a road between two radii, for villagers to walk. */
function walkPath(a: number, r0: number, r1: number, seed: number, from: number, to: number): string {
const pts = roadLine(a, r0, r1, seed).filter((p) => p.t >= from && p.t <= to)
return pts.map((p, i) => `${i ? 'L' : 'M'}${project([p.x, p.y, 1.2]).map((v) => v.toFixed(1)).join(' ')}`).join(' ')
}
/** A flat shadow on the ground, cast away from the light (to the right on screen). */
export function shadow(x: number, y: number, r: number, color: string, seed: number): Face {
return plane(disc(x + r * 0.42, y - r * 0.32, r, 10, seed, 1.4), color)
}
/** A band around the village: worn earth under the wall, or the village's edge without one. */
function ringBand(r: number, width: number, color: string): Face[] {
const n = 56
// Trodden unevenly: each edge wanders in and out.
const edge = (i: number, side: number) => {
const a = ((i % n) / n) * Math.PI * 2
const k = r + side * (width / 2) * (0.55 + 0.9 * hash(i % n, side + 3, 17))
return [Math.cos(a) * k, Math.sin(a) * k, 1] as V3
}
const faces: Face[] = []
for (let i = 0; i < n; i++) faces.push(plane([edge(i, -1), edge(i + 1, -1), edge(i + 1, 1), edge(i, 1)], color))
return faces
}
// The wall rings the village; its look follows the level like the buildings, and each
// segment is its own object so it sorts correctly against buildings inside and out.
export function wallSegments(Rv: number, level: number, gates: number[]): { faces: Face[]; depth: number }[] {
const steps = Math.max(28, Math.round((Math.PI * 2 * Rv) / (U * 0.55)))
const gateHalf = (PATH_HALF + U * 0.3) / Rv
const h = U * (0.5 + Math.min(level, 20) * 0.035)
const at = (a: number): V2 => [Math.cos(a) * Rv, Math.sin(a) * Rv]
const inGate = (a: number) => gates.some((g) => Math.abs(Math.atan2(Math.sin(a - g), Math.cos(a - g))) < gateHalf)
const out: { faces: Face[]; depth: number }[] = []
for (let i = 0; i < steps; i++) {
const a0 = (i / steps) * Math.PI * 2
const a1 = ((i + 1) / steps) * Math.PI * 2
const mid = (a0 + a1) / 2
if (inGate(mid)) continue
const nextToGate = inGate(mid + (Math.PI * 2) / steps) || inGate(mid - (Math.PI * 2) / steps)
const [x, y] = at(mid)
let faces: Face[]
if (level < 5) {
// Palisade of sharpened stakes.
const p = ngon(x, y, U * 0.09, 5, i)
faces = [...prism(p, 0, h, C.wood), ...pyramid(p, h, U * 0.12, C.woodDark)]
} else {
const [x0, y0] = at(a0)
const [x1, y1] = at(a1)
const nx = Math.cos(mid) * U * 0.1
const ny = Math.sin(mid) * U * 0.1
const base: V2[] = [
[x0 - nx, y0 - ny],
[x1 - nx, y1 - ny],
[x1 + nx, y1 + ny],
[x0 + nx, y0 + ny],
]
// Counter-clockwise from above, as prism() expects.
const ccw = (base[1]![0] - base[0]![0]) * (base[2]![1] - base[0]![1]) - (base[1]![1] - base[0]![1]) * (base[2]![0] - base[0]![0]) > 0
const stone = level >= 15
faces = prism(ccw ? base : [...base].reverse(), 0, h, stone ? C.stone : C.wood, stone ? C.stoneDark : C.plank)
if (stone && (i % 7 === 0 || nextToGate)) {
faces.push(...prism(ngon(x, y, U * 0.24, 6), 0, h * 1.55, C.stone, C.stoneDark), ...pyramid(ngon(x, y, U * 0.28, 6), h * 1.55, U * 0.38, C.slate))
} else if (!stone && nextToGate) {
faces.push(...prism(ngon(x, y, U * 0.16, 4, Math.PI / 4), 0, h * 1.4, C.woodDark), ...pyramid(ngon(x, y, U * 0.22, 4, Math.PI / 4), h * 1.4, U * 0.25, C.roofRed))
}
}
out.push({ faces, depth: x + y })
}
return out
}
/**
* How much land a stage's scene draws round the village: its view grown this much, but no
* more than the village's own size grown by AT_MOST, so a tall phone stage, already full of
* land above and below, only grows sideways.
*/
const SURROUNDINGS = 1.6
const AT_MOST = 2.6
/** Smooth value noise in world units: neighbouring points get similar values, so it comes in patches. */
function patches(x: number, y: number, size: number, seed: number): number {
const gx = x / size
const gy = y / size
const i = Math.floor(gx)
const j = Math.floor(gy)
const ease = (t: number) => t * t * (3 - 2 * t)
const u = ease(gx - i)
const v = ease(gy - j)
const top = hash(i, j, seed) * (1 - u) + hash(i + 1, j, seed) * u
const bottom = hash(i, j + 1, seed) * (1 - u) + hash(i + 1, j + 1, seed) * u
return top * (1 - v) + bottom * v
}
/** Pixels at the stage's edges that windows cover; the village fits into the rest. */
export interface SceneInset {
top: number
right: number
bottom: number
left: number
}
/**
* The scene for a stage: either just its shape (`aspect`, the village filling the frame),
* or its size in pixels with the covered edges, so the whole village lands in the free
* part and land and forest run on under the windows to every edge. A stage's scene also
* draws the land round that view (`bounds`), for the camera to pan over and zoom out to.
*/
export function buildScene(village: VillageState, frame: number | { width: number; height: number; inset?: SceneInset; surroundings?: boolean } = 2.2): Scene {
const aspect = typeof frame === 'number' ? frame : frame.width / Math.max(1, frame.height)
const isZone = (type: BuildingType) => ZONE_OF[type] !== undefined
const hq = village.buildings.find((b) => b.type === 'headquarters')
const hqRadius = footRadius(hq?.space ?? 9)
const planned = village.queue.filter((o) => o.action === 'build' && o.space > 0)
// Zone members in id order: existing buildings first, then queued new ones.
const members: Record<Zone, { key: string; space: number }[]> = { iron: [], clay: [], timber: [], farm: [] }
for (const b of [...village.buildings].sort((p, q) => p.id - q.id)) {
const zone = ZONE_OF[b.type]
if (zone) members[zone].push({ key: `b${b.id}`, space: b.space })
}
for (const o of [...planned].sort((p, q) => p.id - q.id)) {
const zone = ZONE_OF[o.type]
if (zone) members[zone].push({ key: `o${o.id}`, space: o.space })
}
const activeZones = ZONE_NAMES.filter((z) => members[z].length)
const roads = [FRONT, ...activeZones.map((z) => ZONES[z].angle)]
// Types with no building and no queued one keep an empty plot: inside the village
// after everything that stands, so building there moves nothing that already exists.
const present = new Set([...village.buildings.map((b) => b.type), ...village.queue.filter((o) => o.action === 'build').map((o) => o.type)])
const unbuilt = village.buildable.filter((o) => !present.has(o.type))
const corePlots = unbuilt.filter((o) => o.type !== 'headquarters' && o.type !== 'wall' && !isZone(o.type))
const coreItems = [
{ key: 'well', space: 1.4 },
...village.buildings.filter((b) => b.type !== 'headquarters' && b.type !== 'wall' && b.space > 0 && !isZone(b.type)).map((b) => ({ key: `b${b.id}`, space: b.space })),
...planned.filter((o) => !isZone(o.type)).map((o) => ({ key: `o${o.id}`, space: o.space })),
...corePlots.map((o) => ({ key: `p:${o.type}`, space: Math.max(o.space, 1) })),
]
const core = layoutCore(coreItems, hqRadius, roads)
const Rv = Math.max(U * 5.2, ...core.map((s) => Math.hypot(s.x, s.y) + s.r + U * 0.9))
const zoneSlots: Record<Zone, Slot[]> = { iron: [], clay: [], timber: [], farm: [] }
for (const zone of ZONE_NAMES) {
const space = members[zone][0]?.space ?? 4
// Each zone shows one free plot of its ground past its buildings, two when empty.
const slots = layoutZone(zone, space, Math.max(members[zone].length + 1, 2), Rv)
members[zone].forEach((m, i) => (slots[i]!.key = m.key))
zoneSlots[zone] = slots
}
const allSlots = [...core, ...ZONE_NAMES.flatMap((z) => zoneSlots[z])]
const plots: ScenePlot[] = corePlots.map((o) => {
const s = core.find((c) => c.key === `p:${o.type}`)!
return { key: `p:${o.type}`, type: o.type, another: false, ring: screenRing(s.x, s.y, s.r) }
})
for (const zone of ZONE_NAMES) {
const type = (Object.keys(ZONE_OF) as BuildingType[]).find((t) => ZONE_OF[t] === zone)!
const free = zoneSlots[zone][members[zone].length]
if (free && village.buildable.some((o) => o.type === type)) plots.push({ key: `p:${type}`, type, another: present.has(type), ring: screenRing(free.x, free.y, free.r) })
}
const slotOf = (key: string) => allSlots.find((s) => s.key === key)!
const zoneEnd = (zone: Zone) => Math.max(Rv + U * 3, ...zoneSlots[zone].map((s) => Math.hypot(s.x, s.y) + s.r))
const running = new Set(village.queue.filter((o) => o.builder !== null && o.building_id !== null).map((o) => o.building_id))
const shadows: Face[] = []
const smoke: V2[] = []
const objects: Ordered[] = []
const labelTops: number[] = []
/** Badge point per building id, and per queued new building (order id), for the timers. */
const anchorOfBuilding = new Map<number, V2>()
const anchorOfOrder = new Map<number, V2>()
// Buildings and queued new ones. Each door is remembered as the ground point just outside it.
const doorOf = new Map<number, V2>()
for (const b of village.buildings) {
if (b.type === 'wall') continue
const slot = b.type === 'headquarters' ? core[0]! : slotOf(`b${b.id}`)
const zone = ZONE_OF[b.type]
const s = zone ? slot.s : halfSize(b.space)
const model = buildingModel(b.type, b.level, s)
const doorFace = model.faces.find((f) => f.color === DOOR)
if (doorFace) {
const dx = doorFace.pts.reduce((n, p) => n + p[0], 0) / doorFace.pts.length
const dy = doorFace.pts.reduce((n, p) => n + p[1], 0) / doorFace.pts.length
doorOf.set(b.id, [slot.x + dx + U * 0.3, slot.y + dy])
}
const upgrading = running.has(b.id)
const faces = upgrading ? [...model.faces, ...crane(s, model.height)] : model.faces
const label = project([slot.x, slot.y, model.height + 10])
labelTops.push(label[1])
anchorOfBuilding.set(b.id, label)
const ground = b.type === 'headquarters' ? PLAZA : zone ? (ZONES[zone].ground ?? GRASS[0]!) : VILLAGE_GROUND
shadows.push(shadow(slot.x, slot.y, s * (zone ? 1.0 : 0.95), scale(ground, 0.8), b.id))
const smokyFrom = SMOKY[b.type]
if (smokyFrom !== undefined && b.level >= smokyFrom && !upgrading) smoke.push(project([slot.x - s * 0.35, slot.y + s * 0.3, model.height * 0.72]))
objects.push({
key: `b${b.id}`,
depth: slot.x + slot.y,
polys: toPolys(faces, [slot.x, slot.y, 0]),
building: { id: b.id, type: b.type, level: b.level, upgrading, label, ring: screenRing(slot.x, slot.y, slot.r), focusable: true },
})
}
for (const o of planned) {
const slot = slotOf(`o${o.id}`)
const model = scaffold(ZONE_OF[o.type] ? slot.s : halfSize(o.space))
anchorOfOrder.set(o.id, project([slot.x, slot.y, model.height + 10]))
objects.push({ key: `o${o.id}`, depth: slot.x + slot.y, polys: toPolys(model.faces, [slot.x, slot.y, 0]), planned: true })
}
const wellSlot = slotOf('well')
objects.push({ key: 'well', depth: wellSlot.x + wellSlot.y, polys: toPolys(well(U * 0.55).faces, [wellSlot.x, wellSlot.y, 0]) })
// The wall: every segment sorts on its own.
const wall = village.buildings.find((b) => b.type === 'wall')
const wallPlanned = !wall && village.queue.some((o) => o.action === 'build' && o.type === 'wall')
let wallTop = 0
if (wall || wallPlanned) {
const level = wall?.level ?? 0
const segments = wallSegments(Rv, level, roads)
wallTop = U * (0.5 + Math.min(level, 20) * 0.035) * 1.55 + U * 0.4
const gateSide = FRONT + deg(24)
const label = project([Math.cos(gateSide) * Rv, Math.sin(gateSide) * Rv, wallTop + 10])
labelTops.push(label[1])
if (wall) anchorOfBuilding.set(wall.id, label)
else for (const o of village.queue) if (o.action === 'build' && o.type === 'wall') anchorOfOrder.set(o.id, label)
const ring = { cx: 0, cy: 0, rx: 0, ry: 0 }
// The segment nearest the badge takes keyboard focus for the whole wall.
const focusIndex = segments.reduce((best, seg, i) => (seg.depth > segments[best]!.depth ? i : best), 0)
segments.forEach((seg, i) => {
objects.push({
key: `wall-${i}`,
depth: seg.depth,
polys: toPolys(seg.faces),
...(wall
? { building: { id: wall.id, type: 'wall' as const, level, upgrading: running.has(wall.id), label, ring, focusable: i === focusIndex } }
: { planned: true }),
})
})
}
// Without a wall, its plot is the stretch of village edge where its badge would sit.
if (!wall && !wallPlanned && unbuilt.some((o) => o.type === 'wall')) {
const gateSide = FRONT + deg(24)
plots.push({ key: 'p:wall', type: 'wall', another: false, ring: screenRing(Math.cos(gateSide) * Rv, Math.sin(gateSide) * Rv, U * 0.9) })
}
// The frame: the village and every zone, with room for labels; then widened or
// heightened to the container's shape, where more land and forest show.
const Rz = Math.max(Rv + U * 4.5, ...ZONE_NAMES.map(zoneEnd))
const pts: V2[] = []
for (let i = 0; i < 24; i++) {
const [x, y] = dir((i / 24) * Math.PI * 2)
pts.push(project([x * (Rv + U * 2.5), y * (Rv + U * 2.5), 0]))
}
for (const s of allSlots) pts.push(project([s.x - s.r, s.y + s.r, 0]), project([s.x + s.r, s.y - s.r, 0]), project([s.x + s.r, s.y + s.r, 0]))
let minX = Math.min(...pts.map((p) => p[0]))
let maxX = Math.max(...pts.map((p) => p[0]))
let minY = Math.min(...pts.map((p) => p[1]), ...labelTops) - U * 1.2
let maxY = Math.max(...pts.map((p) => p[1])) + U * 0.8
// Room round the village, so a strip of the land outside shows at every edge.
const padX = (maxX - minX) * 0.09
const padY = (maxY - minY) * 0.07
minX -= padX
maxX += padX
minY -= padY
maxY += padY
let w = maxX - minX
let h = maxY - minY
const midX = (minX + maxX) / 2
const midY = (minY + maxY) / 2
const most = { w: w * AT_MOST, h: h * AT_MOST }
if (typeof frame !== 'number') {
// Fit the village into the free part of the stage; the view spans the whole stage.
const inset = frame.inset ?? { top: 0, right: 0, bottom: 0, left: 0 }
const freeW = Math.max(120, frame.width - inset.left - inset.right)
const freeH = Math.max(120, frame.height - inset.top - inset.bottom)
const perUnit = Math.min(freeW / w, freeH / h)
w = frame.width / perUnit
h = frame.height / perUnit
minX = midX - (inset.left + freeW / 2) / perUnit
minY = midY - (inset.top + freeH / 2) / perUnit
} else if (w / h < aspect) {
const extra = h * aspect - w
minX -= extra / 2
w += extra
} else {
const extra = w / aspect - h
minY -= extra * 0.45
h += extra
}
maxX = minX + w
maxY = minY + h
const view: View = { x: minX, y: minY, w, h }
// On a stage the land runs on round the village, never less than the view.
let bounds = view
if (typeof frame !== 'number' && frame.surroundings !== false) {
const around = { w: Math.min(w * SURROUNDINGS, most.w), h: Math.min(h * SURROUNDINGS, most.h) }
const bx = Math.min(view.x, midX - around.w / 2)
const by = Math.min(view.y, midY - around.h / 2)
bounds = { x: bx, y: by, w: Math.max(maxX, midX + around.w / 2) - bx, h: Math.max(maxY, midY + around.h / 2) - by }
}
const { x: bX, y: bY, w: bW, h: bH } = bounds
// The main road runs on out of the land, wherever its edge is.
const roadEnd = Math.max(Rz * 3, (bY + bH) / Math.SQRT1_2 + U * 4)
// Decals on the ground, back to front by layer.
const decalFaces: Face[] = [plane(disc(0, 0, Rv + U * 0.25, 40, 7, 0.5), VILLAGE_GROUND)]
for (const zone of ZONE_NAMES) {
const color = ZONES[zone].ground
if (!color) continue
zoneSlots[zone].forEach((s, i) => decalFaces.push(plane(disc(s.x, s.y, s.r * 1.3, 9, 30 + i * 7 + zone.length, 0.8), color)))
}
// Trodden mud between the houses.
for (let k = 0; k < 9; k++) {
const a = hash(k, 81) * Math.PI * 2
const r = (Rv - U) * Math.sqrt(hash(k, 82))
decalFaces.push(blot(Math.cos(a) * r, Math.sin(a) * r, U * (0.6 + 0.7 * hash(k, 83)), 9, 800 + k, 0.55, mix(VILLAGE_GROUND, DIRT, 0.6)))
}
decalFaces.push(road(FRONT, hqRadius * 0.9, roadEnd, PATH_HALF, 1), ...ruts(FRONT, hqRadius * 0.9, roadEnd, PATH_HALF, 1))
for (const zone of activeZones) {
const seed = ZONE_NAMES.indexOf(zone) + 2
decalFaces.push(road(ZONES[zone].angle, hqRadius * 0.9, zoneEnd(zone) + U * 0.5, ZONE_PATH_HALF, seed), ...ruts(ZONES[zone].angle, hqRadius * 0.9, zoneEnd(zone), ZONE_PATH_HALF, seed))
}
// Footpaths: from every door to the nearest road or the plaza, around other buildings,
// with a trodden patch in front of the door; from every site outside to its zone road.
const blockers = [{ key: 'hq', x: 0, y: 0, r: hqRadius * 0.8 }, ...allSlots.filter((sl) => sl.key !== 'hq').map((sl) => ({ key: sl.key, x: sl.x, y: sl.y, r: sl.r * 0.85 }))]
const length = (pts: V2[]) => pts.slice(1).reduce((n, p, i) => n + Math.hypot(p[0] - pts[i]![0], p[1] - pts[i]![1]), 0)
for (const b of village.buildings) {
if (b.type === 'headquarters' || b.type === 'wall') continue
const slot = slotOf(`b${b.id}`)
const zone = ZONE_OF[b.type]
if (zone) {
const [dx, dy] = dir(ZONES[zone].angle)
const t = slot.x * dx + slot.y * dy
if (Math.abs(slot.x * dy - slot.y * dx) > U * 0.6) decalFaces.push(...trail([[slot.x, slot.y], [dx * t, dy * t]], U * 0.17, b.id))
continue
}
const door = doorOf.get(b.id)
const from: V2 = door ?? [slot.x, slot.y]
const step: V2 = door ? [door[0] + U * 0.35, door[1]] : from
const targets: V2[] = []
const r = Math.hypot(step[0], step[1]) || 1
targets.push([(step[0] / r) * hqRadius * 1.15, (step[1] / r) * hqRadius * 1.15])
for (const a of roads) {
const [dx, dy] = dir(a)
const t = step[0] * dx + step[1] * dy
if (t > hqRadius && t < Rv + U) targets.push([dx * t, dy * t])
}
const clear = (pts: V2[]) =>
blockers.every((o) => {
const radius = o.key === slot.key ? slot.s * 0.85 : o.r
return pts.slice(1).every((p, i) => segmentDistance([o.x, o.y], pts[i]!, p) >= radius)
})
const shapes = targets.flatMap((t): V2[][] => [
[step, t],
[step, [step[0], t[1]], t],
[step, [t[0], step[1]], t],
])
shapes.sort((p, q) => length(p) - length(q))
const best = shapes.find(clear) ?? shapes[0]!
if (door) decalFaces.push(plane(disc(step[0], step[1], U * 0.42, 9, b.id + 50, 1.1), DIRT))
decalFaces.push(...trail(door ? [from, ...best] : best, U * 0.2, b.id))
}
decalFaces.push(...ringBand(Rv, U * (wall || wallPlanned ? 0.55 : 0.4), wall || wallPlanned ? WALL_EARTH : DIRT))
decalFaces.push(plane(disc(0, 0, hqRadius * 1.3, 11, 3, 1.6), PLAZA))
// Rain standing on the plaza, where the carts turn.
for (let k = 0; k < 3; k++) {
const [px, py] = dir(FRONT + deg(-50 + k * 50 + hash(k, 85) * 20))
decalFaces.push(blot(px * hqRadius * 1.12, py * hqRadius * 1.12, U * (0.22 + 0.15 * hash(k, 86)), 7, 860 + k, 1.7, PUDDLE))
}
// Landscape: a rocky hill behind the iron zone, then forest everywhere else.
const taken: { x: number; y: number; r: number }[] = allSlots.map((s) => ({ x: s.x, y: s.y, r: s.r + U * 0.45 }))
// Sheep graze past the farms, chickens peck round the plaza: small loops kept free of trees.
const herds: Scene['herds'] = []
const loop = (cx: number, cy: number, r: number, seed: number) => {
const pts = [0, 1, 2, 3, 0].map((i): V2 => {
const a = (i / 4) * Math.PI * 2 + hash(seed, 1) * 6
return project([cx + Math.cos(a) * r * (0.7 + 0.5 * hash(seed, i + 2)), cy + Math.sin(a) * r, 1.2])
})
return pts.map((p, i) => `${i ? 'L' : 'M'}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' ')
}
if (activeZones.includes('farm')) {
const [fx, fy] = dir(ZONES.farm.angle + deg(14))
const r = zoneEnd('farm') + U * 1.6
taken.push({ x: fx * r, y: fy * r, r: U * 1.8 })
for (let k = 0; k < 3; k++) herds.push({ kind: 'sheep', d: loop(fx * r + (k - 1) * U * 0.9, fy * r + (k % 2) * U * 0.7, U * 0.9, 300 + k), dur: 26 + k * 5, begin: -k * 7 })
}
{
const [cx, cy] = dir(FRONT + deg(75))
const r = hqRadius * 1.5
for (let k = 0; k < 2; k++) herds.push({ kind: 'chicken', d: loop(cx * r + k * U * 0.5, cy * r - k * U * 0.4, U * 0.5, 320 + k), dur: 14 + k * 4, begin: -k * 5 })
}
// A pond in the meadow between the clay pits and the hill, with reeds on its bank.
const pondR = U * 1.5
const pondOut = Math.max(Rv + U * 2.6, zoneEnd('clay') * 0.85)
const [pondX, pondY] = [Math.cos(deg(150)) * pondOut, Math.sin(deg(150)) * pondOut]
if (!taken.some((t) => Math.hypot(pondX - t.x, pondY - t.y) < t.r + pondR)) {
decalFaces.push(plane(disc(pondX, pondY, pondR * 1.18, 14, 91, 0.9), '#58513b'))
decalFaces.push(plane(disc(pondX, pondY, pondR, 14, 92, 1.0), WATER))
decalFaces.push(plane(disc(pondX - pondR * 0.25, pondY + pondR * 0.1, pondR * 0.45, 8, 93, 1.1), scale(WATER, 1.12)))
taken.push({ x: pondX, y: pondY, r: pondR * 1.3 })
for (let k = 0; k < 7; k++) {
const a = (k / 7) * Math.PI * 2 + hash(k, 94)
const [x, y] = [pondX + Math.cos(a) * pondR * 1.12, pondY + Math.sin(a) * pondR * 1.12]
const h = U * (0.3 + 0.25 * hash(k, 95))
objects.push({ key: `reed-${k}`, depth: x + y, polys: toPolys(prism(ngon(x, y, U * 0.05, 4), 0, h, '#5c6040', '#77744c')) })
}
}
const iron = ZONES.iron
const hillFrom = zoneEnd('iron')
for (let k = 0; k < 11; k++) {
const a = iron.angle + (hash(k, 41) - 0.5) * 2 * (iron.half + deg(8))
const r = hillFrom + U * (0.6 + 3 * hash(k, 42))
const [x, y] = [Math.cos(a) * r, Math.sin(a) * r]
const size = U * (1.5 + 1.4 * hash(k, 43))
taken.push({ x, y, r: size * 0.45 })
objects.push({ key: `hill-${k}`, depth: x + y, polys: toPolys(rock(x, y, size, 100 + k, hash(k, 44) > 0.5 ? C.stoneDark : C.rock)) })
}
const roadClear = (x: number, y: number) =>
rayDistance(x, y, FRONT) < PATH_HALF + U * 0.5 ||
activeZones.some((z) => {
const [dx, dy] = dir(ZONES[z].angle)
return x * dx + y * dy < zoneEnd(z) + U && rayDistance(x, y, ZONES[z].angle) < ZONE_PATH_HALF + U * 0.45
})
const inSector = (x: number, y: number, zone: Zone, pad: number) => {
const a = Math.atan2(y, x)
return Math.abs(Math.atan2(Math.sin(a - ZONES[zone].angle), Math.cos(a - ZONES[zone].angle))) < ZONES[zone].half + pad
}
// Hard times outside the wall: the graveyard behind the village, a grave more as it
// grows and the newest still open; the gallows by the main road; a farmstead burnt down
// and still smouldering. Each takes the first free spot of a few it may stand at.
const free = (x: number, y: number, r: number) =>
!taken.some((t) => Math.hypot(x - t.x, y - t.y) < t.r + r) &&
!ZONE_NAMES.some((z) => inSector(x, y, z, deg(4))) &&
[0, 1, 2, 3, 4, 5, 6, 7, 8].every((k) => !roadClear(x + (k ? Math.cos((k / 8) * Math.PI * 2) * r : 0), y + (k ? Math.sin((k / 8) * Math.PI * 2) * r : 0)))
const site = (angles: number[], from: number, r: number): V2 | null => {
for (let step = 0; step < 8; step++) {
for (const a of angles) {
const [x, y] = dir(a)
if (free(x * (from + step * U * 0.7), y * (from + step * U * 0.7), r)) return [x * (from + step * U * 0.7), y * (from + step * U * 0.7)]
}
}
return null
}
const hard: { key: string; x: number; y: number; faces: Face[] }[] = []
const yard = site([deg(250), deg(240), deg(260), deg(232)], Rv + U * 2.6, U * 1.8)
if (yard) {
const [gx, gy] = yard
const count = Math.min(14, 4 + Math.floor(village.points / 150))
for (let k = 0; k < count; k++) {
const x = gx + (Math.floor(k / 4) - 1) * U * 0.95 + (hash(k, 91) - 0.5) * U * 0.12
const y = gy + ((k % 4) - 1.5) * U * 0.52 + (hash(k, 92) - 0.5) * U * 0.1
hard.push({ key: `grave-${k}`, x, y, faces: grave(x, y, U, 900 + k, k === count - 1) })
}
hard.push({ key: 'grave-tree', x: gx - U * 1.6, y: gy - U * 1.2, faces: deadTree(gx - U * 1.6, gy - U * 1.2, U * 1.5, 77) })
taken.push({ x: gx, y: gy, r: U * 2.1 })
}
{
const [fx, fy] = dir(FRONT)
const t = Rv + U * 2.6
for (const side of [1, -1]) {
const off = (PATH_HALF + U * 2) * side
const [x, y] = [fx * t - fy * off, fy * t + fx * off]
if (!free(x, y, U * 0.8)) continue
hard.push({ key: 'gallows', x, y, faces: gallows(x, y, U * 1.1, side) })
taken.push({ x, y, r: U * 1.1 })
break
}
}
const burnt = site([deg(64), deg(-24), deg(134), deg(150)], Rv + U * 4.2, U * 1.6)
if (burnt) {
const [x, y] = burnt
hard.push({ key: 'ruin', x, y, faces: ruin(x, y, U * 1.15, 5) })
hard.push({ key: 'ruin-tree', x: x + U * 1.3, y: y - U * 0.9, faces: deadTree(x + U * 1.3, y - U * 0.9, U * 1.3, 78) })
smoke.push(project([x + U * 0.1, y, U * 0.35]))
taken.push({ x, y, r: U * 1.8 })
}
for (const o of hard) objects.push({ key: o.key, depth: o.x + o.y, polys: toPolys(o.faces) })
const f = U * 1.25
const cornersW = [inverse([bX, bY]), inverse([bX + bW, bY]), inverse([bX, bY + bH]), inverse([bX + bW, bY + bH])]
const fi0 = Math.floor(Math.min(...cornersW.map((c) => c[0])) / f)
const fi1 = Math.ceil(Math.max(...cornersW.map((c) => c[0])) / f)
const fj0 = Math.floor(Math.min(...cornersW.map((c) => c[1])) / f)
const fj1 = Math.ceil(Math.max(...cornersW.map((c) => c[1])) / f)
const cx = view.x + w / 2
for (let i = fi0; i <= fi1; i++) {
for (let j = fj0; j <= fj1; j++) {
const x = (i + hash(i, j, 61) * 0.8) * f
const y = (j + hash(i, j, 62) * 0.8) * f
const [X, Y] = project([x, y, 0])
if (X < bX - U || X > bX + bW + U || Y < bY || Y > bY + bH + U * 2) continue
const r = Math.hypot(x, y)
if (r < Rv + U * 1.5) continue
if (roadClear(x, y)) continue
if (taken.some((t) => Math.hypot(x - t.x, y - t.y) < t.r + U * 0.35)) continue
// Open meadow round the village, forest thickening towards the sides and the back.
const edge = Math.abs(X - cx) / (w / 2)
const far = Math.min(1, Math.max(0, (r - Rz * 0.75) / (Rz * 0.5)))
let density = 0.05 + 0.25 * far + 0.75 * Math.max(0, edge - 0.55) / 0.45 + (Y < view.y + h * 0.15 ? 0.15 : 0)
if (inSector(x, y, 'timber', deg(22)) && r > zoneEnd('timber') - U && r < zoneEnd('timber') + U * 4) density += 0.4
if (inSector(x, y, 'farm', deg(6)) && r < zoneEnd('farm') + U * 1.5) density *= 0.15
if (inSector(x, y, 'iron', deg(10))) density *= 0.45
if (inSector(x, y, 'clay', deg(4)) && r < zoneEnd('clay') + U) density *= 0.4
// Further out the forest opens into clearings here and there.
if (r > Rz * 1.15) density *= 0.1 + 0.9 * Math.min(1, Math.max(0, (patches(x, y, U * 8, 67) - 0.38) / 0.2))
const size = U * (1.0 + 0.55 * hash(i, j, 65))
const seed = i * 131 + j
if (hash(i, j, 63) > Math.min(density, 0.88)) {
// The forest round the village has been cut for timber and firewood: stumps remain.
const cleared = r < Rz * 1.1 && !inSector(x, y, 'farm', deg(6)) ? 0.16 : 0.03
if (hash(i, j, 66) < cleared) objects.push({ key: `s${i}:${j}`, depth: x + y, polys: toPolys(stump(x, y, size, seed)) })
continue
}
const kind = hash(i, j, 64)
const faces = kind < 0.1 ? bush(x, y, size * 0.8, seed) : kind < 0.6 ? conifer(x, y, size, seed) : kind < 0.68 ? deadTree(x, y, size, seed) : broadleaf(x, y, size, seed)
taken.push({ x, y, r: size * 0.3 })
shadows.push(shadow(x, y, size * 0.34, scale(GRASS[3]!, 0.8), seed))
// Further out the forest goes dark.
objects.push({ key: `t${i}:${j}`, depth: x + y, polys: toPolys(faces.map((face) => ({ ...face, color: fade(face.color, r, Rz * 0.9, Rz * 1.8, 0.2) }))) })
}
}
// A few stones in the meadows.
for (let k = 0; k < 14; k++) {
const a = hash(k, 71) * Math.PI * 2
const r = Rv + U * (1.4 + 6 * hash(k, 72))
const [x, y] = [Math.cos(a) * r, Math.sin(a) * r]
if (roadClear(x, y) || taken.some((t) => Math.hypot(x - t.x, y - t.y) < t.r + U * 0.3)) continue
objects.push({ key: `stone-${k}`, depth: x + y, polys: toPolys(rock(x, y, U * (0.45 + 0.4 * hash(k, 73)), 200 + k)) })
}
// Countdowns for the orders builders are working on, above what they change.
const timers: SceneTimer[] = []
for (const o of village.queue) {
if (!o.finishes_at) continue
const onBuilding = o.building_id !== null ? anchorOfBuilding.get(o.building_id) : undefined
const at = onBuilding ?? anchorOfOrder.get(o.id)
if (at) timers.push({ orderId: o.id, finishesAt: o.finishes_at, at, buildingId: onBuilding ? o.building_id : null })
}
// Villagers go out to the zones they work in, work there with their tool and bring the
// load home, more where more work. One walks out of the gate and back.
const walks: Scene['walks'] = []
for (const zone of activeZones) {
const workers = village.buildings.filter((b) => ZONE_OF[b.type] === zone).reduce((n, b) => n + b.workers.assigned, 0)
if (!workers) continue
const end = zoneEnd(zone)
const d = walkPath(ZONES[zone].angle, hqRadius * 0.9, end + U * 0.5, ZONE_NAMES.indexOf(zone) + 2, hqRadius * 1.4, end - U * 1.2)
walks.push({ d, count: Math.min(3, Math.max(1, Math.round(workers / 6))), walk: Math.max(8, ((end - hqRadius) / U) * 2.2), work: 4.5, ...WORK[zone] })
}
walks.push({ d: walkPath(FRONT, hqRadius * 0.9, Rz * 3, 1, hqRadius * 1.4, Rv + U * 5), count: 1, walk: 20, work: 0, tool: null, carry: null })
// A guard paces inside the gate.
if (wall) {
const arc = [10, 22, 34, 46].map((a) => project([Math.cos(FRONT + deg(a)) * (Rv - U * 0.9), Math.sin(FRONT + deg(a)) * (Rv - U * 0.9), 1.2]))
walks.push({ d: arc.map((p, i) => `${i ? 'L' : 'M'}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' '), count: 1, walk: 6, work: 2.5, tool: 'spear', carry: null })
}
// People who stay put: two talking on the plaza in front of the headquarters, a builder
// at every order in the works.
const people = (key: string, x: number, y: number, facing: 1 | -1, tool: Tool | null, shirt: number) =>
objects.push({ key, depth: x + y, polys: [], life: { at: project([x, y, 1.2]), facing, tool, shirt } })
const [chatX, chatY] = dir(FRONT + deg(32)).map((v) => v * hqRadius * 1.3)
people('chat-a', chatX! - U * 0.45, chatY! + U * 0.45, 1, null, 1)
people('chat-b', chatX! + U * 0.45, chatY! - U * 0.45, -1, null, 3)
const path = (pts: V2[]) => pts.map(([x, y], i) => `${i ? 'L' : 'M'}${project([x, y, 1.2]).map((v) => v.toFixed(1)).join(' ')}`).join(' ')
const walker = (key: string, from: V2, to: V2, w: Omit<SceneWalker, 'd' | 'walk'>) =>
objects.push({ key, depth: Math.max(from[0] + from[1], to[0] + to[1]), polys: [], walker: { d: path([from, to]), walk: Math.max(2, Math.hypot(to[0] - from[0], to[1] - from[1]) / U * 0.9), ...w } })
// Every order in the queue shows where it goes: building materials piled at the site, a
// porter bringing more from the storage, and while it runs, a builder at work.
const store = village.buildings.find((b) => b.type === 'storage') ?? village.buildings.find((b) => b.type === 'headquarters')
const storeDoor = store ? doorOf.get(store.id) : undefined
const sites = new Set<string>()
for (const o of village.queue) {
const b = o.building_id !== null ? village.buildings.find((x) => x.id === o.building_id) : null
if (b?.type === 'wall' || (!b && o.type === 'wall')) continue
const slot = b ? (b.type === 'headquarters' ? core[0]! : slotOf(`b${b.id}`)) : slotOf(`o${o.id}`)
if (o.builder !== null) {
people(`builder-${o.id}`, slot.x + slot.r * 0.95, slot.y + slot.r * 0.35, -1, o.action === 'demolish' ? 'pick' : 'hammer', o.id)
}
if (sites.has(slot.key) || o.action === 'demolish') continue
sites.add(slot.key)
const pile: V2 = [slot.x + slot.r * 0.3, slot.y + slot.r * 1.05]
const pileFaces = [
...box(pile[0], pile[1], U * 0.75, U * 0.32, 0, U * 0.11, C.plank, C.wood),
...box(pile[0] + U * 0.05, pile[1] - U * 0.04, U * 0.7, U * 0.3, U * 0.11, U * 0.11, C.wood, C.plank),
...pyramid(ngon(pile[0] + U * 0.55, pile[1] + U * 0.15, U * 0.22, 5), 0, U * 0.22, C.stone),
]
objects.push({ key: `pile-${o.id}`, depth: pile[0] + pile[1], polys: toPolys(pileFaces) })
if (storeDoor && Math.hypot(storeDoor[0] - pile[0], storeDoor[1] - pile[1]) > U * 1.5) {
walker(`porter-${o.id}`, storeDoor, [pile[0] + U * 0.6, pile[1] - U * 0.3], { work: 1.4, rest: 3, indoors: true, tool: null, carry: C.plank, shirt: o.id + 2, begin: -o.id * 1.7 })
}
}
// Units in training drill in front of their building, an instructor facing them.
for (const m of village.military) {
if (!m.queue.length) continue
const b = village.buildings.find((x) => x.id === m.building_id)
if (!b) continue
const slot = slotOf(`b${b.id}`)
for (let k = 0; k < 3; k++) {
const x = slot.x + slot.r * 1.15
const y = slot.y - slot.r * 0.35 + k * U * 0.55
objects.push({ key: `drill-${b.id}-${k}`, depth: x + y, polys: [], life: { at: project([x, y, 1.2]), facing: 1, tool: 'spear', shirt: 1, drill: true } })
}
people(`instructor-${b.id}`, slot.x + slot.r * 1.15 + U * 1.1, slot.y + slot.r * 0.2, -1, null, 4)
}
// Troops at home stand guard at the doors, more doors the bigger the army.
const garrison = garrisonOf(village)
for (const b of village.buildings) {
const door = doorOf.get(b.id)
if (!door) continue
guardSpots(b.type, door, guardsAt(b.type, garrison), U).forEach(([x, y], k) =>
objects.push({ key: `guard-${b.id}-${k}`, depth: x + y, polys: [], life: { at: project([x, y, 1.2]), facing: 1, tool: 'spear', shirt: 1, guard: true } }),
)
}
// Villagers step out of their buildings now and then, stand a moment, and go back in.
const homes = village.buildings.filter((b) => doorOf.has(b.id) && !ZONE_OF[b.type]).slice(0, 6)
homes.forEach((b, k) => {
const door = doorOf.get(b.id)!
const a = FRONT + deg(-40 + hash(b.id, 7) * 60)
const out: V2 = [door[0] + Math.cos(a) * U * (1.3 + hash(b.id, 8)), door[1] + Math.sin(a) * U * (1.3 + hash(b.id, 8))]
const soldier = village.military.some((m) => m.building_id === b.id)
walker(`visitor-${b.id}`, door, out, {
work: 2 + hash(b.id, 9) * 3,
rest: 6 + hash(b.id, 10) * 10,
indoors: true,
tool: soldier ? 'spear' : null,
soldier,
carry: b.type === 'storage' ? C.plank : null,
shirt: b.id,
begin: -k * 4.3,
})
})
// Crows cross the upper part of the view now and then, and circle over the graves and
// the gallows.
const birds: Scene['birds'] = [0, 1].map((k) => {
const y0 = view.y + h * (0.12 + 0.1 * k)
const across = bW / w
return { d: `M${(bX - U * 2).toFixed(1)} ${y0.toFixed(1)} L${(bX + bW + U * 2).toFixed(1)} ${(y0 - h * 0.08 * across).toFixed(1)}`, dur: (30 + k * 11) * across, begin: -k * 17 * across }
})
const circle = ([x, y]: V2, rx: number, k: number) => {
const [cx, cy] = project([x, y, U * (3.2 + k)])
const ry = rx * 0.4
return `M${(cx - rx).toFixed(1)} ${cy.toFixed(1)} A${rx.toFixed(1)} ${ry.toFixed(1)} 0 1 1 ${(cx + rx).toFixed(1)} ${cy.toFixed(1)} A${rx.toFixed(1)} ${ry.toFixed(1)} 0 1 1 ${(cx - rx).toFixed(1)} ${cy.toFixed(1)}`
}
const gallowsAt = hard.find((o) => o.key === 'gallows')
for (const [k, at] of [yard, yard, gallowsAt ? ([gallowsAt.x, gallowsAt.y] as V2) : null].entries()) {
if (at) birds.push({ d: circle(at, U * (1.6 + k * 0.5), k * 0.6), dur: 9 + k * 3, begin: -k * 4 })
}
objects.sort((a, b) => a.depth - b.depth)
return {
viewBox: `${view.x.toFixed(1)} ${view.y.toFixed(1)} ${w.toFixed(1)} ${h.toFixed(1)}`,
width: w,
height: h,
home: view,
bounds,
terrain: ground(bounds, { r0: Rz * 0.9, r1: Rz * 1.8 }),
// One at a time, so the layers keep the order they were added in.
decals: [...decalFaces, ...shadows].flatMap((face) => toPolys([face])),
// Wall segments keep their own outlines; the band below covers the stretches between.
objects: objects.map(({ key, polys, building, planned, life, walker }) => ({
key,
polys,
building: building ? { ...building, hit: hitOutline(polys, building.ring) } : undefined,
planned,
life,
walker,
})),
// Centred halfway up the palisade, so the band covers the wall itself, not only its foot.
wallBand: wall ? { id: wall.id, ring: { ...screenRing(0, 0, Rv), cy: -wallTop / 2 }, width: U * 1.6 + wallTop } : null,
plots,
timers,
smoke,
walks,
herds,
birds,
}
}