Files
airdef/airdef-mod/src/sim/route.rs
T
chexit 5620347ffe Add three art pilots and derive chassis envelopes from final models (#115 #114)
Keep authored JSON separate from generated output. Export rotated model bounds for SDK-free navigation and check grazing voxel corners. Include unretouched in-game before/after captures and explicit art/performance limits; pilots are an intermediate pass, not completion of the full asset set.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-02 21:33:59 +03:00

716 lines
28 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,
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) -> Vec<(i32, i32)> {
let r = self.radius.ceil() as i32;
(-r..=r).flat_map(|x| (-r..=r).filter_map(move |z| {
let dx = (f64::from(x.abs()) - 0.5).max(0.0);
let dz = (f64::from(z.abs()) - 0.5).max(0.0);
(dx * dx + dz * dz <= self.radius * self.radius).then_some((x, z))
})).collect()
}
}
#[derive(Clone, Copy)]
struct Info {
h: f32,
ok: bool,
}
enum Eval {
Ok(f32),
Bad,
Pending,
}
#[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,
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,
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 { self.to_goal(c) <= self.slack } else { c == self.cell_of(self.dest) }
}
/// 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.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.cells.insert(self.start, Info { h: pos.y as f32, ok: true });
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)) -> Eval {
if let Some(i) = self.cells.get(&c) {
return if i.ok { Eval::Ok(i.h) } else { Eval::Bad };
}
if self.bad.contains(&c) {
return Eval::Bad;
}
let p = self.centre(c);
let (x, z) = (p.x.floor() as i32, p.z.floor() as i32);
let verdict = match ground.column(x, z, 1024) {
None => return Eval::Pending,
Some(None) => Info { h: 0.0, ok: false },
Some(Some(h)) => {
// The height is the top of what blocks motion or holds a fluid: water has nothing solid under it.
let top = DVec3::new(f64::from(x) + 0.5, h, f64::from(z) + 0.5);
match ground.world.sweep(top + DVec3::Y * 0.5, top - DVec3::Y * 0.5, false, now) {
world::Sweep::Hit { .. } => Info { h: h as f32, ok: true },
world::Sweep::Clear => Info { h: h as f32, ok: false },
world::Sweep::Unknown { pending: true, .. } | world::Sweep::Wait { .. } => return Eval::Pending,
world::Sweep::Unknown { .. } => Info { h: h as f32, ok: false },
}
}
};
if verdict.ok {
match self.clearance_at(ground, DVec3::new(f64::from(x) + 0.5, f64::from(verdict.h), f64::from(z) + 0.5), now) {
Clearance::Clear => {}
Clearance::Blocked => {
let blocked = Info { h: verdict.h, ok: false };
self.cells.insert(c, blocked);
return Eval::Bad;
}
Clearance::Pending => return Eval::Pending,
}
}
self.cells.insert(c, verdict);
if verdict.ok { Eval::Ok(verdict.h) } else { Eval::Bad }
}
/// Check a chassis-sized footprint against sampled support columns and voxel headroom.
/// Unknown columns or sections are pending so neither search nor motion assumes they are open.
fn clearance_at(&self, ground: &mut Ground, pos: DVec3, now: u64) -> Clearance {
let base = pos.y;
let mut pending = false;
for (dx, dz) in self.chassis.samples() {
let x = pos.x.floor() as i32 + dx;
let z = pos.z.floor() as i32 + dz;
let Some(column) = ground.column(x, z, 1024) else { pending = true; continue };
let Some(h) = column else { return Clearance::Blocked };
let dh = h - base;
if dh > STEP_UP || dh < -STEP_DOWN {
return Clearance::Blocked;
}
let top = DVec3::new(f64::from(x) + 0.5, h + 0.05, f64::from(z) + 0.5);
match ground.world.sweep(top, top + DVec3::Y * self.chassis.height, false, now) {
world::Sweep::Clear => {}
world::Sweep::Unknown { pending: true, .. } | world::Sweep::Wait { .. } => pending = true,
world::Sweep::Unknown { .. } | world::Sweep::Hit { .. } => return Clearance::Blocked,
}
}
if pending { Clearance::Pending } else { Clearance::Clear }
}
/// 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 {
self.clearance_at(ground, pos, now)
}
/// 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 Some(h0) = self.cells.get(&c).map(|i| f64::from(i.h)) else { return };
let h1 = match self.eval(ground, now, nb) {
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) {
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 hm = match ground.column(mid.x.floor() as i32, mid.z.floor() as i32, 1024) {
None => return self.park(c, nb),
Some(None) => return,
Some(Some(h)) => h,
};
let half = dist * 0.5;
let allow = |l: f64| (self.slope * l).max(STEP_UP);
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 {
match self.eval(ground, now, self.cell_of(self.dest)) {
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() {
let goal = self.cell_of(self.dest);
self.failed = Some(if self.slack == 0.0 && !self.cells.get(&goal).is_none_or(|i| i.ok) { Why::Goal } else { 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);
self.cells.insert(c, Info { h: 0.0, ok: false });
} 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.cells.insert(c, Info { h: 0.0, ok: false });
}
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 = 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())
}
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 {
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 = Chassis { radius: 2.75, height: 3.0 }.samples();
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);
}
/// Drives a Patriot from the origin to `to` over land of the given heights (water: a height over a lower floor).
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);
}
// 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);
}
}