Redesign in-game menu with tabbed canvas UI and add logistics routes, secondary detonation, and RM48U tracking
build / mod (push) Failing after 15s

This commit is contained in:
2026-12-04 14:16:21 +03:00
parent 76ef94b537
commit 48ec72d3d2
18 changed files with 2461 additions and 924 deletions
+104 -885
View File
File diff suppressed because it is too large Load Diff
+65 -6
View File
@@ -253,7 +253,7 @@ pub struct MapUi {
heading: f64,
ed_sel: Option<EdSel>,
note: Option<(String, u64)>,
dirty: bool,
pub(crate) dirty: bool,
drawn: u64,
buttons: Vec<Btn>,
chunks_at: u64,
@@ -891,6 +891,11 @@ impl AirDef {
return;
}
let Some(p) = crate::player() else { return };
if self.menu.is_some() {
self.menu = None;
self.menu_ui.search_focus = false;
self.menu_ui.clear_hits();
}
let ui = &mut self.map;
ui.open = true;
ui.mode = Mode::View;
@@ -918,9 +923,18 @@ impl AirDef {
self.map.drag = None;
}
pub(crate) fn map_yield_canvas(&mut self) {
self.map.open = false;
self.map.draft = Draft::default();
self.map.mode = Mode::View;
self.map.drag = None;
}
pub(crate) fn open_unit_map(&mut self, unit: u32, centre: bool) {
self.close_menu();
self.post.transition = Some((crate::post::Transition::Map { unit, centre }, false));
self.menu = None;
self.menu_ui.search_focus = false;
self.menu_ui.clear_hits();
self.show_unit_on_map(unit, centre);
}
pub(crate) fn show_unit_on_map(&mut self, id: u32, centre: bool) {
@@ -955,10 +969,14 @@ impl AirDef {
let mut ui = std::mem::take(&mut self.map);
for ev in render::canvas_events() {
self.map_event(&mut ui, ev);
if ui.close {
if ui.close || !ui.open || self.menu.is_some() {
break;
}
}
if !ui.open || self.menu.is_some() {
self.map = ui;
return;
}
if ui.close {
ui.close = false;
self.map = ui;
@@ -1349,8 +1367,11 @@ impl AirDef {
if matches!(ui.mode, Mode::View)
&& let Some(Sel::Sam(id)) = ui.sel
{
self.post.transition = Some((crate::post::Transition::Card(id), false));
ui.close = true;
ui.open = false;
ui.draft = Draft::default();
ui.mode = Mode::View;
ui.drag = None;
self.open_menu(crate::Page::Unit(id, crate::post::From::Map(id)));
}
}
Act::Follow => {
@@ -1837,6 +1858,10 @@ impl AirDef {
if ui.filters[F_OBJECTS] {
self.map_objects(ui, &mut s, &draft, &armed, &mut labs, &mut taken);
}
// Logistics & unit march routes (under systems).
if !editing && ui.filters[F_SAMS] {
self.map_logistics(ui, &mut s);
}
// Systems.
if ui.filters[F_SAMS] {
self.map_sams(ui, &mut s, &draft, &mut labs, &mut taken);
@@ -1936,6 +1961,40 @@ impl AirDef {
}
/// The systems: merged where they crowd, with short names; the filter by class applies.
fn map_logistics(&self, ui: &MapUi, s: &mut Vec<Shape>) {
for (i, sam) in self.sim.sams.iter().enumerate() {
if !sam.alive() {
continue;
}
let selected = ui.sel == Some(Sel::Sam(sam.id));
let is_tzm = sam.kind == SamKind::Tzm && (sam.job().is_some() || sam.moving());
let is_march = sam.moving() && sam.dest.is_some() && (selected || sam.kind == SamKind::Tzm);
if !is_tzm && !is_march {
continue;
}
let pts = self.sim.unit_route(i, 24);
if pts.len() < 2 {
continue;
}
let col = match self.sim.tzm_job_kind(i) {
Some("rm48u" | "return") => alpha(0xFFB85C, 0.8),
Some("deliver") => alpha(0x70E888, 0.8),
Some("fetch") => alpha(0x60D0D0, 0.7),
_ => alpha(0x80C8FF, 0.65),
};
let width = if selected { 1.6 } else { 1.1 };
let mut prev = ui.to_screen(pts[0][0], pts[0][1]);
for p in &pts[1..] {
let next = ui.to_screen(p[0], p[1]);
s.push(line(prev, next, width, col));
prev = next;
}
if ui.on_screen(prev, 10.0) {
s.push(diamond(prev.0, prev.1, 2.5, col));
}
}
}
fn map_sams(&self, ui: &mut MapUi, s: &mut Vec<Shape>, draft: &Draft, labs: &mut Vec<Lab>, taken: &mut Vec<[f32; 4]>) {
let editing = ui.mode == Mode::Editor;
// (id, kind, position, heading, ghost, alive, place in the draft, number)
File diff suppressed because it is too large Load Diff
+16 -3
View File
@@ -4,7 +4,7 @@ use crate::sim::{Part, PartState, Sam, SamKind, SamState, battery::RadarRole, de
/// Keep enough room under the engine's 512-row limit for large layouts.
pub const PAGE_SIZE: usize = 200;
#[derive(Clone, Copy, Default, PartialEq, Eq)]
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
pub enum Filter {
#[default]
All,
@@ -18,7 +18,7 @@ pub enum Filter {
}
impl Filter {
const ALL: [Self; 8] = [
pub const ALL: [Self; 8] = [
Self::All, Self::Weapons, Self::Sensors, Self::Support, Self::InCombat,
Self::NoAmmo, Self::NoLink, Self::Damaged,
];
@@ -27,6 +27,19 @@ impl Filter {
Self::ALL[(self as usize + 1) % Self::ALL.len()]
}
pub fn short_label(self) -> &'static str {
match self {
Self::All => "Все",
Self::Weapons => "Огневые",
Self::Sensors => "РЛС/Опт",
Self::Support => "Тыл",
Self::InCombat => "В бою",
Self::NoAmmo => "Нет БК",
Self::NoLink => "Нет связи",
Self::Damaged => "Повр.",
}
}
pub fn label(self) -> &'static str {
match self {
Self::All => "Все",
@@ -60,7 +73,7 @@ impl Filter {
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum From {
World,
Post,
+78 -10
View File
@@ -301,16 +301,24 @@ impl Sim {
let pos = sam.pos + DVec3::Y;
out.messages.push(format!("{} №{} УНИЧТОЖЕН", sam.kind.name(), i + 1));
let (id, kind) = (sam.id, sam.kind);
// A depot's stock (or a truck's load) goes up with it.
let stock = if matches!(self.sams[i].kind, SamKind::Depot | SamKind::Tzm) {
// A depot's stock (or a truck's load) goes up with it, scaled by actual typed stocks & RM48U rounds.
let is_carrier = matches!(kind, SamKind::Depot | SamKind::Tzm);
let stock_packs = if is_carrier {
self.sams[i].ammo_stock.total().max(self.sams[i].cargo)
} else {
0
};
let stock_charge = if is_carrier {
let typed_charge = self.sams[i].ammo_stock.blast_charge();
if typed_charge > 0.0 { typed_charge } else { f64::from(self.sams[i].cargo) }
} else {
0.0
};
self.sams[i].ammo_stock = AmmoStock::default();
self.sams[i].cargo = 0;
self.sams[i].reload_mask = 0;
let typed = self.sams[i].ground_stock + self.sams[i].air_48n6_stock;
let rm48u_rounds = self.sams[i].ground_stock + self.sams[i].ground_rounds;
let air_48n6 = self.sams[i].air_48n6_stock;
self.sams[i].ground_stock = 0;
self.sams[i].air_48n6_stock = 0;
self.sams[i].ground_rounds = 0;
@@ -318,16 +326,35 @@ impl Sim {
self.sams[i].auto_ground_request = false;
self.sams[i].ground_return = false;
self.sams[i].return_cargo = false;
let missiles = missiles + stock * 2 + typed;
let charge = spec.missile.as_ref().map_or(0.0, |m| m.kind.charge() * missiles as f64) + bursts as f64 / 60.0
+ stock as f64 * 1.5;
let charge = spec.missile.as_ref().map_or(0.0, |m| m.kind.charge() * missiles as f64)
+ bursts as f64 / 60.0
+ stock_charge
+ rm48u_rounds as f64 * 3.0
+ air_48n6 as f64 * 1.2;
if is_carrier && charge >= 4.0 {
out.messages.push(format!("Вторичная детонация боекомплекта ({} №{})!", kind.name(), i + 1));
}
// The vehicle's own fuel and the first of its load at once, then the rest cooking off.
let first = (1.0 + charge * 0.6).round().clamp(1.0, 8.0) as u32;
let first = (1.0 + charge * 0.55).round().clamp(1.0, 10.0) as u32;
self.later.push((now + 2, pos, first, false));
for k in 0..missiles.min(40) {
for k in 0..rm48u_rounds.min(12) {
let when = now + 12 + (k as u64) * 14 + (self.rng.f() * 18.0) as u64;
let at = pos + DVec3::new(self.rng.s() * 4.0, self.rng.f() * 2.5, self.rng.s() * 4.0);
let tnt = if charge >= 10.0 { 5 } else { 4 };
self.later.push((when, at, tnt, true));
}
let cookoffs = (missiles + stock_packs * 2 + air_48n6).min(36);
let spread = if is_carrier { 4.5 } else { 3.0 };
for k in 0..cookoffs {
let when = now + 15 + (k as u64) * 12 + (self.rng.f() * 25.0) as u64;
let at = pos + DVec3::new(self.rng.s() * 3.0, self.rng.f() * 2.0, self.rng.s() * 3.0);
let tnt = if charge > 4.0 && self.rng.chance(0.4) { 2 } else { 1 };
let at = pos + DVec3::new(self.rng.s() * spread, self.rng.f() * 2.0, self.rng.s() * spread);
let tnt = if charge >= 12.0 && self.rng.chance(0.45) {
3
} else if charge > 4.0 && self.rng.chance(0.4) {
2
} else {
1
};
self.later.push((when, at, tnt, true));
}
self.emit_combat_event(pos, record::EventKind::SamLost { sam: id, kind, index: i });
@@ -602,4 +629,45 @@ mod cover_tests {
let source = DVec3::new(8.5, 71.5, 8.5);
assert_eq!(ground.world.blast_cover(source, end, 10), Some(false));
}
#[test]
fn depot_secondary_detonation_scales_with_typed_stock_and_rm48u() {
// Empty depot produces minimal blast and no secondary detonation warning.
let mut empty = Sim::new(7);
let id0 = empty.id();
let mut depot_empty = Sam::new(id0, SamKind::Depot, DVec3::new(0.0, 70.0, 0.0), 0.0);
depot_empty.clear_ammo();
depot_empty.ground_stock = 0;
empty.sams.push(depot_empty);
let mut empty_out = Out::default();
empty.destroy(0, &mut empty_out);
assert_eq!(empty.later.len(), 1);
assert_eq!(empty.later[0].2, 1);
assert!(!empty_out.messages.iter().any(|m| m.contains("Вторичная детонация")));
// Stocked depot with S-400 reloads and RM48U produces a heavy primary blast, secondary cook-offs, and damages nearby SAM within 16m.
let mut loaded = Sim::new(7);
let d_id = loaded.id();
let mut depot = Sam::new(d_id, SamKind::Depot, DVec3::new(0.0, 70.0, 0.0), 0.0);
depot.clear_ammo();
depot.set_ammo(AmmoKind::S400Missile, 6);
depot.ground_stock = 3;
loaded.sams.push(depot);
let s_id = loaded.id();
loaded.sams.push(Sam::new(s_id, SamKind::Tor, DVec3::new(12.0, 70.0, 0.0), 0.0));
let mut loaded_out = Out::default();
loaded.destroy(0, &mut loaded_out);
assert!(loaded_out.messages.iter().any(|m| m.contains("Вторичная детонация")));
assert!(loaded.later[0].2 >= 8, "expected power-4 primary tnt >= 8, got {}", loaded.later[0].2);
assert!(loaded.later.len() > 10, "expected multiple cook-offs, got {}", loaded.later.len());
// Advance simulation past primary blast tick (now + 2) so blast_damage hits the nearby SAM at 12 blocks.
let mut g = Ground::default();
for _ in 0..4 {
loaded.tick += 1;
loaded.step_later(&mut g, None, &mut Out::default());
}
assert!(loaded.sams[1].health < 0.6, "nearby SAM at 12m must suffer heavy secondary blast, health={}", loaded.sams[1].health);
}
}
+132 -14
View File
@@ -112,6 +112,20 @@ impl AmmoKind {
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.
@@ -197,6 +211,14 @@ impl AmmoStock {
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 {
@@ -330,6 +352,13 @@ impl Sim {
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];
@@ -456,7 +485,7 @@ impl Sim {
}
// 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);
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 {
@@ -550,14 +579,22 @@ impl Sim {
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)
&& AmmoKind::ALL.into_iter().any(|k| demand[k.index()] > truck_stock.get(k) && d.ammo_stock.get(k) > 0)
.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(|a, b| a.pos.distance(at).total_cmp(&b.pos.distance(at)).then(a.id.cmp(&b.id)))
.map(|d| (d.id, d.pos))
.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()
@@ -578,19 +615,46 @@ impl Sim {
}
}
/// Reachable waiting systems sorted by distance from `at`, with each system's needed weapon channels.
fn waiting_needs(&self, truck_id: u32, at: DVec3, now: u64, taken: &[u32]) -> Vec<(u32, DVec3, f64, [Option<AmmoKind>; 2])> {
let mut out: Vec<_> = self
/// 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();
(m.is_some() || g.is_some()).then(|| (s.id, s.pos, s.pos.distance(at), [m, g]))
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();
out.sort_by(|a, b| a.2.total_cmp(&b.2).then(a.0.cmp(&b.0)));
out
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`).
@@ -1335,4 +1399,58 @@ mod tests {
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());
}
}
+49
View File
@@ -1721,6 +1721,55 @@ impl Sim {
self.targets.iter().copied().min_by(|a, b| a.distance_squared(to).total_cmp(&b.distance_squared(to)))
}
/// Remaining horizontal waypoints `[x, z]` for unit `i` along its current march or truck job.
pub fn unit_route(&self, i: usize, max_points: usize) -> Vec<[f64; 2]> {
let Some(sam) = self.sams.get(i) else { return Vec::new() };
if !sam.alive() {
return Vec::new();
}
let dest = if sam.moving() {
sam.dest
} else if sam.kind == SamKind::Tzm {
sam.job.and_then(|jid| self.sams.iter().find(|u| u.id == jid && u.alive()).map(|u| u.pos))
} else {
None
};
let Some(dest) = dest else { return Vec::new() };
self.routes.remaining_points(sam.id, sam.pos, dest, max_points)
}
/// Short tag describing unit `i`'s active logistics or march assignment (`rm48u`, `return`, `fetch`, `deliver`, `march`).
pub fn tzm_job_kind(&self, i: usize) -> Option<&'static str> {
let sam = self.sams.get(i)?;
if !sam.alive() {
return None;
}
if sam.kind == SamKind::Tzm
&& let Some(job_id) = sam.job
&& let Some(dest) = self.sams.iter().find(|u| u.id == job_id && u.alive())
{
if sam.return_cargo || dest.ground_return {
return Some("return");
}
if sam.ground_stock > 0
|| dest.ground_request
|| (dest.kind == SamKind::Depot
&& dest.ground_stock > 0
&& self.sams.iter().any(|u| u.alive() && u.ground_request))
{
return Some("rm48u");
}
if dest.kind == SamKind::Depot {
return Some("fetch");
}
return Some("deliver");
}
if sam.moving() && sam.dest.is_some() {
return Some("march");
}
None
}
fn add_drone(&mut self, kind: DroneKind, from: DVec3, dir: DVec3, target: DVec3) {
// Its navigation error is drawn in `make_drone`, the one path of manual and raid launches (#65).
let d = self.make_drone(kind, from, dir, target);
+29
View File
@@ -241,6 +241,29 @@ impl Route {
}
total
}
/// Remaining horizontal route polyline `[x, z]` from `pos` to goal, subsampled to at most `max_points`.
pub(super) fn remaining_points(&self, pos: DVec3, max_points: usize) -> Vec<[f64; 2]> {
let cap = max_points.max(2);
let mut out = vec![[pos.x, pos.z]];
if self.next >= self.pts.len() {
out.push([self.dest.x, self.dest.z]);
return out;
}
let rem = &self.pts[self.next..];
let body = cap - 1;
if rem.len() <= body {
for &pt in rem {
out.push([pt.x, pt.z]);
}
} else {
for i in 0..body {
let idx = (i * (rem.len() - 1)) / (body - 1);
let pt = rem[idx];
out.push([pt.x, pt.z]);
}
}
out
}
pub(super) fn new(pos: DVec3, dest: DVec3, slack: f64, kind: SamKind, now: u64) -> Self {
let dist = horizontal(dest - pos).length();
let cell = if dist <= 400.0 { 4 } else if dist <= 900.0 { 6 } else { 8 };
@@ -755,6 +778,12 @@ impl Routes {
pub(super) fn remaining_distance(&self, unit_id: u32, pos: DVec3, dest: DVec3) -> f64 {
self.map.get(&unit_id).map_or_else(|| (horizontal(dest - pos).length() - HANDOVER).max(0.0), |r| r.remaining_distance(pos))
}
pub(super) fn remaining_points(&self, unit_id: u32, pos: DVec3, dest: DVec3, max_points: usize) -> Vec<[f64; 2]> {
self.map.get(&unit_id).map_or_else(
|| vec![[pos.x, pos.z], [dest.x, dest.z]],
|r| r.remaining_points(pos, max_points),
)
}
}
impl SamKind {
+5
View File
@@ -152,6 +152,11 @@ impl WaveConfig {
let n = self.counts[i];
self.counts[i] = STEPS.iter().copied().find(|&s| s > n).unwrap_or(0);
}
/// The previous number for kind `i`, wrapping from 0 to the largest step.
pub fn step_back(&mut self, i: usize) {
let n = self.counts[i];
self.counts[i] = STEPS.iter().copied().rfind(|&s| s < n).unwrap_or(*STEPS.last().unwrap());
}
pub fn total(&self) -> u32 {
self.counts.iter().sum()
}
+108 -2
View File
@@ -110,12 +110,23 @@ fn public_live(sim: &sim::Sim) -> Value {
let radar_range = emitting.then(|| s.kind.spec().sensor * s.radar_profile().reach);
let supply = sim.supply_status(i).map(|st| battery_view::supply_line(&st));
let depot_reach = (s.kind == sim::SamKind::Depot).then_some(sim::DEPOT_REACH_BLOCKS);
let job = s.job().filter(|jid| sim.sams.iter().any(|u| u.id == *jid && u.alive()));
let job_kind = sim.tzm_job_kind(i);
let route_pts: Vec<[f64; 2]> = sim
.unit_route(i, 16)
.into_iter()
.map(|p| [(p[0] * 10.0).round() / 10.0, (p[1] * 10.0).round() / 10.0])
.collect();
let route = (!route_pts.is_empty()).then_some(route_pts);
merge(
&mut row,
json!({
"status": post::state(s), "details": battery_view::sam_status(s, now),
"supply": supply,
"depotReach": depot_reach,
"job": job,
"jobKind": job_kind,
"route": route,
"health": s.health, "rounds": s.missiles, "bursts": s.bursts,
"symbol": if s.kind == sim::SamKind::Radar { "radar" } else { "unit" },
"radarRange": radar_range,
@@ -198,12 +209,35 @@ fn public_live(sim: &sim::Sim) -> Value {
merge(&mut row, json!({ "target": known.contains(&m.target()).then_some(m.target()), "status": "В полёте" }));
row
}).collect();
let strikes: Vec<_> = sim.strikes.flights.iter().take(ENTITY_LIMIT).map(|f| {
let remaining = f.arrive.saturating_sub(now) as u32;
let eta = remaining.div_ceil(20);
let total = f.arrive.saturating_sub(f.start).max(1) as f64;
let progress = (now.saturating_sub(f.start) as f64 / total).clamp(0.0, 1.0);
let mut row = position(f.id, format!("RM48U №{} → ПУ №{}", f.id, f.site), f.pos);
merge(&mut row, json!({
"symbol": "strike",
"status": format!("В полёте · ~{eta} с"),
"site": f.site,
"carrier": f.carrier,
"fromX": f.from.x,
"fromZ": f.from.z,
"aimX": f.aim.x,
"aimZ": f.aim.y,
"vx": f.aim.x - f.from.x,
"vz": f.aim.y - f.from.z,
"eta": eta,
"progress": (progress * 100.0).round() as u32,
}));
row
}).collect();
json!({
"units": units, "objects": objects, "contacts": contacts, "interceptors": interceptors, "sites": sites,
"units": units, "objects": objects, "contacts": contacts, "interceptors": interceptors, "sites": sites, "strikes": strikes,
"logistics": logistics,
"summary": { "kills": sim.kills, "hits": sim.hits, "planning": sim.planning(), "hold": sim.hold, "autoStrike": sim.auto_strike },
"limited": sim.sams.len() > ENTITY_LIMIT || (!picture.unaided && picture.tracks.len() > ENTITY_LIMIT)
|| sim.missiles.len() > ENTITY_LIMIT || sim.targets.len() > ENTITY_LIMIT || sim.strikes.known.len() > ENTITY_LIMIT
|| sim.strikes.flights.len() > ENTITY_LIMIT
})
}
@@ -248,7 +282,7 @@ fn perspectives(sim: &sim::Sim, debug: bool) -> (Value, Value) {
})
.collect();
(
json!({"contacts": observed, "units": [], "objects": [], "interceptors": [], "sites": [], "reports": reports, "sorties": sorties,
json!({"contacts": observed, "units": [], "objects": [], "interceptors": [], "sites": [], "strikes": [], "reports": reports, "sorties": sorties,
"limited": report.observations.len() > ENTITY_LIMIT}),
json!(truth),
)
@@ -643,5 +677,77 @@ mod tests {
let (enemy, _) = perspectives(&sim, true);
assert_eq!(enemy["sites"], json!([]));
assert_eq!(enemy["strikes"], json!([]));
}
#[test]
fn public_live_includes_moving_unit_routes_and_flying_rm48u_strikes() {
let mut sim = sim::Sim::new(1);
let s400_id = sim.id();
let mut s400 = sim::Sam::new(s400_id, sim::SamKind::S400, DVec3::new(0.0, 64.0, 0.0), 0.0);
s400.ground_rounds = 1;
s400.missiles = 3;
sim.sams.push(s400);
let tzm_id = sim.id();
sim.sams.push(sim::Sam::new(tzm_id, sim::SamKind::Tzm, DVec3::new(20.0, 64.0, 0.0), 0.0));
let mut ground = sim::Ground::default();
for _ in 0..45 {
sim.step(&mut ground, None, &mut Out::default());
}
assert!(sim.order_move(1, DVec3::new(120.0, 64.0, 0.0)));
sim.sites.list.push(sim::sites::LaunchSite {
id: 7,
side: 0,
sector: 0,
bearing: 0.0,
class: sim::sites::SiteClass::Launcher,
pos: DVec3::new(600.0, 64.0, 0.0),
range: 600.0,
water: false,
stock: 1,
planned: 0,
alive: true,
next_free: 0,
offmap: false,
});
sim.strikes.known.push(sim::strike::Known {
site: 7,
class: sim::sites::SiteClass::Launcher,
obs: Vec::new(),
est: Some(sim::strike::Estimate {
pos: glam::DVec2::new(600.0, 0.0),
radius: 20.0,
fix: true,
bearing: 0.0,
bearing_err: 0.05,
origin: glam::DVec2::ZERO,
}),
launches: 1,
last: 1,
state: sim::strike::SiteState::Active,
aimed: false,
});
sim.order_strike(7, DVec3::ZERO, &mut Out::default()).unwrap();
for _ in 0..80 {
sim.step(&mut ground, None, &mut Out::default());
if !sim.strikes.flights.is_empty() {
break;
}
}
assert_eq!(sim.strikes.flights.len(), 1, "expected strike missile in flight");
let snap = public_live(&sim);
assert_eq!(snap["units"][1]["jobKind"], "march");
assert!(snap["units"][1]["route"].as_array().unwrap().len() >= 2);
let strikes = snap["strikes"].as_array().unwrap();
assert_eq!(strikes.len(), 1);
assert_eq!(strikes[0]["symbol"], "strike");
assert_eq!(strikes[0]["site"], 7);
assert_eq!(strikes[0]["carrier"], s400_id);
assert!(strikes[0].get("land").is_none());
assert!(strikes[0].get("snap").is_none());
}
}
+10
View File
@@ -339,6 +339,16 @@ class PanelTest(unittest.TestCase):
self.bridge.poll()
_, _, base = self.request("/api/live?delta=1", cookie=viewer)
self.assertEqual(base["frame"]["sites"][0]["id"], 3)
# Strikes layer propagates upsert and remove deltas.
self.live_frame = dict(EMPTY, sites=self.live_frame["sites"],
strikes=[{"id": 11, "x": 40, "z": 10, "symbol": "strike"}])
self.bridge.poll()
_, _, strike_delta = self.request(f"/api/live?delta=1&after={base['revision']}", cookie=viewer)
self.assertEqual(strike_delta["frameChange"]["layers"]["strikes"]["upsert"][0]["id"], 11)
self.live_frame = dict(EMPTY, sites=self.live_frame["sites"], strikes=[])
self.bridge.poll()
_, _, strike_rm = self.request(f"/api/live?delta=1&after={strike_delta['revision']}", cookie=viewer)
self.assertEqual(strike_rm["frameChange"]["layers"]["strikes"]["remove"], [11])
if __name__ == "__main__":
+1 -1
View File
@@ -16,7 +16,7 @@ from .terrain import TerrainTiles
TOKEN = re.compile(r"[0-9a-f]{16,32}\Z")
MAX_PACKET = 1 << 20
MAX_REPLY = 1 << 18
MAP_LAYERS = ("units", "objects", "contacts", "interceptors", "sites")
MAP_LAYERS = ("units", "objects", "contacts", "interceptors", "sites", "strikes")
LIVE_REVISIONS = 12
+2
View File
@@ -141,6 +141,7 @@ dialog::backdrop { background: #02080dc9; }
.legend [data-layer="contacts"] { accent-color: #f0bf6a; }
.legend [data-layer="interceptors"] { accent-color: #b2e68f; }
.legend [data-layer="sites"] { accent-color: #ff9b52; }
.legend [data-layer="strikes"] { accent-color: #ff6b3d; }
#autostrike-toggle[aria-pressed="true"] { background: #234443; border-color: #3d6864; color: #d3fff3; }
#logistics-summary p { margin: .15rem 0; font-size: .82rem; }
.panel-title { margin: 0; font-size: 1.05rem; }
@@ -152,6 +153,7 @@ dialog::backdrop { background: #02080dc9; }
#object-list [data-kind="contact"] { --marker: #f0bf6a; }
#object-list [data-kind="interceptor"] { --marker: #b2e68f; }
#object-list [data-kind="site"] { --marker: #ff9b52; }
#object-list [data-kind="strike"] { --marker: #ff6b3d; }
@media (max-width: 540px) {
.map-tools { gap: .5rem; }
.inline-field { font-size: .8rem; }
+14 -1
View File
@@ -69,7 +69,7 @@ async function api(path, {method = "GET", data} = {}) {
}
}
const groups = [["units", "unit"], ["objects", "object"], ["contacts", "contact"], ["interceptors", "interceptor"], ["sites", "site"]];
const groups = [["units", "unit"], ["objects", "object"], ["contacts", "contact"], ["interceptors", "interceptor"], ["sites", "site"], ["strikes", "strike"]];
const prefs = read("view", {layers: {}, views: {}, selected: null});
prefs.layers ||= {};
prefs.views ||= {};
@@ -289,6 +289,19 @@ function showObject(opened, frame) {
nodes.push(strikeBtn);
}
}
if (kind === "strike") {
if (row.eta != null) nodes.push(paragraph(`Подлёт · ~${row.eta} с (${row.progress ?? 0}%)`));
if (row.aimX != null && row.aimZ != null) nodes.push(paragraph(`Цель · X ${Math.round(row.aimX)} · Z ${Math.round(row.aimZ)}`));
if (row.site != null && frame?.sites?.some(s => s.id === row.site)) {
nodes.push(button(`Пусковая №${row.site}`, () => select(`site:${row.site}`, true)));
}
if (row.carrier != null && frame?.units?.some(u => u.id === row.carrier)) {
nodes.push(button(`Носитель №${row.carrier}`, () => select(`unit:${row.carrier}`, true)));
}
}
if (kind === "unit" && row.job != null && frame?.units?.some(u => u.id === row.job)) {
nodes.push(button(`Цель маршрута · №${row.job}`, () => select(`unit:${row.job}`, true)));
}
if (row.target) nodes.push(button(`Контакт №${row.target}`, () => select(`contact:${row.target}`, true)));
if (row.source) {
const linked = frame?.units?.some(unit => unit.id === row.source);
+1
View File
@@ -68,6 +68,7 @@
<label><input type="checkbox" data-layer="contacts" checked> Контакты</label>
<label><input type="checkbox" data-layer="interceptors" checked> Перехватчики</label>
<label><input type="checkbox" data-layer="sites" checked> ПУ врага</label>
<label><input type="checkbox" data-layer="strikes" checked> Ударные RM48U</label>
</div>
<div class="map-readout"><span id="map-source"></span><span id="map-status" role="status"></span></div>
</footer>
+62 -1
View File
@@ -7,6 +7,7 @@ const styles = [
["contacts", "contact", "#f0bf6a"],
["interceptors", "interceptor", "#b2e68f"],
["sites", "site", "#ff9b52"],
["strikes", "strike", "#ff6b3d"],
];
const clamp = (x, low, high) => Math.min(high, Math.max(low, x));
@@ -14,7 +15,7 @@ export function createMap(canvas, {onSelect, onView, onTerrain}) {
const ctx = canvas.getContext("2d");
const view = {x: 0, z: 0, scale: .22};
const fingers = new Map();
let points = [], visible = [], selected, width = 1, height = 1, drawnFrame;
let points = [], visible = [], selected, width = 1, height = 1, drawnFrame, activeLayers = {};
const terrain = createTerrain(schedule);
let mode = "map", scope, online, radarId;
let moved = false, autoFit = true, queued = false;
@@ -98,6 +99,63 @@ export function createMap(canvas, {onSelect, onView, onTerrain}) {
const bar = steps.find(s => s * scale >= 40) || steps.at(-1);
ctx.fillText(`${bar} бл.`, 14, height - 23);
ctx.fillRect(14, height - 16, bar * scale, 2);
if (activeLayers.units !== false && drawnFrame?.units) {
const routeColors = {
rm48u: "rgba(255, 184, 92, 0.85)",
return: "rgba(255, 184, 92, 0.85)",
deliver: "rgba(112, 232, 136, 0.85)",
fetch: "rgba(106, 220, 210, 0.75)",
};
for (const row of drawnFrame.units) {
if (!Array.isArray(row.route) || row.route.length < 2) continue;
const isSel = selected === `unit:${row.id}`;
const color = routeColors[row.jobKind] || "rgba(144, 189, 192, 0.7)";
ctx.save();
ctx.strokeStyle = color;
ctx.fillStyle = color;
ctx.lineWidth = isSel ? 2.4 : 1.5;
ctx.setLineDash([6, 4]);
ctx.beginPath();
ctx.moveTo(px(row.route[0][0]), py(row.route[0][1]));
for (const pt of row.route.slice(1)) ctx.lineTo(px(pt[0]), py(pt[1]));
ctx.stroke();
ctx.setLineDash([]);
const end = row.route.at(-1);
ctx.beginPath();
ctx.arc(px(end[0]), py(end[1]), isSel ? 4 : 3, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
}
if (activeLayers.strikes !== false && drawnFrame?.strikes) {
for (const row of drawnFrame.strikes) {
if (![row.fromX, row.fromZ, row.x, row.z, row.aimX, row.aimZ].every(Number.isFinite)) continue;
const isSel = selected === `strike:${row.id}`;
ctx.save();
ctx.strokeStyle = "rgba(255, 107, 61, 0.55)";
ctx.lineWidth = isSel ? 2.2 : 1.4;
ctx.beginPath();
ctx.moveTo(px(row.fromX), py(row.fromZ));
ctx.lineTo(px(row.x), py(row.z));
ctx.stroke();
ctx.strokeStyle = "rgba(255, 160, 64, 0.85)";
ctx.setLineDash([5, 4]);
ctx.beginPath();
ctx.moveTo(px(row.x), py(row.z));
ctx.lineTo(px(row.aimX), py(row.aimZ));
ctx.stroke();
ctx.setLineDash([]);
const ax = px(row.aimX), ay = py(row.aimZ);
ctx.strokeStyle = "#ff9b52";
ctx.beginPath();
ctx.moveTo(ax - 5, ay - 5);
ctx.lineTo(ax + 5, ay + 5);
ctx.moveTo(ax + 5, ay - 5);
ctx.lineTo(ax - 5, ay + 5);
ctx.stroke();
ctx.restore();
}
}
visible = [];
for (const point of points) {
const {row, color, kind} = point;
@@ -131,6 +189,8 @@ export function createMap(canvas, {onSelect, onView, onTerrain}) {
const links = [
focus.row.target != null ? `contact:${focus.row.target}` : null,
focus.row.source != null ? `unit:${focus.row.source}` : null,
focus.row.job != null ? `unit:${focus.row.job}` : null,
focus.row.site != null ? `site:${focus.row.site}` : null,
];
for (const key of links) {
const other = visible.find(item => item.key === key);
@@ -250,6 +310,7 @@ export function createMap(canvas, {onSelect, onView, onTerrain}) {
return {
draw(frame, options) {
drawnFrame = frame;
activeLayers = options.layers || {};
selected = options.selected;
mode = options.mode;
scope = options.scope;
+1 -1
View File
@@ -1,5 +1,5 @@
/* Cache only the public, versioned application shell. API responses are never cached. */
const CACHE = 'airdef-shell-v10';
const CACHE = 'airdef-shell-v11';
const FILES = ['index.html', 'app.css', 'app.js', 'map.js', 'terrain.js', 'symbols.js', 'live.js', 'timeline.js', 'manifest.webmanifest', 'icons/icon-192.png', 'icons/icon-512.png'];
const scope = new URL(self.registration.scope);
const shellUrls = FILES.map(path => new URL(path, scope).href);
+3
View File
@@ -94,6 +94,9 @@ export function drawSymbol(ctx, x, y, {kind, symbol, color = '#d6e5ea', selected
shape([[0,-10],[10,0],[0,10],[-10,0]]);
line([-5,0],[5,0]); line([0,-5],[0,5]);
break;
case 'strike':
shape([[0,-12],[3.5,-4],[3.5,5],[7.5,9],[2.5,8],[0,12],[-2.5,8],[-7.5,9],[-3.5,5],[-3.5,-4]]);
break;
default:
shape([[0,-11],[11,0],[0,11],[-11,0]]);
ctx.fillStyle = '#071219';