diff --git a/airdef-mod/assets/airdef/items/deploy_optical.json b/airdef-mod/assets/airdef/items/deploy_optical.json new file mode 100644 index 0000000..1ed1407 --- /dev/null +++ b/airdef-mod/assets/airdef/items/deploy_optical.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "airdef:item/deploy_optical" + } +} diff --git a/airdef-mod/assets/airdef/lang/en_us.json b/airdef-mod/assets/airdef/lang/en_us.json index 273340f..4925d8e 100644 --- a/airdef-mod/assets/airdef/lang/en_us.json +++ b/airdef-mod/assets/airdef/lang/en_us.json @@ -123,6 +123,7 @@ "item.airdef.deploy_tzm": "Развернуть ТЗМ", "item.airdef.deploy_ew": "Развернуть станцию РЭБ", "item.airdef.deploy_light": "Развернуть прожектор", + "item.airdef.deploy_optical": "Развернуть оптический пост", "item.airdef.mover": "Пульт перемещения", "item.airdef.flare_gun": "Осветительная ракета", "item.airdef.remover": "Свернуть ПВО", diff --git a/airdef-mod/assets/airdef/lang/ru_ru.json b/airdef-mod/assets/airdef/lang/ru_ru.json index 273340f..4925d8e 100644 --- a/airdef-mod/assets/airdef/lang/ru_ru.json +++ b/airdef-mod/assets/airdef/lang/ru_ru.json @@ -123,6 +123,7 @@ "item.airdef.deploy_tzm": "Развернуть ТЗМ", "item.airdef.deploy_ew": "Развернуть станцию РЭБ", "item.airdef.deploy_light": "Развернуть прожектор", + "item.airdef.deploy_optical": "Развернуть оптический пост", "item.airdef.mover": "Пульт перемещения", "item.airdef.flare_gun": "Осветительная ракета", "item.airdef.remover": "Свернуть ПВО", diff --git a/airdef-mod/assets/airdef/models/item/deploy_optical.json b/airdef-mod/assets/airdef/models/item/deploy_optical.json new file mode 100644 index 0000000..8d99691 --- /dev/null +++ b/airdef-mod/assets/airdef/models/item/deploy_optical.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/generated", + "textures": { + "layer0": "airdef:item/deploy_radar" + } +} diff --git a/airdef-mod/data/airdef/horizon/item/deploy_optical.json b/airdef-mod/data/airdef/horizon/item/deploy_optical.json new file mode 100644 index 0000000..1763337 --- /dev/null +++ b/airdef-mod/data/airdef/horizon/item/deploy_optical.json @@ -0,0 +1,4 @@ +{ + "template": "minecraft:stick", + "max_stack_size": 1 +} diff --git a/airdef-mod/src/battery_view.rs b/airdef-mod/src/battery_view.rs index dd7b57b..d9844b7 100644 --- a/airdef-mod/src/battery_view.rs +++ b/airdef-mod/src/battery_view.rs @@ -72,6 +72,16 @@ pub fn sam_status(sam: &Sam) -> String { return format!("{text} «{}»: {}; целей {}{broken}, {channels}", profile.name, profile.products_text(), sam.own.len()); } SamKind::Light => return format!("{text}{}", if sam.target.is_some() { ": в луче цель" } else { "" }), + SamKind::Optical => { + let mut t = format!("{text}: {}", sam.optical.status_text()); + if sam.health < 1.0 { + t += &format!(" ({:.0}%)", sam.health * 100.0); + } + if !sam.comps.whole() { + t += &format!(" [{}]", crate::why_view::worst(&sam.comps, sam.kind)); + } + return t; + } _ => {} } if let Some(cell) = sam.preparing_cell() { @@ -158,6 +168,9 @@ mod tests { let mut light = Sam::new(8, SamKind::Light, DVec3::ZERO, 0.0); light.target = Some(1); assert_eq!(sam_status(&light), "Прожектор: в луче цель"); + + let optical = Sam::new(9, SamKind::Optical, DVec3::ZERO, 0.0); + assert_eq!(sam_status(&optical), "Оптический пост: ищет"); } #[test] diff --git a/airdef-mod/src/layout.rs b/airdef-mod/src/layout.rs index 15575e5..21c18f6 100644 --- a/airdef-mod/src/layout.rs +++ b/airdef-mod/src/layout.rs @@ -244,6 +244,13 @@ mod tests { SamKind::Patriot.key() } + #[test] + fn an_optical_post_loads_by_its_catalog_key() { + let l = Layout::parse("sam optical 10 70 20 0.5\n").unwrap(); + assert_eq!(l.sams[0].kind, SamKind::Optical); + assert_eq!(l.sams[0].mode, sim::battery::SamMode::Integrated); + } + // #86: the issue's file, and the other ways a saved state can be wrong: refused whole, with the line #[test] fn a_damaged_state_is_refused_as_a_whole_with_its_line_and_field() { diff --git a/airdef-mod/src/lib.rs b/airdef-mod/src/lib.rs index 3366b01..7b22588 100644 --- a/airdef-mod/src/lib.rs +++ b/airdef-mod/src/lib.rs @@ -1505,7 +1505,7 @@ impl AirDef { .sams .iter() .enumerate() - .filter(|(_, s)| s.kind.armed() || s.kind == SamKind::Radar) + .filter(|(_, s)| s.kind.armed() || s.kind == SamKind::Radar || s.kind == SamKind::Optical) .map(|(i, s)| { let busy = if self.sim.showing_kill(s) { 98.0 } else { match s.state { sim::SamState::Launch | sim::SamState::Fire => 100.0, @@ -1519,7 +1519,11 @@ impl AirDef { sim::SamState::Waiting => 35.0, sim::SamState::Packing | sim::SamState::Moving | sim::SamState::Deploying => 40.0, } }; - let near = self.sim.watched(s).map_or(0.0, |d| 15.0 * (1.0 - (d.pos.distance(s.pos) / s.kind.range()).min(1.0))); + let near = if s.kind == SamKind::Optical { + 0.0 + } else { + self.sim.watched(s).map_or(0.0, |d| 15.0 * (1.0 - (d.pos.distance(s.pos) / s.kind.range()).min(1.0))) + }; let hurt = if s.alive() && s.health < 0.7 { 15.0 } else { 0.0 }; let keep = if shown.contains(&s.id) { 12.0 } else { 0.0 }; let pinned = if self.monitor == Some(i) { 1000.0 } else { 0.0 }; diff --git a/airdef-mod/src/map.rs b/airdef-mod/src/map.rs index 7367e9b..5d8e9d7 100644 --- a/airdef-mod/src/map.rs +++ b/airdef-mod/src/map.rs @@ -465,7 +465,7 @@ impl MapUi { fn sys_class(k: SamKind) -> usize { if k.armed() { if k == SamKind::Gepard { 1 } else { 0 } - } else if k.spec().sensor > 0.0 { + } else if k == SamKind::Optical || k.spec().sensor > 0.0 { 2 } else { 3 @@ -480,6 +480,7 @@ fn short_name(k: SamKind) -> &'static str { SamKind::Tzm => "ТЗМ", SamKind::Ew => "РЭБ", SamKind::Light => "Прож.", + SamKind::Optical => "Опт.", SamKind::Pantsir => "Панцирь", SamKind::IrisT => "IRIS-T", SamKind::S400 => "С-400", @@ -1778,6 +1779,10 @@ impl AirDef { if ui.filters[F_TRACKS] || ui.filters[F_TRAILS] { self.map_tracks(ui, &mut s, &mut labs, &mut taken); } + // The optical posts and the contacts they watch (#136): a line to a contact last seen in clear sight. + if ui.filters[F_SAMS] || ui.filters[F_TRACKS] { + self.map_optical(ui, &mut s, &mut labs); + } // The truth, when the sandbox shows it, marked as such: the real drones, their routes and aims. if self.sim.truth { map_truth(&self.sim, ui, hover, &mut s, &mut labs, &mut taken); @@ -1902,6 +1907,51 @@ impl AirDef { } } + /// The optical posts (#136): a short status by each, and a line to the contact it has in clear + /// sight (or last saw), never to a radar's measurement. At most a screenful, so a crowd stays cheap. + fn map_optical(&self, ui: &mut MapUi, s: &mut Vec, labs: &mut Vec) { + let now = self.sim.tick; + let picture = self.sim.picture(); + let mut drawn = 0usize; + for (i, sam) in self.sim.sams.iter().enumerate().filter(|(_, sam)| sam.kind == SamKind::Optical && sam.alive()) { + if drawn >= 16 { + break; + } + let c = ui.to_screen(sam.pos.x, sam.pos.z); + if !ui.on_screen(c, 30.0) { + continue; + } + drawn += 1; + let Some(report) = self.sim.optical_report(sam.id) else { continue }; + let chosen = ui.sel == Some(Sel::Sam(sam.id)); + let color = match report.state { + sim::OpticalState::Observing => GREEN, + sim::OpticalState::Holding => CYAN, + sim::OpticalState::NoSight => ORANGE, + sim::OpticalState::Searching => GREY, + }; + add_lab(ui, labs, format!("Опт. №{}: {}", i + 1, report.status()), c, 7.0, alpha(color, 0.95), chosen); + if chosen { + s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN)); + } + // The contact it watches: its own last clear sighting, else the network cue's forecast. + let own = report.seen.is_some(); + let point = report + .seen + .or_else(|| report.target.and_then(|id| picture.get(&id).map(|t| t.est(now)))); + if let Some(p) = point { + let pc = ui.to_screen(p.x, p.z); + s.push(line(c, pc, 1.0, alpha(color, if chosen { 0.9 } else if own { 0.55 } else { 0.3 }))); + let label = match (own, report.observation) { + (true, Some(o)) => format!("вероятно {} · {:.0}%", o.class.name(), (1.0 - o.uncertainty) * 100.0), + (true, None) => "контакт в поле зрения".into(), + (false, _) => "цель по подсказке".into(), + }; + add_lab(ui, labs, label, pc, 5.0, alpha(color, 0.95), chosen); + } + } + } + /// The radars' coverage edges. A radar's edge is where the land first hides a low flyer along each ray round it; /// each is worked out from the sim's own horizon (`low_rim`), a few a redraw, and kept a while. The selected /// one shows its dead zones filled. @@ -2663,6 +2713,18 @@ impl AirDef { btns.push((if sam.radar_on { "Выключить РЛС" } else { "Включить РЛС" }.into(), Act::RadarEmission, sam.radar_on)); } lines.push((crate::battery_view::sam_status(sam), WHITE)); + if k == SamKind::Optical { + if let Some(r) = self.sim.optical_report(sam.id) { + lines.push((r.line(), WHITE)); + if let Some(o) = r.observation { + lines.push((format!("Последнее наблюдение: {} · {} с назад", o.class.name(), o.age(now) / 20), WHITE)); + } + lines.push(("Пассивный пост: не излучает и не ведёт огневой трек".into(), GREY)); + if r.target.is_some() { + lines.push(("Выбранный контакт показан линией".into(), GREY)); + } + } + } lines.push((format!("Исправен {:.0}% · {:.0} {:.0}", sam.health * 100.0, sam.pos.x, sam.pos.z), GREY)); if k == SamKind::Depot { lines.push((format!("Ударные RM48U: {} · снятые 48Н6: {}", sam.ground_stock, sam.air_48n6_stock), WHITE)); diff --git a/airdef-mod/src/monitor.rs b/airdef-mod/src/monitor.rs index 9ad19b4..a03c5be 100644 --- a/airdef-mod/src/monitor.rs +++ b/airdef-mod/src/monitor.rs @@ -3,7 +3,7 @@ //! renders it) locked on its target. K shows one system at a time, J all of //! them in a grid. use crate::panel::distance; -use crate::sim::{ClassEst, Sam, SamState, Sim, heading_of, roles_text}; +use crate::sim::{ClassEst, OpticalState, Sam, SamKind, SamState, Sim, heading_of, roles_text}; use glam::DVec3; use horizon_mod_sdk::render::{self, CameraView, FillShape, Point, QuadShape, Rect, Shape, TextShape, ViewShape}; @@ -91,12 +91,23 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec 0xFF60FF80, + OpticalState::Holding => 0xFF9FE0FF, + OpticalState::NoSight => 0xFFFFA040, + OpticalState::Searching => 0xFFE0E0E0, + } + } else { + state.color() + }; let lw = render::text_width(label); s.push(text(fit(format!("№{} {}", index + 1, spec.name), w - lw - 12.0), x + 3.0, y + 2.0, 0xFF9FE0FF)); - s.push(text(label, x + w - 3.0 - lw, y + 2.0, argb(state.color(), if blink { 0x80 } else { 0xFF }))); + s.push(text(label, x + w - 3.0 - lw, y + 2.0, argb(color, if blink { 0x80 } else { 0xFF }))); // The radar, at the left: round the system, north up. let rr = ((h - 28.0) / 2.0).min(w * 0.2).max(10.0); @@ -114,9 +125,13 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec 0.0 => r, - _ => spec.sensor, + let reach = if optical { + crate::sim::OPTICAL_RANGE + } else { + match sam.kind.range() { + r if r > 0.0 => r, + _ => spec.sensor, + } }; let scale = if reach > 0.0 { rr as f64 / (reach * 1.25) } else { 0.0 }; // The beam is the radar's real one: targets are measured as it passes them. @@ -168,7 +183,9 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec 0.0 && !radar_up { 0xFFFF5040 } else { 0xFF80FF90 })); + let radar_color = if optical { + match sam.optical.state() { + OpticalState::Observing => 0xFF60FF80, + OpticalState::Holding => 0xFF9FE0FF, + OpticalState::NoSight => 0xFFFFA040, + OpticalState::Searching => 0xFFB0B0B0, + } + } else if spec.sensor > 0.0 && !radar_up { + 0xFFFF5040 + } else { + 0xFF80FF90 + }; + s.push(text(fit(radar_text, rr * 2.0 + 4.0), x + 4.0, y + h - 10.0, radar_color)); // Its health under the radar: a bar, red when it is low. if sam.alive() && sam.health < 1.0 { @@ -223,6 +252,21 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec { + // The optical post's picture: its own class observation, never the true model name. + let (color, info) = match sam.optical.state() { + OpticalState::Observing => (0xFF60FF80, sam.optical.status_text()), + OpticalState::Holding => (0xFF9FE0FF, sam.optical.status_text()), + OpticalState::NoSight => (0xFFFFA040, sam.optical.status_text()), + OpticalState::Searching => (0xFFB0B0B0, sam.optical.status_text()), + }; + let (bw, bh) = (cw * 0.3, ch * 0.34); + brackets(s, cx + cw / 2.0 - bw / 2.0, cy + ch / 2.0 - bh / 2.0, bw, bh, 6.0, color); + if ch > 50.0 { + s.push(text(fit(info.clone(), cw - 6.0), cx + 3.0, cy + ch - 20.0, color)); + } + s.push(text(fit(info, cw - 6.0), cx + 3.0, cy + ch - 10.0, 0xFFC0FFC0)); + } Some(t) => { let color = if lock { if blink { 0xFFFF3030 } else { 0xFFFF8080 } } else { 0xFFFFE060 }; let (bw, bh) = (cw * 0.3, ch * 0.34); @@ -257,19 +301,24 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec s.push(text(fit(sam.optical.status_text(), cw - 6.0), cx + 3.0, cy + ch - 10.0, 0xFFB0B0B0)), None => s.push(text("ПОИСК", cx + 3.0, cy + ch - 10.0, 0xFF80FF90)), } // What it carries and does. let mut line = String::new(); - if !matches!(sam.kind, crate::sim::SamKind::Gepard) { - line += &format!("Р{} ", sam.missiles); - if sam.kind == crate::sim::SamKind::S400 { line += &format!("У{} ", sam.ground_rounds); } + if optical { + line = sam.optical.status_text(); + } else { + if !matches!(sam.kind, SamKind::Gepard) { + line += &format!("Р{} ", sam.missiles); + if sam.kind == SamKind::S400 { line += &format!("У{} ", sam.ground_rounds); } + } + if crate::sim::catalog::unit(sam.kind).has_gun() { + line += &format!("Оч{} ", sam.bursts); + } + line += &format!("сб.{} [{}]", sam.kills, roles_text(sam.roles)); } - if crate::sim::catalog::unit(sam.kind).has_gun() { - line += &format!("Оч{} ", sam.bursts); - } - line += &format!("сб.{} [{}]", sam.kills, roles_text(sam.roles)); s.push(text(fit(line, cw), cx, y + h - 10.0, 0xFF9FE0FF)); } diff --git a/airdef-mod/src/panel.rs b/airdef-mod/src/panel.rs index c25fea9..b8e9973 100644 --- a/airdef-mod/src/panel.rs +++ b/airdef-mod/src/panel.rs @@ -88,6 +88,11 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec { let worst = sim.target_health.iter().copied().fold(100.0, f64::min); lines.push(line(format!("Объекты: {}", list.join(" ")), if worst < 50.0 { RED } else { GREEN })); } + // The passive optical posts (#136): their own status and source, never a radar's emission. + let optics = sim.optical_reports(); + if let Some(r) = optics.iter().find(|r| r.state == crate::sim::OpticalState::Observing).or_else(|| optics.first()) { + lines.push(line(format!("Опт. №{}: {}", r.index, r.line()), CYAN)); + } let lost = sim.sams.iter().filter(|s| !s.alive()).count(); if lost > 0 { lines.push(line(format!("Потеряно комплексов: {lost}"), RED)); diff --git a/airdef-mod/src/sim/catalog_entries.rs b/airdef-mod/src/sim/catalog_entries.rs index c7b3a7a..86afb87 100644 --- a/airdef-mod/src/sim/catalog_entries.rs +++ b/airdef-mod/src/sim/catalog_entries.rs @@ -31,4 +31,5 @@ pub const UNITS: &[Unit] = &[ Unit { kind: SamKind::Tzm, deploy_item: "airdef:deploy_tzm" }, Unit { kind: SamKind::Ew, deploy_item: "airdef:deploy_ew" }, Unit { kind: SamKind::Light, deploy_item: "airdef:deploy_light" }, + Unit { kind: SamKind::Optical, deploy_item: "airdef:deploy_optical" }, ]; diff --git a/airdef-mod/src/sim/damage.rs b/airdef-mod/src/sim/damage.rs index ecfd609..06a7d0a 100644 --- a/airdef-mod/src/sim/damage.rs +++ b/airdef-mod/src/sim/damage.rs @@ -61,7 +61,8 @@ impl Part { pub fn on(self, kind: SamKind) -> bool { let spec = kind.spec(); match self { - Part::Sensor => spec.sensor > 0.0, + // A passive optical post has a sensor without radar reach: it can be damaged and blinded too. + Part::Sensor => spec.sensor > 0.0 || kind == SamKind::Optical, 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(), diff --git a/airdef-mod/src/sim/mod.rs b/airdef-mod/src/sim/mod.rs index 7707860..0eb49f3 100644 --- a/airdef-mod/src/sim/mod.rs +++ b/airdef-mod/src/sim/mod.rs @@ -25,6 +25,7 @@ pub mod record; mod sight; mod terrain; mod ew; +mod optical; mod durable; pub use ew::{AimReport, Confidence, ContactReport, EnemyPictureReport, Intent, PendingReport}; pub mod lights; @@ -45,6 +46,9 @@ mod sensor_tests; pub use ew::EW_RADIUS; pub use damage::{Comps, Part, PartState}; pub use sight::{AirPicture, Ident, LowSensor, Track, RIM_RAYS}; +pub use optical::{Optical, OpticalClassEstimate, OpticalObservation, OpticalObservable, OpticalReport, OpticalState, SightBlock}; +/// The passive optical post's clear-day reach (the monitor's scale reads it). +pub const OPTICAL_RANGE: f64 = optical::RANGE; use damage::dice; use outcome::{Impact, Outcome}; pub use units::{Family, SamKind}; @@ -1240,6 +1244,8 @@ pub struct Sam { pub(super) terrain: HashMap, /// Targets whose land hasn't been answered yet, and since when it has been waited for. waits: HashMap, + /// A passive optical post's own state (#136): no radar, no track, one class observation at a time. + pub optical: Optical, } impl Sam { @@ -1313,6 +1319,7 @@ impl Sam { beam_cast: 0, terrain: HashMap::new(), waits: HashMap::new(), + optical: Optical::default(), } } pub fn alive(&self) -> bool { @@ -1552,6 +1559,12 @@ impl Sim { { return self.drones.iter().find(|d| d.id == id); } + // An optical post has no track: its camera looks where it last saw the contact in clear + // sight, and nowhere at all while it has not seen it (#136). + if sam.kind == SamKind::Optical { + let (id, _) = sam.optical.seen(self.tick)?; + return self.drones.iter().find(|d| d.id == id); + } let id = sam .gun_target .or(sam.target) @@ -1567,6 +1580,9 @@ impl Sim { { return Some(self.watched(sam).map_or(at, |d| d.pos)); } + if sam.kind == SamKind::Optical { + return sam.optical.seen(self.tick).map(|(_, p)| p); + } self.watched(sam).map(|d| d.pos) } @@ -2306,7 +2322,7 @@ impl Sim { if self.hold { for i in 0..self.sams.len() { - if self.sams[i].alive() && !self.sams[i].moving() { + if self.sams[i].alive() && !self.sams[i].moving() && self.sams[i].kind != SamKind::Optical { self.sams[i].state = SamState::Hold; } self.draw_sam(i, out); @@ -2362,7 +2378,10 @@ impl Sim { } if !self.sams[i].kind.armed() { let sam = &mut self.sams[i]; - sam.state = SamState::Search; + // An optical post's state is its optics' (#136), not the armed systems' search line. + if sam.kind != SamKind::Optical { + sam.state = SamState::Search; + } // A searchlight's target is its beam's (step_lights): kept for its spot of light. if sam.kind != SamKind::Light { retarget(&mut missile_on, sam.target.take(), None); diff --git a/airdef-mod/src/sim/optical.rs b/airdef-mod/src/sim/optical.rs new file mode 100644 index 0000000..9d664b5 --- /dev/null +++ b/airdef-mod/src/sim/optical.rs @@ -0,0 +1,854 @@ +//! A passive optical observation post (#136): a separate, stationary sensor that watches one +//! already-known contact at a time and says what *class* of thing it is, without naming the model. +//! +//! It is deliberately not a radar and not a [`RadarRole`](battery::RadarRole): its spec has no +//! radar reach (`sensor = 0`), so it never appears in the radar picture, never emits, and never feeds +//! a fire-control track. It gets its contact either from the network's tracks (a cue) or by looking +//! in its own narrow near sector; then it must hold that one contact in clear line of sight for a +//! while. The result is an independent [`OpticalObservation`] with source, time, a wide [`Class`] +//! and an uncertainty — not a fresh [`Track`], not a measurement added to a radar's, and not a new +//! network emission. +//! +//! Line of sight is bounded work: one contact per post, one probe every few ticks, at most +//! [`CHECKS_PER_TICK`] optical probes a tick in the whole simulation. An unknown block section or an +//! unknown land column is *not* a clear line: the post keeps the old observation (which ages) and +//! waits for the game to answer. Night shortens the reach and doubles the hold; there is no thermal +//! mode in this first version. Weather/fog is not in the simulation API yet, so only the game's own +//! day/night state and the world geometry are used here. +//! +//! #133 owns the shared class-estimate contract. This module keeps its own small +//! [`OpticalObservation`]/[`OpticalClassEstimate`] types rather than inventing that contract silently: a +//! future classifier can consume [`Sim::optical_reports`] or the observation's [`OpticalClassEstimate`] +//! without this post pretending to be a [`Track`]. Nothing here reads [`DroneKind`] to classify. +//! +//! The catalog row currently reuses the existing `airdef:radar_truck` and `airdef:radar_panel` +//! models, and the deploy item aliases the radar icon, until the optical post's own assets land. +use super::*; +use super::world::Sweep; + +/// How far the post's optics resolve a contact in clear daytime air, blocks. +pub const RANGE: f64 = 300.0; +/// How far a network cue may point the head; beyond `RANGE` it is only a direction to look. +pub const CUE_RANGE: f64 = 800.0; +/// Half-width of the local search sector, radians. +const SECTOR_HALF: f64 = 70.0_f64.to_radians(); +/// Ticks a contact must stay in clear sight: day, and night. +const HOLD_DAY: u32 = 25; +const HOLD_NIGHT: u32 = 60; +/// Beyond this at night the optics resolve nothing. +const NIGHT_RANGE: f64 = 150.0; +/// A post probes its contact this often; the phase spreads posts over the period. +const PERIOD: u64 = 5; +/// Optical line-of-sight probes a tick, for the whole simulation. +pub const CHECKS_PER_TICK: usize = 4; +/// Nearest local candidates compared per look (one is selected). +const LOCAL_CANDIDATES: usize = 8; +/// Land samples a line is checked against (each may ask the game for its column). +const TERRAIN_SAMPLES: usize = 6; +/// A relayed track older than this is not worth turning the head for. +const CUE_MAX_AGE: u64 = 120; +/// Where the antenna sits over the post's base, blocks. +const MAST: f64 = 2.5; + +/// What the post is doing, in the words the map and monitor use. +#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] +pub enum OpticalState { + /// No contact selected. + #[default] + Searching, + /// One contact selected, not yet held long enough (the post is "busy" with it). + Holding, + /// It has produced an observation and still watches the same contact. + Observing, + /// A contact is selected but the line is blocked or unresolved. + NoSight, +} + +impl OpticalState { + pub fn name(self) -> &'static str { + match self { + Self::Searching => "ищет", + Self::Holding => "занят", + Self::Observing => "наблюдает", + Self::NoSight => "нет видимости", + } + } +} + +/// Why the selected contact cannot be confirmed now. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum SightBlock { + /// Beyond the optics' reach (a cue may point farther than they resolve). + OutOfRange, + /// Too far for the reduced night reach. + Night, + /// The land itself rises into the line. + Terrain, + /// A known block stops the line (a wall, a building). + Obstacle, + /// Geometry along the line is not known: not a clean line of sight. + UnknownGeometry, + /// The sensor part has failed. + Sensor, +} + +impl SightBlock { + pub fn name(self) -> &'static str { + match self { + Self::OutOfRange => "вне дальности", + Self::Night => "ночь", + Self::Terrain => "рельеф", + Self::Obstacle => "препятствие", + Self::UnknownGeometry => "геометрия неизвестна", + Self::Sensor => "оптика отказала", + } + } +} + +/// What can be observed of a contact's motion, without its true model or kind. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OpticalObservable { + /// Speed, blocks a tick. + pub speed: f64, + /// Vertical speed, blocks a tick (negative: descending). + pub climb: f64, + /// Distance from the post, blocks. + pub range: f64, +} + +/// A provisional wide class from observable motion alone. #133 will own the shared classifier; +/// this function is the one place that provisional rule lives, and it never looks at `DroneKind`. +/// Equal observable data therefore gives an equal answer for different true models. +pub fn classify_optical(observable: OpticalObservable) -> Class { + let speed = observable.speed; + if speed >= 6.5 || (speed >= 3.0 && observable.climb <= -0.35) { + Class::Ballistic + } else if speed >= 3.0 { + Class::Supersonic + } else if speed >= 1.8 { + Class::Cruise + } else if speed >= 0.8 { + Class::Jet + } else { + Class::Drone + } +} + +/// The minimum a future class-estimate consumer (#133) needs from one optical observation. +/// Deliberately local: the shared contract is not invented here. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OpticalClassEstimate { + pub class: Class, + /// 0 best, 1 worst. + pub uncertainty: f64, +} + +/// One independent optical observation: who saw it, when, what wide class, and how unsure. +/// It contains no [`DroneKind`], no track hits and no fire-control state. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OpticalObservation { + /// The contact's track id (opaque to the player's data). + pub target: u32, + /// The post's unit id: the observation's source. + pub source: u32, + pub tick: u64, + pub class: Class, + /// 0 best, 1 worst. + pub uncertainty: f64, + pub range: f64, + /// Bearing from the post, radians (as `heading_of`). + pub bearing: f64, + /// Ticks the contact was held before this observation. + pub hold: u32, + /// The observation was made at night. + pub night: bool, +} + +impl OpticalObservation { + pub fn age(&self, now: u64) -> u64 { + now.saturating_sub(self.tick) + } + /// The adapter to the future #133 contract. + pub fn estimate(&self) -> OpticalClassEstimate { + OpticalClassEstimate { class: self.class, uncertainty: self.uncertainty } + } +} + +/// One post's passive optics: the contact it is on, its line-of-sight state and its last observation. +#[derive(Clone, Debug, Default)] +pub struct Optical { + target: Option, + /// A player/network priority for a contact, when one is given. + commanded: Option, + state: OpticalState, + block: Option, + held: u32, + observations: u32, + observation: Option, + /// The last clear sighting of the current contact: target, where it was, its velocity then, when. + /// Only a clear line writes it; a blocked line leaves the old one to be forecast, never refreshed. + seen: Option<(u32, DVec3, DVec3, u64)>, + checks: u64, +} + +impl Optical { + pub fn state(&self) -> OpticalState { + self.state + } + pub fn block(&self) -> Option { + self.block + } + pub fn target(&self) -> Option { + self.target + } + pub fn observation(&self) -> Option { + self.observation + } + /// Where the current contact was last seen in clear sight, carried on by its velocity then. + /// None when the post has not seen it, or its old sighting belongs to another contact. + pub fn seen(&self, now: u64) -> Option<(u32, DVec3)> { + let (id, pos, vel, tick) = self.seen?; + (self.target == Some(id)).then(|| (id, pos + vel * now.saturating_sub(tick) as f64)) + } + pub fn observations(&self) -> u32 { + self.observations + } + pub fn checks(&self) -> u64 { + self.checks + } + fn commanded(&self) -> Option { + self.commanded + } + fn required(&self, night: bool) -> u32 { + if night { HOLD_NIGHT } else { HOLD_DAY } + } + fn clear_activity(&mut self) { + self.target = None; + self.held = 0; + self.state = OpticalState::Searching; + self.block = None; + } + fn drop_target(&mut self) { + self.target = None; + self.commanded = None; + self.held = 0; + self.observations = 0; + self.seen = None; + self.state = OpticalState::Searching; + self.block = None; + } + fn select(&mut self, id: Option) { + if self.target != id { + self.held = 0; + self.observations = 0; + self.seen = None; + } + self.target = id; + self.block = None; + self.state = if id.is_some() { OpticalState::Holding } else { OpticalState::Searching }; + } + /// A short line for the panel and the monitor: status, class and uncertainty, never a model name. + pub fn status_text(&self) -> String { + match self.state { + OpticalState::Searching => "ищет".into(), + OpticalState::Holding => "занят: удерживает контакт".into(), + OpticalState::Observing => match self.observation { + Some(o) => format!("наблюдает: вероятно {} ({:.0}%)", o.class.name(), (1.0 - o.uncertainty) * 100.0), + None => "наблюдает".into(), + }, + OpticalState::NoSight => match self.block { + Some(b) => format!("нет видимости: {}", b.name()), + None => "нет видимости".into(), + }, + } + } + fn report(&self, post: u32, index: usize, now: u64, night: bool) -> OpticalReport { + OpticalReport { + post, + index, + state: self.state, + block: self.block, + target: self.target, + observation: self.observation, + observations: self.observations, + held: self.held, + required: self.required(night), + seen: self.seen(now).map(|(_, p)| p), + checks: self.checks, + night, + } + } +} + +/// A post's state as the map, monitor and panel read it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OpticalReport { + /// The unit id of the post (the source of its observations). + pub post: u32, + /// Its 1-based place among the systems, for the interface. + pub index: usize, + pub state: OpticalState, + pub block: Option, + pub target: Option, + pub observation: Option, + pub observations: u32, + pub held: u32, + pub required: u32, + /// Where the current contact was last seen, forecast; None before the first clear sighting. + pub seen: Option, + pub checks: u64, + pub night: bool, +} + +impl OpticalReport { + pub fn status(&self) -> &'static str { + self.state.name() + } + /// "источник — оптический пост №N": the post itself, never a radar that cued it. + pub fn source_text(&self) -> String { + format!("оптический пост №{}", self.index) + } + pub fn line(&self) -> String { + match self.state { + OpticalState::Searching => "ищет".into(), + OpticalState::Holding => format!("занят: удерживает контакт {}/{}", self.held, self.required), + OpticalState::Observing => match self.observation { + Some(o) => format!( + "наблюдает: вероятно {} · {:.0}% · источник — {}", + o.class.name(), + (1.0 - o.uncertainty) * 100.0, + self.source_text() + ), + None => "наблюдает".into(), + }, + OpticalState::NoSight => match self.block { + Some(b) => format!("нет видимости: {}", b.name()), + None => "нет видимости".into(), + }, + } + } + /// The observation's age, if it has one; an old observation only ages. + pub fn age(&self, now: u64) -> Option { + self.observation.map(|o| o.age(now)) + } +} + +impl Sim { + /// Every live optical post's state, in deployment order (map/panel/monitor). + pub fn optical_reports(&self) -> Vec { + self.sams + .iter() + .enumerate() + .filter(|(_, s)| s.kind == SamKind::Optical && s.alive()) + .map(|(i, s)| s.optical.report(s.id, i + 1, self.tick, self.night)) + .collect() + } + + pub fn optical_report(&self, id: u32) -> Option { + let (i, s) = self.sams.iter().enumerate().find(|(_, s)| s.id == id && s.kind == SamKind::Optical)?; + Some(s.optical.report(s.id, i + 1, self.tick, self.night)) + } + + /// A manual priority for the post: watch this contact, or (None) go back to cues and the local sector. + /// False for a post that is not an optical post or a contact that is not in the air. + pub fn assign_optical(&mut self, post: u32, target: Option) -> bool { + if target.is_some_and(|id| !self.drones.iter().any(|d| d.id == id && d.alive())) { + return false; + } + let Some(sam) = self.sams.iter_mut().find(|s| s.id == post && s.kind == SamKind::Optical && s.alive()) else { + return false; + }; + sam.optical.commanded = target; + if sam.optical.target != target { + sam.optical.target = None; + sam.optical.held = 0; + sam.optical.observations = 0; + sam.optical.state = OpticalState::Searching; + sam.optical.block = None; + } + true + } + + /// The post's own pick: a manual/network cue first, then its narrow near sector. At most one contact. + fn optical_target(&self, i: usize, now: u64, alive: &std::collections::HashSet) -> Option { + let sam = &self.sams[i]; + let optical = &sam.optical; + let alive = |id: u32| alive.contains(&id); + if let Some(id) = optical.commanded() { + if alive(id) { + return Some(id); + } + } + if let Some(id) = optical.target() { + if let Some(d) = self.drones.iter().find(|d| d.id == id && d.alive()) { + if d.pos.distance(sam.pos) <= CUE_RANGE { + return Some(id); + } + } + } + // The network's freshest cue: the post measures it itself, the relay only points the head. + let mut cue: Option<(u64, f64, u32)> = None; + for t in &sam.tracks { + if t.own_tick != 0 || t.age(now) > CUE_MAX_AGE || !alive(t.id) { + continue; + } + let dist = t.est(now).distance(sam.pos); + if dist > CUE_RANGE { + continue; + } + if cue.is_none_or(|(fresh, near, _)| t.tick > fresh || (t.tick == fresh && dist < near)) { + cue = Some((t.tick, dist, t.id)); + } + } + if let Some((_, _, id)) = cue { + return Some(id); + } + // Nothing cued: search a narrow near sector, nearest first, comparing no more than a few. + let mut local: Vec<(f64, u32)> = self + .drones + .iter() + .filter(|d| d.alive()) + .filter_map(|d| { + let rel = d.pos - sam.pos; + let dist = rel.length(); + if dist > RANGE { + return None; + } + let bearing = heading_of(rel); + (angle_diff(sam.heading, bearing).abs() <= SECTOR_HALF).then_some((dist, d.id)) + }) + .collect(); + local.sort_by(|a, b| a.0.total_cmp(&b.0)); + local.truncate(LOCAL_CANDIDATES); + local.first().map(|&(_, id)| id) + } + + /// One tick of every optical post: age state, then spend the bounded line-of-sight budget. + /// It never writes a [`Track`] and never calls the enemy-intel emission channel. + pub(super) fn update_optics(&mut self, ground: &mut Ground) { + let now = self.tick; + let posts: Vec = self + .sams + .iter() + .enumerate() + .filter(|(_, s)| s.kind == SamKind::Optical) + .map(|(i, _)| i) + .collect(); + if posts.is_empty() { + return; + } + let alive: std::collections::HashSet = + self.drones.iter().filter(|d| d.alive()).map(|d| d.id).collect(); + for &i in &posts { + let sam = &mut self.sams[i]; + if !sam.alive() || sam.moving() { + sam.optical.clear_activity(); + continue; + } + if sam.part(Part::Sensor) <= 0.0 { + sam.optical.clear_activity(); + sam.optical.state = OpticalState::NoSight; + sam.optical.block = Some(SightBlock::Sensor); + continue; + } + if let Some(id) = sam.optical.target() { + if !alive.contains(&id) { + sam.optical.drop_target(); + } + } + if let Some(id) = sam.optical.commanded() { + if !alive.contains(&id) { + sam.optical.commanded = None; + } + } + // Searching posts keep their head turning; a post on a contact points at its forecast. + if let Some(id) = sam.optical.target() { + if let Some(d) = self.drones.iter().find(|d| d.id == id) { + sam.dish = heading_of(d.pos - sam.pos); + } + } else { + sam.dish = (sam.dish + 0.02) % TAU; + } + } + // Fair round-robin: a crowd of posts does not starve the last ones for ever. + let start = (now as usize) % posts.len(); + let mut checks = 0usize; + for k in 0..posts.len() { + if checks >= CHECKS_PER_TICK { + break; + } + let i = posts[(start + k) % posts.len()]; + let phase = (self.sams[i].id / PARTS) as u64 % PERIOD; + if now % PERIOD != phase { + continue; + } + let Some(target) = self.optical_target(i, now, &alive) else { + self.sams[i].optical.select(None); + continue; + }; + if self.sams[i].optical.target() != Some(target) { + self.sams[i].optical.select(Some(target)); + } + let sam = &self.sams[i]; + let Some(d) = self.drones.iter().find(|d| d.id == target && d.alive()) else { + continue; + }; + let from = sam.pos + DVec3::Y * MAST; + let to = d.pos; + let rel = to - from; + let range = rel.length(); + let bearing = heading_of(to - sam.pos); + let night = self.night; + let sight = line_of_sight(ground, from, to, now, range, night); + checks += 1; + let sam = &mut self.sams[i]; + sam.optical.checks += 1; + match sight { + Ok(()) => { + sam.optical.block = None; + sam.optical.seen = Some((target, d.pos, d.vel, now)); + sam.optical.held = sam.optical.held.saturating_add(1); + let need = sam.optical.required(night); + if sam.optical.held >= need { + let samples = sam.optical.observations.saturating_add(1); + let observable = OpticalObservable { speed: d.vel.length(), climb: d.vel.y, range }; + let observation = OpticalObservation { + target, + source: sam.id, + tick: now, + class: classify_optical(observable), + uncertainty: uncertainty(range, night, samples), + range, + bearing, + hold: sam.optical.held, + night, + }; + sam.optical.held = 0; + sam.optical.observations = samples; + sam.optical.observation = Some(observation); + sam.optical.state = OpticalState::Observing; + } else { + sam.optical.state = if sam.optical.observation.is_some_and(|o| o.target == target) { + OpticalState::Observing + } else { + OpticalState::Holding + }; + } + } + Err(block) => { + sam.optical.held = 0; + sam.optical.block = Some(block); + sam.optical.state = OpticalState::NoSight; + } + } + // The post's own state is `OpticalState`: it never claims a fire-control track. + sam.state = SamState::Search; + sam.optical.target = Some(target); + } + } +} + +/// How unsure one observation is: range, night and the number of successful holds of the same contact. +fn uncertainty(range: f64, night: bool, samples: u32) -> f64 { + let r = (range / RANGE).clamp(0.0, 1.0); + let base = 0.10 + 0.55 * r + if night { 0.15 } else { 0.0 }; + let refine = 0.85_f64.powi(samples.saturating_sub(1).min(3) as i32); + (base * refine).clamp(0.05, 0.95) +} + +/// A bounded line of sight: land samples first, then one block probe. Unknown is never clear. +fn line_of_sight(ground: &mut Ground, from: DVec3, to: DVec3, now: u64, range: f64, night: bool) -> Result<(), SightBlock> { + if range > RANGE { + return Err(SightBlock::OutOfRange); + } + if night && range > NIGHT_RANGE { + return Err(SightBlock::Night); + } + for k in 1..TERRAIN_SAMPLES { + let t = k as f64 / TERRAIN_SAMPLES as f64; + let p = from + (to - from) * t; + let Some(g) = ground.land(DVec3::new(p.x, 0.0, p.z)) else { + return Err(SightBlock::UnknownGeometry); + }; + if g > p.y - 0.8 { + return Err(SightBlock::Terrain); + } + } + match ground.world.probe(from, to, now) { + Sweep::Clear => Ok(()), + Sweep::Hit { .. } => Err(SightBlock::Obstacle), + Sweep::Unknown { .. } | Sweep::Wait { .. } => Err(SightBlock::UnknownGeometry), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use super::super::sight::Track; + + fn optical_at(sim: &mut Sim, x: f64, z: f64, heading: f64) -> u32 { + let id = sim.id(); + sim.sams.push(Sam::new(id, SamKind::Optical, DVec3::new(x, 70.0, z), heading)); + id + } + + /// Flat land at 70 and empty block sections along the line: a clear day. + fn clear_ground() -> Ground { + let mut ground = Ground::default(); + let mut cols = Vec::new(); + for x in -24..=24 { + for z in -180..=24 { + cols.push((x, z, 70)); + } + } + ground.answer(cols, 0); + let mut answers = Vec::new(); + for x in -1..=1 { + for y in 3..=7 { + for z in -12..=1 { + answers.push(world::SectionAnswer { sec: (x, y, z), fill: world::Fill::Empty }); + } + } + } + ground.world.answer(answers, 0); + ground + } + + fn flat_drone(sim: &mut Sim, kind: DroneKind, at: DVec3, vel: DVec3) -> u32 { + sim.add_drone(kind, at, DVec3::NEG_Z, at + DVec3::NEG_Z * 100.0); + let d = sim.drones.last_mut().unwrap(); + d.pos = at; + d.vel = vel; + d.id + } + + fn run(sim: &mut Sim, ground: &mut Ground, ticks: u64) { + for _ in 0..ticks { + sim.tick += 1; + sim.update_optics(ground); + } + } + + // Day: one contact in the near sector is held and then classed. The source is the post itself. + #[test] + fn a_held_contact_gives_an_independent_class_observation() { + let mut sim = Sim::new(1); + let post = optical_at(&mut sim, 0.0, 0.0, 0.0); + let id = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6)); + let mut ground = clear_ground(); + run(&mut sim, &mut ground, 200); + let r = sim.optical_report(post).unwrap(); + let obs = r.observation.expect("no class observation after a clear held contact"); + assert_eq!(obs.source, post); + assert_eq!(obs.target, id); + assert_eq!(obs.class, Class::Drone); + assert!(obs.uncertainty < 0.5, "uncertainty {}", obs.uncertainty); + assert_eq!(r.state, OpticalState::Observing); + // Another successful hold is another independent observation: it refines, never re-measures a relay. + run(&mut sim, &mut ground, 250); + let later = sim.optical_report(post).unwrap(); + let again = later.observation.unwrap(); + assert!(again.tick > obs.tick && later.observations > 1); + assert!(again.uncertainty <= obs.uncertainty, "{} > {}", again.uncertainty, obs.uncertainty); + } + + // Night blocks a contact beyond the reduced reach, and slows a close one: the day hold is not enough. + #[test] + fn night_shortens_the_reach_and_slows_the_hold() { + let mut sim = Sim::new(2); + sim.night = true; + let post = optical_at(&mut sim, 0.0, 0.0, 0.0); + flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -200.0), DVec3::new(0.5, 0.0, -0.6)); + let mut ground = clear_ground(); + run(&mut sim, &mut ground, 200); + let r = sim.optical_report(post).unwrap(); + assert_eq!(r.state, OpticalState::NoSight); + assert_eq!(r.block, Some(SightBlock::Night)); + assert!(r.observation.is_none()); + + let mut close = Sim::new(3); + close.night = true; + let post = optical_at(&mut close, 0.0, 0.0, 0.0); + flat_drone(&mut close, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6)); + let mut ground = clear_ground(); + run(&mut close, &mut ground, HOLD_DAY as u64 * PERIOD as u64 + 10); + assert!(close.optical_report(post).unwrap().observation.is_none(), "a night hold was as quick as a day one"); + run(&mut close, &mut ground, (HOLD_NIGHT - HOLD_DAY) as u64 * PERIOD as u64 + 20); + let r = close.optical_report(post).unwrap(); + assert_eq!(r.state, OpticalState::Observing); + assert!(r.observation.is_some()); + } + + // A wall hides the contact; unknown block geometry is not a clean line of sight. + #[test] + fn a_wall_blocks_and_unknown_geometry_is_not_clear() { + let mut sim = Sim::new(4); + let post = optical_at(&mut sim, 0.0, 0.0, 0.0); + flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6)); + let mut ground = clear_ground(); + ground.world.answer(vec![world::SectionAnswer { sec: (0, 5, -4), fill: world::Fill::Full }], 0); + run(&mut sim, &mut ground, 200); + let r = sim.optical_report(post).unwrap(); + assert_eq!(r.state, OpticalState::NoSight); + assert_eq!(r.block, Some(SightBlock::Obstacle)); + assert!(r.observation.is_none()); + + // The same clear land and sky, but no answered sections: unknown, not clear. + let mut unknown = Sim::new(5); + let post = optical_at(&mut unknown, 0.0, 0.0, 0.0); + flat_drone(&mut unknown, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6)); + let mut ground = Ground::default(); + let mut cols = Vec::new(); + for x in -24..=24 { + for z in -180..=24 { + cols.push((x, z, 70)); + } + } + ground.answer(cols, 0); + run(&mut unknown, &mut ground, 200); + let r = unknown.optical_report(post).unwrap(); + assert_eq!(r.block, Some(SightBlock::UnknownGeometry)); + assert!(r.observation.is_none()); + } + + // Once the view is lost, the old observation only ages: no new observation is invented. + #[test] + fn an_old_observation_only_ages_after_the_view_is_lost() { + let mut sim = Sim::new(6); + let post = optical_at(&mut sim, 0.0, 0.0, 0.0); + flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -180.0), DVec3::new(0.5, 0.0, -0.6)); + let mut ground = clear_ground(); + run(&mut sim, &mut ground, 300); + let first = sim.optical_report(post).unwrap().observation.expect("no day observation"); + let count = sim.optical_report(post).unwrap().observations; + sim.night = true; + run(&mut sim, &mut ground, 300); + let r = sim.optical_report(post).unwrap(); + let last = r.observation.expect("the old observation was thrown away"); + assert_eq!(last.tick, first.tick, "a new observation was invented while the view was lost"); + assert_eq!(r.observations, count); + assert!(last.age(sim.tick) > 200); + assert_eq!(r.state, OpticalState::NoSight); + } + + // The class comes from observable motion, never from DroneKind: two true models with the same + // pose and velocity get the same estimate and the same uncertainty. + #[test] + fn different_true_models_with_equal_observables_get_an_equal_estimate() { + fn observe(kind: DroneKind) -> (OpticalObservation, String) { + let mut sim = Sim::new(7); + let post = optical_at(&mut sim, 0.0, 0.0, 0.0); + flat_drone(&mut sim, kind, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.9, 0.0, -0.9)); + let mut ground = clear_ground(); + run(&mut sim, &mut ground, 200); + let r = sim.optical_report(post).unwrap(); + (r.observation.expect("no observation"), r.line()) + } + let (a, text_a) = observe(DroneKind::Shahed); + let (b, text_b) = observe(DroneKind::Kinzhal); + assert_eq!((a.class, a.uncertainty), (b.class, b.uncertainty)); + assert_eq!(a.class, Class::Jet); + for text in [text_a, text_b] { + assert!(!text.contains("Шахед") && !text.contains("Кинжал"), "{text}"); + assert!(text.contains("оптический пост"), "{text}"); + } + } + + // A network cue only points the head; it is not a measurement and does not raise confidence. + #[test] + fn a_network_cue_is_not_a_measurement() { + let mut sim = Sim::new(8); + let post = optical_at(&mut sim, 0.0, 0.0, 0.0); + let id = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -500.0), DVec3::new(0.5, 0.0, -0.6)); + sim.sams[0].tracks.push(Track { + id, + class: ClassEst::Probable(Class::Drone), + pos: sim.drones[0].pos, + vel: sim.drones[0].vel, + tick: 0, + own_tick: 0, + source: u32::MAX, + product: battery::Measure::Search, + quality: 60, + own_product: battery::Measure::Search, + own_quality: 0, + ttl: 100_000, + hits: 3, + locked: false, + }); + let mut ground = clear_ground(); + // The cue is fresh only for its `CUE_MAX_AGE`; the contact is beyond the optics' own reach. + run(&mut sim, &mut ground, 60); + let r = sim.optical_report(post).unwrap(); + assert_eq!(r.target, Some(id)); + assert_eq!(r.state, OpticalState::NoSight); + assert_eq!(r.block, Some(SightBlock::OutOfRange)); + assert!(r.observation.is_none() && r.observations == 0, "a relayed track became a measurement"); + } + + // A manual priority selects exactly one contact and is kept while it lives. + #[test] + fn a_manual_priority_selects_one_contact() { + let mut sim = Sim::new(11); + let post = optical_at(&mut sim, 0.0, 0.0, 0.0); + let near = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -60.0), DVec3::new(0.5, 0.0, -0.6)); + let far = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -120.0), DVec3::new(0.5, 0.0, -0.6)); + assert!(sim.assign_optical(post, Some(far))); + let mut ground = clear_ground(); + run(&mut sim, &mut ground, 60); + let r = sim.optical_report(post).unwrap(); + assert_eq!(r.target, Some(far)); + assert!(sim.assign_optical(post, Some(near))); + run(&mut sim, &mut ground, 10); + assert_eq!(sim.optical_report(post).unwrap().target, Some(near)); + assert!(!sim.assign_optical(post, Some(u32::MAX)), "a dead contact cannot be assigned"); + } + + // A failed optic is not a clear line: the state says so, and no observation is made. + #[test] + fn a_failed_sensor_stops_the_observation() { + let mut sim = Sim::new(12); + let post = optical_at(&mut sim, 0.0, 0.0, 0.0); + flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6)); + sim.sams[0].comps.0[Part::Sensor as usize] = 0.0; + let mut ground = clear_ground(); + run(&mut sim, &mut ground, 200); + let r = sim.optical_report(post).unwrap(); + assert_eq!(r.state, OpticalState::NoSight); + assert_eq!(r.block, Some(SightBlock::Sensor)); + assert!(r.observation.is_none()); + } + + // Work is bounded: many posts and many contacts still spend only the per-tick probe budget. + #[test] + fn many_posts_and_contacts_keep_the_los_budget_bounded() { + let mut sim = Sim::new(9); + for i in 0..32 { + optical_at(&mut sim, (i % 8) as f64 * 8.0, (i / 8) as f64 * 8.0, 0.0); + } + for i in 0..64 { + flat_drone(&mut sim, DroneKind::Shahed, DVec3::new((i % 8) as f64, 95.0, -60.0 - (i / 8) as f64 * 4.0), DVec3::new(0.5, 0.0, -0.6)); + } + let mut ground = clear_ground(); + sim.tick += 1; + sim.update_optics(&mut ground); + let checks: u64 = sim.sams.iter().filter(|s| s.kind == SamKind::Optical).map(|s| s.optical.checks()).sum(); + assert!(checks > 0 && checks <= CHECKS_PER_TICK as u64, "checks {checks}"); + } + + // The post is passive: no radar emission, no own track, no enemy emission contact. + #[test] + fn the_post_never_emits_or_makes_a_fire_control_track() { + let mut sim = Sim::new(10); + let post = optical_at(&mut sim, 0.0, 0.0, 0.0); + flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6)); + let mut ground = clear_ground(); + run(&mut sim, &mut ground, 200); + let sam = sim.sams.iter().find(|s| s.id == post).unwrap(); + assert!(!sam.radar_up()); + assert!(sam.own.is_empty()); + assert!(sam.target.is_none() && sam.gun_target.is_none()); + assert!(sam.tracks.is_empty()); + assert!(sim.intel.contacts().is_empty(), "a passive post entered the enemy's emission picture"); + } +} diff --git a/airdef-mod/src/sim/orders.rs b/airdef-mod/src/sim/orders.rs index f236f29..ce7a055 100644 --- a/airdef-mod/src/sim/orders.rs +++ b/airdef-mod/src/sim/orders.rs @@ -18,9 +18,9 @@ impl SamKind { Family::Truck => 10, } } - /// A depot doesn't drive. + /// A depot and a fixed optical post don't drive. pub fn mobile(self) -> bool { - self != SamKind::Depot + !matches!(self, SamKind::Depot | SamKind::Optical) } } diff --git a/airdef-mod/src/sim/sight.rs b/airdef-mod/src/sim/sight.rs index aa02844..f03a5f1 100644 --- a/airdef-mod/src/sim/sight.rs +++ b/airdef-mod/src/sim/sight.rs @@ -611,6 +611,9 @@ impl Sim { } } } + // Passive optics (#136) look after the network has spoken: a cue is only a cue, and every + // observation it makes is its own, never a track and never an emission. + self.update_optics(ground); } /// Whether any system's radar holds this drone (the player's radar shows only those). diff --git a/airdef-mod/src/sim/unit_specs_generated.rs b/airdef-mod/src/sim/unit_specs_generated.rs index 1581692..325dfc7 100644 --- a/airdef-mod/src/sim/unit_specs_generated.rs +++ b/airdef-mod/src/sim/unit_specs_generated.rs @@ -380,6 +380,31 @@ const UNIT_SPEC_LIGHT: SamSpec = SamSpec { mast: 1.5, }; +const UNIT_SPEC_OPTICAL: SamSpec = SamSpec { + name: "Оптический пост", + key: "optical", + missile: None, + gun: None, + reload: 0, + scale: 1.0, + rest_pitch: 0.0, + roles: 0, + family: Family::Static, + parts: Parts { + body: "airdef:radar_truck", + launcher: None, + pack: None, + dish: None, + fixed: &[], + spinner: Some(("airdef:radar_panel", 1.2, 0.0, 0.6, -0.2)), + }, + mount: (0.0, 0.0), + pivot: DVec3::ZERO, + muzzle: Muzzle::None, + sensor: 0.0, + mast: 2.5, +}; + impl SamKind { /// Its row of numbers from `catalog/specs.json`. pub fn spec(self) -> &'static SamSpec { @@ -399,13 +424,14 @@ impl SamKind { SamKind::Tzm => &UNIT_SPEC_TZM, SamKind::Ew => &UNIT_SPEC_EW, SamKind::Light => &UNIT_SPEC_LIGHT, + SamKind::Optical => &UNIT_SPEC_OPTICAL, } } } /// Save keys by kind; a rename needs an explicit migration. #[cfg(test)] -pub(super) const UNIT_SPEC_KEYS: [(SamKind, &str); 15] = [ +pub(super) const UNIT_SPEC_KEYS: [(SamKind, &str); 16] = [ (SamKind::Patriot, "patriot"), (SamKind::Gepard, "gepard"), (SamKind::Pantsir, "pantsir"), @@ -421,4 +447,5 @@ pub(super) const UNIT_SPEC_KEYS: [(SamKind, &str); 15] = [ (SamKind::Tzm, "tzm"), (SamKind::Ew, "ew"), (SamKind::Light, "light"), + (SamKind::Optical, "optical"), ]; diff --git a/airdef-mod/src/sim/units.rs b/airdef-mod/src/sim/units.rs index d853ecd..8a6c863 100644 --- a/airdef-mod/src/sim/units.rs +++ b/airdef-mod/src/sim/units.rs @@ -27,6 +27,8 @@ pub enum SamKind { Ew, /// A searchlight: lights up targets at night for the guns. Light, + /// A passive optical observation post: no radar, no weapon, one class observation at a time (#136). + Optical, } /// How a vehicle is put together: how its launcher or turret moves and is drawn. diff --git a/airdef-mod/src/wave.rs b/airdef-mod/src/wave.rs index 0a8c99f..4874bbc 100644 --- a/airdef-mod/src/wave.rs +++ b/airdef-mod/src/wave.rs @@ -179,14 +179,21 @@ mod catalog_tests { } fn item_exists(item: &str) { let name = item.strip_prefix("airdef:").expect("item namespace"); - for path in [format!("items/{name}.json"), format!("models/item/{name}.json"), format!("textures/item/{name}.png")] { + for path in [format!("items/{name}.json"), format!("models/item/{name}.json")] { assert!(assets().join(&path).is_file(), "{item}: missing {path}"); } let definition = std::fs::read_to_string(assets().join(format!("items/{name}.json"))).unwrap(); assert!(definition.contains(&format!("airdef:item/{name}")), "{item}: wrong item model"); let model = std::fs::read_to_string(assets().join(format!("models/item/{name}.json"))).unwrap(); - assert!(model.contains(&format!("airdef:item/{name}")), "{item}: wrong icon reference"); - let png = std::fs::read(assets().join(format!("textures/item/{name}.png"))).unwrap(); + // The icon reference may be an alias of an existing texture (the optical post uses the + // radar icon until its own asset lands, #136); what matters is that the PNG it names exists. + let layer = model + .split("\"layer0\": \"") + .nth(1) + .and_then(|s| s.split('"').next()) + .unwrap_or_else(|| panic!("{item}: no icon reference")); + let texture = layer.strip_prefix("airdef:item/").unwrap_or_else(|| panic!("{item}: bad icon reference {layer}")); + let png = std::fs::read(assets().join(format!("textures/item/{texture}.png"))).unwrap(); assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "{item}: invalid PNG signature"); } fn model_exists(model: &str) { diff --git a/catalog/content.json b/catalog/content.json index d93d250..5bce516 100644 --- a/catalog/content.json +++ b/catalog/content.json @@ -126,6 +126,10 @@ { "kind": "Light", "item": "deploy_light" + }, + { + "kind": "Optical", + "item": "deploy_optical" } ], "variants": [ @@ -405,6 +409,15 @@ 52 ] }, + { + "id": "deploy_optical", + "title": "Развернуть оптический пост", + "color": [ + 70, + 110, + 90 + ] + }, { "id": "mover", "title": "Пульт перемещения", diff --git a/catalog/specs.json b/catalog/specs.json index 5731175..935a76a 100644 --- a/catalog/specs.json +++ b/catalog/specs.json @@ -668,6 +668,31 @@ "muzzle": {"type": "none"}, "sensor": 0.0, "mast": 1.5 + }, + { + "kind": "Optical", + "key": "optical", + "name": "Оптический пост", + "missile": null, + "gun": null, + "reload": 0, + "scale": 1.0, + "rest_pitch": 0.0, + "roles": 0, + "family": "static", + "parts": { + "body": "airdef:radar_truck", + "launcher": null, + "pack": null, + "dish": null, + "fixed": [], + "spinner": ["airdef:radar_panel", 1.2, 0.0, 0.6, -0.2] + }, + "mount": [0.0, 0.0], + "pivot": [0.0, 0.0, 0.0], + "muzzle": {"type": "none"}, + "sensor": 0.0, + "mast": 2.5 } ], "missiles": [ diff --git a/tools/airdef_assets/icons.py b/tools/airdef_assets/icons.py index 0227914..dd78ac9 100644 --- a/tools/airdef_assets/icons.py +++ b/tools/airdef_assets/icons.py @@ -339,6 +339,8 @@ ICON_DRAW = { "deploy_radar": _radar, "deploy_ew": _ew, "deploy_depot": _depot, "deploy_tzm": _tzm, "deploy_light": _searchlight, + # Temporary placeholder until the optical post has its own icon (#136). + "deploy_optical": _radar, "mover": _mover, "remover": _remover, "flare_gun": _flare, }