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

forked from benjivers/val

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

Keyboard shortcuts