Split The code is public; the app answers only to the crew.

Your crosshair: colour, size, gap, thickness and a dot, remembered like the rest #121

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

vesper/cs:vesper/81-your-crosshair-colour-size-gap-thickness → main 1 commit fork

  • Merged. vesper/81-your-crosshair-colour-size-gap-thickness was merged into main as 9c1997d.

Review

Sign in to review this change.
11 files changed +584 −21
README.md +17
@@ -214,6 +214,23 @@ running — a difficulty picked there takes effect from the next round, never
214214 the one in progress, so changing it mid-fight cannot hand a bot new hands
215215 between one shot and the next.
216216
217 **The crosshair is yours.** A collapsed **Crosshair** disclosure sits under
218 Controls in the menu and again in the pause overlay, with the same six
219 settings in both: **colour** (one of six names — green, white, cyan, yellow,
220 magenta or red — and never a colour you type, since a string that reaches the
221 canvas is an input like any other), **size**, **gap**, **thickness**, a
222 centre **dot** and **dynamic**. Every change takes hold on the next frame,
223 mid-match included, and is remembered for next time alongside sound,
224 sensitivity and your keys. **Dynamic is the default**, and it is the one worth
225 keeping: the arms open exactly as far as the gun is currently inaccurate, so a
226 crosshair that has settled is a shot that will land and a crosshair still
227 wide is the game telling you to stop moving before you fire. Turn it off and
228 the crosshair is the same size whatever you are doing. The defaults are the
229 crosshair this game has always drawn — green, four pixels of gap, seven-pixel
230 arms, two wide, no dot — so nothing moves until you ask it to, and a setting
231 that was never saved, or one saved before these existed, loads as exactly
232 that.
233
217234 Paused means paused. While the pause overlay or the match-over card is up the
218235 world does not run: no ticks, no round clock, no bots, no bomb timer, and the
219236 canvas keeps the last frame it drew. A hidden tab pauses the same way, so
src/client/crosshair.test.ts added +90
@@ -0,0 +1,90 @@
1 /**
2 * The crosshair's shape, without a canvas: four arms, where they start and
3 * where they end. The one thing that has to stay true is the default — the
4 * crosshair this game has always drawn — and the one thing a setting has to
5 * do is move it.
6 */
7
8 import { expect, test } from "bun:test";
9 import {
10 CROSSHAIR_COLOURS, CROSSHAIR_COLOUR_NAMES, crosshairShape, DEFAULT_CROSSHAIR, SPREAD_GAP,
11 type CrosshairStyle,
12 } from "./crosshair.ts";
13
14 const style = (over: Partial<CrosshairStyle> = {}): CrosshairStyle => ({ ...DEFAULT_CROSSHAIR, ...over });
15
16 /** How far the near end of the right-hand arm sits from the middle. */
17 const innerRight = (shape: { segments: { x1: number }[] }): number => shape.segments[0].x1 - 100;
18 /** How long the right-hand arm is. */
19 const armLength = (shape: { segments: { x1: number; x2: number }[] }): number =>
20 shape.segments[0].x2 - shape.segments[0].x1;
21
22 test("the default is today's crosshair: a gap of four, arms of seven, two wide, no dot", () => {
23 const shape = crosshairShape(style(), 0, 100, 100);
24 expect(shape.colour).toBe("rgba(120, 255, 140, 0.9)");
25 expect(shape.thickness).toBe(2);
26 expect(shape.dot).toBeNull();
27 expect(shape.segments).toEqual([
28 { x1: 104, y1: 100, x2: 111, y2: 100 },
29 { x1: 96, y1: 100, x2: 89, y2: 100 },
30 { x1: 100, y1: 104, x2: 100, y2: 111 },
31 { x1: 100, y1: 96, x2: 100, y2: 89 },
32 ]);
33 });
34
35 test("a larger gap moves the arms out without making them longer", () => {
36 const near = crosshairShape(style({ gap: 4 }), 0, 100, 100);
37 const far = crosshairShape(style({ gap: 12 }), 0, 100, 100);
38 expect(innerRight(far)).toBe(innerRight(near) + 8);
39 expect(armLength(far)).toBe(armLength(near));
40 // Every arm moves, not just the one: up is eight further up.
41 expect(far.segments[3].y1).toBe(near.segments[3].y1 - 8);
42 });
43
44 test("a larger size makes the arms longer without moving them out", () => {
45 const small = crosshairShape(style({ size: 7 }), 0, 100, 100);
46 const big = crosshairShape(style({ size: 16 }), 0, 100, 100);
47 expect(armLength(big)).toBe(16);
48 expect(innerRight(big)).toBe(innerRight(small));
49 });
50
51 test("a dynamic crosshair opens with the spread, a static one never moves", () => {
52 const still = crosshairShape(style(), 0, 100, 100);
53 const spraying = crosshairShape(style(), 1.5, 100, 100);
54 expect(innerRight(spraying)).toBeCloseTo(innerRight(still) + 1.5 * SPREAD_GAP, 10);
55 expect(armLength(spraying)).toBe(armLength(still));
56
57 const fixed = crosshairShape(style({ dynamic: false }), 1.5, 100, 100);
58 expect(fixed.segments).toEqual(still.segments);
59 });
60
61 test("a spread that is not a number never reaches the arms", () => {
62 const still = crosshairShape(style(), 0, 100, 100);
63 for (const spread of [NaN, Infinity, -3]) {
64 expect(crosshairShape(style(), spread, 100, 100).segments).toEqual(still.segments);
65 }
66 });
67
68 test("the dot is there only when it is asked for, and it is as wide as the arms", () => {
69 expect(crosshairShape(style({ dot: false }), 0, 100, 100).dot).toBeNull();
70 expect(crosshairShape(style({ dot: true, thickness: 4 }), 0, 100, 100).dot)
71 .toEqual({ x: 100, y: 100, radius: 2 });
72 // The dot sits in the middle whatever the gap does.
73 const wide = crosshairShape(style({ dot: true, gap: 18 }), 2, 100, 100);
74 expect(wide.dot).toEqual({ x: 100, y: 100, radius: 1 });
75 });
76
77 test("the crosshair is drawn where it is told, not at some fixed middle", () => {
78 const shape = crosshairShape(style(), 0, 640, 360);
79 expect(shape.segments[0]).toEqual({ x1: 644, y1: 360, x2: 651, y2: 360 });
80 expect(shape.segments[2]).toEqual({ x1: 640, y1: 364, x2: 640, y2: 371 });
81 });
82
83 test("every colour name resolves to a colour, and the names are the table's own keys", () => {
84 for (const name of CROSSHAIR_COLOUR_NAMES) {
85 expect(crosshairShape(style({ colour: name }), 0, 100, 100).colour).toBe(CROSSHAIR_COLOURS[name]);
86 expect(CROSSHAIR_COLOURS[name]).toMatch(/^rgba\(/);
87 }
88 expect(CROSSHAIR_COLOUR_NAMES).toContain("green");
89 expect(CROSSHAIR_COLOUR_NAMES.length).toBeGreaterThan(3);
90 });
src/client/crosshair.ts added +108
@@ -0,0 +1,108 @@
1 /**
2 * The crosshair: a style and the gun's current inaccuracy in, the lines and
3 * the dot to draw out. Pure — no canvas, no world, no settings — so what a
4 * gap of six or a static crosshair actually does to the shape is a test and
5 * not a screenshot. `hud.ts` strokes whatever comes back; `settings.ts` is
6 * where a style is validated before it ever reaches here.
7 *
8 * Colour is a name, never free text: a string that ends up in
9 * `ctx.strokeStyle` is an input like any other, so the only strings that can
10 * get there are the ones written down in this file.
11 */
12
13 /** The colours a crosshair can be, and the only strings that reach the canvas. */
14 export const CROSSHAIR_COLOURS = {
15 // The default is today's crosshair exactly, to the last hundredth of alpha.
16 green: "rgba(120, 255, 140, 0.9)",
17 white: "rgba(245, 247, 250, 0.9)",
18 cyan: "rgba(96, 226, 255, 0.9)",
19 yellow: "rgba(255, 220, 96, 0.9)",
20 magenta: "rgba(255, 110, 224, 0.9)",
21 red: "rgba(255, 82, 72, 0.9)",
22 } as const;
23
24 export type CrosshairColour = keyof typeof CROSSHAIR_COLOURS;
25
26 export const CROSSHAIR_COLOUR_NAMES = Object.keys(CROSSHAIR_COLOURS) as CrosshairColour[];
27
28 /**
29 * The three numbers, with the range each one is allowed and the value it
30 * falls back to. The page renders its `min`, `max` and `step` from here and
31 * `parseSettings` clamps to the same pair, so a field and the parser can
32 * never disagree about what is a legal crosshair.
33 */
34 export const CROSSHAIR_LIMITS = {
35 size: { min: 1, max: 20, fallback: 7 },
36 gap: { min: 0, max: 20, fallback: 4 },
37 thickness: { min: 1, max: 6, fallback: 2 },
38 } as const;
39
40 export type CrosshairStyle = {
41 colour: CrosshairColour;
42 /** How long each arm is, in pixels. */
43 size: number;
44 /** How far the arms start from the middle before any spread is added. */
45 gap: number;
46 /** The stroke width of the arms, and the diameter of the dot. */
47 thickness: number;
48 dot: boolean;
49 /** Does the gap open with the gun's inaccuracy, or is it the same always? */
50 dynamic: boolean;
51 };
52
53 export const DEFAULT_CROSSHAIR: CrosshairStyle = {
54 colour: "green",
55 size: CROSSHAIR_LIMITS.size.fallback,
56 gap: CROSSHAIR_LIMITS.gap.fallback,
57 thickness: CROSSHAIR_LIMITS.thickness.fallback,
58 dot: false,
59 dynamic: true,
60 };
61
62 /**
63 * How many pixels a unit of `inaccuracy()` pushes the arms out by. Today's
64 * law, kept: the gap was `4 + spread * 14`, and the 4 is now the setting.
65 */
66 export const SPREAD_GAP = 14;
67
68 export type Segment = { x1: number; y1: number; x2: number; y2: number };
69
70 export type CrosshairShape = {
71 /** The CSS colour, resolved from the name — what goes into the context. */
72 colour: string;
73 thickness: number;
74 /** The four arms, in right, left, down, up order. */
75 segments: Segment[];
76 dot: { x: number; y: number; radius: number } | null;
77 };
78
79 /** The four directions an arm goes, in the order they are drawn. */
80 const ARMS: readonly [number, number][] = [[1, 0], [-1, 0], [0, 1], [0, -1]];
81
82 /**
83 * The crosshair at `(cx, cy)` for a gun that is `spread` inaccurate. A
84 * dynamic crosshair adds the spread to its gap — which is how this game
85 * teaches you to stop before you shoot — and a static one ignores it
86 * entirely. A spread that is not a finite, positive number is no spread.
87 */
88 export function crosshairShape(
89 style: CrosshairStyle,
90 spread: number,
91 cx: number,
92 cy: number,
93 ): CrosshairShape {
94 const open = style.dynamic && Number.isFinite(spread) && spread > 0 ? spread * SPREAD_GAP : 0;
95 const gap = style.gap + open;
96 const segments = ARMS.map(([dx, dy]) => ({
97 x1: cx + dx * gap,
98 y1: cy + dy * gap,
99 x2: cx + dx * (gap + style.size),
100 y2: cy + dy * (gap + style.size),
101 }));
102 return {
103 colour: CROSSHAIR_COLOURS[style.colour],
104 thickness: style.thickness,
105 segments,
106 dot: style.dot ? { x: cx, y: cy, radius: style.thickness / 2 } : null,
107 };
108 }
src/client/hud.test.ts +111 −4
@@ -6,23 +6,33 @@
66 */
77
88 import { expect, test } from "bun:test";
9 import { DEFAULT_CROSSHAIR, type CrosshairStyle } from "./crosshair.ts";
910 import { drawHud } from "./hud.ts";
1011 import { SHORT } from "./match.ts";
1112 import type { Camera } from "./renderer.ts";
1213 import { createWorld, eyePos, type Player, type World } from "./world.ts";
1314
14 type Call = { name: string; args: number[]; text: string; alpha: number };
15 type Call = {
16 name: string; args: number[]; text: string; alpha: number;
17 stroke: string; fill: string; lineWidth: number;
18 };
1519
1620 function recorder(): { ctx: CanvasRenderingContext2D; calls: Call[] } {
1721 const calls: Call[] = [];
1822 // The alpha in force when the call was made, snapshotted: a fade is a
19 // property and not an argument, so it is the only way to see one.
23 // property and not an argument, so it is the only way to see one. The
24 // colours and the line width are read the same way and for the same
25 // reason — a crosshair's colour is a property of the context, not of the
26 // stroke that used it.
2027 const log = (name: string) => (...args: unknown[]): void => {
2128 calls.push({
2229 name,
2330 args: args.filter((a) => typeof a === "number") as number[],
2431 text: args.filter((a) => typeof a === "string").join(" "),
2532 alpha: ctx.globalAlpha,
33 stroke: typeof ctx.strokeStyle === "string" ? ctx.strokeStyle : "",
34 fill: typeof ctx.fillStyle === "string" ? ctx.fillStyle : "",
35 lineWidth: ctx.lineWidth,
2636 });
2737 };
2838 const ctx = {
@@ -34,7 +44,10 @@ function recorder(): { ctx: CanvasRenderingContext2D; calls: Call[] } {
3444 drawImage: log("drawImage"), closePath: log("closePath"),
3545 measureText: () => ({ width: 10 }),
3646 createRadialGradient: (...args: unknown[]) => {
37 calls.push({ name: "createRadialGradient", args: args as number[], text: "", alpha: 1 });
47 calls.push({
48 name: "createRadialGradient", args: args as number[], text: "", alpha: 1,
49 stroke: "", fill: "", lineWidth: 1,
50 });
3851 return { addColorStop: (): void => {} };
3952 },
4053 globalAlpha: 1, lineWidth: 1, fillStyle: "", strokeStyle: "",
@@ -51,7 +64,8 @@ const cameraFor = (view: Player): Camera =>
5164
5265 /** One frame of the HUD, drawing `view` — the person unless a spectator is watching. */
5366 const draw = (into: { ctx: CanvasRenderingContext2D }, world: World, view: Player = world.me,
54 scoreboard = false): void => drawHud(into.ctx, world, view, cameraFor(view), W, H, scoreboard);
67 scoreboard = false, crosshair?: CrosshairStyle): void =>
68 drawHud(into.ctx, world, view, cameraFor(view), W, H, scoreboard, crosshair);
5569
5670 /** Where the middle of a stroked wedge lands on the screen. */
5771 const wedgePoint = (call: Call): { x: number; y: number } => {
@@ -130,6 +144,99 @@ test("the hurt vignette follows health and its gradient is built once, not per f
130144 expect(again.calls.filter((c) => c.name === "createRadialGradient").length).toBe(0);
131145 });
132146
147 /**
148 * The crosshair's arms as the context was told to draw them: each `moveTo`
149 * paired with the `lineTo` that follows it, kept only when it starts at the
150 * middle of the screen. Nothing else in a quiet frame starts there — the
151 * radar's own lines are off in the corner and the hit markers need an effect.
152 */
153 function armsDrawn(calls: Call[]): { from: number[]; to: number[]; stroke: string; lineWidth: number }[] {
154 const arms: { from: number[]; to: number[]; stroke: string; lineWidth: number }[] = [];
155 for (let i = 0; i < calls.length - 1; i++) {
156 const move = calls[i], line = calls[i + 1];
157 if (move.name !== "moveTo" || line.name !== "lineTo") continue;
158 const along = (move.args[0] === W / 2) !== (move.args[1] === H / 2);
159 if (!along) continue;
160 arms.push({ from: move.args, to: line.args, stroke: move.stroke, lineWidth: move.lineWidth });
161 }
162 return arms;
163 }
164
165 /** A quiet frame: alive, still, and holding the knife, which has no spread. */
166 const quietWorld = (): World => {
167 const world = createWorld(SHORT, "me", "ct", 5, 67);
168 world.me.weapon = "knife";
169 world.me.vel = [0, 0, 0];
170 return world;
171 };
172
173 test("the default crosshair is the one this game has always drawn", () => {
174 const frame = recorder();
175 draw(frame, quietWorld());
176 // Four green arms, starting 4px out and running 7px, stroked 2px wide —
177 // right, left, down, up, exactly as the hard-coded loop drew them.
178 expect(armsDrawn(frame.calls).map((a) => [...a.from, ...a.to])).toEqual([
179 [W / 2 + 4, H / 2, W / 2 + 11, H / 2],
180 [W / 2 - 4, H / 2, W / 2 - 11, H / 2],
181 [W / 2, H / 2 + 4, W / 2, H / 2 + 11],
182 [W / 2, H / 2 - 4, W / 2, H / 2 - 11],
183 ]);
184 for (const arm of armsDrawn(frame.calls)) {
185 expect(arm.stroke).toBe("rgba(120, 255, 140, 0.9)");
186 expect(arm.lineWidth).toBe(2);
187 }
188 // No dot by default: nothing is filled in the middle of the screen.
189 expect(frame.calls.some((c) => c.name === "arc" && c.args[0] === W / 2 && c.args[1] === H / 2)).toBe(false);
190
191 // And the default is what a frame drawn with no style at all gets, so the
192 // HUD and the settings agree about what "today's crosshair" means.
193 const explicit = recorder();
194 draw(explicit, quietWorld(), undefined, false, DEFAULT_CROSSHAIR);
195 expect(armsDrawn(explicit.calls)).toEqual(armsDrawn(frame.calls));
196 });
197
198 test("the style is what gets drawn: colour, gap, size, thickness and the dot", () => {
199 const style: CrosshairStyle =
200 { colour: "cyan", size: 16, gap: 10, thickness: 4, dot: true, dynamic: false };
201 const frame = recorder();
202 draw(frame, quietWorld(), undefined, false, style);
203 const arms = armsDrawn(frame.calls);
204 expect(arms.map((a) => [...a.from, ...a.to])).toEqual([
205 [W / 2 + 10, H / 2, W / 2 + 26, H / 2],
206 [W / 2 - 10, H / 2, W / 2 - 26, H / 2],
207 [W / 2, H / 2 + 10, W / 2, H / 2 + 26],
208 [W / 2, H / 2 - 10, W / 2, H / 2 - 26],
209 ]);
210 expect(arms[0].stroke).toBe("rgba(96, 226, 255, 0.9)");
211 expect(arms[0].lineWidth).toBe(4);
212 // The dot: a filled circle in the middle, in the same colour as the arms.
213 const dot = frame.calls.find((c) => c.name === "arc" && c.args[0] === W / 2 && c.args[1] === H / 2);
214 expect(dot).toBeDefined();
215 expect((dot as Call).args[2]).toBe(2);
216 expect((dot as Call).fill).toBe("rgba(96, 226, 255, 0.9)");
217 });
218
219 test("a dynamic crosshair opens as the gun loses accuracy; a static one holds still", () => {
220 const running = (crosshair?: CrosshairStyle): number => {
221 const world = quietWorld();
222 world.me.weapon = "ak47";
223 world.me.vel = [250, 0, 0];
224 world.me.onGround = false; // in the air, where a rifle is at its worst
225 const frame = recorder();
226 draw(frame, world, undefined, false, crosshair);
227 return armsDrawn(frame.calls)[0].from[0] - W / 2;
228 };
229 const still = (): number => {
230 const frame = recorder();
231 draw(frame, quietWorld(), undefined, false);
232 return armsDrawn(frame.calls)[0].from[0] - W / 2;
233 };
234
235 expect(running()).toBeGreaterThan(still() + 10);
236 // The same jump with the same rifle, and the arms do not move at all.
237 expect(running({ ...DEFAULT_CROSSHAIR, dynamic: false })).toBe(still());
238 });
239
133240 /** A world where the person is dead and one named teammate is still up. */
134241 const spectatedWorld = (): World => {
135242 const world = createWorld(SHORT, "me", "ct", 5, 79);
src/client/hud.ts +18 −8
@@ -8,6 +8,7 @@
88 * it have to be that teammate's or the HUD belongs to a corpse.
99 */
1010
11 import { crosshairShape, DEFAULT_CROSSHAIR, type CrosshairStyle } from "./crosshair.ts";
1112 import { angleDelta, clamp, rad } from "./math.ts";
1213 import { walkable, type MapDef } from "./map.ts";
1314 import { hullHeight, MOVE } from "./physics.ts";
@@ -293,6 +294,7 @@ export function drawHud(
293294 width: number,
294295 height: number,
295296 showScoreboard: boolean,
297 crosshair: CrosshairStyle = DEFAULT_CROSSHAIR,
296298 ): void {
297299 ctx.clearRect(0, 0, width, height);
298300 ctx.textBaseline = "alphabetic";
@@ -304,7 +306,10 @@ export function drawHud(
304306 // --- being shot: where it came from, and how close to dead it left us
305307 drawDamage(ctx, world, view, width, height);
306308
307 // --- crosshair, opening up exactly as much as the gun is inaccurate
309 // --- crosshair, opening up exactly as much as the gun is inaccurate — as
310 // far as the player's own style lets it: what the arms look like is
311 // crosshair.ts's, and the only thing decided here is the spread they answer
312 // to. A colour is a name that module resolves, never a string from storage.
308313 if (view.alive && !spectating && !over) {
309314 const speed = Math.hypot(view.vel[0], view.vel[1]);
310315 const spread = inaccuracy(weapon, {
@@ -313,16 +318,21 @@ export function drawHud(
313318 ducking: view.duckAmount > 0.5,
314319 scoped: view.scoped,
315320 });
316 const gap = 4 + spread * 14;
317 const arm = 7;
318 ctx.strokeStyle = "rgba(120, 255, 140, 0.9)";
319 ctx.lineWidth = 2;
321 const shape = crosshairShape(crosshair, spread, width / 2, height / 2);
322 ctx.strokeStyle = shape.colour;
323 ctx.lineWidth = shape.thickness;
320324 ctx.beginPath();
321 for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
322 ctx.moveTo(width / 2 + dx * gap, height / 2 + dy * gap);
323 ctx.lineTo(width / 2 + dx * (gap + arm), height / 2 + dy * (gap + arm));
325 for (const segment of shape.segments) {
326 ctx.moveTo(segment.x1, segment.y1);
327 ctx.lineTo(segment.x2, segment.y2);
324328 }
325329 ctx.stroke();
330 if (shape.dot !== null) {
331 ctx.fillStyle = shape.colour;
332 ctx.beginPath();
333 ctx.arc(shape.dot.x, shape.dot.y, shape.dot.radius, 0, Math.PI * 2);
334 ctx.fill();
335 }
326336 }
327337 // The scope mask belongs to the camera, not to the crosshair: a spectator
328338 // watching a scoped teammate is looking down that scope's field of view.
src/client/main.ts +55 −2
@@ -19,7 +19,10 @@ import { clamp, dist } from "./math.ts";
1919 import { COMPETITIVE, SHORT, type Rules } from "./match.ts";
2020 import { MAX_SCALE, nextRenderScale } from "./quality.ts";
2121 import { createRenderer, type Camera } from "./renderer.ts";
22 import { DEFAULT_SETTINGS, loadSettings, saveSettings, SENSITIVITY_MAX, SENSITIVITY_MIN } from "./settings.ts";
22 import type { CrosshairStyle } from "./crosshair.ts";
23 import {
24 DEFAULT_SETTINGS, loadSettings, parseCrosshair, saveSettings, SENSITIVITY_MAX, SENSITIVITY_MIN,
25 } from "./settings.ts";
2326 import { CALL_LIFE, isCall, type Call } from "./plan.ts";
2427 import { nextWatched, watched } from "./spectate.ts";
2528 import { summarize, type MatchSummary } from "./summary.ts";
@@ -153,6 +156,56 @@ function boot(): void {
153156 for (const field of [pauseSensField, volumeField, muteButton, pauseDifficultyField, fullscreenPauseButton])
154157 field.addEventListener("keydown", (event) => event.stopPropagation());
155158
159 // --- the crosshair: the same six controls in the menu and in the pause
160 // overlay, kept in step the way sensitivity is. What a style does to the
161 // shape is crosshair.ts's, what a legal style is is settings.ts's — every
162 // change made here goes back through `parseCrosshair`, because a number
163 // field a player has typed into is as much an input as a stored blob is.
164 const crosshairPanels = (["menu", "pause"] as const).map((prefix) => ({
165 colour: $<HTMLSelectElement>(`${prefix}-xhair-colour`),
166 size: $<HTMLInputElement>(`${prefix}-xhair-size`),
167 gap: $<HTMLInputElement>(`${prefix}-xhair-gap`),
168 thickness: $<HTMLInputElement>(`${prefix}-xhair-thickness`),
169 dot: $<HTMLButtonElement>(`${prefix}-xhair-dot`),
170 dynamic: $<HTMLButtonElement>(`${prefix}-xhair-dynamic`),
171 }));
172
173 const paintCrosshair = (): void => {
174 const style = settings.crosshair;
175 for (const panel of crosshairPanels) {
176 panel.colour.value = style.colour;
177 panel.size.value = String(style.size);
178 panel.gap.value = String(style.gap);
179 panel.thickness.value = String(style.thickness);
180 for (const [button, on, label] of [[panel.dot, style.dot, "Dot"], [panel.dynamic, style.dynamic, "Dynamic"]] as const) {
181 button.textContent = `${label}: ${on ? "on" : "off"}`;
182 button.setAttribute("aria-pressed", String(on));
183 }
184 }
185 };
186 // Unknown in, parsed out: the value a control hands over is never trusted,
187 // so a hand-edited `min` on a number field buys nothing.
188 const syncCrosshair = (change: Partial<Record<keyof CrosshairStyle, unknown>>): void => {
189 settings = { ...settings, crosshair: parseCrosshair({ ...settings.crosshair, ...change }) };
190 paintCrosshair();
191 saveSettings(settings);
192 };
193 paintCrosshair();
194 for (const panel of crosshairPanels) {
195 panel.colour.addEventListener("change", () => syncCrosshair({ colour: panel.colour.value }));
196 panel.size.addEventListener("change", () => syncCrosshair({ size: Number(panel.size.value) }));
197 panel.gap.addEventListener("change", () => syncCrosshair({ gap: Number(panel.gap.value) }));
198 panel.thickness.addEventListener("change", () => syncCrosshair({ thickness: Number(panel.thickness.value) }));
199 panel.dot.addEventListener("click", () => syncCrosshair({ dot: !settings.crosshair.dot }));
200 panel.dynamic.addEventListener("click", () => syncCrosshair({ dynamic: !settings.crosshair.dynamic }));
201 // Same as the pause fields above, and for the same reason — plus the
202 // disclosure itself, whose Space must open it and not latch a jump.
203 for (const control of Object.values(panel))
204 control.addEventListener("keydown", (event) => event.stopPropagation());
205 panel.colour.closest("details")?.querySelector("summary")
206 ?.addEventListener("keydown", (event) => event.stopPropagation());
207 }
208
156209 // --- controls: a button per action, in the menu and in the pause overlay,
157210 // built once and kept in sync by rewriting each button's own text — the
158211 // fixed 16-action list never changes shape, only its keys do. What a key
@@ -748,7 +801,7 @@ function boot(): void {
748801 }
749802 // The same camera the scene was drawn with: the HUD's name plates have to
750803 // agree with the pixels the renderer just put on the screen.
751 drawHud(hudCtx, world, view, camera, w, h, controls.scoreboard);
804 drawHud(hudCtx, world, view, camera, w, h, controls.scoreboard, settings.crosshair);
752805 // The fps is the frame time and nothing else; the scale is an aside, shown
753806 // only when it is costing you pixels, so a slow machine says why.
754807 const note = renderScale < MAX_SCALE ? ` · ${Math.round(renderScale * 100)}% res` : "";
src/client/settings.test.ts +61 −4
@@ -5,8 +5,9 @@
55 */
66
77 import { expect, test } from "bun:test";
8 import { DEFAULT_CROSSHAIR } from "./crosshair.ts";
89 import { DEFAULT_BINDINGS } from "./input.ts";
9 import { DEFAULT_SETTINGS, parseSettings, type Settings } from "./settings.ts";
10 import { DEFAULT_SETTINGS, parseCrosshair, parseSettings, type Settings } from "./settings.ts";
1011
1112 test("nothing stored yet is the default", () => {
1213 expect(parseSettings(null)).toEqual(DEFAULT_SETTINGS);
@@ -25,10 +26,12 @@ test("a JSON value that isn't an object is the default", () => {
2526
2627 test("out-of-range numbers are clamped, not rejected", () => {
2728 expect(parseSettings('{"volume":5,"sensitivity":9999}')).toEqual({
28 muted: false, volume: 1, sensitivity: 12, difficulty: "normal", bindings: DEFAULT_BINDINGS,
29 muted: false, volume: 1, sensitivity: 12, difficulty: "normal",
30 crosshair: DEFAULT_CROSSHAIR, bindings: DEFAULT_BINDINGS,
2931 });
3032 expect(parseSettings('{"volume":-3,"sensitivity":-1}')).toEqual({
31 muted: false, volume: 0, sensitivity: 0.2, difficulty: "normal", bindings: DEFAULT_BINDINGS,
33 muted: false, volume: 0, sensitivity: 0.2, difficulty: "normal",
34 crosshair: DEFAULT_CROSSHAIR, bindings: DEFAULT_BINDINGS,
3235 });
3336 });
3437
@@ -45,10 +48,64 @@ test("muted is only ever true for exactly true", () => {
4548
4649 test("a whole, valid settings object round-trips", () => {
4750 const bindings = { ...DEFAULT_BINDINGS, forward: "KeyG" };
48 const stored: Settings = { muted: true, volume: 0.4, sensitivity: 3.5, difficulty: "hard", bindings };
51 const crosshair = { colour: "cyan", size: 12, gap: 2, thickness: 3, dot: true, dynamic: false } as const;
52 const stored: Settings = {
53 muted: true, volume: 0.4, sensitivity: 3.5, difficulty: "hard", crosshair, bindings,
54 };
4955 expect(parseSettings(JSON.stringify(stored))).toEqual(stored);
5056 });
5157
58 test("a settings blob written before the crosshair existed still loads, with today's crosshair", () => {
59 // Exactly what `saveSettings` wrote yesterday: no `crosshair` key at all.
60 const old = '{"muted":true,"volume":0.4,"sensitivity":3.5,"difficulty":"hard",' +
61 `"bindings":${JSON.stringify(DEFAULT_BINDINGS)}}`;
62 const parsed = parseSettings(old);
63 expect(parsed.crosshair).toEqual(DEFAULT_CROSSHAIR);
64 expect(parsed.sensitivity).toBe(3.5); // and nothing else is disturbed by the new group
65 expect(parsed.difficulty).toBe("hard");
66 });
67
68 test("a crosshair that is not an object at all is the default one", () => {
69 for (const raw of ['{"crosshair":null}', '{"crosshair":"green"}', '{"crosshair":7}', '{"crosshair":[1]}'])
70 expect(parseSettings(raw).crosshair).toEqual(DEFAULT_CROSSHAIR);
71 });
72
73 test("an unknown colour never reaches the canvas", () => {
74 for (const colour of ['"rgba(0,0,0,1)"', '"GREEN"', '"url(x)"', "3", "null", '"toString"'])
75 expect(parseCrosshair(JSON.parse(`{"colour":${colour}}`)).colour).toBe("green");
76 expect(parseCrosshair({ colour: "magenta" }).colour).toBe("magenta");
77 });
78
79 test("a size, gap or thickness that is not a number is that field's default", () => {
80 const bad = parseCrosshair({ size: "big", gap: null, thickness: NaN });
81 expect(bad).toEqual(DEFAULT_CROSSHAIR);
82 expect(parseCrosshair({ size: Infinity }).size).toBe(DEFAULT_CROSSHAIR.size);
83 });
84
85 test("a size, gap or thickness off the end of its range is clamped to it, and always whole", () => {
86 expect(parseCrosshair({ size: 900, gap: 900, thickness: 900 }))
87 .toEqual({ ...DEFAULT_CROSSHAIR, size: 20, gap: 20, thickness: 6 });
88 expect(parseCrosshair({ size: -4, gap: -4, thickness: -4 }))
89 .toEqual({ ...DEFAULT_CROSSHAIR, size: 1, gap: 0, thickness: 1 });
90 expect(parseCrosshair({ size: 6.6, gap: 3.2 })).toMatchObject({ size: 7, gap: 3 });
91 });
92
93 test("the dot and dynamic are booleans, and only exactly true or false moves them", () => {
94 expect(parseCrosshair({}).dot).toBe(false);
95 expect(parseCrosshair({}).dynamic).toBe(true);
96 expect(parseCrosshair({ dot: true }).dot).toBe(true);
97 expect(parseCrosshair({ dot: 1 }).dot).toBe(false);
98 expect(parseCrosshair({ dot: "true" }).dot).toBe(false);
99 expect(parseCrosshair({ dynamic: false }).dynamic).toBe(false);
100 expect(parseCrosshair({ dynamic: "yes" }).dynamic).toBe(false);
101 expect(parseCrosshair({ dynamic: 1 }).dynamic).toBe(false);
102 });
103
104 test("one bad crosshair field does not take the good ones down with it", () => {
105 expect(parseCrosshair({ colour: "nope", size: 11, dot: true }))
106 .toEqual({ ...DEFAULT_CROSSHAIR, size: 11, dot: true });
107 });
108
52109 test("a missing difficulty is the default", () => {
53110 expect(parseSettings('{"muted":true}').difficulty).toBe("normal");
54111 });
src/client/settings.ts +40 −2
@@ -1,6 +1,7 @@
11 /**
22 * Settings a player can reach mid-match: mute, volume, look sensitivity, bot
3 * difficulty and key bindings. Stored in localStorage beside `cs.name`.
3 * difficulty, the crosshair and key bindings. Stored in localStorage beside
4 * `cs.name`.
45 * `parseSettings` is the boundary — a missing, malformed, out-of-range or
56 * unknown value falls back to the default and never puts NaN, an
67 * unrecognised string or an unbound action into the game. What a difficulty
@@ -9,6 +10,10 @@
910 */
1011
1112 import { DEFAULT_DIFFICULTY, DIFFICULTIES, type Difficulty } from "./bots.ts";
13 import {
14 CROSSHAIR_COLOURS, CROSSHAIR_LIMITS, DEFAULT_CROSSHAIR,
15 type CrosshairColour, type CrosshairStyle,
16 } from "./crosshair.ts";
1217 import { ACTIONS, DEFAULT_BINDINGS, type Action } from "./input.ts";
1318
1419 export type Settings = {
@@ -16,11 +21,13 @@ export type Settings = {
1621 volume: number;
1722 sensitivity: number;
1823 difficulty: Difficulty;
24 crosshair: CrosshairStyle;
1925 bindings: Record<Action, string>;
2026 };
2127
2228 export const DEFAULT_SETTINGS: Settings = {
2329 muted: false, volume: 1, sensitivity: 2.2, difficulty: DEFAULT_DIFFICULTY,
30 crosshair: DEFAULT_CROSSHAIR,
2431 bindings: DEFAULT_BINDINGS,
2532 };
2633 export const SENSITIVITY_MIN = 0.2;
@@ -67,6 +74,35 @@ const bounded = (value: unknown, lo: number, hi: number, fallback: number): numb
6774 return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : fallback;
6875 };
6976
77 /** A whole number inside its limits, or that limit's own fallback. */
78 const whole = (value: unknown, limit: { min: number; max: number; fallback: number }): number =>
79 Math.round(bounded(value, limit.min, limit.max, limit.fallback));
80
81 const isColour = (value: unknown): value is CrosshairColour =>
82 typeof value === "string" && Object.hasOwn(CROSSHAIR_COLOURS, value);
83
84 /**
85 * The crosshair group, guarded field by field the way `difficulty` is: a
86 * missing object, an unknown colour name, a NaN size or a gap off the end of
87 * its range is that field's default and nothing else. Nothing here trusts
88 * anything — `parseSettings` calls it with whatever was in storage, and
89 * `main.ts` calls it with whatever a number field currently says, which is
90 * as much an input as the stored blob is.
91 */
92 export function parseCrosshair(raw: unknown): CrosshairStyle {
93 const obj = typeof raw === "object" && raw !== null ? (raw as Record<string, unknown>) : {};
94 return {
95 colour: isColour(obj.colour) ? obj.colour : DEFAULT_CROSSHAIR.colour,
96 size: whole(obj.size, CROSSHAIR_LIMITS.size),
97 gap: whole(obj.gap, CROSSHAIR_LIMITS.gap),
98 thickness: whole(obj.thickness, CROSSHAIR_LIMITS.thickness),
99 // Booleans the way `muted` is: exactly true is true, and a missing one is
100 // the default, which for `dynamic` is on.
101 dot: obj.dot === undefined ? DEFAULT_CROSSHAIR.dot : obj.dot === true,
102 dynamic: obj.dynamic === undefined ? DEFAULT_CROSSHAIR.dynamic : obj.dynamic === true,
103 };
104 }
105
70106 /** Pure: whatever was in storage, in or out of shape, becomes safe settings. */
71107 export function parseSettings(raw: string | null): Settings {
72108 if (raw === null) return defaultSettings();
@@ -83,11 +119,13 @@ export function parseSettings(raw: string | null): Settings {
83119 volume: bounded(obj.volume, 0, 1, DEFAULT_SETTINGS.volume),
84120 sensitivity: bounded(obj.sensitivity, SENSITIVITY_MIN, SENSITIVITY_MAX, DEFAULT_SETTINGS.sensitivity),
85121 difficulty: isDifficulty(obj.difficulty) ? obj.difficulty : DEFAULT_SETTINGS.difficulty,
122 crosshair: parseCrosshair(obj.crosshair),
86123 bindings: parseBindings(obj.bindings),
87124 };
88125 }
89126
90 const defaultSettings = (): Settings => ({ ...DEFAULT_SETTINGS, bindings: { ...DEFAULT_BINDINGS } });
127 const defaultSettings = (): Settings =>
128 ({ ...DEFAULT_SETTINGS, crosshair: { ...DEFAULT_CROSSHAIR }, bindings: { ...DEFAULT_BINDINGS } });
91129
92130 export function loadSettings(): Settings {
93131 try {
src/pages/game.test.ts +30
@@ -5,6 +5,7 @@ import { join } from "node:path";
55 import { openDatabase, saveMatch, standings } from "../db.ts";
66 import { credit } from "../player.ts";
77 import type { Result } from "../result.ts";
8 import { CROSSHAIR_COLOUR_NAMES, CROSSHAIR_LIMITS } from "../client/crosshair.ts";
89 import { gamePage, statsHtml } from "./game.ts";
910
1011 const db = openDatabase(mkdtempSync(join(tmpdir(), "game-page-")));
@@ -99,3 +100,32 @@ test("the radio has an overlay of its own and a button a thumb can reach", () =>
99100 // And the keyboard is told which key it is before a match starts.
100101 expect(element(html, "menu")).toContain("<kbd>Z</kbd> opens the radio");
101102 });
103
104 test("the crosshair controls are in the menu and in the pause overlay, one set each", () => {
105 const html = gamePage(db, options);
106 for (const [overlay, prefix] of [["menu", "menu"], ["pause", "pause"]] as const) {
107 const panel = element(html, overlay);
108 expect(panel).toContain(`<summary>Crosshair</summary>`);
109 for (const field of ["colour", "size", "gap", "thickness", "dot", "dynamic"])
110 expect(panel).toContain(`id="${prefix}-xhair-${field}"`);
111 // The two toggles say their state in their text as well as to a reader,
112 // so neither one has to change width to show it.
113 expect(panel).toContain(`id="${prefix}-xhair-dot" aria-pressed="false">Dot: off`);
114 expect(panel).toContain(`id="${prefix}-xhair-dynamic" aria-pressed="true">Dynamic: on`);
115 }
116 // Both copies exist, and no id is on the page twice.
117 const ids = [...html.matchAll(/id="([^"]+)"/g)].map((m) => m[1]);
118 expect(new Set(ids).size).toBe(ids.length);
119 });
120
121 test("a crosshair field can only offer the numbers the parser would keep", () => {
122 const panel = element(gamePage(db, options), "menu");
123 for (const [field, limit] of Object.entries(CROSSHAIR_LIMITS)) {
124 expect(panel).toContain(
125 `id="menu-xhair-${field}" type="number" min="${limit.min}" max="${limit.max}" step="1" value="${limit.fallback}"`,
126 );
127 }
128 // Colour is a name from the list, never a box to type a colour into.
129 expect(panel).not.toContain(`id="menu-xhair-colour" type="text"`);
130 for (const name of CROSSHAIR_COLOUR_NAMES) expect(panel).toContain(`<option value="${name}">`);
131 });
src/pages/game.ts +41 −1
@@ -5,6 +5,7 @@
55 */
66
77 import type { Database } from "bun:sqlite";
8 import { CROSSHAIR_COLOUR_NAMES, CROSSHAIR_LIMITS } from "../client/crosshair.ts";
89 import { headshotShare, ratio, recentMatches, standings, type MatchRow, type Standing } from "../db.ts";
910 import { isGuest, type Player } from "../player.ts";
1011 import { FORGE_LINK_ATTRS, signInHref } from "../who.ts";
@@ -73,6 +74,39 @@ export function leaderboardJson(db: Database): LeaderboardJson {
7374 };
7475 }
7576
77 /**
78 * The crosshair panel, rendered once into the menu and once into the pause
79 * overlay. Both copies are on the page at the same time, so their ids are
80 * prefixed the way `sens` and `pause-sens` already are, and `main.ts` keeps
81 * the two in step. Every field's range is read out of `CROSSHAIR_LIMITS`, the
82 * same table `parseSettings` clamps to: a control can never offer a number
83 * the parser would throw away. Collapsed, like Controls next to it, so it
84 * never pushes Play or Resume out of view.
85 */
86 export function crosshairControls(prefix: "menu" | "pause"): string {
87 const number = (field: "size" | "gap" | "thickness", label: string): string => {
88 const limit = CROSSHAIR_LIMITS[field];
89 return `<label>${label}<input id="${prefix}-xhair-${field}" type="number" ` +
90 `min="${limit.min}" max="${limit.max}" step="1" value="${limit.fallback}"></label>`;
91 };
92 const options = CROSSHAIR_COLOUR_NAMES
93 .map((name) => `<option value="${name}">${name[0].toUpperCase()}${name.slice(1)}</option>`)
94 .join("");
95 return `<details class="controls"><summary>Crosshair</summary>
96 <div class="grid">
97 <label>Colour<select id="${prefix}-xhair-colour">${options}</select></label>
98 ${number("size", "Size")}
99 ${number("gap", "Gap")}
100 ${number("thickness", "Thickness")}
101 <button type="button" id="${prefix}-xhair-dot" aria-pressed="false">Dot: off</button>
102 <button type="button" id="${prefix}-xhair-dynamic" aria-pressed="true">Dynamic: on</button>
103 </div>
104 <p class="hint">Dynamic is the default: the arms open with your spread, so a crosshair
105 that has settled is a shot that will land. Turn it off for a crosshair that never
106 moves. Changes take hold at once and are remembered for next time.</p>
107 </details>`;
108 }
109
76110 const STYLE = `
77111 :root { color-scheme: dark; --bg:#0b0d11; --panel:#141821; --line:#232a36; --text:#e7eaf0; --dim:#9aa4b4; --t:#e2b04a; --ct:#6fa8e8; }
78112 * { box-sizing: border-box; }
@@ -136,6 +170,10 @@ button.primary { background:#2563eb; border-color:#2563eb; font-weight:600; }
136170 .controls .grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(7.5rem,1fr)); gap:.5rem; width:100%; margin-top:.5rem; }
137171 .controls .grid label { gap:.3rem; }
138172 .controls .grid button { width:100%; }
173 /* A toggle that is its own grid item — the crosshair's dot and dynamic — has
174 no caption above it, so it lines up with the bottom of the fields beside it
175 instead of stretching over their labels. */
176 .controls .grid > button { align-self:end; }
139177 .controls .bind-status { min-height:1.1em; color:#e2b04a; }
140178 #buy .buy-item { display:flex; flex-direction:column; align-items:flex-start; gap:.1rem; text-align:left; white-space:normal; }
141179 #buy .buy-item .buy-index { font-size:.7rem; color:var(--dim); }
@@ -236,7 +274,7 @@ export function gamePage(db: Database, options: PageOptions): string {
236274 mouse to aim and fire · <kbd>R</kbd> reload · <kbd>E</kbd> plant, defuse or take a gun · <kbd>B</kbd> buy ·
237275 <kbd>Z</kbd> radio · right click or <kbd>Q</kbd> to scope · <kbd>1</kbd><kbd>2</kbd><kbd>3</kbd> guns ·
238276 <kbd>4</kbd> the HE grenade, thrown with fire · <kbd>Tab</kbd> scores ·
239 <kbd>Esc</kbd> pauses the match, where sound and sensitivity live too. Every key above is
277 <kbd>Esc</kbd> pauses the match, where sound, sensitivity and the crosshair live too. Every key above is
240278 the default — rebind any of them under <b>Controls</b> below.</p>
241279 <p class="hint"><kbd>Z</kbd> opens the radio: <b>go A</b>, <b>go B</b> or <b>hold</b>. Your four
242280 teammates hear it and turn round — a call stands for twenty seconds and then the side goes
@@ -247,6 +285,7 @@ export function gamePage(db: Database, options: PageOptions): string {
247285 <p class="hint">Paused means paused: the world stops while the overlay is up, and so does
248286 tabbing away — the match is waiting for you when you come back.</p>
249287 <details class="controls"><summary>Controls</summary><div id="controls-menu"></div></details>
288 ${crosshairControls("menu")}
250289 </div>
251290 <div class="overlay" id="pause" hidden>
252291 <h2>Paused</h2>
@@ -268,6 +307,7 @@ export function gamePage(db: Database, options: PageOptions): string {
268307 </div>
269308 <p class="hint">Difficulty takes effect from the next round.</p>
270309 <details class="controls"><summary>Controls</summary><div id="controls-pause"></div></details>
310 ${crosshairControls("pause")}
271311 <div class="row"><button type="button" class="primary" id="resume">Resume</button><button type="button" id="quit">Leave match</button></div>
272312 </div>
273313 <div class="overlay" id="summary" hidden>
src/readme.test.ts +13
@@ -75,3 +75,16 @@ test("the readme names the check and the build the same way the app does", () =>
7575 expect(local).toContain(`\n${app.test} `);
7676 expect(local).toContain("bun run scripts/build.ts");
7777 });
78
79 test("the readme says where the crosshair setting is, and that dynamic is the default", () => {
80 const playing = section("Playing");
81 expect(playing).toContain("**Crosshair** disclosure");
82 expect(playing).toContain("in the menu and again in the pause overlay");
83 expect(playing).toContain("**Dynamic is the default**");
84 // Every colour the code offers is named, and none the code does not.
85 const colours = /export const CROSSHAIR_COLOURS = \{([^}]+)\}/.exec(read("src/client/crosshair.ts"));
86 expect(colours).not.toBeNull();
87 const names = [...(colours as RegExpExecArray)[1].matchAll(/^\s{2}(\w+):/gm)].map((m) => m[1]);
88 expect(names.length).toBeGreaterThan(3);
89 for (const name of names) expect(playing).toContain(name);
90 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs