quill/val Public Public: anyone can read this; nobody can change it.

forked from benjivers/val

workbenchthis machine
Files 03302de7b925b15e6e7d266e9a2ca7c5b4a55296
910 lines · 35.3 KB · ~10k tok Raw History
1
/**
2
 * val, in a browser. It draws what the server sends and sends what the
3
 * person does — nothing else. There is no position here the server did not
4
 * hand over, and no enemy in a snapshot the server decided you cannot see,
5
 * so a patched client learns nothing a plain one does not.
6
 *
7
 * This file is the wiring: the socket, the keys and the pointer, the HUD.
8
 * The drawing lives beside it — `scene.js` for the first-person view,
9
 * `topdown.js` for the map, `gun.js` for the crosshair, `prompt.js` for the
10
 * line of advice and `raycast.js` for the maths all of it stands on.
11
 */
12
"use strict";
13
14
import { makeBeeper } from "./beep.js";
15
import { makeBudget, measure } from "./budget.js";
16
import { arrive, bodyAt, delay, feed, makeTimeline, renderTime } from "./interp.js";
17
import { BODY_R, moveSpeed } from "../src/glide.ts";
18
import { drawGun, gunSnapshot, gunTick, makeGun } from "./gun.js";
19
import { advance, anchor, holdBack, insideWall, makeLocal, project, reconcile } from "./predict.js";
20
import { forget, ghosts, makePresence, shown, sighted, slide } from "./presence.js";
21
import { choosePrompt, REACH } from "./prompt.js";
22
import { renderSize, WIDTHS } from "./resolution.js";
23
import { roster, rosterKey } from "./roster.js";
24
import { AGENT_COLOUR, drawScene, makeScene } from "./scene.js";
25
import { moveVector } from "./steer.js";
26
import { drawTopdown } from "./topdown.js";
27
import { drawWatching, watching, watchLines } from "./watch.js";
28
import { aim as aimAt, makeYaw, settle, told, turn } from "./yaw.js";
29
30
const $ = (id) => document.getElementById(id);
31
const view = $("view");
32
const ctx = view.getContext("2d");
33
// The world is drawn here, at a few hundred columns, and blitted onto the
34
// visible canvas scaled. The HUD, the crosshair and the minimap are drawn on
35
// `view` itself, at whatever the device pixel ratio really is.
36
const sceneCanvas = document.createElement("canvas");
37
const sceneCtx = sceneCanvas.getContext("2d");
38
39
const KEY_SLOT = { KeyC: "c", KeyQ: "q", KeyE: "e", KeyX: "x" };
40
const COARSE = matchMedia("(pointer: coarse)").matches;
41
const LOOK = 0.0022; // radians per pixel of mouse travel
42
const HELP_SEEN = "val.help.seen";
43
44
let map = null;
45
let solid = () => true;
46
let world = null; // what predict.js slides against: the grid, from map.json
47
let pens = null; // the spawn tiles each side is penned to during the buy phase
48
let snap = null;
49
let socket = null;
50
let agents = null;
51
// Everybody else, kept as the last few things the server said about them and
52
// drawn between those — see interp.js. `drawAt` is the moment this frame is
53
// drawing, a snapshot interval behind the present.
54
const timeline = makeTimeline();
55
let drawAt = 0;
56
// Who is in sight and who just left it — see presence.js. A body the server
57
// has only now started sending has no history at all, and drawing it solid
58
// at its exact position is what makes enemies appear to teleport into a room.
59
const presence = makePresence();
60
const slid = { x: 0, y: 0, angle: 0 };
61
let marks = [];
62
let nowSec = performance.now() / 1000;
63
const keys = new Set();
64
// Where this person is looking: the browser's between snapshots, and the
65
// server's word taken only when it is saying something we did not. See
66
// yaw.js — a snapshot that stomps this is what made looking around choppy.
67
const head = makeYaw();
68
let locked = false;
69
let firing = false;
70
let mode = COARSE ? "top" : "fp"; // a raycaster with touch look is miserable
71
let mapOpen = false;
72
let pointer = null; // aim target in canvas pixels, top-down only
73
let stick = null; // { id, ox, oy, mx, my }
74
let aimTouch = null;
75
let helpShown = false;
76
let last = performance.now();
77
let snapAt = last; // when the last snapshot landed: how stale the answer is
78
// How many columns the world is drawn at, and what the frame is costing.
79
// See resolution.js for the ladder and budget.js for the rung it settles on:
80
// the visible canvas is device pixels, this is not.
81
const budget = makeBudget(0, WIDTHS.length - 1);
82
let render = { width: 960, height: 600 };
83
let perfOn = false;
84
let perfAt = 0;
85
86
const walk = { x: 0, y: 0 };
87
// What this person is doing right now, read once a frame for the drawing and
88
// once every 50ms for the server. The same object either way: no allocation
89
// in a loop that runs sixty times a second.
90
const intent = { mx: 0, my: 0, angle: 0, fire: false, use: false, reload: false };
91
// Your own body, run forward from your own keys between snapshots, and the
92
// object the drawing is handed for it.
93
const local = makeLocal();
94
const drawnMe = { id: "", x: 0, y: 0, angle: 0 };
95
const scene = makeScene();
96
const gun = makeGun();
97
const beeper = makeBeeper();
98
99
// ------------------------------------------------------------------ socket
100
101
function connect() {
102
  const url = (location.protocol === "https:" ? "wss://" : "ws://") + location.host + "/ws";
103
  socket = new WebSocket(url);
104
  socket.onopen = () => ($("conn").textContent = "live");
105
  socket.onclose = () => {
106
    $("conn").textContent = "reconnecting…";
107
    setTimeout(connect, 1500);
108
  };
109
  socket.onmessage = (event) => {
110
    const data = JSON.parse(event.data);
111
    if (data.t !== "s") return;
112
    snap = data;
113
    snapAt = performance.now();
114
    // No seat, no `me`, no players. Everything below reads a body out of the
115
    // snapshot, so a watching connection takes the other path entirely.
116
    if (watching(data)) return void paintWatch(data);
117
    // Timed samples for every body in it, ours included: the drawing walks
118
    // between them rather than chasing the newest one.
119
    arrive(timeline, snapAt / 1000);
120
    // Between rounds everybody is teleported to a spawn, so no sighting
121
    // before that says anything about where anybody is now.
122
    if (data.phase !== "live") forget(presence);
123
    else sighted(presence, data.players, snapAt / 1000);
124
    feed(timeline, data.me.id, data.me, snapAt / 1000);
125
    for (const player of data.players) feed(timeline, player.id, player, snapAt / 1000);
126
    // The server's angle is taken only when it is a correction, never as the
127
    // routine echo of the angle we sent it a moment ago.
128
    settle(head, data.me, snapAt / 1000);
129
    gunSnapshot(gun, data);
130
    paintHud(data);
131
    maybeHelp(data);
132
  };
133
}
134
135
const send = (message) => {
136
  if (socket && socket.readyState === 1) socket.send(JSON.stringify(message));
137
};
138
139
// ------------------------------------------------------------------- input
140
141
/**
142
 * Swap the view. The two share one facing — whichever you leave, you keep
143
 * looking the way you were looking — so nothing here touches the angle.
144
 */
145
function setMode(next) {
146
  mode = next;
147
  $("stage").dataset.mode = next;
148
  if (next !== "fp" && document.pointerLockElement === view) document.exitPointerLock();
149
}
150
151
addEventListener("keydown", (event) => {
152
  if (event.target instanceof HTMLInputElement) return;
153
  if (event.code === "Tab") {
154
    mapOpen = true;
155
    event.preventDefault();
156
    return;
157
  }
158
  if (event.code === "KeyH" || event.key === "?") {
159
    toggleHelp();
160
    event.preventDefault();
161
    return;
162
  }
163
  if (event.code === "KeyV") {
164
    setMode(mode === "fp" ? "top" : "fp");
165
    event.preventDefault();
166
    return;
167
  }
168
  if (event.code === "KeyB") {
169
    toggleBuy();
170
    event.preventDefault();
171
    return;
172
  }
173
  if (event.code === "F3" || event.code === "Backquote") {
174
    togglePerf();
175
    event.preventDefault();
176
    return;
177
  }
178
  if (KEY_SLOT[event.code]) {
179
    send({ t: "i", c: KEY_SLOT[event.code] });
180
    event.preventDefault();
181
    return;
182
  }
183
  keys.add(event.code);
184
  if (["KeyW", "KeyA", "KeyS", "KeyD", "Space", "KeyF", "KeyR", "ArrowLeft", "ArrowRight"].includes(event.code))
185
    event.preventDefault();
186
});
187
addEventListener("keyup", (event) => {
188
  if (event.code === "Tab") mapOpen = false;
189
  keys.delete(event.code);
190
});
191
addEventListener("blur", () => {
192
  keys.clear();
193
  mapOpen = false;
194
  firing = false;
195
});
196
197
// Aiming is pointer lock: click the canvas to capture the mouse, move to
198
// look, Escape gives it back. The angle sent is the same angle as ever.
199
view.addEventListener("click", () => {
200
  beeper.wake();
201
  if (watching(snap)) return; // nothing to aim: capturing the mouse would be a lie
202
  if (mode !== "fp" || locked) return;
203
  if (!view.requestPointerLock) return setMode("top"); // no lock, no first person
204
  // Asked for too soon after the last release, a browser rejects this; that
205
  // is a shrug, not an error, and the hint stays up until it takes.
206
  const asked = view.requestPointerLock();
207
  if (asked && asked.catch) asked.catch(() => {});
208
});
209
document.addEventListener("pointerlockchange", () => {
210
  locked = document.pointerLockElement === view;
211
  if (!locked) firing = false;
212
  $("stage").dataset.locked = locked ? "1" : "";
213
});
214
addEventListener("mousemove", (event) => {
215
  if (locked) turn(head, event.movementX * LOOK);
216
});
217
addEventListener("mousedown", (event) => {
218
  if (locked && event.button === 0) firing = true;
219
});
220
addEventListener("mouseup", (event) => {
221
  if (locked && event.button === 0) firing = false;
222
});
223
224
// The top-down view keeps the pointer aim it always had: it is the phone
225
// control scheme, and the fallback when the first-person view is not wanted.
226
const canvasPoint = (event) => {
227
  const box = view.getBoundingClientRect();
228
  return {
229
    x: ((event.clientX - box.left) / box.width) * view.width,
230
    y: ((event.clientY - box.top) / box.height) * view.height,
231
  };
232
};
233
view.addEventListener("pointermove", (event) => {
234
  if (mode !== "top" || event.pointerType === "touch") return;
235
  pointer = canvasPoint(event);
236
});
237
view.addEventListener("pointerdown", (event) => {
238
  beeper.wake();
239
  if (mode !== "top") return;
240
  view.setPointerCapture(event.pointerId);
241
  const box = view.getBoundingClientRect();
242
  if (event.pointerType === "touch") {
243
    if (event.clientX - box.left < box.width / 2)
244
      stick = { id: event.pointerId, ox: event.clientX, oy: event.clientY, mx: 0, my: 0 };
245
    else {
246
      aimTouch = { id: event.pointerId, ...canvasPoint(event) };
247
      firing = true;
248
    }
249
    event.preventDefault();
250
    return;
251
  }
252
  pointer = canvasPoint(event);
253
  firing = true;
254
});
255
view.addEventListener("pointermove", (event) => {
256
  if (stick && event.pointerId === stick.id) {
257
    const dx = event.clientX - stick.ox;
258
    const dy = event.clientY - stick.oy;
259
    const len = Math.hypot(dx, dy) || 1;
260
    const reach = Math.min(len, 48) / 48;
261
    stick.mx = (dx / len) * reach;
262
    stick.my = (dy / len) * reach;
263
  }
264
  if (aimTouch && event.pointerId === aimTouch.id) Object.assign(aimTouch, canvasPoint(event));
265
});
266
const endPointer = (event) => {
267
  if (stick && event.pointerId === stick.id) stick = null;
268
  else if (aimTouch && event.pointerId === aimTouch.id) {
269
    aimTouch = null;
270
    firing = false;
271
  } else firing = false;
272
};
273
view.addEventListener("pointerup", endPointer);
274
view.addEventListener("pointercancel", endPointer);
275
view.addEventListener("contextmenu", (event) => event.preventDefault());
276
277
// What this person is doing, in the world's terms. In the first-person view
278
// the keys are read against the way you are facing; in the top-down view they
279
// are the compass, the way they always were.
280
function readIntent() {
281
  let ax = 0;
282
  let ay = 0;
283
  if (keys.has("KeyW")) ay -= 1;
284
  if (keys.has("KeyS")) ay += 1;
285
  if (keys.has("KeyA")) ax -= 1;
286
  if (keys.has("KeyD")) ax += 1;
287
  if (stick) {
288
    ax = stick.mx;
289
    ay = stick.my;
290
  }
291
  intent.mx = ax;
292
  intent.my = ay;
293
  if (mode === "fp") {
294
    intent.angle = head.angle;
295
    moveVector(ax, ay, head.angle, walk);
296
    intent.mx = walk.x;
297
    intent.my = walk.y;
298
  } else {
299
    const aim = aimTouch || pointer;
300
    const me = worldToScreen(drawnMe.id ? drawnMe : snap.me);
301
    // The pointer is this view's aim, and it is ours the same way the mouse
302
    // is: with no pointer yet, keep the facing rather than the stale answer.
303
    if (aim) aimAt(head, Math.atan2(aim.y - me.y, aim.x - me.x));
304
    intent.angle = head.angle;
305
  }
306
  intent.fire = firing || keys.has("Space");
307
  intent.use = keys.has("KeyF");
308
  intent.reload = keys.has("KeyR");
309
  return intent;
310
}
311
312
// Twenty times a second the server hears it. Intent only — a direction, an
313
// angle, a held key — never a position: the guess below is for drawing.
314
setInterval(() => {
315
  if (!snap || !map || watching(snap)) return; // nothing to drive, nothing to send
316
  const now = readIntent();
317
  send({ t: "i", mx: now.mx, my: now.my, a: now.angle, f: now.fire, u: now.use, r: now.reload });
318
  // What we told it, so its echo is recognisable as ours when it comes back.
319
  told(head, now.angle, performance.now() / 1000);
320
}, 50);
321
322
// ------------------------------------------------------------------ drawing
323
324
function resize() {
325
  const box = view.getBoundingClientRect();
326
  const dpr = Math.min(devicePixelRatio || 1, 2);
327
  view.width = Math.round(box.width * dpr);
328
  view.height = Math.round(box.height * dpr);
329
  sizeRender();
330
}
331
addEventListener("resize", resize);
332
333
/** The offscreen the world is drawn into, at the level in force right now. */
334
function sizeRender() {
335
  render = renderSize(view.width, view.height, budget.level);
336
  if (sceneCanvas.width !== render.width) sceneCanvas.width = render.width;
337
  if (sceneCanvas.height !== render.height) sceneCanvas.height = render.height;
338
}
339
340
const scale = () => (map ? view.width / (map.rows[0].length * map.tile) : 1);
341
const worldToScreen = (p) => ({ x: p.x * scale(), y: p.y * scale() });
342
343
/**
344
 * Everybody else is drawn at `drawAt`: between the two samples that bracket
345
 * it, so they move at the server's own speed and arrive where it put them.
346
 * You are not: your own body is the one this browser can run forward
347
 * honestly, and drawing it late is what dragged the camera backwards.
348
 */
