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

A click shorter than a frame still fires: latch input edges instead of sampling them #13

Merged opened this

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

Merged

vesper/cs:vesper/9-a-click-shorter-than-a-frame-still-fires → main 1 commit fork

  • Merged. vesper/9-a-click-shorter-than-a-frame-still-fires was merged into main as b0d7423.

Review

Sign in to review this change.
6 files changed +295 −55
README.md +2 −2
@@ -71,8 +71,8 @@ the rest.
7171 - `src/client/` — the game, in modules named for one thing each: `math`, `map`,
7272 `physics`, `weapons`, `combat`, `match` (the rules), `world` (the simulation),
7373 `bots`, `observe`, `action`, `policy`, `weights`, `models`, `textures`,
74 `renderer`, `hud`, `input`, `audio`, `main`. Everything except the last five is
75 headless and tested.
74 `press` (the input latch), `renderer`, `hud`, `input`, `audio`, `main`.
75 Everything except the last five is headless and tested.
7676 - `src/rl/` — training, which the game never imports: `arena` is the environment
7777 (a real duel on de_forge with the round and the economy taken out) and `ppo` is
7878 the algorithm, with its backward pass checked against finite differences.
src/client/input.ts +49 −38
@@ -2,16 +2,27 @@
22 * Input: keyboard and mouse under pointer lock, and a thumb stick and buttons
33 * on a touch screen. It collects intent into the same Input the simulation
44 * takes from a bot, and hands over accumulated mouse movement once a frame.
5 *
6 * Events are edges, and the loop only looks once a frame, so press.ts holds
7 * the edges in between: a tap that starts and ends between two frames still
8 * fires, exactly once.
59 */
610
711 import { clamp } from "./math.ts";
12 import { createPress, downAt, type Frame } from "./press.ts";
813 import { NO_INPUT, type Input } from "./world.ts";
914
15 /** The controls a press of counts even if the release beat the next frame. */
16 export const LATCHED = ["fire", "jump", "use", "reload"];
17
1018 export type Controls = {
11 input: Input;
1219 takeLook(): [number, number];
13 scoreboard: boolean;
14 slotWanted: 1 | 2 | 3 | null; // 1 primary, 2 pistol, 3 knife — main knows what they are
20 /** The frame's intent, taken once before the fixed steps it is about to run. */
21 take(steps: number): Frame;
22 /** The Input for one step of a taken frame. The object is reused. */
23 inputAt(frame: Frame, step: number): Input;
24 readonly scoreboard: boolean;
25 readonly slotWanted: 1 | 2 | 3 | null; // 1 primary, 2 pistol, 3 knife — main knows what they are
1526 sensitivity: number;
1627 locked: boolean;
1728 setAction(action: string, down: boolean): void;
@@ -29,25 +40,45 @@ const KEY_ACTIONS: Record<string, string> = {
2940 };
3041
3142 export function createControls(canvas: HTMLCanvasElement, sensitivity = 2.2): Controls {
32 const held = new Set<string>();
43 const press = createPress(LATCHED);
44 const input: Input = { ...NO_INPUT };
3345 let lookX = 0, lookY = 0;
3446 const controls: Controls = {
35 input: { ...NO_INPUT },
3647 takeLook() {
3748 const out: [number, number] = [lookX, lookY];
3849 lookX = 0;
3950 lookY = 0;
4051 return out;
4152 },
42 scoreboard: false,
43 slotWanted: null,
53 take: (steps) => press.take(steps),
54 inputAt(frame, step) {
55 const on = (action: string): boolean => downAt(frame, action, step);
56 input.forward = clamp(
57 (frame.held.has("forward") ? 1 : 0) - (frame.held.has("back") ? 1 : 0) + stick.y, -1, 1);
58 input.side = clamp(
59 (frame.held.has("right") ? 1 : 0) - (frame.held.has("left") ? 1 : 0) + stick.x, -1, 1);
60 input.duck = frame.held.has("duck");
61 input.walk = frame.held.has("walk");
62 input.scope = frame.held.has("scope");
63 input.jump = on("jump");
64 input.reload = on("reload");
65 input.use = on("use");
66 input.fire = on("fire");
67 input.switchTo = null;
68 return input;
69 },
70 get scoreboard(): boolean {
71 return press.isDown("scoreboard");
72 },
73 get slotWanted(): 1 | 2 | 3 | null {
74 return press.isDown("slot3") ? 3 : press.isDown("slot2") ? 2 : press.isDown("slot1") ? 1 : null;
75 },
4476 sensitivity,
4577 locked: false,
4678 setAction: (action, down) => {
47 if (down) held.add(action);
48 else held.delete(action);
79 if (down) press.down(action);
80 else press.up(action);
4981 if (down && action === "buy") controls.onBuy();
50 apply();
5182 },
5283 onBuy: () => {},
5384 onPause: () => {},
@@ -58,24 +89,6 @@ export function createControls(canvas: HTMLCanvasElement, sensitivity = 2.2): Co
5889 },
5990 };
6091
61 function apply(): void {
62 const i = controls.input;
63 i.forward = (held.has("forward") ? 1 : 0) - (held.has("back") ? 1 : 0) + stick.y;
64 i.side = (held.has("right") ? 1 : 0) - (held.has("left") ? 1 : 0) + stick.x;
65 i.forward = clamp(i.forward, -1, 1);
66 i.side = clamp(i.side, -1, 1);
67 i.jump = held.has("jump");
68 i.duck = held.has("duck");
69 i.walk = held.has("walk");
70 i.reload = held.has("reload");
71 i.use = held.has("use");
72 i.fire = held.has("fire");
73 i.scope = held.has("scope");
74 i.switchTo = null;
75 controls.slotWanted = held.has("slot3") ? 3 : held.has("slot2") ? 2 : held.has("slot1") ? 1 : null;
76 controls.scoreboard = held.has("scoreboard");
77 }
78
7992 const stick = { x: 0, y: 0 };
8093
8194 function onKeyDown(event: KeyboardEvent): void {
@@ -92,8 +105,7 @@ export function createControls(canvas: HTMLCanvasElement, sensitivity = 2.2): Co
92105 function onLockChange(): void {
93106 controls.locked = document.pointerLockElement === canvas;
94107 if (!controls.locked) {
95 held.clear();
96 apply();
108 press.clear();
97109 controls.onPause();
98110 }
99111 }
@@ -117,8 +129,7 @@ export function createControls(canvas: HTMLCanvasElement, sensitivity = 2.2): Co
117129 lookY += event.movementY * controls.sensitivity * 0.022;
118130 });
119131 window.addEventListener("blur", () => {
120 held.clear();
121 apply();
132 press.clear();
122133 });
123134
124135 // --- touch: the left third is a stick, the rest of the canvas looks around
@@ -139,7 +150,6 @@ export function createControls(canvas: HTMLCanvasElement, sensitivity = 2.2): Co
139150 if (state.stick) {
140151 stick.x = clamp((touch.clientX - state.startX) / 60, -1, 1);
141152 stick.y = clamp((state.startY - touch.clientY) / 60, -1, 1);
142 apply();
143153 } else {
144154 lookX += (touch.clientX - state.x) * controls.sensitivity * 0.06;
145155 lookY += (touch.clientY - state.y) * controls.sensitivity * 0.06;
@@ -155,7 +165,6 @@ export function createControls(canvas: HTMLCanvasElement, sensitivity = 2.2): Co
155165 if (state?.stick === true) {
156166 stick.x = 0;
157167 stick.y = 0;
158 apply();
159168 }
160169 touches.delete(touch.identifier);
161170 }
@@ -166,19 +175,21 @@ export function createControls(canvas: HTMLCanvasElement, sensitivity = 2.2): Co
166175 return controls;
167176 }
168177
169 /** The buttons a touch screen needs, wired to the same actions as the keys. */
178 /**
179 * The buttons a touch screen needs, wired to the same actions as the keys. A
180 * thumb is quicker than a frame, so the press goes down on pointerdown and up
181 * on pointerup and the latch sees to it that a step counts it.
182 */
170183 export function attachButtons(root: ParentNode, controls: Controls): void {
171184 for (const element of Array.from(root.querySelectorAll<HTMLElement>("[data-action]"))) {
172185 const action = element.dataset.action as string;
173186 const down = (event: Event): void => {
174187 event.preventDefault();
175188 controls.setAction(action, true);
176 if (action === "jump" || action === "reload" || action === "buy")
177 setTimeout(() => controls.setAction(action, false), 120);
178189 };
179190 const up = (event: Event): void => {
180191 event.preventDefault();
181 if (action !== "jump" && action !== "reload" && action !== "buy") controls.setAction(action, false);
192 controls.setAction(action, false);
182193 };
183194 element.addEventListener("pointerdown", down);
184195 element.addEventListener("pointerup", up);
src/client/main.ts +15 −10
@@ -1,8 +1,9 @@
11 /**
2 * The loop. Input is read once a frame, the world is stepped at a fixed 64 Hz
3 * however long the frame took, and then the scene and the HUD are drawn. The
4 * page's overlays — menu, buy, pause — are plain DOM, so they are reachable
5 * with a keyboard and big enough for a thumb.
2 * The loop. Input is latched as it arrives and taken once a frame — a press
3 * shorter than a frame still counts, on one step and one only — the world is
4 * stepped at a fixed 64 Hz however long the frame took, and then the scene and
5 * the HUD are drawn. The page's overlays — menu, buy, pause — are plain DOM,
6 * so they are reachable with a keyboard and big enough for a thumb.
67 */
78
89 import { createAudio } from "./audio.ts";
@@ -200,18 +201,22 @@ function boot(): void {
200201 me.yaw -= dx;
201202 me.pitch = clamp(me.pitch + dy, -89, 89);
202203 }
203 const input = controls.input;
204 input.switchTo =
204 const switchTo =
205205 controls.slotWanted === 3 ? "knife" :
206206 controls.slotWanted === 2 ? me.secondary :
207207 controls.slotWanted === 1 ? me.primary : null;
208208
209 // The latch is consumed once, before the steps: a press that arrived and
210 // left between two frames counts on the first of them and on no other.
209211 accumulator += elapsed;
210 let steps = 0;
211 while (accumulator >= TICK && steps < 8) {
212 update(world, TICK, buyPanel.hidden ? input : { ...input, fire: false });
212 const steps = Math.min(8, Math.floor(accumulator / TICK));
213 const pressed = controls.take(steps);
214 for (let step = 0; step < steps; step += 1) {
215 const input = controls.inputAt(pressed, step);
216 input.switchTo = switchTo;
217 if (!buyPanel.hidden) input.fire = false;
218 update(world, TICK, input);
213219 accumulator -= TICK;
214 steps += 1;
215220 }
216221 playSounds(world);
217222
src/client/press.test.ts added +145
@@ -0,0 +1,145 @@
1 import { expect, test } from "bun:test";
2 import { createPress, downAt, NO_FRAME, type Press } from "./press.ts";
3 import { SHORT } from "./match.ts";
4 import { WEAPONS } from "./weapons.ts";
5 import { buy, createWorld, NO_INPUT, update, type World } from "./world.ts";
6
7 const TICK = 1 / 64;
8
9 /** One frame of the loop: take the latch, then ask each step about `control`. */
10 const frame = (press: Press, steps: number, control = "fire"): boolean[] => {
11 const taken = press.take(steps);
12 const out: boolean[] = [];
13 for (let step = 0; step < steps; step += 1) out.push(downAt(taken, control, step));
14 return out;
15 };
16
17 test("a press that ended before the frame did is still down for a step", () => {
18 const press = createPress(["fire"]);
19 press.down("fire");
20 press.up("fire");
21 expect(press.isDown("fire")).toBe(false);
22 expect(frame(press, 1)).toEqual([true]);
23 });
24
25 test("a press counts on one step of a frame, never on all of them", () => {
26 const press = createPress(["fire"]);
27 press.down("fire");
28 press.up("fire");
29 expect(frame(press, 4)).toEqual([true, false, false, false]);
30 expect(frame(press, 4)).toEqual([false, false, false, false]);
31 });
32
33 test("a frame that runs no steps keeps the press for the frame that can spend it", () => {
34 const press = createPress(["fire"]);
35 press.down("fire");
36 press.up("fire");
37 expect(frame(press, 0)).toEqual([]);
38 expect(frame(press, 2)).toEqual([true, false]);
39 expect(frame(press, 2)).toEqual([false, false]);
40 });
41
42 test("a held control is down on every step, frame after frame, until it is released", () => {
43 const press = createPress(["fire"]);
44 press.down("fire");
45 expect(frame(press, 3)).toEqual([true, true, true]);
46 expect(frame(press, 2)).toEqual([true, true]);
47 press.up("fire");
48 expect(frame(press, 2)).toEqual([false, false]);
49 });
50
51 test("a control that is not latched is level-triggered", () => {
52 const press = createPress(["fire"]);
53 press.down("walk");
54 expect(frame(press, 2, "walk")).toEqual([true, true]);
55 press.up("walk");
56 expect(frame(press, 2, "walk")).toEqual([false, false]);
57 press.down("walk");
58 press.up("walk"); // a tap between two frames leaves nothing behind
59 expect(frame(press, 2, "walk")).toEqual([false, false]);
60 });
61
62 test("jump, use and reload latch too, each on its own", () => {
63 const press = createPress(["fire", "jump", "use", "reload"]);
64 for (const control of ["jump", "use", "reload"]) {
65 press.down(control);
66 press.up(control);
67 }
68 const taken = press.take(2);
69 for (const control of ["jump", "use", "reload"]) {
70 expect(downAt(taken, control, 0)).toBe(true);
71 expect(downAt(taken, control, 1)).toBe(false);
72 }
73 expect(downAt(taken, "fire", 0)).toBe(false);
74 });
75
76 test("clear forgets what is held and what is pending", () => {
77 const press = createPress(["fire"]);
78 press.down("fire");
79 press.down("walk");
80 press.up("fire");
81 press.clear();
82 expect(press.isDown("walk")).toBe(false);
83 expect(frame(press, 2)).toEqual([false, false]);
84 });
85
86 test("an empty frame is down for nothing", () => {
87 expect(downAt(NO_FRAME, "fire", 0)).toBe(false);
88 });
89
90 // --- the same latch against the real simulation
91
92 const live = (seed: number, weapon: "m4a4" | "usp"): World => {
93 const world = createWorld(SHORT, "me", "ct", 5, seed);
94 world.me.money = 5000;
95 if (weapon === "m4a4") buy(world, world.me, "m4a4");
96 for (let t = 0; t < SHORT.freezeTime + 0.5; t += TICK) update(world, TICK, NO_INPUT);
97 return world;
98 };
99
100 /** The loop's inner steps, driven by the latch. */
101 const step = (world: World, press: Press, steps: number): void => {
102 const taken = press.take(steps);
103 for (let i = 0; i < steps; i += 1)
104 update(world, TICK, { ...NO_INPUT, fire: downAt(taken, "fire", i) });
105 };
106
107 test("a tap shorter than a frame fires exactly one bullet", () => {
108 for (const weapon of ["m4a4", "usp"] as const) {
109 const world = live(7, weapon);
110 const ammo = world.me.ammo[weapon] as { mag: number };
111 const before = ammo.mag;
112 const press = createPress(["fire"]);
113 press.down("fire");
114 press.up("fire"); // down and up between two frames
115 for (let f = 0; f < 20; f += 1) step(world, press, 1);
116 expect(before - ammo.mag).toBe(1);
117 }
118 });
119
120 test("a tap on a frame that runs eight steps is still one bullet", () => {
121 const world = live(8, "m4a4");
122 const ammo = world.me.ammo.m4a4 as { mag: number };
123 const before = ammo.mag;
124 const press = createPress(["fire"]);
125 press.down("fire");
126 press.up("fire");
127 step(world, press, 8);
128 expect(before - ammo.mag).toBe(1);
129 });
130
131 test("holding fire keeps an automatic weapon firing", () => {
132 const world = live(9, "m4a4");
133 const ammo = world.me.ammo.m4a4 as { mag: number };
134 const before = ammo.mag;
135 const press = createPress(["fire"]);
136 press.down("fire");
137 for (let f = 0; f < 32; f += 1) step(world, press, 2); // one second of held fire
138 const fired = before - ammo.mag;
139 expect(fired).toBeGreaterThan(5);
140 expect(fired).toBeLessThanOrEqual(Math.ceil(WEAPONS.m4a4.rpm / 60) + 1);
141 press.up("fire");
142 const held = ammo.mag;
143 for (let f = 0; f < 32; f += 1) step(world, press, 2);
144 expect(ammo.mag).toBe(held); // released means released
145 });
src/client/press.ts added +79
@@ -0,0 +1,79 @@
1 /**
2 * Press: what the loop should treat as down, one frame at a time.
3 *
4 * Key and pointer events arrive whenever the browser has them; the loop looks
5 * once a frame. A control that goes down and up between two frames would be
6 * invisible to a loop that only reads what is held right now — a lost shot on
7 * a fast tap, and on a touch screen the common case. So a down edge on a
8 * latched control is remembered until a simulation step has actually seen it,
9 * and no longer than that: the press counts on the first step of the frame
10 * that consumes it, never on all eight steps of a slow one, so one tap stays
11 * one bullet even with an automatic weapon.
12 *
13 * Everything else is level-triggered — down while it is held, nothing more.
14 * This module knows nothing about keys, pointers or the game: controls are
15 * names, edges go in, a frame's worth of intent comes out.
16 */
17
18 /** What the steps of one frame should see. */
19 export type Frame = {
20 /** How many simulation steps this frame runs. */
21 steps: number;
22 /** Controls held down when the frame was taken: down for every step. */
23 held: ReadonlySet<string>;
24 /** Latched presses this frame consumed: down for the first step only. */
25 pressed: ReadonlySet<string>;
26 };
27
28 export type Press = {
29 /** A control went down. Latched controls remember the edge. */
30 down(control: string): void;
31 /** A control came up. A latched edge it has not paid out yet survives. */
32 up(control: string): void;
33 /** Forget everything: focus lost, pointer unlocked. */
34 clear(): void;
35 /** Is the control held right now? */
36 isDown(control: string): boolean;
37 /**
38 * The frame's intent. Called once a frame, before the fixed steps, with the
39 * number of steps about to run: with none, the pending edges wait for a
40 * frame that can spend them.
41 */
42 take(steps: number): Frame;
43 };
44
45 export const NO_FRAME: Frame = { steps: 0, held: new Set(), pressed: new Set() };
46
47 /** Is `control` down on step `step` of `frame`? */
48 export function downAt(frame: Frame, control: string, step: number): boolean {
49 if (frame.held.has(control)) return true;
50 return step === 0 && frame.pressed.has(control);
51 }
52
53 /** `latched` names the controls whose presses survive a frame boundary. */
54 export function createPress(latched: Iterable<string>): Press {
55 const edges = new Set(latched);
56 const held = new Set<string>();
57 const pending = new Set<string>();
58
59 return {
60 down(control) {
61 held.add(control);
62 if (edges.has(control)) pending.add(control);
63 },
64 up(control) {
65 held.delete(control);
66 },
67 clear() {
68 held.clear();
69 pending.clear();
70 },
71 isDown: (control) => held.has(control),
72 take(steps) {
73 if (steps <= 0) return { steps: 0, held: new Set(held), pressed: new Set() };
74 const pressed = new Set(pending);
75 pending.clear();
76 return { steps, held: new Set(held), pressed };
77 },
78 };
79 }
static/app.e8ca965610.js → static/app.baf3356f9f.js renamed +5 −5

Diff not shown — 130,876 bytes of diff (limit 100,000). +5 −5

View file

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs