Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

14.6 KB
Raw Blame
// @vitest-environment node
/**
 * Adversarial tests of the simulation: hit detection (tunnelling, cover,
 * point blank, own bolts), fairness between the two slots, round flow edge
 * cases and the heat edge. Each one is a way someone could try to break or
 * cheese a duel.
 */
import { describe, expect, it } from "vitest";
import { idleControl, makeInput } from "./input";
import { yawOf } from "./math";
import { createContext, createMatch, step } from "./sim";
import { count, liveMatch, place, runner } from "./testing";
import { DEFAULT_TUNING, withTuning } from "./tuning";
import type { CombatEvent, MatchState } from "./types";

/** No spread, bloom or recoil: every bolt goes exactly where it is aimed. */
const EXACT = withTuning(DEFAULT_TUNING, {
  blaster: {
    hipSpreadDeg: 0, adsSpreadDeg: 0, moveSpreadHipDeg: 0, moveSpreadAdsDeg: 0,
    bloomPerShotHipDeg: 0, bloomPerShotAdsDeg: 0, recoilPitchHipDeg: 0, recoilPitchAdsDeg: 0, recoilYawDeg: 0,
  },
});
const ONE_SHOT = withTuning(EXACT, { blaster: { damageNear: 500, damageFar: 500 } });
/** Bolts at 300 m/s: 5 m per tick, far more than any real bolt (max 96 m/s after parries). */
const FAST = withTuning(EXACT, { blaster: { boltSpeed: 300 } });

const MUZZLE_Y = DEFAULT_TUNING.body.muzzleHeight;

/** Pitch from the muzzle to a height `y` at horizontal distance `d`. */
const pitchTo = (y: number, d: number) => Math.atan2(y - MUZZLE_Y, d);

function hits(ev: readonly CombatEvent[]) {
  return ev.filter((e): e is Extract<CombatEvent, { type: "hit" }> => e.type === "hit");
}
function impacts(ev: readonly CombatEvent[]) {
  return ev.filter((e): e is Extract<CombatEvent, { type: "impact" }> => e.type === "impact");
}