349
const look = (p) => {
350
  if (predicting() && p.id === snap.me.id) return drawnMe;
351
  // Your own body, when it is not being predicted — the buy phase, or dead —
352
  // is drawn from the newest word about it and nothing else. It must not go
353
  // through the two treatments below, which exist for OTHER people: drawing
354
  // it in the past puts the camera behind your own mouse, and the arriving
355
  // slide treats a respawn as somebody walking into view and slides the
356
  // camera in from the last place it saw you. Together they are the shake at
357
  // spawn.
358
  if (p.id === snap.me.id) return p;
359
  // A body still arriving is drawn part of the way in from where it came,
360
  // rather than at the position it had already reached when we first saw it.
361
  return slide(presence, p.id, bodyAt(timeline, p, drawAt), nowSec, slid);
362
};
363
364
/** How far into sight somebody is: 0 as they appear, 1 once they are solid. */
365
const shownAt = (p) => shown(presence, p.id, nowSec);
366
367
/**
368
 * Your own movement is only guessed at while the round is live and you are
369
 * alive. The buy phase pens everybody in their own spawn — a rule of the
370
 * match, not of the map — and a guess that does not know it would spend the
371
 * phase being pulled back through the door.
372
 */
373
const predicting = () =>
374
  snap !== null && !watching(snap) && world !== null && snap.me.alive && (snap.phase !== "buy" || pens !== null);
