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
+341 -3
View File
@@ -1,8 +1,346 @@
//! Headless balance CLI. Real implementation at M2.
//! Headless balance tool: plays complete matches with heuristic AI players and
//! aggregates the results into a CSV report.
//!
//! The AI solves the ballistic equation analytically and then adds aim noise
//! according to a skill profile. Simulation stays fully deterministic; only the
//! *inputs* (angle/power) are produced here.
use std::env;
use std::fs::File;
use std::io::{BufWriter, Write};
use sim::fixed::Fx;
use sim::rng::Pcg32;
use sim::state::{Command, Event, Phase, Sim, MAX_TURNS, MUZZLE_LEN, TURN_TICKS};
/// Gravity in px/tick^2, must match `sim::state::GRAVITY`.
const GRAVITY: f64 = 0.2;
/// Wind acceleration per wind unit, mirrors `sim::state::WIND_SCALE`.
const WIND_PER_UNIT: f64 = 0.004;
struct Config {
matches: u32,
seed: u64,
out: String,
skill: f64,
weapon: u8,
}
impl Config {
fn parse() -> Self {
let mut cfg = Config {
matches: 200,
seed: 1,
out: "balance-report.csv".to_string(),
skill: 80.0,
weapon: 1,
};
let args: Vec<String> = env::args().collect();
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
"--matches" => {
cfg.matches = args[i + 1].parse().unwrap_or(cfg.matches);
i += 2;
}
"--seed" => {
cfg.seed = args[i + 1].parse().unwrap_or(cfg.seed);
i += 2;
}
"--out" => {
cfg.out = args[i + 1].clone();
i += 2;
}
"--skill" => {
cfg.skill = args[i + 1].parse().unwrap_or(cfg.skill);
i += 2;
}
"--weapon" => {
cfg.weapon = args[i + 1].parse().unwrap_or(cfg.weapon);
i += 2;
}
"-h" | "--help" => {
println!(
"balance [--matches N] [--seed S] [--out FILE] [--skill 0-100] [--weapon ID]"
);
std::process::exit(0);
}
other => {
eprintln!("unknown argument: {other}");
std::process::exit(2);
}
}
}
cfg
}
}
/// Predicts the absolute vertical error at the target distance.
fn predict_error(dx: f64, dy: f64, angle_deg: f64, power: f64, speed_max: f64, wind: f64) -> f64 {
let theta = angle_deg.to_radians();
let v = power * speed_max;
let vx = v * theta.cos();
let vy = -v * theta.sin();
// Solve 0.5*wind*t^2 + vx*t - dx = 0 for the flight time.
let a = 0.5 * wind;
let b = vx;
let c = -dx;
let t = if a.abs() < 1e-9 {
if b.abs() < 1e-9 {
return f64::INFINITY;
}
-c / b
} else {
let disc = b * b - 4.0 * a * c;
if disc < 0.0 {
return f64::INFINITY;
}
let root = disc.sqrt();
let t1 = (-b + root) / (2.0 * a);
let t2 = (-b - root) / (2.0 * a);
let mut best = f64::INFINITY;
for t in [t1, t2] {
if t > 0.0 && t < best {
best = t;
}
}
best
};
if !t.is_finite() || t <= 0.0 {
return f64::INFINITY;
}
let y = vy * t + 0.5 * GRAVITY * t * t;
(y - dy).abs()
}
/// Picks the angle/power pair with the smallest predicted error, then applies
/// skill-based noise to the inputs.
fn aim(sim: &Sim, player: u8, weapon: u8, skill: f64, rng: &mut Pcg32) -> Option<(u32, Fx)> {
let me = &sim.tanks[player as usize];
let foe = &sim.tanks[1 - player as usize];
let dir = if player == 0 { 1.0 } else { -1.0 };
let dx = (sim::fixed::to_int(foe.x) - sim::fixed::to_int(me.x)) as f64 * dir;
let dy = (sim::fixed::to_int(foe.y) - (sim::fixed::to_int(me.y) - MUZZLE_LEN)) as f64;
let speed_max = sim
.content
.weapon(weapon)
.map(|w| w.speed as f64)
.unwrap_or(20.0);
let wind = sim.wind as f64 * WIND_PER_UNIT * dir;
// Collect feasible solutions. Steep arcs clear hills, so prefer the
// highest angle among the good ones.
let mut feasible: Vec<(f64, f64, f64)> = Vec::new(); // (error, angle, power)
let mut global = (f64::INFINITY, 45.0f64, 0.6f64);
for angle in (30..=80).step_by(4) {
let mut best_for_angle = (f64::INFINITY, 0.6f64);
let mut power = 0.05f64;
while power <= 1.0 {
let error = predict_error(dx, dy, angle as f64, power, speed_max, wind);
if error < best_for_angle.0 {
best_for_angle = (error, power);
}
power += 0.035;
}
let (error, power) = best_for_angle;
if error < global.0 {
global = (error, angle as f64, power);
}
if error < 20.0 {
feasible.push((error, angle as f64, power));
}
}
let best = if feasible.is_empty() {
global
} else {
let mut chosen = feasible[0];
for candidate in feasible.into_iter().skip(1) {
if candidate.1 > chosen.1 {
chosen = candidate;
}
}
chosen
};
if !best.0.is_finite() {
return None;
}
// Skill: 100 = no noise, 0 = +/- 8 degrees and +/- 20% power.
let miss = (100.0 - skill) / 100.0;
let angle_jitter = (rng.next_fx_signed() as f64 / 65536.0) * 6.0 * miss;
let power_jitter = (rng.next_fx_signed() as f64 / 65536.0) * 0.15 * miss;
let angle = (best.1 + angle_jitter).clamp(1.0, 89.0);
let power = (best.2 * (1.0 + power_jitter)).clamp(0.05, 1.0);
Some(((angle * 1000.0) as u32, (power * 65_536.0) as i32))
}
struct Outcome {
seed: u64,
winner: i32,
turns: u16,
ticks: u32,
hp: [i32; 2],
shots: u32,
}
fn play_match(seed: u64, skill: f64, weapon: u8, starter: u8) -> Outcome {
let trace = std::env::var("TRACE").is_ok();
let specs = [
sim::state::TankSpec {
x: 220,
loadout: [1, 2, 5],
},
sim::state::TankSpec {
x: sim::terrain::WORLD_W - 220,
loadout: [1, 3, 4],
},
];
let mut sim = Sim::with_starter(seed, specs, content::Content::builtin(), starter);
let mut rng = Pcg32::new(seed ^ 0xA5A5_5A5A, 99);
let mut shots = 0u32;
while sim.phase != Phase::Finished && sim.turn <= MAX_TURNS {
let player = sim.current_player();
let Some((angle, power)) = aim(&sim, player, weapon, skill, &mut rng) else {
let _ = sim.submit(Command::EndTurn);
run_until_turn_end(&mut sim);
continue;
};
if sim
.submit(Command::Fire {
angle_mdeg: angle,
power,
weapon,
})
.is_err()
{
let _ = sim.submit(Command::EndTurn);
}
shots += 1;
let impact = run_until_turn_end(&mut sim);
if trace && shots <= 6 {
if let Some((ix, iy, dmg)) = impact {
println!(
" shot {shots}: p{player} angle={angle} power={} impact=({ix:.0},{iy:.0}) foe=({},{}) dmg={:?}",
power as f64 / 65536.0,
sim::fixed::to_int(sim.tanks[1 - player as usize].x),
sim::fixed::to_int(sim.tanks[1 - player as usize].y),
dmg
);
} else {
println!(" shot {shots}: no impact event");
}
}
}
Outcome {
seed,
winner: match sim.winner {
Some(0) => 0,
Some(1) => 1,
_ => -1,
},
turns: sim.turn,
ticks: sim.tick,
hp: [sim.tanks[0].hp, sim.tanks[1].hp],
shots,
}
}
fn run_until_turn_end(sim: &mut Sim) -> Option<(f64, f64, [i32; 2])> {
let start_turn = sim.turn;
let mut guard = 0u32;
let mut impact = None;
while sim.phase != Phase::Finished && sim.turn == start_turn && guard < TURN_TICKS * 4 {
let events = sim.tick();
guard += 1;
for event in events {
match event {
Event::Impact { x, y, damage, .. } => {
impact = Some((
sim::fixed::to_int(x) as f64,
sim::fixed::to_int(y) as f64,
damage,
));
}
Event::GameOver { .. } => return impact,
_ => {}
}
}
}
impact
}
fn main() {
let cfg = Config::parse();
let content = sim::state::Sim::default_match(0).content.clone();
let weapon_name = content
.weapon(cfg.weapon)
.map(|w| w.name.clone())
.unwrap_or_else(|| "?".to_string());
println!(
"balance: sim_version={} (not implemented yet, M2)",
sim::SIM_VERSION
"balance: content={} weapons={} skill={} matches={} seed={}",
content.hash(),
content.weapons.len(),
cfg.skill,
cfg.matches,
cfg.seed
);
let file = File::create(&cfg.out).expect("cannot create report file");
let mut out = BufWriter::new(file);
writeln!(out, "seed,winner,turns,ticks,hp0,hp1,shots").unwrap();
let mut wins = [0u32; 3]; // [p0, p1, draw]
let mut total_turns = 0u64;
let mut total_ticks = 0u64;
let started = std::time::Instant::now();
for i in 0..cfg.matches {
let seed = cfg.seed.wrapping_add(i as u64);
let outcome = play_match(seed, cfg.skill, cfg.weapon, (i % 2) as u8);
let slot = match outcome.winner {
0 => 0,
1 => 1,
_ => 2,
};
wins[slot] += 1;
total_turns += outcome.turns as u64;
total_ticks += outcome.ticks as u64;
writeln!(
out,
"{},{},{},{},{},{},{}",
outcome.seed,
outcome.winner,
outcome.turns,
outcome.ticks,
outcome.hp[0],
outcome.hp[1],
outcome.shots
)
.unwrap();
}
out.flush().unwrap();
let n = cfg.matches.max(1) as f64;
let elapsed = started.elapsed().as_secs_f64();
println!("weapon: {weapon_name} (#{})", cfg.weapon);
println!(
"win rate p0={:.1}% p1={:.1}% draw={:.1}%",
wins[0] as f64 / n * 100.0,
wins[1] as f64 / n * 100.0,
wins[2] as f64 / n * 100.0
);
println!(
"avg turns={:.2} avg duration={:.1}s matches/s={:.1}",
total_turns as f64 / n,
total_ticks as f64 / n / 60.0,
n / elapsed
);
println!("report: {} ({:.2}s)", cfg.out, elapsed);
}