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

366 lines
15 KiB
Vue

<script setup lang="ts">
import { mapVillageSymbol } from '~/diorama/mapVillage'
import type { MapMovement, MapVillage, MapView } from '~/types/map'
import type { MarkerRelation } from '~/utils/relations'
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
/** The village the player is in now: drawn white. */
current?: number | null
/** The clock, for where groups on the march are. */
now: number
/** Id of the group on the march that was clicked. */
march?: 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]
/** A group on the march or its line was clicked. */
march: [id: 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])))
// Whole fields touching the visible area.
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)))
// The land, the villages and the groups on the march are drawn for a region of whole fields
// round the visible ones, at their world position, in a layer of their own that dragging only
// moves (a CSS transform the browser composites without painting anew). The region stays the
// same object while the view is inside it, so nothing in it re-renders until the view
// leaves it, PAD fields on, or the zoom changes.
const PAD = 2
const region = computed<{ x0: number; y0: number; x1: number; y1: number; field: number }>((last) => {
const F = props.field
if (last && last.field === F && x0.value >= last.x0 && y0.value >= last.y0 && x1.value <= last.x1 && y1.value <= last.y1) return last
const hi = lo.value + mapSize.value
return { x0: Math.max(lo.value, x0.value - PAD), y0: Math.max(lo.value, y0.value - PAD), x1: Math.min(hi, x1.value + PAD), y1: Math.min(hi, y1.value + PAD), field: F }
})
/** Where the world's 0|0 sits on screen, in whole pixels so the layer stays crisp. */
const shiftX = computed(() => RULER + Math.round(-props.left * props.field))
const shiftY = computed(() => RULER + Math.round(-props.top * props.field))
const layer = computed(() => {
const r = region.value
const F = props.field
/** The region's top-left corner on screen, from where the fields begin. */
const x = shiftX.value - RULER + r.x0 * F
const y = shiftY.value - RULER + r.y0 * F
return {
width: (r.x1 - r.x0) * F,
height: (r.y1 - r.y0) * F,
viewBox: `${r.x0 * F} ${r.y0 * F} ${(r.x1 - r.x0) * F} ${(r.y1 - r.y0) * F}`,
x,
y,
transform: `translate3d(${x}px, ${y}px, 0)`,
}
})
const relation = (v: MapVillage): MarkerRelation => (v.id === props.current ? 'current' : (v.relation ?? (v.own ? 'own' : v.player ? 'none' : 'barbarian')))
/** Villages in the region, row by row so lower ones draw over the roofs and towers above. */
const villages = computed(() => {
const r = region.value
return (props.view?.villages ?? [])
.filter((v) => v.x >= r.x0 && v.x < r.x1 && v.y >= r.y0 && v.y < r.y1)
.sort((a, b) => a.y - b.y || a.x - b.x)
.map((v) => ({ id: v.id, x: v.x, y: v.y, look: mapVillageSymbol(v), colour: RELATION_COLOURS[relation(v)] }))
})
// Groups on the march: a line from village to village and the group where it is now,
// moving straight at constant speed (raiders wait at their camp until they march). A group
// leaves the map when it arrives; the page reloads then and shows what comes of it.
const motion = ref(false)
onMounted(() => (motion.value = !window.matchMedia('(prefers-reduced-motion: reduce)').matches))
const centre = (p: { x: number; y: number }) => [(p.x + 0.5) * props.field, (p.y + 0.5) * props.field] as const
const marches = computed(() =>
(props.view?.movements ?? []).filter((m) => Date.parse(m.arrives_at) > props.now).map((m: MapMovement) => {
const [ax, ay] = centre(m.from)
const [bx, by] = centre(m.to)
const start = Date.parse(m.sent_at)
const end = Date.parse(m.arrives_at)
const p = end > start ? Math.max(0, Math.min(1, (props.now - start) / (end - start))) : 1
const colour = m.raid ? MARCH_COLOURS.raid : MARCH_COLOURS[m.type]
return { m, ax, ay, bx, by, x: ax + (bx - ax) * p, y: ay + (by - ay) * p, colour, flip: bx < ax, waiting: props.now < start }
}),
)
const marchTitle = (m: MapMovement) =>
t(`map.march.${m.raid ? 'raid' : m.type}`, { from: `${m.from.name} (${m.from.x}|${m.from.y})`, to: `${m.to.name} (${m.to.x}|${m.to.y})` }) +
' · ' +
t(`map.march.sizes.${m.size}`) +
' · ' +
formatDuration(Math.max(0, (Date.parse(m.arrives_at) - props.now) / 1000))
// Sector lines every 10 fields, continent borders every 100, across the region.
const lines = computed(() => {
const { x0, y0, x1, y1, field: F } = region.value
const out: { x1: number; y1: number; x2: number; y2: number; kind: 'sector' | 'continent' }[] = []
for (let x = x0; x <= x1; x++) {
if (x % 10 === 0) out.push({ x1: x * F, y1: y0 * F, x2: x * F, y2: y1 * F, kind: x % 100 === 0 ? 'continent' : 'sector' })
}
for (let y = y0; y <= y1; y++) {
if (y % 10 === 0) out.push({ x1: x0 * F, y1: y * F, x2: x1 * 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
})
// The rulers' numbers run along the region too, in layers that move with the fields.
const columns = computed(() => Array.from({ length: region.value.x1 - region.value.x0 }, (_, i) => region.value.x0 + i))
const rowsList = computed(() => Array.from({ length: region.value.y1 - region.value.y0 }, (_, i) => region.value.y0 + i))
const rulerFont = computed(() => Math.max(9, Math.min(12, props.field / 4)))
// 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)
}
/** The field under a pointer, or null over the rulers and off the map. */
function fieldUnder(e: PointerEvent | MouseEvent) {
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 null
const x = Math.floor(props.left + px / props.field)
const y = Math.floor(props.top + py / props.field)
const hi = lo.value + mapSize.value
return x >= lo.value && y >= lo.value && x < hi && y < hi ? { x, y } : null
}
// Hover: one handler on the map finds the field, instead of a listener on every field.
let hoveredKey: string | null = null
function hover(e: PointerEvent) {
const at = fieldUnder(e)
const key = at ? `${at.x}|${at.y}` : null
if (key === hoveredKey) return
hoveredKey = key
emit('hover', key ? (villageAt.value.get(key) ?? null) : null)
}
function unhover() {
hoveredKey = null
emit('hover', null)
}
function onPointerMove(e: PointerEvent) {
if (!drag) return hover(e)
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 at = fieldUnder(e)
if (at) emit('select', at)
}
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>
<div
class="relative touch-none select-none overflow-hidden bg-[#585e3c] outline-none focus-visible:ring-2 focus-visible:ring-gold-500"
:class="dragging ? 'cursor-grabbing' : 'cursor-grab'"
:style="{ width: `${width}px`, height: `${height}px` }"
role="application"
tabindex="0"
:aria-label="t('map.aria')"
@pointerdown="onPointerDown"
@pointermove="onPointerMove"
@pointerup="onPointerUp"
@pointercancel="drag = null"
@pointerleave="unhover"
@keydown="onKey"
>
<!-- The fields' layer: the region at its world position, moved as a whole while dragging. -->
<div class="absolute right-0 bottom-0 overflow-hidden" :style="{ left: `${RULER}px`, top: `${RULER}px` }">
<div class="absolute top-0 left-0 will-change-transform" :style="{ transform: layer.transform }">
<svg :width="layer.width" :height="layer.height" :viewBox="layer.viewBox" class="block">
<defs>
<MapVillageDefs />
</defs>
<MapLand :region="region" :field="field" :villages="villageAt" />
<!-- 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"
/>
<MapVillages :villages="villages" :field="field" />
<!-- Groups on the march, over the villages; the line and the group open the group's card. -->
<g v-for="g in marches" :key="`m${g.m.id}`">
<line v-if="g.m.id === march" :x1="g.ax" :y1="g.ay" :x2="g.bx" :y2="g.by" stroke="#1f150c" stroke-width="6" stroke-linecap="round" />
<line :x1="g.ax" :y1="g.ay" :x2="g.bx" :y2="g.by" :stroke="g.colour" :stroke-width="g.m.id === march ? 3.5 : 2.5" :stroke-dasharray="g.m.type === 'return' ? '6 5' : undefined" stroke-linecap="round" />
<circle :cx="g.bx" :cy="g.by" r="4" :fill="g.colour" />
<line
:x1="g.ax"
:y1="g.ay"
:x2="g.bx"
:y2="g.by"
stroke="transparent"
stroke-width="14"
pointer-events="stroke"
class="cursor-pointer"
@pointerdown.stop
@click="emit('march', g.m.id)"
>
<title>{{ marchTitle(g.m) }}</title>
</line>
<g
:transform="`translate(${g.x} ${g.y}) scale(${Math.max(0.6, field / 55)})`"
class="pointer-events-auto cursor-pointer outline-none focus-visible:outline-2 focus-visible:outline-gold-500"
role="button"
tabindex="0"
:aria-label="marchTitle(g.m)"
@pointerdown.stop
@click="emit('march', g.m.id)"
@keydown.enter.stop="emit('march', g.m.id)"
>
<title>{{ marchTitle(g.m) }}</title>
<MapMarch :size="g.m.size" :colour="g.colour" :flip="g.flip" :motion="motion && !g.waiting" />
</g>
</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"
/>
</svg>
</div>
</div>
<!-- Coordinate rulers, Die Stämme style: x along the top, y down the side; their numbers move like the fields. -->
<div class="pointer-events-none absolute top-0 right-0 overflow-hidden bg-[#dcc595]" :style="{ left: `${RULER}px`, height: `${RULER}px` }">
<div class="absolute top-0 left-0 will-change-transform" :style="{ transform: `translate3d(${layer.x}px, 0, 0)` }">
<svg :width="layer.width" :height="RULER" :viewBox="`${region.x0 * field} 0 ${layer.width} ${RULER}`" class="block">
<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>
</svg>
</div>
</div>
<div class="pointer-events-none absolute bottom-0 left-0 overflow-hidden bg-[#dcc595]" :style="{ top: `${RULER}px`, width: `${RULER}px` }">
<div class="absolute top-0 left-0 will-change-transform" :style="{ transform: `translate3d(0, ${layer.y}px, 0)` }">
<svg :width="RULER" :height="layer.height" :viewBox="`0 ${region.y0 * field} ${RULER} ${layer.height}`" class="block">
<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>
</svg>
</div>
</div>
<div class="pointer-events-none absolute top-0 left-0 bg-[#c4a676]" :style="{ width: `${RULER}px`, height: `${RULER}px` }" />
</div>
</template>