375
376
/** The server's own rule: in the buy phase, nowhere further than 120 from a spawn. */
377
const outsidePen = (x, y) => {
378
  if (snap.phase !== "buy" || pens === null) return false;
379
  const cells = pens[snap.me.side] ?? [];
380
  if (cells.length === 0) return false;
381
  let best = Infinity;
382
  for (const c of cells) best = Math.min(best, Math.hypot(c.x - x, c.y - y));
383
  return best > 120;
384
};
385
386
/** The server's answer, caught up to now, then this frame of your own keys. */
387
function predict(dt, now) {
388
  if (!predicting()) {
389
    local.ready = false;
390
    drawnMe.id = "";
391
    return;
392
  }
393
  const held = readIntent();
394
  const speed = moveSpeed({
395
    haste: snap.me.haste > 0,
396
    slow: snap.me.slow > 0,
397
    stopped: snap.me.planting > 0 || snap.me.defusing,
398
    heavy: snap.me.weapon === "operator",
399
  });
400
  // The snapshot is a moment old and the keys held since have not reached
401
  // it; carry it that far forward and lean the drawn body onto it.
402
  const target = project(snap.me, held.mx, held.my, speed, (now - snapAt) / 1000, world);
403
  const was = { x: local.x, y: local.y };
404
  reconcile(local, target, dt);
405
  advance(local, held.mx, held.my, speed, dt, world);
406
  holdBack(local, target, held.mx, held.my);
407
  // A lean across a corner can put the drawn body inside a wall, and walking
408
  // out of the spawn pen is refused by the server outright. Both used to take
409
  // the server's answer, which is a jump: pressed against a wall and strafing,
410
  // that fired most frames and read as a stutter. Holding the last good place
411
  // is invisible and just as honest — the next snapshot corrects it anyway.
412
  if (insideWall(local, world) || outsidePen(local.x, local.y)) {
413
    local.x = was.x;
414
    local.y = was.y;
415
    if (insideWall(local, world)) anchor(local, snap.me);
416
  }
417
  drawnMe.id = snap.me.id;
418
  drawnMe.x = local.x;
419
  drawnMe.y = local.y;
420
  // Either view: the facing is the one this browser is holding, whether the
421
  // mouse moved it or the pointer aim did. The server hears it a moment later.
422
  drawnMe.angle = head.angle;
423
}
424
425
function frame(now) {
426
  requestAnimationFrame(frame);
427
  const began = performance.now();
428
  const dt = Math.min(0.1, (now - last) / 1000);
429
  last = now;
430
  nowSec = began / 1000;
431
  marks = ghosts(presence, nowSec);
432
  drawAt = renderTime(timeline, now / 1000);
433
  // A watching connection draws the watching view and stops there: it has no
434
  // map to stand on and no body to put on it, and must invent neither.
435
  if (watching(snap)) return void drawWatch();
436
  if (!map) return;
437
  gunTick(gun, dt);
438
  ctx.clearRect(0, 0, view.width, view.height);
439
440
  if (!snap) {
441
    drawTopdown(ctx, map, null, look, { x: 0, y: 0, w: view.width, h: view.height });
442
    return;
443
  }
444
  // Turning with the arrow keys belongs to the frame, at a rate a second,
445
  // rather than to whatever the input timer happens to do.
446
  if (mode === "fp" && keys.has("ArrowLeft")) turn(head, -0.9 * dt);
447
  if (mode === "fp" && keys.has("ArrowRight")) turn(head, 0.9 * dt);
448
  predict(dt, now);
449
  beeper.update(snap.spike.planted, snap.spike.fuse, now / 1000);
450
  const eye = look(snap.me);
451
  const facing = mode === "fp" ? head.angle : eye.angle;
452
453
  if (mode === "fp" && !mapOpen) {
454
    // The world at a few hundred columns, then scaled onto the canvas. The
455
    // walls are flat shaded, so the upscale costs the picture almost
456
    // nothing; the crosshair and the map below are drawn sharp on top.
457
    drawScene(sceneCtx, scene, { solid, tile: map.tile }, { x: eye.x, y: eye.y, angle: facing }, snap, {
458
      width: render.width,
459
      height: render.height,
460
      look,
461
      shown: shownAt,
462
      marks,
463
    });
464
    ctx.drawImage(sceneCanvas, 0, 0, view.width, view.height);
465
    drawGun(ctx, gun, view.width, view.height, snap);
466
    drawMinimap();
467
  } else {
468
    const box = { x: 0, y: 0, w: view.width, h: view.height };
469
    ctx.drawImage(tileLayer(view.width, view.height, true), 0, 0);
470
    drawTopdown(ctx, map, snap, look, box, { marks, tiles: false });
471
  }
472
473
  if (snap.me.planting > 0) bar(snap.me.planting / 4, "#e0a040", "planting");
474
  else if (snap.spike.planted && snap.spike.defuse > 0 && snap.me.side === "def")
475
    bar(snap.spike.defuse / 7, "#4fd6a0", "defusing");
476
  $("flash").style.opacity = Math.min(0.95, snap.me.blind * 0.8);
477
  $("dead").style.display = snap.me.alive ? "none" : "grid";
478
  $("aimhint").style.display = mode === "fp" && !locked && !COARSE ? "grid" : "none";
479
480
  // What this frame cost to draw, not how long the browser waited for the
481
  // next one: a machine with headroom is capped at its refresh rate, and the
482
  // renderer would never earn a rung back if that were the measure.
483
  const ended = performance.now();
484
  if (measure(budget, ended - began, ended / 1000)) sizeRender();
485
  paintPerf(ended);
486
}
487
488
/** F3 or ` — the numbers, so "it feels choppy" has something to argue with. */
489
function togglePerf() {
490
  perfOn = !perfOn;
491
  const box = $("perf");
492
  if (!box) return;
493
  box.style.display = perfOn ? "block" : "none";
494
  // Straight away, whatever the clock says: a readout you turn on and that
495
  // stays blank for half a second reads as a readout that does not work.
496
  if (perfOn) paintPerf(performance.now(), true);
497
}
498
499
/**
500
 * The readout, rewritten twice a second: the frame rate and the mean frame
501
 * the governor decided on, the rate snapshots are actually arriving at, the
502
 * interpolation delay in force, and how wide the world is being drawn.
503
 */
