Files
airdef/airdef-mod/src/map.rs
T
chexit 57a5426e65
build / mod (push) Successful in 4m13s
Strikes on launch sites, command map and placement editor, fire doctrines, ground routes, acoustics switch and reverb
#101: radars locate sites from launches, /airdef sites, /airdef strike; sites launch slower (15/25/50 ticks) so a strike can come in time. #48: M opens the map on the network's picture, with an editor. #47: guard, sector, reserve and salvo per system. #94: vehicles route round slopes and water and say when they cannot get through. #96: reverb, and a menu switch for the acoustics. #92: generated files are validated before the swap, repo map.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:59:03 +03:00

1735 lines
73 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! The command map (#48): a full-screen map of the land with the systems, the objects, the launch sites
//! the radars found and the tracks the player's network holds; a placement editor for the layout before
//! a battle; the doctrine's guards and sector picked on the map.
//!
//! The map shows what the network knows (`Sim::picture`: the last measurement and the forecast of each
//! track), never the true drones, unless the sandbox's `truth` is on, and then it says so. The terrain
//! comes from the game as tiles (`render::TerrainShape`): the mod only says which, and the game scans the
//! loaded chunks within a budget; land it hasn't got is drawn as unknown.
use crate::panel::distance;
use crate::sim::{self, Class, Sam, SamKind, Sim, doctrine::Doctrine, Track, strike::SiteState};
use crate::{AirDef, say};
use glam::DVec3;
use horizon_mod_sdk::render::{self, CanvasEvent, FillShape, Point, QuadShape, Rect, Shape, TerrainShape, TextShape};
use std::collections::HashMap;
use std::f32::consts::TAU;
const FILTERS: [&str; 7] = ["рельеф", "системы", "объекты", "цели сети", "следы", "пусковые", "дальности"];
const F_TERRAIN: usize = 0;
const F_SAMS: usize = 1;
const F_OBJECTS: usize = 2;
const F_TRACKS: usize = 3;
const F_TRAILS: usize = 4;
const F_SITES: usize = 5;
const F_RINGS: usize = 6;
/// Blocks per pixel limits: the whole raid, and one vehicle.
const SCALE_MIN: f64 = 0.04;
const SCALE_MAX: f64 = 24.0;
const TRAIL_POINTS: usize = 90;
/// Ticks between trail samples.
const SAMPLE: u64 = 10;
/// Pixels within which the pointer picks something.
const PICK_R: f32 = 9.0;
const DRAFT_UNDO: usize = 40;
const GREEN: u32 = 0xFF80FF90;
const WHITE: u32 = 0xFFFFFFFF;
const GREY: u32 = 0xFFB0B0B0;
const YELLOW: u32 = 0xFFFFE070;
const RED: u32 = 0xFFFF5050;
const CYAN: u32 = 0xFF9FE0FF;
const ORANGE: u32 = 0xFFFFA040;
const PANEL: u32 = 0xD0101814;
/// The right card's width in GUI pixels.
const CARD_W: f32 = 196.0;
#[derive(Clone, Copy, PartialEq, Debug)]
enum Sel {
Sam(u32),
Object(usize),
Site(u32),
Track(u32),
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum Pick {
None,
Sam(SamKind),
Object,
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum Mode {
View,
/// Pick the objects the system guards.
Guard(u32),
/// Pick the sector's centre, then its width.
Sector(u32, Option<f64>),
Editor,
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum Act {
Filter(usize),
Editor,
Pick(Pick),
Confirm,
Cancel,
Undo,
Guard,
Sector,
SectorOff,
Reserve,
Salvo,
Role(u8),
ResetDoc,
Strike(u32),
Centre,
Follow,
Rotate,
Delete,
Close,
Player,
}
/// A system in the draft layout: an existing one (by id) or one to be built.
#[derive(Clone, Debug)]
struct DSam {
id: Option<u32>,
kind: SamKind,
pos: DVec3,
heading: f64,
gone: bool,
}
#[derive(Clone, Debug)]
struct DObj {
idx: Option<usize>,
pos: DVec3,
gone: bool,
}
#[derive(Clone, Debug, Default)]
struct Draft {
sams: Vec<DSam>,
objs: Vec<DObj>,
}
enum Drag {
Pan { from: (f32, f32), centre: (f64, f64), moved: bool },
Sam(usize),
Obj(usize),
}
struct Btn {
rect: [f32; 4],
act: Act,
}
/// What the map keeps between frames.
pub struct MapUi {
pub open: bool,
size: (f32, f32),
cursor: (f32, f32),
centre: (f64, f64),
scale: f64,
placed: bool,
drag: Option<Drag>,
sel: Option<Sel>,
follow: bool,
mode: Mode,
filters: [bool; 7],
trails: HashMap<u32, Vec<(f32, f32)>>,
seen: HashMap<u32, u64>,
sampled: u64,
draft: Draft,
history: Vec<Draft>,
pick: Pick,
heading: f64,
ed_sel: Option<EdSel>,
note: Option<(String, u64)>,
dirty: bool,
drawn: u64,
buttons: Vec<Btn>,
chunks_at: u64,
close: bool,
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum EdSel {
Sam(usize),
Obj(usize),
}
impl Default for MapUi {
fn default() -> Self {
MapUi {
open: false,
size: (480.0, 270.0),
cursor: (0.0, 0.0),
centre: (0.0, 0.0),
scale: 0.5,
placed: false,
drag: None,
sel: None,
follow: false,
mode: Mode::View,
filters: [true; 7],
trails: HashMap::new(),
seen: HashMap::new(),
sampled: 0,
draft: Draft::default(),
history: Vec::new(),
pick: Pick::None,
heading: 0.0,
ed_sel: None,
note: None,
dirty: true,
drawn: u64::MAX,
buttons: Vec::new(),
chunks_at: 0,
close: false,
}
}
}
fn pt(x: f32, y: f32) -> Point {
Point { x, y }
}
fn fill(x: f32, y: f32, w: f32, h: f32, color: u32) -> Shape {
Shape::Fill(FillShape { rect: Rect { x, y, w, h }, color })
}
fn text(t: impl Into<String>, x: f32, y: f32, color: u32) -> Shape {
Shape::Text(TextShape { text: t.into(), at: pt(x, y), color: color & 0xFFFFFF, centered: false, shadow: true })
}
fn text_c(t: impl Into<String>, x: f32, y: f32, color: u32) -> Shape {
Shape::Text(TextShape { text: t.into(), at: pt(x, y), color: color & 0xFFFFFF, centered: true, shadow: true })
}
/// A line of `w` pixels.
fn line(a: (f32, f32), b: (f32, f32), w: f32, color: u32) -> Shape {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let len = dx.hypot(dy).max(0.001);
let (nx, ny) = (-dy / len * w / 2.0, dx / len * w / 2.0);
Shape::Quad(QuadShape { corners: (pt(a.0 + nx, a.1 + ny), pt(b.0 + nx, b.1 + ny), pt(b.0 - nx, b.1 - ny), pt(a.0 - nx, a.1 - ny)), color })
}
fn frame(x: f32, y: f32, w: f32, h: f32, b: f32, color: u32) -> [Shape; 4] {
[fill(x, y, w, b, color), fill(x, y + h - b, w, b, color), fill(x, y, b, h, color), fill(x + w - b, y, b, h, color)]
}
fn alpha(rgb: u32, a: f32) -> u32 {
(((a.clamp(0.0, 1.0) * 255.0) as u32) << 24) | (rgb & 0xFFFFFF)
}
/// A diamond, a square and the like around (x, y).
fn diamond(x: f32, y: f32, r: f32, color: u32) -> Shape {
Shape::Quad(QuadShape { corners: (pt(x, y - r), pt(x + r, y), pt(x, y + r), pt(x - r, y)), color })
}
/// The direction a heading looks along on the map (x east, z south): `heading_of`'s inverse.
fn dir_of(h: f64) -> (f64, f64) {
(-h.sin(), -h.cos())
}
impl MapUi {
fn to_screen(&self, x: f64, z: f64) -> (f32, f32) {
(
(self.size.0 as f64 / 2.0 + (x - self.centre.0) * self.scale) as f32,
(self.size.1 as f64 / 2.0 + (z - self.centre.1) * self.scale) as f32,
)
}
fn to_world(&self, p: (f32, f32)) -> (f64, f64) {
(
self.centre.0 + (p.0 as f64 - self.size.0 as f64 / 2.0) / self.scale,
self.centre.1 + (p.1 as f64 - self.size.1 as f64 / 2.0) / self.scale,
)
}
fn on_screen(&self, p: (f32, f32), margin: f32) -> bool {
p.0 > -margin && p.1 > -margin && p.0 < self.size.0 + margin && p.1 < self.size.1 + margin
}
fn note(&mut self, tick: u64, s: impl Into<String>) {
self.note = Some((s.into(), tick + 100));
self.dirty = true;
}
/// Remembers where the network's tracks are, every few ticks, for the trails.
pub fn sample(&mut self, sim: &Sim) {
if sim.tick < self.sampled {
self.trails.clear();
self.seen.clear();
}
if sim.tick < self.sampled + SAMPLE {
return;
}
self.sampled = sim.tick;
for (id, t) in sim.picture() {
// Only measurements: a forecast is not a place the target has been.
if t.age(sim.tick) > SAMPLE * 2 {
continue;
}
let trail = self.trails.entry(id).or_default();
let p = (t.pos.x as f32, t.pos.z as f32);
if trail.last().is_none_or(|l| (l.0 - p.0).hypot(l.1 - p.1) > 4.0) {
trail.push(p);
if trail.len() > TRAIL_POINTS {
trail.remove(0);
}
}
self.seen.insert(id, sim.tick);
}
let now = sim.tick;
self.seen.retain(|_, t| now.saturating_sub(*t) < 1200);
let seen = &self.seen;
self.trails.retain(|id, _| seen.contains_key(id));
}
fn enter_editor(&mut self) {
self.draft = Draft::default();
self.history.clear();
self.mode = Mode::Editor;
self.pick = Pick::None;
self.ed_sel = None;
self.sel = None;
self.dirty = true;
}
fn push_history(&mut self) {
self.history.push(self.draft.clone());
if self.history.len() > DRAFT_UNDO {
self.history.remove(0);
}
}
}
/// Whether a system reaches the point (its weapons, on the plane).
fn reaches(kind: SamKind, pos: DVec3, p: DVec3) -> bool {
kind.range() > 0.0 && (pos.x - p.x).hypot(pos.z - p.z) <= kind.range()
}
fn class_name(c: sim::sites::SiteClass) -> &'static str {
match c {
sim::sites::SiteClass::Ramp => "рампа дронов",
sim::sites::SiteClass::Launcher => "пусковая ракет",
sim::sites::SiteClass::Battery => "батарея баллистических",
}
}
impl AirDef {
/// Opens the map (the key, or the menu).
pub(crate) fn map_toggle(&mut self) {
if self.map.open {
self.map_close();
return;
}
if self.replay.is_some() {
say("Карта: сначала закройте повтор");
return;
}
let Some(p) = crate::player() else { return };
let ui = &mut self.map;
ui.open = true;
ui.mode = Mode::View;
ui.drag = None;
ui.size = render::gui_size();
if !ui.placed {
ui.centre = (p.x, p.z);
ui.placed = true;
}
ui.dirty = true;
ui.drawn = u64::MAX;
render::open_canvas();
}
pub(crate) fn map_close(&mut self) {
if self.map.open {
render::close_canvas();
render::set_canvas(&[]);
}
self.map.open = false;
self.map.draft = Draft::default();
self.map.mode = Mode::View;
self.map.drag = None;
}
/// Once a frame while the map is open.
pub(crate) fn map_frame(&mut self) {
if !self.map.open {
return;
}
if !render::canvas_open() {
// The game closed it (the world was left, or it was not the time).
self.map.open = false;
self.map.draft = Draft::default();
self.map.mode = Mode::View;
return;
}
let mut ui = std::mem::take(&mut self.map);
for ev in render::canvas_events() {
self.map_event(&mut ui, ev);
if ui.close {
break;
}
}
if ui.close {
ui.close = false;
self.map = ui;
self.map_close();
return;
}
if ui.open {
if ui.follow
&& let Some(Sel::Track(id)) = ui.sel
&& let Some(t) = self.sim.picture().get(&id)
{
let e = t.est(self.sim.tick);
ui.centre = (e.x, e.z);
ui.dirty = true;
}
// The data moves at the sim's pace: a few redraws a second even when nothing is touched.
let step = self.sim.tick / 2;
if ui.dirty || ui.drawn != step {
ui.dirty = false;
ui.drawn = step;
let shapes = self.map_shapes(&mut ui);
render::set_canvas(&shapes);
}
}
self.map = ui;
}
fn ground_y(&mut self, x: f64, z: f64) -> Option<f64> {
self.ground.at(DVec3::new(x, 0.0, z), self.sim.tick)
}
fn map_event(&mut self, ui: &mut MapUi, ev: CanvasEvent) {
match ev {
CanvasEvent::Resized((w, h)) => {
ui.size = (w, h);
ui.dirty = true;
}
CanvasEvent::Moved(p) => {
ui.cursor = (p.x, p.y);
ui.dirty = true;
match &mut ui.drag {
Some(Drag::Pan { from, centre, moved }) => {
let (dx, dy) = (p.x - from.0, p.y - from.1);
if dx.hypot(dy) > 3.0 {
*moved = true;
}
if *moved {
ui.centre = (centre.0 - dx as f64 / ui.scale, centre.1 - dy as f64 / ui.scale);
ui.follow = false;
}
}
Some(Drag::Sam(i)) => {
let i = *i;
let (x, z) = ui.to_world((p.x, p.y));
if let Some(y) = self.ground_y(x, z)
&& let Some(d) = ui.draft.sams.get_mut(i)
{
d.pos = DVec3::new(x, y, z);
}
}
Some(Drag::Obj(i)) => {
let i = *i;
let (x, z) = ui.to_world((p.x, p.y));
if let Some(y) = self.ground_y(x, z)
&& let Some(d) = ui.draft.objs.get_mut(i)
{
d.pos = DVec3::new(x, y, z);
}
}
None => {}
}
}
CanvasEvent::Scrolled(s) => {
let at = (s.at.x, s.at.y);
let before = ui.to_world(at);
ui.scale = (ui.scale * 1.25f64.powf(s.steps as f64)).clamp(SCALE_MIN, SCALE_MAX);
// The point under the pointer stays under it.
ui.centre = (before.0 - (at.0 as f64 - ui.size.0 as f64 / 2.0) / ui.scale, before.1 - (at.1 as f64 - ui.size.1 as f64 / 2.0) / ui.scale);
ui.follow = false;
ui.dirty = true;
}
CanvasEvent::Pressed(b) => {
let at = (b.at.x, b.at.y);
ui.cursor = at;
ui.dirty = true;
if b.button == 0 {
let hit = ui.buttons.iter().find(|bt| at.0 >= bt.rect[0] && at.0 <= bt.rect[0] + bt.rect[2] && at.1 >= bt.rect[1] && at.1 <= bt.rect[1] + bt.rect[3]).map(|bt| bt.act);
if let Some(act) = hit {
self.map_act(ui, act);
return;
}
}
match (b.button, ui.mode) {
(0, Mode::Editor) => self.editor_press(ui, at),
(0 | 2, _) => {
ui.drag = Some(Drag::Pan { from: at, centre: ui.centre, moved: false });
}
(1, Mode::Editor) => self.editor_remove_at(ui, at),
(1, _) => self.map_right(ui, at),
_ => {}
}
}
CanvasEvent::Released(b) => {
let at = (b.at.x, b.at.y);
ui.cursor = at;
ui.dirty = true;
let drag = ui.drag.take();
match drag {
Some(Drag::Pan { moved: false, .. }) if b.button == 0 => self.map_click(ui, at),
Some(Drag::Sam(_) | Drag::Obj(_)) => {}
_ => {}
}
}
CanvasEvent::Key(k) => self.map_key(ui, &k),
}
}
fn map_key(&mut self, ui: &mut MapUi, key: &str) {
ui.dirty = true;
let step = (60.0 / ui.scale).max(2.0);
match key {
"key.keyboard.escape" => {
if ui.drag.is_some() {
ui.drag = None;
} else if ui.mode == Mode::Editor {
if ui.pick != Pick::None || ui.ed_sel.is_some() {
ui.pick = Pick::None;
ui.ed_sel = None;
} else {
ui.mode = Mode::View;
ui.draft = Draft::default();
ui.note(self.sim.tick, "Расстановка отменена");
}
} else if ui.mode != Mode::View {
ui.mode = Mode::View;
} else if ui.sel.is_some() {
ui.sel = None;
ui.follow = false;
} else {
ui.close = true;
}
}
"key.keyboard.m" => {
if ui.mode == Mode::Editor && (!ui.draft.sams.is_empty() || !ui.draft.objs.is_empty()) && self.draft_changed(ui) {
ui.note(self.sim.tick, "Есть неподтверждённые изменения: Enter подтвердить, Esc отмена");
return;
}
ui.close = true;
}
"key.keyboard.left" => ui.centre.0 -= step,
"key.keyboard.right" => ui.centre.0 += step,
"key.keyboard.up" => ui.centre.1 -= step,
"key.keyboard.down" => ui.centre.1 += step,
"key.keyboard.equal" => self.map_zoom_centre(ui, 1.25),
"key.keyboard.minus" => self.map_zoom_centre(ui, 0.8),
"key.keyboard.c" => self.map_act(ui, Act::Player),
"key.keyboard.e" => self.map_act(ui, Act::Editor),
"key.keyboard.enter" if ui.mode == Mode::Editor => self.map_act(ui, Act::Confirm),
"key.keyboard.z" if ui.mode == Mode::Editor => self.map_act(ui, Act::Undo),
"key.keyboard.r" if ui.mode == Mode::Editor => self.map_act(ui, Act::Rotate),
"key.keyboard.delete" | "key.keyboard.backspace" if ui.mode == Mode::Editor => self.map_act(ui, Act::Delete),
"key.keyboard.f" => self.map_act(ui, Act::Follow),
k if k.len() == 14 && k.starts_with("key.keyboard.") && k.as_bytes()[13].is_ascii_digit() && k.as_bytes()[13] != b'0' => {
let n = (k.as_bytes()[13] - b'1') as usize;
if n < FILTERS.len() {
ui.filters[n] = !ui.filters[n];
}
}
_ => {}
}
}
fn map_zoom_centre(&mut self, ui: &mut MapUi, k: f64) {
ui.scale = (ui.scale * k).clamp(SCALE_MIN, SCALE_MAX);
}
/// The draft differs from the layout.
fn draft_changed(&self, ui: &MapUi) -> bool {
let d = &ui.draft;
d.sams.iter().any(|s| match s.id {
None => !s.gone,
Some(id) => s.gone || self.sim.sams.iter().find(|x| x.id == id).is_none_or(|x| x.pos.distance(s.pos) > 0.01 || (x.heading - s.heading).abs() > 1e-6),
}) || d.objs.iter().any(|o| match o.idx {
None => !o.gone,
Some(i) => o.gone || self.sim.targets.get(i).is_none_or(|t| t.distance(o.pos) > 0.01),
})
}
/// Loads the layout into the draft the first time the editor needs it.
fn ensure_draft(&mut self, ui: &mut MapUi) {
if !ui.draft.sams.is_empty() || !ui.draft.objs.is_empty() {
return;
}
ui.draft.sams = self.sim.sams.iter().map(|s| DSam { id: Some(s.id), kind: s.kind, pos: s.pos, heading: s.heading, gone: false }).collect();
ui.draft.objs = self.sim.targets.iter().enumerate().map(|(i, p)| DObj { idx: Some(i), pos: *p, gone: false }).collect();
}
fn battle(&self) -> bool {
!self.sim.drones.is_empty() || !self.sim.queue.is_empty() || self.sim.planning()
}
fn map_act(&mut self, ui: &mut MapUi, act: Act) {
ui.dirty = true;
let tick = self.sim.tick;
match act {
Act::Filter(i) => ui.filters[i] = !ui.filters[i],
Act::Close => {
ui.close = true;
}
Act::Player => {
if let Some(p) = crate::player() {
ui.centre = (p.x, p.z);
ui.follow = false;
}
}
Act::Editor => {
if ui.mode == Mode::Editor {
if self.draft_changed(ui) {
ui.note(tick, "Есть неподтверждённые изменения: Enter подтвердить, «Отмена» сбросить");
} else {
ui.mode = Mode::View;
ui.draft = Draft::default();
}
} else if self.battle() {
ui.note(tick, "Бой идёт: расстановка закрыта до конца налёта");
} else {
ui.enter_editor();
self.ensure_draft(ui);
}
}
Act::Pick(p) => {
ui.pick = if ui.pick == p { Pick::None } else { p };
ui.ed_sel = None;
}
Act::Cancel => {
ui.draft = Draft::default();
ui.history.clear();
ui.mode = Mode::View;
ui.pick = Pick::None;
ui.note(tick, "Изменения отменены, ничего не построено");
}
Act::Undo => {
if let Some(d) = ui.history.pop() {
ui.draft = d;
ui.ed_sel = None;
}
}
Act::Rotate => {
let step = std::f64::consts::FRAC_PI_4;
match ui.ed_sel {
Some(EdSel::Sam(i)) => {
ui.push_history();
if let Some(d) = ui.draft.sams.get_mut(i) {
d.heading += step;
}
}
_ => ui.heading += step,
}
}
Act::Delete => {
if let Some(s) = ui.ed_sel.take() {
ui.push_history();
match s {
EdSel::Sam(i) => remove_dsam(&mut ui.draft, i),
EdSel::Obj(i) => remove_dobj(&mut ui.draft, i),
}
}
}
Act::Confirm => self.commit_draft(ui),
Act::Centre => {
if let Some(p) = self.sel_pos(ui) {
ui.centre = (p.x, p.z);
}
}
Act::Follow => {
if matches!(ui.sel, Some(Sel::Track(_))) {
ui.follow = !ui.follow;
}
}
Act::Guard => {
if let Some(Sel::Sam(id)) = ui.sel {
ui.mode = if ui.mode == Mode::Guard(id) { Mode::View } else { Mode::Guard(id) };
}
}
Act::Sector => {
if let Some(Sel::Sam(id)) = ui.sel {
ui.mode = if matches!(ui.mode, Mode::Sector(i, _) if i == id) { Mode::View } else { Mode::Sector(id, None) };
}
}
Act::SectorOff => {
if let Some(i) = self.sel_sam(ui) {
self.edit_doctrine(i, |d| d.sector = None);
}
ui.mode = Mode::View;
}
Act::Reserve => {
if let Some(i) = self.sel_sam(ui) {
self.edit_doctrine(i, |d| d.reserve = [0, 1, 2, 4, 8, 16].into_iter().find(|&r| r > d.reserve).unwrap_or(0));
}
}
Act::Salvo => {
if let Some(i) = self.sel_sam(ui) {
self.edit_doctrine(i, |d| d.salvo = d.salvo.next());
}
}
Act::ResetDoc => {
if let Some(i) = self.sel_sam(ui) {
self.edit_doctrine(i, |d| *d = Doctrine::default());
}
ui.mode = Mode::View;
}
Act::Role(bit) => {
if let Some(i) = self.sel_sam(ui) {
let s = &mut self.sim.sams[i];
s.roles ^= bit;
s.target = None;
s.gun_target = None;
self.dirty = true;
}
}
Act::Strike(site) => {
let Some(p) = crate::player() else { return };
let mut out = sim::Out::default();
match self.sim.order_strike(site, DVec3::new(p.x, p.y, p.z), &mut out) {
Ok(m) => {
say(&m);
ui.note(tick, "Ударная ракета пошла");
}
Err(e) => {
ui.note(tick, e.clone());
say(&e);
}
}
self.emit(out);
}
}
}
fn sel_sam(&self, ui: &MapUi) -> Option<usize> {
match ui.sel {
Some(Sel::Sam(id)) => self.sim.sams.iter().position(|s| s.id == id),
_ => None,
}
}
fn sel_pos(&self, ui: &MapUi) -> Option<DVec3> {
match ui.sel? {
Sel::Sam(id) => self.sim.sams.iter().find(|s| s.id == id).map(|s| s.pos),
Sel::Object(i) => self.sim.targets.get(i).copied(),
Sel::Site(id) => self.sim.strikes.get(id).and_then(|k| k.est.filter(|e| e.fix)).map(|e| DVec3::new(e.pos.x, 0.0, e.pos.y)),
Sel::Track(id) => self.sim.picture().get(&id).map(|t| t.est(self.sim.tick)),
}
}
/// What is under the pointer: systems, objects, launch sites, then tracks.
fn pick_at(&self, ui: &MapUi, p: (f32, f32)) -> Option<Sel> {
let near = |w: DVec3| {
let s = ui.to_screen(w.x, w.z);
(s.0 - p.0).hypot(s.1 - p.1) <= PICK_R
};
if ui.filters[F_SAMS] {
if let Some(s) = self.sim.sams.iter().find(|s| near(s.pos)) {
return Some(Sel::Sam(s.id));
}
}
if ui.filters[F_OBJECTS] {
if let Some(i) = self.sim.targets.iter().position(|t| near(*t)) {
return Some(Sel::Object(i));
}
}
if ui.filters[F_SITES] {
for k in &self.sim.strikes.known {
if let Some(e) = k.est.filter(|e| e.fix)
&& near(DVec3::new(e.pos.x, 0.0, e.pos.y))
{
return Some(Sel::Site(k.site));
}
}
}
if ui.filters[F_TRACKS] {
let now = self.sim.tick;
let pic = self.sim.picture();
let mut best: Option<(f32, u32)> = None;
for (id, t) in &pic {
let e = t.est(now);
let s = ui.to_screen(e.x, e.z);
let d = (s.0 - p.0).hypot(s.1 - p.1);
if d <= PICK_R + 2.0 && best.is_none_or(|b| d < b.0) {
best = Some((d, *id));
}
}
if let Some((_, id)) = best {
return Some(Sel::Track(id));
}
}
None
}
fn map_click(&mut self, ui: &mut MapUi, at: (f32, f32)) {
let hit = self.pick_at(ui, at);
match ui.mode {
Mode::Guard(id) => {
if let Some(Sel::Object(k)) = hit
&& let Some(i) = self.sim.sams.iter().position(|s| s.id == id)
{
let g = self.sim.targets[k];
self.edit_doctrine(i, |d| match d.guards.iter().position(|x| x.distance(g) < 16.0) {
Some(j) => {
d.guards.remove(j);
}
None => d.guards.push(g),
});
} else if hit.is_none() {
ui.mode = Mode::View;
}
}
Mode::Sector(id, centre) => {
let Some(i) = self.sim.sams.iter().position(|s| s.id == id) else {
ui.mode = Mode::View;
return;
};
let (x, z) = ui.to_world(at);
let a = sim::heading_of(DVec3::new(x - self.sim.sams[i].pos.x, 0.0, z - self.sim.sams[i].pos.z));
match centre {
None => ui.mode = Mode::Sector(id, Some(a)),
Some(c) => {
let half = sim_angle_diff(c, a).abs().clamp(10f64.to_radians(), std::f64::consts::PI);
self.edit_doctrine(i, |d| d.sector = Some((c, half)));
ui.mode = Mode::View;
}
}
}
_ => {
ui.sel = hit;
ui.follow = false;
}
}
}
/// Right button in the view: a mobile system selected drives to the point.
fn map_right(&mut self, ui: &mut MapUi, at: (f32, f32)) {
if let Some(i) = self.sel_sam(ui)
&& self.sim.sams[i].kind.mobile()
{
let (x, z) = ui.to_world(at);
match self.ground_y(x, z) {
Some(y) => {
if self.sim.order_move(i, DVec3::new(x, y, z)) {
let s = &self.sim.sams[i];
ui.note(self.sim.tick, format!("{} №{}: на марш, {}", s.kind.name(), i + 1, distance(s.pos.distance(DVec3::new(x, y, z)))));
}
}
None => ui.note(self.sim.tick, "Земля там не загружена: подождите и повторите"),
}
} else {
ui.sel = None;
ui.mode = Mode::View;
}
}
// ------------------------------------------------------------------ the editor
fn draft_pick(&self, ui: &MapUi, at: (f32, f32)) -> Option<EdSel> {
let near = |w: DVec3| {
let s = ui.to_screen(w.x, w.z);
(s.0 - at.0).hypot(s.1 - at.1) <= PICK_R
};
if let Some(i) = ui.draft.sams.iter().position(|s| !s.gone && near(s.pos)) {
return Some(EdSel::Sam(i));
}
ui.draft.objs.iter().position(|o| !o.gone && near(o.pos)).map(EdSel::Obj)
}
fn editor_press(&mut self, ui: &mut MapUi, at: (f32, f32)) {
self.ensure_draft(ui);
if let Some(hit) = self.draft_pick(ui, at) {
ui.push_history();
ui.ed_sel = Some(hit);
ui.drag = Some(match hit {
EdSel::Sam(i) => Drag::Sam(i),
EdSel::Obj(i) => Drag::Obj(i),
});
return;
}
let (x, z) = ui.to_world(at);
match ui.pick {
Pick::None => {
ui.ed_sel = None;
ui.drag = Some(Drag::Pan { from: at, centre: ui.centre, moved: false });
}
p => {
let Some(y) = self.ground_y(x, z) else {
ui.note(self.sim.tick, "Земля здесь не загружена: подождите секунду и нажмите снова");
return;
};
ui.push_history();
let pos = DVec3::new(x, y, z);
match p {
Pick::Sam(kind) => {
ui.draft.sams.push(DSam { id: None, kind, pos, heading: ui.heading, gone: false });
ui.ed_sel = Some(EdSel::Sam(ui.draft.sams.len() - 1));
}
Pick::Object => {
ui.draft.objs.push(DObj { idx: None, pos, gone: false });
ui.ed_sel = Some(EdSel::Obj(ui.draft.objs.len() - 1));
}
Pick::None => {}
}
}
}
}
fn editor_remove_at(&mut self, ui: &mut MapUi, at: (f32, f32)) {
if let Some(hit) = self.draft_pick(ui, at) {
ui.push_history();
match hit {
EdSel::Sam(i) => remove_dsam(&mut ui.draft, i),
EdSel::Obj(i) => remove_dobj(&mut ui.draft, i),
}
ui.ed_sel = None;
} else {
ui.pick = Pick::None;
}
}
/// Builds what the draft says: nothing before this, and nothing is spent until it.
fn commit_draft(&mut self, ui: &mut MapUi) {
let tick = self.sim.tick;
if !self.draft_changed(ui) {
ui.mode = Mode::View;
ui.draft = Draft::default();
return;
}
if self.battle() {
ui.note(tick, "Бой идёт: расстановка закрыта");
return;
}
let d = std::mem::take(&mut ui.draft);
// Objects: removals from the end so the indices hold.
let mut gone: Vec<usize> = d.objs.iter().filter(|o| o.gone).filter_map(|o| o.idx).collect();
gone.sort_unstable_by(|a, b| b.cmp(a));
for o in &d.objs {
if let (Some(i), false) = (o.idx, o.gone)
&& let Some(t) = self.sim.targets.get_mut(i)
{
*t = o.pos;
}
}
for i in gone {
if i < self.sim.targets.len() {
self.sim.targets.remove(i);
if i < self.sim.target_health.len() {
self.sim.target_health.remove(i);
}
}
}
for o in d.objs.iter().filter(|o| o.idx.is_none() && !o.gone) {
self.sim.targets.push(o.pos);
self.sim.target_health.push(100.0);
}
for s in &d.sams {
match (s.id, s.gone) {
(Some(id), true) => self.sim.sams.retain(|x| x.id != id),
(Some(id), false) => {
if let Some(i) = self.sim.sams.iter().position(|x| x.id == id) {
let moved = self.sim.sams[i].pos.distance(s.pos) > 0.01;
let sam = &mut self.sim.sams[i];
sam.heading = s.heading;
if moved {
// Before the battle a unit is simply put down elsewhere.
sam.pos = s.pos;
sam.dest = None;
}
}
}
(None, false) => {
let id = self.sim.id();
let mut sam = Sam::new(id, s.kind, s.pos, s.heading);
if let Some(r) = self.sim.roles.get(&s.kind) {
sam.roles = *r;
}
self.sim.sams.push(sam);
}
(None, true) => {}
}
}
self.dirty = true;
ui.mode = Mode::View;
ui.history.clear();
ui.pick = Pick::None;
ui.ed_sel = None;
ui.sel = None;
ui.note(tick, "Расстановка подтверждена");
}
// ------------------------------------------------------------------ drawing
fn map_shapes(&mut self, ui: &mut MapUi) -> Vec<Shape> {
let mut s: Vec<Shape> = Vec::with_capacity(2048);
ui.buttons.clear();
let (w, h) = ui.size;
let now = self.sim.tick;
let editing = ui.mode == Mode::Editor;
let cur_world = ui.to_world(ui.cursor);
// The ground under the pointer is asked for while placing, so that the click finds it.
if editing || ui.pick != Pick::None {
let _ = self.ground_y(cur_world.0, cur_world.1);
}
// Chunks round the view's middle are loaded now and then, so a place looked at fills in.
if now >= ui.chunks_at + 10 && ui.scale >= 0.2 {
ui.chunks_at = now;
let (cx, cz) = ((ui.centre.0.floor() as i32) >> 4, (ui.centre.1.floor() as i32) >> 4);
let wanted: Vec<(i32, i32)> = (-2..2).flat_map(|dz| (-2..2).map(move |dx| (cx + dx, cz + dz))).collect();
render::load_chunks(&wanted);
}
let draft = ui.draft.clone();
// Terrain.
if ui.filters[F_TERRAIN] {
self.map_terrain(ui, &mut s);
}
self.map_grid(ui, &mut s);
// What covers what (editor).
let armed: Vec<(SamKind, DVec3)> = if editing {
draft.sams.iter().filter(|d| !d.gone && d.kind.range() > 0.0).map(|d| (d.kind, d.pos)).collect()
} else {
self.sim.sams.iter().filter(|x| x.alive() && x.kind.range() > 0.0).map(|x| (x.kind, x.pos)).collect()
};
if editing {
let cell = 20.0f32;
let mut y = 0.0;
while y < h {
let mut x = 0.0;
while x < w {
let c = ui.to_world((x + cell / 2.0, y + cell / 2.0));
let p = DVec3::new(c.0, 0.0, c.1);
let n = armed.iter().filter(|(k, pos)| reaches(*k, *pos, p)).count();
if n > 0 {
s.push(fill(x, y, cell, cell, alpha(0x40FF60, if n == 1 { 0.10 } else { 0.18 })));
}
x += cell;
}
y += cell;
}
}
// Reach rings.
if ui.filters[F_RINGS] {
let list: Vec<(SamKind, DVec3, bool)> = if editing {
draft.sams.iter().filter(|d| !d.gone).map(|d| (d.kind, d.pos, d.id.is_none())).collect()
} else {
self.sim.sams.iter().filter(|x| x.alive()).map(|x| (x.kind, x.pos, false)).collect()
};
let many = list.len() > 12;
let picked = if editing { match ui.ed_sel { Some(EdSel::Sam(i)) => draft.sams.get(i).map(|d| d.pos), _ => None } } else { self.sel_pos(ui) };
for (kind, pos, ghost) in list {
let r = kind.range();
let chosen = picked.is_some_and(|p| p.distance(pos) < 1.0);
if r > 0.0 && (!many || chosen || ghost) {
let c = ui.to_screen(pos.x, pos.z);
ring(ui, &mut s, c, (r * ui.scale) as f32, 1.0, alpha(if ghost { 0xFFE070 } else { 0x40A0FF }, 0.75));
}
}
}
// The selected system's sensor, sector and guards.
if let Some(i) = self.sel_sam(ui) {
let sam = &self.sim.sams[i];
let c = ui.to_screen(sam.pos.x, sam.pos.z);
let sens = sam.kind.spec().sensor;
if sens > 0.0 {
ring(ui, &mut s, c, (sens * ui.scale) as f32, 1.0, alpha(0x80FF90, 0.45));
}
self.map_sector(ui, &mut s, sam.pos, &sam.doctrine, sam.kind.range().max(200.0));
for g in &sam.doctrine.guards {
let gp = ui.to_screen(g.x, g.z);
s.push(line(c, gp, 1.0, alpha(0xFFE070, 0.7)));
ring(ui, &mut s, gp, (sim::doctrine::GUARD_R * ui.scale) as f32, 1.0, alpha(0xFFE070, 0.6));
}
}
if let Mode::Sector(id, centre) = ui.mode
&& let Some(sam) = self.sim.sams.iter().find(|x| x.id == id)
{
let a = sim::heading_of(DVec3::new(cur_world.0 - sam.pos.x, 0.0, cur_world.1 - sam.pos.z));
let d = match centre {
None => Doctrine { sector: Some((a, 15f64.to_radians())), ..Default::default() },
Some(c) => Doctrine { sector: Some((c, sim_angle_diff(c, a).abs().clamp(10f64.to_radians(), std::f64::consts::PI))), ..Default::default() },
};
self.map_sector(ui, &mut s, sam.pos, &d, sam.kind.range().max(200.0));
}
// Flights of the strike missiles.
for f in &self.sim.strikes.flights {
let a = ui.to_screen(f.from.x, f.from.z);
let b = ui.to_screen(f.aim.x, f.aim.y);
s.push(line(a, b, 1.0, alpha(0xFFA040, 0.5)));
let k = ((now.saturating_sub(f.start)) as f64 / (f.arrive.saturating_sub(f.start)).max(1) as f64).clamp(0.0, 1.0) as f32;
s.push(diamond(a.0 + (b.0 - a.0) * k, a.1 + (b.1 - a.1) * k, 3.0, ORANGE));
}
// Objects.
if ui.filters[F_OBJECTS] {
let list: Vec<(usize, DVec3, bool)> = if editing {
draft.objs.iter().enumerate().filter(|(_, o)| !o.gone).map(|(i, o)| (i, o.pos, o.idx.is_none())).collect()
} else {
self.sim.targets.iter().enumerate().map(|(i, p)| (i, *p, false)).collect()
};
for (i, p, ghost) in list {
let c = ui.to_screen(p.x, p.z);
if !ui.on_screen(c, 20.0) {
continue;
}
let covered = armed.iter().any(|(k, pos)| reaches(*k, *pos, p));
let col = if !covered && (editing || !armed.is_empty()) { RED } else if ghost { YELLOW } else { WHITE };
s.push(fill(c.0 - 4.0, c.1 - 4.0, 8.0, 8.0, col));
s.push(fill(c.0 - 2.5, c.1 - 2.5, 5.0, 5.0, 0xFF101010));
if !editing {
let hp = self.sim.target_health.get(i).copied().unwrap_or(100.0);
s.push(text(format!("{}{}", i + 1, if hp < 100.0 { format!(" {hp:.0}%") } else { String::new() }), c.0 + 6.0, c.1 - 4.0, col));
} else if !covered {
s.push(text("не прикрыт", c.0 + 6.0, c.1 - 4.0, RED));
}
if ui.sel == Some(Sel::Object(i)) && !editing {
s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN));
}
}
}
// Systems.
if ui.filters[F_SAMS] {
let list: Vec<(Option<u32>, SamKind, DVec3, f64, bool, bool, usize)> = if editing {
draft.sams.iter().enumerate().filter(|(_, d)| !d.gone).map(|(i, d)| (d.id, d.kind, d.pos, d.heading, d.id.is_none(), true, i)).collect()
} else {
self.sim.sams.iter().map(|x| (Some(x.id), x.kind, x.pos, x.heading, false, x.alive(), 0)).collect()
};
for (id, kind, pos, heading, ghost, alive, di) in list {
let c = ui.to_screen(pos.x, pos.z);
if !ui.on_screen(c, 30.0) {
continue;
}
let col = if !alive {
0xFF704040
} else if ghost {
YELLOW
} else if kind.range() > 0.0 {
0xFF40A0FF
} else {
0xFF60D0A0
};
s.push(fill(c.0 - 4.0, c.1 - 4.0, 8.0, 8.0, col));
let (dx, dz) = dir_of(heading);
s.push(line(c, (c.0 + dx as f32 * 11.0, c.1 + dz as f32 * 11.0), 1.5, col));
if ui.scale > 0.12 && (self.sim.sams.len() <= 12 || ui.scale > 2.0) {
s.push(text(format!("{}", kind.name()), c.0 + 7.0, c.1 - 4.0, alpha(col, 0.95)));
}
let chosen = !editing && id.is_some() && ui.sel == id.map(Sel::Sam);
let ed = editing && ui.ed_sel == Some(EdSel::Sam(di));
if chosen || ed {
s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN));
}
}
}
// Launch sites the radars found.
if ui.filters[F_SITES] {
self.map_sites(ui, &mut s);
}
// Own interceptors.
for m in &self.sim.missiles {
let c = ui.to_screen(m.pos.x, m.pos.z);
if ui.on_screen(c, 4.0) {
s.push(fill(c.0 - 1.0, c.1 - 1.0, 2.0, 2.0, YELLOW));
}
}
// The network's tracks.
if ui.filters[F_TRACKS] || ui.filters[F_TRAILS] {
self.map_tracks(ui, &mut s);
}
// The truth, when the sandbox shows it, marked as such.
if self.sim.truth {
for d in &self.sim.drones {
let c = ui.to_screen(d.pos.x, d.pos.z);
if ui.on_screen(c, 4.0) {
s.extend(frame(c.0 - 3.0, c.1 - 3.0, 6.0, 6.0, 1.0, alpha(0xFF4040, 0.9)));
}
}
}
// The ghost under the pointer while placing.
if editing && let Some(y) = self.ground_y(cur_world.0, cur_world.1) {
let c = ui.cursor;
match ui.pick {
Pick::Sam(kind) => {
s.push(fill(c.0 - 4.0, c.1 - 4.0, 8.0, 8.0, alpha(0xFFE070, 0.6)));
let (dx, dz) = dir_of(ui.heading);
s.push(line(c, (c.0 + dx as f32 * 11.0, c.1 + dz as f32 * 11.0), 1.5, alpha(0xFFE070, 0.6)));
if kind.range() > 0.0 {
ring(ui, &mut s, c, (kind.range() * ui.scale) as f32, 1.0, alpha(0xFFE070, 0.55));
}
let _ = y;
}
Pick::Object => s.push(fill(c.0 - 4.0, c.1 - 4.0, 8.0, 8.0, alpha(0xFFE070, 0.6))),
Pick::None => {}
}
} else if editing && ui.pick != Pick::None {
s.push(text("земля не загружена", ui.cursor.0 + 8.0, ui.cursor.1 + 8.0, RED));
}
self.map_panels(ui, &mut s, &draft);
s.truncate(8000);
s
}
fn map_terrain(&mut self, ui: &MapUi, s: &mut Vec<Shape>) {
let (w, h) = ui.size;
let tl = ui.to_world((0.0, 0.0));
let br = ui.to_world((w, h));
let mut bpt = 1u32;
loop {
let span = 128.0 * bpt as f64;
let nx = ((br.0 - tl.0) / span).ceil() as i64 + 1;
let nz = ((br.1 - tl.1) / span).ceil() as i64 + 1;
if (nx * nz <= 20 && 128.0 * bpt as f64 * ui.scale >= 64.0) || bpt >= 64 {
break;
}
bpt *= 2;
}
let span = 128 * bpt as i32;
let (x0, z0) = ((tl.0.floor() as i32).div_euclid(span) * span, (tl.1.floor() as i32).div_euclid(span) * span);
let px = (span as f64 * ui.scale) as f32;
let mut z = z0;
let mut n = 0;
while (z as f64) < br.1 && n < 24 {
let mut x = x0;
while (x as f64) < br.0 && n < 24 {
let a = ui.to_screen(x as f64, z as f64);
s.push(Shape::Terrain(TerrainShape { rect: Rect { x: a.0, y: a.1, w: px, h: px }, x, z, blocks_per_texel: bpt }));
n += 1;
x += span;
}
z += span;
}
}
fn map_grid(&self, ui: &MapUi, s: &mut Vec<Shape>) {
let (w, h) = ui.size;
// A square of 1, 2, 5... x 10^n blocks that is at least 70 pixels wide.
let mut step = 10.0f64;
for m in [1.0, 2.0, 5.0].iter().cycle().zip(0..30).map(|(m, i)| m * 10f64.powi(1 + i / 3)) {
step = m;
if m * ui.scale >= 70.0 {
break;
}
}
let tl = ui.to_world((0.0, 0.0));
let br = ui.to_world((w, h));
let mut x = (tl.0 / step).floor() * step;
while x < br.0 {
let sx = ui.to_screen(x, 0.0).0;
s.push(fill(sx, 0.0, 1.0, h, 0x18FFFFFF));
x += step;
}
let mut z = (tl.1 / step).floor() * step;
while z < br.1 {
let sy = ui.to_screen(0.0, z).1;
s.push(fill(0.0, sy, w, 1.0, 0x18FFFFFF));
z += step;
}
// The scale bar.
let bar = (step * ui.scale) as f32;
s.push(fill(12.0, h - 16.0, bar, 2.0, WHITE));
s.push(fill(12.0, h - 20.0, 1.0, 6.0, WHITE));
s.push(fill(12.0 + bar, h - 20.0, 1.0, 6.0, WHITE));
s.push(text(distance(step), 14.0, h - 30.0, WHITE));
}
fn map_sector(&self, ui: &MapUi, s: &mut Vec<Shape>, pos: DVec3, d: &Doctrine, reach: f64) {
let Some((c, half)) = d.sector else { return };
let o = ui.to_screen(pos.x, pos.z);
let r = (reach * ui.scale) as f32;
let n = ((half * 2.0 / 0.15) as usize).clamp(4, 48);
let at = |a: f64| {
let (dx, dz) = dir_of(a);
(o.0 + dx as f32 * r, o.1 + dz as f32 * r)
};
let col = alpha(0xFFB040, 0.16);
for i in 0..n {
let a0 = c - half + half * 2.0 * i as f64 / n as f64;
let a1 = c - half + half * 2.0 * (i + 1) as f64 / n as f64;
s.push(Shape::Quad(QuadShape { corners: (pt(o.0, o.1), pt(at(a0).0, at(a0).1), pt(at(a1).0, at(a1).1), pt(o.0, o.1)), color: col }));
}
s.push(line(o, at(c - half), 1.0, alpha(0xFFB040, 0.8)));
s.push(line(o, at(c + half), 1.0, alpha(0xFFB040, 0.8)));
}
fn map_sites(&self, ui: &MapUi, s: &mut Vec<Shape>) {
let (w, h) = ui.size;
for k in &self.sim.strikes.known {
let Some(e) = k.est else { continue };
let gone = matches!(k.state, SiteState::Destroyed(_));
let col = if gone { 0xFF707070 } else { ORANGE };
let chosen = ui.sel == Some(Sel::Site(k.site));
if e.fix {
let c = ui.to_screen(e.pos.x, e.pos.y);
// The circle of error: the place is somewhere in it.
ring(ui, s, c, (e.radius * ui.scale) as f32, 1.0, alpha(col & 0xFFFFFF, 0.8));
if ui.on_screen(c, 20.0) {
s.push(diamond(c.0, c.1, 5.0, col));
s.push(diamond(c.0, c.1, 2.5, 0xFF101010));
s.push(text(format!("ПУ {}{}", k.site, if gone { " ×" } else { "" }), c.0 + 8.0, c.1 - 4.0, col));
if chosen {
s.extend(frame(c.0 - 9.0, c.1 - 9.0, 18.0, 18.0, 1.0, GREEN));
}
}
} else {
// Only a bearing: a ray from where it was seen.
let o = ui.to_screen(e.origin.x, e.origin.y);
let (dx, dz) = (e.bearing.sin(), -e.bearing.cos());
let len = (w.max(h) * 2.0) as f64;
let b = (o.0 + (dx * len) as f32, o.1 + (dz * len) as f32);
s.push(line(o, b, 1.0, alpha(0xFFA040, 0.35)));
// The ray's label where it crosses the screen's rim, near the origin when that is on the screen.
s.push(text(format!("ПУ {}: азимут {:.0}°", k.site, e.bearing.to_degrees()), (o.0 + dx as f32 * 40.0).clamp(4.0, w - 120.0), (o.1 + dz as f32 * 40.0).clamp(4.0, h - 10.0), alpha(0xFFA040, 0.9)));
}
}
}
fn map_tracks(&self, ui: &MapUi, s: &mut Vec<Shape>) {
let now = self.sim.tick;
let pic = self.sim.picture();
for (id, t) in &pic {
let chosen = ui.sel == Some(Sel::Track(*id));
if ui.filters[F_TRAILS]
&& let Some(trail) = ui.trails.get(id)
{
let col = alpha(0xFF6060, if chosen { 0.95 } else { 0.5 });
let mut prev: Option<(f32, f32)> = None;
for p in trail {
let c = ui.to_screen(p.0 as f64, p.1 as f64);
if let Some(a) = prev
&& (ui.on_screen(a, 0.0) || ui.on_screen(c, 0.0))
{
s.push(line(a, c, 1.0, col));
}
prev = Some(c);
}
}
if !ui.filters[F_TRACKS] {
continue;
}
let age = t.age(now);
let forecast = t.forecast(now);
let e = t.est(now);
let c = ui.to_screen(e.x, e.z);
let m = ui.to_screen(t.pos.x, t.pos.z);
// The last measurement and the forecast from it: dashes, never drawn as a certainty.
if forecast {
s.push(line(m, c, 1.0, alpha(0xFFB0B0, 0.4)));
let r = (t.uncertainty(now) * ui.scale) as f32;
ring(ui, s, c, r.min(300.0), 1.0, alpha(0xFFB0B0, 0.5));
}
if chosen {
// Ahead along the course for 30 s, dashed.
let v = t.vel;
let ahead = ui.to_screen(e.x + v.x * 600.0, e.z + v.z * 600.0);
dashed(s, c, ahead, alpha(0xFF8080, 0.8));
}
if ui.on_screen(c, 12.0) {
let col = if forecast { alpha(0xFFB0B0, 0.65) } else { 0xFFFF5050 };
s.push(diamond(c.0, c.1, 4.0, col));
if !forecast {
s.push(diamond(c.0, c.1, 2.0, 0xFF200808));
}
if chosen || ui.scale > 0.5 {
s.push(text(format!("{}{}", if forecast { "~" } else { "" }, if age < 20 { "сейчас".to_string() } else { format!("{} с", age / 20) }), c.0 + 7.0, c.1 - 4.0, col));
}
if chosen {
s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN));
}
}
}
}
// ------------------------------------------------------------------ the panels
fn map_panels(&mut self, ui: &mut MapUi, s: &mut Vec<Shape>, draft: &Draft) {
let (w, h) = ui.size;
let now = self.sim.tick;
let editing = ui.mode == Mode::Editor;
// The top bar: what the map shows, always said.
s.push(fill(0.0, 0.0, w, 14.0, PANEL));
let head = if self.sim.truth { "КАРТА · ИСТИНА (песочница): красные рамки — настоящие дроны" } else { "КАРТА · режим: данные сети РЛС" };
s.push(text(head, 6.0, 3.0, if self.sim.truth { YELLOW } else { GREEN }));
let cw = ui.to_world(ui.cursor);
let tail = format!("x {:.0} z {:.0}", cw.0, cw.1);
let tw = render::text_width(&tail);
s.push(text(tail, w - tw - 6.0, 3.0, GREY));
// The left panel: filters and keys.
let mut y = 20.0;
s.push(fill(4.0, y - 3.0, 112.0, 14.0 * (FILTERS.len() as f32 + 1.0) + 8.0, PANEL));
s.push(text("Слои (клавиши 1–7)", 8.0, y, GREY));
y += 14.0;
for (i, name) in FILTERS.iter().enumerate() {
let on = ui.filters[i];
let r = [6.0, y - 1.0, 108.0, 12.0];
if hovered(ui, r) {
s.push(fill(r[0], r[1], r[2], r[3], 0x30FFFFFF));
}
s.push(text(format!("{} {} {}", if on { "[x]" } else { "[ ]" }, i + 1, name), 9.0, y, if on { WHITE } else { GREY }));
ui.buttons.push(Btn { rect: r, act: Act::Filter(i) });
y += 14.0;
}
y += 8.0;
// The mode buttons.
let mut bx = 6.0;
let button = |s: &mut Vec<Shape>, ui: &mut MapUi, label: &str, act: Act, on: bool, x: f32, y: f32| -> f32 {
let bw = render::text_width(label) + 10.0;
let r = [x, y, bw, 14.0];
let hv = hovered(ui, r);
s.push(fill(r[0], r[1], r[2], r[3], if on { 0xE0306040 } else if hv { 0xE0304038 } else { 0xE0182420 }));
s.extend(frame(r[0], r[1], r[2], r[3], 1.0, if on { GREEN } else { 0x60FFFFFF }));
s.push(text(label, x + 5.0, y + 3.0, WHITE));
ui.buttons.push(Btn { rect: r, act });
bw + 4.0
};
bx += button(s, ui, "Правка (E)", Act::Editor, editing, bx, y);
bx += button(s, ui, "Игрок (C)", Act::Player, false, bx, y);
button(s, ui, "Выход (M)", Act::Close, false, bx, y);
// The keys.
let help = if editing {
"ЛКМ: ставить/переносить · ПКМ: убрать · R · Z · Enter · Esc"
} else {
"ЛКМ: выбор, тянуть: сдвиг · колесо: масштаб · ПКМ: марш · Esc"
};
let hw = render::text_width(help);
s.push(fill(w / 2.0 - hw / 2.0 - 6.0, h - 16.0, hw + 12.0, 14.0, PANEL));
s.push(text_c(help, w / 2.0, h - 13.0, GREY));
// The note.
if let Some((n, until)) = ui.note.clone() {
if now < until {
let nw = render::text_width(&n);
s.push(fill(w / 2.0 - nw / 2.0 - 8.0, 22.0, nw + 16.0, 16.0, 0xE0302010));
s.push(text_c(n, w / 2.0, 26.0, YELLOW));
} else {
ui.note = None;
}
}
// The right card.
let cx = w - CARD_W - 2.0;
let mut lines: Vec<(String, u32)> = Vec::new();
let mut btns: Vec<(String, Act, bool)> = Vec::new();
if editing {
self.editor_card(ui, draft, &mut lines, &mut btns);
} else {
self.sel_card(ui, &mut lines, &mut btns);
}
// Long lines break at the card's width.
let mut wrapped: Vec<(String, u32)> = Vec::new();
for (l, c) in lines {
let mut cur = String::new();
for word in l.split(' ') {
let try_ = if cur.is_empty() { word.to_string() } else { format!("{cur} {word}") };
if render::text_width(&try_) > CARD_W - 8.0 && !cur.is_empty() {
wrapped.push((std::mem::take(&mut cur), c));
cur = word.to_string();
} else {
cur = try_;
}
}
wrapped.push((cur, c));
}
let lines = wrapped;
if !lines.is_empty() || !btns.is_empty() {
let mut y = 18.0;
let ch = lines.len() as f32 * 11.0 + btns.len() as f32 * 0.0 + 10.0;
// Buttons go in rows that wrap.
let mut rows: Vec<Vec<(String, Act, bool, f32)>> = vec![Vec::new()];
let mut used = 0.0;
for (l, a, on) in btns {
let bw = render::text_width(&l) + 10.0;
if used + bw > CARD_W - 6.0 && !rows.last().unwrap().is_empty() {
rows.push(Vec::new());
used = 0.0;
}
rows.last_mut().unwrap().push((l, a, on, bw));
used += bw + 4.0;
}
let total = ch + rows.iter().filter(|r| !r.is_empty()).count() as f32 * 18.0 + 4.0;
s.push(fill(cx - 3.0, y - 3.0, CARD_W + 2.0, total, PANEL));
for (l, c) in &lines {
s.push(text(l.as_str(), cx, y, *c));
y += 11.0;
}
y += 6.0;
for row in rows {
let mut x = cx;
for (l, a, on, bw) in row {
let r = [x, y, bw, 14.0];
let hv = hovered(ui, r);
s.push(fill(r[0], r[1], r[2], r[3], if on { 0xE0306040 } else if hv { 0xE0304038 } else { 0xE0182420 }));
s.extend(frame(r[0], r[1], r[2], r[3], 1.0, if on { GREEN } else { 0x60FFFFFF }));
s.push(text(l.as_str(), x + 5.0, y + 3.0, WHITE));
ui.buttons.push(Btn { rect: r, act: a });
x += bw + 4.0;
}
y += 18.0;
}
}
// The editor's palette along the bottom.
if editing {
let mut kinds: Vec<(String, Pick)> = SamKind::ALL.iter().map(|k| (k.name().to_string(), Pick::Sam(*k))).collect();
kinds.push(("Объект".into(), Pick::Object));
// Rows first, so the palette sits just above the help line.
let mut rows = 1;
let mut used = 6.0;
for (label, _) in &kinds {
let bw = render::text_width(label) + 10.0;
if used + bw > w - 4.0 {
rows += 1;
used = 6.0;
}
used += bw + 4.0;
}
let mut x = 6.0;
let mut y = h - 18.0 - rows as f32 * 16.0;
s.push(fill(0.0, y - 3.0, w, rows as f32 * 16.0 + 4.0, PANEL));
for (label, pick) in kinds {
let bw = render::text_width(&label) + 10.0;
if x + bw > w - 4.0 {
x = 6.0;
y += 16.0;
}
let on = ui.pick == pick;
let r = [x, y, bw, 14.0];
let hv = hovered(ui, r);
s.push(fill(r[0], r[1], r[2], r[3], if on { 0xE0806020 } else if hv { 0xE0304038 } else { 0xE0182420 }));
s.extend(frame(r[0], r[1], r[2], r[3], 1.0, if on { YELLOW } else { 0x60FFFFFF }));
s.push(text(label, x + 5.0, y + 3.0, WHITE));
ui.buttons.push(Btn { rect: r, act: Act::Pick(pick) });
x += bw + 4.0;
}
}
}
fn editor_card(&self, ui: &MapUi, d: &Draft, lines: &mut Vec<(String, u32)>, btns: &mut Vec<(String, Act, bool)>) {
lines.push(("РАССТАНОВКА ДО БОЯ".into(), YELLOW));
lines.push(("Пока не подтвердите, ничего не строится.".into(), GREY));
let new_s = d.sams.iter().filter(|s| s.id.is_none() && !s.gone).count();
let gone_s = d.sams.iter().filter(|s| s.id.is_some() && s.gone).count();
let new_o = d.objs.iter().filter(|o| o.idx.is_none() && !o.gone).count();
let gone_o = d.objs.iter().filter(|o| o.idx.is_some() && o.gone).count();
lines.push((format!("Новых: комплексов {new_s}, объектов {new_o}"), WHITE));
lines.push((format!("Убрать: комплексов {gone_s}, объектов {gone_o}"), WHITE));
if self.draft_changed(ui) {
lines.push(("Есть неподтверждённые изменения".into(), ORANGE));
}
// The gaps: objects no system reaches.
let bare = d
.objs
.iter()
.filter(|o| !o.gone)
.filter(|o| !d.sams.iter().any(|s| !s.gone && reaches(s.kind, s.pos, o.pos)))
.count();
lines.push((if bare == 0 { "Все объекты в зоне поражения".into() } else { format!("Без прикрытия: объектов {bare} (красные)") }, if bare == 0 { GREEN } else { RED }));
lines.push(("Зелёное: зона огня, тёмное: дыра".into(), GREY));
match ui.pick {
Pick::Sam(k) => lines.push((format!("В руке: {}, дальность {}", k.name(), distance(k.range())), YELLOW)),
Pick::Object => lines.push(("В руке: объект (его будут защищать)".into(), YELLOW)),
Pick::None => lines.push(("Выберите тип внизу".into(), GREY)),
}
btns.push(("Готово (Enter)".into(), Act::Confirm, false));
btns.push(("Отмена".into(), Act::Cancel, false));
btns.push(("Назад (Z)".into(), Act::Undo, false));
btns.push(("Поворот (R)".into(), Act::Rotate, false));
btns.push(("Убрать (Del)".into(), Act::Delete, false));
}
fn sel_card(&self, ui: &MapUi, lines: &mut Vec<(String, u32)>, btns: &mut Vec<(String, Act, bool)>) {
let now = self.sim.tick;
match ui.sel {
Some(Sel::Sam(id)) => {
let Some((n, sam)) = self.sim.sams.iter().enumerate().find(|(_, s)| s.id == id) else { return };
let k = sam.kind;
lines.push((format!("{} №{}", k.name(), n + 1), CYAN));
lines.push((sam.status(), WHITE));
lines.push((format!("Исправен {:.0}% · {:.0} {:.0}", sam.health * 100.0, sam.pos.x, sam.pos.z), GREY));
if k.armed() {
lines.push((format!("Боезапас: {} ракет, {} очередей{}", sam.missiles, sam.bursts, if sam.reloading > 0 { format!(" · перезарядка {} с", sam.reloading / 20) } else { String::new() }), WHITE));
lines.push((format!("Дальность огня: {}", distance(k.range())), WHITE));
}
if k.spec().sensor > 0.0 {
lines.push((format!("Свой обзор: {} (зелёное кольцо)", distance(k.spec().sensor)), WHITE));
}
if let Some(t) = sam.gun_target.or(sam.target) {
lines.push((format!("Ведёт цель: трек №{t}"), YELLOW));
}
if k.armed() {
lines.push(("Роли (кнопки): Д дроны, Г реактивные, К крылатые, С сверхзвук, Б баллистика".into(), GREY));
lines.push((format!("Доктрина: {}", sam.doctrine.text(&self.sim.targets)), WHITE));
for c in Class::ALL {
btns.push((c.letter().to_string(), Act::Role(c.bit()), sam.roles & c.bit() != 0));
}
btns.push(("Охрана".into(), Act::Guard, matches!(ui.mode, Mode::Guard(i) if i == id)));
btns.push(("Сектор".into(), Act::Sector, matches!(ui.mode, Mode::Sector(i, _) if i == id)));
btns.push(("Без сектора".into(), Act::SectorOff, false));
btns.push((format!("Резерв {}", sam.doctrine.reserve), Act::Reserve, false));
btns.push((format!("Залп: {}", sam.doctrine.salvo.name()), Act::Salvo, false));
btns.push(("Сброс".into(), Act::ResetDoc, false));
match ui.mode {
Mode::Guard(_) => lines.push(("Нажимайте объекты на карте: охранять / не охранять. Esc — готово.".into(), YELLOW)),
Mode::Sector(_, None) => lines.push(("Сектор: щёлкните в сторону центра сектора.".into(), YELLOW)),
Mode::Sector(_, Some(_)) => lines.push(("Сектор: щёлкните, чтобы задать ширину.".into(), YELLOW)),
_ => {}
}
}
if k.mobile() {
lines.push(("ПКМ по земле — отправить на марш".into(), GREY));
}
}
Some(Sel::Object(i)) => {
let Some(p) = self.sim.targets.get(i) else { return };
lines.push((format!("Объект №{}", i + 1), WHITE));
lines.push((format!("Прочность: {:.0}% {:.0} {:.0}", self.sim.target_health.get(i).copied().unwrap_or(100.0), p.x, p.z), GREY));
let cover: Vec<String> = self.sim.sams.iter().filter(|s| s.alive() && reaches(s.kind, s.pos, *p)).map(|s| s.kind.name().to_string()).collect();
if cover.is_empty() {
lines.push(("НЕ ПРИКРЫТ: ни один комплекс не достаёт".into(), RED));
} else {
lines.push((format!("Прикрыт: {}", cover.join(", ")), GREEN));
}
let guards = self.sim.sams.iter().filter(|s| s.doctrine.guards.iter().any(|g| g.distance(*p) < 16.0)).count();
if guards > 0 {
lines.push((format!("Охраняют по доктрине: {guards}"), WHITE));
}
}
Some(Sel::Site(id)) => {
let Some(k) = self.sim.strikes.get(id) else { return };
lines.push((format!("Пусковая №{id}: {}", class_name(k.class)), ORANGE));
match (&k.est, k.state) {
(Some(e), st) => {
if e.fix {
lines.push((format!("Место известно: {:.0} {:.0} ± {}", e.pos.x, e.pos.y, distance(e.radius)), WHITE));
} else {
lines.push((format!("Места не знаем, только азимут {:.0}°", e.bearing.to_degrees()), YELLOW));
}
lines.push((format!("Точность: {}", sim::strike::accuracy(e)), WHITE));
lines.push((
match st {
SiteState::Active => "Состояние: действует".to_string(),
SiteState::Stunned(t) => format!("Состояние: подавлена ещё {} с", t.saturating_sub(now) / 20),
SiteState::Destroyed(_) => "Состояние: уничтожена".to_string(),
},
WHITE,
));
}
(None, _) => lines.push(("Данных нет".into(), GREY)),
}
lines.push((format!("Пусков замечено: {}; последний {} с назад", k.launches, now.saturating_sub(k.last) / 20), GREY));
lines.push((format!("Ударных ракет: {}", self.sim.strikes.stock), WHITE));
if k.aimed {
lines.push(("Ракета по ней уже в полёте".into(), YELLOW));
}
if k.est.is_some_and(|e| e.fix) && !matches!(k.state, SiteState::Destroyed(_)) {
btns.push(("Ударить по пусковой".into(), Act::Strike(id), false));
}
btns.push(("В центр".into(), Act::Centre, false));
}
Some(Sel::Track(id)) => {
let pic = self.sim.picture();
let Some(t) = pic.get(&id) else {
lines.push((format!("Трек №{id}: потерян сетью"), GREY));
return;
};
lines.push((format!("Трек сети №{id}"), 0xFFFF8080));
lines.push((format!("Опознание: {}", t.ident().name()), WHITE));
let age = t.age(now);
lines.push((
if t.forecast(now) { format!("ПРОГНОЗ: последнее измерение {} с назад", age / 20) } else { format!("Измерение {} с назад", age / 20) },
if t.forecast(now) { YELLOW } else { GREEN },
));
lines.push((format!("Высота {:.0} м, скорость {:.0} км/ч", t.pos.y, t.vel.length() * 20.0 * 3.6), WHITE));
lines.push((format!("Погрешность места до {}", distance(t.uncertainty(now))), GREY));
lines.push(("Цель и маршрут неизвестны сети: тонкая линия —".into(), GREY));
lines.push(("пройденное по измерениям, пунктир — прогноз курса.".into(), GREY));
if let Some(trail) = ui.trails.get(&id) {
lines.push((format!("Точек измерений: {}", trail.len()), GREY));
}
let who = self.who_tracks(t);
if !who.is_empty() {
lines.push((format!("Держат: {who}"), WHITE));
}
btns.push(("В центр".into(), Act::Centre, false));
btns.push(("Следить (F)".into(), Act::Follow, ui.follow));
}
None => {
let live = self.sim.strikes.known.iter().filter(|k| !matches!(k.state, SiteState::Destroyed(_))).count();
lines.push(("Ничего не выбрано".into(), GREY));
lines.push((format!("Комплексов: {} · объектов: {}", self.sim.sams.len(), self.sim.targets.len()), WHITE));
lines.push((format!("Целей у сети: {} · известных ПУ: {live}", self.sim.picture().len()), WHITE));
if self.battle() {
lines.push(("Идёт налёт: расстановка закрыта".into(), YELLOW));
}
}
}
}
/// The systems whose tracks hold this one, by name (the network's own bookkeeping, not the drone's).
fn who_tracks(&self, t: &Track) -> String {
let n = self.sim.sams.iter().filter(|s| s.tracks.iter().any(|x| x.id == t.id)).count();
if n == 0 { String::new() } else { format!("{n} комплексов") }
}
}
fn remove_dsam(d: &mut Draft, i: usize) {
if let Some(s) = d.sams.get_mut(i) {
if s.id.is_some() {
s.gone = true;
} else {
d.sams.remove(i);
}
}
}
fn remove_dobj(d: &mut Draft, i: usize) {
if let Some(o) = d.objs.get_mut(i) {
if o.idx.is_some() {
o.gone = true;
} else {
d.objs.remove(i);
}
}
}
fn sim_angle_diff(from: f64, to: f64) -> f64 {
(to - from + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI
}
fn hovered(ui: &MapUi, r: [f32; 4]) -> bool {
ui.cursor.0 >= r[0] && ui.cursor.0 <= r[0] + r[2] && ui.cursor.1 >= r[1] && ui.cursor.1 <= r[1] + r[3]
}
/// A circle of `r` pixels round `c`, only the parts on the screen.
fn ring(ui: &MapUi, s: &mut Vec<Shape>, c: (f32, f32), r: f32, w: f32, color: u32) {
if !r.is_finite() || r < 2.0 {
return;
}
// Wholly off the screen: the nearest the circle comes is |distance to the middle - r|.
let mid = (ui.size.0 / 2.0, ui.size.1 / 2.0);
let far = (c.0 - mid.0).hypot(c.1 - mid.1);
let reach = mid.0.hypot(mid.1);
if far - r > reach || r - far > reach {
return;
}
let n = ((r / 5.0) as usize).clamp(16, 120);
let mut prev = (c.0, c.1 - r);
for i in 1..=n {
let a = i as f32 / n as f32 * TAU;
let p = (c.0 + a.sin() * r, c.1 - a.cos() * r);
if ui.on_screen(p, 40.0) || ui.on_screen(prev, 40.0) {
s.push(line(prev, p, w, color));
}
prev = p;
}
}
fn dashed(s: &mut Vec<Shape>, a: (f32, f32), b: (f32, f32), color: u32) {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let len = dx.hypot(dy);
let n = ((len / 8.0) as usize).min(200);
for i in (0..n).step_by(2) {
let (t0, t1) = (i as f32 / n as f32, (i + 1) as f32 / n as f32);
s.push(line((a.0 + dx * t0, a.1 + dy * t0), (a.0 + dx * t1, a.1 + dy * t1), 1.0, color));
}
}