HD render fixes (#35-#39, #41) and replay time of day (#57) (fork patch 25); radar scan cycles with ageing tracks (#46), damage to individual system parts (#50), long-lasting fires (#52)
build / mod (push) Successful in 3m22s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 22:56:15 +03:00
parent d0b9498aaf
commit e3148bf458
40 changed files with 2374 additions and 143 deletions
+221 -2
View File
@@ -8,6 +8,124 @@ use super::*;
/// By blast power (as `explode` grades it): how far it reaches a vehicle, and how hard it hits one at the centre.
const REACH: [f64; 5] = [4.0, 7.0, 12.0, 18.0, 26.0];
const HIT: [f64; 5] = [0.2, 0.45, 0.85, 1.25, 1.7];
/// A unit's working parts, each 1 (whole) to 0 (failed); the hull is `Sam::health` (0 destroys it).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Part {
/// The radar (or optics): its reach and its scan.
Sensor,
/// The aiming drive of the launcher or turret.
Mount,
/// The launcher: cells, reload.
Launcher,
/// The gun: it jams.
Gun,
/// The running gear: it can't march when it fails.
Tracks,
/// The data link: no network when it fails.
Comms,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum PartState {
Ok,
Damaged,
Failed,
}
impl Part {
pub const ALL: [Part; 6] = [Part::Sensor, Part::Mount, Part::Launcher, Part::Gun, Part::Tracks, Part::Comms];
pub fn name(self) -> &'static str {
match self {
Part::Sensor => "РЛС",
Part::Mount => "привод наведения",
Part::Launcher => "пусковая",
Part::Gun => "орудие",
Part::Tracks => "ходовая",
Part::Comms => "связь",
}
}
pub fn short(self) -> &'static str {
match self {
Part::Sensor => "РЛС",
Part::Mount => "Прив",
Part::Launcher => "ПУ",
Part::Gun => "Ор",
Part::Tracks => "Ход",
Part::Comms => "Св",
}
}
fn index(self) -> usize {
self as usize
}
/// Whether this kind of unit has the part at all.
pub fn on(self, kind: SamKind) -> bool {
let spec = kind.spec();
match self {
Part::Sensor => spec.sensor > 0.0,
Part::Mount => kind.armed() && kind != SamKind::Light && (spec.missile.is_some() || spec.gun.is_some()),
Part::Launcher => spec.missile.is_some(),
Part::Gun => spec.gun.is_some(),
Part::Tracks => kind.mobile(),
Part::Comms => true,
}
}
/// Where the part is on the vehicle: right, up, back, blocks at scale 1 (the nose points to -back).
fn place(self, spec: &super::units::SamSpec) -> (f64, f64, f64) {
match self {
Part::Sensor => (0.0, spec.mast / spec.scale, 1.0),
Part::Mount => (0.0, spec.mount.0, -spec.mount.1),
Part::Launcher => (0.0, spec.mount.0, -spec.mount.1 + 0.4),
Part::Gun => (0.0, spec.mount.0, -spec.mount.1 - 1.0),
Part::Tracks => (0.0, 0.3, 0.0),
Part::Comms => (0.0, 1.6, 1.8),
}
}
}
/// Below this a part is damaged (works worse), at 0 it has failed.
pub const WORN: f64 = 0.6;
/// The state of every part: `Part::ALL`'s order.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Comps(pub [f64; 6]);
impl Default for Comps {
fn default() -> Self {
Self([1.0; 6])
}
}
impl Comps {
pub fn get(&self, p: Part) -> f64 {
self.0[p.index()]
}
pub fn state(&self, p: Part) -> PartState {
let v = self.get(p);
if v <= 0.0 {
PartState::Failed
} else if v < WORN {
PartState::Damaged
} else {
PartState::Ok
}
}
pub fn whole(&self) -> bool {
self.0.iter().all(|&v| v >= 1.0)
}
/// Parts of this kind that are not whole, as "РЛС 40%, ходовая отказ".
pub fn describe(&self, kind: SamKind) -> String {
Part::ALL
.iter()
.filter(|p| p.on(kind) && self.get(**p) < 1.0)
.map(|p| match self.state(*p) {
PartState::Failed => format!("{} отказ", p.short()),
_ => format!("{} {:.0}%", p.short(), self.get(*p) * 100.0),
})
.collect::<Vec<_>>()
.join(", ")
}
}
/// Health points an object loses at the centre of a blast.
const OBJECT_HIT: [f64; 5] = [2.0, 6.0, 14.0, 26.0, 40.0];
@@ -112,9 +230,39 @@ impl Sim {
sam.health -= hit * k * k * if d < 1.0 { 1.5 } else { 1.0 };
if sam.health <= 0.0 {
destroyed.push(i);
} else if before >= 0.5 && sam.health < 0.5 {
continue;
}
if before >= 0.5 && sam.health < 0.5 {
out.messages.push(format!("{} №{} повреждён", sam.kind.name(), i + 1));
}
// The parts take the blast by their own distance from it: the side it came from decides which.
let spec = sam.kind.spec();
let rot = DQuat::from_rotation_y(sam.heading);
for part in Part::ALL {
if !part.on(sam.kind) {
continue;
}
let (x, y, back) = part.place(spec);
let at = sam.pos + rot * DVec3::new(x, y, back) * spec.scale;
let size = if part == Part::Tracks { 2.5 } else { 1.0 };
let dp = (at.distance(pos) - size).max(0.0);
if dp >= reach {
continue;
}
let kp = 1.0 - dp / reach;
let roll = dice(self.seed, self.tick, sam.id as u64, part as u64);
// The parts are softer than the hull: a blast the hull survives can still put one out.
let dmg = hit * kp * kp * (0.7 + roll) * 1.5 * if dp < 1.0 { 1.4 } else { 1.0 };
let was = sam.comps.state(part);
let v = &mut sam.comps.0[part as usize];
*v = (*v - dmg).max(0.0);
let now = sam.comps.state(part);
if now != was && now != PartState::Ok {
let word = if now == PartState::Failed { "отказал(а)" } else { "повреждён(а)" };
out.messages.push(format!("{} №{}: {} {word}", sam.kind.name(), i + 1, part.name()));
}
}
sam.fit_cells();
}
for i in destroyed {
self.destroy(i, out);
@@ -144,6 +292,9 @@ impl Sim {
sam.target = None;
sam.gun_target = None;
sam.reloading = 0;
sam.tracks.clear();
sam.seen.clear();
sam.own.clear();
let spec = sam.kind.spec();
let missiles = sam.missiles;
let bursts = sam.bursts;
@@ -224,11 +375,76 @@ impl Sim {
}
/// A roll from 0 to 1 fixed by the seed and three numbers: the same events roll the same in every run,
/// and the simulation's own random sequence is left alone.
pub(super) fn dice(seed: u64, a: u64, b: u64, c: u64) -> f64 {
let mut x = seed ^ a.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ b.wrapping_mul(0xBF58_476D_1CE4_E5B9) ^ c.wrapping_mul(0x94D0_49BB_1331_11EB);
x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
x ^= x >> 31;
(x >> 11) as f64 / (1u64 << 53) as f64
}
impl Sam {
/// Its wreck still burns.
pub fn burning(&self) -> bool {
self.burn > 0
}
/// A part's state, `Ok` for one this unit does not have.
pub fn part(&self, p: Part) -> f64 {
if p.on(self.kind) { self.comps.get(p) } else { 1.0 }
}
pub fn part_state(&self, p: Part) -> PartState {
if p.on(self.kind) { self.comps.state(p) } else { PartState::Ok }
}
pub fn parts_text(&self) -> String {
self.comps.describe(self.kind)
}
/// The aiming drive's share of its speed: a failed one doesn't turn at all.
pub(super) fn drive_fit(&self) -> f64 {
let h = self.part(Part::Mount);
if h <= 0.0 { 0.0 } else { 0.3 + 0.7 * h }
}
/// The radar's share of its reach; the scan is slower by the same.
pub(super) fn radar_fit(&self) -> f64 {
let h = self.part(Part::Sensor);
if h <= 0.0 { 0.0 } else { 0.4 + 0.6 * h }
}
/// The gun's share of its hit chance.
pub(super) fn gun_fit(&self) -> f64 {
0.5 + 0.5 * self.part(Part::Gun)
}
/// Its launcher's cells still good: a damaged one holds fewer missiles.
pub(super) fn cells(&self) -> u32 {
let Some(load) = &self.kind.spec().missile else { return 0 };
let h = self.part(Part::Launcher);
if h <= 0.0 { 0 } else { ((load.magazine as f64 * (0.4 + 0.6 * h)).ceil() as u32).clamp(1, load.magazine) }
}
/// Missiles above what the cells hold are lost with them.
pub fn fit_cells(&mut self) {
if self.kind.spec().missile.is_some() {
self.missiles = self.missiles.min(self.cells());
}
}
/// Ticks a reload takes: longer with a damaged launcher.
pub(super) fn reload_time(&self) -> u32 {
let r = self.kind.spec().reload.max(1);
(r as f64 * (1.0 + 1.5 * (1.0 - self.part(Part::Launcher)))).round() as u32
}
/// The gun fires (not jammed for good, not jammed now).
pub(super) fn gun_up(&self) -> bool {
self.part(Part::Gun) > 0.0 && self.jam == 0
}
/// How far it can march: the running gear's share of the speed (0 can't).
pub(super) fn drive_speed(&self) -> f64 {
let h = self.part(Part::Tracks);
if h <= 0.0 { 0.0 } else { 0.35 + 0.65 * h }
}
/// The data link's reach, 0 when the link has failed.
pub(super) fn link_range(&self) -> f64 {
let h = self.part(Part::Comms);
if h <= 0.0 { 0.0 } else { super::sight::LINK * (0.3 + 0.7 * h) }
}
}
impl Sim {
@@ -236,9 +452,11 @@ impl Sim {
pub fn repair(&mut self) -> u32 {
let mut n = 0;
for sam in &mut self.sams {
if sam.health < 1.0 {
if sam.health < 1.0 || !sam.comps.whole() {
n += 1;
}
sam.comps = Comps::default();
sam.jam = 0;
let spec = sam.kind.spec();
sam.health = 1.0;
sam.burn = 0;
@@ -256,6 +474,7 @@ impl Sim {
}
// The wrecks' ammunition still to cook off goes with them.
self.later.clear();
self.fires.extinguish();
n
}
+223
View File
@@ -0,0 +1,223 @@
//! Long fires (#52): where a drone or a missile came down, where a warhead struck and on a
//! destroyed system a fire burns for minutes: it flares up, burns steadily, smokes thick and
//! heavy, dies down and smoulders. Visual first (flames, smoke columns, a flickering light, a
//! crackle); with damage on, a few real fire blocks on solid ground (never on water or in the
//! air), put back while it burns and taken away when it is out. At most `MAX` fires burn, the
//! oldest dying down first. A replay draws the same fires from its events (`replay_fire`).
use super::*;
/// Fires burning at once.
pub const MAX: usize = 12;
/// A fire put out by the water it fell in lasts this long (steam only).
const STEAM: u32 = 160;
/// Ticks the oldest fire has left when a newer one pushes it out.
const FADE: u32 = 160;
/// Ticks between the fire blocks being set again.
const REFRESH: u64 = 80;
pub struct Fire {
pub id: u32,
pub at: DVec3,
pub start: u64,
pub life: u32,
/// 0.6 (a crashed drone) to 3 (a cruise or ballistic warhead, a depot).
pub size: f32,
/// The system it burns on, if any: its own wreck fire does the flames for as long as it lasts.
host: Option<u32>,
/// The land under it found: `Some(true)` land, `Some(false)` water (steam only).
land: Option<bool>,
/// Asked about the ground since this tick.
asked: u64,
/// Fire blocks set (whole coordinates).
blocks: Vec<(i32, i32, i32)>,
/// The host's wreck is flaming: this fire leaves the flames to it.
pub quiet: bool,
}
#[derive(Default)]
pub struct Fires {
pub list: Vec<Fire>,
/// Commands to take fire blocks away, sent next tick.
cleanup: Vec<String>,
}
/// How long a fire of this power burns, in ticks: 2 to 5 minutes.
pub fn life_for(power: u32) -> u32 {
2400 + 900 * power.min(4)
}
/// The size of a fire of this power.
pub fn size_for(power: u32) -> f32 {
[0.6, 1.0, 1.6, 2.4, 3.0][power.min(4) as usize]
}
/// How strong the flames (`.0`) and the smoke (`.1`) are, 0 to about 1, `age` ticks into a fire
/// that burns `life`: flaring up, steady flame, thick smoke while it dies down, then embers.
pub fn level(age: f64, life: f64) -> (f32, f32) {
let f = (age / life.max(1.0)).clamp(0.0, 1.0);
let flare = if age < 40.0 { 0.35 + 0.65 * age / 40.0 } else { 1.0 };
let flame = if f < 0.45 { flare } else { flare * (1.0 - (f - 0.45) / 0.4).clamp(0.0, 1.0) };
let smoke = if age < 100.0 { age / 100.0 } else if f < 0.8 { 1.0 } else { 1.0 - 0.85 * (f - 0.8) / 0.2 };
(flame as f32, smoke.clamp(0.0, 1.0) as f32)
}
impl Fires {
/// Fires burning now.
pub fn len(&self) -> usize {
self.list.len()
}
pub fn is_empty(&self) -> bool {
self.list.is_empty()
}
/// Puts every fire out; the fire blocks are taken away on the next step.
pub fn extinguish(&mut self) {
let list = std::mem::take(&mut self.list);
for f in list {
self.cleanup.extend(f.take_blocks());
}
}
}
impl Fire {
fn take_blocks(self) -> Vec<String> {
self.blocks
.into_iter()
.map(|(x, y, z)| format!("fill {x} {y} {z} {x} {y} {z} minecraft:air replace minecraft:fire"))
.collect()
}
/// How strong it burns at tick `now`: (flames, smoke); water leaves steam only.
pub fn level(&self, now: u64) -> (f32, f32) {
let (fl, sm) = level(now.saturating_sub(self.start) as f64, self.life as f64);
if self.land == Some(false) { (0.0, sm * 0.5) } else { (fl, sm) }
}
}
impl Sim {
/// Something came down or struck at `pos` (power 0 to 4): a fire starts there, or the fire
/// already burning close by grows. `host` is the system it burns on.
pub(super) fn ignite(&mut self, pos: DVec3, power: u32, host: Option<u32>) {
let now = self.tick;
let (size, life) = (size_for(power), life_for(power));
if let Some(f) = self.fires.list.iter_mut().find(|f| f.at.distance(pos) < 6.0) {
// The same spot (a warhead and the wreck it made): one fire, the greater of the two.
f.size = f.size.max(size);
f.life = f.life.max((now - f.start) as u32 + life);
f.host = f.host.or(host);
return;
}
let id = self.id();
self.fires.list.push(Fire {
id,
at: pos,
start: now,
life,
size,
host,
land: None,
asked: 0,
blocks: Vec::new(),
quiet: false,
});
if self.fires.list.len() > MAX {
// The oldest dies down (and is gone) instead of burning on.
let old = self.fires.list.iter_mut().filter(|f| now.saturating_sub(f.start) as u32 + FADE < f.life).min_by_key(|f| f.start);
if let Some(f) = old {
f.life = (now - f.start) as u32 + FADE;
}
}
}
/// Once a tick: finds the ground under each new fire, burns the old ones, ends the burnt out.
pub(super) fn step_fires(&mut self, ground: &mut Ground, out: &mut Out) {
let now = self.tick;
out.commands.append(&mut self.fires.cleanup);
let damage = self.damage;
let mut fires = std::mem::take(&mut self.fires.list);
for f in &mut fires {
let age = now.saturating_sub(f.start);
// Where the land is under it: it burns on the surface, not at the height of what fell.
if f.land.is_none() && age >= f.asked {
f.asked = age + 10;
if let Some(h) = ground.at(f.at, now) {
let (x, z) = (f.at.x.floor() as i32, f.at.z.floor() as i32);
let h = h as i32;
if ground.world.is_known_solid(x, h - 1, z, now) {
f.at.y = h as f64;
f.land = Some(true);
} else if ground.world.is_known_open(x, h - 1, z, now) {
// Water (or another fluid): the fire goes out in a cloud of steam.
f.at.y = h as f64;
f.land = Some(false);
f.life = f.life.min(age as u32 + STEAM);
}
}
// Not known for a while: it burns where it is, on the land.
if f.land.is_none() && age > 100 {
f.land = Some(true);
}
}
f.quiet = f.host.is_some_and(|id| self.sams.iter().any(|s| s.id == id && !s.alive() && s.burn > 0));
let (fl, sm) = f.level(now);
let s = f.size;
if !f.quiet {
let top = f.at + DVec3::Y * 0.4;
let spread = 0.4 + 0.5 * s;
if fl > 0.04 && now % 2 == 0 {
out.particles("minecraft:flame", top, spread, DVec3::new(0.0, 0.05 + 0.05 * fl as f64, 0.0), 0.02, (3.0 * s * fl).ceil() as u32);
}
if sm > 0.04 && now % 3 == 0 {
out.particles("minecraft:large_smoke", top + DVec3::Y * 0.6, spread, DVec3::new(0.0, 0.1, 0.0), 0.03, (2.0 * s * sm).ceil() as u32);
}
// The tall column: a plume that rises far.
if sm > 0.3 && now % 6 == (f.id % 6) as u64 {
out.particles("minecraft:campfire_signal_smoke", top, 0.5 * s, DVec3::new(0.0, 0.09, 0.0), 0.01, 1 + (s * sm) as u32);
}
if fl > 0.5 && now % 20 == (f.id % 20) as u64 {
out.particles("minecraft:lava", top + DVec3::Y * 0.5, 0.4 * s, DVec3::new(0.0, 0.2, 0.0), 0.1, 2);
}
if now % 50 == (f.id % 50) as u64 && fl + sm * 0.3 > 0.1 {
out.sound("minecraft:block.fire.ambient", f.at, 0.5 + 1.2 * fl, 0.8 + 0.2 * s.min(1.0));
}
}
// Real fire, only where the damage is real: a few blocks on the solid ground.
if damage && f.land == Some(true) && fl > 0.3 && now % REFRESH == (f.id as u64) % REFRESH && age >= 20 {
let (x, y, z) = (f.at.x.floor() as i32, f.at.y.floor() as i32, f.at.z.floor() as i32);
let n = if s >= 2.5 { 5 } else if s >= 1.5 { 3 } else { 1 };
for k in 0..n {
let (dx, dz) = if k == 0 { (0, 0) } else { [(1, 0), (-1, 0), (0, 1), (0, -1)][k - 1] };
let (bx, bz) = (x + dx, z + dz);
// Only where the land is as high as at the centre.
let level = ground.at(DVec3::new(bx as f64 + 0.5, 0.0, bz as f64 + 0.5), now).is_some_and(|h| h as i32 == y);
if level && ground.world.is_known_solid(bx, y - 1, bz, now) && ground.world.is_known_open(bx, y, bz, now) {
out.commands.push(format!("setblock {bx} {y} {bz} minecraft:fire keep"));
if !f.blocks.contains(&(bx, y, bz)) {
f.blocks.push((bx, y, bz));
}
}
}
}
}
// The burnt out: their fire blocks go too.
let mut keep = Vec::with_capacity(fires.len());
for f in fires {
if now.saturating_sub(f.start) < f.life as u64 {
keep.push(f);
} else {
out.commands.extend(f.take_blocks());
}
}
// Fires lit this very tick were pushed to the list meanwhile (none are: ignite runs inside the step).
keep.append(&mut self.fires.list);
self.fires.list = keep;
}
}
/// A fire for a replay: the event's power at age `age` ticks, as a glowing flame model's scale
/// (zero when it is out or not started) and a smoke strength.
pub fn replay_fire(power: u32, age: f64) -> (f32, f32) {
if age < 0.0 {
return (0.0, 0.0);
}
let (fl, sm) = level(age, life_for(power) as f64);
(fl * size_for(power), sm)
}
+2 -2
View File
@@ -50,7 +50,7 @@ impl Sim {
// 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() || now % 10 != t as u64 % 10 {
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;
@@ -116,7 +116,7 @@ impl Sim {
fn reload_now(&mut self, i: usize, out: &mut Out) {
let sam = &mut self.sams[i];
sam.empty = false;
sam.reloading = sam.kind.spec().reload.max(1);
sam.reloading = sam.reload_time();
out.sound("minecraft:block.piston.extend", sam.pos, 2.0, 0.6);
}
}
+103 -38
View File
@@ -10,6 +10,7 @@ use glam::{DQuat, DVec3};
use std::collections::HashMap;
mod damage;
pub mod fires;
mod raid;
pub mod record;
mod sight;
@@ -22,7 +23,12 @@ mod why;
pub mod world;
#[cfg(test)]
mod regress;
#[cfg(test)]
mod sensor_tests;
pub use ew::EW_RADIUS;
pub use damage::{Comps, Part, PartState};
pub use sight::{Ident, Track};
use damage::dice;
pub use units::{Family, SamKind};
use units::Muzzle;
pub use raid::{Approach, Aim, RaidOrder};
@@ -747,9 +753,13 @@ impl Drone {
}
/// How much a system wants to shoot it: fast and heavy first, decoys look real.
fn threat(&self, from: DVec3) -> f64 {
self.threat_at(from, self.pos)
}
/// The same for a target believed to be at `at` (a track's forecast).
fn threat_at(&self, from: DVec3, at: DVec3) -> f64 {
let s = self.kind.spec();
let warhead = if s.decoy { 3.0 } else { s.warhead as f64 };
(1.0 + warhead) * (1.0 + s.speed) / (1.0 + self.pos.distance(from) * 0.02)
(1.0 + warhead) * (1.0 + s.speed) / (1.0 + at.distance(from) * 0.02)
}
}
@@ -1034,7 +1044,14 @@ pub struct Sam {
pub health: f64,
/// Ticks its wreck still burns.
burn: u32,
/// The drones it has tracks of this tick: its own radar's and the network's.
/// Its working parts (the hull is `health`).
pub comps: Comps,
/// Ticks its gun stays jammed.
jam: u32,
/// Where its radar beam points (radians), and the tracks it holds: its own radar's and the network's.
pub(super) beam: f64,
pub tracks: Vec<Track>,
/// The ids of the tracks it holds this tick: its own radar's and the network's.
pub seen: Vec<u32>,
/// The drones its own radar (or optics) holds: guns need these.
pub own: Vec<u32>,
@@ -1087,6 +1104,10 @@ impl Sam {
launched: 0,
health: 1.0,
burn: 0,
comps: Comps::default(),
jam: 0,
beam: id as f64 * 2.4,
tracks: Vec::new(),
seen: Vec::new(),
own: Vec::new(),
kill_view: None,
@@ -1108,12 +1129,16 @@ impl Sam {
pub fn alive(&self) -> bool {
self.health > 0.0
}
/// Where its radar beam points now (radians clockwise from north).
pub fn beam(&self) -> f64 {
self.beam
}
/// How well it still works: turning, aiming, its radar's reach.
/// Turns the mount towards `yaw` (and `pitch`, if it elevates) under its drive's limits; a damaged
/// system has the less of both speed and acceleration.
fn aim_towards(&mut self, yaw: f64, pitch: Option<f64>) {
let d = self.kind.spec().drive();
let fit = self.fitness();
let fit = self.drive_fit();
self.yaw += drive(&mut self.yaw_vel, angle_diff(self.yaw, yaw), d.yaw.0 * fit, d.yaw.1 * fit);
if let Some(pitch) = pitch {
self.pitch += drive(&mut self.pitch_vel, pitch - self.pitch, d.pitch.0 * fit, d.pitch.1 * fit);
@@ -1124,9 +1149,6 @@ impl Sam {
self.yaw_vel = 0.0;
self.pitch_vel = 0.0;
}
fn fitness(&self) -> f64 {
0.45 + 0.55 * self.health.clamp(0.0, 1.0)
}
pub fn status(&self) -> String {
let spec = self.kind.spec();
let mut text = spec.name.to_string();
@@ -1143,7 +1165,10 @@ impl Sam {
let state = if self.ew_on { "ГЛУШИТ" } else if self.ew_lock { "остывает" } else { "готова" };
return format!("{text}: {state}, нагрев {:.0}%", self.heat * 100.0);
}
SamKind::Radar => return format!("{text}: целей {}", self.own.len()),
SamKind::Radar => {
let broken = if self.comps.whole() { String::new() } else { format!(" [{}]", self.parts_text()) };
return format!("{text}: целей {}{broken}", self.own.len());
}
SamKind::Light => return format!("{text}{}", if self.target.is_some() { ": в луче цель" } else { "" }),
_ => {}
}
@@ -1153,6 +1178,9 @@ impl Sam {
if self.health < 1.0 {
text += &format!(" ({:.0}%)", self.health * 100.0);
}
if !self.comps.whole() {
text += &format!(" [{}]", self.parts_text());
}
if self.reloading > 0 {
text += &format!(" перезарядка {}с", self.reloading.div_ceil(20));
} else {
@@ -1202,6 +1230,10 @@ pub struct Sim {
pub launched: u32,
/// Explosions damage the land (primed TNT through commands).
pub damage: bool,
/// The seed: what falls to chance without the sequence (scan hits, damage to parts) is rolled from it.
seed: u64,
/// The air picture shows the true positions beside the tracks (a sandbox and analysis aid; changes no behaviour).
pub truth: bool,
/// The shader draws fireballs: no glowing cubes.
pub shader: bool,
/// Air defence holds fire.
@@ -1228,6 +1260,10 @@ pub struct Sim {
intel: ew::Intel,
/// Night: guns need light (the mod sets it from the game's clock).
pub night: bool,
/// The long fires at crash and impact points (#52).
pub fires: fires::Fires,
/// The world clock's time of day in ticks (the mod sets it; recordings keep it).
pub day_time: Option<u64>,
/// Illumination flares in the sky, and the drones lit this tick.
pub flares: Vec<lights::Flare>,
pub lit: Vec<u32>,
@@ -1255,6 +1291,8 @@ impl Sim {
crashes: 0,
launched: 0,
damage: true,
seed: seed.wrapping_mul(0x2545_F491_4F6C_DD1D) | 1,
truth: false,
shader: false,
hold: false,
horizons: HashMap::new(),
@@ -1269,6 +1307,8 @@ impl Sim {
tally: record::Tally::default(),
intel: ew::Intel::default(),
night: false,
fires: fires::Fires::default(),
day_time: None,
flares: Vec::new(),
lit: Vec::new(),
}
@@ -1387,6 +1427,7 @@ impl Sim {
self.later.clear();
self.flares.clear();
self.lit.clear();
self.fires.extinguish();
}
/// One game tick.
@@ -1407,6 +1448,7 @@ impl Sim {
self.step_fx(ground, out);
self.draw_targets(out);
self.step_wrecks(out);
self.step_fires(ground, out);
self.report_wave(out);
self.record();
let now = self.tick;
@@ -1871,18 +1913,20 @@ impl Sim {
retarget(&mut guns_on, sam.gun_target.take(), None);
continue;
}
let fit = self.sams[i].fitness();
{
let sam = &mut self.sams[i];
sam.cooldown = sam.cooldown.saturating_sub(1);
sam.gun_cooldown = sam.gun_cooldown.saturating_sub(1);
sam.flash = sam.flash.saturating_sub(1);
sam.recoil *= 0.6;
sam.dish = (sam.dish + 0.15) % TAU;
if sam.radar_up() {
sam.dish = sam.beam;
}
sam.jam = sam.jam.saturating_sub(1);
if sam.reloading > 0 {
sam.reloading -= 1;
if sam.reloading == 0 {
sam.missiles = spec.missile.as_ref().map_or(0, |m| m.magazine);
sam.missiles = sam.cells();
sam.bursts = spec.gun.as_ref().map_or(0, |g| g.bursts);
out.sound("minecraft:block.piston.extend", sam.pos, 2.0, 0.6);
}
@@ -1904,23 +1948,27 @@ impl Sim {
let pos = self.sams[i].pos;
let roles = self.sams[i].roles;
let (had_target, had_gun) = (self.sams[i].target, self.sams[i].gun_target);
let now = self.tick;
let (target, gun_target) = {
let (seen, own) = (&self.sams[i].seen, &self.sams[i].own);
// The conditions are `why`'s, shared with the diagnostic.
let allowed = |d: &Drone| why::allowed(roles, seen, d);
let tracks = &self.sams[i].tracks;
// The conditions are `why`'s, shared with the diagnostic. A system knows its targets by their tracks:
// the forecast of the last measurement, never the true place.
let drone = |tr: &Track| drone_at.get(&tr.id).map(|&k| &self.drones[k]);
let claimed = |d: &Drone| why::claimed(d, &missile_on, had_target);
let needed = why::needed;
let target = spec.missile.as_ref().map(|load| {
let in_reach = |d: &Drone, k: f64| why::in_reach(load.min, load.max, k, pos, d);
let keep = had_target.filter(|t| {
drone_at.get(t).is_some_and(|&k| allowed(&self.drones[k]) && in_reach(&self.drones[k], 1.1))
});
let ok = |tr: &Track, k: f64| {
drone(tr).is_some_and(|d| why::allowed(roles, tr, now, d) && why::in_reach(load.min, load.max, k, pos, tr.est(now)))
};
let keep = had_target.filter(|t| tracks.iter().any(|tr| tr.id == *t && ok(tr, 1.1)));
keep.or_else(|| {
self.drones
tracks
.iter()
.filter(|d| allowed(d) && in_reach(d, 1.0) && claimed(d) < needed(d))
.max_by(|a, b| a.threat(pos).total_cmp(&b.threat(pos)))
.map(|d| d.id)
.filter(|tr| ok(tr, 1.0))
.filter_map(|tr| drone(tr).map(|d| (tr, d)))
.filter(|(_, d)| claimed(d) < needed(d))
.max_by(|a, b| a.1.threat_at(pos, a.0.est(now)).total_cmp(&b.1.threat_at(pos, b.0.est(now))))
.map(|(_, d)| d.id)
})
});
// Guns: the nearest, spread over the targets the other guns and missiles aren't on.
@@ -1928,12 +1976,13 @@ impl Sim {
let on_it = |d: &Drone| {
(guns_on.get(&d.id).copied().unwrap_or(0) - u32::from(had_gun == Some(d.id))) as f64
};
self.drones
tracks
.iter()
.filter(|d| why::gun_candidate(roles, seen, own, gun.track, pos, d))
.map(|d| {
.filter_map(|tr| drone(tr).map(|d| (tr, d)))
.filter(|(tr, d)| why::gun_candidate(roles, tr, now, gun.track, pos, d))
.map(|(tr, d)| {
let busy = 1.0 + 2.0 * on_it(d) + if d.engaged > 0 { 1.5 } else { 0.0 };
(d.pos.distance(pos) * busy, d.id)
(tr.est(now).distance(pos) * busy, d.id)
})
.min_by(|a, b| a.0.total_cmp(&b.0))
.map(|(_, id)| id)
@@ -1957,18 +2006,23 @@ impl Sim {
}
let sam = &mut self.sams[i];
// What the turret or launcher points at: guns first when a target is close.
let aim = sam.gun_target.or(sam.target).and_then(|t| drone_at.get(&t).map(|&k| &self.drones[k]));
let aim = sam
.gun_target
.or(sam.target)
.filter(|t| drone_at.contains_key(t))
.and_then(|t| sam.track(t))
.map(|tr| (tr.id, tr.est(now), tr.vel));
sam.launched = sam.launched.saturating_sub(1);
let Some(aim) = aim else {
// Out of missiles or of shells, and nothing to shoot: reload now (both, as a
// combined system's crew would), not only once both are spent.
let spent = (spec.missile.is_some() && sam.missiles == 0) || (spec.gun.is_some() && sam.bursts == 0);
let spent = (spec.missile.is_some() && sam.missiles == 0 && sam.part(Part::Launcher) > 0.0) || (spec.gun.is_some() && sam.bursts == 0);
if spent && sam.reloading == 0 && !sam.empty {
if logistics {
sam.empty = true;
ammo_waits += 1;
} else {
sam.reloading = spec.reload
sam.reloading = sam.reload_time()
}
}
sam.state = if sam.reloading > 0 {
@@ -1984,7 +2038,8 @@ impl Sim {
};
let (mount, _) = sam.mount();
let lead_speed = spec.gun.as_ref().map_or(5.0, |g| g.shell);
let (lead, want_yaw, want_pitch) = why::aim_wants(mount, aim, lead_speed);
let (aim_id, aim_pos, aim_vel) = aim;
let (lead, want_yaw, want_pitch) = why::aim_wants(mount, aim_pos, aim_vel, lead_speed);
let cells = matches!(spec.muzzle, Muzzle::Cells);
match spec.family {
// Vertical launch: no aiming (the Tor's turret turns its radar to the target).
@@ -2007,7 +2062,7 @@ impl Sim {
SamState::Fire
} else if !vertical && aim_error > 0.15 {
SamState::Slew
} else if aim.pos.distance(mount) < self::SamKind::range(sam.kind) {
} else if aim_pos.distance(mount) < self::SamKind::range(sam.kind) {
SamState::Lock
} else {
SamState::Track
@@ -2015,8 +2070,16 @@ impl Sim {
// Guns.
if let (Some(gun), Some(gt)) = (&spec.gun, sam.gun_target) {
if let Some(t) = drone_at.get(&gt).map(|&k| &self.drones[k]) {
let dist = t.pos.distance(mount);
if why::gun_blocks(sam, aim.id, gt, aim_error, dist, gun.range) == 0 {
let est = sam.track(gt).map_or(t.pos, |tr| tr.est(now));
let dist = est.distance(mount);
let mut blocks = why::gun_blocks(sam, aim_id, gt, aim_error, dist, gun.range, now);
// A damaged gun jams now and then, for a while: the burst it was about to fire is lost.
let wear = 1.0 - sam.part(Part::Gun);
if blocks == 0 && wear > 0.0 && dice(self.seed, now, sam.id as u64, 77) < wear * 0.1 {
sam.jam = 30 + (dice(self.seed, now, sam.id as u64, 78) * 90.0) as u32;
blocks = why::JAMMED;
}
if blocks == 0 {
sam.gun_cooldown = 2;
sam.bursts -= 1;
sam.flash = 2;
@@ -2026,7 +2089,7 @@ impl Sim {
sam.empty = true;
ammo_waits += 1;
} else {
sam.reloading = spec.reload
sam.reloading = sam.reload_time()
}
}
let (_, rot) = sam.mount();
@@ -2053,7 +2116,9 @@ impl Sim {
}
// At night a gun sees what is lit (a searchlight, a flare) and little else.
let dark = if self.night && !self.lit.contains(&t.id) { lights::DARK_HITS } else { 1.0 };
let p = gun.p * fit * dark / t.kind.spec().stealth * (1.0 - dist / (gun.range * 1.3)).max(0.35);
// The aim point is the track's forecast: the farther it is from the truth, the more shells miss.
let off = est.distance(t.pos);
let p = gun.p * sam.gun_fit() * dark / (t.kind.spec().stealth * (1.0 + (off / 8.0).powi(2))) * (1.0 - dist / (gun.range * 1.3)).max(0.35);
if self.rng.chance(p) {
gun_hits.push((gt, sam.id));
} else {
@@ -2066,8 +2131,8 @@ impl Sim {
if let (Some(load), Some(mt)) = (&spec.missile, sam.target) {
let ready = why::missile_blocks(sam) == 0;
// The missile turns after its boost, but the launcher must point near the target.
let t = drone_at.get(&mt).map(|&k| &self.drones[k]);
let aligned = why::missile_aligned(spec.family, sam.yaw, mount, t, aim.id, mt, aim_error);
let t = sam.track(mt).filter(|_| drone_at.contains_key(&mt)).map(|tr| tr.est(now));
let aligned = why::missile_aligned(spec.family, sam.yaw, mount, t, aim_id, mt, aim_error);
if ready && aligned {
let n = load.magazine - sam.missiles;
let (muzzle, dir) = sam.muzzle(n);
@@ -2088,7 +2153,7 @@ impl Sim {
sam.empty = true;
ammo_waits += 1;
} else {
sam.reloading = spec.reload
sam.reloading = sam.reload_time()
}
}
}
@@ -2140,7 +2205,7 @@ impl Sim {
let mut done: Vec<(u32, Option<u32>, bool, u32)> = Vec::new(); // (missile, target, kill, sam)
let (mut missed, mut expired, mut orphaned) = (0u32, 0u32, 0u32);
let mut blocked = 0u32;
let sams_fit: HashMap<u32, f64> = self.sams.iter().map(|s| (s.id, s.fitness())).collect();
let sams_fit: HashMap<u32, f64> = self.sams.iter().map(|s| (s.id, 1.0 - 0.3 * (1.0 - s.health.clamp(0.0, 1.0)))).collect();
for m in &mut self.missiles {
m.age += 1;
let spec = m.kind.spec();
+7 -3
View File
@@ -36,10 +36,10 @@ impl Sam {
}
impl Sim {
/// Orders unit `i` to drive to `to`. False for one that can't (a depot, a wreck).
/// Orders unit `i` to drive to `to`. False for one that can't (a depot, a wreck, failed running gear).
pub fn order_move(&mut self, i: usize, to: DVec3) -> bool {
let Some(sam) = self.sams.get_mut(i) else { return false };
if !sam.alive() || !sam.kind.mobile() {
if !sam.alive() || !sam.kind.mobile() || sam.drive_speed() <= 0.0 {
return false;
}
sam.dest = Some(to);
@@ -75,6 +75,10 @@ impl Sim {
}
}
SamState::Moving => {
// The running gear failed on the way: it stops where it is and deploys there.
if sam.drive_speed() <= 0.0 {
sam.dest = None;
}
let Some(to) = sam.dest else {
sam.state = SamState::Deploying;
sam.march = sam.kind.march_ticks();
@@ -93,7 +97,7 @@ impl Sim {
sam.heading = slew(sam.heading, heading_of(flat), 0.06);
let ahead = DQuat::from_rotation_y(sam.heading) * DVec3::NEG_Z;
let turning = angle_diff(sam.heading, heading_of(flat)).abs();
let step = SPEED * (1.0 - turning / std::f64::consts::PI).max(0.2);
let step = SPEED * sam.drive_speed() * (1.0 - turning / std::f64::consts::PI).max(0.2);
let next = sam.pos + ahead * step;
let y = ground.at(next, now).unwrap_or(sam.pos.y);
sam.pos = DVec3::new(next.x, sam.pos.y + (y - sam.pos.y).clamp(-0.5, 0.5), next.z);
+60
View File
@@ -110,10 +110,16 @@ pub struct Recording {
/// The systems and objects as they stood: (id, kind, where).
pub sams: Vec<(u32, SamKind, DVec3)>,
pub objects: Vec<DVec3>,
/// The world clock's time of day (ticks) every `TIME_STEP` ticks of the recording, from its
/// start: replays show the sky of the raid, not the current one. Empty when the clock was unknown.
times: Vec<u64>,
/// Ticks the sky has been clear.
quiet: u32,
}
/// Ticks between the recording's clock samples.
const TIME_STEP: u32 = 20;
impl Track {
/// Where it was at `t` (the recording's ticks, fractional), if it was.
pub fn at(&self, origin: DVec3, t: f64) -> Option<DVec3> {
@@ -169,6 +175,7 @@ impl Recording {
tally: Tally::default(),
sams: sim.sams.iter().map(|s| (s.id, s.kind, s.pos)).collect(),
objects: sim.targets.clone(),
times: Vec::new(),
quiet: 0,
}
}
@@ -184,6 +191,19 @@ impl Recording {
}
}
}
/// The time of day (ticks, 24000 a day) the world showed at the recording's tick `t`: the
/// clock as sampled, run on between samples at the pace it ran (a jump is a step), or None
/// when the clock was not known (the replay then shows the world's own time).
pub fn day_time(&self, t: f64) -> Option<u64> {
let k = (t.max(0.0) / TIME_STEP as f64).floor() as usize;
let i = k.min(self.times.len().checked_sub(1)?);
let a = self.times[i];
let into = if i == k { t.max(0.0) - (i as u32 * TIME_STEP) as f64 } else { 0.0 };
match self.times.get(i + 1) {
Some(&b) if b >= a && b - a <= 2 * TIME_STEP as u64 => Some(a + ((b - a) as f64 * into / TIME_STEP as f64) as u64),
_ => Some(a),
}
}
pub fn track(&self, id: u32) -> Option<&Track> {
self.index.get(&id).map(|&i| &self.tracks[i])
}
@@ -211,6 +231,15 @@ impl Sim {
/// Something worth a replay happened.
pub(super) fn log(&mut self, pos: DVec3, kind: EventKind) {
match kind {
EventKind::Crash { power, .. } => self.ignite(pos, power, None),
EventKind::Hit { power, sam, .. } => {
let host = sam.and_then(|(_, i)| self.sams.get(i)).map(|s| s.id);
self.ignite(pos, power.max(1), host)
}
EventKind::SamLost { sam, .. } => self.ignite(pos, 2, Some(sam)),
_ => {}
}
if let Some(r) = &mut self.rec {
let at = r.len;
if let EventKind::Kill { drone, .. } = kind
@@ -236,6 +265,12 @@ impl Sim {
self.rec = Some(Recording::new(self.recordings, self));
}
let Some(r) = &mut self.rec else { return };
if r.len % TIME_STEP == 0
&& let Some(dt) = self.day_time
&& r.times.len() == (r.len / TIME_STEP) as usize
{
r.times.push(dt);
}
if r.len % STEP == 0 {
for d in &self.drones {
r.point(d.id, What::Drone(d.kind), d.pos);
@@ -310,6 +345,31 @@ impl Sim {
}
}
}
// Fires: what the events left burning (the flames dim and the smoke thickens with time).
let mut lit: Vec<(DVec3, f64)> = Vec::new();
for (k, e) in rec.events.iter().enumerate() {
let power = match e.kind {
EventKind::Crash { power, .. } => power,
EventKind::Hit { power, .. } => power.max(1),
EventKind::SamLost { .. } => 2,
_ => continue,
};
let age = t - e.at as f64;
// One fire where several events met.
if lit.iter().any(|(p, at)| p.distance(e.pos) < 6.0 && *at <= e.at as f64) {
continue;
}
lit.push((e.pos, e.at as f64));
let (flame, smoke) = fires::replay_fire(power, age);
let id = base + 0x00c0_0000 + k as u32 * PARTS;
if flame > 0.05 {
let wob = 1.0 + 0.15 * (age * 0.9 + k as f64).sin();
out.model(id, "airdef:flame", e.pos + DVec3::Y * 0.5, DQuat::from_rotation_y(age * 0.07), (flame as f64 * 0.8 * wob).max(0.05), true);
}
if smoke > 0.1 && (age as u64) % 3 == 0 {
out.particles("minecraft:large_smoke", e.pos + DVec3::Y, 0.8, DVec3::new(0.0, 0.1, 0.0), 0.03, 1 + (smoke * 2.0) as u32);
}
}
// Blasts: a fireball growing and fading for 1.5 s after each.
for (k, e) in rec.events.iter().enumerate() {
let age = t - e.at as f64;
+46
View File
@@ -501,3 +501,49 @@ fn wall_and_tunnel_fixtures_agree() {
}
assert!(ground.world.bytes() < 64 * 1024);
}
// #57: a recording keeps the world clock of the raid, with jumps as steps.
#[test]
fn recordings_keep_the_time_of_day() {
let mut sim = Sim::new(1);
sim.day_time = Some(18000);
sim.add_drone(DroneKind::Geran3, DVec3::new(0.0, 80.0, 0.0), DVec3::Z, DVec3::new(0.0, 70.0, 500.0));
let mut g = Ground::default();
let mut out = Out::default();
for i in 0..100u64 {
sim.day_time = Some(if i < 50 { 18000 + i } else { 6000 + i });
sim.step(&mut g, None, &mut out);
}
let r = sim.rec.as_ref().unwrap();
assert_eq!(r.day_time(0.0), Some(18000 + sim_first(r)));
// The jump is a step, not a glide through the day.
for t in 0..r.len.min(100) {
let v = r.day_time(t as f64).unwrap();
assert!((18000..18060).contains(&v) || (6000..6110).contains(&v), "{t}: {v}");
}
}
fn sim_first(r: &record::Recording) -> u64 {
r.tracks.first().map_or(0, |t| t.first as u64)
}
// #52: a crash lights a fire; the oldest of too many dies down; water leaves steam only.
#[test]
fn fires_start_merge_and_are_limited() {
let mut sim = Sim::new(1);
sim.ignite(DVec3::new(0.0, 70.0, 0.0), 1, None);
sim.ignite(DVec3::new(2.0, 70.0, 0.0), 2, None);
assert_eq!(sim.fires.len(), 1, "one fire where two things fell");
assert!(sim.fires.list[0].size >= fires::size_for(2));
for i in 0..30 {
sim.tick += 10;
sim.ignite(DVec3::new(100.0 * (i + 1) as f64, 70.0, 0.0), 1, None);
}
let now = sim.tick;
// Past the limit the oldest are already dying down.
let healthy = sim.fires.list.iter().filter(|f| (now - f.start) + 160 < f.life as u64).count();
assert!(healthy <= fires::MAX, "{healthy}");
let (fl, sm) = fires::level(10.0, 3000.0);
assert!(fl > 0.0 && sm > 0.0);
assert_eq!(fires::level(3000.0, 3000.0).0, 0.0);
}
+228
View File
@@ -0,0 +1,228 @@
//! Radar scan cycles with ageing tracks (#46) and damage to a system's parts (#50).
use super::sight::{swept, FORECAST_AGE};
use super::*;
fn flat() -> (Ground, Out) {
(Ground::default(), Out::default())
}
fn radar_at(sim: &mut Sim, kind: SamKind, x: f64) -> usize {
let id = sim.id();
sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
sim.sams.len() - 1
}
/// A Shahed flying east along z = 40, from x = `from`, high enough to be above any horizon of the systems.
fn drone_from(sim: &mut Sim, from: f64) -> u32 {
sim.add_drone(DroneKind::Shahed, DVec3::new(from, 95.0, 40.0), DVec3::X, DVec3::new(5000.0, 95.0, 40.0));
sim.drones.last().unwrap().id
}
// #46: the radar measures a target when the beam passes it; between passes its track stays where it was measured.
#[test]
fn a_radar_measures_once_a_turn_and_the_track_stays_put_between() {
let mut sim = Sim::new(5);
let (mut ground, mut out) = flat();
let r = radar_at(&mut sim, SamKind::Radar, 0.0);
let id = drone_from(&mut sim, -150.0);
let (mut seen_at, mut last) = (Vec::new(), None::<(u64, DVec3)>);
let mut stale_gap = 0.0f64;
for _ in 0..700 {
sim.step(&mut ground, None, &mut out);
let Some(t) = sim.sams[r].track(id).copied() else { continue };
match last {
Some((tick, pos)) if tick == t.tick => {
assert_eq!(pos, t.pos, "the track moved without a new measurement");
let d = sim.drones.iter().find(|d| d.id == id).unwrap();
stale_gap = stale_gap.max(d.pos.distance(t.pos));
if t.age(sim.tick) > FORECAST_AGE {
assert!(t.forecast(sim.tick));
}
}
_ => seen_at.push(t.tick),
}
last = Some((t.tick, t.pos));
}
assert!(seen_at.len() >= 2, "measured {} times", seen_at.len());
// A turn of the early-warning radar is 140 ticks (less relative to a target that moves round it): never every tick.
assert!(seen_at.windows(2).all(|w| w[1] - w[0] >= 60), "{seen_at:?}");
assert!(stale_gap > 20.0, "the track never fell behind the target ({stale_gap})");
}
#[test]
fn a_beam_crossing_north_between_ticks_still_passes_a_target_there() {
let tau = std::f64::consts::TAU;
assert!(swept(0.01, tau - 0.05, 0.1));
assert!(swept(tau - 0.02, tau - 0.05, 0.1));
assert!(!swept(0.2, tau - 0.05, 0.1));
assert!(!swept(tau - 0.1, tau - 0.05, 0.1));
}
#[test]
fn two_radars_have_their_own_phase_and_the_network_keeps_the_age() {
let mut sim = Sim::new(7);
let (mut ground, mut out) = flat();
let a = radar_at(&mut sim, SamKind::Radar, 0.0);
let b = radar_at(&mut sim, SamKind::Radar, 500.0);
let n = radar_at(&mut sim, SamKind::P1sun, 250.0);
assert_ne!(sim.sams[a].beam, sim.sams[b].beam, "radars start at different phases");
let id = drone_from(&mut sim, -50.0);
let mut relayed = 0;
for _ in 0..800 {
sim.step(&mut ground, None, &mut out);
let own = |s: usize| sim.sams[s].track(id).map_or(0, |t| t.own_tick);
let Some(t) = sim.sams[n].track(id) else { continue };
relayed += 1;
assert_eq!(t.own_tick, 0, "a relayed measurement is not the receiver's own");
assert!(t.tick <= own(a).max(own(b)), "the network made a track fresher than any measurement");
if own(a).max(own(b)) > 0 {
assert_eq!(t.tick, own(a).max(own(b)), "the network holds the freshest measurement");
}
}
assert!(relayed > 100, "the network never passed a track ({relayed})");
}
#[test]
fn a_lock_measures_every_tick_and_a_dead_radar_stops_the_feed() {
let mut sim = Sim::new(3);
let (mut ground, mut out) = flat();
let p = radar_at(&mut sim, SamKind::Pantsir, 0.0);
let net = radar_at(&mut sim, SamKind::P1sun, 100.0);
let id = drone_from(&mut sim, -190.0);
let mut locked = 0;
for _ in 0..600 {
sim.step(&mut ground, None, &mut out);
if sim.sams[p].target == Some(id)
&& let Some(t) = sim.sams[p].track(id)
&& t.age(sim.tick) <= 1
&& t.locked
{
locked += 1;
}
}
assert!(locked > 5, "no fire-control lock ({locked})");
// The radar is destroyed: the network's track is no longer renewed.
let newest = sim.sams[net].tracks.iter().map(|t| t.tick).max();
sim.sams[p].health = 0.0;
let drones = sim.drones.iter().filter(|d| d.alive()).count();
for _ in 0..40 {
sim.step(&mut ground, None, &mut out);
}
assert!(sim.sams[p].tracks.is_empty() && sim.sams[p].seen.is_empty());
if drones > 0 {
assert!(sim.sams[net].tracks.iter().map(|t| t.tick).max() <= newest, "a dead radar still renewed a track");
}
}
#[test]
fn a_failed_radar_gives_no_own_tracks_but_the_network_still_feeds_it() {
let mut sim = Sim::new(9);
let (mut ground, mut out) = flat();
let p = radar_at(&mut sim, SamKind::Patriot, 0.0);
let early = radar_at(&mut sim, SamKind::Radar, 120.0);
let id = drone_from(&mut sim, -150.0);
sim.sams[p].comps.0[Part::Sensor as usize] = 0.0;
for _ in 0..500 {
sim.step(&mut ground, None, &mut out);
}
assert!(!sim.sams[p].radar_up());
assert!(sim.sams[p].own.is_empty(), "a failed radar measured something");
assert!(sim.sams[p].track(id).is_some(), "the network should still feed the system");
// Without its link it is blind.
sim.sams[p].comps.0[Part::Comms as usize] = 0.0;
sim.sams[p].tracks.clear();
for _ in 0..200 {
sim.step(&mut ground, None, &mut out);
}
assert!(sim.sams[p].tracks.is_empty(), "no link, no network tracks");
assert!(sim.sams[early].own.len() >= sim.sams[p].own.len());
}
// #50: a blast hurts the parts nearest to it.
#[test]
fn a_blast_from_behind_hurts_the_link_a_blast_from_the_front_the_drive() {
let at = DVec3::new(0.0, 70.0, 0.0);
let hurt = |dz: f64| {
let mut sim = Sim::new(4);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Patriot, at, 0.0));
let mut out = Out::default();
sim.blast_damage(at + DVec3::new(0.0, 3.0, dz), 2, &mut out);
assert!(sim.sams[0].alive());
let c = sim.sams[0].comps;
(1.0 - c.get(Part::Comms), 1.0 - c.get(Part::Mount), 1.0 - c.get(Part::Sensor))
};
let (back_comms, back_mount, _) = hurt(6.0);
let (front_comms, front_mount, _) = hurt(-6.0);
assert!(back_comms > back_mount, "behind: link {back_comms} drive {back_mount}");
assert!(front_mount > front_comms, "front: link {front_comms} drive {front_mount}");
}
#[test]
fn a_close_blast_can_leave_a_firing_but_immobile_system() {
// Over many blasts at moderate range some leave the system able to fire and unable to drive.
let mut found = false;
for seed in 0..60 {
let mut sim = Sim::new(seed);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Pantsir, DVec3::new(0.0, 70.0, 0.0), 0.0));
let mut out = Out::default();
sim.tick = seed;
sim.blast_damage(DVec3::new(0.0, 69.0, 6.0 + seed as f64 * 0.06), 3, &mut out);
let s = &sim.sams[0];
if s.alive() && s.part(Part::Tracks) <= 0.0 && s.part(Part::Launcher) > 0.0 && s.part(Part::Gun) > 0.0 {
assert!(!sim.order_move(0, DVec3::new(300.0, 70.0, 0.0)), "failed running gear must refuse a march");
assert!(why::missile_blocks(&sim.sams[0]) & why::LAUNCHER_DOWN == 0);
assert!(sim.why(0).iter().any(|c| c.text.contains("ходовая отказала")), "{:?}", sim.why(0).iter().map(|c| &c.text).collect::<Vec<_>>());
found = true;
break;
}
}
assert!(found, "no seed left it firing but immobile");
}
#[test]
fn failed_parts_block_what_they_serve_and_repair_restores_them() {
let mut sim = Sim::new(2);
let g = radar_at(&mut sim, SamKind::Gepard, 0.0);
let p = radar_at(&mut sim, SamKind::Patriot, 400.0);
sim.sams[g].comps.0[Part::Gun as usize] = 0.0;
assert!(!sim.sams[g].gun_up());
assert!(why::gun_blocks(&sim.sams[g], 1, 1, 0.0, 10.0, 90.0, 0) & why::JAMMED != 0);
sim.sams[p].comps.0[Part::Launcher as usize] = 0.0;
assert!(why::missile_blocks(&sim.sams[p]) & why::LAUNCHER_DOWN != 0);
// A worn launcher: fewer cells, a longer reload.
sim.sams[p].comps.0[Part::Launcher as usize] = 0.3;
sim.sams[p].fit_cells();
let full = Sam::new(0, SamKind::Patriot, DVec3::ZERO, 0.0);
assert!(sim.sams[p].cells() < full.cells());
assert!(sim.sams[p].missiles <= sim.sams[p].cells());
assert!(sim.sams[p].reload_time() > full.reload_time());
// A worn mount turns slower, a failed one not at all.
sim.sams[p].comps.0[Part::Mount as usize] = 0.0;
assert_eq!(sim.sams[p].drive_fit(), 0.0);
sim.sams[p].comps.0[Part::Tracks as usize] = 0.0;
assert_eq!(sim.repair(), 2, "both damaged systems are counted");
assert!(sim.sams.iter().all(|s| s.comps.whole() && s.cells() == s.kind.spec().missile.as_ref().map_or(0, |m| m.magazine)));
assert!(sim.later.is_empty(), "repair must not leave cook-offs behind");
assert!(sim.order_move(p, DVec3::new(500.0, 70.0, 0.0)));
}
#[test]
fn the_same_seed_rolls_the_same_scan_and_damage() {
let run = || {
let mut sim = Sim::new(11);
let (mut ground, mut out) = flat();
let r = radar_at(&mut sim, SamKind::Radar, 0.0);
let id = drone_from(&mut sim, -150.0);
let mut ticks = Vec::new();
for _ in 0..500 {
sim.step(&mut ground, None, &mut out);
if let Some(t) = sim.sams[r].track(id) {
ticks.push(t.tick);
}
}
ticks
};
assert_eq!(run(), run());
}
+246 -22
View File
@@ -3,6 +3,17 @@
//! (over the curve of the earth, scaled to the game's distances), and the land
//! hides what flies behind hills and woods: each system keeps its horizon, the
//! highest the land rises seen from its antenna, ray by ray round it.
//!
//! A radar does not know where everything is all the time. Its beam sweeps round
//! (a period by the kind of radar; an electronic one also revisits what it holds
//! more often), a target is measured when the beam passes it, with a chance that
//! falls with range and size, and the measurement is kept as a *track*: where it
//! was and how fast it went then, and when. Between measurements the track is
//! carried on by that velocity (a forecast, shown as one), and after three missed
//! scans it is dropped. A fire-control lock on a target the system is engaging is
//! a dedicated channel: it measures every tick while the target is in reach and in
//! sight. The network passes tracks with the age of their measurement; relaying
//! makes none of them fresher.
use super::*;
/// Rays round a radar, and blocks between the land's samples along them.
@@ -10,6 +21,13 @@ const RAYS: usize = 48;
const STEP: f64 = 16.0;
/// How far units share their tracks (the network's data links).
pub(super) const LINK: f64 = 1500.0;
/// A launcher fires on a track no older than this (ticks); a gun needs its own radar's, newer than `GUN_AGE`.
pub(super) const MISSILE_AGE: u64 = 120;
pub(super) const GUN_AGE: u64 = 3;
/// A gun takes a target its radar measured this recently (then the lock refreshes it every tick).
pub(super) const GUN_PICK_AGE: u64 = 40;
/// A track older than this is shown as a forecast.
pub const FORECAST_AGE: u64 = 20;
/// Radio horizon: `HORIZON * (√mast + √height)` blocks.
const HORIZON: f64 = 35.0;
/// Anything this near is seen (and heard), whatever hides it.
@@ -70,13 +88,144 @@ pub(super) fn reach(sam: &Sam, kind: DroneKind, height: f64) -> f64 {
if spec.sensor <= 0.0 {
return 0.0;
}
let radar = spec.sensor * sam.fitness() * kind.rcs().powf(0.25);
let radar = spec.sensor * sam.radar_fit() * kind.rcs().powf(0.25);
let horizon = HORIZON * (spec.mast.sqrt() + height.max(0.0).sqrt());
radar.min(horizon).max(NEAR)
}
/// How a kind's radar looks round.
pub(super) struct Scan {
/// Ticks for the beam to go round.
pub period: u32,
/// An electronic radar: what it holds it revisits at once a third of the period, between the beam's passes.
pub agile: bool,
}
impl SamKind {
pub(super) fn scan(self) -> Scan {
let (period, agile) = match self {
SamKind::Patriot => (30, true),
SamKind::S400 => (36, true),
SamKind::S500 => (24, true),
SamKind::IrisT | SamKind::Nasams => (40, true),
SamKind::Buk => (50, false),
SamKind::Tor | SamKind::Pantsir => (40, false),
SamKind::Gepard => (50, false),
// The early-warning radar: a big antenna turning slowly.
SamKind::Radar => (140, false),
_ => (40, false),
};
Scan { period, agile }
}
}
/// How well a track says what it is.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Ident {
/// One measurement: something is there.
Unknown,
/// Measured again: a drone or missile by how it flies.
Probable,
/// Held by a lock or by several measurements.
Confirmed,
}
impl Ident {
pub fn name(self) -> &'static str {
match self {
Ident::Unknown => "неопознана",
Ident::Probable => "предположительно воздушная цель",
Ident::Confirmed => "подтверждена",
}
}
}
/// What a system knows of one target: the last measurement, not the target itself.
#[derive(Clone, Copy, Debug)]
pub struct Track {
pub id: u32,
/// Where it was and how it went when last measured (blocks, blocks a tick).
pub pos: DVec3,
pub vel: DVec3,
/// When that was, and when this system's own radar last measured it (0: never, the network's only).
pub tick: u64,
pub own_tick: u64,
/// Ticks the track lives without a new measurement.
pub ttl: u32,
pub hits: u8,
/// The last own measurement came from a fire-control lock.
pub locked: bool,
}
impl Track {
pub fn age(&self, now: u64) -> u64 {
now.saturating_sub(self.tick)
}
/// Where the target should be by now, carrying the last measurement on: the forecast, not a measurement.
pub fn est(&self, now: u64) -> DVec3 {
self.pos + self.vel * self.age(now) as f64
}
pub fn forecast(&self, now: u64) -> bool {
self.age(now) > FORECAST_AGE
}
/// Own radar measured it within `age` ticks.
pub fn own_within(&self, now: u64, age: u64) -> bool {
self.own_tick > 0 && now.saturating_sub(self.own_tick) <= age
}
pub fn ident(&self) -> Ident {
match self.hits {
0 | 1 => Ident::Unknown,
2 => Ident::Probable,
_ => Ident::Confirmed,
}
}
/// How far the forecast may be off, blocks: grows with the age.
pub fn uncertainty(&self, now: u64) -> f64 {
1.0 + self.age(now) as f64 * (0.05 + self.vel.length() * 0.1)
}
}
impl Sam {
/// Ticks for its beam to go round (longer when the radar is damaged).
pub(super) fn scan_ticks(&self) -> f64 {
self.kind.scan().period as f64 / self.radar_fit().max(0.2)
}
/// Its own radar works: it has one, it is not failed and the unit is deployed.
pub fn radar_up(&self) -> bool {
self.alive() && !self.moving() && self.kind.spec().sensor > 0.0 && self.part(Part::Sensor) > 0.0
}
pub fn track(&self, id: u32) -> Option<&Track> {
self.tracks.iter().find(|t| t.id == id)
}
}
/// Whether a beam that moved from `from` by `w` radians this tick passed `bearing` (all angles taken round 2π,
/// so a beam crossing north between two ticks still passes a target there).
pub(super) fn swept(bearing: f64, from: f64, w: f64) -> bool {
(bearing - from).rem_euclid(TAU) < w
}
/// A new measurement into a list of tracks (the index maps ids to places): a fresher one replaces an older.
fn merge(tracks: &mut Vec<Track>, index: &mut HashMap<u32, usize>, t: Track) {
match index.get(&t.id) {
Some(&k) => {
let mine = &mut tracks[k];
if t.tick > mine.tick {
let (own_tick, locked) = (mine.own_tick, if t.own_tick > 0 { t.locked } else { mine.locked });
let hits = mine.hits.max(t.hits);
*mine = Track { own_tick: if t.own_tick > 0 { t.own_tick } else { own_tick }, hits, locked, ..t };
}
}
None => {
index.insert(t.id, tracks.len());
tracks.push(t);
}
}
}
impl Sim {
/// Rebuilds the systems' horizons in turn, and what each radar holds now.
/// Rebuilds the systems' horizons in turn, then lets each radar's beam pass the sky: new measurements
/// into the tracks, old tracks out, and the network's tracks shared.
pub(super) fn update_sight(&mut self, ground: &mut Ground) {
let now = self.tick;
// One horizon every few ticks: the land answers come in over time.
@@ -95,44 +244,108 @@ impl Sim {
// Each drone's height over the land under it (or over the systems' ground, unknown).
let heights: Vec<Option<f64>> =
self.drones.iter().map(|d| ground.at(d.pos, now).map(|g| d.pos.y - g)).collect();
let drone_at: HashMap<u32, usize> = self.drones.iter().enumerate().map(|(k, d)| (d.id, k)).collect();
let seed = self.seed;
let mut index: HashMap<u32, usize> = HashMap::new();
for sam in &mut self.sams {
sam.seen.clear();
sam.own.clear();
if !sam.alive() || sam.kind.spec().sensor <= 0.0 || sam.moving() {
// A track of a drone that is gone is dropped (the kill is seen), so is one not renewed for its time.
sam.tracks.retain(|t| now - t.tick <= t.ttl as u64 && drone_at.get(&t.id).is_some_and(|&k| self.drones[k].alive()));
if !sam.alive() || sam.moving() {
sam.tracks.clear();
continue;
}
if !sam.radar_up() {
continue;
}
index.clear();
index.extend(sam.tracks.iter().enumerate().map(|(k, t)| (t.id, k)));
let spec = sam.kind.spec();
let scan = sam.kind.scan();
let period = sam.scan_ticks();
let w = TAU / period;
let (b0, ttl) = (sam.beam, ((period * 3.0) as u32).max(60));
sam.beam = (b0 + w) % TAU;
let at = antenna(sam);
let horizon = self.horizons.get(&sam.id);
let mut fresh: Vec<Track> = Vec::new();
for (d, h) in self.drones.iter().zip(&heights) {
if !d.alive() {
continue;
}
let dist = d.pos.distance(at);
let rel = d.pos - at;
let dist = rel.length();
if dist > spec.sensor * 1.2 {
continue;
}
let locked = sam.target == Some(d.id) || sam.gun_target == Some(d.id);
let held = index.get(&d.id).map(|&k| sam.tracks[k]);
// The beam passes its bearing this tick (the angle wraps at 2π: the difference is taken round).
let in_beam = swept(rel.x.atan2(-rel.z), b0, w);
let revisit = scan.agile && held.is_some_and(|t| t.own_tick > 0 && now - t.own_tick >= (period / 3.0) as u64);
if !(in_beam || locked || revisit) {
continue;
}
let height = h.unwrap_or(d.pos.y - sam.pos.y);
if dist > reach(sam, d.kind, height) {
let reach = reach(sam, d.kind, height);
if dist > reach || (dist > NEAR && horizon.is_some_and(|hz| hz.hides(at, d.pos))) {
continue;
}
if dist > NEAR && horizon.is_some_and(|hz| hz.hides(at, d.pos)) {
let key = (sam.id as u64) << 32 | d.id as u64;
// A target in the beam is measured with a chance that falls towards the edge of reach and
// with the target's stealth; one the radar already follows is lost only now and then.
let p = if locked || revisit {
0.985
} else {
((0.97 - 0.5 * (dist / reach).powi(3)) / d.kind.spec().stealth.sqrt()).clamp(0.05, 0.97)
};
if dist > NEAR && dice(seed, now, key, 0) >= p {
continue;
}
sam.own.push(d.id);
let sigma = if locked { 0.3 } else { 0.8 + dist * 0.004 };
let noise = DVec3::new(dice(seed, now, key, 1) - 0.5, (dice(seed, now, key, 2) - 0.5) * 0.5, dice(seed, now, key, 3) - 0.5) * 2.0 * sigma;
fresh.push(Track {
id: d.id,
pos: d.pos + noise,
vel: d.vel,
tick: now,
own_tick: now,
ttl,
hits: held.map_or(1, |t| t.hits.saturating_add(1)),
locked,
});
}
for t in fresh {
merge(&mut sam.tracks, &mut index, t);
}
}
// The network: every unit gets the tracks of the radars within data-link range.
let tracks: Vec<(DVec3, Vec<u32>)> =
self.sams.iter().filter(|s| !s.own.is_empty()).map(|s| (s.pos, s.own.clone())).collect();
// Merged in the radars' order, each track once: a set marks what is in already.
let mut have: std::collections::HashSet<u32> = std::collections::HashSet::new();
// The network: every unit gets the tracks the radars within data-link range measured themselves,
// with the time they were measured: a relayed track is never fresher than its measurement.
let shared: Vec<(u32, DVec3, f64, Vec<Track>)> = self
.sams
.iter()
.filter(|s| s.alive() && !s.moving() && s.link_range() > 0.0)
.map(|s| (s.id, s.pos, s.link_range(), s.tracks.iter().filter(|t| t.own_tick == t.tick).copied().collect::<Vec<_>>()))
.filter(|s| !s.3.is_empty())
.collect();
for sam in &mut self.sams {
sam.seen.clone_from(&sam.own);
if !sam.alive() || sam.moving() || !sam.kind.armed() {
continue;
if sam.alive() && !sam.moving() && sam.kind.armed() && sam.link_range() > 0.0 && !shared.is_empty() {
index.clear();
index.extend(sam.tracks.iter().enumerate().map(|(k, t)| (t.id, k)));
let mine = sam.link_range();
for (id, at, range, tracks) in &shared {
if *id != sam.id && at.distance(sam.pos) <= range.min(mine) {
for t in tracks {
merge(&mut sam.tracks, &mut index, Track { own_tick: 0, ..*t });
}
}
}
}
have.clear();
have.extend(sam.own.iter().copied());
for (at, ids) in &tracks {
if at.distance(sam.pos) <= LINK {
sam.seen.extend(ids.iter().copied().filter(|id| have.insert(*id)));
sam.seen.clear();
sam.own.clear();
for t in &sam.tracks {
sam.seen.push(t.id);
if t.own_within(now, t.ttl as u64) {
sam.own.push(t.id);
}
}
}
@@ -142,4 +355,15 @@ impl Sim {
pub fn tracked(&self, id: u32) -> bool {
self.sams.iter().any(|s| s.seen.contains(&id))
}
/// The freshest track of each drone any system holds: the air picture.
pub fn picture(&self) -> HashMap<u32, Track> {
let mut best: HashMap<u32, Track> = HashMap::new();
for t in self.sams.iter().flat_map(|s| s.tracks.iter()) {
if best.get(&t.id).is_none_or(|b| t.tick > b.tick) {
best.insert(t.id, *t);
}
}
best
}
}
+97 -32
View File
@@ -11,29 +11,32 @@ use super::*;
pub(super) const DEAD: u8 = 1;
pub(super) const ROLE: u8 = 2;
pub(super) const UNSEEN: u8 = 4;
/// Its track is older than a launcher fires on.
pub(super) const STALE: u8 = 8;
pub(super) fn target_blocks(roles: u8, seen: &[u32], d: &Drone) -> u8 {
pub(super) fn target_blocks(roles: u8, track: Option<&Track>, now: u64, d: &Drone) -> u8 {
(if d.alive() { 0 } else { DEAD })
| (if roles & d.kind.spec().class.bit() != 0 { 0 } else { ROLE })
| (if seen.contains(&d.id) { 0 } else { UNSEEN })
| (if track.is_some() { 0 } else { UNSEEN })
| (if track.is_some_and(|t| t.age(now) > sight::MISSILE_AGE) { STALE } else { 0 })
}
/// Alive, of a class the system engages, and on its picture (own radar or the network's).
pub(super) fn allowed(roles: u8, seen: &[u32], d: &Drone) -> bool {
target_blocks(roles, seen, d) == 0
/// Alive, of a class the system engages, and on its picture (own radar or the network's), fresh enough.
pub(super) fn allowed(roles: u8, track: &Track, now: u64, d: &Drone) -> bool {
target_blocks(roles, Some(track), now, d) == 0
}
pub(super) const TOO_CLOSE: u8 = 1;
pub(super) const TOO_FAR: u8 = 2;
/// Missile range: `min` to `max * k` (a target already held may stray to 1.1 × max).
pub(super) fn reach_blocks(min: f64, max: f64, k: f64, pos: DVec3, d: &Drone) -> u8 {
let dist = d.pos.distance(pos);
pub(super) fn reach_blocks(min: f64, max: f64, k: f64, pos: DVec3, at: DVec3) -> u8 {
let dist = at.distance(pos);
(if dist >= min { 0 } else { TOO_CLOSE }) | (if dist < max * k { 0 } else { TOO_FAR })
}
pub(super) fn in_reach(min: f64, max: f64, k: f64, pos: DVec3, d: &Drone) -> bool {
reach_blocks(min, max, k, pos, d) == 0
pub(super) fn in_reach(min: f64, max: f64, k: f64, pos: DVec3, at: DVec3) -> bool {
reach_blocks(min, max, k, pos, at) == 0
}
/// Interceptors a target has or will have: in flight, and other systems' launchers on it.
@@ -47,9 +50,10 @@ pub(super) fn needed(d: &Drone) -> u32 {
if d.kind.spec().class == Class::Ballistic { 2 } else { 1 }
}
/// A gun's candidates: held by the system's own radar and within the gun's tracking range.
pub(super) fn gun_candidate(roles: u8, seen: &[u32], own: &[u32], track: f64, pos: DVec3, d: &Drone) -> bool {
allowed(roles, seen, d) && own.contains(&d.id) && d.pos.distance(pos) < track
/// A gun's candidates: measured by the system's own radar a moment ago and within the gun's tracking range
/// (by the track's forecast, not the target's true place).
pub(super) fn gun_candidate(roles: u8, track: &Track, now: u64, gun_track: f64, pos: DVec3, d: &Drone) -> bool {
allowed(roles, track, now, d) && track.own_within(now, sight::GUN_PICK_AGE) && track.est(now).distance(pos) < gun_track
}
/// How many systems have each drone as their missile target and as their gun target.
@@ -66,8 +70,8 @@ pub(super) fn engagement_counts(sams: &[Sam]) -> (HashMap<u32, u32>, HashMap<u32
// ---------------------------------------------------------------- aiming
/// Where the lead point is and the yaw and pitch that point the mount at it.
pub(super) fn aim_wants(mount: DVec3, aim: &Drone, lead_speed: f64) -> (DVec3, f64, f64) {
let lead = aim.pos + aim.vel * (aim.pos.distance(mount) / lead_speed);
pub(super) fn aim_wants(mount: DVec3, at: DVec3, vel: DVec3, lead_speed: f64) -> (DVec3, f64, f64) {
let lead = at + vel * (at.distance(mount) / lead_speed);
let to = lead - mount;
let want_yaw = heading_of(to);
let want_pitch = (to.y / to.length().max(0.01)).asin().clamp(-0.1, 1.45);
@@ -88,19 +92,22 @@ pub(super) fn aim_error(family: Family, yaw: f64, pitch: f64, want_yaw: f64, wan
pub(super) const COOLDOWN: u8 = 1;
pub(super) const RELOADING: u8 = 2;
pub(super) const NO_ROUNDS: u8 = 4;
/// The launcher has failed.
pub(super) const LAUNCHER_DOWN: u8 = 8;
/// What keeps a loaded launcher from firing now (aim aside).
pub(super) fn missile_blocks(s: &Sam) -> u8 {
(if s.cooldown == 0 { 0 } else { COOLDOWN })
(if s.part(Part::Launcher) > 0.0 { 0 } else { LAUNCHER_DOWN })
| (if s.cooldown == 0 { 0 } else { COOLDOWN })
| (if s.reloading == 0 { 0 } else { RELOADING })
| (if s.missiles > 0 { 0 } else { NO_ROUNDS })
}
/// The launcher points near enough: a trainable one only by its training, a turret by its
/// whole aim at this target, the vertical ones need nothing.
pub(super) fn missile_aligned(family: Family, yaw: f64, mount: DVec3, t: Option<&Drone>, aim_id: u32, mt: u32, aim_error: f64) -> bool {
pub(super) fn missile_aligned(family: Family, yaw: f64, mount: DVec3, t: Option<DVec3>, aim_id: u32, mt: u32, aim_error: f64) -> bool {
match family {
Family::Trainable => t.is_some_and(|t| angle_diff(yaw, heading_of(t.pos - mount)).abs() < 0.15),
Family::Trainable => t.is_some_and(|t| angle_diff(yaw, heading_of(t - mount)).abs() < 0.15),
Family::Turret => aim_id == mt && aim_error < 0.15,
_ => true,
}
@@ -109,11 +116,17 @@ pub(super) fn missile_aligned(family: Family, yaw: f64, mount: DVec3, t: Option<
pub(super) const NOT_AIMED: u8 = 8;
pub(super) const AIM_ERROR: u8 = 16;
pub(super) const OUT_OF_RANGE: u8 = 32;
/// The gun is jammed (for a while, or failed).
pub(super) const JAMMED: u8 = 64;
/// Its radar has no fresh measurement of the target.
pub(super) const NO_LOCK: u8 = 128;
/// What keeps a gun from firing now: the turret on another target, not yet laid, out of range,
/// and the gun's own cooldown, reload and shells (`COOLDOWN`, `RELOADING`, `NO_ROUNDS` bits).
pub(super) fn gun_blocks(s: &Sam, aim_id: u32, gt: u32, aim_error: f64, dist: f64, range: f64) -> u8 {
pub(super) fn gun_blocks(s: &Sam, aim_id: u32, gt: u32, aim_error: f64, dist: f64, range: f64, now: u64) -> u8 {
(if aim_id == gt { 0 } else { NOT_AIMED })
| (if s.gun_up() { 0 } else { JAMMED })
| (if s.track(gt).is_some_and(|t| t.own_within(now, sight::GUN_AGE)) { 0 } else { NO_LOCK })
| (if aim_error < 0.1 { 0 } else { AIM_ERROR })
| (if dist < range { 0 } else { OUT_OF_RANGE })
| (if s.gun_cooldown == 0 { 0 } else { COOLDOWN })
@@ -160,9 +173,38 @@ impl Sim {
let logistics = self.logistics();
let (missile_on, guns_on) = engagement_counts(&self.sams);
let alive = self.drones.iter().filter(|d| d.alive()).count();
let now = self.tick;
let seen = self.drones.iter().filter(|d| d.alive() && sam.seen.contains(&d.id)).count();
let own = self.drones.iter().filter(|d| d.alive() && sam.own.contains(&d.id)).count();
v.push(check(alive > 0, format!("в небе {alive}, на картине {seen} (своя РЛС {own}, остальные по сети)")));
// The parts: what is worn or failed and what it costs.
if !sam.comps.whole() {
v.push(check(false, format!("узлы: {}", sam.parts_text())));
}
for p in Part::ALL {
if !p.on(sam.kind) || sam.part_state(p) == PartState::Ok {
continue;
}
let failed = sam.part_state(p) == PartState::Failed;
let effect = match (p, failed) {
(Part::Sensor, true) => "РЛС отказала: своих измерений нет, стволы не стреляют, ракеты — по данным сети".to_string(),
(Part::Sensor, false) => format!("РЛС повреждена: дальность {:.0}%, обзор вдвое реже при худшем", sam.radar_fit() * 100.0),
(Part::Mount, true) => format!("привод наведения заклинил: стоит на {:.0}°, не доворачивается", sam.yaw.to_degrees().rem_euclid(360.0)),
(Part::Mount, false) => format!("привод наведения повреждён: поворот {:.0}% от нормы", sam.drive_fit() * 100.0),
(Part::Launcher, true) => "пусковая отказала: пуски невозможны".to_string(),
(Part::Launcher, false) => format!("пусковая повреждена: {} ячеек из {}, перезарядка {:.0} с", sam.cells(), spec.missile.as_ref().map_or(0, |m| m.magazine), sam.reload_time() as f64 / 20.0),
(Part::Gun, true) => "орудие заклинило: не стреляет".to_string(),
(Part::Gun, false) => format!("орудие повреждено: меткость {:.0}%, заклинивает", sam.gun_fit() * 100.0),
(Part::Tracks, true) => "ходовая отказала: на марш не выйдет".to_string(),
(Part::Tracks, false) => format!("ходовая повреждена: скорость марша {:.0}%", sam.drive_speed() * 100.0),
(Part::Comms, true) => "связь отказала: сети нет, цели только свои".to_string(),
(Part::Comms, false) => format!("связь повреждена: линия {:.0} м", sam.link_range()),
};
v.push(check(false, effect));
}
if sam.jam > 0 {
v.push(check(false, format!("орудие заклинило, ещё {:.1} с", sam.jam as f64 / 20.0)));
}
let drone_at = |id: u32| self.drones.iter().find(|d| d.id == id);
let subject = sam.target.or(sam.gun_target).and_then(drone_at).or_else(|| {
self.drones
@@ -175,24 +217,42 @@ impl Sim {
return v;
};
let held = sam.target == Some(t.id) || sam.gun_target == Some(t.id);
let dist = t.pos.distance(sam.pos);
let dist = sam.track(t.id).map_or(t.pos, |tr| tr.est(self.tick)).distance(sam.pos);
v.push(check(
true,
format!("цель: {} {}, {}", t.kind.spec().name, if held { "(сопровождается)" } else { "(самая опасная)" }, crate::panel::distance(dist)),
));
let blocks = target_blocks(sam.roles, &sam.seen, t);
let track = sam.track(t.id);
let blocks = target_blocks(sam.roles, track, now, t);
// Where the system believes the target is: its track's forecast (the true place only when it has no track).
let est = track.map_or(t.pos, |tr| tr.est(now));
let evel = track.map_or(t.vel, |tr| tr.vel);
v.push(check(
blocks & ROLE == 0,
format!("роль: {} {} [{}]", t.kind.spec().class.name(), if blocks & ROLE == 0 { "в ролях" } else { "не в ролях" }, roles_text(sam.roles)),
));
let detect = match (sam.own.contains(&t.id), sam.seen.contains(&t.id)) {
(true, _) => "обнаружена своей РЛС",
(false, true) => "видна только по сети (стволы не стреляют)",
_ => "не обнаружена ни своей РЛС, ни сетью",
let detect = match (track, sam.own.contains(&t.id)) {
(Some(tr), own) => {
let kind = if own { "своей РЛС" } else { "по сети (стволы не стреляют)" };
let age = tr.age(now) as f64 / 20.0;
let lock = if tr.own_within(now, sight::GUN_AGE) && tr.locked { ", захват" } else { "" };
let how = if tr.forecast(now) { format!("прогноз ±{:.0} м", tr.uncertainty(now)) } else { "измерение".to_string() };
format!("трек {kind}: {}, возраст {age:.1} с, {how}{lock}, {}", tr.ident().name(), if blocks & STALE != 0 { "устарел для пуска" } else { "годен для пуска" })
}
_ => "не обнаружена ни своей РЛС, ни сетью".to_string(),
};
v.push(check(blocks & UNSEEN == 0, detect));
let fit = sam.fitness();
v.push(check(fit >= 0.9, format!("состояние {:.0}%: поворот и точность {:.0}%", sam.health * 100.0, fit * 100.0)));
v.push(check(blocks & (UNSEEN | STALE) == 0, detect));
if sam.kind.spec().sensor > 0.0 {
let period = sam.scan_ticks();
v.push(check(
sam.radar_up(),
if sam.radar_up() {
format!("обзор: оборот {:.1} с{}, луч на {:.0}°", period / 20.0, if sam.kind.scan().agile { ", электронный, цели в треке чаще" } else { "" }, sam.beam.to_degrees())
} else {
"обзор: РЛС не работает".to_string()
},
));
}
// Ammunition and its supply.
let mut rounds = String::new();
if let Some(load) = &spec.missile {
@@ -211,12 +271,12 @@ impl Sim {
v.push(check(sam.reloading == 0 && !sam.empty && (sam.missiles > 0 || sam.bursts > 0), format!("{rounds}— {supply}")));
let mount = sam.mount().0;
let lead_speed = spec.gun.as_ref().map_or(5.0, |g| g.shell);
let (_, want_yaw, want_pitch) = aim_wants(mount, t, lead_speed);
let (_, want_yaw, want_pitch) = aim_wants(mount, est, evel, lead_speed);
let err = aim_error(spec.family, sam.yaw, sam.pitch, want_yaw, want_pitch);
let vertical = spec.family == Family::Vertical;
let mut fires = false;
if let Some(load) = &spec.missile {
let reach = reach_blocks(load.min, load.max, 1.0, sam.pos, t);
let reach = reach_blocks(load.min, load.max, 1.0, sam.pos, est);
v.push(check(
reach == 0,
format!(
@@ -241,15 +301,18 @@ impl Sim {
if mb & NO_ROUNDS != 0 {
why.push("нет ракет".to_string());
}
if mb & LAUNCHER_DOWN != 0 {
why.push("пусковая отказала".to_string());
}
v.push(check(mb == 0, if mb == 0 { "пусковая готова".to_string() } else { format!("пусковая не готова: {}", why.join(", ")) }));
let aligned = missile_aligned(spec.family, sam.yaw, mount, Some(t), t.id, t.id, err);
let aligned = missile_aligned(spec.family, sam.yaw, mount, Some(est), t.id, t.id, err);
let turn = if vertical { "вертикальный старт" } else { "доворот" };
v.push(check(aligned, format!("{turn}: ошибка наведения {:.0}°{}", err.to_degrees(), if aligned { "" } else { " — ещё доворачивается" })));
fires |= reach == 0 && free < need && mb == 0 && aligned && blocks == 0;
}
if let Some(gun) = &spec.gun {
let on_it = guns_on.get(&t.id).copied().unwrap_or(0) - u32::from(sam.gun_target == Some(t.id));
let cand = gun_candidate(sam.roles, &sam.seen, &sam.own, gun.track, sam.pos, t);
let cand = track.is_some_and(|tr| gun_candidate(sam.roles, tr, now, gun.track, sam.pos, t));
v.push(check(
cand,
format!(
@@ -259,7 +322,7 @@ impl Sim {
if cand { "" } else { " — вне сопровождения (нужна своя РЛС)" }
),
));
let gb = gun_blocks(sam, t.id, t.id, err, mount.distance(t.pos), gun.range);
let gb = gun_blocks(sam, t.id, t.id, err, mount.distance(est), gun.range, now);
let mut why = Vec::new();
for (bit, name) in [
(AIM_ERROR, format!("орудие ещё наводится ({:.0}°)", err.to_degrees())),
@@ -267,6 +330,8 @@ impl Sim {
(COOLDOWN, "пауза между очередями".to_string()),
(RELOADING, "перезарядка".to_string()),
(NO_ROUNDS, "нет снарядов".to_string()),
(JAMMED, "орудие заклинило".to_string()),
(NO_LOCK, "нет свежего захвата своей РЛС".to_string()),
] {
if gb & bit != 0 {
why.push(name);