1// The stage: the canvas the game is drawn on, and the camera over it. Anything that 2// has to turn a world point into a screen pixel, or back, asks here and nowhere else. 3import { CELL, CELL_WORLD, GALAXY_MAX, GALAXY_MIN, ZOOM_MAX, ZOOM_MIN, type Camera } from './view'; 4 5export const canvas = document.getElementById('view') as HTMLCanvasElement; 6 7export type Scene = 'local' | 'galaxy'; 8type Cam = Camera & { follow: boolean; scene: Scene }; 9 10// Two scenes, two cameras: the map keeps the pan and zoom you left it at, and 11// coming back to local space finds that camera exactly where it was, following or 12// not. 13const cams: Record<Scene, Cam> = { 14 local: { x: 0, y: 0, zoom: ZOOM_MIN, follow: true, scene: 'local' }, 15 galaxy: { x: 0, y: 0, zoom: GALAXY_MIN, follow: false, scene: 'galaxy' }, 16}; 17export let cam: Cam = cams.local; 18export const switchScene = (s: Scene): void => { 19 cam = cams[s]; 20}; 21 22export const wpc = () => CELL_WORLD / cam.zoom; // world units per character cell 23export const wpp = () => wpc() / CELL; // world units per css px 24export const rect = () => canvas.getBoundingClientRect(); 25 26export const pan = (dx: number, dy: number) => { 27 cam.x += dx; 28 cam.y += dy; 29 cam.follow = false; 30}; 31export const snap = (x: number, y: number) => { 32 cam.x = x; 33 cam.y = y; 34}; 35 36export const at = (e: { clientX: number; clientY: number }) => { 37 const r = rect(); // the camera is centered on the canvas, not the window 38 return { 39 x: cam.x + (e.clientX - r.left - r.width / 2) * wpp(), 40 y: cam.y - (e.clientY - r.top - r.height / 2) * wpp(), // screen y points down, world y up 41 }; 42}; 43 44export const screenOf = (r: DOMRect, x: number, y: number) => ({ 45 px: r.left + r.width / 2 + (x - cam.x) / wpp(), 46 py: r.top + r.height / 2 - (y - cam.y) / wpp(), 47}); 48export const screen = (x: number, y: number) => screenOf(rect(), x, y); 49 50export const cellOf = (px: number, py: number, r = rect()) => ({ 51 cellX: Math.floor((px - r.left) / CELL), 52 cellY: Math.floor((py - r.top) / CELL), 53}); 54 55// Zoom is multiplicative and anchored on the world point under the cursor, and it 56// stops at the range of the scene it is in. 57export const zoomAt = (e: { clientX: number; clientY: number; deltaY: number }) => { 58 const a = at(e); 59 const [lo, hi] = cam.scene === 'galaxy' ? [GALAXY_MIN, GALAXY_MAX] : [ZOOM_MIN, ZOOM_MAX]; 60 const z = Math.min(hi, Math.max(lo, cam.zoom * Math.exp(-e.deltaY * 0.0015))); 61 if (z === cam.zoom) return; 62 cam.zoom = z; 63 const b = at(e); 64 cam.x += a.x - b.x; 65 cam.y += a.y - b.y; 66};