Back to Faultline
SOURCE / PINNED RELEASE

Made of little things.

Faultline

Release
da1ffaa5624c…
Author-recorded commit
60f5f03189db…
License
LICENSE
Author’s source reference
nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-6932b12c78c

Archive hash verified: 5a2e0492417ec4e7…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/renderer.ts
import { type Arena, type Vec } from './maps';
import { type Player, type Grenade, eye, eyeOrigin, leanReach, look, AIM, DUCK } from './simulation';
import { combat } from './combat-tuning';
import { bones, Effects, skeleton } from './effects';
import { guns, RPG, isSecondary } from './weapons';

const vadd = (a: Vec, b: Vec): Vec => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
const sub = (a: Vec, b: Vec): Vec => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
const mul = (a: Vec, n: number): Vec => [a[0] * n, a[1] * n, a[2] * n];
const cross = (a: Vec, b: Vec): Vec => [
  a[1] * b[2] - a[2] * b[1],
  a[2] * b[0] - a[0] * b[2],
  a[0] * b[1] - a[1] * b[0],
];
const norm = (a: Vec) => mul(a, 1 / (Math.hypot(...a) || 1));
const X: Vec = [1, 0, 0],
  Y: Vec = [0, 1, 0],
  Z: Vec = [0, 0, 1];