describe("hit detection", () => {
  it("fast bolts do not tunnel through bodies: a 5 m step still hits a target 0.35 m off the line and misses one 0.45 m off", () => {
    const { ctx, state } = liveMatch({ tuning: FAST });
    for (const [off, expectHit] of [[0, true], [0.35, true], [0.45, false]] as const) {
      // Shooter faces +Z; its muzzle sits 0.22 m to its right (-X).
      const shooter = { x: 38.8, z: 8, yaw: 0 };
      const mx = shooter.x - DEFAULT_TUNING.body.muzzleRight;
      const r = runner(ctx, place(state, shooter, { x: mx + off, z: 30.4, yaw: Math.PI }));
      const ev = r.run(20, { fire: true, yaw: 0, pitch: pitchTo(1.0, 22) }, { yaw: Math.PI });
      expect(hits(ev).length > 0, `offset ${off}`).toBe(expectHit);
    }
  });

  it("fast bolts do not tunnel through thin cover (wall pipes, a coolant run) and never pass the core", () => {
    const { ctx, state } = liveMatch({ tuning: FAST });
    // North at the far wall's pipe run (0.75 m deep, 0.9..2.3 m high).
    let r = runner(ctx, place(state, { x: 38.8, z: 10, yaw: Math.PI }, { x: 70, z: 34 }));
    let ev = r.run(20, { fire: true, yaw: Math.PI, pitch: 0 });
    expect(impacts(ev)[0]?.collider).toBe("wall_pipes_w");
    // East, low, at a waist-high coolant run (1.0 m) in front of a conduit.
    r = runner(ctx, place(state, { x: 66, z: 12, yaw: Math.PI / 2 }, { x: 40, z: 34 }));
    ev = r.run(20, { fire: true, yaw: Math.PI / 2, pitch: pitchTo(0.5, 6) });
    expect(impacts(ev)[0]?.collider).toBe("coolant_0");
    // Over the coolant run at chest height: on to the conduit behind it.
    r = runner(ctx, place(state, { x: 66, z: 12, yaw: Math.PI / 2 }, { x: 40, z: 34 }));
    ev = r.run(20, { fire: true, yaw: Math.PI / 2, pitch: 0 });
    expect(impacts(ev)[0]?.collider).toBe("conduit_0");
    // Across the shaft at a head behind the core: the core takes every bolt.
    const s = place(state, { x: 38.8, z: 22 }, { x: 69.2, z: 22 });
    r = runner(ctx, s);
    ev = r.run(30, { fire: true, pitch: pitchTo(1.7, 30.4) });
    expect(hits(ev)).toEqual([]);
    expect(impacts(ev).every((e) => e.collider === "core")).toBe(true);
  });

  it("a waist-high coolant run stops low bolts but not a chest shot at someone behind it", () => {
    const { ctx, state } = liveMatch({ tuning: EXACT });
    const shooter = { x: 64, z: 12, yaw: Math.PI / 2 };
    const target = { x: 77.3, z: 12, yaw: -Math.PI / 2 };
    const chest = runner(ctx, place(state, shooter, target));
    expect(hits(chest.run(30, { fire: true, yaw: Math.PI / 2, pitch: pitchTo(1.15, 13) }, { yaw: -Math.PI / 2 })).length).toBeGreaterThan(0);
    const low = runner(ctx, place(state, shooter, target));
    const ev = low.run(30, { fire: true, yaw: Math.PI / 2, pitch: pitchTo(0.45, 13) }, { yaw: -Math.PI / 2 });
    expect(hits(ev)).toEqual([]);
    expect(impacts(ev)[0]?.collider).toMatch(/^coolant_/);
  });

  it("point blank: the shield still covers the front with the muzzle inside it, but not a flank", () => {
    const { ctx, state } = liveMatch({ tuning: EXACT });
    const b = { x: 38.8, z: 20, yaw: Math.PI };
    // In front, 1 m away: the muzzle is inside the 0.8 m shield radius.
    const front = runner(ctx, place(state, { x: 38.8, z: 19, yaw: 0 }, b));
    front.run(20, {}, { shield: true, yaw: Math.PI });
    const ev = front.run(30, { fire: true, yaw: 0 }, { shield: true, yaw: Math.PI });
    // (A glancing bolt may come back at the shooter; the shield bearer is never hit.)
    expect(hits(ev).filter((h) => h.target === 1)).toEqual([]);
    expect(count(ev, "block") + count(ev, "deflect") + count(ev, "parry")).toBeGreaterThan(0);
    // From the side (90 deg off its aim): past the +-60 deg arc.
    const side = runner(ctx, place(state, { x: 37.8, z: 20, yaw: Math.PI / 2 }, b));
    side.run(20, {}, { shield: true, yaw: Math.PI });
    expect(hits(side.run(30, { fire: true, yaw: Math.PI / 2 }, { shield: true, yaw: Math.PI })).length).toBeGreaterThan(0);
  });

  it("a bolt never hits its owner: parry rallies hand it over and stop after three reflections", () => {
    const { ctx, state } = liveMatch({ tuning: EXACT });
    const A = { x: 38.8, z: 12 };
    const B = { x: 38.8, z: 32 };
    const r = runner(ctx, place(state, A, B));
    // Each side raises its shield when a bolt it does not own is about to arrive.
    const guard = (slot: number) => (s: MatchState) => {
      const me = s.players[slot];
      const o = s.players[1 - slot];
      const incoming = s.bolts.some((b) => b.owner !== slot && Math.hypot(b.x - me.x, b.z - me.z) < 5 && (b.vx * (me.x - b.x) + b.vz * (me.z - b.z)) > 0);
      return { yaw: yawOf(o.x - me.x, o.z - me.z), pitch: 0, shield: incoming };
    };
    const ev = r.run(1, { fire: true, yaw: 0 }, guard(1)).concat(r.run(200, guard(0), guard(1)));
    // Three reflections, never a fourth: the bolt then ends on a shield or a body.
    expect(count(ev, "parry")).toBe(DEFAULT_TUNING.shield.maxReflections);
    for (const h of hits(ev)) expect(h.owner).not.toBe(h.target);
    expect(r.state.bolts).toEqual([]);
  });

  it("a deflected bolt never comes back at the one who deflected it", () => {
    const { ctx, state } = liveMatch({ tuning: EXACT, seed: 4 });
    const r = runner(ctx, place(state, { x: 38.8, z: 12 }, { x: 38.8, z: 20 }));
    r.run(30, {}, { shield: true });
    // Six bolts: the shield holds (it would break on the seventh).
    const ev = r.run(70, { fire: true }, { shield: true });
    expect(count(ev, "deflect", 1)).toBeGreaterThan(0);
    for (const h of hits(ev)) expect(h.target).toBe(0);
  });
});

describe("fairness between the slots", () => {
  it("a lag-compensated shot never stops the other player's shot of the same tick: point-blank one-shots trade", () => {
    const { ctx, state } = liveMatch({ tuning: ONE_SHOT });
    let s = place(state, { x: 38.8, z: 14 }, { x: 38.8, z: 20 });
    for (let i = 0; i < 12; i++) s = step(s, [makeInput(i, idleControl(0, 0)), makeInput(i, idleControl(Math.PI, 0))], ctx).state;
    const vt = s.tick - 10;
    const res = step(s, [makeInput(20, { ...idleControl(0, 0), fire: true }, vt), makeInput(20, { ...idleControl(Math.PI, 0), fire: true }, vt)], ctx);
    expect(count(res.events, "shot")).toBe(2);
    expect(res.events.filter((e) => e.type === "death").map((e) => (e as { player: number }).player).sort()).toEqual([0, 1]);
    // Swapping who is slot 0 gives the mirror result.
    expect(res.state.players.every((p) => !p.alive)).toBe(true);
  });

  it("mirror-image duels play out as mirror images (no hidden slot order)", () => {
    const { ctx, state } = liveMatch({ tuning: EXACT });
    const run = (swap: boolean) => {
      const a = { x: 38.8, z: 12 };
      const b = { x: 38.8, z: 28 };
      const r = runner(ctx, swap ? place(state, b, a) : place(state, a, b));
      const shooter = swap ? 1 : 0;
      // The shooter stands at `a` facing +Z in both runs; only its slot differs.
      const ctl = (s: MatchState) => ({ fire: s.tick % 30 < 12, yaw: 0 });
      r.run(240, swap ? undefined : ctl, swap ? ctl : undefined);
      return { damage: r.state.players[1 - shooter].stats.damageTaken, shots: r.state.players[shooter].stats.shots };
    };
    // Spread is seeded per slot, so only exact (spread-free) shots must match.
    const a = run(false);
    expect(a.damage).toBeGreaterThan(40);
    expect(run(true)).toEqual(a);
  });
});

describe("round flow edge cases", () => {
  const live = (r: ReturnType<typeof runner>) => {
    for (let i = 0; i < 2000 && r.state.phase !== "live"; i++) r.run(1);
  };

  it("a double knock-out scores nobody, and five of them end the match as a draw", () => {
    const { ctx, state } = liveMatch({ tuning: ONE_SHOT });
    const r = runner(ctx, state);
    const ends: Extract<CombatEvent, { type: "round_end" }>[] = [];
    for (let round = 1; round <= 5; round++) {
      live(r);
      r.state = place(r.state, { x: 38.8, z: 12 }, { x: 38.8, z: 28 });
      const ev = r.run(30, { fire: true }, { fire: true });
      ends.push(...ev.filter((e): e is Extract<CombatEvent, { type: "round_end" }> => e.type === "round_end"));
    }
    expect(ends.map((e) => e.reason)).toEqual(["trade", "trade", "trade", "trade", "trade"]);
    expect(r.state.scores).toEqual([0, 0]);
    expect(r.state.phase).toBe("ended");
    expect(r.state.winner).toBe(-1);
    expect(r.state.endReason).toBe("draw");
  });

  it("time running out with equal health is a drawn round, not a win for slot 0", () => {
    const { ctx, state } = liveMatch({ config: { roundTimeLimitTicks: 120 } });
    const r = runner(ctx, state);
    const ev = r.run(130);
    const end = ev.find((e) => e.type === "round_end") as Extract<CombatEvent, { type: "round_end" }>;
    expect(end.reason).toBe("time");
    expect(end.winner).toBe(-1);
    expect(r.state.scores).toEqual([0, 0]);
  });

  it("the dead cannot shoot, roll, raise a shield or move until the next round", () => {
    const { ctx, state } = liveMatch({ tuning: ONE_SHOT });
    const r = runner(ctx, place(state, { x: 38.8, z: 12 }, { x: 38.8, z: 28 }));
    r.run(30, { fire: true });
    expect(r.state.players[1].alive).toBe(false);
    const at = { x: r.state.players[1].x, z: r.state.players[1].z };
    const ev = r.run(60, {}, (s) => ({ fire: true, moveY: 1, shield: s.tick % 2 === 0, dodge: s.tick % 2 === 0, vent: true }));
    expect(ev.filter((e) => "player" in e && e.player === 1 && e.type !== "ping")).toEqual([]);
    expect({ x: r.state.players[1].x, z: r.state.players[1].z }).toEqual(at);
  });

  it("a shield held through the round change needs a fresh press, and presses in the countdown do nothing", () => {
    const { ctx, state } = liveMatch({ tuning: ONE_SHOT });
    const r = runner(ctx, place(state, { x: 38.8, z: 12 }, { x: 38.8, z: 28 }));
    r.run(30, { fire: true });
    expect(r.state.phase).toBe("round_end");
    // Slot 0 holds the shield and mashes fire, roll and vent through the pause and the countdown.
    const ev: CombatEvent[] = [];
    const mash = (s: MatchState) => ({ shield: true, dodge: s.tick % 3 === 0, vent: s.tick % 3 === 1, fire: true });
    for (let i = 0; i < 1000 && r.state.phase !== "live"; i++) ev.push(...r.run(1, mash));
    expect(count(ev, "dodge") + count(ev, "vent_start") + count(ev, "shot") + count(ev, "shield_up")).toBe(0);
    expect(r.state.phase).toBe("live");
    r.run(5, { shield: true });
    expect(r.state.players[0].shieldUp).toBe(false);
    r.run(1);
    r.run(2, { shield: true });
    expect(r.state.players[0].shieldUp).toBe(true);
  });

  it("a forfeit works in the countdown and in the pause between rounds", () => {
    const ctx = createContext();
    const counting = runner(ctx, createMatch(ctx, { seed: 2, playerIds: ["a", "b"] }));
    expect(counting.state.phase).toBe("countdown");
    const e1 = counting.run(1, {}, { forfeit: true }).find((e) => e.type === "match_end") as Extract<CombatEvent, { type: "match_end" }>;
    expect(e1.winner).toBe(0);
    const { ctx: oneCtx, state } = liveMatch({ tuning: ONE_SHOT });
    const one = runner(oneCtx, place(state, { x: 38.8, z: 12 }, { x: 38.8, z: 28 }));
    one.run(30, { fire: true });
    expect(one.state.phase).toBe("round_end");
    const e2 = one.run(1, { forfeit: true }).find((e) => e.type === "match_end") as Extract<CombatEvent, { type: "match_end" }>;
    expect(e2.winner).toBe(1);
    expect(e2.reason).toBe("forfeit");
  });
});

