feat(m2): content-driven ruleset, balance cli and tuning findings

This commit is contained in:
2026-10-24 22:43:58 +02:00
parent e371c72a35
commit e77595eaf0
18 changed files with 844 additions and 120 deletions
+3 -3
View File
@@ -4,8 +4,8 @@ version.workspace = true
edition.workspace = true
rust-version.workspace = true
authors.workspace = true
description = "Data-driven content models (tanks, weapons, maps) with validation"
description = "Data-driven content models (weapons, tanks, maps) with validation and hashing"
[dependencies]
serde.workspace = true
serde_json.workspace = true
serde = { workspace = true, default-features = false, features = ["derive", "alloc"] }
serde_json = { workspace = true, default-features = false, features = ["alloc"] }
+103
View File
@@ -0,0 +1,103 @@
{
"version": "1.0.0",
"weapons": [
{
"id": 1,
"name": "Baby Shell",
"damage": 30,
"radius_px": 60,
"ammo": 255,
"speed": 20,
"digs": false
},
{
"id": 2,
"name": "Heavy Shell",
"damage": 42,
"radius_px": 75,
"ammo": 3,
"speed": 15,
"digs": false
},
{
"id": 3,
"name": "Roller",
"damage": 34,
"radius_px": 64,
"ammo": 2,
"speed": 18,
"digs": false
},
{
"id": 4,
"name": "Digger",
"damage": 14,
"radius_px": 55,
"ammo": 2,
"speed": 18,
"digs": true
},
{
"id": 5,
"name": "Shield",
"damage": 0,
"radius_px": 1,
"ammo": 2,
"speed": 0,
"digs": false
},
{
"id": 6,
"name": "MIRV",
"damage": 22,
"radius_px": 48,
"ammo": 2,
"speed": 19,
"digs": false
}
],
"tanks": [
{
"id": "vanguard",
"name": "Vanguard",
"hp": 100,
"passive": "shield_recharge",
"ultimate": "overdrive"
},
{
"id": "longshot",
"name": "Longshot",
"hp": 100,
"passive": "range_bonus",
"ultimate": "target_marker"
},
{
"id": "bulwark",
"name": "Bulwark",
"hp": 110,
"passive": "damage_reduction",
"ultimate": "dome"
},
{
"id": "sapper",
"name": "Sapper",
"hp": 95,
"passive": "dig_depth",
"ultimate": "emp"
}
],
"maps": [
{
"id": "default",
"width": 2048,
"height": 1152,
"spawn_x": 220
},
{
"id": "canyon",
"width": 2048,
"height": 1152,
"spawn_x": 180
}
]
}
+248 -6
View File
@@ -1,9 +1,251 @@
//! Content models and validation for tanks, weapons and map presets.
//! Data-driven content: weapons, tanks and map presets.
//!
//! Content is versioned as a whole: `content_hash` pins a ruleset so that
//! replays stay verifiable (see docs/protocol.md).
//! The JSON file is the single source of truth for balancing. It is embedded at
//! compile time and hashed (`content_hash`) so that a replay can only be
//! validated against the exact ruleset it was played with.
#![cfg_attr(not(test), no_std)]
#![forbid(unsafe_code)]
/// Placeholder until M2 fills in the models.
pub fn content_hash_placeholder() -> &'static str {
"b3:uninitialized"
extern crate alloc;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};
/// Embedded content shipped with the build.
pub const BUILTIN_JSON: &str = include_str!("../assets/content.json");
/// Ammo value that means "unlimited".
pub const UNLIMITED_AMMO: u8 = 255;
/// A weapon definition.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Weapon {
/// Stable id used in replays.
pub id: u8,
/// Display name (localised by the client).
pub name: String,
/// 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 at full power in px/tick.
pub speed: i32,
/// True if the weapon digs instead of blasting.
pub digs: bool,
}
/// A tank definition.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Tank {
/// Stable id used in payloads.
pub id: String,
/// Display name.
pub name: String,
/// Maximum hit points.
pub hp: i32,
/// Passive ability key (client/sim wiring follows at M3).
pub passive: String,
/// Ultimate ability key.
pub ultimate: String,
}
/// A map preset.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct MapPreset {
/// Stable id.
pub id: String,
/// World width in pixels.
pub width: i32,
/// World height in pixels.
pub height: i32,
/// Spawn distance from the map edge.
pub spawn_x: i32,
}
/// The complete ruleset.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Content {
/// Content version (SemVer).
pub version: String,
/// All weapons.
pub weapons: Vec<Weapon>,
/// All tanks.
pub tanks: Vec<Tank>,
/// All map presets.
pub maps: Vec<MapPreset>,
}
/// Validation failures.
#[derive(Debug, PartialEq, Eq)]
pub enum ContentError {
/// JSON could not be parsed.
Parse(String),
/// No weapons defined.
NoWeapons,
/// Duplicate weapon id.
DuplicateWeapon(u8),
/// Duplicate tank id.
DuplicateTank(String),
/// Duplicate map id.
DuplicateMap(String),
/// Weapon values out of range.
BadWeapon(u8),
/// Tank values out of range.
BadTank(String),
/// Map values out of range.
BadMap(String),
}
impl Content {
/// Parses and validates content from JSON.
pub fn from_json(json: &str) -> Result<Self, ContentError> {
let content: Content =
serde_json::from_str(json).map_err(|e| ContentError::Parse(e.to_string()))?;
content.validate()?;
Ok(content)
}
/// The content compiled into this build.
pub fn builtin() -> Self {
Self::from_json(BUILTIN_JSON).expect("builtin content must be valid")
}
/// Checks structural invariants.
pub fn validate(&self) -> Result<(), ContentError> {
if self.weapons.is_empty() {
return Err(ContentError::NoWeapons);
}
for (i, w) in self.weapons.iter().enumerate() {
if w.id == 0 || w.damage < 0 || w.radius_px < 0 || w.speed < 0 || w.name.is_empty() {
return Err(ContentError::BadWeapon(w.id));
}
if self.weapons[..i].iter().any(|o| o.id == w.id) {
return Err(ContentError::DuplicateWeapon(w.id));
}
}
for (i, t) in self.tanks.iter().enumerate() {
if t.id.is_empty() || !(50..=200).contains(&t.hp) {
return Err(ContentError::BadTank(t.id.clone()));
}
if self.tanks[..i].iter().any(|o| o.id == t.id) {
return Err(ContentError::DuplicateTank(t.id.clone()));
}
}
for (i, m) in self.maps.iter().enumerate() {
if m.width <= 0 || m.height <= 0 || m.spawn_x <= 0 || m.spawn_x * 2 >= m.width {
return Err(ContentError::BadMap(m.id.clone()));
}
if self.maps[..i].iter().any(|o| o.id == m.id) {
return Err(ContentError::DuplicateMap(m.id.clone()));
}
}
Ok(())
}
/// Looks up a weapon by id.
pub fn weapon(&self, id: u8) -> Option<&Weapon> {
self.weapons.iter().find(|w| w.id == id)
}
/// Looks up a tank by id.
pub fn tank(&self, id: &str) -> Option<&Tank> {
self.tanks.iter().find(|t| t.id == id)
}
/// Looks up a map by id.
pub fn map(&self, id: &str) -> Option<&MapPreset> {
self.maps.iter().find(|m| m.id == id)
}
/// Canonical JSON (field order is fixed by the struct definitions).
pub fn canonical_json(&self) -> String {
serde_json::to_string(self).expect("content is serialisable")
}
/// Stable content hash as a plain number (used inside the state hash).
pub fn hash_u64(&self) -> u64 {
fnv1a(self.canonical_json().as_bytes())
}
/// Stable content hash used to pin replays and balance reports.
pub fn hash(&self) -> String {
format!("fnv1a:{:016x}", self.hash_u64())
}
}
fn fnv1a(bytes: &[u8]) -> u64 {
let mut state: u64 = 0xcbf2_9ce4_8422_2325;
for b in bytes {
state ^= *b as u64;
state = state.wrapping_mul(0x0000_0100_0000_01b3);
}
state
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builtin_content_is_valid() {
let c = Content::builtin();
assert_eq!(c.weapons.len(), 6);
assert!(c.tanks.len() >= 2);
assert!(!c.maps.is_empty());
assert_eq!(c.version, "1.0.0");
}
#[test]
fn lookups_work() {
let c = Content::builtin();
assert_eq!(c.weapon(1).unwrap().name, "Baby Shell");
assert_eq!(c.weapon(1).unwrap().ammo, UNLIMITED_AMMO);
assert!(c.weapon(99).is_none());
assert_eq!(c.tank("vanguard").unwrap().hp, 100);
}
#[test]
fn hash_is_stable_and_sensitive() {
let a = Content::builtin();
let b = Content::builtin();
assert_eq!(a.hash(), b.hash());
assert!(a.hash().starts_with("fnv1a:"));
let mut c = Content::builtin();
c.weapons[0].damage += 1;
assert_ne!(a.hash(), c.hash());
}
#[test]
fn invalid_json_is_rejected() {
assert!(matches!(
Content::from_json("{ not json }"),
Err(ContentError::Parse(_))
));
}
#[test]
fn duplicate_weapon_id_is_rejected() {
let json = r#"{ "version": "1", "weapons": [
{ "id": 1, "name": "A", "damage": 1, "radius_px": 1, "ammo": 1, "speed": 1, "digs": false },
{ "id": 1, "name": "B", "damage": 1, "radius_px": 1, "ammo": 1, "speed": 1, "digs": false }
], "tanks": [], "maps": [] }"#;
assert_eq!(
Content::from_json(json),
Err(ContentError::DuplicateWeapon(1))
);
}
#[test]
fn out_of_range_values_are_rejected() {
let json = r#"{ "version": "1", "weapons": [
{ "id": 2, "name": "A", "damage": -5, "radius_px": 1, "ammo": 1, "speed": 1, "digs": false }
], "tanks": [], "maps": [] }"#;
assert_eq!(Content::from_json(json), Err(ContentError::BadWeapon(2)));
}
}
+3 -1
View File
@@ -33,7 +33,9 @@ pub extern "C" fn iron_arc_selftest(seed: u64) -> u64 {
/// Returns the simulation version as a packed `major*10000 + minor*100 + patch`.
#[no_mangle]
pub extern "C" fn iron_arc_sim_version_code() -> u32 {
let mut parts = sim::SIM_VERSION.split('.').filter_map(|p| p.parse::<u32>().ok());
let mut parts = sim::SIM_VERSION
.split('.')
.filter_map(|p| p.parse::<u32>().ok());
let major = parts.next().unwrap_or(0);
let minor = parts.next().unwrap_or(0);
let patch = parts.next().unwrap_or(0);
+1
View File
@@ -14,5 +14,6 @@ default = []
serde = ["dep:serde", "dep:serde_json"]
[dependencies]
content.workspace = true
serde = { workspace = true, optional = true }
serde_json = { workspace = true, optional = true }
+5 -1
View File
@@ -23,5 +23,9 @@ fn main() {
sim.tick();
}
println!("seed={seed} sim_version={} hash={}", sim::SIM_VERSION, sim.state_hash());
println!(
"seed={seed} sim_version={} hash={}",
sim::SIM_VERSION,
sim.state_hash()
);
}
-1
View File
@@ -19,7 +19,6 @@ 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";
+12 -4
View File
@@ -102,7 +102,7 @@ pub struct ReplayV1 {
impl ReplayV1 {
/// Builds a replay from a finished (or in-flight) simulation.
pub fn capture(sim: &Sim, content_hash: &str, mode: &str, duration_ticks: u32) -> Self {
pub fn capture(sim: &Sim, mode: &str, duration_ticks: u32) -> Self {
let commands = sim
.recorded_commands()
.iter()
@@ -129,7 +129,7 @@ impl ReplayV1 {
Self {
v: 1,
sim_version: SIM_VERSION.to_string(),
content_hash: content_hash.to_string(),
content_hash: sim.content.hash(),
seed: sim.seed,
mode: mode.to_string(),
players,
@@ -167,7 +167,15 @@ impl ReplayV1 {
loadout: self.players[1].loadout,
},
];
let mut sim = Sim::new(self.seed, specs);
let content = content::Content::builtin();
if content.hash() != self.content_hash {
return Err(format!(
"content mismatch: replay {} vs server {}",
self.content_hash,
content.hash()
));
}
let mut sim = Sim::new(self.seed, specs, content);
let mut projected = 0u8;
for (i, rec) in self.commands.iter().enumerate() {
@@ -208,7 +216,7 @@ mod tests {
for _ in 0..300 {
sim.tick();
}
ReplayV1::capture(&sim, "b3:test", "hotseat", sim.tick)
ReplayV1::capture(&sim, "hotseat", sim.tick)
}
#[test]
+40 -10
View File
@@ -6,8 +6,8 @@ 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;
use content::Content;
/// Maximum hit points per tank.
pub const MAX_HP: i32 = 100;
@@ -22,7 +22,7 @@ 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);
pub const WIND_SCALE: Fx = from_ratio(4, 1000);
/// Muzzle offset above the tank in px.
pub const MUZZLE_LEN: i32 = 16;
/// Shield duration in ticks (2 turns).
@@ -114,11 +114,11 @@ pub struct Tank {
}
impl Tank {
fn new(spec: TankSpec, terrain: &Terrain) -> Self {
fn new(spec: TankSpec, terrain: &Terrain, content: &Content) -> 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);
ammo[i] = content.weapon(*id).map(|w| w.ammo).unwrap_or(0);
}
Self {
x,
@@ -165,6 +165,10 @@ pub struct Sim {
pub winner: Option<u8>,
pub lava_y: i32,
pub seed: u64,
/// Ruleset this match runs on.
pub content: Content,
/// Hash of the ruleset (part of the state hash).
pub content_hash: u64,
rng: Pcg32,
log: Vec<(u32, Command)>,
pending_end: bool,
@@ -172,11 +176,20 @@ pub struct Sim {
impl Sim {
/// Creates a match. Player 0 starts left, player 1 right.
pub fn new(seed: u64, specs: [TankSpec; 2]) -> Self {
pub fn new(seed: u64, specs: [TankSpec; 2], content: Content) -> Self {
Self::with_starter(seed, specs, content, 0)
}
/// Creates a match with an explicit starting player (0 or 1).
pub fn with_starter(seed: u64, specs: [TankSpec; 2], content: Content, starter: u8) -> 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 tanks = [
Tank::new(specs[0], &terrain, &content),
Tank::new(specs[1], &terrain, &content),
];
let content_hash = content.hash_u64();
let mut rng = Pcg32::new(seed, 11);
let wind = (rng.below(17) as i32) - 8;
Self {
@@ -187,11 +200,13 @@ impl Sim {
tick: 0,
turn: 1,
phase: Phase::Aiming,
current: 0,
current: starter % 2,
turn_ticks_left: TURN_TICKS,
winner: None,
lava_y: WORLD_H + 200,
seed,
content,
content_hash,
rng,
log: Vec::new(),
pending_end: false,
@@ -212,6 +227,7 @@ impl Sim {
loadout: [1, 3, 4],
},
],
Content::builtin(),
)
}
@@ -251,7 +267,11 @@ impl Sim {
if power < from_ratio(5, 100) || power > from_int(1) {
return Err(SimError::BadPower);
}
let w = weapons::get(weapon).ok_or(SimError::UnknownWeapon)?;
let w = self
.content
.weapon(weapon)
.ok_or(SimError::UnknownWeapon)?
.clone();
let slot = self.tanks[self.current as usize]
.slot_of(weapon)
.ok_or(SimError::WeaponNotInLoadout)?;
@@ -348,7 +368,7 @@ impl Sim {
}
fn resolve_impact(&mut self, x: Fx, y: Fx, p: &Projectile, events: &mut Vec<Event>) {
let Some(w) = weapons::get(p.weapon) else {
let Some(w) = self.content.weapon(p.weapon).cloned() else {
self.end_turn(events);
return;
};
@@ -364,7 +384,8 @@ impl Sim {
if d >= radius {
continue;
}
let falloff = from_int(1) - fixed::div(d, radius);
// Near misses keep 25% damage so the game does not turn into pixel hunting.
let falloff = (from_int(1) - fixed::div(d, radius)).max(from_ratio(25, 100));
let mut dmg = ((w.damage as i64) * (falloff as i64)) >> 16;
dmg *= multiplier;
if tank.shield_ticks > 0 {
@@ -376,6 +397,14 @@ impl Sim {
}
}
// Tanks follow the terrain: if the ground under them was removed, they drop.
for tank in &mut self.tanks {
let surface = self.terrain.surface_y(tank.x);
if surface > tank.y {
tank.y = surface;
}
}
events.push(Event::Impact {
x,
y,
@@ -459,6 +488,7 @@ impl Sim {
});
h.i32(self.wind);
h.i32(self.lava_y);
h.u64(self.content_hash);
for tank in &self.tanks {
h.i32(tank.x);
h.i32(tank.y);
-83
View File
@@ -1,83 +0,0 @@
//! 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)
}