// 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 { type Face, hash, ngon, plane, type Poly, prism, project, pyramid, scale, toPolys, type V2, type V3 } from './iso' import { broadleaf, buildingModel, bush, C, conifer, crane, rock, scaffold, well } from './models' /** World units per unit of building space, roughly. */ 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> = { 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 = { iron: { angle: deg(196), half: deg(26), scale: 1.15, gap: 2.5, ground: '#7c776a' }, clay: { angle: deg(102), half: deg(24), scale: 1.1, gap: 2.4, ground: '#8d5a3b' }, timber: { angle: deg(8), half: deg(22), scale: 1.1, gap: 2.4, ground: '#76703f' }, farm: { angle: deg(-62), half: deg(27), scale: 1.3, gap: 2.6, ground: null }, } const ZONE_NAMES = Object.keys(ZONES) as Zone[] const GRASS = ['#7a8b48', '#778848', '#7d8d4a', '#748546'] const DIRT = '#9c8157' const PLAZA = '#a3885c' const VILLAGE_GROUND = '#868d4d' const WALL_EARTH = '#8c7350' 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 } /** * 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 } export interface Scene { viewBox: string /** viewBox size, for keeping badges a fixed size on screen. */ width: number height: number 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; seconds: 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 } /** Buildings that smoke, from this level on. */ const SMOKY: Partial> = { headquarters: 1, barracks: 1, workshop: 1, academy: 1, clay_pit: 1, iron_mine: 5 } const WATER = '#5f7f87' /** 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(' ') } 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. */ function ground(view: { x: number; y: number; w: number; h: 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) => GRASS[Math.floor(hash(i, j, k) * GRASS.length)]! faces.push({ pts: [a, b, c], color: tone(4), twoSided: true }, { pts: [a, c, d], color: tone(5), twoSided: true }) } } return toPolys(faces).map((p) => ({ ...p, stroke: p.fill })) } 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) } /** 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). */ 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 const faces: Face[] = [] for (let i = 0; i < n; i++) { const a0 = (i / n) * Math.PI * 2 const a1 = ((i + 1) / n) * Math.PI * 2 const r0 = r - width / 2 const r1 = r + width / 2 faces.push( plane( [ [Math.cos(a0) * r0, Math.sin(a0) * r0, 1], [Math.cos(a1) * r0, Math.sin(a1) * r0, 1], [Math.cos(a1) * r1, Math.sin(a1) * r1, 1], [Math.cos(a0) * r1, Math.sin(a0) * r1, 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. 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 } /** 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. */ export function buildScene(village: VillageState, frame: number | { width: number; height: number; inset?: SceneInset } = 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 = { 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 = { 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() const anchorOfOrder = new Map() // Buildings and queued new ones. 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 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 const padX = (maxX - minX) * 0.04 minX -= padX maxX += padX let w = maxX - minX let h = maxY - minY 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) const cx = (minX + maxX) / 2 const cy = (minY + maxY) / 2 w = frame.width / perUnit h = frame.height / perUnit minX = cx - (inset.left + freeW / 2) / perUnit minY = cy - (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 = { x: minX, y: minY, w, h } // 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))) } decalFaces.push(road(FRONT, hqRadius * 0.9, Rz * 3, PATH_HALF, 1)) for (const zone of activeZones) decalFaces.push(road(ZONES[zone].angle, hqRadius * 0.9, zoneEnd(zone) + U * 0.5, ZONE_PATH_HALF, ZONE_NAMES.indexOf(zone) + 2)) 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)) // 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 })) // 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), '#7d7348')) 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, '#5b6b2e', '#7a8a3a')) }) } } 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 } const f = U * 1.25 const cornersW = [inverse([view.x, view.y]), inverse([view.x + w, view.y]), inverse([view.x, view.y + h]), inverse([view.x + w, view.y + h])] 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 < view.x - U || X > view.x + w + U || Y < view.y || Y > view.y + h + 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 if (hash(i, j, 63) > Math.min(density, 0.88)) continue const kind = hash(i, j, 64) const size = U * (1.0 + 0.55 * hash(i, j, 65)) const seed = i * 131 + j const faces = kind < 0.1 ? bush(x, y, size * 0.8, seed) : kind < 0.62 ? conifer(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)) objects.push({ key: `t${i}:${j}`, depth: x + y, polys: toPolys(faces) }) } } // 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 walk from the plaza out to the zones they work in and back, more where more work. 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))), seconds: Math.max(16, ((end - hqRadius) / U) * 4.5) }) } walks.push({ d: walkPath(FRONT, hqRadius * 0.9, Rz * 3, 1, hqRadius * 1.4, Rv + U * 5), count: 1, seconds: 40 }) 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, terrain: ground(view), // 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 }) => ({ key, polys, building: building ? { ...building, hit: hitOutline(polys, building.ring) } : undefined, planned, })), // 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, } }