Files
airdef/airdef-mod/src/sim/route.rs
T
chexit 7612d15963
build / mod (push) Successful in 30m46s
Finish AirDef catalog, route, stock and observation fixes
Refs #91, #114, #118, #135. Show the latest recorded unit decision in the native card (#153).
2026-12-02 18:22:22 +03:00

1018 lines
41 KiB
Rust

//! Ground routes for the vehicles (#94): a march is no longer a straight line through the relief. A bounded
//! A* over a coarse grid of the land the game has told of finds a way that avoids cliffs, water and walls; it
//! is worked on a few hundred cells a tick, shared by all the vehicles, and it keeps its state between ticks.
//! Land the game has not answered yet is waited for (the search parks those edges and goes on elsewhere), and
//! after a while the vehicle goes as far as the known land; a place nobody can reach is refused with a reason.
//! While driving, the column ahead is checked once more (a wall the grid missed, a drop): the cell is marked bad
//! and the way is searched again.
use super::*;
use std::collections::{BinaryHeap, HashSet};
/// Cells opened a tick, all vehicles together.
pub(super) const WORK_PER_TICK: usize = 600;
/// Cells opened for one route before it settles for the nearest it got.
const MAX_NODES: usize = 24_000;
/// Ticks the search waits for land the game has not told of, before the vehicle goes as far as is known.
const WAIT_MAP: u64 = 300;
/// Ticks a driver waits for the column ahead.
const WAIT_AHEAD: u32 = 200;
/// Searches again, after a way was found blocked on the march, before giving up.
const REPLANS: u32 = 16;
/// The tallest step a vehicle climbs between two columns, and the deepest drop it takes.
pub(super) const STEP_UP: f64 = 1.5;
pub(super) const STEP_DOWN: f64 = 3.5;
/// Ticks a truck keeps away from a job it found unreachable.
pub(super) const UNREACHABLE_FOR: u64 = 3600;
/// Why a vehicle waits or stops.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Why {
/// Waiting for the game's answers about the land.
Map,
/// The place itself can't be driven to (cliff, water, wall).
Goal,
/// No way there over the known land.
NoWay,
/// The way was found blocked on the march, again and again.
Stuck,
/// The map did not come.
NoMap,
/// It drove as far as the land is known.
Partial,
}
impl Why {
pub fn text(self) -> &'static str {
match self {
Why::Map => "ждёт карту местности",
Why::Goal => "туда не проехать: обрыв, вода или стена в точке назначения",
Why::NoWay => "прохода нет: путь перекрыт обрывами, водой или стенами",
Why::Stuck => "путь перекрыт на марше, объезда нет",
Why::NoMap => "карта местности не пришла, остался на месте",
Why::Partial => "дальше карта неизвестна: остановился на краю известного",
}
}
}
/// What the route says a vehicle does this tick.
pub(super) enum Drive {
/// Stand: for the land, or the planner.
Wait(Why),
/// Drive at this point; whether it is the last, and the route ends short of the order.
Go(DVec3, bool),
/// Stop here, and say why.
Fail(Why),
}
/// Result of checking the vehicle's clearance at its next position.
pub(super) enum Clearance {
Clear(f64),
Blocked,
Pending,
}
/// Conservative chassis envelope. The circular footprint is the circumscribed plan-view of the
/// folded vehicle; it makes turns safe without adding heading to the bounded A* state.
#[derive(Clone, Copy)]
struct Chassis {
radius: f64,
height: f64,
}
impl Chassis {
fn for_kind(kind: SamKind) -> Self {
let (radius, height): (f64, f64) = match kind.spec().family {
Family::Trainable => (2.25, 3.0),
Family::Gun => (1.75, 3.0),
Family::Turret => (2.0, 3.25),
Family::Vertical => (2.75, 3.5),
Family::Static => (2.0, 3.0),
Family::Truck => (1.75, 2.75),
Family::Light => (1.25, 2.5),
};
// Rendered geometry may extend past the nominal family envelope (rotated wheels too).
// Read the generated bounds of the exact body rather than letting art silently shrink clearance.
let (radius, height) = match super::generated_bounds::bounds(kind.spec().parts.body) {
Some((lo, hi)) => {
let scale = kind.spec().scale / 16.0;
let half_x = (lo[0] - 8.0).abs().max((hi[0] - 8.0).abs()) * scale;
let half_z = (lo[2] - 8.0).abs().max((hi[2] - 8.0).abs()) * scale;
(radius.max(half_x.hypot(half_z) + 0.125), height.max(hi[1] * scale))
}
None => (radius, height), // Content validation rejects missing models before packaging.
};
Self { radius, height }
}
/// Every voxel whose square intersects the conservative footprint, including grazing corners.
fn samples(self, pos: DVec3) -> impl Iterator<Item = (i32, i32)> {
let min_x = (pos.x - self.radius).floor() as i32;
let max_x = (pos.x + self.radius).floor() as i32;
let min_z = (pos.z - self.radius).floor() as i32;
let max_z = (pos.z + self.radius).floor() as i32;
(min_x..=max_x).flat_map(move |x| (min_z..=max_z).filter_map(move |z| {
let dx = (f64::from(x) - pos.x).max(pos.x - (f64::from(x) + 1.0)).max(0.0);
let dz = (f64::from(z) - pos.z).max(pos.z - (f64::from(z) + 1.0)).max(0.0);
(dx * dx + dz * dz <= self.radius * self.radius).then_some((x, z))
}))
}
}
#[derive(Clone, Copy)]
struct Info {
h: f32,
}
enum Eval {
Ok(f32),
Bad,
Pending,
}
/// Look below the reachable ceiling rather than lifting a vehicle onto an overhang.
/// The heightmap still distinguishes exposed water from dry solid surfaces.
fn support(ground: &mut Ground, x: i32, z: i32, near: f64, up: f64, down: f64, now: u64) -> Eval {
let column = ground.column(x, z, 1024);
if ground.known.get(&(x, z)).is_some_and(|&(_, tick)| tick == STALE) {
return Eval::Pending;
}
let top = match column {
None => return Eval::Pending,
Some(None) => return Eval::Bad,
Some(Some(top)) => top,
};
let low = (near - down).ceil() as i32 - 1;
let high = (near + up).floor() as i32 - 1;
let top = top as i32 - 1;
if top < low {
return Eval::Bad;
}
let mut section = None;
match ground.world.road_block(&mut section, x, top, z, now) {
None => return Eval::Pending,
// The motion-blocking map includes the surface of an open body of water.
Some(Some(true)) => {}
Some(_) => return Eval::Bad,
}
if top <= high {
return Eval::Ok((top + 1) as f32);
}
for y in (low..=high).rev() {
match ground.world.road_block(&mut section, x, y, z, now) {
Some(Some(true)) => return Eval::Ok((y + 1) as f32),
Some(Some(false)) => {}
None => return Eval::Pending,
Some(None) => return Eval::Bad,
}
}
Eval::Bad
}
#[derive(PartialEq)]
struct Open(f32, (i32, i32));
impl Eq for Open {}
impl Ord for Open {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
other.0.total_cmp(&self.0)
}
}
impl PartialOrd for Open {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
#[derive(PartialEq)]
enum Phase {
Search,
Follow,
}
/// One vehicle's way to its destination.
pub(super) struct Route {
dest: DVec3,
/// How near the destination counts (a truck stops beside its job); 0: the place itself.
slack: f64,
cell: i32,
slope: f64,
chassis: Chassis,
start: (i32, i32),
lo: (i32, i32),
hi: (i32, i32),
cells: HashMap<(i32, i32), Info>,
bad: HashSet<(i32, i32)>,
g: HashMap<(i32, i32), f32>,
came: HashMap<(i32, i32), (i32, i32)>,
open: BinaryHeap<Open>,
/// Edges waiting for a cell the game has not answered.
parked: Vec<((i32, i32), (i32, i32))>,
retry_at: u64,
stuck_since: Option<u64>,
/// The cell opened that is nearest the destination.
near: ((i32, i32), f64),
expanded: usize,
goal_checked: bool,
truck: bool,
work_approach: bool,
work_wait: u32,
works: u8,
phase: Phase,
pts: Vec<DVec3>,
next: usize,
pub(super) partial: bool,
replans: u32,
ahead_wait: u32,
began: u64,
pub(super) told: bool,
failed: Option<Why>,
}
impl Route {
pub(super) fn new(pos: DVec3, dest: DVec3, slack: f64, kind: SamKind, now: u64) -> Self {
let dist = horizontal(dest - pos).length();
let cell = if dist <= 400.0 { 4 } else if dist <= 900.0 { 6 } else { 8 };
let mut r = Self {
dest,
slack,
cell,
slope: kind.climbs(),
chassis: Chassis::for_kind(kind),
start: (0, 0),
lo: (0, 0),
hi: (0, 0),
cells: HashMap::new(),
bad: HashSet::new(),
g: HashMap::new(),
came: HashMap::new(),
open: BinaryHeap::new(),
parked: Vec::new(),
retry_at: 0,
stuck_since: None,
near: ((0, 0), f64::MAX),
expanded: 0,
goal_checked: slack > 0.0,
truck: kind == SamKind::Tzm && slack > 0.0,
work_approach: false,
work_wait: 0,
works: 0,
phase: Phase::Search,
pts: Vec::new(),
next: 0,
partial: false,
replans: 0,
ahead_wait: 0,
began: now,
told: false,
failed: None,
};
r.restart(pos);
r
}
fn cell_of(&self, p: DVec3) -> (i32, i32) {
((p.x.floor() as i32).div_euclid(self.cell), (p.z.floor() as i32).div_euclid(self.cell))
}
fn centre(&self, c: (i32, i32)) -> DVec3 {
let k = f64::from(self.cell);
DVec3::new((f64::from(c.0) + 0.5) * k, 0.0, (f64::from(c.1) + 0.5) * k)
}
fn to_goal(&self, c: (i32, i32)) -> f64 {
horizontal(self.centre(c) - self.dest).length()
}
fn is_goal(&self, c: (i32, i32)) -> bool {
if self.slack == 0.0 {
return c == self.cell_of(self.dest);
}
let Some(info) = self.cells.get(&c) else { return false };
let p = self.centre(c);
DVec3::new(p.x, f64::from(info.h), p.z).distance(self.dest) <= self.slack
}
/// Searches afresh from `pos`, keeping the cells found bad.
fn restart(&mut self, pos: DVec3) {
self.start = self.cell_of(pos);
let goal = self.cell_of(self.dest);
let margin = (((self.start.0 - goal.0).abs().max((self.start.1 - goal.1).abs()) / 2).max(16)).min(64);
self.lo = (self.start.0.min(goal.0) - margin, self.start.1.min(goal.1) - margin);
self.hi = (self.start.0.max(goal.0) + margin, self.start.1.max(goal.1) + margin);
self.g.clear();
self.cells.clear();
self.came.clear();
self.open.clear();
self.parked.clear();
self.pts.clear();
self.next = 0;
self.phase = Phase::Search;
self.stuck_since = None;
self.expanded = 0;
self.near = (self.start, f64::MAX);
self.partial = false;
self.work_approach = false;
self.work_wait = 0;
self.cells.insert(self.start, Info { h: pos.y as f32 });
self.g.insert(self.start, 0.0);
let h = self.heur(self.start);
self.open.push(Open(h, self.start));
}
fn heur(&self, c: (i32, i32)) -> f32 {
(self.to_goal(c) * 1.1) as f32
}
fn eval(&mut self, ground: &mut Ground, now: u64, c: (i32, i32), near: f64, climb: f64) -> Eval {
if let Some(i) = self.cells.get(&c) {
return Eval::Ok(i.h);
}
if self.bad.contains(&c) {
return Eval::Bad;
}
let verdict = self.road_at(ground, self.centre(c).with_y(near), climb, climb.max(STEP_DOWN), now);
if let Eval::Ok(h) = verdict {
self.cells.insert(c, Info { h });
}
verdict
}
/// Check support and headroom for the complete folded chassis. Unknown or just changed voxels
/// remain pending so neither search nor motion assumes they are open.
fn road_at(&self, ground: &mut Ground, pos: DVec3, climb: f64, drop: f64, now: u64) -> Eval {
let (cx, cz) = (pos.x.floor() as i32, pos.z.floor() as i32);
let base = match support(ground, cx, cz, pos.y, climb, drop, now) {
Eval::Ok(h) => f64::from(h),
other => return other,
};
let up = if self.truck { 2.0 } else { STEP_UP };
let mut pending = false;
for (x, z) in self.chassis.samples(pos) {
let h = if x == cx && z == cz {
base
} else {
match support(ground, x, z, base, up, STEP_DOWN, now) {
Eval::Ok(h) => f64::from(h),
Eval::Pending => { pending = true; continue; }
Eval::Bad => return Eval::Bad,
}
};
let mut section = None;
let top = h.max(base);
for y in top as i32..(top + self.chassis.height).ceil() as i32 {
match ground.world.road_block(&mut section, x, y, z, now) {
Some(Some(false)) => {}
None => { pending = true; break; }
Some(_) => return Eval::Bad,
}
}
}
if pending { Eval::Pending } else { Eval::Ok(base as f32) }
}
/// Recheck the envelope at the live position, since obstacles may change after planning.
pub(super) fn clearance(&self, ground: &mut Ground, pos: DVec3, now: u64) -> Clearance {
match self.road_at(ground, pos, STEP_UP, STEP_DOWN, now) {
Eval::Ok(h) => Clearance::Clear(f64::from(h)),
Eval::Bad => Clearance::Blocked,
Eval::Pending => Clearance::Pending,
}
}
/// Relaxes the edge from the opened cell `c` to `nb`; parks it when the land between isn't known yet.
fn relax(&mut self, ground: &mut Ground, now: u64, c: (i32, i32), nb: (i32, i32)) {
if nb.0 < self.lo.0 || nb.1 < self.lo.1 || nb.0 > self.hi.0 || nb.1 > self.hi.1 {
return;
}
let (di, dj) = (nb.0 - c.0, nb.1 - c.1);
let len = if di != 0 && dj != 0 { std::f64::consts::SQRT_2 } else { 1.0 };
let dist = len * f64::from(self.cell);
let slope = self.slope;
let allow = |l: f64| (slope * l).max(STEP_UP);
let Some(h0) = self.cells.get(&c).map(|i| f64::from(i.h)) else { return };
let h1 = match self.eval(ground, now, nb, h0, allow(dist)) {
Eval::Ok(h) => f64::from(h),
Eval::Bad => return,
Eval::Pending => return self.park(c, nb),
};
// A diagonal doesn't cut a corner of something in the way.
if di != 0 && dj != 0 {
for side in [(c.0 + di, c.1), (c.0, c.1 + dj)] {
match self.eval(ground, now, side, h0, allow(f64::from(self.cell))) {
Eval::Ok(h) if (f64::from(h) - h0).abs() <= (self.slope * f64::from(self.cell)).max(STEP_UP) => {}
Eval::Pending => return self.park(c, nb),
_ => return,
}
}
}
// Between the centres: a wall one block thick or a ditch there is what the centres don't show.
let (a, b) = (self.centre(c), self.centre(nb));
let mid = (a + b) * 0.5;
let half = dist * 0.5;
let hm = match self.road_at(ground, mid.with_y(h0), allow(half), STEP_DOWN, now) {
Eval::Pending => return self.park(c, nb),
Eval::Bad => return,
Eval::Ok(h) => f64::from(h),
};
if (hm - h0).abs() > allow(half) || (h1 - hm).abs() > allow(half) || hm - h0 < -STEP_DOWN * (half / 2.0).max(1.0) {
return;
}
let dh = (h1 - h0).abs();
if dh > allow(dist) {
return;
}
let cost = (dist + 2.0 * dh) as f32;
let ng = self.g.get(&c).copied().unwrap_or(0.0) + cost;
if self.g.get(&nb).is_none_or(|&g| ng < g) {
self.g.insert(nb, ng);
self.came.insert(nb, c);
self.open.push(Open(ng + self.heur(nb), nb));
}
}
fn park(&mut self, c: (i32, i32), nb: (i32, i32)) {
if self.parked.len() < 4096 {
self.parked.push((c, nb));
}
}
/// Works on the search: at most `budget` cells.
fn search(&mut self, ground: &mut Ground, now: u64, mut budget: usize) {
if !self.goal_checked {
let x = self.dest.x.floor() as i32;
let z = self.dest.z.floor() as i32;
let goal = match ground.column(x, z, 1024) {
// Orders made while flying above an exposed road still mean the ground below.
Some(Some(top)) => self.road_at(ground, self.dest.with_y(self.dest.y.min(top)), STEP_UP, STEP_DOWN, now),
Some(None) => Eval::Bad,
None => Eval::Pending,
};
match goal {
Eval::Bad => {
self.failed = Some(Why::Goal);
return;
}
Eval::Ok(_) => self.goal_checked = true,
Eval::Pending => {}
}
}
if now >= self.retry_at && !self.parked.is_empty() {
self.retry_at = now + 1;
let parked = std::mem::take(&mut self.parked);
for (k, &(c, nb)) in parked.iter().enumerate() {
// The game loads the chunk of the first few, if it loads on request.
if k < 6 {
let p = self.centre(nb);
ground.want_chunk(((p.x.floor() as i32) >> 4, (p.z.floor() as i32) >> 4));
}
self.relax(ground, now, c, nb);
}
}
let before = self.expanded;
while budget > 0 {
let Some(Open(f, c)) = self.open.pop() else { break };
let g = self.g.get(&c).copied().unwrap_or(f32::INFINITY);
if f > g + self.heur(c) + 1e-3 {
continue;
}
budget -= 1;
self.expanded += 1;
if self.is_goal(c) {
self.finish(c, false);
return;
}
let d = self.to_goal(c);
if d < self.near.1 {
self.near = (c, d);
}
for (di, dj) in [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)] {
self.relax(ground, now, c, (c.0 + di, c.1 + dj));
}
// Let pending footprint queries settle before opening a broad, less useful frontier.
// Otherwise three trucks can saturate the shared world budget without ever moving.
if self.expanded >= MAX_NODES {
self.settle(now);
return;
}
if !self.parked.is_empty() { break; }
}
if self.expanded > before {
self.stuck_since = None;
}
if self.open.is_empty() {
if self.parked.is_empty() {
self.failed = Some(Why::NoWay);
} else {
let since = *self.stuck_since.get_or_insert(now);
if now.saturating_sub(since) > WAIT_MAP {
self.settle(now);
}
}
} else {
self.stuck_since = None;
}
}
/// The land stays unknown (or the search is too big): the way to the nearest cell it got to.
fn settle(&mut self, _now: u64) {
let (c, d) = self.near;
let here = self.to_goal(self.start);
if c == self.start || here - d < f64::from(self.cell) * 2.0 {
self.failed = Some(Why::NoMap);
} else {
self.finish(c, true);
}
}
/// The way to cell `c`, as points with the straight stretches dropped.
fn finish(&mut self, c: (i32, i32), partial: bool) {
let mut cells = vec![c];
let mut k = c;
while let Some(&p) = self.came.get(&k) {
cells.push(p);
k = p;
if cells.len() > 100_000 {
break;
}
}
cells.reverse();
let mut pts: Vec<DVec3> = Vec::new();
for w in 1..cells.len() {
let dir = (cells[w].0 - cells[w - 1].0, cells[w].1 - cells[w - 1].1);
let last = w + 1 == cells.len();
let turns = !last && (cells[w + 1].0 - cells[w].0, cells[w + 1].1 - cells[w].1) != dir;
if last || turns {
pts.push(self.centre(cells[w]));
}
}
let end = if partial || self.slack > 0.0 { self.centre(c) } else { self.dest };
match pts.last_mut() {
Some(l) => *l = end,
None => pts.push(end),
}
self.pts = pts;
self.next = 0;
self.partial = partial;
self.phase = Phase::Follow;
}
/// The column ahead stopped the vehicle: mark it, and search again from here.
pub(super) fn blocked_ahead(&mut self, at: DVec3, pos: DVec3) {
let c = self.cell_of(at);
if c != self.cell_of(pos) {
self.bad.insert(c);
} else {
// In the cell itself: the stretch ahead, one cell on.
let d = horizontal(at - pos).normalize_or(DVec3::X) * f64::from(self.cell);
let c = self.cell_of(pos + d);
self.bad.insert(c);
}
self.replans += 1;
if self.replans > REPLANS {
self.failed = Some(Why::Stuck);
} else {
self.restart(pos);
}
}
/// Ticks the vehicle has waited for the land ahead; true when it has waited too long.
pub(super) fn wait_ahead(&mut self) -> bool {
self.ahead_wait += 1;
self.ahead_wait > WAIT_AHEAD
}
pub(super) fn ahead_ok(&mut self) {
self.ahead_wait = 0;
}
pub(super) fn waited(&self, now: u64) -> u64 {
now.saturating_sub(self.began)
}
/// What the vehicle at `pos` does: works the search on its share of the tick, then follows the way.
pub(super) fn drive(&mut self, ground: &mut Ground, now: u64, pos: DVec3, budget: usize) -> Drive {
if self.phase == Phase::Search && self.failed.is_none() {
self.search(ground, now, budget);
}
if let Some(why) = self.failed {
return Drive::Fail(why);
}
if self.phase == Phase::Search {
return Drive::Wait(Why::Map);
}
let reach = if self.truck { 0.65 } else { f64::from(self.cell) * 0.7 };
while self.next + 1 < self.pts.len() && horizontal(self.pts[self.next] - pos).length() < reach {
self.next += 1;
}
Drive::Go(self.pts[self.next], self.next + 1 >= self.pts.len())
}
/// Let an automatic delivery approach the nearest reachable spot before trying local roadwork.
pub(super) fn approach_works(&mut self) -> bool {
if !self.truck || self.works >= 2 || self.near.0 == self.start
|| self.to_goal(self.start) - self.near.1 < f64::from(self.cell)
{
return false;
}
self.failed = None;
self.finish(self.near.0, true);
self.work_approach = true;
true
}
pub(super) fn work_approach(&self) -> bool {
self.work_approach
}
/// Make a short local crossing only after route search or motion finds a blockage.
/// Returns true while waiting for terrain data or after requesting the edits.
pub(super) fn try_works(&mut self, ground: &mut Ground, pos: DVec3, now: u64, out: &mut Out) -> bool {
if !self.truck || self.works >= 2 || self.work_wait >= 60 {
return false;
}
self.work_wait += 1;
let direction = horizontal(self.dest - pos);
let (dx, dz) = if direction.x.abs() >= direction.z.abs() {
(if direction.x >= 0.0 { 1 } else { -1 }, 0)
} else {
(0, if direction.z >= 0.0 { 1 } else { -1 })
};
let coord = |row: i32, side: i32| (
pos.x.floor() as i32 + dx * row + dz * side,
pos.z.floor() as i32 + dz * row + dx * side,
);
let width = self.chassis.radius.ceil() as i32;
let start = pos.y.round() as i32;
let (ex, ez) = coord(10, 0);
let Some(Some(end)) = ground.column(ex, ez, 1024) else {
ground.want_chunk((ex >> 4, ez >> 4));
return true;
};
let end = end.round() as i32;
if (end - start).abs() > 2 || !(-63..=320).contains(&start) || !(-63..=320).contains(&end) {
return false;
}
let mut commands = Vec::new();
for row in 1..=10 {
let level = start + ((end - start) as f64 * f64::from(row) / 10.0).round() as i32;
let mut deck = false;
for side in -width..=width {
let (x, z) = coord(row, side);
let Some(Some(top)) = ground.column(x, z, 1024) else {
ground.want_chunk((x >> 4, z >> 4));
return true;
};
let top = top.round() as i32;
if top > level + 2 {
return false;
}
let p = DVec3::new(f64::from(x) + 0.5, f64::from(level), f64::from(z) + 0.5);
match ground.world.sweep(p + DVec3::Y * 0.25, p - DVec3::Y * 0.25, false, now) {
world::Sweep::Hit { .. } if top >= level => {}
world::Sweep::Hit { .. } | world::Sweep::Clear => deck = true,
_ => return true,
}
if top > level {
// Only shallow natural cover is cleared. Vanilla fills preserve other materials.
for block in ["short_grass", "fern", "snow", "dirt", "grass_block", "sand", "gravel"] {
commands.push(format!("fill {x} {level} {z} {x} {} {z} minecraft:air replace minecraft:{block}", top - 1));
}
}
}
if deck {
let (ax, az) = coord(row, -width);
let (bx, bz) = coord(row, width);
let y = level - 1;
for block in ["air", "water"] {
commands.push(format!("fill {ax} {y} {az} {bx} {y} {bz} minecraft:cobblestone replace minecraft:{block}"));
}
}
}
if commands.is_empty() || out.commands.len() + commands.len() > 192 {
return false;
}
out.commands.extend(commands);
let centre = pos + DVec3::new(f64::from(dx * 5), 0.0, f64::from(dz * 5));
ground.forget(centre, 9);
let (cx, cz) = (centre.x.floor() as i32, centre.z.floor() as i32);
let mut chunks = Vec::new();
for x in (cx - 9).div_euclid(16)..=(cx + 9).div_euclid(16) {
for z in (cz - 9).div_euclid(16)..=(cz + 9).div_euclid(16) {
chunks.push((x, z));
}
}
ground.world.columns_changed(&chunks);
self.works += 1;
self.replans = 0;
self.failed = None;
self.bad.clear();
self.cells.clear();
self.restart(pos);
true
}
pub(super) fn searching(&self) -> bool {
self.phase == Phase::Search && self.failed.is_none()
}
}
/// The routes of the vehicles that drive, by system id, and the jobs a truck found out of reach.
#[derive(Default)]
pub(super) struct Routes {
pub map: HashMap<u32, Route>,
/// (truck id, the job's id) and until when the truck leaves it alone.
pub unreachable: HashMap<(u32, u32), u64>,
}
impl Routes {
/// What the routes and their searches hold, about (see `sim::memory`).
pub(super) fn bytes(&self) -> usize {
use super::memory::{map_bytes, vec_bytes};
let cell = std::mem::size_of::<(i32, i32)>();
let mut n = map_bytes(self.map.len(), std::mem::size_of::<u32>() + std::mem::size_of::<Route>())
+ map_bytes(self.unreachable.len(), std::mem::size_of::<(u32, u32)>() + std::mem::size_of::<u64>());
for r in self.map.values() {
n += map_bytes(r.cells.len(), cell + std::mem::size_of::<Info>())
+ map_bytes(r.bad.len(), cell)
+ map_bytes(r.g.len(), cell + std::mem::size_of::<f32>())
+ map_bytes(r.came.len(), 2 * cell)
+ r.open.capacity() * std::mem::size_of::<Open>()
+ vec_bytes(&r.parked)
+ vec_bytes(&r.pts);
}
n
}
pub(super) fn out_of_reach(&self, truck: u32, job: u32, now: u64) -> bool {
self.unreachable.get(&(truck, job)).is_some_and(|&t| t > now)
}
}
impl SamKind {
/// The steepest slope (rise a block) it drives: trucks the least.
pub(super) fn climbs(self) -> f64 {
match self.spec().family {
Family::Truck => 0.5,
_ => 0.6,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gun_chassis_cannot_use_the_old_one_point_seven_five_block_radius() {
// The rendered Gepard hull alone is wider/longer than that nominal family circle.
assert!(Chassis::for_kind(SamKind::Gepard).radius > 2.5);
for kind in SamKind::ALL {
assert!(super::super::generated_bounds::bounds(kind.spec().parts.body).is_some(), "{kind:?}");
}
}
#[test]
fn footprint_checks_voxels_grazed_between_their_centres() {
let cells: Vec<_> = Chassis { radius: 2.75, height: 3.0 }.samples(DVec3::new(0.5, 64.0, 0.5)).collect();
assert!(cells.contains(&(3, 1)), "the body reaches the near corner of this voxel");
assert!(cells.contains(&(-3, -1)));
assert!(!cells.contains(&(3, 3)));
}
/// The land as the game would tell it: the height map, and under it the blocks that are solid.
struct Src<H: Fn(i32, i32) -> i32, B: Fn(i32, i32) -> i32> {
height: H,
floor: B,
}
impl<H: Fn(i32, i32) -> i32, B: Fn(i32, i32) -> i32> world::WorldSource for Src<H, B> {
fn solid(&self, x: i32, y: i32, z: i32) -> Option<bool> {
Some(y < (self.floor)(x, z))
}
}
fn answer<H: Fn(i32, i32) -> i32, B: Fn(i32, i32) -> i32>(ground: &mut Ground, src: &Src<H, B>, now: u64) {
let columns = ground.take_wanted().into_iter().map(|(x, z)| (x, z, (src.height)(x, z))).collect();
ground.answer(columns, now);
let sections = ground.world.take_wanted(now);
ground.world.serve(src, sections, now);
}
#[derive(Default)]
struct Overhang {
lowered: bool,
}
impl Overhang {
fn spans(x: i32, z: i32) -> bool {
(16..32).contains(&x) && (-120..120).contains(&z)
}
fn answer(&self, ground: &mut Ground, tick: u64) {
let columns = ground.take_wanted().into_iter().map(|(x, z)| {
(x, z, if Self::spans(x, z) { 73 } else { 64 })
}).collect();
ground.answer(columns, tick);
let sections = ground.world.take_wanted(tick);
ground.world.serve(self, sections, tick);
}
}
impl world::WorldSource for Overhang {
fn solid(&self, x: i32, y: i32, z: i32) -> Option<bool> {
Some(y < 64 || Self::spans(x, z) && (y == 72 || self.lowered && y == 65))
}
}
fn march_under_overhang(lower_after_planning: bool) -> (Sim, bool, bool) {
let mut src = Overhang::default();
let mut sim = Sim::new(3);
let mut ground = Ground::default();
let mut out = Out::default();
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::S400, DVec3::new(0.5, 64.0, 0.5), 0.0));
assert!(sim.order_move(0, DVec3::new(60.5, 64.0, 0.5)));
let mut crossed = false;
let mut replanned = false;
for _ in 0..4000 {
sim.tick += 1;
src.answer(&mut ground, sim.tick);
sim.step_moves(&mut ground, &mut out);
let unit = &sim.sams[0];
if lower_after_planning && !src.lowered && unit.pos.x > 5.0 {
assert!(sim.routes.map.get(&id).is_some_and(|route| route.phase == Phase::Follow));
src.lowered = true;
// A new block under the deck changes the navigable road without changing the heightmap.
let changed: Vec<_> = (-8..8).map(|z| (1, 4, z)).collect();
ground.world.changed(1, false, &changed);
}
if src.lowered {
replanned |= sim.routes.map.get(&id).is_some_and(|route| route.replans > 0);
assert!(unit.pos.x + Chassis::for_kind(unit.kind).radius <= 16.0, "entered the changed ceiling at {:?}", unit.pos);
}
if Overhang::spans(unit.pos.x.floor() as i32, unit.pos.z.floor() as i32) {
assert_eq!(unit.pos.y, 64.0);
crossed = true;
}
if !unit.moving() {
break;
}
}
(sim, crossed, replanned)
}
#[test]
fn a_vehicle_can_follow_the_lower_road_under_a_bridge_deck() {
let (sim, crossed, _) = march_under_overhang(false);
let unit = &sim.sams[0];
assert!(crossed && !unit.moving() && unit.pos.x > 59.0, "ended at {:?}", unit.pos);
}
#[test]
fn a_new_low_ceiling_on_a_planned_road_stops_the_vehicle_and_replans() {
let (sim, crossed, replanned) = march_under_overhang(true);
assert!(replanned && !crossed && !sim.sams[0].moving(), "ended at {:?}", sim.sams[0].pos);
}
#[test]
fn a_supply_truck_builds_a_bridge_then_crosses_it() {
struct Creek(HashSet<(i32, i32)>);
impl world::WorldSource for Creek {
fn solid(&self, x: i32, y: i32, z: i32) -> Option<bool> {
let floor = if (16..20).contains(&x) && !self.0.contains(&(x, z)) { 60 } else { 64 };
Some(y < floor)
}
}
let mut creek = Creek(HashSet::new());
let mut sim = Sim::new(5);
let from = DVec3::new(0.5, 64.0, 0.5);
let to = DVec3::new(80.5, 64.0, 0.5);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Tzm, from, 0.0));
sim.sams[0].job = Some(999);
assert!(sim.order_move_near(0, to, HANDOVER - 0.75));
let mut ground = Ground::default();
let mut out = Out::default();
for _ in 0..2000 {
sim.tick += 1;
let columns = ground.take_wanted().into_iter().map(|(x, z)| (x, z, 64)).collect();
ground.answer(columns, sim.tick);
let sections = ground.world.take_wanted(sim.tick);
ground.world.serve(&creek, sections, sim.tick);
sim.step_moves(&mut ground, &mut out);
for command in out.commands.drain(..) {
let words: Vec<&str> = command.split_whitespace().collect();
if words[7] == "minecraft:cobblestone" && words[9] == "minecraft:water" {
let [ax, ay, az, bx, by, bz] = std::array::from_fn(|i| words[i + 1].parse::<i32>().unwrap());
assert_eq!((ay, by), (63, 63));
for x in ax.min(bx)..=ax.max(bx) {
for z in az.min(bz)..=az.max(bz) {
if (16..20).contains(&x) { creek.0.insert((x, z)); }
}
}
}
}
if !sim.sams[0].moving() { break; }
}
assert!(!creek.0.is_empty(), "the truck built no bridge");
assert!(sim.sams[0].pos.distance(to) <= HANDOVER, "{:?} {:?}", sim.sams[0].pos, out.messages);
assert!(out.messages.is_empty(), "{:?}", out.messages);
}
/// Drives a Patriot from the origin to `to` over land of the given heights.
fn march_kind<H: Fn(i32, i32) -> i32, B: Fn(i32, i32) -> i32>(kind: SamKind, height: H, floor: B, to: DVec3, ticks: u32) -> (Sim, Out, u32) {
let src = Src { height, floor };
let mut sim = Sim::new(3);
sim.damage = false;
let mut ground = Ground::default();
let id = sim.id();
sim.sams.push(Sam::new(id, kind, DVec3::new(0.5, 64.0, 0.5), 0.0));
let mut out = Out::default();
for _ in 0..3 {
sim.tick += 1;
answer(&mut ground, &src, sim.tick);
}
assert!(sim.order_move(0, to));
let mut used = 0;
let mut worst = 0usize;
for _ in 0..ticks {
sim.tick += 1;
sim.step_moves(&mut ground, &mut out);
answer(&mut ground, &src, sim.tick);
used += 1;
let p = sim.sams[0].pos;
let (x, z) = (p.x.floor() as i32, p.z.floor() as i32);
assert!(((src.height)(x, z) as f64) <= p.y + 2.5, "inside the land at {p:?}");
assert!((src.floor)(x, z) >= (src.height)(x, z), "drove onto water at {p:?}");
worst = worst.max(sim.routes.map.values().filter(|r| r.searching()).count());
if !sim.sams[0].moving() {
break;
}
}
let _ = worst;
(sim, out, used)
}
fn march<H: Fn(i32, i32) -> i32, B: Fn(i32, i32) -> i32>(height: H, floor: B, to: DVec3, ticks: u32) -> (Sim, Out, u32) {
march_kind(SamKind::Patriot, height, floor, to, ticks)
}
// A wall across the way, with a gap far to one side: the vehicle goes round and arrives.
#[test]
fn a_wall_with_a_gap_is_driven_round() {
let wall = |x: i32, z: i32| if (40..44).contains(&x) && (-60..=40).contains(&z) { 90 } else { 64 };
let (sim, _, _) = march(wall, wall, DVec3::new(120.0, 64.0, 0.5), 6000);
let s = &sim.sams[0];
assert!(!s.moving() && s.pos.distance(DVec3::new(120.0, 64.0, 0.5)) < 3.0, "ended at {:?} {:?}", s.pos, s.state);
}
// A closed pocket: refused with a reason, no teleport and no drive into the wall.
#[test]
fn an_unreachable_place_is_refused() {
let walls = |x: i32, z: i32| if (60..64).contains(&x) && (-300..300).contains(&z) { 100 } else { 64 };
let (sim, out, _) = march(walls, walls, DVec3::new(120.0, 64.0, 0.5), 6000);
let s = &sim.sams[0];
assert!(!s.moving() && s.pos.x < 62.0, "{:?}", s.pos);
assert!(out.messages.iter().any(|m| m.contains("прохода нет") || m.contains("перекрыт") || m.contains("карта")), "{:?}", out.messages);
}
// A lake (height 64 over a floor of 50) is no road: it is gone round, and a destination in it is refused.
#[test]
fn a_lake_is_not_a_road() {
let floor = |x: i32, z: i32| if (50..90).contains(&x) && z.abs() < 40 { 50 } else { 64 };
let (sim, _, _) = march(|_, _| 64, floor, DVec3::new(130.0, 64.0, 0.5), 6000);
let s = &sim.sams[0];
assert!(!s.moving() && s.pos.distance(DVec3::new(130.0, 64.0, 0.5)) < 3.0, "{:?}", s.pos);
let (sim, out, _) = march(|_, _| 64, floor, DVec3::new(70.0, 64.0, 0.5), 3000);
assert!(!sim.sams[0].moving() && sim.sams[0].pos.x < 10.0, "{:?}", sim.sams[0].pos);
assert!(out.messages.iter().any(|m| m.contains("не проехать")), "{:?}", out.messages);
}
// Open ground: straight on, arrives.
#[test]
fn open_ground_is_driven_straight() {
let (sim, out, _) = march(|_, _| 64, |_, _| 64, DVec3::new(100.0, 64.0, 30.5), 1500);
let s = &sim.sams[0];
let route = sim.routes.map.get(&s.id).map(|r| (r.expanded, r.parked.len(), r.open.len(), r.cells.len()));
assert!(!s.moving() && s.pos.distance(DVec3::new(100.0, 64.0, 30.5)) < 3.0, "pos={:?} state={:?} messages={:?} route={route:?}", s.pos, s.state, out.messages);
}
#[test]
fn an_order_from_above_an_open_road_still_reaches_the_ground() {
let (sim, _, _) = march(|_, _| 64, |_, _| 64, DVec3::new(30.5, 110.0, 0.5), 1500);
let unit = &sim.sams[0];
assert!(!unit.moving() && unit.pos.distance(DVec3::new(30.5, 64.0, 0.5)) < 1.0, "ended at {:?}", unit.pos);
}
// A point-column route fits through this one-block slit, but the S-400 chassis does not.
#[test]
fn s400_rejects_a_one_block_corridor() {
let walls = |x: i32, z: i32| if (-500..500).contains(&x) && z != 0 { 96 } else { 64 };
let (sim, out, _) = march_kind(SamKind::S400, walls, walls, DVec3::new(60.5, 64.0, 0.5), 4000);
assert!(!sim.sams[0].moving(), "{:?}", sim.sams[0].state);
assert!(sim.sams[0].pos.x < 20.0, "narrow passage was traversed: {:?}", sim.sams[0].pos);
assert!(out.messages.iter().any(|m| m.contains("прохода нет") || m.contains("не проехать")), "{:?}", out.messages);
}
// A broad, level lane remains driveable for the same large vehicle.
#[test]
fn s400_uses_a_wide_corridor() {
let walls = |x: i32, z: i32| if (-500..500).contains(&x) && !(-6..=6).contains(&z) { 96 } else { 64 };
let (sim, _, _) = march_kind(SamKind::S400, walls, walls, DVec3::new(60.5, 64.0, 0.5), 5000);
assert!(!sim.sams[0].moving() && sim.sams[0].pos.distance(DVec3::new(60.5, 64.0, 0.5)) < 3.0, "pos={:?} state={:?}", sim.sams[0].pos, sim.sams[0].state);
}
}