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

forked from benjivers/val

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

Keyboard shortcuts