504
function paintPerf(nowMs, force) {
505
  const box = $("perf");
506
  if (!perfOn || !box || (!force && nowMs - perfAt < 500)) return;
507
  perfAt = nowMs;
508
  const hz = timeline.interval > 0 ? 1 / timeline.interval : 0;
509
  box.textContent =
510
    `${budget.fps.toFixed(1)} fps · ${budget.mean.toFixed(1)} ms/frame · ` +
511
    `${hz.toFixed(1)} Hz in · ${(delay(timeline) * 1000).toFixed(0)} ms behind · ` +
512
    `${render.width}×${render.height} of ${view.width}×${view.height}`;
513
}
514
515
/**
516
 * The map's own tiles, drawn once a size and kept. There are 570 of them and
517
 * they are the same 570 every frame — on the minimap that was more fills
518
 * than the whole first-person view costs. Called with no snapshot,
519
 * `drawTopdown` draws exactly this layer and nothing else.
520
 */
521
const layers = new Map();
522
function tileLayer(w, h, labels) {
523
  const key = `${w}x${h}${labels ? "L" : ""}`;
524
  const had = layers.get(key);
525
  if (had) return had;
526
  const layer = document.createElement("canvas");
527
  layer.width = w;
528
  layer.height = h;
529
  drawTopdown(layer.getContext("2d"), map, null, look, { x: 0, y: 0, w, h }, { labels });
530
  if (layers.size > 3) layers.clear(); // a window being dragged, not a leak
531
  layers.set(key, layer);
532
  return layer;
533
}
534
535
/** The same top-down drawing, small, in the corner, with you as an arrow. */
536
function drawMinimap() {
537
  const w = Math.min(view.width * 0.3, 260 * (view.width / 900));
538
  const h = (w * map.rows.length) / map.rows[0].length;
539
  const pad = 8;
540
  ctx.save();
541
  ctx.globalAlpha = 0.85;
542
  ctx.fillStyle = "#0b0d11";
543
  ctx.fillRect(pad - 2, pad - 2, w + 4, h + 4);
544
  ctx.drawImage(tileLayer(Math.max(1, Math.round(w)), Math.max(1, Math.round(h)), false), pad, pad, w, h);
545
  drawTopdown(ctx, map, snap, look, { x: pad, y: pad, w, h }, { labels: false, marks, tiles: false });
546
  ctx.restore();
547
  ctx.strokeStyle = "rgba(255,255,255,0.18)";
548
  ctx.lineWidth = 1;
549
  ctx.strokeRect(pad - 2, pad - 2, w + 4, h + 4);
550
}
551
552
function bar(fraction, colour, label) {
553
  const w = view.width * 0.4;
554
  const x = view.width / 2 - w / 2;
555
  const y = view.height * 0.86;
556
  ctx.fillStyle = "#0009";
557
  ctx.fillRect(x, y, w, 16);
558
  ctx.fillStyle = colour;
559
  ctx.fillRect(x, y, w * Math.min(1, fraction), 16);
560
  ctx.fillStyle = "#fff";
561
  ctx.font = "12px system-ui, sans-serif";
562
  ctx.textAlign = "center";
563
  ctx.fillText(label, view.width / 2, y + 12);
564
  ctx.textAlign = "left";
565
}
566
567
// --------------------------------------------------------------------- hud
568
569
// The buy opens itself every buy phase; closing it is remembered until the
570
// next one, so nobody has to fight the panel to watch the round start.
571
function toggleBuy() {
572
  const open = $("buy").classList.toggle("on");
573
  $("buy").dataset.closed = open ? "" : "1";
574
}
575
$("buytoggle").addEventListener("click", toggleBuy);
576
$("viewtoggle").addEventListener("click", () => setMode(mode === "fp" ? "top" : "fp"));
577
$("helptoggle").addEventListener("click", () => toggleHelp());
578
$("helpclose").addEventListener("click", () => toggleHelp(false));
579
for (const button of document.querySelectorAll("[data-buy]"))
580
  button.addEventListener("click", () => send({ t: "buy", what: button.dataset.buy }));
