feat: isometric low-poly village diorama with building details card

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-28 19:54:20 +01:00
parent f5e03d3500
commit 3ab9156664
5 changed files with 1323 additions and 0 deletions

View File

@ -0,0 +1,108 @@
<script setup lang="ts">
import type { Building, Cost, Resources } from '~/types/game'
defineProps<{
building: Building
resources: Resources
canAfford: (cost: Cost) => boolean
busy: boolean
}>()
const emit = defineEmits<{
upgrade: [buildingId: number]
demolish: [buildingId: number]
priority: [buildingId: number, priority: number]
close: []
}>()
</script>
<!-- Details of the building selected in the diorama, with its actions. -->
<template>
<section class="panel bg-white/95 shadow-lg backdrop-blur" :aria-label="$t(`buildings.${building.type}`)">
<div class="flex items-center gap-3 border-b border-parchment-200 px-4 py-3">
<IconBuildingTile :type="building.type" class="size-11" />
<div class="min-w-0 flex-1">
<h2 class="truncate font-display text-lg font-semibold">{{ $t(`buildings.${building.type}`) }}</h2>
<p class="text-xs text-ink-500">
{{ $t('village.buildings.level_n', { level: building.level }) }}
<template v-if="building.space"> · {{ $t('village.build.space', { space: building.space }) }}</template>
</p>
</div>
<button type="button" class="btn btn-ghost p-1.5" :aria-label="$t('common.close')" :title="$t('common.close')" @click="emit('close')">
<IconUi name="close" class="size-4" />
</button>
</div>
<div class="space-y-4 px-4 py-3">
<div class="grid grid-cols-2 gap-3 text-sm">
<div>
<p class="text-xs text-ink-500">{{ $t('village.buildings.workers') }}</p>
<p class="tabular-nums">{{ building.workers.assigned }}/{{ building.workers.required }}</p>
<UiBar class="mt-1" :value="building.staffing" :tone="building.staffing < 1 ? 'rose' : 'emerald'" />
</div>
<div>
<p class="text-xs text-ink-500">{{ $t('village.buildings.output') }}</p>
<p v-if="building.production" class="flex items-center gap-1 tabular-nums">
<IconResource :resource="building.production.resource" class="size-4" />
{{ $t('village.resources.per_hour', { rate: formatRate(building.production.per_hour) }) }}
</p>
<p v-else class="text-ink-400">–</p>
</div>
</div>
<div class="flex items-center justify-between gap-3 text-sm">
<span class="text-ink-500">{{ $t('village.buildings.priority') }}</span>
<div class="inline-flex items-center rounded-lg ring-1 ring-parchment-300">
<button
type="button"
class="btn btn-ghost rounded-r-none p-1"
:aria-label="$t('village.buildings.priority_down')"
:disabled="busy || building.priority <= 0"
@click="emit('priority', building.id, building.priority - 1)"
>
<IconUi name="minus" class="size-3.5" />
</button>
<span class="w-6 text-center font-semibold tabular-nums">{{ building.priority }}</span>
<button
type="button"
class="btn btn-ghost rounded-l-none p-1"
:aria-label="$t('village.buildings.priority_up')"
:disabled="busy || building.priority >= 9"
@click="emit('priority', building.id, building.priority + 1)"
>
<IconUi name="plus" class="size-3.5" />
</button>
</div>
</div>
<div v-if="building.upgrade" class="space-y-1.5 rounded-lg bg-parchment-50 p-3 ring-1 ring-parchment-200">
<div class="flex items-center justify-between gap-2 text-xs text-ink-500">
<UiCost :cost="building.upgrade.cost" :have="resources" />
<span class="flex items-center gap-1 tabular-nums">
<IconUi name="clock" class="size-3" />
{{ formatDuration(building.upgrade.seconds) }}
</span>
</div>
<button
type="button"
class="btn btn-primary w-full"
:disabled="busy || !canAfford(building.upgrade.cost)"
@click="emit('upgrade', building.id)"
>
<IconUi name="up" class="size-3.5" />
{{ $t('village.buildings.upgrade', { level: building.upgrade.target_level }) }}
</button>
</div>
<p v-else class="text-sm text-ink-500">{{ $t('village.blocked.max_level') }}</p>
<div v-if="building.demolish" class="flex items-center justify-between gap-2 text-xs text-ink-500">
<span class="flex flex-wrap items-center gap-1.5">
{{ $t('village.buildings.refund') }}
<UiCost :cost="building.demolish.refund" />
</span>
<button type="button" class="btn btn-danger" :disabled="busy" @click="emit('demolish', building.id)">
{{ $t('village.buildings.demolish') }}
</button>
</div>
</div>
</section>
</template>

View File

