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

269 lines
8.6 KiB
TypeScript
Raw Normal View History

// 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]) }))
}