581
for (const button of document.querySelectorAll("[data-agent]"))
582
  button.addEventListener("click", () => send({ t: "agent", id: button.dataset.agent }));
583
584
function toggleHelp(force) {
585
  const open = force === undefined ? $("help").style.display !== "grid" : force;
586
  $("help").style.display = open ? "grid" : "none";
587
  if (!open) {
588
    helpShown = true;
589
    try {
590
      localStorage.setItem(HELP_SEEN, "1");
591
    } catch {
592
      // A browser that refuses storage still gets the card, every visit.
593
    }
594
  }
595
}
596
597
/** The first-run card, once per browser, and never over a round in progress. */
598
function maybeHelp(s) {
599
  if (helpShown) return;
600
  try {
601
    if (localStorage.getItem(HELP_SEEN) === "1") {
602
      helpShown = true;
603
      return;
604
    }
605
  } catch {
606
    /* no storage: show it and move on */
607
  }
608
  if (s.phase === "live" && s.me.alive) return;
609
  helpShown = true;
610
  $("help").style.display = "grid";
611
}
612
613
const KITS = {};
614
615
function paintHud(s) {
616
  $("clock").textContent = Math.ceil(s.phase === "live" && s.spike.planted ? s.spike.fuse : s.clock);
617
  document.querySelector("#scoreline .red").textContent = "red " + s.score.red;
618
  document.querySelector("#scoreline .blue").textContent = s.score.blue + " blue";
619
  $("phase").textContent =
620
    `round ${s.round} · ${s.phase === "buy" ? "buy phase" : s.phase === "live" ? (s.spike.planted ? "spike down" : "live") : s.phase === "end" ? "round over" : "match over"} · ${s.attackers} attacking · you are ${s.me.side === "atk" ? "attacking" : "defending"}${s.result ? " · " + s.result : ""}`;
621
  $("hp").textContent = `${s.me.hp} hp${s.me.armour ? " +" + s.me.armour : ""}`;
622
  $("gun").textContent = `${s.me.weapon}${s.me.reloading ? " reloading" : " " + s.me.ammo}`;
623
  $("creds").textContent = `${s.me.credits} cr`;
624
  $("ultmeter").textContent = `ult ${s.me.ult}/${s.me.ultNeeds}`;
625
  $("buy").classList.toggle("on", s.phase === "buy" && $("buy").dataset.closed !== "1");
626
  if (s.phase !== "buy") $("buy").dataset.closed = "";
627
628
  const text = choosePrompt(s, {
629
    onSite: onSite(s.me),
630
    nearSpike: s.spike.x !== null && Math.hypot(s.spike.x - s.me.x, s.spike.y - s.me.y) < REACH,
631
  });
632
  if ($("prompt").textContent !== text) $("prompt").textContent = text;
633
634
  paintKit(s);
635
  paintBuy(s);
636
  paintRoster(s);
637
  paintFeed(s);
638
  paintLog(s);
639
640
  for (const side of ["atk", "def"]) {
641
    const body = $(side + "board");
642
    const rows = s.board.filter((p) => p.side === side).sort((a, b) => b.kills - a.kills);
643
    const key = rows.map((p) => `${p.name}${p.kills}${p.deaths}${p.alive}${p.credits}`).join();
644
    if (body.dataset.key === key) continue;
645
    body.dataset.key = key;
646
    body.replaceChildren();
647
    for (const player of rows) {
648
      const tr = document.createElement("tr");
649
      const cells = [
650
        player.name + (player.bot ? " (bot)" : "") + (player.alive ? "" : " ✕"),
651
        player.agent + (player.credits !== null ? ` · ${player.credits}cr` : ""),
652
        String(player.kills),
653
        String(player.deaths),
654
      ];
655
      for (const value of cells) {
656
        const td = document.createElement("td");
657
        td.textContent = value;
658
        tr.append(td);
659
      }
660
      if (player.id === s.me.id) tr.style.fontWeight = "700";
661
      body.append(tr);
662
    }
663
  }
664
}
665
666
/** The last few things that happened, in words. Rebuilt only when they change. */
667
function paintLog(s) {
668
  const log = $("log");
669
  const lines = (s.events ?? []).slice(0, 3);
670
  if (log.dataset.text === lines.join("\n")) return;
671
  log.dataset.text = lines.join("\n");
672
  log.replaceChildren();
673
  for (const line of lines) {
674
    const div = document.createElement("div");
675
    div.textContent = line;
676
    log.append(div);
677
  }
678
}
679
680
/**
681
 * The HUD for a connection with no seat. Everything a seat's HUD says about
682
 * you — health, gun, credits, kit, your five — has no answer here, so it says
683
 * so rather than leaving the page's first paint standing there going stale.
684
 */
685
function paintWatch(s) {
686
  const lines = watchLines(s);
687
  $("clock").textContent = Math.ceil(Math.max(0, Number(s.clock) || 0));
688
  document.querySelector("#scoreline .red").textContent = "red " + (s.score?.red ?? 0);
689
  document.querySelector("#scoreline .blue").textContent = (s.score?.blue ?? 0) + " blue";
690
  $("phase").textContent = lines.phase;
691
  $("hp").textContent = "watching";
692
  $("gun").textContent = "no seat";
693
  $("creds").textContent = "—";
694
  $("ultmeter").textContent = "—";
695
  $("buy").classList.toggle("on", false);
696
  if ($("prompt").textContent !== lines.why) $("prompt").textContent = lines.why;
697
  paintFeed(s);
698
  paintLog(s);
699
  blank($("kit"));
700
  blank($("roster"));
701
  blank($("atkboard"));
702
  blank($("defboard"));
703
  if (KITS.shape !== "watching") KITS.shape = "watching";
704
}
705
706
/** Empty a panel whose answer this connection is not sent, once. */
707
function blank(panel) {
708
  if (panel.dataset.key === "watching") return;
709
  panel.dataset.key = "watching";
710
  panel.dataset.text = "watching";
711
  panel.replaceChildren();
712
}
713
714
/** The canvas, watching: no map, no bodies, and the overlays a seat owns off. */
715
function drawWatch() {
716
  ctx.clearRect(0, 0, view.width, view.height);
717
  drawWatching(ctx, snap, view.width, view.height);
718
  $("flash").style.opacity = 0;
719
  $("dead").style.display = "none";
720
  $("aimhint").style.display = "none";
721
}
722
723
/** Is this player standing where the spike arms? The grid says so. */
724
function onSite(me) {
725
  if (!map) return false;
726
  const row = map.rows[Math.floor(me.y / map.tile)];
727
  const cell = row ? row[Math.floor(me.x / map.tile)] : "";
728
  return cell === "A" || cell === "B";
729
}
730
731
/**
732
 * What just happened to whom: newest first, and gone a few seconds later.
733
 * The server sends names and a gun and nothing else, so there is nothing
734
 * here to read a position out of.
735
 */
736
function paintFeed(s) {
737
  const box = $("feed");
738
  const lines = (s.feed ?? []).slice().reverse();
739
  // The age is bucketed into the key: an entry fades once on its way out
740
  // rather than rebuilding the panel every frame.
741
  const key = lines.map((l) => `${l.k}>${l.v}:${l.w}:${l.h}:${l.t > 6 ? "old" : "new"}`).join("|");
742
  if (box.dataset.key === key) return;
743
  box.dataset.key = key;
744
  box.replaceChildren();
745
  for (const line of lines) {
746
    const row = document.createElement("div");
747
    row.style.opacity = line.t > 6 ? "0.5" : "1";
748
    const killer = document.createElement("span");
749
    killer.className = "k";
750
    killer.textContent = line.k ?? "—";
751
    const victim = document.createElement("span");
752
    victim.className = "v";
753
    victim.textContent = line.v;
754
    const how = document.createElement("span");
755
    how.className = "w";
756
    how.textContent = `${line.w ? " " + line.w : " ability"}${line.h ? " ✧" : ""}`;
757
    const arrow = document.createElement("span");
758
    arrow.textContent = " ▸ ";
759
    row.append(killer, arrow, victim, how);
760
    box.append(row);
761
  }
762
}
763
764
/**
765
 * Your team, always on screen: five slots, health, and struck through when
766
 * somebody is dead. The one place both questions — who is with me, who is
767
 * still up — are answered whether anybody is in sight or not.
768
 */
