Files
airdef/airdef-mod/src/sim/logistics.rs
T
chexit 02f99c31f6
build / mod (push) Successful in 30m51s
Fire P1-SUN on network fire plots, make S-400/S-500 launchers only, give radars own models
Gameplay fixes and art from the owner's balance review of 2026-12-05.

- The P1-SUN never launched (0 launches in 12 seeds of a 196-target raid): it
  has no radar of its own and only a separate launcher could fire on another
  station's plot. A unit without its own radar now fires like one
  (`why::on_network`), on the fresh own fire plot of an engagement or
  multifunction radar within link reach. Seven P1-SUN then launch 26-42 and
  kill 13-24 per raid; the leak count does not change.
- The С-400 and С-500 exist only as separate launchers (`mode: "launcher"` in
  the catalog). The `s400_launcher`/`s500_launcher` variants and their remotes
  are gone: `deploy s400`/`s500` and their remotes place a launcher. A system
  saved with its own radar loads as a launcher; `battery <n> integrated` is
  refused for these kinds.
- Every radar role has its own model: a wide curved array (search), a
  parabolic dish (engagement), a small head on mast sections (height); the
  multifunction radar keeps its panel, the optical post gets its own post and
  a turning head with a lens. A variant may carry its own `parts` in
  `catalog/content.json`; `Sam::parts()` resolves them.
- The enemy remembers the sides each approach raided from: a raid ordered the
  same way and within 200 blocks of the same distance comes from the same
  sides, so its sites stand where the last ones did. A launch area the radars
  fixed is remembered (up to 32): a site placed there again is known before
  its first launch and can be struck at once. Neither is saved yet.
- `sim/balance.rs` flies several raids over one cluster with stocked depots
  (`supply_raids`). With the 16-block depot reach, depots 30 blocks from the
  batteries leave 10 / 36 / 80 leaks over three raids against 6 / 10 / 17 for
  depots within reach; the reach itself is unchanged by decision of the owner.

The saturation checkpoint is re-recorded (123 kills / 323 launches instead of
129 / 344): that loadout has no fire radar, so its С-400/С-500 fire less as
launchers.

Verified: airdef-core release 363 passed and 8 scenarios; airdef-mod 135 passed,
1 boundary, 2 saturation, 5 scenarios; gen_catalog/gen_models/gen_sounds --check;
test_gen_assets, test_model_bounds, test_web_panel; git diff --check. Not run:
the actual WASM contract, the models in game, CI.
Co-Authored-By: ZCode <zcode@localhost>
2026-12-05 23:38:14 +03:00