describe("the heat edge", () => {
  it("eleven bolts and a timed vent, again and again, never overheat; the twelfth always does", () => {
    const { ctx, state } = liveMatch({ tuning: EXACT });
    const r = runner(ctx, place(state, { x: 38.8, z: 12 }, { x: 70, z: 30 }));
    let overheats = 0;
    let shots = 0;
    for (let cycle = 0; cycle < 4; cycle++) {
      // Eleven bolts at the far wall.
      for (let i = 0; i < 11 * 12 && r.state.players[0].shotCount < shots + 11; i++) {
        const ev = r.run(1, { fire: true, yaw: Math.PI });
        overheats += count(ev, "overheat");
      }
      shots += 11;
      r.run(1);
      expect(r.state.players[0].heat).toBeGreaterThan(90);
      r.run(1, { vent: true });
      const p = r.state.players[0];
      expect(p.ventStart).toBeGreaterThanOrEqual(0);
      r.run(Math.max(0, p.ventWinStart + 1 - r.state.tick));
      expect(count(r.run(1, { vent: true }), "vent_perfect")).toBe(1);
      expect(r.state.players[0].heat).toBe(0);
    }
    expect(overheats).toBe(0);
    const ev = r.run(12 * 12, { fire: true, yaw: Math.PI });
    expect(count(ev, "overheat")).toBe(1);
  });

  it("holding the vent key does not start vent after vent, and spamming it spends the one timing try", () => {
    const { ctx, state } = liveMatch({ tuning: EXACT });
    const r = runner(ctx, place(state, { x: 38.8, z: 12 }, { x: 70, z: 30 }));
    r.run(6 * 12, { fire: true, yaw: Math.PI });
    const ev = r.run(200, { vent: true });
    expect(count(ev, "vent_start")).toBe(1);
    const spam = runner(ctx, place(state, { x: 38.8, z: 12 }, { x: 70, z: 30 }));
    spam.run(6 * 12, { fire: true, yaw: Math.PI });
    const ev2 = spam.run(200, (s) => ({ vent: s.tick % 2 === 0 }));
    expect(count(ev2, "vent_perfect")).toBe(0);
    expect(count(ev2, "vent_miss")).toBeGreaterThanOrEqual(1);
  });
});