769
function paintRoster(s) {
770
  const rows = roster(s);
771
  const panel = $("roster");
772
  const key = rosterKey(rows);
773
  if (panel.dataset.key === key) return;
774
  panel.dataset.key = key;
775
  panel.replaceChildren();
776
  for (const row of rows) {
777
    const slot = document.createElement("div");
778
    slot.className = `slot${row.mine ? " mine" : ""}${row.alive ? "" : " down"}`;
779
    slot.style.borderLeftColor = AGENT_COLOUR[row.agent] || "#4a5162";
780
    const who = document.createElement("span");
781
    who.className = "who";
782
    who.textContent = row.name;
783
    const agent = document.createElement("span");
784
    agent.className = "agent";
785
    agent.textContent = row.alive ? row.agent : `${row.agent} · dead`;
786
    if (row.spike) {
787
      const spike = document.createElement("span");
788
      spike.className = "spike";
789
      spike.textContent = " spike";
790
      agent.append(spike);
791
    }
792
    const bar = document.createElement("span");
793
    bar.className = "hp";
794
    const fill = document.createElement("i");
795
    fill.style.width = `${row.hp}%`;
796
    fill.style.background = row.hp > 40 ? "#6fcf6f" : "#e0a040";
797
    bar.append(fill);
798
    slot.append(who, agent, bar);
799
    panel.append(slot);
800
  }
801
}
802
803
const kitOf = (id) => (agents ? agents.find((a) => a.id === id) : null);
804
805
/** The four ability buttons, each saying what it does and what it has left. */
806
function paintKit(s) {
807
  const kit = $("kit");
808
  const agent = kitOf(s.me.agent);
809
  const shape =
810
    ["c", "q", "e", "x"].map((slot) => `${slot}${s.me.charges[slot]}${Math.ceil(s.me.cooldown[slot])}`).join("|") +
811
    s.me.agent +
812
    s.me.ult +
813
    (agent ? "k" : "");
814
  if (KITS.shape === shape) return;
815
  KITS.shape = shape;
816
  kit.replaceChildren();
817
  for (const slot of ["c", "q", "e", "x"]) {
818
    const ability = agent ? agent.abilities[slot] : null;
819
    const button = document.createElement("button");
820
    const ready = slot === "x" ? s.me.ult >= s.me.ultNeeds : s.me.charges[slot] > 0 && s.me.cooldown[slot] <= 0;
821
    button.disabled = !ready;
822
    button.type = "button";
823
    const count =
824
      slot === "x"
825
        ? `${s.me.ult}/${s.me.ultNeeds}`
826
        : s.me.cooldown[slot] > 0
827
          ? `${Math.ceil(s.me.cooldown[slot])}s`
828
          : s.me.charges[slot];
829
    const name = document.createElement("span");
830
    name.textContent = `${slot.toUpperCase()}${ability ? " " + ability.name : ""}`;
831
    const tally = document.createElement("b");
832
    tally.textContent = String(count);
833
    button.append(name, tally);
834
    if (ability) button.title = `${ability.name} — ${ability.text}`;
835
    button.addEventListener("click", () => send({ t: "i", c: slot }));
836
    kit.append(button);
837
  }
838
}
839
840
/** Prices on every button, greyed when you cannot afford it. */
841
function paintBuy(s) {
842
  const agent = kitOf(s.me.agent);
843
  for (const button of document.querySelectorAll("[data-buy]")) {
844
    const what = button.dataset.buy;
845
    let cost = Number(button.dataset.cost ?? 0);
846
    if ((what === "c" || what === "q") && agent) {
847
      const ability = agent.abilities[what];
848
      cost = ability.cost;
849
      button.replaceChildren();
850
      const name = document.createElement("span");
851
      name.textContent = `${what.toUpperCase()} ${ability.name}`;
852
      const price = document.createElement("b");
853
      price.textContent = `${ability.cost} · ${s.me.charges[what]}/${ability.charges}`;
854
      button.append(name, price);
855
      button.title = `${ability.text} (${ability.charges} charge${ability.charges === 1 ? "" : "s"} a round)`;
856
    }
857
    button.disabled = cost > s.me.credits;
858
  }
859
  for (const button of document.querySelectorAll("[data-agent]")) {
860
    const picked = button.dataset.agent === s.me.agent;
861
    button.style.outline = picked ? "2px solid #6fcf9f" : "";
862
  }
863
}
864
865
// ------------------------------------------------------------------- start
866
867
Promise.all([fetch("/map.json").then((r) => r.json()), fetch("/agents.json").then((r) => r.json())])
868
  .then(([mapData, kit]) => {
869
    map = mapData;
870
    agents = kit.agents;
871
    const rows = map.rows;
872
    const cols = rows[0].length;
873
    solid = (col, row) =>
874
      col < 0 || row < 0 || row >= rows.length || col >= cols || rows[row][col] === "#";
875
    // The same grid the server collides against, so a guess about your own
876
    // movement lands where the server's answer is about to.
877
    world = { solid, tile: map.tile, r: BODY_R };
878
    // The buy phase pens everybody in their own spawn, and the map the client
879
    // is handed carries the spawn tiles ('a' attackers, 'd' defenders), so the
880
    // browser can know the rule rather than turning prediction off through the
881
    // whole phase and drawing your own body thirty times a second.
882
    const cellsOf = (letter) => {
883
      const out = [];
884
      for (let row = 0; row < rows.length; row++)
885
        for (let col = 0; col < cols; col++)
886
          if (rows[row][col] === letter)
887
            out.push({ x: (col + 0.5) * map.tile, y: (row + 0.5) * map.tile });
888
      return out;
889
    };
890
    pens = { atk: cellsOf("a"), def: cellsOf("d") };
891
    $("stage").dataset.mode = mode;
892
    fillHelp();
893
    resize();
894
    connect();
895
  })
896
  .catch(() => ($("conn").textContent = "offline"));
897
898
/** The card says the round, the sides, the keys and the kit, in that order. */
899
function fillHelp() {
900
  const list = $("helpagents");
901
  if (!list || !agents) return;
902
  list.replaceChildren();
903
  for (const agent of agents) {
904
    const li = document.createElement("li");
905
    li.textContent = `${agent.name} (${agent.role}) — ${agent.blurb}`;
906
    list.append(li);
907
  }
908
}
909
910
requestAnimationFrame(frame);
↑↓ navigate ↵ open esc close
↑↓ navigate ↵ open esc close

Keyboard shortcuts