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

The gun says what it is doing: a muzzle flash, a reload you can see, and a raise when you switch #106

Merged opened this

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

Merged

vesper/cs:vesper/70-the-gun-says-what-it-is-doing-a-muzzle-f → main 1 commit fork

  • Merged. vesper/70-the-gun-says-what-it-is-doing-a-muzzle-f was merged into main as 3d1e771.

Review

Sign in to review this change.
5 files changed +377 −18
README.md +13 −1
@@ -67,7 +67,19 @@ wants one, but the running server never reads it.
6767 it, and they keep buying guns. Hit feedback runs both ways: a hit marker and a beep when you hit
6868 someone, and when you are hit a view punch away from the shot, a wedge around
6969 the crosshair pointing at whoever fired, a vignette that reddens as your health
70 falls and a pain sound. Every world sound is panned around the listener's
70 falls and a pain sound. The gun says what it is doing, too. Every shot lights
71 a **muzzle flash** — a star of additive light at the end of the barrel, sized
72 by the weapon and gone in three frames — on the gun in your hands and on
73 every other gun on the map, so a firefight across the site reads as people
74 firing rather than as lines appearing in the air; a knife and a grenade have
75 no muzzle and flash for nobody. A **reload** is something the hands do: the
76 gun drops out of the way and comes back, driven by how far through the
77 weapon's own reload time you are, and it is level again exactly when the
78 magazine is full. A weapon you **switch to** is raised over a quarter of a
79 second. Both of those are animation and nothing else — the switch itself is
80 still instantaneous, as it always was, so a gun still on its way up fires the
81 moment the simulation says it may, and no bot, no `observe.ts` input and no
82 rule of the round can tell the difference. Every world sound is panned around the listener's
7183 view and fades with distance — a shot or a footstep to your left plays from
7284 the left channel, to your right the right — and a running player who is not
7385 walking, ducking or airborne leaves footsteps this way too, so someone
src/client/models.ts +39 −2
@@ -76,6 +76,15 @@ export function levelMesh(boxes: Box[]): Mesh {
7676 const cube = (b: Builder, cx: number, cy: number, cz: number, sx: number, sy: number, sz: number, layer: number): void =>
7777 addBox(b, [cx - sx / 2, cy - sy / 2, cz - sz / 2], [cx + sx / 2, cy + sy / 2, cz + sz / 2], layer, 64);
7878
79 /**
80 * The end of the gun in a player's hands, in the player mesh's own space: the
81 * point a muzzle flash belongs at when somebody else fires. It is derived from
82 * the gun cube below rather than written twice, so moving the gun moves the
83 * flash with it.
84 */
85 const HELD_GUN = { x: 14, y: -6, z: 46, long: 26 };
86 export const HELD_MUZZLE: Vec3 = [HELD_GUN.x + HELD_GUN.long / 2, HELD_GUN.y, HELD_GUN.z];
87
7988 /**
8089 * A player: legs, torso, arms, head, and the gun they are holding, built
8190 * standing at the origin facing +X so a yaw rotation is all a draw needs.
@@ -89,7 +98,7 @@ export function playerMesh(): Mesh {
8998 cube(b, 2, -14, 46, 9, 9, 22, KIT); // right arm
9099 cube(b, 6, 10, 46, 9, 9, 20, KIT); // left arm
91100 cube(b, 1, 0, 67, 13, 13, 13, SKIN); // head
92 cube(b, 14, -6, 46, 26, 5, 7, GEAR); // the gun in their hands
101 cube(b, HELD_GUN.x, HELD_GUN.y, HELD_GUN.z, HELD_GUN.long, 5, 7, GEAR); // the gun in their hands
93102 return finish(b);
94103 }
95104
@@ -129,6 +138,34 @@ export function grenadeMesh(): Mesh {
129138 return finish(b);
130139 }
131140
141 /** How long the barrel of a view model is, in view units. */
142 const barrelLength = (kind: string): number =>
143 kind === "sniper" ? 3.6 : kind === "rifle" ? 3.0 : kind === "smg" ? 2.2 : 1.5;
144
145 /** How big the flash off that barrel is, relative to a rifle's. */
146 const FLASH_SIZE: Record<string, number> = { pistol: 0.7, smg: 0.8, rifle: 1, sniper: 1.4 };
147
148 /**
149 * Where the flash comes out of a held weapon and how big it is: a point just
150 * past the end of the barrel in the view model's own space, and a multiplier
151 * each pass scales into its own units — the same number sizes the star in your
152 * hands and the one across the map.
153 *
154 * One frozen answer per kind, built here and not per call: a renderer asks
155 * this once per shooter per frame and a frame allocates nothing. A knife and a
156 * grenade have no muzzle, and neither does the bomb, so they answer `null` and
157 * nothing is drawn for them at all.
158 */
159 export type Muzzle = { at: Vec3; size: number };
160 const MUZZLES: Record<string, Muzzle> = Object.fromEntries(
161 Object.entries(FLASH_SIZE).map(([kind, size]) => [
162 kind,
163 Object.freeze({ at: [0.55, -0.62, -(barrelLength(kind) + 0.7)] as Vec3, size }),
164 ]),
165 );
166
167 export const muzzle = (kind: string): Muzzle | null => MUZZLES[kind] ?? null;
168
132169 /**
133170 * A first-person weapon, in view space: X right, Y up, Z back, so the barrel
134171 * runs down -Z and the model needs no rotation at all.
@@ -148,7 +185,7 @@ export function viewModelMesh(kind: string): Mesh {
148185 cube(b, 0.7, -0.95, -0.5, 0.2, 0.34, 0.7, GRIP);
149186 return finish(b);
150187 }
151 const long = kind === "sniper" ? 3.6 : kind === "rifle" ? 3.0 : kind === "smg" ? 2.2 : 1.5;
188 const long = barrelLength(kind);
152189 cube(b, 0.55, -0.62, -long / 2 - 0.6, 0.16, 0.2, long, GUN); // barrel
153190 cube(b, 0.55, -0.78, -0.55, 0.3, 0.44, 1.5, GUN); // receiver
154191 cube(b, 0.55, -1.18, -0.35, 0.22, 0.5, 0.4, GRIP); // grip
src/client/renderer.test.ts +147 −4
@@ -14,9 +14,10 @@ import { expect, test } from "bun:test";
1414 import { addBody } from "./bodies.ts";
1515 import { advance, TICK, waiting } from "./loop.ts";
1616 import { SHORT } from "./match.ts";
17 import { levelMesh } from "./models.ts";
18 import { createRenderer, type Camera, type Renderer, type RendererHooks } from "./renderer.ts";
19 import { createWorld, type Player, type World } from "./world.ts";
17 import { HELD_MUZZLE, levelMesh, viewModelMesh } from "./models.ts";
18 import { createRenderer, LINE_CAPACITY, type Camera, type Renderer, type RendererHooks } from "./renderer.ts";
19 import type { WeaponId } from "./weapons.ts";
20 import { createWorld, eyePos, type Effect, type Player, type World } from "./world.ts";
2021
2122 type Call = { name: string; args: unknown[] };
2223
@@ -45,7 +46,8 @@ function recorder(): {
4546 createBuffer: handle("buffer"), bindBuffer: log("bindBuffer"),
4647 bufferData: log("bufferData"), bufferSubData: log("bufferSubData"),
4748 enableVertexAttribArray: log("enableVertexAttribArray"), vertexAttribPointer: log("vertexAttribPointer"),
48 enable: log("enable"), cullFace: log("cullFace"), clearColor: log("clearColor"),
49 enable: log("enable"), disable: log("disable"), blendFunc: log("blendFunc"),
50 cullFace: log("cullFace"), clearColor: log("clearColor"),
4951 viewport: log("viewport"), clear: log("clear"), useProgram: log("useProgram"),
5052 activeTexture: log("activeTexture"), uniform1i: log("uniform1i"),
5153 uniformMatrix4fv: log("uniformMatrix4fv"), uniform3fv: log("uniform3fv"), uniform3f: log("uniform3f"),
@@ -154,6 +156,147 @@ test("a grenade in the air is one more draw, off a mesh uploaded before the fram
154156 expect(frame(canvas, calls, world, world.me).length).toBe(empty);
155157 });
156158
159 // --- what the gun says it is doing
160
161 /** The model matrix the view model was drawn with, or null if it was not drawn. */
162 function heldPlace(calls: Call[], kind: string): Float32Array | null {
163 const count = viewModelMesh(kind).index.length;
164 const at = calls.findIndex((c) => c.name === "drawElements" && c.args[1] === count);
165 if (at < 0) return null;
166 for (let i = at; i >= 0; i -= 1) {
167 const call = calls[i] as Call;
168 if (call.name === "uniformMatrix4fv") return call.args[2] as Float32Array;
169 }
170 return null;
171 }
172
173 /** Every run of lines drawn this frame: tracers, sparks and flashes alike. */
174 const lineRuns = (calls: Call[]): { first: number; count: number }[] =>
175 calls.filter((c) => c.name === "drawArrays")
176 .map((c) => ({ first: c.args[1] as number, count: c.args[2] as number }));
177
178 const shotBy = (world: World, p: Player, weapon: WeaponId): Effect =>
179 ({ kind: "shot", at: world.time, pos: eyePos(p), weapon, mine: p === world.me, shooter: p.id });
180
181 test("a shot flashes at the end of the shooter's gun, and a knife flashes not at all", () => {
182 const { canvas, calls } = recorder();
183 const world = scene();
184 const shooter = world.players.find((p) => p !== world.me && p.alive) as Player;
185 shooter.yaw = 90;
186 const quiet = frame(canvas, calls, world, world.me).length;
187 expect(lineRuns(calls).length).toBe(0); // a still frame draws no line at all
188
189 world.effects.push(shotBy(world, shooter, "ak47"));
190 expect(frame(canvas, calls, world, world.me).length).toBe(quiet + 1);
191 const runs = lineRuns(calls);
192 expect(runs.length).toBe(1);
193 expect(runs[0]?.count).toBe(12); // six spokes, two vertices each
194
195 // Additive: a flash adds light to what is behind it, which is the one thing
196 // in this renderer that does.
197 expect(calls.filter((c) => c.name === "blendFunc").length).toBe(1);
198
199 // And its core is the muzzle of the gun in that player's hands — facing
200 // north, so the gun's own +X is the world's +Y — not the middle of their face.
201 const data = calls.find((c) => c.name === "bufferSubData")?.args[2] as Float32Array;
202 expect(data[0]).toBeCloseTo(shooter.pos[0] + HELD_MUZZLE[1] * -1, 3);
203 expect(data[1]).toBeCloseTo(shooter.pos[1] + HELD_MUZZLE[0], 3);
204 expect(data[2]).toBeCloseTo(shooter.pos[2] + HELD_MUZZLE[2], 3);
205
206 // A knife has no muzzle, so the same effect off a knife draws nothing.
207 world.effects.length = 0;
208 world.effects.push(shotBy(world, shooter, "knife"));
209 expect(frame(canvas, calls, world, world.me).length).toBe(quiet);
210 expect(lineRuns(calls).length).toBe(0);
211
212 // Nor does the flash outlive the shot: a sixteenth of a second later it is gone.
213 world.effects.length = 0;
214 world.effects.push({ ...shotBy(world, shooter, "ak47"), at: world.time - 0.2 });
215 expect(frame(canvas, calls, world, world.me).length).toBe(quiet);
216 });
217
218 test("the view model is not drawn while scoped, nor while watching a dead teammate", () => {
219 const { canvas, calls } = recorder();
220 const world = scene();
221 world.me.weapon = "awp";
222 frame(canvas, calls, world, world.me);
223 expect(heldPlace(calls, "sniper")).not.toBeNull();
224
225 world.me.scoped = true;
226 frame(canvas, calls, world, world.me);
227 expect(heldPlace(calls, "sniper")).toBeNull();
228
229 // Dead, with a shot of their own a frame old: no gun, and so no flash either.
230 world.me.scoped = false;
231 world.me.alive = false;
232 world.me.lastShotAt = world.time;
233 frame(canvas, calls, world, world.me);
234 expect(heldPlace(calls, "sniper")).toBeNull();
235 expect(lineRuns(calls).length).toBe(0);
236 });
237
238 test("a reload is something the hands do, and it is over when the reload is", () => {
239 const { canvas, calls } = recorder();
240 const world = scene();
241 world.me.weapon = "ak47";
242 frame(canvas, calls, world, world.me);
243 const idle = heldPlace(calls, "rifle") as Float32Array;
244
245 world.me.reloadUntil = world.time + 1.25; // halfway through the AK's 2.5 s
246 frame(canvas, calls, world, world.me);
247 const halfway = heldPlace(calls, "rifle") as Float32Array;
248 expect(halfway[13]).toBeLessThan((idle[13] as number) - 0.4); // dropped out of the way
249 expect(halfway[0]).not.toBeCloseTo(idle[0] as number, 3); // and rolled with it
250
251 // The last frame of the reload is the pose the first frame after it has:
252 // the animation cannot outlive the thing it is showing.
253 world.me.reloadUntil = world.time;
254 frame(canvas, calls, world, world.me);
255 expect(heldPlace(calls, "rifle")).toEqual(idle);
256 });
257
258 test("a switch raises the gun over a fixed time, and the simulation never hears about it", () => {
259 const { canvas, calls } = recorder();
260 const world = scene();
261 world.me.weapon = "ak47";
262 frame(canvas, calls, world, world.me);
263 const raising = heldPlace(calls, "rifle") as Float32Array;
264
265 world.time += 1; // long past the raise
266 const before = structuredClone(world.me);
267 frame(canvas, calls, world, world.me);
268 const up = heldPlace(calls, "rifle") as Float32Array;
269 expect(raising[13]).toBeLessThan((up[13] as number) - 0.5);
270 // Nothing about the player moved: the raise is this file's and no rule of
271 // the world's, so `observe.ts` and the arena see the same player they did.
272 expect(structuredClone(world.me)).toEqual(before);
273
274 // Taking out the pistol starts the same raise again, from the same place.
275 world.me.weapon = "usp";
276 frame(canvas, calls, world, world.me);
277 const pistol = heldPlace(calls, "pistol") as Float32Array;
278 expect(pistol[13]).toBeCloseTo(raising[13] as number, 6);
279 });
280
281 test("ten guns firing at once stay well inside the line budget", () => {
282 const { canvas, calls } = recorder();
283 const world = scene();
284 frame(canvas, calls, world, world.me); // the level and the view model go up here
285 for (const p of world.players) world.effects.push(shotBy(world, p, "ak47"));
286 world.me.lastShotAt = world.time;
287 frame(canvas, calls, world, world.me);
288
289 const runs = lineRuns(calls);
290 // Nine other shooters in the world, and the tenth is the gun in your hands.
291 expect(runs.reduce((total, r) => total + r.count, 0)).toBe(10 * 12);
292 for (const run of runs) expect(run.first + run.count).toBeLessThanOrEqual(LINE_CAPACITY);
293 for (const call of calls.filter((c) => c.name === "bufferSubData"))
294 expect((call.args[3] as number) + (call.args[4] as number)).toBeLessThanOrEqual(LINE_CAPACITY * 6);
295 // And not one of them is an upload: the flashes are vertices in a buffer
296 // that was made once, off meshes that were uploaded before the round began.
297 expect(count(calls, "bufferData")).toBe(0);
298 });
299
157300 // --- a context the browser takes away
158301
159302 /** A renderer of this canvas's own, with the hooks main.ts would pass. */
src/client/renderer.ts +171 −9
@@ -13,9 +13,10 @@
1313 * all, and `webglcontextrestored` builds the lot a second time.
1414 */
1515
16 import { fallenMatrix, multiply, perspective, viewMatrix, modelMatrix, type Vec3 } from "./math.ts";
16 import { fallenMatrix, multiply, perspective, rad, viewMatrix, modelMatrix, type Vec3 } from "./math.ts";
1717 import {
18 bombMesh, grenadeMesh, levelMesh, pickupMesh, playerMesh, viewModelMesh, type Mesh,
18 bombMesh, grenadeMesh, HELD_MUZZLE, levelMesh, muzzle, pickupMesh, playerMesh, viewModelMesh,
19 type Mesh,
1920 } from "./models.ts";
2021 import type { MapDef } from "./map.ts";
2122 import { MAX_SCALE, MIN_SCALE } from "./quality.ts";
@@ -156,9 +157,37 @@ const BODY_LIFT = 7;
156157 const BODY_SHADE = 0.66;
157158 const BODY_FALL = 0.4;
158159
159 const LINE_CAPACITY = 4096; // vertices
160 export const LINE_CAPACITY = 4096; // vertices
160161 const LINE_BYTES = LINE_CAPACITY * 6 * Float32Array.BYTES_PER_ELEMENT;
161162
163 /**
164 * A muzzle flash: a star of bright spokes out of the barrel, drawn from the
165 * same line buffer the tracers use and blended additively so the core burns
166 * out white where the spokes cross. It lives `FLASH_LIFE` seconds — three
167 * frames at 60 Hz — which is a flash and not a lamp, and it costs
168 * `FLASH_SPOKES * 2` vertices of the budget per shooter: ten people firing at
169 * once is 120 of 4096.
170 *
171 * `FLASH_WORLD` and `FLASH_VIEW` are the same star in the two spaces this
172 * renderer draws in — world units, and the view model's own tiny units.
173 */
174 const FLASH_LIFE = 0.06;
175 const FLASH_SPOKES = 6;
176 const FLASH_WORLD = 17;
177 const FLASH_VIEW = 0.42;
178
179 /**
180 * The hands: how long the gun takes to come up after a switch, and how far
181 * down it goes to be reloaded. Both are animation and nothing else — the
182 * simulation lets you fire the instant it says you may, and `observe.ts` and
183 * the arena cannot see either number.
184 */
185 const RAISE_TIME = 0.24;
186 const RAISE_DROP = 0.7;
187 const RAISE_ROLL = 14;
188 const RELOAD_DROP = 0.55;
189 const RELOAD_ROLL = 26;
190
162191 /**
163192 * Everything that lives inside one GL context: the two programs and their
164193 * uniform locations, the texture array, the four meshes that never change, the
@@ -320,6 +349,12 @@ export function createRenderer(canvas: HTMLCanvasElement, hooks: RendererHooks =
320349 };
321350
322351 let bobPhase = 0;
352 // The gun the hands last had, and when they were given it: a change of
353 // weapon — or of the player the camera is inside — starts a raise. It is
354 // kept here and not on the player because nothing but this file may know it.
355 let heldWeapon = "";
356 let heldId = -1;
357 let raisedAt = -99;
323358
324359 const draw = (world: World, camera: Camera, view: Player, dt: number): void => {
325360 // The flag the event set, asked once: a GL call on a lost context is at
@@ -427,6 +462,29 @@ export function createRenderer(canvas: HTMLCanvasElement, hooks: RendererHooks =
427462 lineData[i + 3] = r; lineData[i + 4] = g; lineData[i + 5] = b;
428463 n += 1;
429464 };
465 /**
466 * One flash, as `FLASH_SPOKES` lines out of a bright core, in the plane
467 * spanned by `right` and `up` — the camera's, so it faces whoever sees it.
468 * The spoke lengths come off the shot's own timestamp, so two shots in a
469 * burst are not the same star and nothing asks `Math.random` in a frame.
470 */
471 const star = (
472 cx: number, cy: number, cz: number,
473 rx: number, ry: number, rz: number,
474 ux: number, uy: number, uz: number,
475 radius: number, seed: number, bright: number,
476 ): void => {
477 for (let s = 0; s < FLASH_SPOKES; s += 1) {
478 const a = (s / FLASH_SPOKES) * Math.PI * 2 + seed;
479 const len = radius * (0.5 + 0.5 * Math.abs(Math.sin(seed * 37.1 + s * 2.399)));
480 const ca = Math.cos(a) * len, sa = Math.sin(a) * len;
481 push(cx, cy, cz, bright, bright * 0.96, bright * 0.8);
482 push(
483 cx + rx * ca + ux * sa, cy + ry * ca + uy * sa, cz + rz * ca + uz * sa,
484 bright * 0.7, bright * 0.42, bright * 0.08,
485 );
486 }
487 };
430488 for (const effect of world.effects) {
431489 const age = world.time - effect.at;
432490 if (effect.kind === "tracer" && age < 0.08) {
@@ -456,13 +514,56 @@ export function createRenderer(canvas: HTMLCanvasElement, hooks: RendererHooks =
456514 push(world.bomb.pos[0], world.bomb.pos[1], world.bomb.pos[2] + 14, 1, 0.2 * blink, 0.15);
457515 push(world.bomb.pos[0], world.bomb.pos[1], world.bomb.pos[2] + 140, 1 * blink, 0.15, 0.1);
458516 }
517 // Everything above this line is drawn as it is; everything below it is
518 // drawn added to what is there, so the two passes are split here.
519 const opaque = n - (n % 2);
520
521 // --- the muzzle of everyone else. A tracer that comes out of nothing is a
522 // line appearing in the air; the flash is what says a person fired it. The
523 // shooter is looked up so the star sits at the end of the gun in their
524 // hands and not in the middle of their face, and the one player the camera
525 // is inside is skipped — their gun is the one in your hands, below.
526 //
527 // First the camera's right and up, as six numbers rather than two tuples:
528 // the star is built in that plane so it faces the eye, and a frame
529 // allocates none of it. (`angleVectors` says this and returns three arrays.)
530 const cy = Math.cos(rad(camera.yaw)), sy = Math.sin(rad(camera.yaw));
531 const cp = Math.cos(rad(camera.pitch)), sp = Math.sin(rad(camera.pitch));
532 const fx = cp * cy, fy = cp * sy, fz = -sp;
533 const rightX = sy, rightY = -cy;
534 const upX = rightY * fz, upY = -rightX * fz, upZ = rightX * fy - rightY * fx;
535 for (const effect of world.effects) {
536 if (effect.kind !== "shot" || effect.shooter === view.id) continue;
537 const age = world.time - effect.at;
538 if (age < 0 || age >= FLASH_LIFE) continue;
539 const flash = muzzle(WEAPONS[effect.weapon]?.kind ?? "");
540 if (flash === null) continue; // a knife and a grenade have no muzzle
541 let mx = effect.pos[0], my = effect.pos[1], mz = effect.pos[2];
542 for (const p of world.players) {
543 if (p.id !== effect.shooter || !p.alive) continue;
544 const c = Math.cos(rad(p.yaw)), s = Math.sin(rad(p.yaw));
545 mx = p.pos[0] + HELD_MUZZLE[0] * c - HELD_MUZZLE[1] * s;
546 my = p.pos[1] + HELD_MUZZLE[0] * s + HELD_MUZZLE[1] * c;
547 mz = p.pos[2] + HELD_MUZZLE[2] * (hullHeight(p) / 72);
548 break;
549 }
550 const bright = 1 - age / FLASH_LIFE;
551 star(mx, my, mz, rightX, rightY, 0, upX, upY, upZ, FLASH_WORLD * flash.size, effect.at, bright);
552 }
553
459554 if (n > 0) {
460555 gl.useProgram(gpu.lines);
461556 gl.uniformMatrix4fv(u.lineViewProj, false, viewProj);
462557 gl.bindVertexArray(gpu.lineVao);
463558 gl.bindBuffer(gl.ARRAY_BUFFER, gpu.lineBuffer);
464559 gl.bufferSubData(gl.ARRAY_BUFFER, 0, lineData, 0, n * 6);
465 gl.drawArrays(gl.LINES, 0, n - (n % 2));
560 if (opaque > 0) gl.drawArrays(gl.LINES, 0, opaque);
561 if (n > opaque) {
562 gl.enable(gl.BLEND);
563 gl.blendFunc(gl.ONE, gl.ONE);
564 gl.drawArrays(gl.LINES, opaque, n - opaque - ((n - opaque) % 2));
565 gl.disable(gl.BLEND);
566 }
466567 }
467568
468569 // --- the gun in your hands, on its own projection and its own depth. It is
@@ -473,7 +574,32 @@ export function createRenderer(canvas: HTMLCanvasElement, hooks: RendererHooks =
473574 const bobX = Math.sin(bobPhase) * Math.min(speed / 250, 1) * 0.05;
474575 const bobY = Math.abs(Math.cos(bobPhase)) * Math.min(speed / 250, 1) * 0.04;
475576 const kick = Math.max(0, 0.12 - (world.time - view.lastShotAt)) * 2.2;
476 const kind = WEAPONS[view.weapon]?.kind ?? "rifle";
577 const weapon = WEAPONS[view.weapon];
578 const kind = weapon?.kind ?? "rifle";
579
580 // A raise: the gun the hands are holding changed, so it comes up from
581 // below over a fixed `RAISE_TIME`. The switch itself was instantaneous
582 // and stays that way — this is the hands catching up with a decision the
583 // simulation has already made, and it is measured off `world.time` so a
584 // paused match does not raise the gun behind the overlay.
585 if (view.weapon !== heldWeapon || view.id !== heldId || world.time < raisedAt) {
586 heldWeapon = view.weapon;
587 heldId = view.id;
588 raisedAt = world.time;
589 }
590 const raised = Math.min(1, Math.max(0, (world.time - raisedAt) / RAISE_TIME));
591 const rise = (1 - raised) * (1 - raised); // 1 the moment it is drawn, 0 when it is up
592
593 // A reload the hands perform: down and rolled away, and back up, over the
594 // weapon's own `reloadTime`. `sin(pi * progress)` is zero at both ends,
595 // so the gun is level again exactly when `reloadUntil` passes and the
596 // magazine is full — the animation cannot outlive the thing it shows.
597 const reloadTime = weapon?.reloadTime ?? 0;
598 const reloadLeft = view.reloadUntil - world.time;
599 const dip = reloadTime > 0 && reloadLeft > 0 && reloadLeft <= reloadTime
600 ? Math.sin(Math.PI * (1 - reloadLeft / reloadTime))
601 : 0;
602
477603 let model = viewModels.get(kind);
478604 if (model === undefined) {
479605 model = upload(gl, viewModelMesh(kind));
@@ -485,13 +611,49 @@ export function createRenderer(canvas: HTMLCanvasElement, hooks: RendererHooks =
485611 gl.uniformMatrix4fv(u.viewProj, false, vmProj);
486612 gl.uniform3f(u.tint, 1, 1, 1);
487613 gl.uniform3fv(u.eye, [0, 0, 0]);
488 const place = modelMatrix([0, 0, 0], 0);
489 place[12] = bobX;
490 place[13] = bobY - kick * 0.12;
491 place[14] = kick * 0.35;
614 // One matrix for the lot: the roll is about the view's own Z, which
615 // tips the gun away from the middle of the screen as it drops.
616 const place = modelMatrix([0, 0, 0], -RELOAD_ROLL * dip - RAISE_ROLL * rise);
617 place[12] = bobX + 0.18 * rise;
618 place[13] = bobY - kick * 0.12 - RELOAD_DROP * dip - RAISE_DROP * rise;
619 place[14] = kick * 0.35 + 0.25 * dip + 0.2 * rise;
492620 gl.uniformMatrix4fv(u.model, false, place);
493621 gl.bindVertexArray(model.vao);
494622 gl.drawElements(gl.TRIANGLES, model.count, gl.UNSIGNED_INT, 0);
623
624 // --- and the flash off the end of it, after the gun and against the
625 // gun's depth, so the barrel takes the half of the star behind it. Its
626 // vertices go on the tail of the same line buffer the world used, at the
627 // muzzle the model itself declares, carried by `place` — which rotates
628 // about the view's Z and nothing else, so the muzzle's own Z is left
629 // alone and only the translation reaches it.
630 const flash = muzzle(kind);
631 const shotAge = world.time - view.lastShotAt;
632 const start = n;
633 if (flash !== null && shotAge >= 0 && shotAge < FLASH_LIFE) {
634 const at = flash.at;
635 star(
636 (place[0] as number) * at[0] + (place[4] as number) * at[1] + place[12],
637 (place[1] as number) * at[0] + (place[5] as number) * at[1] + place[13],
638 at[2] + place[14],
639 1, 0, 0, 0, 1, 0,
640 FLASH_VIEW * flash.size, view.lastShotAt, 1 - shotAge / FLASH_LIFE,
641 );
642 }
643 if (n > start) {
644 gl.useProgram(gpu.lines);
645 gl.uniformMatrix4fv(u.lineViewProj, false, vmProj);
646 gl.bindVertexArray(gpu.lineVao);
647 gl.bindBuffer(gl.ARRAY_BUFFER, gpu.lineBuffer);
648 gl.bufferSubData(
649 gl.ARRAY_BUFFER, start * 6 * Float32Array.BYTES_PER_ELEMENT,
650 lineData, start * 6, (n - start) * 6,
651 );
652 gl.enable(gl.BLEND);
653 gl.blendFunc(gl.ONE, gl.ONE);
654 gl.drawArrays(gl.LINES, start, (n - start) - ((n - start) % 2));
655 gl.disable(gl.BLEND);
656 }
495657 }
496658 gl.bindVertexArray(null);
497659 };
src/client/world.ts +7 −2
@@ -85,7 +85,12 @@ export type Effect =
8585 | { kind: "tracer"; from: Vec3; to: Vec3; at: number }
8686 | { kind: "impact"; at: number; pos: Vec3; normal: Vec3 }
8787 | { kind: "blood"; at: number; pos: Vec3 }
88 | { kind: "shot"; at: number; pos: Vec3; weapon: WeaponId; mine: boolean }
88 // A trigger pulled: where the gun was, what it was, whether it was the
89 // person's own, and who pulled it. `shooter` is what lets the renderer put a
90 // muzzle flash on that player's gun and skip the one whose eyes the camera
91 // is behind — `mine` cannot answer that, because a dead person watches a
92 // teammate shoot.
93 | { kind: "shot"; at: number; pos: Vec3; weapon: WeaponId; mine: boolean; shooter: number }
8994 | { kind: "hitmark"; at: number; headshot: boolean }
9095 // Damage the person took: who took it, where it came from in the world, and
9196 // how much. Only ever pushed for the person — a bot being shot is silent.
@@ -541,7 +546,7 @@ export function shoot(world: World, p: Player): boolean {
541546 const dir = angleVectors(yaw, pitch).forward;
542547 const to: Vec3 = [from[0] + dir[0] * range, from[1] + dir[1] * range, from[2] + dir[2] * range];
543548 const hit = traceBullet(from, to, world.boxes, world.players, p.id);
544 world.effects.push({ kind: "shot", at: world.time, pos: from, weapon: w.id, mine: p === world.me });
549 world.effects.push({ kind: "shot", at: world.time, pos: from, weapon: w.id, mine: p === world.me, shooter: p.id });
545550 if (w.kind !== "knife") world.effects.push({ kind: "tracer", at: world.time, from, to: hit.kind === "none" ? to : hit.point });
546551
547552 if (hit.kind === "world") {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs