diff --git a/crates/sim/src/fixed.rs b/crates/sim/src/fixed.rs new file mode 100644 index 0000000..a072396 --- /dev/null +++ b/crates/sim/src/fixed.rs @@ -0,0 +1,168 @@ +//! Q16.16 fixed-point arithmetic. +//! +//! Floating point is forbidden in the simulation (see ADR 0002): results must be +//! bit-identical on arm64, x86_64 and wasm. All rounding is floor via `>> 16`. + +use crate::trig_table; + +/// Fixed-point number with 16 fractional bits. +pub type Fx = i32; + +/// Number of fractional bits. +pub const FRAC_BITS: u32 = 16; + +/// 1.0 in Q16.16. +pub const ONE: Fx = 1 << FRAC_BITS; + +/// 0.5 in Q16.16. +pub const HALF: Fx = ONE / 2; + +/// Converts an integer to Q16.16. +#[inline] +pub const fn from_int(v: i32) -> Fx { + v << FRAC_BITS +} + +/// Converts to integer, rounding towards negative infinity. +#[inline] +pub const fn to_int(v: Fx) -> i32 { + v >> FRAC_BITS +} + +/// Builds `n / d` in Q16.16. +#[inline] +pub const fn from_ratio(n: i32, d: i32) -> Fx { + (((n as i64) << FRAC_BITS) / d as i64) as Fx +} + +/// Fixed-point multiplication. +#[inline] +pub fn mul(a: Fx, b: Fx) -> Fx { + (((a as i64) * (b as i64)) >> FRAC_BITS) as Fx +} + +/// Fixed-point division. +#[inline] +pub fn div(a: Fx, b: Fx) -> Fx { + (((a as i64) << FRAC_BITS) / b as i64) as Fx +} + +/// Absolute value. +#[inline] +pub fn abs(v: Fx) -> Fx { + if v < 0 { + -v + } else { + v + } +} + +/// Clamps to the given inclusive range. +#[inline] +pub fn clamp(v: Fx, lo: Fx, hi: Fx) -> Fx { + if v < lo { + lo + } else if v > hi { + hi + } else { + v + } +} + +/// Integer square root (Newton), deterministic for identical inputs. +#[inline] +pub fn isqrt_u64(n: u64) -> u64 { + if n == 0 { + return 0; + } + let mut x = n; + let mut y = x.div_ceil(2); + while y < x { + x = y; + y = (x + n / x) / 2; + } + x +} + +/// Square root of a Q16.16 value (negative inputs yield 0). +#[inline] +pub fn sqrt(v: Fx) -> Fx { + if v <= 0 { + return 0; + } + isqrt_u64((v as u64) << FRAC_BITS) as Fx +} + +/// Euclidean distance of a Q16.16 vector. +pub fn dist(dx: Fx, dy: Fx) -> Fx { + let dx = dx as i64; + let dy = dy as i64; + let sum = ((dx * dx + dy * dy) >> FRAC_BITS).max(0) as u64; + isqrt_u64(sum << FRAC_BITS) as Fx +} + +/// Sine for an angle in millidegrees (1/1000 deg), Q16.16 rounded down. +pub fn sin(mdeg: u32) -> Fx { + let a = mdeg % 360_000; + let (part, sign) = if a <= 90_000 { + (a, 1) + } else if a <= 180_000 { + (180_000 - a, 1) + } else if a <= 270_000 { + (a - 180_000, -1) + } else { + (360_000 - a, -1) + }; + let idx = (part as u64 * trig_table::QUARTER as u64) / 90_000; + let idx = idx.min(trig_table::QUARTER as u64) as usize; + trig_table::SIN_Q16[idx] * sign +} + +/// Cosine for an angle in millidegrees. +pub fn cos(mdeg: u32) -> Fx { + let a = (mdeg + 90_000) % 360_000; + sin(a) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn int_roundtrip() { + assert_eq!(to_int(from_int(7)), 7); + assert_eq!(to_int(from_int(-3)), -3); + assert_eq!(from_int(1), ONE); + } + + #[test] + fn mul_div_are_exact_for_simple_values() { + assert_eq!(mul(from_int(3), from_int(4)), from_int(12)); + assert_eq!(div(from_int(3), from_int(4)), from_ratio(3, 4)); + assert_eq!(mul(ONE, HALF), HALF); + } + + #[test] + fn sqrt_of_four_is_two() { + assert_eq!(sqrt(from_int(4)), from_int(2)); + let r = sqrt(from_int(2)); + assert!(r > 92_600 && r < 92_800, "r={r}"); + } + + #[test] + fn trig_hits_cardinal_points() { + assert_eq!(sin(0), 0); + assert_eq!(sin(90_000), 65_535); + assert_eq!(sin(180_000), 0); + assert_eq!(sin(270_000), -65_535); + assert_eq!(cos(0), sin(90_000)); + let s30 = sin(30_000); + assert!((32_667..=32_867).contains(&s30), "s30={s30}"); + } + + #[test] + fn pythagoras() { + assert_eq!(dist(from_int(3), from_int(4)), from_int(5)); + assert_eq!(dist(0, 0), 0); + } +} diff --git a/crates/sim/src/hash.rs b/crates/sim/src/hash.rs new file mode 100644 index 0000000..0b43643 --- /dev/null +++ b/crates/sim/src/hash.rs @@ -0,0 +1,85 @@ +//! FNV-1a based state hash chain (see ADR 0002). + +const OFFSET: u64 = 0xcbf2_9ce4_8422_2325; +const PRIME: u64 = 0x0000_0100_0000_01b3; + +/// Streaming FNV-1a hasher. +#[derive(Clone, Debug)] +pub struct Hasher { + state: u64, +} + +impl Default for Hasher { + fn default() -> Self { + Self::new() + } +} + +impl Hasher { + /// Creates a hasher with the FNV offset basis. + pub fn new() -> Self { + Self { state: OFFSET } + } + + /// Feeds one byte. + pub fn byte(&mut self, b: u8) { + self.state ^= b as u64; + self.state = self.state.wrapping_mul(PRIME); + } + + /// Feeds a little endian u32. + pub fn u32(&mut self, v: u32) { + for i in 0..4 { + self.byte((v >> (8 * i)) as u8); + } + } + + /// Feeds a little endian i32. + pub fn i32(&mut self, v: i32) { + self.u32(v as u32); + } + + /// Feeds a little endian u64. + pub fn u64(&mut self, v: u64) { + for i in 0..8 { + self.byte((v >> (8 * i)) as u8); + } + } + + /// Current hash value. + pub fn finish(&self) -> u64 { + self.state + } +} + +/// Convenience helper for hashing a byte slice. +pub fn fnv1a(bytes: &[u8]) -> u64 { + let mut h = Hasher::new(); + for b in bytes { + h.byte(*b); + } + h.finish() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn known_fnv_vector() { + assert_eq!(fnv1a(b""), 0xcbf2_9ce4_8422_2325); + assert_eq!(fnv1a(b"a"), 0xaf63_dc4c_8601_ec8c); + assert_eq!(fnv1a(b"foobar"), 0x8594_4171_f739_67e8); + } + + #[test] + fn order_matters() { + let mut a = Hasher::new(); + a.u32(1); + a.u32(2); + let mut b = Hasher::new(); + b.u32(2); + b.u32(1); + assert_ne!(a.finish(), b.finish()); + } +} diff --git a/crates/sim/src/lib.rs b/crates/sim/src/lib.rs index 204adcf..e422c7b 100644 --- a/crates/sim/src/lib.rs +++ b/crates/sim/src/lib.rs @@ -8,10 +8,17 @@ #![cfg_attr(not(test), no_std)] #![forbid(unsafe_code)] #![deny(clippy::float_arithmetic)] - -#[cfg(not(test))] +// `alloc` is available in std builds as well, so the core can use Vec/SmallVec. extern crate alloc; +pub mod fixed; +pub mod hash; +pub mod rng; +pub mod state; +pub mod terrain; +pub mod trig_table; +pub mod weapons; + /// Version of the simulation. Bumped on any formula/balance change. pub const SIM_VERSION: &str = "0.1.0"; diff --git a/crates/sim/src/rng.rs b/crates/sim/src/rng.rs new file mode 100644 index 0000000..e9e6162 --- /dev/null +++ b/crates/sim/src/rng.rs @@ -0,0 +1,117 @@ +//! Deterministic pseudo random number generator (PCG32). +//! +//! Own implementation on purpose: a dependency update must never change the +//! random sequence of an already recorded replay (ADR 0002). + +use crate::fixed::{Fx, ONE}; + +/// PCG32 generator (XSH-RR variant). +#[derive(Clone, Debug)] +pub struct Pcg32 { + state: u64, + inc: u64, +} + +impl Pcg32 { + /// Creates a generator from a match seed and a stream id. + pub fn new(seed: u64, stream: u64) -> Self { + let mut rng = Self { + state: 0, + inc: (stream << 1) | 1, + }; + let _ = rng.next_u32(); + rng.state = rng.state.wrapping_add(seed); + let _ = rng.next_u32(); + rng + } + + /// Next 32 bit value. + pub fn next_u32(&mut self) -> u32 { + let old = self.state; + self.state = old + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(self.inc); + let xorshifted = (((old >> 18) ^ old) >> 27) as u32; + let rot = (old >> 59) as u32; + xorshifted.rotate_right(rot) + } + + /// Next 64 bit value. + pub fn next_u64(&mut self) -> u64 { + let hi = self.next_u32() as u64; + let lo = self.next_u32() as u64; + (hi << 32) | lo + } + + /// Uniform value in `[0, n)`; panics if `n == 0`. + pub fn below(&mut self, n: u32) -> u32 { + ((self.next_u32() as u64 * n as u64) >> 32) as u32 + } + + /// Uniform value in `[0, 1.0)` as Q16.16. + pub fn next_fx(&mut self) -> Fx { + self.below(ONE as u32) as Fx + } + + /// Uniform value in `[-1.0, 1.0)` as Q16.16. + pub fn next_fx_signed(&mut self) -> Fx { + self.below(ONE as u32 * 2) as Fx - ONE + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn same_seed_yields_same_sequence() { + let mut a = Pcg32::new(42, 0); + let mut b = Pcg32::new(42, 0); + for _ in 0..1000 { + assert_eq!(a.next_u32(), b.next_u32()); + } + } + + #[test] + fn different_stream_yields_different_sequence() { + let mut a = Pcg32::new(42, 0); + let mut b = Pcg32::new(42, 1); + let same = (0..32).filter(|_| a.next_u32() == b.next_u32()).count(); + assert!(same < 3, "sequences are too similar ({same}) "); + } + + #[test] + fn below_stays_in_range() { + let mut rng = Pcg32::new(7, 3); + for _ in 0..10_000 { + assert!(rng.below(6) < 6); + } + } + + #[test] + fn fixed_ranges_are_respected() { + let mut rng = Pcg32::new(9, 2); + for _ in 0..10_000 { + let u = rng.next_fx(); + assert!((0..ONE).contains(&u)); + let s = rng.next_fx_signed(); + assert!((-ONE..ONE).contains(&s)); + } + } + + #[test] + fn sequence_is_stable_across_runs() { + // Guards against accidental algorithm changes: the first values are pinned. + let mut rng = Pcg32::new(12345, 0); + let first: [u32; 4] = [ + rng.next_u32(), + rng.next_u32(), + rng.next_u32(), + rng.next_u32(), + ]; + assert_eq!(first, REFERENCE_SEQUENCE); + } + + /// Filled in on first run, then pinned as a regression guard. + const REFERENCE_SEQUENCE: [u32; 4] = [304133009, 2564000426, 1539170214, 2267019874]; +} diff --git a/crates/sim/src/state.rs b/crates/sim/src/state.rs new file mode 100644 index 0000000..b00e313 --- /dev/null +++ b/crates/sim/src/state.rs @@ -0,0 +1,629 @@ +//! Match simulation: tanks, turns, projectiles, damage. + +use alloc::vec::Vec; + +use crate::fixed::{self, from_int, from_ratio, mul, to_int, Fx}; +use crate::hash::Hasher; +use crate::rng::Pcg32; +use crate::terrain::{Terrain, WORLD_H, WORLD_W}; +use crate::weapons; +use crate::TICK_HZ; + +/// Maximum hit points per tank. +pub const MAX_HP: i32 = 100; +/// Ticks per turn (25 s). +pub const TURN_TICKS: u32 = 25 * TICK_HZ; +/// Hard match limit in turns. +pub const MAX_TURNS: u16 = 30; +/// Turn at which lava starts rising. +pub const LAVA_TURN: u16 = 12; +/// Turn at which damage is doubled. +pub const SUDDEN_DEATH_TURN: u16 = 20; +/// Gravity in px/tick^2. +pub const GRAVITY: Fx = from_ratio(2, 10); +/// Wind acceleration per wind unit in px/tick^2. +pub const WIND_SCALE: Fx = from_ratio(2, 100); +/// Muzzle offset above the tank in px. +pub const MUZZLE_LEN: i32 = 16; +/// Shield duration in ticks (2 turns). +pub const SHIELD_TICKS: u8 = 120; + +/// A player action. Units: millidegrees, Q16.16 power. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Command { + /// Fire a weapon. + Fire { + angle_mdeg: u32, + power: Fx, + weapon: u8, + }, + /// Raise the shield (costs one turn). + Shield, + /// Give up the turn. + EndTurn, +} + +/// Match phase. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Phase { + Aiming, + Flying, + Finished, +} + +/// Why a command was rejected. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SimError { + NotAiming, + Finished, + BadAngle, + BadPower, + UnknownWeapon, + WeaponNotInLoadout, + NoAmmo, + NoShieldAvailable, +} + +/// Things that happened during a tick (drives VFX/SFX on the client). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Event { + Fired { + player: u8, + weapon: u8, + }, + ShieldUp { + player: u8, + }, + Impact { + x: Fx, + y: Fx, + damage: [i32; 2], + dug: bool, + }, + TurnEnded { + next: u8, + turn: u16, + }, + WindChanged { + wind: i32, + }, + LavaRose { + y: i32, + }, + GameOver { + winner: Option, + }, +} + +/// Initial placement of a tank. +#[derive(Clone, Copy, Debug)] +pub struct TankSpec { + pub x: i32, + pub loadout: [u8; 3], +} + +/// Mutable tank state. +#[derive(Clone, Copy, Debug)] +pub struct Tank { + pub x: Fx, + pub y: Fx, + pub hp: i32, + pub shield_ticks: u8, + pub loadout: [u8; 3], + pub ammo: [u8; 3], +} + +impl Tank { + fn new(spec: TankSpec, terrain: &Terrain) -> Self { + let x = from_int(spec.x); + let mut ammo = [0u8; 3]; + for (i, id) in spec.loadout.iter().enumerate() { + ammo[i] = weapons::get(*id).map(|w| w.ammo).unwrap_or(0); + } + Self { + x, + y: terrain.surface_y(x), + hp: MAX_HP, + shield_ticks: 0, + loadout: spec.loadout, + ammo, + } + } + + fn slot_of(&self, weapon: u8) -> Option { + self.loadout.iter().position(|w| *w == weapon) + } + + fn is_alive(&self) -> bool { + self.hp > 0 + } +} + +/// A projectile in flight. +#[derive(Clone, Copy, Debug)] +pub struct Projectile { + pub x: Fx, + pub y: Fx, + pub vx: Fx, + pub vy: Fx, + pub weapon: u8, + pub owner: u8, +} + +/// The whole match state. Everything here is part of the state hash. +pub struct Sim { + pub terrain: Terrain, + pub tanks: [Tank; 2], + pub projectile: Option, + /// Wind in units -8..=8. + pub wind: i32, + pub tick: u32, + pub turn: u16, + pub phase: Phase, + pub current: u8, + pub turn_ticks_left: u32, + pub winner: Option, + pub lava_y: i32, + pub seed: u64, + rng: Pcg32, + log: Vec<(u32, Command)>, + pending_end: bool, +} + +impl Sim { + /// Creates a match. Player 0 starts left, player 1 right. + pub fn new(seed: u64, specs: [TankSpec; 2]) -> Self { + let mut terrain = Terrain::generate(seed); + terrain.flatten_under(from_int(specs[0].x), 48); + terrain.flatten_under(from_int(specs[1].x), 48); + let tanks = [Tank::new(specs[0], &terrain), Tank::new(specs[1], &terrain)]; + let mut rng = Pcg32::new(seed, 11); + let wind = (rng.below(17) as i32) - 8; + Self { + terrain, + tanks, + projectile: None, + wind, + tick: 0, + turn: 1, + phase: Phase::Aiming, + current: 0, + turn_ticks_left: TURN_TICKS, + winner: None, + lava_y: WORLD_H + 200, + seed, + rng, + log: Vec::new(), + pending_end: false, + } + } + + /// Convenience constructor with default spawn positions. + pub fn default_match(seed: u64) -> Self { + Self::new( + seed, + [ + TankSpec { + x: 220, + loadout: [1, 2, 5], + }, + TankSpec { + x: WORLD_W - 220, + loadout: [1, 3, 4], + }, + ], + ) + } + + /// Currently acting player. + pub fn current_player(&self) -> u8 { + self.current + } + + /// Number of commands recorded so far (replay length). + pub fn command_count(&self) -> usize { + self.log.len() + } + + /// Recorded commands with the tick they were submitted at. + pub fn recorded_commands(&self) -> &[(u32, Command)] { + &self.log + } + + /// Records and validates a player command. + pub fn submit(&mut self, cmd: Command) -> Result<(), SimError> { + if self.phase == Phase::Finished { + return Err(SimError::Finished); + } + if self.phase != Phase::Aiming { + return Err(SimError::NotAiming); + } + + match cmd { + Command::Fire { + angle_mdeg, + power, + weapon, + } => { + if angle_mdeg >= 360_000 { + return Err(SimError::BadAngle); + } + if power < from_ratio(5, 100) || power > from_int(1) { + return Err(SimError::BadPower); + } + let w = weapons::get(weapon).ok_or(SimError::UnknownWeapon)?; + let slot = self.tanks[self.current as usize] + .slot_of(weapon) + .ok_or(SimError::WeaponNotInLoadout)?; + if self.tanks[self.current as usize].ammo[slot] == 0 { + return Err(SimError::NoAmmo); + } + self.tanks[self.current as usize].ammo[slot] -= 1; + + let speed = mul(from_int(w.speed), power); + let dir = if self.current == 0 { 1 } else { -1 }; + let tank = self.tanks[self.current as usize]; + self.projectile = Some(Projectile { + x: tank.x, + y: tank.y - from_int(MUZZLE_LEN), + vx: mul(speed, fixed::cos(angle_mdeg)) * dir, + vy: -mul(speed, fixed::sin(angle_mdeg)), + weapon, + owner: self.current, + }); + self.phase = Phase::Flying; + self.log.push((self.tick, cmd)); + Ok(()) + } + Command::Shield => { + let tank = &mut self.tanks[self.current as usize]; + let slot = tank.slot_of(5).ok_or(SimError::NoShieldAvailable)?; + if tank.ammo[slot] == 0 { + return Err(SimError::NoAmmo); + } + tank.ammo[slot] -= 1; + tank.shield_ticks = SHIELD_TICKS; + self.pending_end = true; + self.log.push((self.tick, cmd)); + Ok(()) + } + Command::EndTurn => { + self.pending_end = true; + self.log.push((self.tick, cmd)); + Ok(()) + } + } + } +} + +impl Sim { + /// Advances the simulation by exactly one tick and returns pending events. + pub fn tick(&mut self) -> Vec { + let mut events = Vec::new(); + if self.phase == Phase::Finished { + return events; + } + self.tick += 1; + + for tank in &mut self.tanks { + if tank.shield_ticks > 0 { + tank.shield_ticks -= 1; + } + } + + match self.phase { + Phase::Aiming => { + if self.pending_end { + self.pending_end = false; + self.end_turn(&mut events); + } else { + self.turn_ticks_left = self.turn_ticks_left.saturating_sub(1); + if self.turn_ticks_left == 0 { + self.end_turn(&mut events); + } + } + } + Phase::Flying => { + let mut hit: Option<(Fx, Fx)> = None; + if let Some(p) = self.projectile.as_mut() { + p.vy += GRAVITY; + p.vx += mul(from_int(self.wind), WIND_SCALE); + p.x += p.vx; + p.y += p.vy; + let in_world_x = p.x >= 0 && p.x <= from_int(WORLD_W); + let in_world_y = p.y <= from_int(WORLD_H); + if !in_world_x || !in_world_y || self.terrain.is_solid(p.x, p.y) { + hit = Some((p.x, p.y)); + } + } + if let Some((x, y)) = hit { + let projectile = self.projectile.take().expect("projectile present"); + self.resolve_impact(x, y, &projectile, &mut events); + } + } + Phase::Finished => {} + } + + events + } + + fn resolve_impact(&mut self, x: Fx, y: Fx, p: &Projectile, events: &mut Vec) { + let Some(w) = weapons::get(p.weapon) else { + self.end_turn(events); + return; + }; + let radius = from_int(w.radius_px.max(1)); + self.terrain.carve_circle(x, y, radius); + self.terrain.collapse(); + + let mut damage = [0i32; 2]; + if w.damage > 0 { + let multiplier: i64 = if self.turn >= SUDDEN_DEATH_TURN { 2 } else { 1 }; + for (i, tank) in self.tanks.iter_mut().enumerate() { + let d = fixed::dist(tank.x - x, tank.y - y); + if d >= radius { + continue; + } + let falloff = from_int(1) - fixed::div(d, radius); + let mut dmg = ((w.damage as i64) * (falloff as i64)) >> 16; + dmg *= multiplier; + if tank.shield_ticks > 0 { + dmg /= 2; + } + let dealt = dmg.clamp(0, MAX_HP as i64) as i32; + tank.hp = (tank.hp - dealt).max(0); + damage[i] = dealt; + } + } + + events.push(Event::Impact { + x, + y, + damage, + dug: w.digs, + }); + + let alive0 = self.tanks[0].is_alive(); + let alive1 = self.tanks[1].is_alive(); + if !alive0 || !alive1 { + self.winner = match (alive0, alive1) { + (true, false) => Some(0), + (false, true) => Some(1), + _ => None, + }; + self.phase = Phase::Finished; + events.push(Event::GameOver { + winner: self.winner, + }); + return; + } + + self.end_turn(events); + } + + fn end_turn(&mut self, events: &mut Vec) { + self.projectile = None; + self.phase = Phase::Aiming; + self.pending_end = false; + self.turn += 1; + self.current = 1 - self.current; + self.turn_ticks_left = TURN_TICKS; + + if self.turn > MAX_TURNS { + let (h0, h1) = (self.tanks[0].hp, self.tanks[1].hp); + self.winner = if h0 > h1 { + Some(0) + } else if h1 > h0 { + Some(1) + } else { + None + }; + self.phase = Phase::Finished; + events.push(Event::GameOver { + winner: self.winner, + }); + return; + } + + if self.turn % 5 == 0 { + self.wind = (self.rng.below(17) as i32) - 8; + events.push(Event::WindChanged { wind: self.wind }); + } + + if self.turn >= LAVA_TURN { + self.lava_y -= 20; + for i in 0..2 { + if to_int(self.tanks[i].y) >= self.lava_y { + self.tanks[i].hp = (self.tanks[i].hp - 15).max(0); + } + } + events.push(Event::LavaRose { y: self.lava_y }); + } + + events.push(Event::TurnEnded { + next: self.current, + turn: self.turn, + }); + } + + /// FNV-1a hash over the complete state (replay proof). + pub fn state_hash(&self) -> u64 { + let mut h = Hasher::new(); + h.u32(self.tick); + h.u32(self.turn as u32); + h.byte(self.current); + h.byte(match self.phase { + Phase::Aiming => 0, + Phase::Flying => 1, + Phase::Finished => 2, + }); + h.i32(self.wind); + h.i32(self.lava_y); + for tank in &self.tanks { + h.i32(tank.x); + h.i32(tank.y); + h.i32(tank.hp); + h.byte(tank.shield_ticks); + for a in tank.ammo { + h.byte(a); + } + } + match &self.projectile { + Some(p) => { + h.i32(1); + h.i32(p.x); + h.i32(p.y); + h.i32(p.vx); + h.i32(p.vy); + h.byte(p.weapon); + } + None => h.i32(0), + } + let mut tmp = h; + self.terrain.feed_hash(|b| tmp.byte(b)); + tmp.finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fire_45(sim: &mut Sim, weapon: u8) -> Result<(), SimError> { + sim.submit(Command::Fire { + angle_mdeg: 45_000, + power: from_int(1), + weapon, + }) + } + + fn run(sim: &mut Sim, ticks: u32) -> Vec { + let mut all = Vec::new(); + for _ in 0..ticks { + all.extend(sim.tick()); + } + all + } + + #[test] + fn fresh_match_is_aiming_for_player_zero() { + let sim = Sim::default_match(1); + assert_eq!(sim.phase, Phase::Aiming); + assert_eq!(sim.current_player(), 0); + assert_eq!(sim.tanks[0].hp, MAX_HP); + assert!(sim.tanks[0].y > 0); + } + + #[test] + fn firing_consumes_ammo_and_enters_flight() { + let mut sim = Sim::default_match(2); + fire_45(&mut sim, 1).unwrap(); + assert_eq!(sim.phase, Phase::Flying); + assert_eq!(sim.tanks[0].ammo[0], 254); + assert!(sim.projectile.is_some()); + assert_eq!(sim.command_count(), 1); + } + + #[test] + fn rejects_invalid_commands() { + let mut sim = Sim::default_match(3); + assert_eq!( + sim.submit(Command::Fire { + angle_mdeg: 45_000, + power: 0, + weapon: 1 + }), + Err(SimError::BadPower) + ); + assert_eq!( + sim.submit(Command::Fire { + angle_mdeg: 400_000, + power: from_int(1), + weapon: 1 + }), + Err(SimError::BadAngle) + ); + assert_eq!( + sim.submit(Command::Fire { + angle_mdeg: 45_000, + power: from_int(1), + weapon: 6 + }), + Err(SimError::WeaponNotInLoadout) + ); + assert_eq!( + sim.submit(Command::Fire { + angle_mdeg: 45_000, + power: from_int(1), + weapon: 99 + }), + Err(SimError::UnknownWeapon) + ); + } + + #[test] + fn shot_impacts_and_hands_over_the_turn() { + let mut sim = Sim::default_match(4); + fire_45(&mut sim, 1).unwrap(); + let events = run(&mut sim, 600); + assert!( + events.iter().any(|e| matches!(e, Event::Impact { .. })), + "no impact event" + ); + assert!( + events.iter().any(|e| matches!(e, Event::TurnEnded { .. })), + "no turn end" + ); + assert_eq!(sim.phase, Phase::Aiming); + assert_eq!(sim.current_player(), 1); + assert_eq!(sim.turn, 2); + } + + #[test] + fn same_commands_produce_same_hash() { + let mut a = Sim::default_match(77); + let mut b = Sim::default_match(77); + for sim in [&mut a, &mut b] { + fire_45(sim, 1).unwrap(); + } + run(&mut a, 300); + run(&mut b, 300); + assert_eq!(a.state_hash(), b.state_hash()); + } + + #[test] + fn different_seeds_produce_different_hash() { + let a = Sim::default_match(1); + let b = Sim::default_match(2); + assert_ne!(a.state_hash(), b.state_hash()); + } + + #[test] + fn turn_timer_switches_player() { + let mut sim = Sim::default_match(5); + let events = run(&mut sim, TURN_TICKS); + assert!(events.iter().any(|e| matches!(e, Event::TurnEnded { .. }))); + assert_eq!(sim.current_player(), 1); + } + + #[test] + fn shield_costs_a_turn_and_decays() { + let mut sim = Sim::default_match(6); + sim.submit(Command::Shield).unwrap(); + assert_eq!(sim.tanks[0].shield_ticks, SHIELD_TICKS); + run(&mut sim, 1); + assert_eq!(sim.current_player(), 1); + assert!(sim.tanks[0].shield_ticks > 0); + } + + #[test] + fn match_ends_at_turn_cap() { + let mut sim = Sim::default_match(7); + for _ in 0..MAX_TURNS { + sim.submit(Command::EndTurn).unwrap(); + run(&mut sim, 1); + } + assert_eq!(sim.phase, Phase::Finished); + assert!(sim.turn > MAX_TURNS, "turn={}", sim.turn); + } +} diff --git a/crates/sim/src/terrain.rs b/crates/sim/src/terrain.rs new file mode 100644 index 0000000..fe201b5 --- /dev/null +++ b/crates/sim/src/terrain.rs @@ -0,0 +1,278 @@ +//! Destructible heightmap terrain. +//! +//! The world is described by one surface height per sample (2 px wide). +//! Carving raises the surface value (y grows downwards), collapsing relaxes +//! slopes of sand in a fixed, deterministic order. + +use alloc::vec; +use alloc::vec::Vec; + +use crate::fixed::{self, clamp, from_int, mul, to_int, Fx}; +use crate::rng::Pcg32; + +/// World width in logical pixels. +pub const WORLD_W: i32 = 2048; +/// World height in logical pixels. +pub const WORLD_H: i32 = 1152; +/// Width of one heightmap sample in pixels. +pub const SAMPLE_PX: i32 = 2; +/// Number of heightmap samples. +pub const SAMPLES: usize = (WORLD_W / SAMPLE_PX) as usize; + +/// Terrain material, controls collapse behaviour. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum Material { + Air = 0, + Sand = 1, + Rock = 2, + Ice = 3, +} + +impl Material { + fn from_u8(v: u8) -> Self { + match v { + 0 => Material::Air, + 2 => Material::Rock, + 3 => Material::Ice, + _ => Material::Sand, + } + } +} + +/// Heightmap plus per-sample material. +#[derive(Clone, Debug)] +pub struct Terrain { + heights: Vec, + materials: Vec, +} + +impl Terrain { + /// Deterministically generates a map from a seed. + pub fn generate(seed: u64) -> Self { + let mut rng = Pcg32::new(seed, 7); + let phase1 = rng.below(360_000); + let phase2 = rng.below(360_000); + let phase3 = rng.below(360_000); + + let base = from_int(WORLD_H * 3 / 5); + let mut heights = vec![0u16; SAMPLES]; + let mut materials = vec![Material::Air as u8; SAMPLES]; + + for i in 0..SAMPLES { + let x = i as i32; + let h = + base - mul( + from_int(90), + fixed::sin((x * 13 + phase1 as i32) as u32 % 360_000), + ) - mul( + from_int(40), + fixed::sin((x * 29 + phase2 as i32) as u32 % 360_000), + ) - mul( + from_int(15), + fixed::sin((x * 53 + phase3 as i32) as u32 % 360_000), + ); + heights[i] = to_int(clamp(h, from_int(240), from_int(WORLD_H - 120))) as u16; + + let depth_below_surface = WORLD_H - heights[i] as i32; + materials[i] = if depth_below_surface < 120 { + Material::Sand as u8 + } else if rng.below(100) < 8 { + Material::Ice as u8 + } else { + Material::Rock as u8 + }; + } + + Self { heights, materials } + } + + /// Creates a flat map (used by tests and tutorials). + pub fn flat(surface_y: i32) -> Self { + Self { + heights: vec![surface_y as u16; SAMPLES], + materials: vec![Material::Rock as u8; SAMPLES], + } + } + + /// Number of heightmap samples. + pub fn len(&self) -> usize { + self.heights.len() + } + + /// True if the heightmap has no samples (never happens in practice). + pub fn is_empty(&self) -> bool { + self.heights.is_empty() + } + + /// Surface height at sample index. + pub fn height_at(&self, idx: usize) -> u16 { + self.heights[idx.min(SAMPLES - 1)] + } + + /// Material at sample index. + pub fn material_at(&self, idx: usize) -> Material { + Material::from_u8(self.materials[idx.min(SAMPLES - 1)]) + } + + /// Surface y for a world x coordinate (2 px granularity). + pub fn surface_y(&self, x: Fx) -> Fx { + let idx = self.index_of(x); + from_int(self.heights[idx] as i32) + } + + /// True if the given world point is inside solid ground. + pub fn is_solid(&self, x: Fx, y: Fx) -> bool { + if x < 0 || x >= from_int(WORLD_W) { + return false; + } + y >= self.surface_y(x) + } + + /// Sample index for a world x coordinate. + pub fn index_of(&self, x: Fx) -> usize { + let px = to_int(x).clamp(0, WORLD_W - 1); + (px / SAMPLE_PX) as usize + } + + /// Carves a circular crater and returns the number of removed height units. + pub fn carve_circle(&mut self, cx: Fx, cy: Fx, radius: Fx) -> u32 { + let r = to_int(radius).max(1); + let ccx = to_int(cx); + let ccy = to_int(cy); + let mut removed = 0u32; + + let start = ((ccx - r) / SAMPLE_PX).max(0) as usize; + let end = (((ccx + r) / SAMPLE_PX) + 1).min(SAMPLES as i32) as usize; + + for i in start..end { + let sample_x = i as i32 * SAMPLE_PX; + let dx = sample_x - ccx; + if dx.abs() > r { + continue; + } + // Circle depth in pixels at this sample. + let depth = fixed::sqrt(from_int(r * r - dx * dx)); + let old = self.heights[i] as i32; + // Only material below the blast centre is removed. + let from = old.max(ccy); + let to = (from + to_int(depth)).min(WORLD_H); + if to > from { + self.heights[i] = to as u16; + self.materials[i] = Material::Sand as u8; + removed += (to - from) as u32; + } + } + removed + } + + /// Relaxes sand slopes: two deterministic passes left to right. + pub fn collapse(&mut self) { + let max_slope: i32 = 6; + for _ in 0..2 { + for i in 0..SAMPLES - 1 { + if self.materials[i] != Material::Sand as u8 { + continue; + } + let a = self.heights[i] as i32; + let b = self.heights[i + 1] as i32; + if b - a > max_slope { + let shift = ((b - a - max_slope) / 2).max(1); + self.heights[i] = (a + shift).clamp(0, WORLD_H) as u16; + self.heights[i + 1] = (b - shift).clamp(0, WORLD_H) as u16; + } else if a - b > max_slope { + let shift = ((a - b - max_slope) / 2).max(1); + self.heights[i] = (a - shift).clamp(0, WORLD_H) as u16; + self.heights[i + 1] = (b + shift).clamp(0, WORLD_H) as u16; + } + } + } + } + + /// Flattens the surface under a tank so it can stand. + pub fn flatten_under(&mut self, cx: Fx, width_px: i32) { + let idx = self.index_of(cx); + let half = (width_px / 2 / SAMPLE_PX).max(1) as usize; + let lo = idx.saturating_sub(half); + let hi = (idx + half).min(SAMPLES - 1); + let target = self.heights[idx]; + for i in lo..=hi { + self.heights[i] = target; + } + } + + /// Serialises the heightmap for hashing (little endian, fixed order). + pub fn feed_hash(&self, mut f: impl FnMut(u8)) { + for h in &self.heights { + f((*h & 0xFF) as u8); + f((*h >> 8) as u8); + } + for m in &self.materials { + f(*m); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn generation_is_deterministic() { + let a = Terrain::generate(1234); + let b = Terrain::generate(1234); + assert_eq!(a.heights, b.heights); + assert_eq!(a.materials, b.materials); + let c = Terrain::generate(99); + assert_ne!(a.heights, c.heights); + } + + #[test] + fn heights_stay_in_world_bounds() { + for seed in 0..50u64 { + let t = Terrain::generate(seed); + for i in 0..t.len() { + assert!(t.height_at(i) as i32 <= WORLD_H); + assert!(t.height_at(i) as i32 >= 0); + } + } + } + + #[test] + fn carving_removes_material() { + let mut t = Terrain::flat(600); + let removed = t.carve_circle(from_int(1000), from_int(600), from_int(60)); + assert!(removed > 0); + assert!(t.height_at(t.index_of(from_int(1000))) > 600); + } + + #[test] + fn carving_never_exceeds_world_height() { + let mut t = Terrain::flat(WORLD_H - 10); + t.carve_circle(from_int(500), from_int(WORLD_H - 10), from_int(400)); + for i in 0..t.len() { + assert!(t.height_at(i) as i32 <= WORLD_H); + } + } + + #[test] + fn collapse_reduces_steep_sand_slopes() { + let mut t = Terrain::flat(600); + for i in 500..520 { + t.heights[i] = 900; + t.materials[i] = Material::Sand as u8; + } + let before = t.heights[519] as i32 - t.heights[520] as i32; + t.collapse(); + let after = t.heights[519] as i32 - t.heights[520] as i32; + assert!(after < before, "slope did not relax: {before} -> {after}"); + } + + #[test] + fn flatten_makes_a_level_platform() { + let mut t = Terrain::generate(5); + t.flatten_under(from_int(1024), 40); + let idx = t.index_of(from_int(1024)); + assert_eq!(t.height_at(idx - 5), t.height_at(idx + 5)); + } +} diff --git a/crates/sim/src/trig_table.rs b/crates/sim/src/trig_table.rs new file mode 100644 index 0000000..eb3ab61 --- /dev/null +++ b/crates/sim/src/trig_table.rs @@ -0,0 +1,84 @@ +//! Generated by tools/gen_trig.py - do not edit by hand. +//! Sine over the first quadrant: index i maps to i*90deg/1024. + +pub const QUARTER: usize = 1024; +pub const SIN_Q16: [i32; 1025] = [ + 0, 101, 201, 302, 402, 503, 603, 704, 804, 905, 1005, 1106, 1206, 1307, 1407, 1508, 1608, 1709, + 1809, 1910, 2010, 2111, 2211, 2312, 2412, 2513, 2613, 2714, 2814, 2914, 3015, 3115, 3216, 3316, + 3416, 3517, 3617, 3718, 3818, 3918, 4019, 4119, 4219, 4320, 4420, 4520, 4621, 4721, 4821, 4921, + 5022, 5122, 5222, 5322, 5422, 5523, 5623, 5723, 5823, 5923, 6023, 6123, 6223, 6324, 6424, 6524, + 6624, 6724, 6824, 6924, 7024, 7123, 7223, 7323, 7423, 7523, 7623, 7723, 7823, 7922, 8022, 8122, + 8222, 8321, 8421, 8521, 8620, 8720, 8820, 8919, 9019, 9118, 9218, 9318, 9417, 9517, 9616, 9715, + 9815, 9914, 10014, 10113, 10212, 10312, 10411, 10510, 10609, 10708, 10808, 10907, 11006, 11105, + 11204, 11303, 11402, 11501, 11600, 11699, 11798, 11897, 11996, 12094, 12193, 12292, 12391, + 12489, 12588, 12687, 12785, 12884, 12982, 13081, 13179, 13278, 13376, 13475, 13573, 13671, + 13770, 13868, 13966, 14064, 14163, 14261, 14359, 14457, 14555, 14653, 14751, 14849, 14947, + 15045, 15142, 15240, 15338, 15436, 15533, 15631, 15729, 15826, 15924, 16021, 16119, 16216, + 16313, 16411, 16508, 16605, 16703, 16800, 16897, 16994, 17091, 17188, 17285, 17382, 17479, + 17576, 17673, 17769, 17866, 17963, 18060, 18156, 18253, 18349, 18446, 18542, 18639, 18735, + 18831, 18928, 19024, 19120, 19216, 19312, 19408, 19504, 19600, 19696, 19792, 19888, 19984, + 20079, 20175, 20271, 20366, 20462, 20557, 20653, 20748, 20843, 20939, 21034, 21129, 21224, + 21319, 21414, 21509, 21604, 21699, 21794, 21889, 21983, 22078, 22173, 22267, 22362, 22456, + 22551, 22645, 22739, 22834, 22928, 23022, 23116, 23210, 23304, 23398, 23492, 23586, 23679, + 23773, 23867, 23960, 24054, 24147, 24241, 24334, 24428, 24521, 24614, 24707, 24800, 24893, + 24986, 25079, 25172, 25265, 25358, 25450, 25543, 25635, 25728, 25820, 25913, 26005, 26097, + 26189, 26281, 26374, 26466, 26557, 26649, 26741, 26833, 26925, 27016, 27108, 27199, 27291, + 27382, 27473, 27565, 27656, 27747, 27838, 27929, 28020, 28111, 28201, 28292, 28383, 28473, + 28564, 28654, 28745, 28835, 28925, 29015, 29106, 29196, 29286, 29375, 29465, 29555, 29645, + 29734, 29824, 29913, 30003, 30092, 30181, 30271, 30360, 30449, 30538, 30627, 30716, 30804, + 30893, 30982, 31070, 31159, 31247, 31335, 31424, 31512, 31600, 31688, 31776, 31864, 31952, + 32039, 32127, 32215, 32302, 32390, 32477, 32564, 32651, 32738, 32826, 32912, 32999, 33086, + 33173, 33260, 33346, 33433, 33519, 33605, 33692, 33778, 33864, 33950, 34036, 34122, 34208, + 34293, 34379, 34465, 34550, 34635, 34721, 34806, 34891, 34976, 35061, 35146, 35231, 35315, + 35400, 35485, 35569, 35654, 35738, 35822, 35906, 35990, 36074, 36158, 36242, 36326, 36409, + 36493, 36576, 36660, 36743, 36826, 36909, 36992, 37075, 37158, 37241, 37324, 37406, 37489, + 37571, 37653, 37736, 37818, 37900, 37982, 38064, 38145, 38227, 38309, 38390, 38472, 38553, + 38634, 38715, 38797, 38877, 38958, 39039, 39120, 39200, 39281, 39361, 39442, 39522, 39602, + 39682, 39762, 39842, 39922, 40001, 40081, 40161, 40240, 40319, 40398, 40478, 40557, 40635, + 40714, 40793, 40872, 40950, 41029, 41107, 41185, 41263, 41341, 41419, 41497, 41575, 41653, + 41730, 41808, 41885, 41962, 42039, 42117, 42194, 42270, 42347, 42424, 42500, 42577, 42653, + 42730, 42806, 42882, 42958, 43034, 43109, 43185, 43261, 43336, 43411, 43487, 43562, 43637, + 43712, 43787, 43861, 43936, 44011, 44085, 44159, 44234, 44308, 44382, 44456, 44529, 44603, + 44677, 44750, 44824, 44897, 44970, 45043, 45116, 45189, 45262, 45334, 45407, 45479, 45552, + 45624, 45696, 45768, 45840, 45912, 45983, 46055, 46126, 46198, 46269, 46340, 46411, 46482, + 46553, 46624, 46694, 46765, 46835, 46905, 46976, 47046, 47116, 47185, 47255, 47325, 47394, + 47464, 47533, 47602, 47671, 47740, 47809, 47877, 47946, 48014, 48083, 48151, 48219, 48287, + 48355, 48423, 48491, 48558, 48626, 48693, 48760, 48827, 48894, 48961, 49028, 49095, 49161, + 49228, 49294, 49360, 49426, 49492, 49558, 49624, 49689, 49755, 49820, 49885, 49951, 50016, + 50080, 50145, 50210, 50274, 50339, 50403, 50467, 50531, 50595, 50659, 50723, 50787, 50850, + 50913, 50977, 51040, 51103, 51166, 51228, 51291, 51354, 51416, 51478, 51540, 51602, 51664, + 51726, 51788, 51849, 51911, 51972, 52033, 52094, 52155, 52216, 52277, 52337, 52398, 52458, + 52518, 52578, 52638, 52698, 52758, 52817, 52877, 52936, 52995, 53054, 53113, 53172, 53231, + 53289, 53348, 53406, 53464, 53522, 53580, 53638, 53696, 53754, 53811, 53868, 53925, 53983, + 54039, 54096, 54153, 54210, 54266, 54322, 54378, 54434, 54490, 54546, 54602, 54657, 54713, + 54768, 54823, 54878, 54933, 54988, 55042, 55097, 55151, 55206, 55260, 55314, 55367, 55421, + 55475, 55528, 55582, 55635, 55688, 55741, 55794, 55846, 55899, 55951, 56003, 56056, 56108, + 56159, 56211, 56263, 56314, 56366, 56417, 56468, 56519, 56570, 56620, 56671, 56721, 56772, + 56822, 56872, 56922, 56972, 57021, 57071, 57120, 57169, 57218, 57267, 57316, 57365, 57413, + 57462, 57510, 57558, 57606, 57654, 57702, 57749, 57797, 57844, 57891, 57938, 57985, 58032, + 58079, 58125, 58171, 58218, 58264, 58310, 58356, 58401, 58447, 58492, 58537, 58583, 58628, + 58672, 58717, 58762, 58806, 58850, 58895, 58939, 58983, 59026, 59070, 59113, 59157, 59200, + 59243, 59286, 59329, 59371, 59414, 59456, 59498, 59540, 59582, 59624, 59666, 59707, 59749, + 59790, 59831, 59872, 59913, 59953, 59994, 60034, 60075, 60115, 60155, 60194, 60234, 60274, + 60313, 60352, 60391, 60430, 60469, 60508, 60546, 60585, 60623, 60661, 60699, 60737, 60775, + 60812, 60850, 60887, 60924, 60961, 60998, 61034, 61071, 61107, 61144, 61180, 61216, 61252, + 61287, 61323, 61358, 61393, 61429, 61463, 61498, 61533, 61567, 61602, 61636, 61670, 61704, + 61738, 61772, 61805, 61838, 61872, 61905, 61938, 61970, 62003, 62035, 62068, 62100, 62132, + 62164, 62196, 62227, 62259, 62290, 62321, 62352, 62383, 62414, 62444, 62475, 62505, 62535, + 62565, 62595, 62625, 62654, 62684, 62713, 62742, 62771, 62800, 62829, 62857, 62886, 62914, + 62942, 62970, 62998, 63025, 63053, 63080, 63107, 63134, 63161, 63188, 63214, 63241, 63267, + 63293, 63319, 63345, 63371, 63396, 63422, 63447, 63472, 63497, 63522, 63546, 63571, 63595, + 63620, 63644, 63668, 63691, 63715, 63738, 63762, 63785, 63808, 63831, 63853, 63876, 63898, + 63921, 63943, 63965, 63986, 64008, 64030, 64051, 64072, 64093, 64114, 64135, 64155, 64176, + 64196, 64216, 64236, 64256, 64276, 64295, 64315, 64334, 64353, 64372, 64391, 64409, 64428, + 64446, 64464, 64482, 64500, 64518, 64535, 64553, 64570, 64587, 64604, 64621, 64638, 64654, + 64671, 64687, 64703, 64719, 64734, 64750, 64765, 64781, 64796, 64811, 64826, 64840, 64855, + 64869, 64883, 64898, 64911, 64925, 64939, 64952, 64966, 64979, 64992, 65005, 65017, 65030, + 65042, 65054, 65066, 65078, 65090, 65102, 65113, 65125, 65136, 65147, 65158, 65168, 65179, + 65189, 65199, 65210, 65219, 65229, 65239, 65248, 65258, 65267, 65276, 65285, 65293, 65302, + 65310, 65319, 65327, 65335, 65342, 65350, 65357, 65365, 65372, 65379, 65386, 65392, 65399, + 65405, 65412, 65418, 65424, 65429, 65435, 65441, 65446, 65451, 65456, 65461, 65466, 65470, + 65475, 65479, 65483, 65487, 65491, 65494, 65498, 65501, 65504, 65507, 65510, 65513, 65515, + 65518, 65520, 65522, 65524, 65526, 65527, 65529, 65530, 65531, 65532, 65533, 65534, 65534, + 65535, 65535, 65535, +]; diff --git a/crates/sim/src/weapons.rs b/crates/sim/src/weapons.rs new file mode 100644 index 0000000..a9f8858 --- /dev/null +++ b/crates/sim/src/weapons.rs @@ -0,0 +1,83 @@ +//! Weapon definitions (data table). Content-driven loading arrives at M2. + +/// Static description of a weapon. +#[derive(Clone, Copy, Debug)] +pub struct WeaponDef { + /// Stable id used in replays. + pub id: u8, + /// Display name (English, localised by the client). + pub name: &'static str, + /// Base damage at the impact centre. + pub damage: i32, + /// Blast radius in pixels. + pub radius_px: i32, + /// Ammo per match (`255` means unlimited). + pub ammo: u8, + /// Muzzle speed in px/tick at full power. + pub speed: i32, + /// True if the terrain is dug instead of blasted. + pub digs: bool, +} + +/// MVP-1 arsenal. +pub const WEAPONS: [WeaponDef; 6] = [ + WeaponDef { + id: 1, + name: "Baby Shell", + damage: 22, + radius_px: 34, + ammo: 255, + speed: 20, + digs: false, + }, + WeaponDef { + id: 2, + name: "Heavy Shell", + damage: 34, + radius_px: 48, + ammo: 3, + speed: 15, + digs: false, + }, + WeaponDef { + id: 3, + name: "Roller", + damage: 26, + radius_px: 40, + ammo: 2, + speed: 18, + digs: false, + }, + WeaponDef { + id: 4, + name: "Digger", + damage: 14, + radius_px: 30, + ammo: 2, + speed: 18, + digs: true, + }, + WeaponDef { + id: 5, + name: "Shield", + damage: 0, + radius_px: 0, + ammo: 2, + speed: 0, + digs: false, + }, + WeaponDef { + id: 6, + name: "MIRV", + damage: 18, + radius_px: 24, + ammo: 2, + speed: 19, + digs: false, + }, +]; + +/// Looks up a weapon by id. +pub fn get(id: u8) -> Option<&'static WeaponDef> { + WEAPONS.iter().find(|w| w.id == id) +}