use core::cmp::Ordering;
use crate::grid::{GridCell, UniformGrid, is_open};
pub trait LineOfSight: UniformGrid {
fn line_of_sight(&self, from: GridCell, to: GridCell) -> bool {
supercover(self, from, to)
}
}
impl<G: LineOfSight + ?Sized> LineOfSight for &G {
fn line_of_sight(&self, from: GridCell, to: GridCell) -> bool {
(**self).line_of_sight(from, to)
}
}
fn supercover<G: UniformGrid + ?Sized>(grid: &G, from: GridCell, to: GridCell) -> bool {
if !is_open(grid, from) || !is_open(grid, to) {
return false;
}
let signed = |value: usize| i128::try_from(value).expect("grid coordinates fit in i128");
let (width, height) = (signed(from.0.abs_diff(to.0)), signed(from.1.abs_diff(to.1)));
let step_x: i128 = if to.0 >= from.0 { 1 } else { -1 };
let step_y: i128 = if to.1 >= from.1 { 1 } else { -1 };
let open = |x: i128, y: i128| {
let (Ok(x), Ok(y)) = (usize::try_from(x), usize::try_from(y)) else {
return false;
};
is_open(grid, (x, y))
};
let (mut x, mut y) = (signed(from.0), signed(from.1));
let (mut columns, mut rows) = (0, 0);
while columns < width || rows < height {
match ((2 * columns + 1) * height).cmp(&((2 * rows + 1) * width)) {
Ordering::Equal => {
if !open(x + step_x, y) || !open(x, y + step_y) {
return false;
}
x += step_x;
y += step_y;
columns += 1;
rows += 1;
}
Ordering::Less => {
x += step_x;
columns += 1;
}
Ordering::Greater => {
y += step_y;
rows += 1;
}
}
if !open(x, y) {
return false;
}
}
true
}