game-village-politics-frontend/app/components/map/WorldMap.vue

358 lines
13 KiB
Vue
Raw 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.

<script setup lang="ts">
import type { MapVillage, MapView } from '~/types/map'
const props = defineProps<{
/** Loaded villages; fields outside it show plain land until the next load. */
view: MapView | null
/** Visible area in fields: left/top edge (fractional) and how many fit. */
left: number
top: number
cols: number
rows: number
/** Map size in px; the map fills it exactly. */
width: number
height: number
/** Field size in px. */
field: number
selected: { x: number; y: number } | null
}>()
const emit = defineEmits<{
select: [at: { x: number; y: number }]
hover: [village: MapVillage | null]
/** Pixel movement while dragging, for smooth panning. */
drag: [dx: number, dy: number]
dragend: []
/** Whole fields, from the arrow keys. */
pan: [dx: number, dy: number]
}>()
const { t } = useI18n()
const RULER = 26
const mapSize = computed(() => props.view?.size ?? 1000)
/** Lowest coordinate: the world starts at 0|0, negative included. */
const lo = computed(() => props.view?.min ?? mapMin(mapSize.value))
const villageAt = computed(() => new Map((props.view?.villages ?? []).map((v) => [`${v.x}|${v.y}`, v])))
// Same field, same look: terrain comes from a hash of the coordinates.
const hash = (x: number, y: number) => {
let h = (x * 73856093) ^ (y * 19349663)
h = Math.imul(h ^ (h >>> 13), 1274126177)
return ((h ^ (h >>> 16)) >>> 0) / 4294967296
}
const GRASS = ['#7f9645', '#78903f', '#86994b', '#73893c']
const WATER = '#5f7f87'
/** Smooth value noise: neighbouring fields get similar values, so terrain comes in patches. */
const smooth = (t: number) => t * t * (3 - 2 * t)
function noise(x: number, y: number, size: number, seed: number) {
const gx = x / size
const gy = y / size
const ix = Math.floor(gx)
const iy = Math.floor(gy)
const fx = smooth(gx - ix)
const fy = smooth(gy - iy)
const at = (a: number, b: number) => hash(a * 7 + seed * 101, b * 13 - seed * 37)
const top = at(ix, iy) + (at(ix + 1, iy) - at(ix, iy)) * fx
const bottom = at(ix, iy + 1) + (at(ix + 1, iy + 1) - at(ix, iy + 1)) * fx
return top + (bottom - top) * fy
}
type Ground = 'grass' | 'forest' | 'water' | 'hill'
/** Lakes, rocky hills and forests in patches; a village's field is always open land. */
function groundAt(x: number, y: number): Ground {
if (noise(x, y, 11, 1) < 0.17) return 'water'
if (noise(x, y, 8, 2) > 0.8) return 'hill'
if (noise(x, y, 6, 3) > 0.6 || hash(x, y) < 0.05) return 'forest'
return 'grass'
}
// Whole fields touching the visible area. These only change when an edge crosses a
// field, so dragging moves one transform instead of re-rendering every field.
const x0 = computed(() => Math.max(lo.value, Math.floor(props.left)))
const y0 = computed(() => Math.max(lo.value, Math.floor(props.top)))
const x1 = computed(() => Math.min(lo.value + mapSize.value, Math.ceil(props.left + props.cols)))
const y1 = computed(() => Math.min(lo.value + mapSize.value, Math.ceil(props.top + props.rows)))
interface Field {
x: number
y: number
grass: string
village: MapVillage | null
ground: Ground
/** Trees as [x, y, size] in the field's 100 × 100 box, back to front. */
trees: [number, number, number][]
/** Sides of a lake field that meet land and get a shore. */
shore: { top: boolean; right: boolean; bottom: boolean; left: boolean } | null
}
const fields = computed<Field[]>(() => {
const out: Field[] = []
for (let y = y0.value; y < y1.value; y++) {
for (let x = x0.value; x < x1.value; x++) {
const r = hash(x, y)
const village = villageAt.value.get(`${x}|${y}`) ?? null
const ground: Ground = village ? 'grass' : groundAt(x, y)
const land = (gx: number, gy: number) => !!villageAt.value.get(`${gx}|${gy}`) || groundAt(gx, gy) !== 'water'
// Deeper in a forest, more and bigger trees.
const count = ground === 'forest' ? 2 + Math.round(noise(x, y, 6, 3) * 4) : 0
const trees = Array.from({ length: count }, (_, i): [number, number, number] => [
14 + hash(x * 3 + i, y) * 72,
28 + hash(x, y * 3 + i) * 56,
0.75 + hash(x + i, y + i) * 0.5,
]).sort((a, b) => a[1] - b[1])
out.push({
x,
y,
grass: GRASS[Math.floor(r * GRASS.length)]!,
village,
ground,
trees,
shore: ground === 'water' ? { top: land(x, y - 1), right: land(x + 1, y), bottom: land(x, y + 1), left: land(x - 1, y) } : null,
})
}
}
return out
})
const villageFields = computed(() => fields.value.filter((f) => f.village))
/** Five sizes by points, like the Die Stämme map. */
const tier = (points: number): 1 | 2 | 3 | 4 | 5 => (points < 150 ? 1 : points < 500 ? 2 : points < 1500 ? 3 : points < 5000 ? 4 : 5)
const relation = (v: MapVillage) => (v.own ? 'own' : v.player ? 'player' : 'barbarian')
// Sector lines every 10 fields, continent borders every 100.
const lines = computed(() => {
const F = props.field
const out: { x1: number; y1: number; x2: number; y2: number; kind: 'sector' | 'continent' }[] = []
for (let x = x0.value; x <= x1.value; x++) {
if (x % 10 === 0) out.push({ x1: x * F, y1: y0.value * F, x2: x * F, y2: y1.value * F, kind: x % 100 === 0 ? 'continent' : 'sector' })
}
for (let y = y0.value; y <= y1.value; y++) {
if (y % 10 === 0) out.push({ x1: x0.value * F, y1: y * F, x2: x1.value * F, y2: y * F, kind: y % 100 === 0 ? 'continent' : 'sector' })
}
return out
})
// One label per continent in view, at its top-left corner or the first fully visible field.
const continents = computed(() => {
const out: { label: string; x: number; y: number }[] = []
const left = Math.ceil(props.left)
const top = Math.ceil(props.top)
for (let cy = Math.floor(y0.value / 100); cy * 100 < y1.value; cy++) {
for (let cx = Math.floor(x0.value / 100); cx * 100 < x1.value; cx++) {
out.push({ label: continentOf(cx * 100, cy * 100, mapSize.value), x: Math.max(cx * 100, left), y: Math.max(cy * 100, top) })
}
}
return out
})
const columns = computed(() => Array.from({ length: x1.value - x0.value }, (_, i) => x0.value + i))
const rowsList = computed(() => Array.from({ length: y1.value - y0.value }, (_, i) => y0.value + i))
const rulerFont = computed(() => Math.max(9, Math.min(12, props.field / 4)))
const shiftX = computed(() => RULER - props.left * props.field)
const shiftY = computed(() => RULER - props.top * props.field)
// Dragging pans pixel by pixel; a click without movement selects a field.
let drag: { lastX: number; lastY: number; moved: boolean } | null = null
const dragging = ref(false)
function onPointerDown(e: PointerEvent) {
if (e.button !== 0) return
drag = { lastX: e.clientX, lastY: e.clientY, moved: false }
;(e.currentTarget as Element).setPointerCapture(e.pointerId)
}
function onPointerMove(e: PointerEvent) {
if (!drag) return
const dx = e.clientX - drag.lastX
const dy = e.clientY - drag.lastY
if (!drag.moved && Math.abs(dx) + Math.abs(dy) < 4) return
drag.moved = true
dragging.value = true
drag.lastX = e.clientX
drag.lastY = e.clientY
emit('drag', dx, dy)
}
function onPointerUp(e: PointerEvent) {
const d = drag
drag = null
dragging.value = false
if (!d) return
if (d.moved) {
emit('dragend')
return
}
const rect = (e.currentTarget as Element).getBoundingClientRect()
const px = e.clientX - rect.left - RULER
const py = e.clientY - rect.top - RULER
if (px < 0 || py < 0) return
const x = Math.floor(props.left + px / props.field)
const y = Math.floor(props.top + py / props.field)
const hi = lo.value + mapSize.value
if (x >= lo.value && y >= lo.value && x < hi && y < hi) emit('select', { x, y })
}
function onKey(e: KeyboardEvent) {
const step = e.shiftKey ? 5 : 1
const moves: Record<string, [number, number]> = {
ArrowLeft: [-step, 0],
ArrowRight: [step, 0],
ArrowUp: [0, -step],
ArrowDown: [0, step],
}
const move = moves[e.key]
if (!move) return
e.preventDefault()
emit('pan', move[0], move[1])
}
</script>
<template>
<svg
:width="width"
:height="height"
:viewBox="`0 0 ${width} ${height}`"
class="block touch-none select-none outline-none focus-visible:ring-2 focus-visible:ring-gold-500"
:class="dragging ? 'cursor-grabbing' : 'cursor-grab'"
role="application"
tabindex="0"
:aria-label="t('map.aria')"
@pointerdown="onPointerDown"
@pointermove="onPointerMove"
@pointerup="onPointerUp"
@pointercancel="drag = null"
@pointerleave="emit('hover', null)"
@keydown="onKey"
>
<defs>
<clipPath id="map-fields">
<rect :x="RULER" :y="RULER" :width="Math.max(0, width - RULER)" :height="Math.max(0, height - RULER)" />
</clipPath>
<clipPath id="map-ruler-x">
<rect :x="RULER" y="0" :width="Math.max(0, width - RULER)" :height="RULER" />
</clipPath>
<clipPath id="map-ruler-y">
<rect x="0" :y="RULER" :width="RULER" :height="Math.max(0, height - RULER)" />
</clipPath>
</defs>
<rect :width="width" :height="height" fill="#4f6129" />
<g clip-path="url(#map-fields)">
<!-- Fields sit at their world position; panning only moves this group. -->
<g :transform="`translate(${shiftX} ${shiftY})`">
<g v-for="f in fields" :key="`${f.x}|${f.y}`" @pointerenter="emit('hover', f.village)">
<rect :x="f.x * field" :y="f.y * field" :width="field" :height="field" :fill="f.ground === 'water' ? WATER : f.grass" />
<g v-if="f.ground !== 'grass'" :transform="`translate(${f.x * field} ${f.y * field}) scale(${field / 100})`">
<template v-if="f.shore">
<!-- Sandy shore where the lake meets land, and a ripple. -->
<rect v-if="f.shore.top" x="0" y="0" width="100" height="9" fill="#b8a173" />
<rect v-if="f.shore.bottom" x="0" y="91" width="100" height="9" fill="#b8a173" />
<rect v-if="f.shore.left" x="0" y="0" width="9" height="100" fill="#b8a173" />
<rect v-if="f.shore.right" x="91" y="0" width="9" height="100" fill="#b8a173" />
<path :d="`M${28 + hash(f.x, f.y) * 30} 50h18M${40 + hash(f.y, f.x) * 20} 64h12`" stroke="#7e9da3" stroke-width="3" stroke-linecap="round" />
</template>
<g v-else-if="f.ground === 'hill'">
<ellipse cx="52" cy="70" rx="40" ry="16" fill="#6f7f3d" />
<polygon points="18,72 40,30 58,72" fill="#8d877b" />
<polygon points="40,30 58,72 64,60" fill="#6f6a60" />
<polygon points="48,74 68,42 86,74" fill="#a39d92" />
<polygon points="68,42 86,74 90,66" fill="#7c776a" />
</g>
<g v-for="(tr, i) in f.trees" :key="i" :transform="`translate(${tr[0]} ${tr[1]}) scale(${tr[2]})`">
<ellipse cx="4" cy="26" rx="12" ry="4" fill="#5f7531" />
<rect x="-2" y="18" width="4" height="9" fill="#57391f" />
<polygon points="0,-10 -13,20 0,16" fill="#2f5222" />
<polygon points="0,-10 13,20 0,16" fill="#46702f" />
</g>
</g>
</g>
<!-- Continent labels and lines lie on the ground, under the villages. -->
<text
v-for="c in continents"
:key="c.label"
:x="c.x * field + 5"
:y="c.y * field + 19"
font-size="17"
font-weight="700"
font-family="Georgia, serif"
fill="rgb(243 231 201 / 0.6)"
>
{{ c.label }}
</text>
<line
v-for="(l, i) in lines"
:key="i"
:x1="l.x1"
:y1="l.y1"
:x2="l.x2"
:y2="l.y2"
:stroke="l.kind === 'continent' ? 'rgb(31 21 12 / 0.85)' : 'rgb(31 21 12 / 0.3)'"
:stroke-width="l.kind === 'continent' ? 2.5 : 1"
/>
<g
v-for="f in villageFields"
:key="`v${f.x}|${f.y}`"
:transform="`translate(${f.x * field} ${f.y * field}) scale(${field / 100})`"
class="pointer-events-none"
>
<MapVillageMarker :tier="tier(f.village!.points)" :relation="relation(f.village!)" />
</g>
<rect
v-if="selected"
:x="selected.x * field + 1"
:y="selected.y * field + 1"
:width="field - 2"
:height="field - 2"
rx="4"
fill="rgb(217 180 74 / 0.18)"
stroke="#d9b44a"
stroke-width="2.5"
/>
</g>
</g>
<!-- Coordinate rulers, Die Stämme style: x along the top, y down the side. -->
<rect x="0" y="0" :width="width" :height="RULER" fill="#dcc595" />
<rect x="0" y="0" :width="RULER" :height="height" fill="#dcc595" />
<g clip-path="url(#map-ruler-x)">
<g :transform="`translate(${shiftX} 0)`">
<text
v-for="x in columns"
:key="`x${x}`"
:x="(x + 0.5) * field"
:y="RULER / 2 + 4"
text-anchor="middle"
:font-size="rulerFont"
fill="#2f2013"
class="tabular-nums"
>
{{ x }}
</text>
</g>
</g>
<g clip-path="url(#map-ruler-y)">
<g :transform="`translate(0 ${shiftY})`">
<text
v-for="y in rowsList"
:key="`y${y}`"
:x="RULER / 2"
:y="(y + 0.5) * field + 4"
text-anchor="middle"
:font-size="rulerFont"
fill="#2f2013"
class="tabular-nums"
>
{{ y }}
</text>
</g>
</g>
<rect x="0" y="0" :width="RULER" :height="RULER" fill="#c4a676" />
</svg>
</template>