const faces = [
  [0, 4, 6, 2, 0.72],
  [1, 3, 7, 5, 0.86],
  [0, 1, 5, 4, 0.48],
  [2, 6, 7, 3, 1.08],
  [0, 2, 3, 1, 0.9],
  [4, 5, 7, 6, 0.68],
];
class Mesh {
  private storage = new Float32Array(8192);
  private count = 0;
  private corners = new Float32Array(24);
  get data() {
    return this.storage.subarray(0, this.count);
  }
  clear() {
    this.count = 0;
  }
  private reserve(count: number) {
    if (this.count + count <= this.storage.length) return;
    const bigger = new Float32Array(Math.max(this.count + count, this.storage.length * 2));
    bigger.set(this.storage);
    this.storage = bigger;
  }
  triangle(a: Vec, b: Vec, c: Vec, color: string, shade = 1) {
    const n = parseInt(color.slice(1), 16),
      rgb = [n >> 16, (n >> 8) & 255, n & 255].map((channel) => (channel * shade) / 255);
    this.reserve(18);
    for (const p of [a, b, c]) {
      this.storage.set(p, this.count);
      this.storage.set(rgb, this.count + 3);
      this.count += 6;
    }
  }
  flare(center: Vec, radius: number, length: number, phase: number) {
    const tip: Vec = [center[0], center[1], center[2] + length];
    const point = (i: number): Vec => {
      const angle = (i * Math.PI) / 6 + phase,
        size = radius * (i % 2 ? 0.34 : 1);
      return [
        center[0] + Math.cos(angle) * size,
        center[1] + Math.sin(angle) * size,
        center[2] + length * 0.18,
      ];
    };
    this.reserve(12 * 36);
    for (let i = 0; i < 12; i++) {
      const a = point(i),
        b = point(i + 1);
      for (const [p, col] of [
        [center, [1, 0.98, 0.78]],
        [b, [1, 0.67, 0.22]],
        [a, [1, 0.76, 0.37]],
        [a, [1, 0.76, 0.37]],
        [b, [1, 0.67, 0.22]],
        [tip, [1, 0.94, 0.6]],
      ] as [Vec, Vec][]) {
        this.storage.set(p, this.count);
        this.storage.set(col, this.count + 3);
        this.count += 6;
      }
    }
  }
  box(c: Vec, w: number, h: number, d: number, color: string, axes: Vec[] = [X, Y, Z]) {
    const n = parseInt(color.slice(1), 16),
      red = (n >> 16) / 255,
      green = ((n >> 8) & 255) / 255,
      blue = (n & 255) / 255;
    this.reserve(216);
    const pts = this.corners,
      out = this.storage;
    for (let i = 0; i < 8; i++) {
      const x = w * (i & 1 ? 0.5 : -0.5),
        y = h * (i & 2 ? 0.5 : -0.5),
        z = d * (i & 4 ? 0.5 : -0.5);
      for (let k = 0; k < 3; k++)
        pts[i * 3 + k] = c[k] + axes[0][k] * x + axes[1][k] * y + axes[2][k] * z;
    }
    for (const [a, b, c, d, k] of faces) {
      const r = red * k,
        g = green * k,
        bl = blue * k;
      for (const i of [a, b, c, a, c, d]) {
        const j = i * 3;
        out[this.count++] = pts[j];
        out[this.count++] = pts[j + 1];
        out[this.count++] = pts[j + 2];
        out[this.count++] = r;
        out[this.count++] = g;
        out[this.count++] = bl;
      }
    }
  }
  beam(a: Vec, b: Vec, w: number, h: number, col: string) {
    const line: Vec = [b[0] - a[0], b[1] - a[1], b[2] - a[2]],
      f = norm(line),
      r = norm(cross(Math.abs(f[1]) > 0.94 ? Z : Y, f));
    this.box(mul(vadd(a, b), 0.5), w, h, Math.hypot(...line), col, [r, cross(f, r), f]);
  }
  body(j: Vec[], id: number, teamMode = false) {
    const jacket = teamMode ? (id % 2 ? '#587eaa' : '#cb924c') : id % 2 ? '#626f60' : '#6a7176',
      armor = '#424d47',
      boot = '#383d38';
    for (const [i, [a, b]] of bones.entries()) {
      if (i < 2) continue;
      const wide = i >= 8 ? 0.14 : 0.115;
      this.beam(j[a], j[b], wide, wide, i >= 8 ? armor : jacket);
    }
    const right = norm(sub(j[6], j[3])),
      up = norm(sub(j[1], j[0])),
      forward = norm(cross(right, up));
    const torso = [right, norm(cross(forward, right)), forward];
    const center = mul(vadd(j[0], j[1]), 0.5);
    this.box(center, 0.4, 0.48, 0.25, jacket, torso);
    this.box(vadd(center, mul(forward, 0.095)), 0.34, 0.31, 0.13, armor, torso);
    this.box(vadd(j[0], mul(up, -0.045)), 0.33, 0.18, 0.23, armor, torso);
    this.beam(j[1], j[2], 0.13, 0.13, '#968974');
    const headUp = norm(sub(j[2], j[1])),
      headAxes = [right, headUp, norm(cross(right, headUp))];
    this.box(j[2], 0.26, 0.26, 0.25, '#aa9982', headAxes);
    this.box(vadd(j[2], mul(headUp, 0.075)), 0.3, 0.16, 0.29, armor, headAxes);
    this.box(vadd(j[2], mul(headAxes[2], 0.13)), 0.23, 0.057, 0.035, '#414b48', headAxes);
    for (const i of [11, 14]) {
      const shin = norm(sub(j[i - 1], j[i])),
        sole = norm(cross(right, shin));
      this.box(vadd(j[i], mul(sole, 0.04)), 0.16, 0.14, 0.28, boot, [right, shin, sole]);
    }
    this.beam(j[3], j[6], 0.17, 0.17, jacket);
  }
}
export type Camera = { o: Vec; r: Vec; u: Vec; f: Vec; scale: number; aspect: number };
function shaderProgram(gl: WebGLRenderingContext) {
  const program = gl.createProgram()!;
  for (const [kind, source] of [
    [
      gl.VERTEX_SHADER,
      `
  attribute vec3 p;attribute vec3 c;uniform vec3 o,r,u,f;uniform vec2 lens;
  varying vec3 col;varying vec3 pos;varying float depth;
  void main(){vec3 d=p-o;float z=dot(d,f);gl_Position=vec4(dot(d,r)*lens.x,dot(d,u)*lens.y,z*1.00045-.065,z);col=c;pos=p;depth=z;}`,
    ],
    [
      gl.FRAGMENT_SHADER,
      `precision mediump float;uniform float opacity;varying vec3 col;varying vec3 pos;varying float depth;
    void main(){vec3 cell=floor(pos*5.);float n=fract(dot(mod(cell,32.),vec3(.381,.517,.723)));
    float grit=(n-.5)*.028;gl_FragColor=vec4(mix(col+grit,vec3(.70,.72,.66),clamp((depth-14.)*.008,0.,.55)),opacity);}`,
    ],
  ] as const) {
    const sh = gl.createShader(kind)!;
    gl.shaderSource(sh, source);
    gl.compileShader(sh);
    if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS))
      throw new Error(gl.getShaderInfoLog(sh) ?? 'Shader unavailable');
    gl.attachShader(program, sh);
    gl.deleteShader(sh);
  }
  gl.linkProgram(program);
  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error('Unable to link arena shader');
  return program;
}
export class Renderer {
  private actors = new Mesh();
  private viewModel = new Mesh();
  private autoScale = 1;
  private requestedScale = 1;
  private sampleTime = 0;
  private sampleCount = 0;
  private gl: WebGLRenderingContext | null;
  private flat: CanvasRenderingContext2D | null = null;
  private program?: WebGLProgram;
  private fixed?: WebGLBuffer;
  private dynamic?: WebGLBuffer;
  private glazing = new Float32Array();
  private staticData = new Float32Array();
  private level?: Arena;
  private uniforms: Record<string, WebGLUniformLocation | null> = {};
  private p = 0;
  private c = 0;
  width = 0;
  height = 0;
  constructor(readonly canvas: HTMLCanvasElement) {
    this.gl = canvas.getContext('webgl', {
      alpha: true,
      antialias: false,
      depth: true,
      powerPreference: 'high-performance',
    });
    if (this.gl) this.setup();
    else this.flat = canvas.getContext('2d', { alpha: true });
    canvas.addEventListener('webglcontextlost', (e) => e.preventDefault());
    canvas.addEventListener('webglcontextrestored', () => {
      this.level = undefined;
      this.setup();
    });
  }
  private setup() {
    const g = this.gl!;
    this.program = shaderProgram(g);
    g.useProgram(this.program);
    this.fixed = g.createBuffer()!;
    this.dynamic = g.createBuffer()!;
    this.p = g.getAttribLocation(this.program, 'p');
    this.c = g.getAttribLocation(this.program, 'c');
    for (const key of ['o', 'r', 'u', 'f', 'lens', 'opacity'])
      this.uniforms[key] = g.getUniformLocation(this.program, key);
    g.enable(g.DEPTH_TEST);
    g.enable(g.CULL_FACE);
    g.frontFace(g.CW);
    g.enableVertexAttribArray(this.p);
    g.enableVertexAttribArray(this.c);
    g.clearColor(0, 0, 0, 0);
  }
  resize(w: number, h: number, scale: number) {
    this.width = w;
    this.height = h;
    this.requestedScale = scale;
    const density = Math.min(1.5, devicePixelRatio) * scale * this.autoScale;
    const cw = Math.max(1, Math.round(w * density)),
      ch = Math.max(1, Math.round(h * density));
    if (this.canvas.width !== cw || this.canvas.height !== ch) {
      this.canvas.width = cw;
      this.canvas.height = ch;
      this.gl?.viewport(0, 0, cw, ch);
    }
  }
  private geometry?: Arena['boxes'];
  private overhead = false;
  private build(map: Arena, overhead: boolean) {
    this.overhead = overhead;
    const m = new Mesh(),
      glass = new Mesh();
    this.geometry = map.boxes;
    const t = map.terrain;
    if (t) {
      const vertex = (ix: number, iz: number): Vec => [
        ix * t.spacing - t.extent,
        t.heights[iz * t.side + ix],
        iz * t.spacing - t.extent,
      ];
      for (let z = 0; z < t.side - 1; z++)
        for (let x = 0; x < t.side - 1; x++) {
          const a = vertex(x, z),
            b = vertex(x + 1, z),
            c = vertex(x, z + 1),
            d = vertex(x + 1, z + 1);
          const trail =
            Math.abs(a[0] - 9 * Math.sin(a[2] * 0.066)) < 3 ||
            Math.abs(a[2] + 7 * Math.sin(a[0] * 0.075)) < 3;
          const color = trail ? '#a49a74' : a[1] > 5 ? '#919872' : '#77835f';
          m.triangle(a, c, b, color, 0.98 + (b[1] - a[1]) * 0.048);
          m.triangle(b, c, d, color, 0.97 + (d[1] - c[1]) * 0.048);
        }
    }
    for (const b of map.boxes) {
      if (b.boundary || (overhead && b.roof)) continue;
      if (b.pane) {
        glass.box([b.x, b.y + b.h / 2, b.z], b.w, b.h, b.d, b.color);
        for (const s of [-1, 1])
          m.box([b.x, b.y + (s > 0 ? b.h - 0.1 : 0.12), b.z], b.w, 0.09, b.d, '#a9cbca');
        for (const k of [-0.27, 0, 0.27])
          m.beam(
            [b.x + b.w * k - 0.24, b.y + 0.45, b.z],
            [b.x + b.w * k + 0.38, b.y + b.h - 0.35, b.z],
            0.045,
            0.04,
            '#b9d2cf',
          );
      } else if (b.shape) {
        const point = (i: number, y: number, r: number): Vec => [
          b.x + Math.cos((i * Math.PI) / 3) * b.w * 0.5 * r,
          y,
          b.z + Math.sin((i * Math.PI) / 3) * b.d * 0.5 * r,
        ];
        for (let i = 0; i < 6; i++) {
          const a = point(i, b.y, 1),
            c = point(i + 1, b.y, 1),
            shade = 0.76 + 0.22 * Math.cos(i);
          if (b.shape === 'pine') m.triangle(a, [b.x, b.y + b.h, b.z], c, b.color, shade);
          else {
            const tip = point(i, b.y + b.h * 0.73, 0.82),
              tip2 = point(i + 1, b.y + b.h * 0.73, 0.82);
            m.triangle(a, tip, c, b.color, shade);
            m.triangle(c, tip, tip2, b.color, shade);
            m.triangle(tip, [b.x + b.w * 0.08, b.y + b.h, b.z], tip2, b.color, 1.1);
          }
        }
      } else m.box([b.x, b.y + b.h / 2, b.z], b.w, b.h, b.d, b.color);
    }
    // Distant skyline suggests the surrounding industrial district at negligible draw cost.
    for (let i = 0; !t && i < 26; i++) {
      const a = i * 2.399,
        r = 40 + (i % 4) * 3,
        h = 3 + ((i * 11) % 9);
      m.box([Math.sin(a) * r, h / 2 - 0.8, Math.cos(a) * r], 4 + (i % 8), h, 5 + (i % 5), '#858f84');
      if (i % 5 === 0) m.box([Math.sin(a) * r, h + 2, Math.cos(a) * r], 0.85, 6, 0.85, '#7c8178');
    }
    // Painted cargo markings, wall seams and a shadow footprint for major objects.
    for (const b of map.boxes) {
      if (t || b.pane || !b.solid || b.y !== 0 || b.h < 1 || b.w > 35 || b.d > 35) continue;
      m.box([b.x + 0.26, 0.014, b.z + 0.39], b.w + 0.25, 0.012, b.d + 0.4, '#767867');
      if (b.w > 4 && b.h > 2.5) {
        for (const t of [-1, 1])
          m.box(
            [b.x - b.w * 0.28, b.h * 0.57, b.z + t * (b.d * 0.5 + 0.025)],
            0.9,
            0.14,
            0.044,
            '#d2c7a6',
          );
      }
    }
    this.glazing = new Float32Array(glass.data);
    this.staticData = new Float32Array(m.data);
    this.level = map;
    const g = this.gl;
    if (g) {
      g.bindBuffer(g.ARRAY_BUFFER, this.fixed!);
      g.bufferData(g.ARRAY_BUFFER, this.staticData, g.STATIC_DRAW);
    }
  }
  private draw(c: Camera, data: Float32Array, staticBuffer = false, opacity = 1) {
    const g = this.gl;
    if (g) {
      g.uniform1f(this.uniforms.opacity, opacity);
      g.uniform3fv(this.uniforms.o, c.o);
      g.uniform3fv(this.uniforms.r, c.r);
      g.uniform3fv(this.uniforms.u, c.u);
      g.uniform3fv(this.uniforms.f, c.f);
      g.uniform2f(this.uniforms.lens, c.scale / c.aspect, c.scale);
      g.bindBuffer(g.ARRAY_BUFFER, staticBuffer ? this.fixed! : this.dynamic!);
      if (!staticBuffer) g.bufferData(g.ARRAY_BUFFER, data, g.STREAM_DRAW);
      g.vertexAttribPointer(this.p, 3, g.FLOAT, false, 24, 0);
      g.vertexAttribPointer(this.c, 3, g.FLOAT, false, 24, 12);
      g.drawArrays(g.TRIANGLES, 0, data.length / 6);
    }
  }
  // Depth-sorted clipped triangles make practice and hosted play usable on software-only clients.
  private software(c: Camera, meshes: Float32Array[]) {
    const ctx = this.flat;
    if (!ctx) return;
    const w = this.canvas.width,
      h = this.canvas.height,
      scale = h * c.scale * 0.5;
    const faces: { pts: number[][]; depth: number; color: string }[] = [];
    for (const data of meshes)
      for (let i = 0; i < data.length; i += 18) {
        let pts: number[][] = [];
        for (let k = i; k < i + 18; k += 6) {
          const x = data[k] - c.o[0],
            y = data[k + 1] - c.o[1],
            z = data[k + 2] - c.o[2];
          pts.push([
            x * c.r[0] + y * c.r[1] + z * c.r[2],
            x * c.u[0] + y * c.u[1] + z * c.u[2],
            x * c.f[0] + y * c.f[1] + z * c.f[2],
          ]);
        }
        if (pts.every((p) => p[2] < 0.06)) continue;
        if (pts.some((p) => p[2] < 0.06)) {
          const clipped: number[][] = [];
          for (let k = 0; k < 3; k++) {
            const a = pts[k],
              b = pts[(k + 1) % 3];
            if (a[2] >= 0.06) clipped.push(a);
            if (a[2] >= 0.06 !== b[2] >= 0.06) {
              const t = (0.06 - a[2]) / (b[2] - a[2]);
              clipped.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, 0.06]);
            }
          }
          pts = clipped;
        }
        const screen = pts.map((p) => [w / 2 + (p[0] * scale) / p[2], h / 2 - (p[1] * scale) / p[2]]);
        if (
          screen.every((p) => p[0] < 0) ||
          screen.every((p) => p[0] > w) ||
          screen.every((p) => p[1] < 0) ||
          screen.every((p) => p[1] > h)
        )
          continue;
        faces.push({
          pts: screen,
          depth: pts.reduce((n, p) => n + p[2], 0) / pts.length,
          color:
            'rgba(' +
            [3, 4, 5].map((k) => Math.round(data[i + k] * 255)).join(',') +
            (data === this.glazing ? ',.12)' : ',1)'),
        });
      }
    faces.sort((a, b) => b.depth - a.depth);
    for (const f of faces) {
      ctx.beginPath();
      f.pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y)));
      ctx.closePath();
      ctx.fillStyle = f.color;
      ctx.fill();
    }
  }
  render(
    map: Arena,
    me: Player | undefined,
    players: Player[],
    grenades: Grenade[],
    fx: Effects,
    time: number,
    reduced: boolean,
    teamMode = false,
  ) {
    if (this.level !== map || this.geometry !== map.boxes || this.overhead !== !me) this.build(map, !me);
    // Adapt pixel cost to the sustained frame interval. Simulation stays at 60 Hz.
    if (!this.sampleTime) this.sampleTime = time;
    if (++this.sampleCount >= 24) {
      const interval = (time - this.sampleTime) / this.sampleCount;
      const next =
        interval > 21
          ? Math.max(0.5, this.autoScale - 0.12)
          : interval < 17.2
            ? Math.min(1, this.autoScale + 0.035)
            : this.autoScale;
      if (next !== this.autoScale) {
        this.autoScale = next;
        this.resize(this.width, this.height, this.requestedScale);
      }
      this.sampleTime = time;
      this.sampleCount = 0;
    }
    const m = this.actors;
    m.clear();
    const aspect = this.canvas.width / this.canvas.height;
    const aim = !!me && Boolean(me.buttons & AIM) && me.hp > 0;
    let bounce = 0;
    let cam: Camera;
    if (me) {
      const walk = Math.hypot(me.vx, me.vz);
      bounce = reduced ? 0 : Math.sin(time * 0.012) * Math.min(0.027, walk * 0.006);
      const pitch = me.pitch + (reduced ? 0 : fx.kick * 0.65 + fx.shake * Math.sin(time * 0.12) * 0.12);
      const r: Vec = [Math.cos(me.yaw), 0, -Math.sin(me.yaw)],
        f: Vec = [Math.sin(me.yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(me.yaw) * Math.cos(pitch)];
      const origin = eyeOrigin(me), up = cross(f, r), tilt = reduced ? 0 : me.lean * 0.0013;
      origin[1] = me.y + (me.hp > 0 ? eye(me) + bounce : 0.48);
      cam = { o: origin, r: vadd(mul(r, Math.cos(tilt)), mul(up, -Math.sin(tilt))),
        u: vadd(mul(up, Math.cos(tilt)), mul(r, Math.sin(tilt))), f, aspect,
        scale: (aim ? guns[me.gun].zoom : 1) * 1.32 };
    } else {
      const f: Vec = [0, -0.96, 0.28];
      const scale = Math.min(1.32, 1.32 * aspect);
      const distance = map.size * (0.31 + 1.06 * Math.max(scale / aspect, scale));
      cam = { o: mul(f, -distance), r: X, u: cross(f, X), f, aspect, scale };
    }
    const inView = (x: number, z: number) => {
      if (!me) return true;
      const dx = x - me.x, dz = z - me.z;
      const forward = dx * cam.f[0] + dz * cam.f[2];
      return forward >= -1.4 && Math.abs(dx * cam.r[0] + dz * cam.r[2]) <
        3 + ((Math.max(0, forward) * cam.aspect) / cam.scale) * 1.45;
    };
    for (const p of players) {
      if (p.id === me?.id || !p.hp || !inView(p.x, p.z)) continue;
      const moving = Math.hypot(p.vx, p.vz) > 0.3;
      const j = skeleton(
        p.x,
        p.y,
        p.z,
        p.yaw,
        moving ? time * 0.012 + p.id : 0,
        Boolean(p.buttons & DUCK),
        p.pitch,
      );
      for (let k = 0; k < 9; k++) {
        const amount = ((k === 0 ? 0.12 : k === 2 ? 1 : 0.55) * p.lean * leanReach) / 100;
        j[k][0] += Math.cos(p.yaw) * amount;
        j[k][2] -= Math.sin(p.yaw) * amount;
      }
      m.body(j, p.id, teamMode);
      const dir = look(p.yaw, p.pitch);
      const length = p.gun === RPG ? 0.78 : isSecondary(p.gun) ? 0.3 : 0.66;
      const end = vadd(j[8], mul(dir, length));
      m.beam(j[8], end, p.gun === RPG ? 0.18 : 0.09, 0.11, '#393e3b');
      if (fx.muzzles.has(p.id)) m.beam(end, vadd(end, mul(dir, 0.21)), 0.12, 0.1, '#ffce6d');
      m.box([p.x, p.y + 0.016, p.z], 0.68, 0.02, 0.5, '#747662');
    }
    for (const b of fx.bodies)
      if (inView(b.j[0].p[0], b.j[0].p[2]))
        m.body(
          b.j.map((n) => n.p),
          b.team,
          teamMode,
        );
    for (const blast of fx.blasts) {
      const t = blast.age / combat.feel.duration,
        radius = 0.18 + combat.feel.ringRadius * Math.sqrt(t),
        height = blast.o[1] + 0.06;
      if (blast.age < combat.feel.coreDuration) {
        const size = combat.feel.coreRadius * (1 - blast.age / combat.feel.coreDuration);
        m.box(blast.o, size * 0.76, size, size * 0.72, '#fff0ba');
        for (let i = 0; i < 5; i++) {
          const a = (i * Math.PI * 2) / 5 + blast.o[0],
            reach = size * 0.8;
          const tip: Vec = [
            blast.o[0] + Math.cos(a) * reach,
            blast.o[1] + size * (0.12 + (i % 2) * 0.22),
            blast.o[2] + Math.sin(a) * reach,
          ];
          m.beam(blast.o, tip, size * 0.37, size * 0.26, '#ffc16a');
        }
      }
      for (let i = 0; i < 16; i++) {
        const a = (i * Math.PI) / 8,
          b = a + 0.3;
        m.beam(
          [blast.o[0] + Math.cos(a) * radius, height, blast.o[2] + Math.sin(a) * radius],
          [blast.o[0] + Math.cos(b) * radius, height, blast.o[2] + Math.sin(b) * radius],
          0.065 * (1 - t) + 0.015,
          0.045,
          t < 0.4 ? '#fbc784' : '#c5b69a',
        );
      }
    }
    for (const g of grenades)
      m.box(
        [g.x, g.y, g.z],
        g.rocket ? 0.28 : 0.22,
        g.rocket ? 0.18 : 0.27,
        0.22,
        g.rocket ? '#edab54' : '#57613c',
      );
    for (const p of fx.sparks) {
      const size = p.size * (0.5 + p.t / p.total);
      m.box(p.p, size, size, size, p.color);
    }
    for (const mark of fx.marks) {
      if (!inView(mark.o[0], mark.o[2])) continue;
      const normal = mark.n,
        tangent = norm(cross(Math.abs(normal[1]) > 0.9 ? X : Y, normal)),
        up = cross(normal, tangent),
        axes = [tangent, up, normal];
      const origin = vadd(mark.o, mul(normal, 0.035)),
        blood = mark.size > 0.1;
      const count = blood ? 8 : 1;
      for (let i = 0; i < count; i++) {
        const angle = mark.seed + i * 2.4,
          dist = i ? mark.size * (0.38 + i * 0.15) : 0,
          r = mark.size * (i ? 0.27 : 1);
        const center = vadd(
          vadd(origin, mul(tangent, Math.cos(angle) * dist)),
          mul(up, Math.sin(angle) * dist),
        );
        m.box(center, r * 1.3, r, 0.008, mark.color, axes);
      }
    }
    this.gl?.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);
    if (this.flat) this.flat.clearRect(0, 0, this.canvas.width, this.canvas.height);
    const dyn = m.data;
    if (this.gl) {
      this.draw(cam, this.staticData, true);
      this.draw(cam, dyn);
      if (this.glazing.length) {
        const gl = this.gl;
        gl.enable(gl.BLEND);
        gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
        gl.depthMask(false);
        this.draw(cam, this.glazing, false, 0.23);
        gl.depthMask(true);
        gl.disable(gl.BLEND);
      }
    } else this.software(cam, [this.staticData, dyn, this.glazing]);
    if (!me) return cam;
    if (!me.hp) return;
    const gun = this.viewModel;
    gun.clear();
    const model = guns[me.gun],
      reloading = me.reload > 0 ? Math.sin((Math.PI * me.reload) / model.reload) : 0;
    // The view model uses camera-local coordinates and a fresh depth range.
    const gx = aim ? 0.0 : Math.min(0.22, cam.aspect * 0.17),
      gy = (aim ? -0.104 : -0.205) - reloading * 0.17 + bounce * 0.4,
      gz = 0.56 - fx.kick * 0.7;
    const part = (x: number, y: number, z: number, w: number, h: number, d: number, c: string) =>
      gun.box([gx + x, gy + y, gz + z], w, h, d, c);
    const tan = me.gun === 2 ? '#947254' : me.gun === 4 ? '#6f715a' : '#55605b',
      barrel = me.gun === 1 ? 0.22 : me.gun === 3 ? 0.5 : 0.34;
    if (me.gun === RPG) {
      part(0, 0.0, 0.12, 0.17, 0.16, 0.78, '#586447');
      part(0, 0.014, 0.51, 0.2, 0.19, 0.06, '#323e35');
      part(0, 0.102, 0.02, 0.055, 0.055, 0.05, '#4b5041');
      part(0.06, -0.09, -0.05, 0.12, 0.12, 0.22, '#71735d');
    } else if (isSecondary(me.gun)) {
      part(0, 0.02, 0.02, 0.075, 0.08, 0.26, me.gun === 5 ? '#57625b' : '#838578');
      part(0, -0.072, -0.058, 0.075, 0.15, 0.1, '#424b43');
      part(0.047, -0.083, -0.11, 0.094, 0.105, 0.17, '#6d735e');
      part(0, 0.075, 0.125, 0.016, 0.025, 0.02, '#414941');
    } else {
      part(0, 0, 0, 0.103, 0.109, 0.36, '#363e3c');
      part(0, 0.044, 0.04, 0.112, 0.04, 0.31, tan);
      part(0, 0.005, 0.21, 0.096, 0.088, 0.23, tan);
      part(0, 0.021, 0.38, 0.034, 0.034, barrel, '#424a48');
      part(0, 0.022, 0.36 + barrel / 2, 0.05, 0.049, 0.1, '#363b39');
      part(0, -0.09, 0.03, 0.057, 0.17, 0.09, '#535b52');
      for (let k = 0; k < 7; k++) part(0, 0.065, 0.08 + k * 0.034, 0.106, 0.014, 0.014, '#343c38');
      part(0, 0.082, -0.025, 0.074, 0.018, 0.054, '#404944');
      for (const s of [-1, 1]) part(s * 0.029, 0.105, -0.025, 0.014, 0.046, 0.038, '#373d39');
      part(0, 0.127, -0.025, 0.07, 0.013, 0.04, '#4e5a50');
      part(0, 0.077, 0.32, 0.012, 0.063, 0.018, '#414941');
      part(0.068, -0.074, -0.08, 0.105, 0.104, 0.19, '#6e7360');
      part(-0.053, -0.067, 0.17, 0.093, 0.1, 0.13, '#777a62');
    }
    if (fx.flash > 0) {
      const size = fx.flash / 0.075;
      gun.flare(
        [gx, gy + 0.022, gz + (me.gun === RPG ? 0.54 : isSecondary(me.gun) ? 0.16 : 0.42 + barrel / 2)],
        (0.032 + 0.049 * size) * (me.gun === 2 ? 1.4 : 1),
        0.12 + 0.19 * size,
        fx.shotCount * 1.7,
      );
    }
    const view: Camera = { o: [0, 0, 0], r: X, u: Y, f: Z, aspect: cam.aspect, scale: 1.42 };
    const viewData = gun.data;
    if (this.gl) {
      this.gl.clear(this.gl.DEPTH_BUFFER_BIT);
      this.draw(view, viewData);
    } else this.software(view, [viewData]);
  }
}