@ -0,0 +1,196 @@
<script setup lang="ts">
import type { VillageState } from '~/types/game'
import { buildScene, type SceneBuilding } from '~/diorama/scene'
const props = defineProps<{ village: VillageState }>()
/** Id of the building whose details are open. */
const selected = defineModel<number | null>('selected', { default: null })
const { t } = useI18n()
const scene = computed(() => buildScene(props.village))
const hovered = ref<number | null>(null)
const uid = useId()
const name = (b: SceneBuilding) => t(`buildings.${b.type}`)
const label = (b: SceneBuilding) => t('village.diorama.label', { name: name(b), level: b.level })
const badges = computed(() => scene.value.objects.flatMap((o) => (o.building?.focusable ? [o.building] : [])))
const isActive = (id: number) => selected.value === id || hovered.value === id
function toggle(id: number) {
selected.value = selected.value === id ? null : id
}
// Badges keep the same size on screen however the scene is scaled.
const svg = ref<SVGSVGElement | null>(null)
const unitsPerPx = ref(1)
function measure() {
const el = svg.value
if (!el) return
const [, , w, h] = scene.value.viewBox.split(' ').map(Number) as [number, number, number, number]
const scale = Math.min(el.clientWidth / w, el.clientHeight / h)
// Smaller badges on phones, where the whole village is only a few hundred pixels wide.
if (scale > 0) unitsPerPx.value = (el.clientWidth < 640 ? 0.75 : 1) / scale
}
let observer: ResizeObserver | undefined
onMounted(() => {
measure()
observer = new ResizeObserver(measure)
if (svg.value) observer.observe(svg.value)
})
onBeforeUnmount(() => observer?.disconnect())
watch(() => scene.value.viewBox, () => nextTick(measure))
const k = computed(() => unitsPerPx.value)
const pillWidth = (b: SceneBuilding) => (name(b).length * 6.6 + 18) * k.value
</script>
<template>
<div class="relative h-full w-full">
<!-- Backdrop across the full width: sky, haze and far hills. -->
<svg class="absolute inset-0 h-full w-full" viewBox="0 0 1600 600" preserveAspectRatio="xMidYMax slice" aria-hidden="true">
<defs>
<linearGradient :id="`${uid}-sky`" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#cfe3ee" />
<stop offset="0.6" stop-color="#eef1e2" />
<stop offset="1" stop-color="#f3ead6" />
</linearGradient>
</defs>
<rect width="1600" height="600" :fill="`url(#${uid}-sky)`" />
<g fill="#fff" opacity="0.75">
<polygon points="180,120 230,98 300,104 338,124 300,138 210,138" />
<polygon points="1180,86 1236,66 1310,72 1352,92 1300,106 1206,104" />
<polygon points="760,64 800,50 850,56 874,70 838,80 778,78" />
</g>
<polygon points="0,430 140,392 260,410 400,368 540,402 700,380 860,410 1010,372 1160,398 1320,366 1460,396 1600,378 1600,600 0,600" fill="#c9d8b6" />
<polygon points="0,468 180,440 330,458 470,432 640,456 800,438 960,462 1120,436 1290,458 1450,440 1600,452 1600,600 0,600" fill="#b7c99d" />
<rect y="500" width="1600" height="100" fill="#efe6d1" opacity="0.65" />
</svg>
<svg
ref="svg"
class="relative h-full w-full select-none"
:viewBox="scene.viewBox"
preserveAspectRatio="xMidYMid meet"
role="group"
:aria-label="$t('village.diorama.title')"
@click="selected = null"
>
<defs>
<radialGradient :id="`${uid}-shadow`">
<stop offset="0" stop-color="#3b2f22" stop-opacity="0.32" />
<stop offset="1" stop-color="#3b2f22" stop-opacity="0" />
</radialGradient>
</defs>
<ellipse v-bind="scene.shadow" :fill="`url(#${uid}-shadow)`" />
<g stroke-width="0.6" stroke-linejoin="round">
<polygon v-for="(p, i) in scene.terrain" :key="`t${i}`" :points="p.points" :fill="p.fill" :stroke="p.stroke" />
<polygon v-for="(p, i) in scene.decals" :key="`d${i}`" :points="p.points" :fill="p.fill" :stroke="p.stroke" />
</g>
<template v-for="obj in scene.objects" :key="obj.key">
<g
v-if="obj.building"
v-memo="[obj, isActive(obj.building.id), selected === obj.building.id]"
class="bld"
:class="{ 'is-active': isActive(obj.building.id), 'is-selected': selected === obj.building.id }"
:role="obj.building.focusable ? 'button' : undefined"
:tabindex="obj.building.focusable ? 0 : -1"
:aria-hidden="obj.building.focusable ? undefined : 'true'"
:aria-label="obj.building.focusable ? label(obj.building) : undefined"
:aria-pressed="obj.building.focusable ? selected === obj.building.id : undefined"
stroke-width="0.6"
stroke-linejoin="round"
@click.stop="toggle(obj.building.id)"
@keydown.enter.prevent="toggle(obj.building.id)"
@keydown.space.prevent="toggle(obj.building.id)"
@mouseenter="hovered = obj.building.id"
@mouseleave="hovered = null"
@focus="hovered = obj.building.id"
@blur="hovered = null"
>
<ellipse v-if="obj.building.ring.rx" class="ring" v-bind="obj.building.ring" />
<polygon
v-for="(p, i) in obj.polys"
:key="i"
:points="p.points"
:fill="p.fill"
:stroke="p.stroke"
:fill-opacity="p.opacity"
/>
<title>{{ label(obj.building) }}</title>
</g>
<g v-else v-memo="[obj]" stroke-width="0.6" stroke-linejoin="round" :opacity="obj.planned ? 0.7 : 1">
<polygon
v-for="(p, i) in obj.polys"
:key="i"
:points="p.points"
:fill="p.fill"
:stroke="p.stroke"
:fill-opacity="p.opacity"
/>
<title v-if="obj.planned">{{ $t('village.diorama.planned') }}</title>
</g>
</template>
<!-- Level badges and, for the hovered or selected building, its name. -->
<g class="pointer-events-none" font-family="ui-sans-serif, system-ui, sans-serif" text-anchor="middle">
<g v-for="b in badges" :key="`badge-${b.id}`" :transform="`translate(${b.label[0]} ${b.label[1]})`">
<g v-if="isActive(b.id)">
<rect
:x="-pillWidth(b) / 2"
:y="-30 * k"
:width="pillWidth(b)"
:height="20 * k"
:rx="10 * k"
fill="#2b2118"
fill-opacity="0.86"
/>
<text :y="-16 * k" :font-size="12 * k" font-weight="600" fill="#fff">{{ name(b) }}</text>
</g>
<circle
:r="10 * k"
:fill="b.upgrading ? '#f59e0b' : '#fffaf0'"
:stroke="isActive(b.id) ? '#b45309' : '#a1835e'"
:stroke-width="1.5 * k"
/>
<text :y="4 * k" :font-size="11 * k" font-weight="700" :fill="b.upgrading ? '#fff' : '#4a3b2e'">{{ b.level }}</text>
</g>
</g>
</svg>
</div>
</template>
<style scoped>
.bld {
cursor: pointer;
outline: none;
transition: transform 0.15s ease;
}
.bld.is-active {
transform: translateY(-3px);
}
.ring {
fill: transparent;
stroke: transparent;
}
.bld.is-active .ring {
fill: rgb(251 191 36 / 0.22);
stroke: #d97706;
stroke-width: 1.2;
}
.bld.is-selected .ring {
fill: rgb(251 191 36 / 0.32);
stroke: #b45309;
stroke-width: 2;
}
.bld.is-selected polygon {
stroke: #b45309;
stroke-width: 1;
}
.bld:focus-visible .ring {
stroke: #b45309;
stroke-width: 2;
stroke-dasharray: 4 3;
}
</style>

268
app/diorama/iso.ts Normal file
View File

@ -0,0 +1,268 @@
// Isometric low-poly geometry for the village diorama.
//
// World space: x and y on the ground, z up, right-handed. The 2:1 projection puts +x
// towards the lower right and +y towards the lower left, so the viewer looks along
// −(1, 1, 1): a face is visible when its outward normal points towards +(1, 1, 1).
export type V2 = [number, number]
export type V3 = [number, number, number]
export interface Face {
pts: V3[]
color: string
/** Planes like fields and banners: shown from either side. */
twoSided?: boolean
/** Skip light shading, e.g. for glowing fire. */
flat?: boolean
opacity?: number
}
export interface Poly {
points: string
fill: string
stroke: string
opacity: number
}
const VIEW: V3 = [1, 1, 1]
const LIGHT = unit([-0.35, 0.45, 0.82])
const LIGHT_TOP = LIGHT[2]
export function project([x, y, z]: V3): V2 {
return [x - y, (x + y) / 2 - z]
}
/** Painter's order key: larger is closer to the viewer. */
export const depthOf = ([x, y, z]: V3) => x + y + z
function unit(v: V3): V3 {
const l = Math.hypot(v[0], v[1], v[2]) || 1
return [v[0] / l, v[1] / l, v[2] / l]
}
const dot = (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
/** Newell's method: the normal of a planar polygon in the order its points are given. */
function normal(pts: V3[]): V3 {
let nx = 0
let ny = 0
let nz = 0
for (let i = 0; i < pts.length; i++) {
const [x1, y1, z1] = pts[i]!
const [x2, y2, z2] = pts[(i + 1) % pts.length]!
nx += (y1 - y2) * (z1 + z2)
ny += (z1 - z2) * (x1 + x2)
nz += (x1 - x2) * (y1 + y2)
}
return unit([nx, ny, nz])
}
function centroid(pts: V3[]): V3 {
const c: V3 = [0, 0, 0]
for (const p of pts) {
c[0] += p[0]
c[1] += p[1]
c[2] += p[2]
}
return [c[0] / pts.length, c[1] / pts.length, c[2] / pts.length]
}
// Colours
function rgb(hex: string): V3 {
const n = Number.parseInt(hex.slice(1), 16)
return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
}
function hex([r, g, b]: V3): string {
const c = (v: number) => Math.round(Math.min(255, Math.max(0, v))).toString(16).padStart(2, '0')
return `#${c(r)}${c(g)}${c(b)}`
}
export function scale(color: string, k: number): string {
const [r, g, b] = rgb(color)
return hex([r * k, g * k, b * k])
}
export function mix(a: string, b: string, t: number): string {
const x = rgb(a)
const y = rgb(b)
return hex([x[0] + (y[0] - x[0]) * t, x[1] + (y[1] - x[1]) * t, x[2] + (y[2] - x[2]) * t])
}
/** Light from the upper left: tops keep their colour, left faces dim a little, right faces more. */
function shade(color: string, n: V3): string {
return scale(color, 0.6 + (0.4 * Math.max(0, dot(n, LIGHT))) / LIGHT_TOP)
}
/** Deterministic 0..1 noise for stable variety (same input, same output). */
export function hash(...n: number[]): number {
let h = 2166136261
for (const v of n) {
h ^= Math.round(v * 1000)
h = Math.imul(h, 16777619)
}
h ^= h >>> 13
h = Math.imul(h, 2246822507)
h ^= h >>> 16
return (h >>> 0) / 4294967295
}
// Faces → SVG polygons
export function toPolys(faces: Face[], offset: V3 = [0, 0, 0]): Poly[] {
const out: { poly: Poly; depth: number }[] = []
for (const f of faces) {
const pts = f.pts.map((p): V3 => [p[0] + offset[0], p[1] + offset[1], p[2] + offset[2]])
let n = normal(pts)
if (dot(n, VIEW) <= 0) {
if (!f.twoSided) continue
n = [-n[0], -n[1], -n[2]]
}
const fill = f.flat ? f.color : shade(f.color, n)
out.push({
depth: depthOf(centroid(pts)),
poly: {
points: pts.map((p) => project(p).map((v) => v.toFixed(1)).join(',')).join(' '),
fill,
stroke: scale(fill, 0.86),
opacity: f.opacity ?? 1,
},
})
}
// Faces of one object: back to front.
return out.sort((a, b) => a.depth - b.depth).map((o) => o.poly)
}
/** Flip a face if its normal points towards `inside`, so it faces outward. */
export function orient(pts: V3[], inside: V3): V3[] {
const n = normal(pts)
const c = centroid(pts)
return dot(n, [c[0] - inside[0], c[1] - inside[1], c[2] - inside[2]]) < 0 ? [...pts].reverse() : pts
}
// Shapes. Bases are counter-clockwise seen from above.
export function rect(cx: number, cy: number, w: number, d: number): V2[] {
return [
[cx - w / 2, cy - d / 2],
[cx + w / 2, cy - d / 2],
[cx + w / 2, cy + d / 2],
[cx - w / 2, cy + d / 2],
]
}
export function ngon(cx: number, cy: number, r: number, n: number, rot = 0): V2[] {
return Array.from({ length: n }, (_, i): V2 => {
const a = rot + (i / n) * Math.PI * 2
return [cx + Math.cos(a) * r, cy + Math.sin(a) * r]
})
}
/** An upright prism: a box, a hexagonal post, a wall segment. */
export function prism(base: V2[], z0: number, h: number, color: string, top = color): Face[] {
const z1 = z0 + h
const faces: Face[] = [{ pts: base.map(([x, y]): V3 => [x, y, z1]), color: top }]
base.forEach(([x1, y1], i) => {
const [x2, y2] = base[(i + 1) % base.length]!
faces.push({ pts: [[x1, y1, z0], [x2, y2, z0], [x2, y2, z1], [x1, y1, z1]], color })
})
return faces
}
export const box = (cx: number, cy: number, w: number, d: number, z0: number, h: number, color: string, top = color) =>
prism(rect(cx, cy, w, d), z0, h, color, top)
/** A pyramid or cone (many-sided base) with its apex above `apex` (default: the centre). */
export function pyramid(base: V2[], z0: number, h: number, color: string, apex?: V2): Face[] {
const [ax, ay] = apex ?? [base.reduce((s, p) => s + p[0], 0) / base.length, base.reduce((s, p) => s + p[1], 0) / base.length]
const top: V3 = [ax, ay, z0 + h]
return base.map(([x1, y1], i) => {
const [x2, y2] = base[(i + 1) % base.length]!
return { pts: [[x1, y1, z0], [x2, y2, z0], top], color }
})
}
/** A gable roof over the rectangle [x0, x1] × [y0, y1] at height z, ridge along x or y. */
export function gable(
x0: number,
y0: number,
x1: number,
y1: number,
z: number,
rise: number,
along: 'x' | 'y',
color: string,
ends: string,
): Face[] {
const inside: V3 = [(x0 + x1) / 2, (y0 + y1) / 2, z + rise / 3]
const r = z + rise
const faces: Face[] =
along === 'x'
? (() => {
const ym = (y0 + y1) / 2
return [
{ pts: [[x0, y1, z], [x1, y1, z], [x1, ym, r], [x0, ym, r]] as V3[], color },
{ pts: [[x0, y0, z], [x1, y0, z], [x1, ym, r], [x0, ym, r]] as V3[], color },
{ pts: [[x0, y0, z], [x0, y1, z], [x0, ym, r]] as V3[], color: ends },
{ pts: [[x1, y0, z], [x1, y1, z], [x1, ym, r]] as V3[], color: ends },
]
})()
: (() => {
const xm = (x0 + x1) / 2
return [
{ pts: [[x1, y0, z], [x1, y1, z], [xm, y1, r], [xm, y0, r]] as V3[], color },
{ pts: [[x0, y0, z], [x0, y1, z], [xm, y1, r], [xm, y0, r]] as V3[], color },
{ pts: [[x0, y0, z], [x1, y0, z], [xm, y0, r]] as V3[], color: ends },
{ pts: [[x0, y1, z], [x1, y1, z], [xm, y1, r]] as V3[], color: ends },
]
})()
return faces.map((f) => ({ ...f, pts: orient(f.pts, inside) }))
}
/** A box with a gable roof: the most common house. */
export function house(
cx: number,
cy: number,
w: number,
d: number,
h: number,
rise: number,
walls: string,
roof: string,
along: 'x' | 'y' = w >= d ? 'x' : 'y',
): Face[] {
const o = Math.min(w, d) * 0.08
return [
...box(cx, cy, w, d, 0, h, walls),
...gable(cx - w / 2 - o, cy - d / 2 - o, cx + w / 2 + o, cy + d / 2 + o, h, rise, along, roof, walls),
]
}
/** A log lying along x: a hexagonal prism on its side. */
export function log(cx: number, cy: number, z: number, len: number, r: number, color: string, cut: string): Face[] {
const ring = Array.from({ length: 6 }, (_, i): V2 => {
const a = (i / 6) * Math.PI * 2
return [cy + Math.cos(a) * r, z + r + Math.sin(a) * r]
})
const x0 = cx - len / 2
const x1 = cx + len / 2
const inside: V3 = [cx, cy, z + r]
const faces: Face[] = ring.map(([y1, z1], i) => {
const [y2, z2] = ring[(i + 1) % 6]!
return { pts: orient([[x0, y1, z1], [x1, y1, z1], [x1, y2, z2], [x0, y2, z2]], inside), color }
})
faces.push({ pts: orient(ring.map(([y, zz]): V3 => [x1, y, zz]), inside), color: cut })
faces.push({ pts: orient(ring.map(([y, zz]): V3 => [x0, y, zz]), inside), color: cut })
return faces
}
/** A flat, two-sided quad on the ground (fields, pits, paths) or upright (banners). */
export function plane(pts: V3[], color: string, opacity?: number): Face {
return { pts, color, twoSided: true, opacity }
}
/** Every face moved by (dx, dy, dz). */
export function shift(faces: Face[], dx: number, dy: number, dz = 0): Face[] {
return faces.map((f) => ({ ...f, pts: f.pts.map(([x, y, z]): V3 => [x + dx, y + dy, z + dz]) }))
}

458
app/diorama/models.ts Normal file
View File

@ -0,0 +1,458 @@
// Low-poly building models for the diorama, one per type and level tier. Each fits in
// the square [-s, s] around its own origin and returns its faces and roof height.
// Original shapes in the genre's style: tents and lean-tos at level 0, timber next,
// stone and bigger at high levels.
import type { BuildingType } from '~/types/game'
import { box, type Face, hash, house, log, ngon, plane, prism, pyramid, rect, shift, type V2, type V3 } from './iso'
export const C = {
wood: '#b98552',
woodDark: '#8d5f36',
plank: '#cfa16a',
thatch: '#d9b65f',
canvas: '#ece2ca',
canvasDark: '#d7c6a2',
roofRed: '#b9573c',
slate: '#6a7482',
stone: '#b9b3a8',
stoneDark: '#948e85',
field: '#a8c65e',
wheat: '#e3c45f',
furrow: '#c9a24e',
soil: '#9c744a',
leaf: '#5f9c46',
leafDark: '#4b8439',
trunk: '#7b5333',
clay: '#cc7a4f',
clayDark: '#a65a37',
clayWet: '#b9683f',
rock: '#8e8983',
ore: '#5e6a78',
fire: '#f4a53b',
banner: '#b9443a',
hay: '#e6cb6c',
cloth: '#7a5f4a',
skin: '#e7bb92',
dark: '#3e342b',
grass: '#86b456',
}
export interface Model {
faces: Face[]
/** Highest point, for the level badge. */
height: number
}
/** 0 at level 0, 1 for 1–4, 2 for 5–14, 3 from 15 on. */
export const tier = (level: number) => (level <= 0 ? 0 : level < 5 ? 1 : level < 15 ? 2 : 3)
// Small props
function post(x: number, y: number, h: number, r: number, color = C.woodDark): Face[] {
return prism(rect(x, y, r * 2, r * 2), 0, h, color)
}
function banner(x: number, y: number, h: number, size: number, color = C.banner): Face[] {
return [
...post(x, y, h, size * 0.035),
plane(
[
[x, y, h],
[x - size * 0.05, y + size * 0.75, h - size * 0.1],
[x - size * 0.05, y + size * 0.75, h - size * 0.5],
[x, y, h - size * 0.42],
],
color,
),
]
}
function crate(x: number, y: number, z: number, a: number): Face[] {
return box(x, y, a, a, z, a, C.plank, C.wood)
}
export function tree(x: number, y: number, size: number, seed = 0): Face[] {
const leaf = hash(seed, 3) > 0.5 ? C.leaf : C.leafDark
const rot = hash(seed, 7) * Math.PI
return [
...prism(ngon(x, y, size * 0.09, 5, rot), 0, size * 0.32, C.trunk),
...pyramid(ngon(x, y, size * 0.48, 6, rot), size * 0.25, size * 0.75, leaf),
...pyramid(ngon(x, y, size * 0.34, 6, rot + 0.4), size * 0.68, size * 0.62, leaf),
]
}
export function rock(x: number, y: number, size: number, seed = 0): Face[] {
const base = ngon(x, y, size * 0.5, 5, hash(seed, 1) * 6).map(([px, py], i): V2 => {
const k = 0.75 + 0.45 * hash(seed, i)
return [x + (px - x) * k, y + (py - y) * k]
})
return pyramid(base, 0, size * (0.45 + 0.3 * hash(seed, 9)), C.rock, [x + size * 0.08, y - size * 0.06])
}
function person(x: number, y: number, s: number, shirt = C.cloth): Face[] {
const r = s * 0.06
return [...prism(ngon(x, y, r, 5), 0, s * 0.2, shirt), ...box(x, y, r * 1.3, r * 1.3, s * 0.2, r * 1.4, C.skin)]
}
function field(x: number, y: number, w: number, d: number, color: string, rows: number): Face[] {
const faces: Face[] = [plane(rect(x, y, w, d).map(([px, py]) => [px, py, 0.6]), color)]
for (let i = 1; i < rows; i++) {
const fx = x - w / 2 + (w * i) / rows
faces.push(plane([[fx - 0.5, y - d / 2 + 1, 0.8], [fx + 0.5, y - d / 2 + 1, 0.8], [fx + 0.5, y + d / 2 - 1, 0.8], [fx - 0.5, y + d / 2 - 1, 0.8]], C.furrow))
}
return faces
}
function logPile(x: number, y: number, s: number, rows = 2): Face[] {
const r = s * 0.09
const faces: Face[] = []
for (let row = 0; row < rows; row++) {
const n = 3 - row
for (let i = 0; i < n; i++) faces.push(...log(x, y - (n - 1) * r + i * r * 2, row * r * 1.7, s * 0.7, r, C.wood, C.plank))
}
return faces
}
function bricks(x: number, y: number, s: number, layers: number): Face[] {
const faces: Face[] = []
for (let i = 0; i < layers; i++) faces.push(...box(x, y, s * 0.3, s * 0.2, i * s * 0.08, s * 0.08, i % 2 ? C.clayDark : C.clay))
return faces
}
function fire(x: number, y: number, s: number): Face[] {
const faces: Face[] = []
for (const [px, py] of ngon(x, y, s * 0.12, 6)) faces.push(...box(px, py, s * 0.05, s * 0.05, 0, s * 0.04, C.rock))
faces.push(...pyramid(ngon(x, y, s * 0.07, 4), 0, s * 0.2, C.fire).map((f) => ({ ...f, flat: true })))
return faces
}
function kiln(x: number, y: number, s: number): Face[] {
return [
...prism(ngon(x, y, s * 0.32, 7), 0, s * 0.4, C.clay, C.clayDark),
...pyramid(ngon(x, y, s * 0.32, 7), s * 0.4, s * 0.28, C.clayDark),
...box(x + s * 0.05, y - s * 0.05, s * 0.1, s * 0.1, s * 0.5, s * 0.35, C.stoneDark),
]
}
function headframe(x: number, y: number, s: number, h: number): Face[] {
const a = s * 0.28
return [
...post(x - a, y - a, h, s * 0.04),
...post(x + a, y - a, h, s * 0.04),
...post(x - a, y + a, h, s * 0.04),
...post(x + a, y + a, h, s * 0.04),
...box(x, y, a * 2.3, a * 2.3, h, s * 0.06, C.wood),
...pyramid(rect(x, y, a * 2.3, a * 2.3), h + s * 0.06, s * 0.25, C.woodDark),
]
}
// Buildings
const models: Record<BuildingType, (s: number, t: number) => Model> = {
headquarters(s, t) {
if (t === 0) {
return {
faces: [
...pyramid(ngon(0, 0, s * 0.62, 6, 0.3), 0, s * 1.0, C.canvas),
...pyramid(ngon(s * 0.05, s * 0.05, s * 0.2, 6, 0.3), s * 0.85, s * 0.25, C.canvasDark),
...fire(s * 0.62, s * 0.58, s),
...banner(-s * 0.6, s * 0.55, s * 1.25, s * 0.6),
],
height: s * 1.25,
}
}
if (t === 1) {
return {
faces: [
...house(0, 0, s * 1.35, s * 1.0, s * 0.5, s * 0.5, C.wood, C.thatch),
...banner(s * 0.85, -s * 0.6, s * 1.25, s * 0.55),
...fire(s * 0.7, s * 0.72, s),
],
height: s * 1.25,
}
}
if (t === 2) {
return {
faces: [
...box(0, 0, s * 1.6, s * 1.2, 0, s * 0.14, C.stoneDark, C.stone),
...shift(house(0, 0, s * 1.45, s * 1.05, s * 0.5, s * 0.55, C.plank, C.roofRed), 0, 0, s * 0.14),
...box(-s * 0.62, -s * 0.48, s * 0.5, s * 0.5, 0, s * 1.25, C.stone),
...pyramid(rect(-s * 0.62, -s * 0.48, s * 0.6, s * 0.6), s * 1.25, s * 0.45, C.roofRed),
...banner(s * 0.85, s * 0.7, s * 1.3, s * 0.55),
],
height: s * 1.7,
}
}
return {
faces: [
...box(0, 0, s * 1.35, s * 1.35, 0, s * 0.9, C.stone, C.stoneDark),
...pyramid(rect(0, 0, s * 1.5, s * 1.5), s * 0.9, s * 0.65, C.slate),
...prism(ngon(-s * 0.72, s * 0.72, s * 0.28, 6), 0, s * 1.3, C.stone),
...pyramid(ngon(-s * 0.72, s * 0.72, s * 0.34, 6), s * 1.3, s * 0.45, C.slate),
...prism(ngon(s * 0.72, -s * 0.72, s * 0.28, 6), 0, s * 1.3, C.stone),
...pyramid(ngon(s * 0.72, -s * 0.72, s * 0.34, 6), s * 1.3, s * 0.45, C.slate),
...banner(0, 0, s * 2.0, s * 0.6),
],
height: s * 2.0,
}
},
storage(s, t) {
if (t === 0) {
const back = s * 0.85
const front = s * 0.5
return {
faces: [
...post(-s * 0.6, -s * 0.5, back, s * 0.05),
...post(s * 0.6, -s * 0.5, back, s * 0.05),
...post(-s * 0.6, s * 0.5, front, s * 0.05),
...post(s * 0.6, s * 0.5, front, s * 0.05),
plane([[-s * 0.75, -s * 0.6, back], [s * 0.75, -s * 0.6, back], [s * 0.75, s * 0.62, front], [-s * 0.75, s * 0.62, front]], C.plank),
...crate(-s * 0.25, 0, 0, s * 0.3),
...crate(s * 0.15, s * 0.05, 0, s * 0.3),
...crate(-s * 0.05, -s * 0.05, s * 0.3, s * 0.26),
...pyramid(ngon(s * 0.75, s * 0.75, s * 0.12, 5), 0, s * 0.22, C.canvasDark),
],
height: back,
}
}
if (t === 1) return { faces: [...house(0, 0, s * 1.15, s * 1.0, s * 0.55, s * 0.4, C.wood, C.woodDark, 'y'), ...crate(s * 0.75, s * 0.7, 0, s * 0.28)], height: s * 0.95 }
if (t === 2) {
return {
faces: [
...house(0, -s * 0.1, s * 1.5, s * 1.1, s * 0.75, s * 0.55, C.plank, C.roofRed),
plane([[s * 0.76, -s * 0.28, 0], [s * 0.76, s * 0.08, 0], [s * 0.76, s * 0.08, s * 0.45], [s * 0.76, -s * 0.28, s * 0.45]], C.dark),
...crate(s * 0.55, s * 0.78, 0, s * 0.26),
...crate(s * 0.2, s * 0.8, 0, s * 0.26),
],
height: s * 1.3,
}
}
return {
faces: [
...house(-s * 0.1, -s * 0.1, s * 1.55, s * 1.25, s * 0.85, s * 0.55, C.stone, C.slate),
...house(s * 0.7, s * 0.65, s * 0.55, s * 0.5, s * 0.4, s * 0.25, C.wood, C.woodDark),
...crate(-s * 0.55, s * 0.8, 0, s * 0.26),
],
height: s * 1.4,
}
},
farm(s, t) {
if (t === 0) {
return {
faces: [
...field(0, 0, s * 1.5, s * 1.2, C.wheat, 5),
...person(-s * 0.2, s * 0.15, s),
...person(s * 0.35, -s * 0.2, s, C.soil),
...pyramid(ngon(s * 0.85, s * 0.75, s * 0.13, 6), 0, s * 0.16, C.hay),
],
height: s * 0.4,
}
}
if (t === 1) {
return {
faces: [
...field(0, s * 0.3, s * 1.6, s * 1.0, C.wheat, 6),
...house(-s * 0.35, -s * 0.65, s * 0.7, s * 0.55, s * 0.4, s * 0.35, C.wood, C.thatch),
...person(s * 0.3, s * 0.3, s),
],
height: s * 0.8,
}
}
if (t === 2) {
return {
faces: [
...field(-s * 0.4, s * 0.35, s * 1.05, s * 1.1, C.wheat, 4),
...field(s * 0.55, s * 0.35, s * 0.75, s * 1.1, C.field, 3),
...house(-s * 0.2, -s * 0.65, s * 0.9, s * 0.6, s * 0.45, s * 0.4, C.plank, C.roofRed),
...pyramid(ngon(s * 0.65, -s * 0.6, s * 0.22, 7), 0, s * 0.42, C.hay),
],
height: s * 0.85,
}
}
return {
faces: [
...field(-s * 0.3, s * 0.45, s * 1.3, s * 0.95, C.wheat, 5),
...field(s * 0.7, s * 0.45, s * 0.55, s * 0.95, C.field, 2),
...house(-s * 0.3, -s * 0.6, s * 1.1, s * 0.7, s * 0.6, s * 0.45, C.roofRed, C.slate),
...prism(ngon(s * 0.65, -s * 0.6, s * 0.22, 7), 0, s * 1.1, C.stone),
...pyramid(ngon(s * 0.65, -s * 0.6, s * 0.26, 7), s * 1.1, s * 0.3, C.slate),
],
height: s * 1.4,
}
},
timber_camp(s, t) {
if (t === 0) {
return {
faces: [...logPile(0, s * 0.2, s, 2), ...prism(ngon(-s * 0.55, -s * 0.4, s * 0.12, 6), 0, s * 0.14, C.wood, C.plank), ...tree(s * 0.55, -s * 0.55, s * 1.1, 1)],
height: s * 1.1,
}
}
if (t === 1) {
return {
faces: [
...logPile(s * 0.2, s * 0.45, s, 2),
...post(-s * 0.75, -s * 0.15, s * 0.6, s * 0.04),
...post(-s * 0.15, -s * 0.15, s * 0.6, s * 0.04),
...post(-s * 0.75, -s * 0.75, s * 0.75, s * 0.04),
...post(-s * 0.15, -s * 0.75, s * 0.75, s * 0.04),
plane([[-s * 0.85, -s * 0.85, s * 0.75], [-s * 0.05, -s * 0.85, s * 0.75], [-s * 0.05, -s * 0.05, s * 0.6], [-s * 0.85, -s * 0.05, s * 0.6]], C.woodDark),
...tree(s * 0.6, -s * 0.55, s * 1.1, 2),
...tree(-s * 0.7, s * 0.65, s * 0.9, 3),
],
height: s * 1.1,
}
}
if (t === 2) {
return {
faces: [
...house(-s * 0.2, -s * 0.35, s * 1.1, s * 0.8, s * 0.5, s * 0.4, C.wood, C.plank),
...logPile(s * 0.25, s * 0.6, s, 2),
...tree(s * 0.7, -s * 0.6, s * 1.1, 4),
...tree(-s * 0.75, s * 0.7, s, 5),
],
height: s * 1.1,
}
}
return {
faces: [
...house(-s * 0.15, -s * 0.3, s * 1.35, s * 0.95, s * 0.6, s * 0.45, C.plank, C.roofRed),
...logPile(-s * 0.3, s * 0.7, s, 3),
...box(s * 0.55, s * 0.6, s * 0.5, s * 0.25, 0, s * 0.18, C.plank),
...tree(s * 0.75, -s * 0.7, s * 1.2, 6),
],
height: s * 1.2,
}
},
clay_pit(s, t) {
const pit = (x: number, y: number, r: number): Face[] => [
plane(ngon(x, y, r, 7, 0.2).map(([px, py]) => [px, py, 0.4]), C.clayDark),
plane(ngon(x, y, r * 0.65, 7, 0.5).map(([px, py]) => [px, py, 0.6]), C.clayWet),
]
if (t === 0) {
return {
faces: [...pit(-s * 0.1, s * 0.1, s * 0.6), ...pyramid(ngon(s * 0.6, -s * 0.55, s * 0.3, 6), 0, s * 0.3, C.clay), ...person(s * 0.15, -s * 0.3, s)],
height: s * 0.4,
}
}
if (t === 1) {
return {
faces: [...pit(-s * 0.2, s * 0.2, s * 0.6), ...bricks(s * 0.6, -s * 0.45, s, 4), ...bricks(s * 0.25, -s * 0.7, s, 3), ...person(s * 0.4, s * 0.3, s)],
height: s * 0.45,
}
}
if (t === 2) {
return {
faces: [...pit(-s * 0.3, s * 0.3, s * 0.55), ...kiln(s * 0.35, -s * 0.35, s), ...bricks(s * 0.65, s * 0.55, s, 5)],
height: s * 0.85,
}
}
return {
faces: [
...pit(-s * 0.35, s * 0.4, s * 0.5),
...kiln(s * 0.45, -s * 0.15, s),
...kiln(-s * 0.35, -s * 0.55, s),
...bricks(s * 0.65, s * 0.65, s, 6),
],
height: s * 0.85,
}
},
iron_mine(s, t) {
const outcrop = (k: number) => pyramid(ngon(-s * 0.2, -s * 0.25, s * 0.75 * k, 6, 0.4), 0, s * 0.95 * k, C.rock, [-s * 0.35, -s * 0.45])
const mouth = plane([[s * 0.32, -s * 0.35, 0], [s * 0.32, -s * 0.05, 0], [s * 0.2, -s * 0.05, s * 0.3], [s * 0.2, -s * 0.35, s * 0.3]], C.dark)
const ore = (x: number, y: number) => pyramid(ngon(x, y, s * 0.18, 5), 0, s * 0.18, C.ore)
if (t === 0) return { faces: [...outcrop(1), mouth, ...ore(s * 0.55, s * 0.5)], height: s * 0.95 }
if (t === 1) {
return {
faces: [
...outcrop(1),
mouth,
...post(s * 0.36, -s * 0.4, s * 0.38, s * 0.04),
...post(s * 0.36, 0, s * 0.38, s * 0.04),
...box(s * 0.36, -s * 0.2, s * 0.08, s * 0.5, s * 0.38, s * 0.06, C.woodDark),
...box(s * 0.6, s * 0.55, s * 0.3, s * 0.2, s * 0.04, s * 0.12, C.woodDark, C.ore),
...ore(s * 0.1, s * 0.6),
],
height: s * 0.95,
}
}
if (t === 2) return { faces: [...outcrop(1.05), mouth, ...headframe(s * 0.45, s * 0.35, s, s * 1.0), ...ore(-s * 0.5, s * 0.6)], height: s * 1.3 }
return {
faces: [
...outcrop(1.15),
mouth,
...headframe(s * 0.5, s * 0.25, s, s * 1.15),
...box(-s * 0.45, s * 0.6, s * 0.55, s * 0.45, 0, s * 0.4, C.stone),
...box(-s * 0.3, s * 0.5, s * 0.12, s * 0.12, s * 0.4, s * 0.5, C.stoneDark),
{ pts: ngon(-s * 0.3, s * 0.5, s * 0.05, 4).map(([x, y]): V3 => [x, y, s * 0.92]), color: C.fire, flat: true },
],
height: s * 1.45,
}
},
hiding_place(s, t) {
if (t === 0) return { faces: pyramid(ngon(0, 0, s * 0.62, 7), 0, s * 0.85, C.hay), height: s * 0.85 }
const door = plane([[s * 0.45, -s * 0.2, 0], [s * 0.45, s * 0.2, 0], [s * 0.45, s * 0.2, s * 0.35], [s * 0.45, -s * 0.2, s * 0.35]], C.dark)
if (t === 1) return { faces: [...pyramid(rect(0, 0, s * 1.2, s * 1.2), 0, s * 0.55, C.grass), door], height: s * 0.55 }
return {
faces: [...box(0, 0, s * 1.0, s * 1.0, 0, s * 0.4, C.stone), ...pyramid(rect(0, 0, s * 1.1, s * 1.1), s * 0.4, s * 0.3, C.grass), shift([door], s * 0.06, 0)[0]!],
height: s * 0.7,
}
},
rally_point(s, t) {
const stones: Face[] = ngon(0, 0, s * 0.6, 8).flatMap(([x, y]) => box(x, y, s * 0.14, s * 0.14, 0, s * 0.1, C.stone))
if (t === 0) return { faces: [...stones, ...banner(0, 0, s * 1.6, s * 0.8)], height: s * 1.6 }
return {
faces: [
...box(0, 0, s * 0.9, s * 0.9, 0, s * 0.15, C.plank, C.wood),
...banner(-s * 0.3, -s * 0.3, s * 1.8, s * 0.8),
...banner(s * 0.3, s * 0.3, s * 1.5, s * 0.7, C.slate),
],
height: s * 1.8,
}
},
// The wall is drawn as the ring around the plateau, see scene.ts.
wall: () => ({ faces: [], height: 0 }),
}
export function buildingModel(type: BuildingType, level: number, s: number): Model {
return models[type](s, tier(level))
}
/** A queued new building: posts, planks and its outline on the ground. */
export function scaffold(s: number): Model {
const a = s * 0.6
return {
faces: [
plane(rect(0, 0, a * 2.1, a * 2.1).map(([x, y]) => [x, y, 0.5]), C.soil, 0.5),
...post(-a, -a, s * 0.75, s * 0.035),
...post(a, -a, s * 0.75, s * 0.035),
...post(-a, a, s * 0.75, s * 0.035),
...post(a, a, s * 0.75, s * 0.035),
...box(0, a, a * 2.1, s * 0.05, s * 0.45, s * 0.05, C.plank),
...box(a, 0, s * 0.05, a * 2.1, s * 0.6, s * 0.05, C.plank),
...crate(-a * 0.3, a * 0.2, 0, s * 0.22),
],
height: s * 0.8,
}
}
/** A small crane beside a building that is being upgraded or taken down. */
export function crane(s: number, height: number): Face[] {
const x = s * 0.85
const y = -s * 0.85
const h = height + s * 0.35
return [
...post(x, y, h, s * 0.045, C.woodDark),
...box(x - s * 0.3, y, s * 0.75, s * 0.06, h, s * 0.06, C.wood),
...box(x - s * 0.6, y, s * 0.02, s * 0.02, h - s * 0.4, s * 0.4, C.dark),
...crate(x - s * 0.6, y, h - s * 0.55, s * 0.14),
]
}

293
app/diorama/scene.ts Normal file
View File

@ -0,0 +1,293 @@
// The village diorama scene: a floating low-poly plateau with the buildings laid out
// by the client. The server only says which buildings exist and how much building
// space they take; where they stand is decided here, deterministically:
// the headquarters in the centre, everything else in id order on a golden-angle
// spiral around it, keeping the path to the front free.
import type { BuildingType, VillageState } from '~/types/game'
import { type Face, hash, mix, ngon, orient, plane, type Poly, prism, project, pyramid, toPolys, type V2, type V3 } from './iso'
import { buildingModel, C, crane, rock, scaffold, tree } from './models'
/** World units per unit of building space, roughly. */
const U = 24
const GAP = U * 0.3
const PATH_HALF = U * 0.5
const GOLDEN = Math.PI * (3 - Math.sqrt(5))
/** The path runs from the headquarters straight towards the viewer. */
const DIR: V2 = [Math.SQRT1_2, Math.SQRT1_2]
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
}
export interface SceneObject {
key: string
polys: Poly[]
building?: SceneBuilding
planned?: boolean
}
export interface Scene {
viewBox: string
shadow: { cx: number; cy: number; rx: number; ry: number }
terrain: Poly[]
decals: Poly[]
objects: SceneObject[]
}
/** 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
r: 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 the path (a ray from the centre towards the viewer). */
function pathDistance(x: number, y: number) {
const along = x * DIR[0] + y * DIR[1]
return along < 0 ? Math.hypot(x, y) : Math.abs(x * DIR[1] - y * DIR[0])
}
function layout(items: { key: string; space: number }[], hqRadius: number): Slot[] {
const slots: Slot[] = [{ key: 'hq', x: 0, y: 0, r: hqRadius }]
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 (pathDistance(x, y) < r + PATH_HALF) continue
if (slots.some((s) => Math.hypot(x - s.x, y - s.y) < r + s.r + GAP)) continue
slots.push({ key: item.key, x, y, r })
break
}
}
return slots
}
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 }
}
// Terrain
function plateau(R: number): { terrain: Poly[]; bottom: number } {
const n = 24
const outer = Array.from({ length: n }, (_, i): V3 => {
const a = (i / n) * Math.PI * 2
const k = 1 + 0.07 * (hash(i, 1) - 0.5)
return [Math.cos(a) * R * k, Math.sin(a) * R * k, 0]
})
const m = n / 2
const inner = Array.from({ length: m }, (_, i): V3 => {
const a = ((i + 0.5) / m) * Math.PI * 2
const k = 0.5 + 0.12 * hash(i, 2)
return [Math.cos(a) * R * k, Math.sin(a) * R * k, 1 + 4 * hash(i, 3)]
})
const centre: V3 = [0, 0, 2]
const below: V3 = [0, 0, -1000]
const grass = (i: number) => mix(mix('#93c25d', '#78aa4b', hash(i, 4)), '#a6c96a', hash(i, 5) * 0.35)
const top: Face[] = []
const tri = (pts: V3[], i: number) => top.push({ pts: orient(pts, below), color: grass(i) })
for (let i = 0; i < m; i++) {
const a = inner[i]!
const b = inner[(i + 1) % m]!
tri([centre, a, b], i)
const o0 = outer[2 * i]!
const o1 = outer[2 * i + 1]!
const o2 = outer[(2 * i + 2) % n]!
tri([a, o0, o1], 100 + i)
tri([a, o1, b], 200 + i)
tri([b, o1, o2], 300 + i)
}
// Earth band under the grass, then a rocky cone tapering to a point.
const drop = (i: number) => R * 0.12 + 8 * hash(i, 6)
const rim = outer.map(([x, y], i): V3 => [x * 0.93, y * 0.93, -drop(i)])
const apex: V3 = [R * 0.06, -R * 0.04, -R * 0.55]
const sides: Face[] = []
const cone: Face[] = []
for (let i = 0; i < n; i++) {
const j = (i + 1) % n
sides.push({ pts: orient([outer[i]!, outer[j]!, rim[j]!, rim[i]!], [0, 0, -R * 0.06]), color: mix('#9b7650', '#86633f', hash(i, 7)) })
cone.push({ pts: orient([rim[i]!, rim[j]!, apex], [0, 0, -R * 0.3]), color: mix('#857a6f', '#6f655b', hash(i, 8)) })
}
return { terrain: [...toPolys(cone), ...toPolys(sides), ...toPolys(top)], bottom: project(apex)[1] }
}
function path(R: number, hqRadius: number): Poly[] {
const steps = 7
const start = hqRadius * 0.5
const end = R * 1.02
const perp: V2 = [-DIR[1], DIR[0]]
const left: V3[] = []
const right: V3[] = []
for (let k = 0; k <= steps; k++) {
const t = start + ((end - start) * k) / steps
const wobble = k === 0 ? 0 : (hash(k, 5) - 0.5) * U * 0.45
const w = PATH_HALF * (0.85 + 0.3 * hash(k, 6))
const cx = DIR[0] * t + perp[0] * wobble
const cy = DIR[1] * t + perp[1] * wobble
left.push([cx + perp[0] * w, cy + perp[1] * w, 2])
right.push([cx - perp[0] * w, cy - perp[1] * w, 2])
}
const plaza = ngon(0, 0, hqRadius * 1.08, 9, 0.2).map(([x, y]): V3 => [x, y, 2])
return toPolys([plane(plaza, '#c9ab76'), plane([...left, ...right.reverse()], '#cdb07a')])
}
// The wall rings the plateau; its look follows the level like the buildings.
function wallFaces(R: number, level: number): { back: Face[]; front: Face[]; height: number } {
const ring = R - U * 0.2
const gate = (PATH_HALF + 6) / ring
const steps = Math.max(24, Math.round((Math.PI * 2 * ring) / (U * 0.55)))
const h = U * (0.45 + Math.min(level, 20) * 0.035)
const back: Face[] = []
const front: Face[] = []
const at = (a: number): V2 => [Math.cos(a) * ring, Math.sin(a) * ring]
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
// Leave a gate where the path leaves the village.
if (Math.abs(Math.atan2(Math.sin(mid - Math.PI / 4), Math.cos(mid - Math.PI / 4))) < gate) continue
const [x, y] = at(mid)
const faces: Face[] =
level < 5
? [...prism(ngon(x, y, U * 0.09, 5, i), 0, h, C.wood), ...pyramid(ngon(x, y, U * 0.09, 5, i), h, U * 0.12, C.woodDark)]
: (() => {
const [x0, y0] = at(a0)
const [x1, y1] = at(a1)
const nx = Math.cos(mid) * U * 0.09
const ny = Math.sin(mid) * U * 0.09
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 color = level < 15 ? C.wood : C.stone
const seg = prism(ccw ? base : [...base].reverse(), 0, h, color, level < 15 ? C.plank : C.stoneDark)
const tower =
level >= 15 && i % 6 === 0
? [...prism(ngon(x, y, U * 0.22, 6), 0, h * 1.5, C.stone), ...pyramid(ngon(x, y, U * 0.26, 6), h * 1.5, U * 0.35, C.slate)]
: []
return [...seg, ...tower]
})()
;(x + y < 0 ? back : front).push(...faces)
}
return { back, front, height: h }
}
// Decoration: trees and rocks inside the wall, away from buildings and the path.
function decor(R: number, slots: Slot[]): Ordered[] {
const out: Ordered[] = []
const taken: Slot[] = []
const want = Math.floor((R / U) * 1.6)
for (let k = 0; k < 90 && taken.length < want; k++) {
const a = k * GOLDEN * 1.7 + 0.3
const d = R * (0.6 + 0.32 * hash(k, 11))
const x = Math.cos(a) * d
const y = Math.sin(a) * d
const r = U * 0.4
if (Math.hypot(x, y) > R - U * 0.65) continue
if (pathDistance(x, y) < PATH_HALF + r) continue
if ([...slots, ...taken].some((s) => Math.hypot(x - s.x, y - s.y) < s.r + r + 2)) continue
taken.push({ key: `d${k}`, x, y, r })
const size = U * (0.85 + 0.45 * hash(k, 12))
const faces = taken.length % 4 === 0 ? rock(x, y, size * 0.6, k) : tree(x, y, size, k)
out.push({ key: `decor-${k}`, polys: toPolys(faces), depth: x + y })
}
return out
}
export function buildScene(village: VillageState): Scene {
const hq = village.buildings.find((b) => b.type === 'headquarters')
const hqRadius = footRadius(hq?.space ?? 9)
const placedBuildings = village.buildings.filter((b) => b.type !== 'headquarters' && b.space > 0)
const planned = village.queue.filter((o) => o.action === 'build' && o.space > 0)
const slots = layout(
[...placedBuildings.map((b) => ({ key: `b${b.id}`, space: b.space })), ...planned.map((o) => ({ key: `o${o.id}`, space: o.space }))],
hqRadius,
)
const extent = Math.max(...slots.map((s) => Math.hypot(s.x, s.y) + s.r))
const R = Math.max(Math.sqrt((village.space.max * U * U * 2.3) / Math.PI), extent + U * 0.75)
const slotOf = (key: string) => slots.find((s) => s.key === key)!
const running = new Set(village.queue.filter((o) => o.builder !== null && o.building_id !== null).map((o) => o.building_id))
const objects: Ordered[] = []
let topY = Infinity
for (const b of village.buildings) {
if (b.type === 'wall') continue
const slot = b.type === 'headquarters' ? slots[0]! : slotOf(`b${b.id}`)
const 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])
topY = Math.min(topY, label[1])
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(halfSize(o.space))
objects.push({ key: `o${o.id}`, depth: slot.x + slot.y, polys: toPolys(model.faces, [slot.x, slot.y, 0]), planned: true })
}
objects.push(...decor(R, slots))
objects.sort((a, b) => a.depth - b.depth)
// The wall wraps everything: its back half is drawn first, its front half last.
const wall = village.buildings.find((b) => b.type === 'wall')
const wallPlanned = !wall && village.queue.some((o) => o.action === 'build' && o.type === 'wall')
const sorted: SceneObject[] = objects
if (wall || wallPlanned) {
const level = wall?.level ?? 0
const { back, front, height } = wallFaces(R, level)
const gateAngle = Math.PI / 4 + 0.45
const label = project([Math.cos(gateAngle) * R, Math.sin(gateAngle) * R, height + 12])
const ring = { cx: 0, cy: 0, rx: 0, ry: 0 }
const part = (key: string, faces: Face[], focusable: boolean): SceneObject =>
wall
? { key, polys: toPolys(faces), building: { id: wall.id, type: 'wall', level, upgrading: running.has(wall.id), label, ring, focusable } }
: { key, polys: toPolys(faces), planned: true }
sorted.unshift(part('wall-back', back, false))
sorted.push(part('wall-front', front, true))
}
const { terrain, bottom } = plateau(R)
const halfW = R * 1.08 * Math.SQRT2 + U
const minY = Math.min(-R * 1.08 * Math.SQRT1_2, topY) - U * 1.2
const maxY = bottom + U * 2
return {
viewBox: `${(-halfW).toFixed(0)} ${minY.toFixed(0)} ${(halfW * 2).toFixed(0)} ${(maxY - minY).toFixed(0)}`,
shadow: { cx: 0, cy: bottom + U * 0.6, rx: R * 1.05, ry: R * 0.13 },
terrain,
decals: path(R, hqRadius),
objects: sorted.map(({ key, polys, building, planned }) => ({ key, polys, building, planned })),
}
}