1457 lines
72 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Empty magazines are replenished from finite typed depot stock, either directly or via a truck.
use super::*;
pub const DEPOT_RM48U_CHANCE: f64 = 0.35;
pub(super) const RELOAD_MISSILE: u8 = 1;
pub(super) const RELOAD_GUN: u8 = 2;
/// Typed air-defence ammunition carried by depots and reload trucks, differentiated per system and weapon channel.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum AmmoKind {
PatriotMissile,
GepardGun,
PantsirMissile,
PantsirGun,
S400Missile,
S500Missile,
IrisTMissile,
NasamsMissile,
BukMissile,
TorMissile,
P1sunMissile,
}
impl AmmoKind {
pub const COUNT: usize = 11;
pub const ALL: [AmmoKind; Self::COUNT] = [
AmmoKind::PatriotMissile,
AmmoKind::GepardGun,
AmmoKind::PantsirMissile,
AmmoKind::PantsirGun,
AmmoKind::S400Missile,
AmmoKind::S500Missile,
AmmoKind::IrisTMissile,
AmmoKind::NasamsMissile,
AmmoKind::BukMissile,
AmmoKind::TorMissile,
AmmoKind::P1sunMissile,
];
pub const fn index(self) -> usize {
self as usize
}
pub const fn key(self) -> &'static str {
match self {
AmmoKind::PatriotMissile => "patriot",
AmmoKind::GepardGun => "gepard_gun",
AmmoKind::PantsirMissile => "pantsir_missile",
AmmoKind::PantsirGun => "pantsir_gun",
AmmoKind::S400Missile => "s400",
AmmoKind::S500Missile => "s500",
AmmoKind::IrisTMissile => "irist",
AmmoKind::NasamsMissile => "nasams",
AmmoKind::BukMissile => "buk",
AmmoKind::TorMissile => "tor",
AmmoKind::P1sunMissile => "p1sun",
}
}
pub fn from_key(key: &str) -> Option<Self> {
Self::ALL.into_iter().find(|k| k.key() == key)
}
pub const fn short_name(self) -> &'static str {
match self {
AmmoKind::PatriotMissile => "Patriot",
AmmoKind::GepardGun => "Гепард пуш",
AmmoKind::PantsirMissile => "Панцирь рак",
AmmoKind::PantsirGun => "Панцирь пуш",
AmmoKind::S400Missile => "С-400",
AmmoKind::S500Missile => "С-500",
AmmoKind::IrisTMissile => "IRIS-T",
AmmoKind::NasamsMissile => "NASAMS",
AmmoKind::BukMissile => "Бук",
AmmoKind::TorMissile => "Тор",
AmmoKind::P1sunMissile => "P1-SUN",
}
}
pub const fn name(self) -> &'static str {
match self {
AmmoKind::PatriotMissile => "Patriot (PAC-3)",
AmmoKind::GepardGun => "Гепард (35 мм)",
AmmoKind::PantsirMissile => "Панцирь (57Э6)",
AmmoKind::PantsirGun => "Панцирь (30 мм)",
AmmoKind::S400Missile => "С-400 (48Н6)",
AmmoKind::S500Missile => "С-500 (77Н6)",
AmmoKind::IrisTMissile => "IRIS-T SLM",
AmmoKind::NasamsMissile => "NASAMS (AMRAAM)",
AmmoKind::BukMissile => "Бук-М2 (9М317)",
AmmoKind::TorMissile => "Тор-М2 (9М338)",
AmmoKind::P1sunMissile => "P1-SUN",
}
}
pub const fn is_gun(self) -> bool {
matches!(self, AmmoKind::GepardGun | AmmoKind::PantsirGun)
}
pub const fn spawn_range(self) -> (u32, u32) {
match self {
AmmoKind::PatriotMissile => (1, 4),
AmmoKind::GepardGun => (2, 6),
AmmoKind::PantsirMissile => (1, 5),
AmmoKind::PantsirGun => (2, 6),
AmmoKind::S400Missile => (1, 4),
AmmoKind::S500Missile => (1, 3),
AmmoKind::IrisTMissile => (1, 4),
AmmoKind::NasamsMissile => (1, 4),
AmmoKind::BukMissile => (1, 4),
AmmoKind::TorMissile => (2, 5),
AmmoKind::P1sunMissile => (2, 6),
}
}
pub const fn blast_charge(self) -> f64 {
match self {
AmmoKind::S500Missile => 2.2,
AmmoKind::S400Missile => 1.8,
AmmoKind::PatriotMissile => 1.4,
AmmoKind::BukMissile => 1.1,
AmmoKind::IrisTMissile | AmmoKind::NasamsMissile => 0.9,
AmmoKind::TorMissile | AmmoKind::PantsirMissile => 0.8,
AmmoKind::GepardGun => 0.35,
AmmoKind::PantsirGun => 0.3,
AmmoKind::P1sunMissile => 0.25,
}
}
}
/// Per-type air-defence reload stock stored at a depot or carried on a TZM.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct AmmoStock(pub [u32; AmmoKind::COUNT]);
impl AmmoStock {
/// Deterministic stock used by `Sam::new(Depot)` when not deployed with a random roll.
pub const fn new_default_depot() -> Self {
Self([3; AmmoKind::COUNT])
}
/// Distributes a legacy untyped `cargo` count across all `AmmoKind`s for backward-compatible save loading.
pub fn from_legacy_cargo(cargo: u32) -> Self {
let base = cargo / AmmoKind::COUNT as u32;
let rem = cargo % AmmoKind::COUNT as u32;
let mut counts = [base; AmmoKind::COUNT];
for (i, c) in counts.iter_mut().enumerate() {
if (i as u32) < rem {
*c += 1;
}
}
Self(counts)
}
/// Rolls random stock for each system/weapon channel plus a probabilistic RM48U strike allocation.
pub fn roll(rng: &mut Rng) -> (Self, u32) {
let mut stock = Self::default();
for kind in AmmoKind::ALL {
let (lo, hi) = kind.spawn_range();
let span = hi - lo + 1;
let n = lo + ((rng.f() * span as f64) as u32).min(span - 1);
stock.set(kind, n);
}
let rm48u = if rng.chance(DEPOT_RM48U_CHANCE) {
if rng.chance(0.30) { 2 } else { 1 }
} else {
0
};
(stock, rm48u)
}
pub const fn get(self, kind: AmmoKind) -> u32 {
self.0[kind.index()]
}
pub fn set(&mut self, kind: AmmoKind, n: u32) {
self.0[kind.index()] = n.min(STOCK_LIMIT);
}
pub fn add(&mut self, kind: AmmoKind, n: u32) -> Option<u32> {
let total = self.total();
let room = STOCK_LIMIT.saturating_sub(total);
let added = n.min(room);
self.0[kind.index()] = self.0[kind.index()].saturating_add(added);
(added > 0 || n == 0).then_some(added)
}
pub fn take(&mut self, kind: AmmoKind, n: u32) -> u32 {
let taken = self.0[kind.index()].min(n);
self.0[kind.index()] -= taken;
taken
}
pub fn total(self) -> u32 {
self.0.iter().copied().sum()
}
pub fn is_empty(self) -> bool {
self.0.iter().all(|&n| n == 0)
}
pub fn non_zero(self) -> impl Iterator<Item = (AmmoKind, u32)> {
AmmoKind::ALL
.into_iter()
.filter_map(move |k| {
let n = self.get(k);
(n > 0).then_some((k, n))
})
}
pub fn save_text(self) -> String {
let parts: Vec<String> = self.non_zero().map(|(k, n)| format!("{}={n}", k.key())).collect();
if parts.is_empty() { "-".into() } else { parts.join(" ") }
}
/// Combined secondary detonation yield for all typed ammunition packs stored in a depot or truck.
pub fn blast_charge(self) -> f64 {
AmmoKind::ALL
.into_iter()
.map(|k| f64::from(self.get(k)) * k.blast_charge())
.sum()
}
}
impl Sim {
/// Rolls random per-complex ammunition and probabilistic RM48U stock when deploying a depot.
pub fn roll_depot_stock(&mut self, sam: &mut Sam) {
if sam.kind != SamKind::Depot {
return;
}
let (stock, rm48u) = AmmoStock::roll(&mut self.rng);
sam.ammo_stock = stock;
sam.sync_cargo();
sam.ground_stock = rm48u;
}
/// Prepare one explicitly typed round at a nearby living depot. Any displaced air round is retained there.
pub fn load_ground_round(&mut self, i: usize) -> Result<String, String> {
let s = self.sams.get(i).ok_or("Нет такого комплекса")?;
if !s.kind.supports_rm48u() { return Err("Для этого комплекса нет игрового профиля RM48U".into()); }
if !s.alive() || s.moving() || s.preparing.is_some() || s.reloading > 0 || s.part(Part::Launcher) <= 0.0 {
return Err("Комплекс должен быть исправен и развёрнут".into());
}
if s.ground_return { return Err("Сначала отмените заявку на вывоз RM48U".into()); }
if s.ground_rounds >= s.cells() { return Err("Нет свободной ячейки для RM48U".into()); }
let depot = self.sams.iter().enumerate().filter(|(_, d)| d.kind == SamKind::Depot && d.alive() && d.ground_stock > 0 && d.pos.distance(s.pos) < DEPOT_REACH)
.min_by(|(_, a), (_, b)| a.pos.distance(s.pos).total_cmp(&b.pos.distance(s.pos)).then(a.id.cmp(&b.id)))
.map(|(j, _)| j);
let Some(depot) = depot else {
if s.ground_request { return Err("Заявка RM48U уже ожидает ТЗМ".into()); }
if !self.sams.iter().any(|d| d.alive() && ((d.kind == SamKind::Depot && d.ground_stock > 0) || (d.kind == SamKind::Tzm && d.ground_stock > 0))) {
if let Some((j, _)) = self.sams.iter().enumerate().find(|(_, d)| d.kind == SamKind::Depot && d.alive() && d.pos.distance(s.pos) < DEPOT_REACH) {
return Err(format!("Склад №{} рядом, но RM48U: 0. Задайте запас: /airdef ground-stock {} <количество>", j + 1, j + 1));
}
return Err(format!("Нет живого склада с RM48U рядом ({:.0} блоков)", DEPOT_REACH));
}
if !self.sams.iter().any(|t| t.kind == SamKind::Tzm && t.alive()) { return Err("Для доставки RM48U нужна исправная ТЗМ".into()); }
self.sams[i].ground_request = true;
self.sams[i].auto_ground_request = false;
return Ok(format!("С-400 №{}: заявка RM48U ожидает доставки ТЗМ", i + 1));
};
let displaced = u32::from(self.sams[i].missiles + self.sams[i].ground_rounds >= self.sams[i].cells());
let air_48n6_stock = self.sams[depot].air_48n6_stock.checked_add(displaced).ok_or("Запас склада переполнен")?;
self.sams[i].missiles -= displaced;
self.sams[i].ground_rounds += 1;
self.sams[i].ground_request = false;
self.sams[i].auto_ground_request = false;
if self.sams[i].ground_rounds >= self.sams[i].cells() && self.sams[i].kind.spec().gun.is_none() { self.sams[i].empty = false; }
self.sams[depot].ground_stock -= 1;
self.sams[depot].air_48n6_stock = air_48n6_stock;
Ok(format!("С-400 №{}: загружена RM48U (игровой профиль), ударных {}, ПВО {}; на складе RM48U {}, снятых ракет ПВО {}", i + 1, self.sams[i].ground_rounds, self.sams[i].missiles, self.sams[depot].ground_stock, self.sams[depot].air_48n6_stock))
}
/// Return a loaded ground round to a nearby depot; restore a previously removed air round if available.
pub fn unload_ground_round(&mut self, i: usize) -> Result<String, String> {
let s = self.sams.get(i).ok_or("Нет такого комплекса")?;
if !s.kind.supports_rm48u() || !s.alive() || s.moving() || s.preparing.is_some() || s.reloading > 0 || s.part(Part::Launcher) <= 0.0 || s.ground_rounds == 0 {
return Err("Нужен исправный развёрнутый С-400 с загруженной RM48U".into());
}
if s.ground_return { return Err("Заявка на вывоз RM48U уже ожидает ТЗМ".into()); }
let depot = self.sams.iter().enumerate().filter(|(_, d)| d.kind == SamKind::Depot && d.alive() && d.pos.distance(s.pos) < DEPOT_REACH)
.min_by(|(_, a), (_, b)| a.pos.distance(s.pos).total_cmp(&b.pos.distance(s.pos)).then(a.id.cmp(&b.id)))
.map(|(j, _)| j);
let Some(depot) = depot else {
if s.ground_request { return Err("Сначала отмените заявку на доставку RM48U".into()); }
if !self.sams.iter().any(|d| d.kind == SamKind::Depot && d.alive() && d.ground_stock < STOCK_LIMIT) { return Err("Нет доступного склада для возврата RM48U".into()); }
if !self.sams.iter().any(|t| t.kind == SamKind::Tzm && t.alive() && t.drive_speed() > 0.0 && t.ground_stock.saturating_add(t.air_48n6_stock) < TRUCK_LOAD) { return Err("Нет исправной ТЗМ со свободным местом для RM48U".into()); }
self.sams[i].ground_return = true;
return Ok(format!("С-400 №{}: RM48U зарезервирована, ожидается вывоз ТЗМ", i + 1));
};
let stock = self.sams[depot].ground_stock.checked_add(1).filter(|n| *n <= STOCK_LIMIT).ok_or("Запас склада переполнен")?;
self.sams[i].ground_rounds -= 1;
self.sams[depot].ground_stock = stock;
if self.sams[depot].air_48n6_stock > 0 {
self.sams[depot].air_48n6_stock -= 1;
self.sams[i].missiles += 1;
}
Ok(format!("С-400 №{}: выгружена RM48U; ударных {}, ПВО {}", i + 1, self.sams[i].ground_rounds, self.sams[i].missiles))
}
pub fn cancel_ground_request(&mut self, i: usize) -> Result<String, String> {
let s = self.sams.get_mut(i).ok_or("Нет такого комплекса")?;
if !s.kind.supports_rm48u() || (!s.ground_request && !s.ground_return) { return Err("Нет ожидающей заявки RM48U".into()); }
s.ground_request = false;
s.auto_ground_request = false;
s.ground_return = false;
Ok(format!("С-400 №{}: заявка RM48U отменена", i + 1))
}
/// Reloads from depots near the systems, and the trucks' rounds.
pub(super) fn step_supply(&mut self, out: &mut Out) {
let now = self.tick;
// Systems by a depot reload directly from matching typed stock.
for i in 0..self.sams.len() {
let s = &self.sams[i];
if !s.empty || !s.alive() || s.moving() || s.reloading > 0 {
continue;
}
let pos = s.pos;
let (need_m, need_g) = s.needed_ammo();
let mut mask = 0u8;
if let Some(mk) = need_m
&& let Some(d) = self
.sams
.iter()
.enumerate()
.filter(|(_, d)| d.kind == SamKind::Depot && d.alive() && d.ammo_stock.get(mk) > 0 && d.pos.distance(pos) < DEPOT_REACH)
.min_by(|(_, a), (_, b)| a.pos.distance(pos).total_cmp(&b.pos.distance(pos)).then(a.id.cmp(&b.id)))
.map(|(j, _)| j)
{
self.sams[d].ammo_stock.take(mk, 1);
self.sams[d].sync_cargo();
mask |= RELOAD_MISSILE;
}
if let Some(gk) = need_g
&& let Some(d) = self
.sams
.iter()
.enumerate()
.filter(|(_, d)| d.kind == SamKind::Depot && d.alive() && d.ammo_stock.get(gk) > 0 && d.pos.distance(pos) < DEPOT_REACH)
.min_by(|(_, a), (_, b)| a.pos.distance(pos).total_cmp(&b.pos.distance(pos)).then(a.id.cmp(&b.id)))
.map(|(j, _)| j)
{
self.sams[d].ammo_stock.take(gk, 1);
self.sams[d].sync_cargo();
mask |= RELOAD_GUN;
}
if mask != 0 {
self.reload_weapons(i, mask, out);
}
}
// A destroyed truck drops its job, for another to take.
for s in self.sams.iter_mut().filter(|s| s.kind == SamKind::Tzm && !s.alive()) {
s.job = None;
}
let has_waiting = self.sams.iter().any(|s| s.empty && s.alive() && !s.moving() && s.reloading == 0);
let has_truck = self.sams.iter().any(|t| t.kind == SamKind::Tzm && t.alive() && !t.moving() && t.drive_speed() > 0.0);
let network_tracks: Vec<(DVec3, ClassEst)> = if has_waiting && has_truck {
self.picture().values().map(|trk| (trk.est(now), trk.class)).collect()
} else {
Vec::new()
};
// The trucks: a job each, when idle.
for t in 0..self.sams.len() {
let truck = &self.sams[t];
if truck.kind != SamKind::Tzm || !truck.alive() || truck.moving() || truck.drive_speed() <= 0.0 || now % 10 != t as u64 % 10 {
continue;
}
let at = truck.pos;
let truck_id = truck.id;
// A return is picked up physically; its cargo remains marked until a depot accepts it.
// The return keeps its priority only while it can actually proceed (#128): a carrier
// holding a reserved round needs a depot with room in reach, an empty one a system
// ready to hand a round over (whole, deployed, not claimed by another truck, a
// reachable route). A return that is merely claimed but impossible used to clear the
// job and stop the truck, starving independent supply requests; the claim now stays
// untouched and only real RM48U demand pulls the truck away from its watch.
let return_cargo = truck.return_cargo && truck.ground_stock > 0;
let can_pick = truck.ground_stock == 0 && truck.air_48n6_stock < TRUCK_LOAD;
let claim_pending = return_cargo || (can_pick && self.sams.iter().any(|s| s.kind.supports_rm48u() && s.alive() && s.ground_return));
let taken: Vec<u32> = self.sams.iter().filter(|s| s.kind == SamKind::Tzm && s.alive() && s.id != truck_id).filter_map(|s| s.job).collect();
let target = if return_cargo {
self.sams.iter().filter(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock < STOCK_LIMIT && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
} else if can_pick {
self.sams.iter().filter(|s| s.kind.supports_rm48u() && s.alive() && s.ground_return && s.ground_rounds > 0 && !s.moving() && s.preparing.is_none() && s.reloading == 0 && s.part(Part::Launcher) > 0.0 && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
} else {
None
}.map(|s| (s.id, s.pos));
if let Some((id, to)) = target {
self.sams[t].job = Some(id);
if at.distance(to) > HANDOVER {
self.order_move_near(t, to, HANDOVER - 0.75);
} else if let Some(j) = self.sams.iter().position(|s| s.id == id) {
if self.sams[t].return_cargo {
self.sams[j].ground_stock += 1;
self.sams[t].ground_stock -= 1;
self.sams[t].return_cargo = false;
} else {
self.sams[j].ground_rounds -= 1;
self.sams[j].ground_return = false;
self.sams[t].ground_stock += 1;
self.sams[t].return_cargo = true;
if self.sams[t].air_48n6_stock > 0 && self.sams[j].missiles + self.sams[j].ground_rounds < self.sams[j].cells() {
self.sams[t].air_48n6_stock -= 1;
self.sams[j].missiles += 1;
}
}
self.sams[t].job = None;
out.sound("minecraft:block.piston.extend", at, 1.5, 0.8);
}
continue;
}
if claim_pending {
// The impossible return still outranks a mere stock run: without RM48U demand
// the truck holds its watch (and drops a stale job) exactly as before.
let supply_demand = (self.sams[t].ground_stock > 0 && self.sams.iter().any(|s| s.alive() && s.ground_request))
|| (self.sams.iter().any(|s| s.kind.supports_rm48u() && s.alive() && s.ground_request)
&& self.sams.iter().any(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock > 0));
if !supply_demand {
self.sams[t].job = None;
continue;
}
}
// Typed strike cargo takes precedence over generic reloads. Jobs are reconstructed
// after loading a save; the request and physical cargo survive independently.
let typed_work = truck.ground_stock > 0 || truck.air_48n6_stock > 0 ||
(self.sams.iter().any(|s| s.kind.supports_rm48u() && s.alive() && s.ground_request)
&& self.sams.iter().any(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock > 0));
if typed_work {
if let Some(id) = self.sams[t].job {
let valid = self.sams.iter().find(|s| s.id == id).is_some_and(|s| s.alive() && !self.routes.out_of_reach(truck_id, s.id, now) && (s.kind == SamKind::Depot || (self.sams[t].ground_stock > 0 && s.kind.supports_rm48u() && s.ground_request)));
if !valid { self.sams[t].job = None; }
}
if let Some(id) = self.sams[t].job {
if let Some(j) = self.sams.iter().position(|s| s.id == id && s.alive()) {
if self.sams[j].pos.distance(at) <= HANDOVER {
if self.sams[j].kind == SamKind::Depot {
if let Some(n) = self.sams[j].air_48n6_stock.checked_add(self.sams[t].air_48n6_stock) {
self.sams[j].air_48n6_stock = n;
self.sams[t].air_48n6_stock = 0;
}
if self.sams[t].ground_stock > 0 && !self.sams.iter().any(|s| s.alive() && s.ground_request) && self.sams[j].ground_stock < STOCK_LIMIT {
let take = self.sams[t].ground_stock.min(STOCK_LIMIT - self.sams[j].ground_stock);
self.sams[j].ground_stock += take;
self.sams[t].ground_stock -= take;
// The last reserved round left the truck: nothing marks as return cargo any more.
if self.sams[t].ground_stock == 0 { self.sams[t].return_cargo = false; }
}
if self.sams[t].ground_stock == 0 && self.sams[j].ground_stock > 0 && self.sams[t].air_48n6_stock == 0 && self.sams.iter().any(|s| s.kind.supports_rm48u() && s.alive() && s.ground_request) {
self.sams[j].ground_stock -= 1;
self.sams[t].ground_stock += 1;
}
} else if self.sams[j].kind.supports_rm48u() && self.sams[j].ground_request && !self.sams[j].moving() && self.sams[j].preparing.is_none() && self.sams[j].reloading == 0 && self.sams[j].part(Part::Launcher) > 0.0 && self.sams[j].ground_rounds < self.sams[j].cells() && self.sams[t].ground_stock > 0 {
let displaced = u32::from(self.sams[j].missiles + self.sams[j].ground_rounds >= self.sams[j].cells());
self.sams[j].missiles -= displaced;
self.sams[j].ground_rounds += 1;
if self.sams[j].ground_rounds >= self.sams[j].cells() && self.sams[j].kind.spec().gun.is_none() { self.sams[j].empty = false; }
self.sams[j].ground_request = false;
self.sams[j].auto_ground_request = false;
self.sams[t].ground_stock -= 1;
// A round reserved for return redirected to a waiting request is no
// longer return cargo once the last one leaves the truck (#128).
if self.sams[t].ground_stock == 0 { self.sams[t].return_cargo = false; }
self.sams[t].air_48n6_stock += displaced;
out.sound("minecraft:block.piston.extend", at, 1.5, 0.8);
}
self.sams[t].job = None;
} else {
let to = self.sams[j].pos;
self.order_move_near(t, to, HANDOVER - 0.75);
continue;
}
} else { self.sams[t].job = None; }
}
let taken: Vec<u32> = self.sams.iter().filter(|s| s.kind == SamKind::Tzm && s.alive() && s.id != truck_id).filter_map(|s| s.job).collect();
let next = if self.sams[t].ground_stock > 0 && self.sams.iter().any(|s| s.alive() && s.ground_request) {
self.sams.iter().filter(|s| s.kind.supports_rm48u() && s.alive() && s.ground_request && !s.moving() && s.preparing.is_none() && s.reloading == 0 && s.part(Part::Launcher) > 0.0 && s.ground_rounds < s.cells() && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
} else {
self.sams.iter().filter(|s| s.kind == SamKind::Depot && s.alive() && (self.sams[t].air_48n6_stock > 0 || (self.sams[t].ground_stock > 0 && s.ground_stock < STOCK_LIMIT) || (self.sams[t].ground_stock == 0 && s.ground_stock > 0)) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at)))
}.map(|s| (s.id, s.pos));
if let Some((id, to)) = next {
self.sams[t].job = Some(id);
if to.distance(at) > HANDOVER { self.order_move_near(t, to, HANDOVER - 0.75); }
}
continue;
}
// Priority 3: typed air-defence resupply.
let taken: Vec<u32> = self.sams.iter().filter(|s| s.kind == SamKind::Tzm && s.alive() && s.id != truck_id).filter_map(|s| s.job).collect();
let waiting = self.waiting_needs(truck_id, at, now, &taken, &network_tracks);
let demand = demand_totals(&waiting);
if let Some(job) = truck.job {
let Some(j) = self.sams.iter().position(|s| s.id == job && s.alive()) else {
self.sams[t].job = None;
continue;
};
if self.sams[j].pos.distance(at) <= HANDOVER {
if self.sams[j].kind == SamKind::Depot {
let mut moved = false;
// Unload any cargo not needed by reachable waiting systems (or exceeding total demand).
for kind in AmmoKind::ALL {
let have = self.sams[t].ammo_stock.get(kind);
let excess = have.saturating_sub(demand[kind.index()]);
if excess > 0 {
let put = self.sams[j].ammo_stock.add(kind, excess).unwrap_or(0);
if put > 0 {
self.sams[t].ammo_stock.take(kind, put);
moved = true;
}
}
}
// Load needed ammunition kinds in order of nearest waiting systems up to TRUCK_LOAD.
'fill: for (_, _, _, needs) in &waiting {
for kind in needs.into_iter().flatten() {
if self.sams[t].ammo_stock.total() >= TRUCK_LOAD {
break 'fill;
}
let carried = self.sams[t].ammo_stock.get(*kind);
if carried < demand[kind.index()] && self.sams[j].ammo_stock.get(*kind) > 0 {
let taken_n = self.sams[j].ammo_stock.take(*kind, 1);
if taken_n > 0 {
self.sams[t].ammo_stock.add(*kind, taken_n);
moved = true;
}
}
}
}
self.sams[j].sync_cargo();
self.sams[t].sync_cargo();
if moved {
out.sound("minecraft:block.piston.extend", at, 1.5, 0.8);
}
} else if self.sams[j].empty && self.sams[j].alive() && !self.sams[j].moving() && self.sams[j].reloading == 0 {
let (need_m, need_g) = self.sams[j].needed_ammo();
let mut mask = 0u8;
if let Some(mk) = need_m && self.sams[t].ammo_stock.take(mk, 1) > 0 {
mask |= RELOAD_MISSILE;
}
if let Some(gk) = need_g && self.sams[t].ammo_stock.take(gk, 1) > 0 {
mask |= RELOAD_GUN;
}
self.sams[t].sync_cargo();
if mask != 0 {
self.reload_weapons(j, mask, out);
}
}
self.sams[t].job = None;
} else if self.sams[j].kind == SamKind::Depot {
let depot = &self.sams[j];
let can_fetch = self.sams[t].ammo_stock.total() < TRUCK_LOAD
&& AmmoKind::ALL.into_iter().any(|k| demand[k.index()] > self.sams[t].ammo_stock.get(k) && depot.ammo_stock.get(k) > 0);
let can_drop = depot.ammo_stock.total() < STOCK_LIMIT
&& AmmoKind::ALL.into_iter().any(|k| self.sams[t].ammo_stock.get(k) > demand[k.index()]);
if !self.routes.out_of_reach(truck_id, depot.id, now) && (can_fetch || can_drop) {
let to = depot.pos;
self.order_move_near(t, to, HANDOVER - 0.75);
continue;
}
self.sams[t].job = None;
} else {
let target_sam = &self.sams[j];
let (need_m, need_g) = target_sam.needed_ammo();
let has_needed = [need_m, need_g].into_iter().flatten().any(|k| self.sams[t].ammo_stock.get(k) > 0);
if target_sam.empty && target_sam.reloading == 0 && !target_sam.moving() && has_needed && !self.routes.out_of_reach(truck_id, target_sam.id, now) {
// Stopped short of it (it drove off meanwhile): on to where it stands now.
let to = target_sam.pos;
self.order_move_near(t, to, HANDOVER - 0.75);
continue;
}
self.sams[t].job = None;
}
}
// A new job: deliver carried matching ammo first, else fetch needed ammo (or drop unneeded cargo) at a depot.
let truck_stock = self.sams[t].ammo_stock;
let next = waiting
.iter()
.find(|(_, _, _, needs)| needs.into_iter().flatten().any(|k| truck_stock.get(*k) > 0))
.map(|&(id, pos, _, _)| (id, pos));
let next = next.or_else(|| {
let any_demand = demand.iter().any(|&d| d > 0);
if truck_stock.total() < TRUCK_LOAD && any_demand {
self.sams
.iter()
.filter(|d| d.kind == SamKind::Depot && d.alive() && !self.routes.out_of_reach(truck_id, d.id, now))
.filter_map(|d| {
let rank = waiting.iter().position(|(_, _, _, needs)| {
needs
.into_iter()
.flatten()
.any(|k| demand[k.index()] > truck_stock.get(*k) && d.ammo_stock.get(*k) > 0)
})?;
Some((rank, d))
})
.min_by(|(ra, da), (rb, db)| {
ra.cmp(rb)
.then_with(|| da.pos.distance(at).total_cmp(&db.pos.distance(at)))
.then_with(|| da.id.cmp(&db.id))
})
.map(|(_, d)| (d.id, d.pos))
} else if truck_stock.total() >= TRUCK_LOAD && AmmoKind::ALL.into_iter().any(|k| truck_stock.get(k) > demand[k.index()]) {
self.sams
.iter()
.filter(|d| d.kind == SamKind::Depot && d.alive() && d.ammo_stock.total() < STOCK_LIMIT && !self.routes.out_of_reach(truck_id, d.id, now))
.min_by(|a, b| a.pos.distance(at).total_cmp(&b.pos.distance(at)).then(a.id.cmp(&b.id)))
.map(|d| (d.id, d.pos))
} else {
None
}
});
if let Some((id, to)) = next {
self.sams[t].job = Some(id);
// Stop beside it, not on it.
if to.distance(at) > HANDOVER {
self.order_move_near(t, to, HANDOVER - 0.75);
}
}
}
}
/// Reachable waiting systems prioritized by active network threat matching their roles, whether both channels are dry, and distance.
fn waiting_needs(
&self,
truck_id: u32,
at: DVec3,
now: u64,
taken: &[u32],
tracks: &[(DVec3, ClassEst)],
) -> Vec<(u32, DVec3, f64, [Option<AmmoKind>; 2])> {
let mut ranked: Vec<_> = self
.sams
.iter()
.filter(|s| s.empty && s.alive() && !s.moving() && s.reloading == 0 && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now))
.filter_map(|s| {
let (m, g) = s.needed_ammo();
if m.is_none() && g.is_none() {
return None;
}
let range_limit = s.kind.range() * 1.25;
let mut threat_tier = 2u8;
for &(tpos, tclass) in tracks {
let matches = match tclass {
ClassEst::Firm(c) | ClassEst::Probable(c) => (s.roles & c.bit()) != 0,
ClassEst::Unknown => s.roles != 0,
};
if !matches {
continue;
}
if horizontal(tpos - s.pos).length() <= range_limit {
threat_tier = 0;
break;
}
threat_tier = threat_tier.min(1);
}
let dry_tier = u8::from(s.missiles > 0 || s.bursts > 0);
Some((threat_tier, dry_tier, s.pos.distance(at), s.id, s.pos, [m, g]))
})
.collect();
ranked.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)).then_with(|| a.2.total_cmp(&b.2)).then(a.3.cmp(&b.3)));
ranked.into_iter().map(|(_, _, d, id, pos, needs)| (id, pos, d, needs)).collect()
}
/// System `i` begins reloading the specified weapon channels (`RELOAD_MISSILE | RELOAD_GUN`).
fn reload_weapons(&mut self, i: usize, mask: u8, out: &mut Out) {
let sam = &mut self.sams[i];
sam.empty = false;
sam.reload_mask = mask;
sam.reloading = sam.reload_time();
out.sound("minecraft:block.piston.extend", sam.pos, 2.0, 0.6);
}
}
/// Why an armed unit is currently waiting for ammunition or actively resupplying.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SupplyStatus {
Reloading { ticks_left: u32 },
TruckEnRoute { truck_num: usize, truck_id: u32, eta_ticks: u32, rm48u: bool, returning: bool },
TruckFetching { truck_num: usize, truck_id: u32, depot_num: usize, eta_ticks: u32, rm48u: bool },
NoRm48uStock,
OutOfStock { missing: [Option<AmmoKind>; 2] },
NoTruck { rm48u: bool },
RouteBlocked { rm48u: bool },
WaitingForTruck { rm48u: bool, returning: bool },
}
/// Aggregate ammunition & logistics state across all live depots, trucks, and batteries.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SupplySummary {
pub depots_alive: u32,
pub trucks_alive: u32,
pub trucks_busy: u32,
pub waiting_ammo: u32,
pub waiting_rm48u: u32,
pub reloading: u32,
pub rm48u_depot: u32,
pub rm48u_truck: u32,
pub rm48u_loaded: u32,
pub depot_ammo: [u32; AmmoKind::COUNT],
pub truck_ammo: [u32; AmmoKind::COUNT],
}
impl SupplySummary {
pub fn total_for(&self, kind: AmmoKind) -> u32 {
self.depot_ammo[kind.index()] + self.truck_ammo[kind.index()]
}
pub fn depot_total(&self) -> u32 {
self.depot_ammo.iter().sum::<u32>() + self.rm48u_depot
}
}
fn truck_eta_ticks(sim: &Sim, truck: &Sam, dest: DVec3) -> u32 {
let dist = sim.routes.remaining_distance(truck.id, truck.pos, dest);
let speed = truck.drive_speed().max(0.05);
let travel = (dist / speed).ceil() as u32;
let march = if truck.state == SamState::Packing {
truck.march
} else if truck.state != SamState::Moving && dist > HANDOVER {
SamKind::Tzm.march_ticks()
} else {
0
};
march + travel
}
fn fetch_eta_ticks(sim: &Sim, truck: &Sam, depot: &Sam, target: DVec3) -> u32 {
let leg1 = sim.routes.remaining_distance(truck.id, truck.pos, depot.pos);
let leg2 = (depot.pos.distance(target) - HANDOVER).max(0.0);
let speed = truck.drive_speed().max(0.05);
let march1 = if truck.state == SamState::Packing {
truck.march
} else if truck.state != SamState::Moving && leg1 > HANDOVER {
SamKind::Tzm.march_ticks()
} else {
0
};
let march2 = if leg2 > 0.0 { SamKind::Tzm.march_ticks() } else { 0 };
march1 + march2 + ((leg1 + leg2) / speed).ceil() as u32
}
impl Sim {
/// Aggregate logistics inventory and delivery queues across live units.
pub fn supply_summary(&self) -> SupplySummary {
let mut out = SupplySummary::default();
for sam in &self.sams {
if !sam.alive() {
continue;
}
match sam.kind {
SamKind::Depot => {
out.depots_alive += 1;
out.rm48u_depot += sam.ground_stock;
for kind in AmmoKind::ALL {
out.depot_ammo[kind.index()] += sam.ammo_stock.get(kind);
}
}
SamKind::Tzm => {
out.trucks_alive += 1;
if sam.job.is_some() {
out.trucks_busy += 1;
}
out.rm48u_truck += sam.ground_stock;
for kind in AmmoKind::ALL {
out.truck_ammo[kind.index()] += sam.ammo_stock.get(kind);
}
}
kind if kind.armed() => {
if sam.reloading > 0 {
out.reloading += 1;
} else if sam.empty {
out.waiting_ammo += 1;
}
if sam.ground_request || sam.ground_return {
out.waiting_rm48u += 1;
}
if kind.supports_rm48u() {
out.rm48u_loaded += sam.ground_rounds;
}
}
_ => {}
}
}
out
}
/// Explains why armed unit `i` is reloading or waiting for ammunition / RM48U delivery.
pub fn supply_status(&self, i: usize) -> Option<SupplyStatus> {
let sam = self.sams.get(i)?;
if !sam.alive() || !sam.kind.armed() {
return None;
}
if sam.reloading > 0 {
return Some(SupplyStatus::Reloading { ticks_left: sam.reloading });
}
let now = self.tick;
let mobile_trucks = self
.sams
.iter()
.filter(|t| t.kind == SamKind::Tzm && t.alive() && t.drive_speed() > 0.0)
.count();
if sam.ground_return {
if let Some((t_idx, truck)) = self
.sams
.iter()
.enumerate()
.find(|(_, t)| t.kind == SamKind::Tzm && t.alive() && t.job == Some(sam.id))
{
return Some(SupplyStatus::TruckEnRoute {
truck_num: t_idx + 1,
truck_id: truck.id,
eta_ticks: truck_eta_ticks(self, truck, sam.pos),
rm48u: true,
returning: true,
});
}
if mobile_trucks == 0 {
return Some(SupplyStatus::NoTruck { rm48u: true });
}
let all_blocked = self
.sams
.iter()
.filter(|t| t.kind == SamKind::Tzm && t.alive() && t.drive_speed() > 0.0)
.all(|t| self.routes.out_of_reach(t.id, sam.id, now));
return Some(if all_blocked {
SupplyStatus::RouteBlocked { rm48u: true }
} else {
SupplyStatus::WaitingForTruck { rm48u: true, returning: true }
});
}
if sam.ground_request {
if let Some((t_idx, truck)) = self
.sams
.iter()
.enumerate()
.find(|(_, t)| t.kind == SamKind::Tzm && t.alive() && t.job == Some(sam.id))
{
return Some(SupplyStatus::TruckEnRoute {
truck_num: t_idx + 1,
truck_id: truck.id,
eta_ticks: truck_eta_ticks(self, truck, sam.pos),
rm48u: true,
returning: false,
});
}
if let Some((t_idx, truck, d_idx, depot)) = self.sams.iter().enumerate().find_map(|(ti, t)| {
if t.kind != SamKind::Tzm || !t.alive() || t.ground_stock > 0 {
return None;
}
let job = t.job?;
let (di, d) = self.sams.iter().enumerate().find(|(_, d)| d.id == job && d.kind == SamKind::Depot && d.alive() && d.ground_stock > 0)?;
Some((ti, t, di, d))
}) {
return Some(SupplyStatus::TruckFetching {
truck_num: t_idx + 1,
truck_id: truck.id,
depot_num: d_idx + 1,
eta_ticks: fetch_eta_ticks(self, truck, depot, sam.pos),
rm48u: true,
});
}
let has_rm48u = self
.sams
.iter()
.any(|s| s.alive() && matches!(s.kind, SamKind::Depot | SamKind::Tzm) && s.ground_stock > 0);
if !has_rm48u {
return Some(SupplyStatus::NoRm48uStock);
}
if mobile_trucks == 0 {
return Some(SupplyStatus::NoTruck { rm48u: true });
}
let all_blocked = self
.sams
.iter()
.filter(|t| t.kind == SamKind::Tzm && t.alive() && t.drive_speed() > 0.0)
.all(|t| self.routes.out_of_reach(t.id, sam.id, now));
return Some(if all_blocked {
SupplyStatus::RouteBlocked { rm48u: true }
} else {
SupplyStatus::WaitingForTruck { rm48u: true, returning: false }
});
}
if sam.empty {
let (need_m, need_g) = sam.needed_ammo();
let needs = [need_m, need_g];
if need_m.is_none() && need_g.is_none() {
return None;
}
if let Some((t_idx, truck)) = self
.sams
.iter()
.enumerate()
.find(|(_, t)| t.kind == SamKind::Tzm && t.alive() && t.job == Some(sam.id))
{
return Some(SupplyStatus::TruckEnRoute {
truck_num: t_idx + 1,
truck_id: truck.id,
eta_ticks: truck_eta_ticks(self, truck, sam.pos),
rm48u: false,
returning: false,
});
}
if let Some((t_idx, truck, d_idx, depot)) = self.sams.iter().enumerate().find_map(|(ti, t)| {
if t.kind != SamKind::Tzm || !t.alive() || t.ammo_stock.total() >= TRUCK_LOAD {
return None;
}
let job = t.job?;
let (di, d) = self.sams.iter().enumerate().find(|(_, d)| {
d.id == job
&& d.kind == SamKind::Depot
&& d.alive()
&& needs.into_iter().flatten().any(|k| d.ammo_stock.get(k) > 0)
})?;
Some((ti, t, di, d))
}) {
return Some(SupplyStatus::TruckFetching {
truck_num: t_idx + 1,
truck_id: truck.id,
depot_num: d_idx + 1,
eta_ticks: fetch_eta_ticks(self, truck, depot, sam.pos),
rm48u: false,
});
}
let has_stock = self.sams.iter().any(|s| {
s.alive()
&& matches!(s.kind, SamKind::Depot | SamKind::Tzm)
&& needs.into_iter().flatten().any(|k| s.ammo_stock.get(k) > 0)
});
if !has_stock {
return Some(SupplyStatus::OutOfStock { missing: needs });
}
if mobile_trucks == 0 {
return Some(SupplyStatus::NoTruck { rm48u: false });
}
let all_blocked = self
.sams
.iter()
.filter(|t| t.kind == SamKind::Tzm && t.alive() && t.drive_speed() > 0.0)
.all(|t| self.routes.out_of_reach(t.id, sam.id, now));
return Some(if all_blocked {
SupplyStatus::RouteBlocked { rm48u: false }
} else {
SupplyStatus::WaitingForTruck { rm48u: false, returning: false }
});
}
None
}
}
fn demand_totals(waiting: &[(u32, DVec3, f64, [Option<AmmoKind>; 2])]) -> [u32; AmmoKind::COUNT] {
let mut totals = [0u32; AmmoKind::COUNT];
for (_, _, _, needs) in waiting {
for kind in needs.into_iter().flatten() {
totals[kind.index()] += 1;
}
}
totals
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_empty_nearby_depot_explains_the_missing_typed_stock() {
let mut sim = Sim::new(1);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 1.0)] {
let id = sim.id();
sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
let error = sim.load_ground_round(1).unwrap_err();
assert!(error.contains("RM48U: 0"));
assert!(error.contains("/airdef ground-stock 1"));
assert_eq!((sim.sams[0].ground_stock, sim.sams[1].ground_rounds, sim.sams[1].missiles), (0, 0, 4));
}
#[test]
fn return_waits_for_capacity_and_ready_carrier_and_can_be_cancelled() {
let mut sim = Sim::new(3);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 160.0), (SamKind::Tzm, 160.0)] {
let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
sim.sams[1].ground_rounds = 1;
sim.sams[1].missiles = 3;
sim.sams[2].air_48n6_stock = 2;
assert!(sim.unload_ground_round(1).is_err());
sim.sams[2].air_48n6_stock = 1;
sim.unload_ground_round(1).unwrap();
sim.cancel_ground_request(1).unwrap();
assert!(!sim.sams[1].ground_return);
sim.unload_ground_round(1).unwrap();
sim.tick = 2;
sim.sams[1].reloading = 1;
sim.step_supply(&mut Out::default());
assert_eq!(sim.sams[1].ground_rounds, 1);
sim.sams[1].reloading = 0;
sim.step_supply(&mut Out::default());
assert_eq!((sim.sams[1].ground_rounds, sim.sams[1].missiles), (0, 4));
assert_eq!((sim.sams[2].ground_stock, sim.sams[2].air_48n6_stock), (1, 0));
assert!(sim.sams[2].return_cargo);
sim.direct_hit(sim.sams[2].pos + DVec3::Y, DVec3::ZERO, 1, &mut Out::default());
sim.repair();
assert_eq!((sim.sams[0].ground_stock, sim.sams[1].ground_rounds, sim.sams[2].ground_stock), (0, 0, 0));
assert!(!sim.sams[2].return_cargo);
}
#[test]
fn return_waits_for_moving_or_damaged_units() {
let mut sim = Sim::new(4);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 160.0), (SamKind::Tzm, 160.0)] {
let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
sim.sams[1].ground_rounds = 1;
sim.sams[1].missiles = 3;
sim.unload_ground_round(1).unwrap();
sim.tick = 2;
sim.sams[1].comps.0[Part::Launcher as usize] = 0.0;
sim.step_supply(&mut Out::default());
assert_eq!(sim.sams[1].ground_rounds, 1);
sim.sams[1].comps.0[Part::Launcher as usize] = 1.0;
sim.sams[2].comps.0[Part::Tracks as usize] = 0.0;
sim.step_supply(&mut Out::default());
assert_eq!(sim.sams[1].ground_rounds, 1);
sim.sams[2].comps.0[Part::Tracks as usize] = 1.0;
assert!(sim.order_move(1, DVec3::new(220.0, 70.0, 0.0)));
sim.step_supply(&mut Out::default());
assert_eq!(sim.sams[1].ground_rounds, 1);
sim.sams[1].state = SamState::Search;
sim.step_supply(&mut Out::default());
assert_eq!((sim.sams[1].ground_rounds, sim.sams[2].ground_stock), (0, 1));
}
#[test]
fn typed_delivery_uses_stock_and_shared_cells_and_survives_interruption() {
let mut sim = Sim::new(1);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 200.0), (SamKind::Tzm, 0.0)] {
let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
assert!(sim.load_ground_round(1).is_err());
sim.sams[0].ground_stock = 1;
assert!(sim.load_ground_round(0).is_err());
sim.load_ground_round(1).unwrap();
sim.tick = 2;
sim.step_supply(&mut Out::default()); // assign depot
sim.step_supply(&mut Out::default()); // physically take one
assert_eq!((sim.sams[0].ground_stock, sim.sams[2].ground_stock), (0, 1));
assert_eq!(sim.sams[1].ground_rounds, 0);
// Interrupted truck retains cargo and request; a restored job is not required.
sim.sams[2].job = None;
sim.sams[2].state = SamState::Search;
sim.sams[2].pos = sim.sams[1].pos;
sim.step_supply(&mut Out::default());
sim.step_supply(&mut Out::default());
assert_eq!((sim.sams[1].missiles, sim.sams[1].ground_rounds), (3, 1));
assert_eq!((sim.sams[2].ground_stock, sim.sams[2].air_48n6_stock), (0, 1));
assert!(!sim.sams[1].ground_request);
sim.sams[2].job = None;
sim.sams[2].state = SamState::Search;
sim.sams[2].pos = sim.sams[0].pos;
sim.step_supply(&mut Out::default());
sim.step_supply(&mut Out::default());
assert_eq!((sim.sams[0].air_48n6_stock, sim.sams[2].air_48n6_stock), (1, 0));
assert!(sim.load_ground_round(1).is_err());
}
#[test]
fn pending_delivery_waits_for_compatible_type_and_cell_after_unload() {
let mut sim = Sim::new(2);
for kind in [SamKind::Depot, SamKind::S400, SamKind::Tzm] {
let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::ZERO, 0.0));
}
sim.sams[1].ground_request = true;
sim.sams[2].ground_stock = 1;
sim.sams[1].kind = SamKind::Patriot;
sim.tick = 2;
for _ in 0..4 { sim.step_supply(&mut Out::default()); }
assert_eq!(sim.sams[2].ground_stock, 1);
assert_eq!(sim.sams[1].ground_rounds, 0);
sim.sams[1].kind = SamKind::S400;
sim.sams[1].missiles = 0;
sim.sams[1].ground_rounds = 4;
for _ in 0..4 { sim.step_supply(&mut Out::default()); }
assert_eq!(sim.sams[2].ground_stock, 1);
sim.unload_ground_round(1).unwrap();
for _ in 0..4 { sim.step_supply(&mut Out::default()); }
assert_eq!((sim.sams[1].ground_rounds, sim.sams[2].ground_stock, sim.sams[0].ground_stock), (4, 0, 1));
assert!(!sim.sams[1].ground_request);
}
/// Runs `step_supply`, jumping the truck beside its current job each tick so handovers
/// resolve without a full drive (movement itself is covered by the lib round-trip tests).
/// Fails after 200 ticks if `done` never holds.
fn serve_until(sim: &mut Sim, truck: usize, mut done: impl FnMut(&Sim) -> bool) {
let mut ok = false;
for _ in 0..200 {
if done(sim) { ok = true; break; }
if let Some(id) = sim.sams[truck].job()
&& let Some(j) = sim.sams.iter().position(|s| s.id == id)
{
sim.sams[truck].pos = sim.sams[j].pos;
}
sim.sams[truck].state = SamState::Search;
sim.tick += 1;
sim.step_supply(&mut Out::default());
}
assert!(ok, "condition not reached within 200 step_supply calls");
}
/// #128: a return that is claimed but cannot proceed (here: the returning system is on the
/// move) must not stop the free truck with job=None; an independent typed request is served.
/// The claim stays, the rounds are conserved, and once the system stops the return completes.
#[test]
fn a_moving_return_claim_does_not_starve_an_independent_supply_request() {
let mut sim = Sim::new(5);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 40.0), (SamKind::S400, 160.0), (SamKind::Tzm, 0.0)] {
let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
let (depot, a, b, truck) = (0usize, 1usize, 2usize, 3usize);
let b_id = sim.sams[b].id;
sim.sams[depot].ground_stock = 2;
sim.sams[a].ground_rounds = 1;
sim.sams[a].missiles = 3;
sim.sams[a].ground_return = true;
sim.sams[b].ground_request = true;
assert!(sim.order_move(a, DVec3::new(400.0, 70.0, 0.0)));
// The free truck loads one RM48U at the depot and starts driving to B within 100 ticks;
// before the fix it entered the return branch, found the moving A impossible and idled.
let mut started = false;
for _ in 0..100 {
sim.tick += 1;
sim.step_supply(&mut Out::default());
if sim.sams[truck].job() == Some(b_id) { started = true; break; }
}
assert!(started, "truck never started the delivery to B");
// The claim and the rounds are untouched by the fallback.
assert!(sim.sams[a].ground_return);
assert_eq!(sim.sams[a].ground_rounds, 1);
assert_eq!((sim.sams[depot].ground_stock, sim.sams[truck].ground_stock), (1, 1));
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
// Hand the round over to B; the full drive is exercised in the lib round-trip test.
serve_until(&mut sim, truck, |s| s.sams[b].ground_rounds == 1);
assert!(!sim.sams[b].ground_request);
assert_eq!((sim.sams[b].missiles, sim.sams[truck].air_48n6_stock), (3, 1));
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
// No request is left, so the truck holds its watch (a stock run aside): the pending
// return still outranks it and the claim survives.
for _ in 0..20 { sim.tick += 1; sim.step_supply(&mut Out::default()); }
assert!(sim.sams[a].ground_return);
assert_eq!(sim.sams[a].ground_rounds, 1);
// A stops: the actual return is picked up and driven back to the depot.
sim.sams[a].state = SamState::Search;
sim.sams[a].dest = None;
serve_until(&mut sim, truck, |s| s.sams[truck].return_cargo);
assert!(!sim.sams[a].ground_return);
assert_eq!((sim.sams[a].ground_rounds, sim.sams[a].missiles), (0, 4));
assert_eq!((sim.sams[truck].ground_stock, sim.sams[truck].air_48n6_stock), (1, 0));
serve_until(&mut sim, truck, |s| s.sams[depot].ground_stock == 2);
assert!(!sim.sams[truck].return_cargo);
assert_eq!((sim.sams[depot].ground_stock, sim.sams[truck].ground_stock, sim.sams[b].ground_rounds), (2, 0, 1));
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
}
/// #128 variant: the pickup is already claimed by another truck, so for this one the return
/// is impossible; it must turn to the waiting request instead of idling with job=None. A
/// dropped job (as after loading a save) is rebuilt, damaged trucks wait, and the repaired
/// claiming truck keeps the priority of the now executable return over the request.
#[test]
fn a_return_claimed_by_another_truck_leaves_the_supply_to_the_second_one() {
let mut sim = Sim::new(7);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 160.0), (SamKind::S400, 200.0), (SamKind::Tzm, 0.0), (SamKind::Tzm, 150.0)] {
let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
let (depot, a, b, t2, t1) = (0usize, 1usize, 2usize, 3usize, 4usize);
let (a_id, b_id) = (sim.sams[a].id, sim.sams[b].id);
sim.sams[depot].ground_stock = 2;
sim.sams[a].ground_rounds = 1;
sim.sams[a].missiles = 3;
sim.sams[a].ground_return = true;
sim.sams[b].ground_request = true;
// The first truck claimed A's pickup earlier; both trucks start damaged: nothing
// moves, no round is lost, the claim waits.
sim.sams[t1].job = Some(a_id);
sim.sams[t1].comps.0[Part::Tracks as usize] = 0.0;
sim.sams[t2].comps.0[Part::Tracks as usize] = 0.0;
for _ in 0..30 { sim.tick += 1; sim.step_supply(&mut Out::default()); }
assert_eq!(sim.sams[t2].job(), None);
assert_eq!((sim.sams[depot].ground_stock, sim.sams[b].ground_rounds), (2, 0));
assert!(sim.sams[a].ground_return);
assert_eq!(sim.sams[depot].ground_stock + sim.sams[t1].ground_stock + sim.sams[t2].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
// Repaired, the second truck must not idle on the claimed return: depot first, then B.
sim.sams[t2].comps.0[Part::Tracks as usize] = 1.0;
let mut started = false;
for _ in 0..100 {
sim.tick += 1;
sim.step_supply(&mut Out::default());
if sim.sams[t2].job() == Some(b_id) { started = true; break; }
}
assert!(started, "second truck never started the delivery to B");
assert_eq!((sim.sams[depot].ground_stock, sim.sams[t2].ground_stock), (1, 1));
assert!(sim.sams[a].ground_return, "claimed return must survive the fallback");
// A save/load drops the job; the request and the cargo survive and the job is rebuilt.
sim.sams[t2].job = None;
serve_until(&mut sim, t2, |s| s.sams[t2].job() == Some(b_id));
// The claiming truck is repaired: the executable return has priority over the request,
// and the still-hauling second truck is not diverted from B.
sim.sams[t1].comps.0[Part::Tracks as usize] = 1.0;
serve_until(&mut sim, t1, |s| s.sams[t1].return_cargo);
assert!(!sim.sams[a].ground_return);
assert_eq!(sim.sams[a].ground_rounds, 0);
assert_eq!(sim.sams[t2].job(), Some(b_id), "hauling truck must keep its supply job");
// B gets its round; the displaced air round rides along.
serve_until(&mut sim, t2, |s| s.sams[b].ground_rounds == 1);
assert_eq!((sim.sams[b].missiles, sim.sams[t2].air_48n6_stock), (3, 1));
assert_eq!(sim.sams[depot].ground_stock + sim.sams[t1].ground_stock + sim.sams[t2].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
// And the picked-up return reaches the depot: everything is back except B's new round.
serve_until(&mut sim, t1, |s| s.sams[depot].ground_stock == 2);
assert!(!sim.sams[t1].return_cargo);
assert_eq!((sim.sams[depot].ground_stock, sim.sams[t1].ground_stock, sim.sams[b].ground_rounds), (2, 0, 1));
}
/// #128 variant: the route to the returning system is marked unreachable, so the return is
/// impossible for now; the truck serves the request, and the return completes once the
/// route is passable again and the system is still waiting with its claim.
#[test]
fn an_unreachable_route_falls_back_to_supply_until_it_expires() {
let mut sim = Sim::new(9);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 40.0), (SamKind::S400, 160.0), (SamKind::Tzm, 0.0)] {
let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
let (depot, a, b, truck) = (0usize, 1usize, 2usize, 3usize);
let (a_id, b_id) = (sim.sams[a].id, sim.sams[b].id);
sim.sams[depot].ground_stock = 2;
sim.sams[a].ground_rounds = 1;
sim.sams[a].missiles = 3;
sim.sams[a].ground_return = true;
sim.sams[b].ground_request = true;
sim.routes.unreachable.insert((sim.sams[truck].id, a_id), u64::MAX);
let mut started = false;
for _ in 0..100 {
sim.tick += 1;
sim.step_supply(&mut Out::default());
if sim.sams[truck].job() == Some(b_id) { started = true; break; }
}
assert!(started, "truck never started the delivery to B");
assert!(sim.sams[a].ground_return, "claim must survive the blocked route");
serve_until(&mut sim, truck, |s| s.sams[b].ground_rounds == 1);
// The route is passable again: the waiting claim is picked up and returned.
sim.routes.unreachable.clear();
serve_until(&mut sim, truck, |s| s.sams[truck].return_cargo);
assert!(!sim.sams[a].ground_return);
serve_until(&mut sim, truck, |s| s.sams[depot].ground_stock == 2);
assert!(!sim.sams[truck].return_cargo);
assert_eq!(sim.sams[depot].ground_stock + sim.sams[truck].ground_stock + sim.sams[a].ground_rounds + sim.sams[b].ground_rounds, 3);
}
#[test]
fn depot_spawn_roll_varies_by_system_weapon_and_rolls_rm48u_with_chance() {
let mut saw_rm48u = false;
let mut saw_zero_rm48u = false;
let mut saw_diff_pantsir_channels = false;
for seed in 1..=100u64 {
let mut sim = Sim::new(seed);
let mut depot = Sam::new(1, SamKind::Depot, DVec3::ZERO, 0.0);
sim.roll_depot_stock(&mut depot);
for kind in AmmoKind::ALL {
let (lo, hi) = kind.spawn_range();
let n = depot.ammo_stock.get(kind);
assert!((lo..=hi).contains(&n), "seed {seed} {kind:?}: {n} not in {lo}..={hi}");
}
if depot.ammo_stock.get(AmmoKind::PantsirMissile) != depot.ammo_stock.get(AmmoKind::PantsirGun) {
saw_diff_pantsir_channels = true;
}
assert!(depot.ground_stock <= 2);
if depot.ground_stock > 0 {
saw_rm48u = true;
} else {
saw_zero_rm48u = true;
}
assert_eq!(depot.cargo, depot.ammo_stock.total());
}
assert!(saw_rm48u && saw_zero_rm48u, "RM48U should appear probabilistically across spawns");
assert!(saw_diff_pantsir_channels, "Pantsir missile and gun stocks should vary independently");
}
#[test]
fn depot_only_reloads_matching_system_and_weapon_channel() {
let mut sim = Sim::new(1);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::S400, 10.0), (SamKind::Pantsir, 12.0), (SamKind::Patriot, DEPOT_REACH + 10.0)] {
let id = sim.id();
sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
sim.sams[0].clear_ammo();
sim.sams[0].set_ammo(AmmoKind::PatriotMissile, 2);
sim.sams[0].set_ammo(AmmoKind::PantsirMissile, 1);
sim.sams[1].missiles = 0;
sim.sams[1].empty = true;
sim.sams[2].missiles = 0;
sim.sams[2].bursts = 0;
sim.sams[2].empty = true;
sim.sams[3].missiles = 0;
sim.sams[3].empty = true;
sim.step_supply(&mut Out::default());
assert_eq!(sim.sams[1].reloading, 0, "S-400 must not reload from Patriot stock");
assert!(sim.sams[1].empty);
assert_eq!(sim.sams[3].reloading, 0, "Patriot beyond DEPOT_REACH must not auto-reload directly");
assert!(sim.sams[3].empty);
assert!(sim.sams[2].reloading > 0, "Pantsir must start reloading missiles");
assert_eq!(sim.sams[0].ammo_stock.get(AmmoKind::PantsirMissile), 0);
assert_eq!(sim.sams[0].ammo_stock.get(AmmoKind::PatriotMissile), 2);
// Simulate reload completion in step_sams: only missiles are restored, guns remain 0.
sim.sams[2].reloading = 1;
sim.step(&mut Ground::default(), None, &mut Out::default());
assert_eq!(sim.sams[2].missiles, 12);
assert_eq!(sim.sams[2].bursts, 0);
// After step_sams detects bursts == 0, Pantsir marks empty again and waits for PantsirGun.
assert!(sim.sams[2].empty);
sim.sams[0].set_ammo(AmmoKind::PantsirGun, 1);
sim.step_supply(&mut Out::default());
assert!(sim.sams[2].reloading > 0, "Pantsir must now reload gun channel");
sim.sams[2].reloading = 1;
sim.step(&mut Ground::default(), None, &mut Out::default());
assert_eq!(sim.sams[2].bursts, 140);
assert_eq!(sim.sams[0].ammo_stock.get(AmmoKind::PantsirGun), 0);
}
#[test]
fn tzm_fetches_matching_ammo_and_drops_unneeded_cargo() {
let mut sim = Sim::new(4);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::Tor, 160.0), (SamKind::Tzm, 0.0)] {
let id = sim.id();
sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
sim.sams[0].clear_ammo();
sim.sams[0].set_ammo(AmmoKind::TorMissile, 1);
sim.sams[1].missiles = 0;
sim.sams[1].empty = true;
// Full TZM carrying unneeded PatriotMissile must drop it off at the depot and pick up TorMissile.
sim.sams[2].set_ammo(AmmoKind::PatriotMissile, 2);
sim.tick = 1;
serve_until(&mut sim, 2, |s| s.sams[1].reloading > 0);
assert_eq!(sim.sams[0].ammo_stock.get(AmmoKind::PatriotMissile), 2);
assert_eq!(sim.sams[0].ammo_stock.get(AmmoKind::TorMissile), 0);
assert_eq!(sim.sams[2].ammo_stock.total(), 0);
assert!(!sim.sams[1].empty);
}
#[test]
fn supply_summary_and_status_diagnose_all_wait_and_delivery_states() {
let mut sim = Sim::new(1);
for (kind, x) in [(SamKind::Depot, 0.0), (SamKind::Tor, 160.0), (SamKind::S400, 200.0), (SamKind::Tzm, 40.0)] {
let id = sim.id();
sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
}
sim.sams[0].clear_ammo();
sim.sams[0].ground_stock = 1;
sim.sams[1].missiles = 0;
sim.sams[1].empty = true;
sim.sams[2].ground_request = true;
assert_eq!(sim.supply_status(0), None);
assert_eq!(sim.supply_status(3), None);
assert_eq!(sim.supply_status(1), Some(SupplyStatus::OutOfStock { missing: [Some(AmmoKind::TorMissile), None] }));
sim.sams[0].set_ammo(AmmoKind::TorMissile, 2);
sim.sams[0].ground_stock = 0;
assert_eq!(sim.supply_status(2), Some(SupplyStatus::NoRm48uStock));
sim.sams[0].ground_stock = 1;
sim.sams[3].job = Some(sim.sams[0].id);
match sim.supply_status(2) {
Some(SupplyStatus::TruckFetching { truck_num: 4, depot_num: 1, eta_ticks, rm48u: true, .. }) => assert!(eta_ticks > 0),
other => panic!("expected RM48U fetch status, got {other:?}"),
}
sim.sams[3].ground_stock = 1;
sim.sams[3].job = Some(sim.sams[2].id);
match sim.supply_status(2) {
Some(SupplyStatus::TruckEnRoute { truck_num: 4, eta_ticks, rm48u: true, returning: false, .. }) => assert!(eta_ticks > 0),
other => panic!("expected RM48U delivery status, got {other:?}"),
}
sim.sams[2].ground_request = false;
sim.sams[3].job = Some(sim.sams[0].id);
match sim.supply_status(1) {
Some(SupplyStatus::TruckFetching { truck_num: 4, depot_num: 1, eta_ticks, rm48u: false, .. }) => assert!(eta_ticks > 0),
other => panic!("expected Tor fetch status, got {other:?}"),
}
sim.sams[3].job = None;
assert_eq!(sim.supply_status(1), Some(SupplyStatus::WaitingForTruck { rm48u: false, returning: false }));
sim.routes.unreachable.insert((sim.sams[3].id, sim.sams[1].id), 100);
assert_eq!(sim.supply_status(1), Some(SupplyStatus::RouteBlocked { rm48u: false }));
sim.sams[3].comps.0[Part::Tracks as usize] = 0.0;
assert_eq!(sim.supply_status(1), Some(SupplyStatus::NoTruck { rm48u: false }));
sim.sams[1].reloading = 42;
assert_eq!(sim.supply_status(1), Some(SupplyStatus::Reloading { ticks_left: 42 }));
let summary = sim.supply_summary();
assert_eq!((summary.depots_alive, summary.trucks_alive, summary.trucks_busy), (1, 1, 0));
assert_eq!((summary.rm48u_depot, summary.rm48u_truck, summary.reloading), (1, 1, 1));
assert_eq!(summary.total_for(AmmoKind::TorMissile), 2);
}
#[test]
fn tzm_prioritizes_threatened_and_dry_system_over_closer_idle_unit() {
let mut sim = Sim::new(5);
let tzm_id = sim.id();
sim.sams.push(Sam::new(tzm_id, SamKind::Tzm, DVec3::ZERO, 0.0));
let radar_id = sim.id();
sim.sams.push(Sam::new(radar_id, SamKind::Radar, DVec3::new(0.0, 70.0, 0.0), 0.0));
// Closer idle Tor (no matching track).
let tor_id = sim.id();
let mut tor = Sam::new(tor_id, SamKind::Tor, DVec3::new(100.0, 70.0, 0.0), 0.0);
tor.missiles = 0;
tor.empty = true;
sim.sams.push(tor);
// Farther S-400 threatened by a confirmed ballistic radar track inside its reach.
let s400_id = sim.id();
let mut s400 = Sam::new(s400_id, SamKind::S400, DVec3::new(250.0, 70.0, 0.0), 0.0);
s400.missiles = 0;
s400.empty = true;
sim.sams.push(s400);
// Nearest depot carries Tor stock; slightly farther depot carries S-400 stock.
let d_tor_id = sim.id();
let mut d_tor = Sam::new(d_tor_id, SamKind::Depot, DVec3::new(20.0, 70.0, 0.0), 0.0);
d_tor.clear_ammo();
d_tor.set_ammo(AmmoKind::TorMissile, 2);
sim.sams.push(d_tor);
let d_s400_id = sim.id();
let mut d_s400 = Sam::new(d_s400_id, SamKind::Depot, DVec3::new(40.0, 70.0, 0.0), 0.0);
d_s400.clear_ammo();
d_s400.set_ammo(AmmoKind::S400Missile, 2);
sim.sams.push(d_s400);
sim.sams[1].tracks.push(sight::Track {
id: 42,
class: ClassEst::Firm(Class::Ballistic),
pos: DVec3::new(320.0, 120.0, 0.0),
vel: DVec3::new(-1.0, 0.0, 0.0),
tick: 1,
own_tick: 1,
source: radar_id,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 200,
hits: 3,
locked: false,
});
sim.step_supply(&mut Out::default());
assert_eq!(sim.sams[0].job, Some(d_s400_id), "TZM must fetch S-400 ammo from depot matching the threatened unit first");
assert_eq!(sim.tzm_job_kind(0), Some("fetch"));
assert!(!sim.unit_route(0, 16).is_empty());
}
}