#![allow(
dead_code,
reason = "shared by the bench and test crates; not every helper is used in each"
)]
use geo_types::{Coord, Rect};
use map_tile_toolkit::TileId;
pub type Pt = [f64; 2];
#[must_use]
pub fn tile_span(t: i32, extent: u32, buffer: u16) -> (f64, f64) {
let lo = f64::from(t) * f64::from(extent) - f64::from(buffer);
(lo, lo + f64::from(extent) + 2.0 * f64::from(buffer))
}
#[must_use]
pub fn tile_rect(tile: TileId, extent: u32, buffer: u16) -> Rect<f64> {
let ((x0, x1), (y0, y1)) = (tile_span(tile.x, extent, buffer), tile_span(tile.y, extent, buffer));
Rect::new(Coord { x: x0, y: y0 }, Coord { x: x1, y: y1 })
}
pub fn clip(pts: &[Pt], axis: usize, lo: f64, hi: f64, closed: bool, out: &mut Vec<Vec<Pt>>) {
let mut part = Vec::new();
for (i, &a) in pts.iter().enumerate() {
let ak = a[axis];
if (lo..=hi).contains(&ak) {
part.push(a);
}
let Some(&b) = pts.get(i + 1).or(if closed { pts.first() } else { None }) else {
break;
};
let (bk, up) = (b[axis], ak < b[axis]);
let mut bounds = [(lo, (ak < lo) != (bk < lo), false), (hi, (ak > hi) != (bk > hi), true)];
if !up {
bounds.reverse();
}
for (k, crosses, is_hi) in bounds {
if crosses {
let mut p = a;
p[axis] = k;
p[1 - axis] += (b[1 - axis] - a[1 - axis]) * (k - ak) / (bk - ak);
part.push(p);
if !closed && is_hi == up {
out.push(std::mem::take(&mut part));
}
}
}
}
if part.len() >= if closed { 3 } else { 2 } {
out.push(part);
}
}
pub fn clip_tile(parts: &[Vec<Pt>], tile: TileId, extent: u32, buffer: u16, closed: bool, out: &mut Vec<Vec<Pt>>) {
let ((x0, x1), (y0, y1)) = (tile_span(tile.x, extent, buffer), tile_span(tile.y, extent, buffer));
let mut column = Vec::new();
for part in parts {
clip(part, 0, x0, x1, closed, &mut column);
}
for part in &column {
clip(part, 1, y0, y1, closed, out);
}
}
pub fn clip_all(
parts: &[Vec<Pt>],
tiles: &[TileId],
extent: u32,
buffer: u16,
closed: bool,
mut emit: impl FnMut(TileId, &[Vec<Pt>]),
) {
let (mut column, mut cell) = (Vec::new(), Vec::new());
for col in tiles.chunk_by(|a, b| a.x == b.x) {
let (x0, x1) = tile_span(col[0].x, extent, buffer);
column.clear();
for part in parts {
clip(part, 0, x0, x1, closed, &mut column);
}
for &tile in col {
let (y0, y1) = tile_span(tile.y, extent, buffer);
cell.clear();
for part in &column {
clip(part, 1, y0, y1, closed, &mut cell);
}
if !cell.is_empty() {
emit(tile, &cell);
}
}
}
}