game-village-politics-frontend/app/composables/useDioramaCamera.ts

233 lines
9.3 KiB
TypeScript
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.

import type { SceneInset, View } from '~/diorama/scene'
/** How far the camera goes in, as a multiple of the view that fits the whole village. */
const MAX_ZOOM = 4
/** One step of the buttons and keys. */
const STEP = 1.4
/** Pixels a pointer moves before a press becomes a drag, so a shaky click still clicks. */
const DRAG_FROM = 5
interface Camera {
zoom: number
/** Where the view's centre sits, in viewBox units from the home view's centre. */
dx: number
dy: number
}
const HOME: Camera = { zoom: 1, dx: 0, dy: 0 }
// Per village while the app runs, so the view stays put when hopping to the map and back.
const cameras = reactive(new Map<number, Camera>())
const fit = (v: number, lo: number, hi: number) => (lo > hi ? (lo + hi) / 2 : Math.min(hi, Math.max(lo, v)))
/**
* Pan and zoom over the village: the view is the home view (the whole village in the free
* part of the stage) zoomed in or out round a centre, and never leaves the drawn land.
* Drag pans, the wheel and a pinch zoom at the pointer, + − 0 and the arrows work from
* the keyboard. A drag never ends in a click, so it opens nothing.
*/
export function useDioramaCamera(opts: {
id: () => number
stage: Ref<HTMLElement | null>
home: () => View
bounds: () => View
inset: () => SceneInset
enabled: () => boolean
}) {
const minZoom = computed(() => {
const home = opts.home()
const bounds = opts.bounds()
return Math.min(1, Math.max(home.w / bounds.w, home.h / bounds.h))
})
/** The camera inside its limits: zoom in range, the view on the land. */
function clamp(c: Camera): Camera {
const home = opts.home()
const bounds = opts.bounds()
const zoom = Math.min(MAX_ZOOM, Math.max(minZoom.value, c.zoom))
const w = home.w / zoom
const h = home.h / zoom
const hx = home.x + home.w / 2
const hy = home.y + home.h / 2
const cx = fit(hx + c.dx, bounds.x + w / 2, bounds.x + bounds.w - w / 2)
const cy = fit(hy + c.dy, bounds.y + h / 2, bounds.y + bounds.h - h / 2)
return { zoom, dx: cx - hx, dy: cy - hy }
}
const camera = computed<Camera>({
get: () => (opts.enabled() ? clamp(cameras.get(opts.id()) ?? HOME) : HOME),
set: (c) => {
cameras.set(opts.id(), clamp(c))
},
})
const view = computed<View>(() => {
const home = opts.home()
const { zoom, dx, dy } = camera.value
const w = home.w / zoom
const h = home.h / zoom
return { x: home.x + home.w / 2 + dx - w / 2, y: home.y + home.h / 2 + dy - h / 2, w, h }
})
const viewBox = computed(() => {
const v = view.value
return `${v.x.toFixed(1)} ${v.y.toFixed(1)} ${v.w.toFixed(1)} ${v.h.toFixed(1)}`
})
/** Moves the land with the pointer by (px, py) screen pixels. */
function panBy(px: number, py: number) {
const el = opts.stage.value
if (!el?.clientWidth) return
const perPixel = view.value.w / el.clientWidth
const c = camera.value
camera.value = { ...c, dx: c.dx - px * perPixel, dy: c.dy - py * perPixel }
}
/** Zooms by `factor`, keeping the land under the screen point (x, y) where it is. */
function zoomAt(factor: number, x: number, y: number) {
const el = opts.stage.value
if (!el) return
const rect = el.getBoundingClientRect()
const fx = (x - rect.left) / Math.max(1, rect.width)
const fy = (y - rect.top) / Math.max(1, rect.height)
const home = opts.home()
const v = view.value
const zoom = Math.min(MAX_ZOOM, Math.max(minZoom.value, camera.value.zoom * factor))
const w = home.w / zoom
const h = home.h / zoom
const px = v.x + fx * v.w
const py = v.y + fy * v.h
camera.value = { zoom, dx: px - fx * w + w / 2 - (home.x + home.w / 2), dy: py - fy * h + h / 2 - (home.y + home.h / 2) }
}
/** Zooms round the middle of the part of the stage that windows don't cover. */
function zoomBy(factor: number) {
const el = opts.stage.value
if (!el) return
const rect = el.getBoundingClientRect()
const inset = opts.inset()
zoomAt(factor, rect.left + inset.left + (rect.width - inset.left - inset.right) / 2, rect.top + inset.top + (rect.height - inset.top - inset.bottom) / 2)
}
const zoomIn = () => zoomBy(STEP)
const zoomOut = () => zoomBy(1 / STEP)
const reset = () => (camera.value = HOME)
const canZoomIn = computed(() => camera.value.zoom < MAX_ZOOM - 1e-3)
const canZoomOut = computed(() => camera.value.zoom > minZoom.value + 1e-3)
const atHome = computed(() => {
const c = camera.value
return Math.abs(c.zoom - 1) < 1e-3 && Math.abs(c.dx) < 0.5 && Math.abs(c.dy) < 0.5
})
// One pointer drags, two pinch. A press that never moved past DRAG_FROM stays a click.
const pointers = new Map<number, [number, number]>()
const panning = ref(false)
let moved = false
let swallowClick = false
function onPointerDown(e: PointerEvent) {
if (!opts.enabled() || (e.pointerType === 'mouse' && e.button !== 0)) return
if (!pointers.size) {
moved = false
swallowClick = false
}
pointers.set(e.pointerId, [e.clientX, e.clientY])
}
function onPointerMove(e: PointerEvent) {
const last = pointers.get(e.pointerId)
if (!last) return
// Released outside the window before the drag began: no pointerup ever came.
if (e.pointerType === 'mouse' && !(e.buttons & 1)) {
pointers.delete(e.pointerId)
return
}
const now: [number, number] = [e.clientX, e.clientY]
if (pointers.size === 1) {
if (!moved && Math.hypot(now[0] - last[0], now[1] - last[1]) < DRAG_FROM) return
if (!moved) opts.stage.value?.setPointerCapture(e.pointerId)
moved = true
panning.value = true
panBy(now[0] - last[0], now[1] - last[1])
} else if (pointers.size === 2) {
const other = [...pointers].find(([id]) => id !== e.pointerId)![1]
if (!moved) for (const id of pointers.keys()) opts.stage.value?.setPointerCapture(id)
moved = true
panning.value = true
const before = Math.hypot(last[0] - other[0], last[1] - other[1])
const after = Math.hypot(now[0] - other[0], now[1] - other[1])
panBy((now[0] - last[0]) / 2, (now[1] - last[1]) / 2)
if (before > 0) zoomAt(after / before, (now[0] + other[0]) / 2, (now[1] + other[1]) / 2)
}
pointers.set(e.pointerId, now)
}
function onPointerUp(e: PointerEvent) {
if (!pointers.delete(e.pointerId) || pointers.size) return
panning.value = false
// The click that follows a drag lands on whatever is under the pointer; drop it.
if (moved && e.type === 'pointerup') swallowClick = true
}
function onClick(e: MouseEvent) {
if (!swallowClick) return
swallowClick = false
e.stopPropagation()
e.preventDefault()
}
function onWheel(e: WheelEvent) {
if (!opts.enabled()) return
e.preventDefault()
const lines = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? 400 : 1
// A trackpad pinch comes as a wheel with ctrl and small steps.
const speed = e.ctrlKey ? 0.01 : 0.0015
zoomAt(Math.exp(-e.deltaY * lines * speed), e.clientX, e.clientY)
}
// A building reached by Tab that lies outside the free part of the view comes into it.
function onFocusIn(e: FocusEvent) {
const el = e.target
const stage = opts.stage.value
if (!opts.enabled() || !(el instanceof SVGGraphicsElement) || !stage?.clientWidth) return
const box = el.getBBox()
const x = box.x + box.width / 2
const y = box.y + box.height / 2
const v = view.value
const perPixel = v.w / stage.clientWidth
const inset = opts.inset()
const free = { x: v.x + inset.left * perPixel, y: v.y + inset.top * perPixel, r: v.x + v.w - inset.right * perPixel, b: v.y + v.h - inset.bottom * perPixel }
if (x > free.x && x < free.r && y > free.y && y < free.b) return
const c = camera.value
camera.value = { ...c, dx: c.dx + x - (free.x + free.r) / 2, dy: c.dy + y - (free.y + free.b) / 2 }
}
function onKey(e: KeyboardEvent) {
if (!opts.enabled() || e.ctrlKey || e.metaKey || e.altKey || document.querySelector('dialog[open]')) return
const el = e.target as HTMLElement | null
if (el && (el.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(el.tagName))) return
// Arrows pan only while nothing else has focus, so they keep scrolling lists in windows.
const free = !el || el === document.body || !!opts.stage.value?.contains(el)
const step = e.shiftKey ? 240 : 80
const arrows: Record<string, [number, number]> = { ArrowLeft: [step, 0], ArrowRight: [-step, 0], ArrowUp: [0, step], ArrowDown: [0, -step] }
if (e.key === '+' || e.key === '=') zoomIn()
else if (e.key === '-' || e.key === '_') zoomOut()
else if (e.key === '0') reset()
else if (arrows[e.key] && free) panBy(...arrows[e.key]!)
else return
e.preventDefault()
}
onMounted(() => {
const el = opts.stage.value
if (!el) return
el.addEventListener('pointerdown', onPointerDown)
el.addEventListener('pointermove', onPointerMove)
el.addEventListener('pointerup', onPointerUp)
el.addEventListener('pointercancel', onPointerUp)
el.addEventListener('click', onClick, true)
el.addEventListener('wheel', onWheel, { passive: false })
el.addEventListener('focusin', onFocusIn)
window.addEventListener('keydown', onKey)
})
onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
return { view, viewBox, panning, zoomIn, zoomOut, reset, canZoomIn, canZoomOut, atHome }
}