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/simulation.ts
import { groundHeight } from './terrain';
import { roundArena, setBroken } from './maps';
import {
  clamp,
  contacts,
  inside,
  rayBox,
  shotSurfaces,
  wallDistance,
  type Arena,
  type Vec,
} from './maps';
import { FIRST_SECONDARY, RPG, guns, isPrimary, isSecondary } from './weapons';
import { combat } from './combat-tuning';

export const HZ = 60,
  DT = 1 / HZ,
  ROUND = HZ * 300,
  GOAL = 12;
export const FIRE = 1,
  JUMP = 2,
  DUCK = 4,
  AIM = 8,
  RELOAD = 16,
  THROW = 32,
  SPRINT = 64,
  PRIMARY = 128,
  SECONDARY = 256,
  LEAN_LEFT = 512,
  LEAN_RIGHT = 1024;
export const teams = ['Amber', 'Slate'] as const;
export type Input = [
  seq: number,
  forward: number,
  side: number,
  yaw: number,
  pitch: number,
  buttons: number,
  life: number,
  viewTick: number,
];
export type Player = {
  id: number;
  x: number;
  y: number;
  z: number;
  vx: number;
  vy: number;
  vz: number;
  yaw: number;
  pitch: number;
  hp: number;
  gun: number;
  ammo: number;
  holster: number;
  spareAmmo: number;
  cook: number;
  boost: number;
  lean: number;
  cool: number;
  reload: number;
  frags: number;
  life: number;
  kills: number;
  deaths: number;
  respawn: number;
  ack: number;
  buttons: number;
  ground: number;
  protect: number;
};
export type Grenade = {
  x: number;
  y: number;
  z: number;
  vx: number;
  vy: number;
  vz: number;
  fuse: number;
  owner: number;
  rocket?: boolean;
};
export type Effect = {
  kind: 'shot' | 'hit' | 'death' | 'blast' | 'impact' | 'blood' | 'glass';
  id: number;
  who: number;
  other: number;
  o: Vec;
  v: Vec;
  gun: number;
};
export const eye = (p: Player) => (p.buttons & DUCK ? 1.02 : 1.59);
export const leanReach = 0.46;
export function eyeOrigin(p: Player): Vec {
  return [
    p.x + (Math.cos(p.yaw) * p.lean * leanReach) / 100,
    p.y + eye(p),
    p.z - (Math.sin(p.yaw) * p.lean * leanReach) / 100,
  ];
}
export function spreadFor(p: Player) {
  return (
    guns[p.gun].spread *
    (p.buttons & AIM ? 0.44 : 1) *
    (p.buttons & DUCK ? combat.crouch.spread : 1) *
    (1 + Math.hypot(p.vx, p.vz) * 0.1)
  );
}
export function recoilFor(gun: number, buttons: number) {
  return guns[gun].kick * (buttons & DUCK ? combat.crouch.recoil : 1);
}
function stepLean(map: Arena, p: Player, buttons: number) {
  const wanted = 100 * (Number(!!(buttons & LEAN_RIGHT)) - Number(!!(buttons & LEAN_LEFT)));
  let next = p.lean + clamp(wanted - p.lean, -16, 16);
  if (next) {
    const sign = Math.sign(next),
      v: Vec = [Math.cos(p.yaw) * sign, 0, -Math.sin(p.yaw) * sign],
      o: Vec = [p.x, p.y + eye(p), p.z];
    let reach = (Math.abs(next) * leanReach) / 100;
    for (const b of contacts(map, p.x, p.z)) {
      const t = rayBox(
        o,
        v,
        [b.x - b.w / 2 - 0.17, b.y - 0.17, b.z - b.d / 2 - 0.17],
        [b.x + b.w / 2 + 0.17, b.y + b.h + 0.17, b.z + b.d / 2 + 0.17],
        reach,
      );
      reach = Math.min(reach, Math.max(0, t - 0.005));
    }
    next = sign * Math.round((reach * 100) / leanReach);
  }
  p.lean = next;
}
export const look = (a: number, b: number): Vec => [
  Math.sin(a) * Math.cos(b),
  Math.sin(b),
  Math.cos(a) * Math.cos(b),
];
export const idle = (p: Player): Input => [p.ack, 0, 0, p.yaw, p.pitch, 0, p.life, -1];
export function spawn(
  map: Arena,
  id: number,
  gun: number,
  life = 1,
  secondary = FIRST_SECONDARY,
  teamMode = false,
): Player {
  const s = map.spawns[(id + (life - 1) * (teamMode ? 2 : 3)) % map.spawns.length];
  const holster = isPrimary(gun) ? secondary : 0;
  return {
    id,
    x: s[0],
    y: groundHeight(map.terrain, s[0], s[1]),
    z: s[1],
    vx: 0,
    vy: 0,
    vz: 0,
    yaw: s[2],
    pitch: 0,
    hp: 100,
    gun,
    ammo: guns[gun].mag,
    holster,
    spareAmmo: guns[holster].mag,
    cook: 0,
    boost: 0,
    lean: 0,
    cool: 0,
    reload: 0,
    frags: 2,
    life,
    kills: 0,
    deaths: 0,
    respawn: 0,
    ack: 0,
    buttons: 0,
    ground: 1,
    protect: 80,
  };
}
export function equipLoadout(p: Player, primary: number, secondary: number) {
  if (!isPrimary(primary) || !isSecondary(secondary)) return;
  const active = isPrimary(p.gun) ? primary : secondary,
    spare = isPrimary(p.gun) ? secondary : primary;
  if (p.gun !== active) {
    p.gun = active;
    p.ammo = 0;
    p.reload = guns[active].reload;
    p.cool = 12;
  }
  if (p.holster !== spare) {
    p.holster = spare;
    p.spareAmmo = 0;
  }
}
export function blocked(map: Arena, x: number, y: number, z: number, height: number, r = 0.32) {
  return contacts(map, x, z).some(
    (b) => b.y + b.h > y + 0.035 && b.y < y + height - 0.015 && inside(b, x, z, r),
  );
}
// Shared movement and weapon clocks. Only the authority resolves hits or spawns projectiles.
export function stepPlayer(map: Arena, p: Player, i: Input) {
  if (p.hp <= 0 || p.life !== i[6]) return 0;
  const previous = p.buttons,
    bits = i[5] & 127;
  if (!p.cook && ((i[5] & SECONDARY && isPrimary(p.gun)) || (i[5] & PRIMARY && isSecondary(p.gun)))) {
    [p.gun, p.holster] = [p.holster, p.gun];
    [p.ammo, p.spareAmmo] = [p.spareAmmo, p.ammo];
    p.reload = p.ammo ? 0 : guns[p.gun].reload;
    p.cool = Math.max(p.cool, 10);
  }
  const profile = guns[p.gun];
  p.yaw = i[3];
  p.pitch = i[4];
  p.buttons = bits;
  if (!(bits & DUCK) && blocked(map, p.x, p.y, p.z, 1.76)) p.buttons |= DUCK;
  const height = eye(p) + 0.17;
  const speed =
    (p.buttons & DUCK ? 2.2 : bits & AIM ? 2.85 : bits & SPRINT ? 7 : 4.9) *
    (p.boost ? combat.hit.speedScale : 1);
  p.boost = Math.max(0, p.boost - 1);
  const l = Math.max(1, Math.hypot(i[1], i[2])),
    f = i[1] / l,
    s = i[2] / l;
  const dx = (Math.sin(p.yaw) * f + Math.cos(p.yaw) * s) * speed,
    dz = (Math.cos(p.yaw) * f - Math.sin(p.yaw) * s) * speed;
  const approach = p.ground ? 0.35 : 0.14;
  p.vx += (dx - p.vx) * approach;
  p.vz += (dz - p.vz) * approach;
  for (const [axis, velocity] of [
    ['x', 'vx'],
    ['z', 'vz'],
  ] as const) {
    const x = p.x + (axis === 'x' ? p.vx * DT : 0),
      z = p.z + (axis === 'z' ? p.vz * DT : 0);
    if (blocked(map, x, p.y, z, height)) {
      if (!p.ground || blocked(map, x, p.y + 0.25, z, height)) {
        p[velocity] = 0;
        continue;
      }
      let top = p.y;
      for (const b of contacts(map, x, z))
        if (inside(b, x, z, 0.32) && b.y + b.h <= p.y + 0.26) top = Math.max(top, b.y + b.h);
      p.y = top;
    }
    p[axis] = axis === 'x' ? x : z;
  }
  if (bits & JUMP && !(previous & JUMP) && p.ground) {
    p.vy = 6.4;
    p.ground = 0;
  }
  p.vy -= 17 * DT;
  const nextY = p.y + p.vy * DT;
  let floor = groundHeight(map.terrain, p.x, p.z),
    ceiling = 100;
  for (const b of contacts(map, p.x, p.z)) {
    if (!inside(b, p.x, p.z, 0.31)) continue;
    if (b.y + b.h <= p.y + 0.035) floor = Math.max(floor, b.y + b.h);
    if (b.y >= p.y + height - 0.02) ceiling = Math.min(ceiling, b.y - height);
  }
  p.y = map.terrain && p.ground && floor >= p.y - 0.15 ? floor : clamp(nextY, floor, ceiling);
  p.ground = Number(p.y <= floor + 0.001);
  if (p.ground || nextY >= ceiling) p.vy = 0;
  stepLean(map, p, i[5]);
  p.protect = Math.max(0, p.protect - 1);
  p.cool = Math.max(0, p.cool - 1);
  if (p.reload > 0 && --p.reload === 0) p.ammo = profile.mag;
  if ((bits & RELOAD || (bits & FIRE && !p.ammo)) && !p.reload && p.ammo < profile.mag)
    p.reload = profile.reload;
  let actions = 0;
  if (!p.cook && bits & THROW && !(previous & THROW) && p.frags > 0) {
    p.frags--;
    p.cook = combat.grenade.fuse;
    p.protect = 0;
  }
  if (p.cook) {
    p.cook--;
    if (!(bits & THROW) || !p.cook) actions |= THROW;
    // The caller uses the remaining fuse when spawning the projectile.
    if (actions & THROW) p.cook = 0;
    return actions;
  }
  if (
    bits & FIRE &&
    !p.reload &&
    !p.cool &&
    p.ammo > 0 &&
    (profile.mode === 'AUTO' || !(previous & FIRE))
  ) {
    p.ammo--;
    p.cool = profile.delay;
    p.protect = 0;
    actions |= FIRE;
  }
  return actions;
}
export function validInput(v: unknown): v is Input {
  return (
    Array.isArray(v) &&
    v.length === 8 &&
    v.every(Number.isFinite) &&
    Number.isSafeInteger(v[0]) &&
    v[0] > 0 &&
    v[0] < 1e9 &&
    Math.abs(v[1]) <= 1 &&
    Math.abs(v[2]) <= 1 &&
    Math.abs(v[3]) <= Math.PI + 0.001 &&
    Math.abs(v[4]) <= 1.39 &&
    Number.isInteger(v[5]) &&
    v[5] >= 0 &&
    v[5] < 2048 &&
    Number.isSafeInteger(v[6]) &&
    Number.isSafeInteger(v[7])
  );
}
type Pose = {
  id: number;
  life: number;
  x: number;
  y: number;
  z: number;
  crouched: boolean;
  dx: number;
  dz: number;
};
function poseOf(p: Player): Pose {
  return {
    id: p.id,
    life: p.life,
    x: p.x,
    y: p.y,
    z: p.z,
    crouched: Boolean(p.buttons & DUCK),
    dx: (Math.cos(p.yaw) * p.lean * leanReach) / 100,
    dz: (-Math.sin(p.yaw) * p.lean * leanReach) / 100,
  };
}
function hitZones(body: Pose) {
  const low = body.crouched ? 0.38 : 0;
  const zone = (bottom: number, top: number, r: number, weight: number, shift: number) => ({
    min: [body.x + body.dx * shift - r, body.y + bottom, body.z + body.dz * shift - r] as Vec,
    max: [body.x + body.dx * shift + r, body.y + top, body.z + body.dz * shift + r] as Vec,
    weight,
  });
  return [
    zone(1.49 - low, 1.84 - low, 0.16, combat.hit.head, 1),
    zone(0.79 - low, 1.49 - low, 0.265, combat.hit.torso, 0.55),
    zone(0, 0.79 - low, 0.18, combat.hit.legs, 0),
  ];
}
export class World {
  tick = 0;
  done = false;
  players = new Map<number, Player>();
  grenades: Grenade[] = [];
  effects: Effect[] = [];
  private sequence = 0;
  private history: { tick: number; poses: Pose[] }[] = [];
  readonly map: Arena;
  scores: [number, number] = [0, 0];
  constructor(
    map: Arena,
    readonly teamMode = false,
  ) {
    this.map = roundArena(map);
  }
  private shatter(pane: number, who: number, at: Vec) {
    if ((this.map.broken ?? 0) & pane) return;
    setBroken(this.map, (this.map.broken ?? 0) | pane);
    this.emit('glass', who, -1, at, [0, 0, 0], 0);
  }
  add(id: number, gun: number, secondary = FIRST_SECONDARY) {
    const p = spawn(this.map, id, gun, 1, secondary, this.teamMode);
    this.players.set(id, p);
    return p;
  }
  remove(id: number) {
    this.players.delete(id);
    this.grenades = this.grenades.filter((g) => g.owner !== id);
    for (const frame of this.history) frame.poses = frame.poses.filter((p) => p.id !== id);
  }
  private emit(kind: Effect['kind'], who: number, other: number, o: Vec, v: Vec, gun: number) {
    this.effects.push({ kind, id: ++this.sequence, who, other, o, v, gun });
  }
  private harm(p: Player, source: number, n: number, v: Vec, incoming: Vec = v) {
    if (p.hp <= 0 || p.protect || (this.teamMode && source !== p.id && source % 2 === p.id % 2)) return;
    p.hp = Math.max(0, p.hp - n);
    p.boost = combat.hit.speedTicks;
    this.emit('hit', source, p.id, [p.x, p.y + 0.9, p.z], incoming, p.gun);
    if (!p.hp) {
      if (p.cook) {
        this.grenades.push({
          x: p.x,
          y: p.y + 0.7,
          z: p.z,
          vx: p.vx,
          vy: 0,
          vz: p.vz,
          owner: p.id,
          fuse: p.cook,
        });
        p.cook = 0;
      }
      p.deaths++;
      p.respawn = 150;
      const killer = this.players.get(source);
      if (killer && killer !== p) {
        killer.kills++;
        if (this.teamMode) this.scores[killer.id % 2]++;
      }
      this.emit('death', source, p.id, [p.x, p.y, p.z], v, p.gun);
    }
  }
  private fire(p: Player, viewTick: number) {
    const profile = guns[p.gun],
      o = eyeOrigin(p);
    const spread = spreadFor(p),
      range = Math.ceil(this.map.size * 2 * Math.SQRT2);
    const direction = look(p.yaw, p.pitch);
    this.emit('shot', p.id, -1, o, direction, p.gun);
    if (p.gun === RPG) {
      this.grenades.push({
        x: o[0],
        y: o[1],
        z: o[2],
        vx: direction[0] * combat.rocket.speed,
        vy: direction[1] * combat.rocket.speed,
        vz: direction[2] * combat.rocket.speed,
        fuse: combat.rocket.lifetime,
        owner: p.id,
        rocket: true,
      });
      return;
    }
    const rewindTick = clamp(viewTick, this.tick - 15, this.tick);
    const poses =
      (viewTick >= 0 && this.history.find((s) => s.tick === rewindTick)?.poses) || this.poses();
    const targets = poses.flatMap((body) => {
      const target = this.players.get(body.id);
      return target && target !== p && target.hp > 0 && target.life === body.life
        ? [{ target, zones: hitZones(body) }]
        : [];
    });
    for (let pellet = 0; pellet < profile.pellets; pellet++) {
      const v = look(
        p.yaw + (Math.random() - 0.5) * spread * 2,
        p.pitch + (Math.random() - 0.5) * spread * 2,
      );
      const surfaces = shotSurfaces(this.map, o, v, range);
      type BodyHit = { distance: number; target: Player; weight: number };
      const hits: BodyHit[] = [];
      for (const { target, zones } of targets) {
        if (target.hp <= 0) continue;
        let closest = Infinity,
          weight = 0;
        for (const zone of zones) {
          const t = rayBox(o, v, zone.min, zone.max, Math.min(range, closest));
          if (t < closest) {
            closest = t;
            weight = zone.weight;
          }
        }
        if (Number.isFinite(closest)) hits.push({ distance: closest, target, weight });
      }
      const contacts = [...surfaces, ...hits].sort((a, b) => a.distance - b.distance);
      const initial = profile.penetration;
      let energy: number = initial,
        drag = 0,
        last = 0,
        bloodDistance = -Infinity;
      for (const hit of contacts) {
        energy -= (hit.distance - last) * drag;
        last = hit.distance;
        // A body can stop the pellet and still leave blood on a nearby surface.
        if (energy <= 0 && last - bloodDistance >= combat.shot.splatterRange) break;
        const at: Vec = [o[0] + v[0] * last, o[1] + v[1] * last, o[2] + v[2] * last];
        if ('target' in hit) {
          if (energy <= 0) continue;
          if (!hit.target.protect && !(this.teamMode && hit.target.id % 2 === p.id % 2)) {
            this.harm(
              hit.target,
              p.id,
              Math.max(1, Math.round((profile.damage * hit.weight * energy) / initial)),
              [v[0] * 4, 1.5 + v[1] * 3, v[2] * 4],
              v,
            );
            bloodDistance = last;
          }
          energy -= combat.shot.bodyCost;
        } else {
          if (hit.pane && energy > 0) {
            if (hit.entering) this.shatter(hit.pane, p.id, at);
            bloodDistance = -Infinity;
          } else if (energy > 0) this.emit('impact', p.id, -1, at, hit.normal, p.gun);
          if (hit.entering && last - bloodDistance < combat.shot.splatterRange) {
            this.emit('blood', p.id, -1, at, hit.normal, p.gun);
            bloodDistance = -Infinity;
          }
          if (energy <= 0 || !Number.isFinite(hit.cost)) break;
          drag = Math.max(0, drag + (hit.entering ? hit.cost : -hit.cost));
        }
      }
    }
  }
  private poses() {
    return [...this.players.values()].filter((p) => p.hp > 0).map(poseOf);
  }
  advance(inputs: Map<number, Input>) {
    if (this.done) return;
    this.tick++;
    for (const p of this.players.values()) {
      const i = inputs.get(p.id);
      if (p.hp <= 0) {
        if (--p.respawn <= 0) {
          const replacement = spawn(
            this.map,
            p.id,
            isPrimary(p.gun) ? p.gun : p.holster,
            p.life + 1,
            isSecondary(p.gun) ? p.gun : p.holster,
            this.teamMode,
          );
          this.players.set(p.id, { ...replacement, kills: p.kills, deaths: p.deaths, ack: p.ack });
        }
        if (i) p.ack = i[0];
        continue;
      }
      // During an input gap keep remote simulation clocks running without inventing an acknowledged input.
      const oldCook = p.cook,
        oldButtons = p.buttons;
      const input = i ?? idle(p);
      if (!i)
        input[5] =
          (p.buttons & (THROW | DUCK | AIM)) | (p.lean < 0 ? LEAN_LEFT : p.lean > 0 ? LEAN_RIGHT : 0);
      const action = stepPlayer(this.map, p, input);
      if (i) p.ack = i[0];
      else p.buttons |= oldButtons & FIRE;
      if (action & FIRE) this.fire(p, input[7]);
      if (action & THROW) {
        const v = look(p.yaw, Math.min(Math.PI / 2, p.pitch + 0.17));
        const hand = eyeOrigin(p);
        hand[1] -= 0.19;
        const reach = oldCook <= 1 ? 0 : Math.max(0, wallDistance(this.map, hand, v, 0.67) - 0.12);
        this.grenades.push({
          x: hand[0] + v[0] * reach,
          y: hand[1] + v[1] * reach,
          z: hand[2] + v[2] * reach,
          vx: v[0] * combat.grenade.speed,
          vy: v[1] * combat.grenade.speed + combat.grenade.lift,
          vz: v[2] * combat.grenade.speed,
          fuse: Math.max(1, oldCook),
          owner: p.id,
        });
      }
    }
    for (let k = this.grenades.length - 1; k >= 0; k--) {
      const g = this.grenades[k];
      if (g.rocket) {
        const o: Vec = [g.x, g.y, g.z],
          v: Vec = [g.vx / combat.rocket.speed, g.vy / combat.rocket.speed, g.vz / combat.rocket.speed];
        const travel = combat.rocket.speed * DT;
        let nearest = wallDistance(this.map, o, v, travel + 0.0001);
        for (const p of this.players.values()) {
          if (p.id === g.owner || p.hp <= 0) continue;
          for (const zone of hitZones(poseOf(p)))
            nearest = Math.min(nearest, rayBox(o, v, zone.min, zone.max, travel));
        }
        const d = nearest <= travel ? Math.max(0, nearest - 0.025) : travel;
        g.x += v[0] * d;
        g.y += v[1] * d;
        g.z += v[2] * d;
        if (nearest <= travel) g.fuse = 1;
      } else if (g.fuse > 1) {
        g.vy -= combat.grenade.gravity * DT;
        for (const [pos, vel] of [
          ['x', 'vx'],
          ['z', 'vz'],
          ['y', 'vy'],
        ] as const) {
          // Keep each step shorter than the projectile diameter so thin rails still bounce it.
          const distance = g[vel] * DT,
            steps = Math.max(1, Math.ceil(Math.abs(distance) / 0.15));
          for (let step = 0; step < steps; step++) {
            const next = g[pos] + distance / steps;
            const x = pos === 'x' ? next : g.x,
              y = pos === 'y' ? next : g.y,
              z = pos === 'z' ? next : g.z;
            if (
              y < groundHeight(this.map.terrain, x, z) + 0.13 ||
              blocked(this.map, x, y - 0.1, z, 0.2, 0.1)
            ) {
              g[vel] *= -combat.grenade.bounce;
              if (pos === 'y') {
                g.vx *= combat.grenade.floorGrip;
                g.vz *= combat.grenade.floorGrip;
              }
              break;
            }
            g[pos] = next;
          }
        }
      }
      if (Math.max(Math.abs(g.x), Math.abs(g.z), Math.abs(g.y)) > this.map.size + 31) g.fuse = 1;
      if (--g.fuse > 0) continue;
      this.grenades.splice(k, 1);
      const o: Vec = [g.x, g.y, g.z];
      for (const b of this.map.boxes)
        if (b.pane) {
          const at: Vec = [
            clamp(g.x, b.x - b.w / 2, b.x + b.w / 2),
            clamp(g.y, b.y, b.y + b.h),
            clamp(g.z, b.z - b.d / 2, b.z + b.d / 2),
          ];
          const d = Math.hypot(at[0] - g.x, at[1] - g.y, at[2] - g.z);
          if (
            d < combat.blast.radius &&
            (!d || wallDistance(this.map, o, at.map((x, k) => (x - o[k]) / d) as Vec, d) >= d - 0.03)
          )
            this.shatter(b.pane, g.owner, at);
        }
      this.emit('blast', g.owner, -1, o, [0, 0, 0], 0);
      for (const p of this.players.values()) {
        const dx = p.x - g.x,
          dy = p.y + 0.85 - g.y,
          dz = p.z - g.z,
          d = Math.max(0.01, Math.hypot(dx, dy, dz));
        const v: Vec = [dx / d, dy / d, dz / d];
        if (d < combat.blast.radius && wallDistance(this.map, o, v, d) >= d - 0.01)
          this.harm(
            p,
            g.owner,
            Math.max(1, Math.round(combat.blast.damage * (1 - d / combat.blast.radius))),
            [v[0] * combat.blast.impulse, combat.blast.lift + v[1] * 5, v[2] * combat.blast.impulse],
            v,
          );
      }
    }
    this.history.push({ tick: this.tick, poses: this.poses() });
    if (this.history.length > 16) this.history.shift();
    this.done =
      this.tick >= ROUND ||
      (this.teamMode
        ? this.scores.some((n) => n >= GOAL)
        : [...this.players.values()].some((p) => p.kills >= GOAL));
  }
}
// A shared 1.5-unit navigation grid keeps bots moving through the same doors as players.
export class Bots {
  private cells: number;
  private half: number;
  private walk: Uint8Array;
  private layout?: Arena['boxes'];
  private way = new Map<number, [number, number]>();
  constructor(map: Arena) {
    this.half = Math.floor((map.size - 1) / 1.5);
    this.cells = this.half * 2 + 1;
    this.walk = new Uint8Array(this.cells ** 2);
    this.refresh(map);
  }
  private refresh(map: Arena) {
    this.layout = map.boxes;
    this.way.clear();
    for (let n = 0; n < this.walk.length; n++) {
      const [x, z] = this.point(n);
      this.walk[n] = Number(!blocked(map, x, groundHeight(map.terrain, x, z), z, 1.8, 0.5));
    }
  }
  private point(n: number) {
    return [((n % this.cells) - this.half) * 1.5, (Math.floor(n / this.cells) - this.half) * 1.5];
  }
  private cell(x: number, z: number) {
    return (
      clamp(Math.round(z / 1.5) + this.half, 0, this.cells - 1) * this.cells +
      clamp(Math.round(x / 1.5) + this.half, 0, this.cells - 1)
    );
  }
  private route(start: number, goal: number): [number, number] {
    const seen = new Int16Array(this.walk.length).fill(-1),
      queue = [start];
    seen[start] = start;
    for (let i = 0; i < queue.length; i++) {
      const n = queue[i];
      if (n === goal) break;
      for (const d of [1, -1, this.cells, -this.cells]) {
        const m = n + d;
        if (!this.walk[m] || seen[m] !== -1 || Math.abs((n % this.cells) - (m % this.cells)) > 1)
          continue;
        seen[m] = n;
        queue.push(m);
      }
    }
    let n = goal;
    if (seen[n] === -1) n = start;
    while (seen[n] !== start && n !== start) n = seen[n];
    return this.point(n) as [number, number];
  }
  input(world: World, p: Player): Input {
    if (this.layout !== world.map.boxes) this.refresh(world.map);
    const target = [...world.players.values()]
      .filter((q) => q !== p && q.hp > 0 && (!world.teamMode || q.id % 2 !== p.id % 2))
      .sort((a, b) => Math.hypot(a.x - p.x, a.z - p.z) - Math.hypot(b.x - p.x, b.z - p.z))[0];
    if (!target) return idle(p);
    const dx = target.x - p.x,
      dz = target.z - p.z,
      d = Math.hypot(dx, dz),
      dy = target.y + 1.1 - p.y - eye(p);
    let yaw = Math.atan2(dx, dz),
      pitch = Math.atan2(dy, d),
      f = 0,
      s = 0,
      flags = 0;
    const visible = wallDistance(world.map, [p.x, p.y + eye(p), p.z], look(yaw, pitch), d) >= d - 0.1;
    if (visible && d < 26) {
      yaw += Math.sin(world.tick * 0.07 + p.id) * 0.06;
      pitch += Math.cos(world.tick * 0.05 + p.id) * 0.027;
      f = d > 12 ? 0.55 : 0;
      s = Math.sin(world.tick * 0.027 + p.id) * 0.4;
      if (
        world.tick > 64 &&
        (world.tick + p.id * 17) % 85 < 43 &&
        (guns[p.gun].mode === 'AUTO' || world.tick % 4 === 0)
      )
        flags |= FIRE;
    } else {
      if (!this.way.has(p.id) || (world.tick + p.id) % 10 === 0)
        this.way.set(p.id, this.route(this.cell(p.x, p.z), this.cell(target.x, target.z)));
      const [x, z] = this.way.get(p.id)!;
      yaw = Math.atan2(x - p.x, z - p.z);
      pitch = 0;
      f = 1;
    }
    if (!p.ammo) flags |= RELOAD;
    return [world.tick + 1, f, s, yaw, pitch, flags, p.life, -1];
  }
}