use std::sync::{Arc, OnceLock};
use geometry::Point;
use smallvec::{SmallVec, smallvec};
use super::{Crs, NO_ANSWER, TileMatrixSet, is_answer};
use crate::geo::LatLngBounds;
const ROUND_TRIP_TOLERANCE: f64 = 1e-3;
const EDGE_SEARCH_STEPS: usize = 30;
const MAX_MERIDIAN_STRETCH: f64 = 10.0;
const BOX_SAMPLE_STEPS: usize = 16;
const BOX_SAMPLE_SIDE: usize = BOX_SAMPLE_STEPS + 1;
type Positions = SmallVec<[[f64; 2]; 1]>;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WorldBox {
pub min: Point<f64>,
pub max: Point<f64>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct BoxSamples {
pub points: Vec<Point<f64>>,
pub bulge: f64,
}
impl BoxSamples {
#[must_use]
pub(crate) fn new(
bounds: &LatLngBounds,
world_from_lng_lats: impl FnOnce(&[[f64; 2]], &mut [[f64; 2]]),
) -> BoxSamples {
let longitude_at = |step: usize| {
if step == BOX_SAMPLE_STEPS {
bounds.east()
} else {
bounds.west() + (bounds.east() - bounds.west()) * step as f64 / BOX_SAMPLE_STEPS as f64
}
};
let latitude_at = |step: usize| {
if step == BOX_SAMPLE_STEPS {
bounds.south()
} else {
bounds.north() + (bounds.south() - bounds.north()) * step as f64 / BOX_SAMPLE_STEPS as f64
}
};
let mut lng_lats = Vec::with_capacity(BOX_SAMPLE_SIDE * BOX_SAMPLE_SIDE + 4 * BOX_SAMPLE_STEPS);
for row in 0..BOX_SAMPLE_SIDE {
lng_lats.extend((0..BOX_SAMPLE_SIDE).map(|column| [longitude_at(column), latitude_at(row)]));
}
for step in 0..BOX_SAMPLE_STEPS {
let longitude_halfway = f64::midpoint(longitude_at(step), longitude_at(step + 1));
let latitude_halfway = f64::midpoint(latitude_at(step), latitude_at(step + 1));
lng_lats.extend([
[longitude_halfway, bounds.north()],
[longitude_halfway, bounds.south()],
[bounds.west(), latitude_halfway],
[bounds.east(), latitude_halfway],
]);
}
let mut world = vec![[0.0; 2]; lng_lats.len()];
world_from_lng_lats(&lng_lats, &mut world);
let (grid, halfway) = world.split_at(BOX_SAMPLE_SIDE * BOX_SAMPLE_SIDE);
let at = |row: usize, column: usize| grid[row * BOX_SAMPLE_SIDE + column];
let mut bulge = 0.0;
for (step, &[north, south, west, east]) in halfway.as_chunks::<4>().0.iter().enumerate() {
let edges = [
(at(0, step), at(0, step + 1), north),
(at(BOX_SAMPLE_STEPS, step), at(BOX_SAMPLE_STEPS, step + 1), south),
(at(step, 0), at(step + 1, 0), west),
(at(step, BOX_SAMPLE_STEPS), at(step + 1, BOX_SAMPLE_STEPS), east),
];
for (start, end, middle) in edges {
let chord = [end[0] - start[0], end[1] - start[1]];
let to_middle = [middle[0] - start[0], middle[1] - start[1]];
let chord_length = chord[0].hypot(chord[1]);
let distance = if chord_length > 0.0 {
(chord[0] * to_middle[1] - chord[1] * to_middle[0]).abs() / chord_length
} else {
to_middle[0].hypot(to_middle[1])
};
bulge = f64::max(bulge, distance);
}
}
BoxSamples { points: grid.iter().map(|point| Point::new(point[0], point[1])).collect(), bulge }
}
#[must_use]
pub fn world_box(&self) -> WorldBox {
let mut min = Point::new(f64::INFINITY, f64::INFINITY);
let mut max = Point::new(f64::NEG_INFINITY, f64::NEG_INFINITY);
for point in &self.points {
min = Point::new(min.x.min(point.x), min.y.min(point.y));
max = Point::new(max.x.max(point.x), max.y.max(point.y));
}
let bulge = self.bulge;
WorldBox { min: Point::new(min.x - bulge, min.y - bulge), max: Point::new(max.x + bulge, max.y + bulge) }
}
}
#[derive(Debug)]
pub(crate) struct CrsMapping {
crs: Arc<Crs>,
latitude_range: OnceLock<[f64; 2]>,
}
impl CrsMapping {
#[must_use]
pub(crate) fn new(crs: Arc<Crs>) -> CrsMapping {
CrsMapping { crs, latitude_range: OnceLock::new() }
}
#[must_use]
pub(crate) fn crs(&self) -> &Arc<Crs> {
&self.crs
}
pub(crate) fn world_from_lng_lats(&self, lng_lats: &[[f64; 2]], world: &mut [[f64; 2]]) {
if lng_lats.is_empty() {
return;
}
self.crs.converter.forward(lng_lats, world);
let TileMatrixSet { origin: [origin_x, origin_y], extent_at_zoom0: extent } = self.crs.tile_matrix_set;
for position in world {
*position = [(position[0] - origin_x) / extent, (origin_y - position[1]) / extent];
}
}
pub(crate) fn lng_lats_from_world(&self, world: &[[f64; 2]], lng_lats: &mut [[f64; 2]]) {
self.own_answers(world, lng_lats);
let mut rest: Vec<usize> = Vec::new();
let mut inside: Vec<[f64; 2]> = Vec::new();
for (index, (point, lng_lat)) in world.iter().zip(lng_lats.iter()).enumerate() {
if !is_answer(lng_lat) {
rest.push(index);
inside.push([point[0].clamp(0.0, 1.0), point[1].clamp(0.0, 1.0)]);
}
}
fall_back(&mut rest, &mut inside, lng_lats, |inside, found| self.own_answers(inside, found));
fall_back(&mut rest, &mut inside, lng_lats, |inside, found| self.answers_toward_center(inside, found));
fall_back(&mut rest, &mut inside, lng_lats, |inside, found| {
let positions: Vec<[f64; 2]> = inside.iter().map(|point| self.crs_position(*point)).collect();
self.finite_inverses(&positions, found);
});
for lng_lat in lng_lats {
lng_lat[1] = lng_lat[1].clamp(-90.0, 90.0);
}
}
#[must_use]
pub(crate) fn has_lat_lng(&self, world: [f64; 2]) -> bool {
let mut lng_lat = [[0.0; 2]];
self.own_answers(&[world], &mut lng_lat);
is_answer(&lng_lat[0]) && lng_lat[0][1].abs() <= 90.0
}
#[must_use]
pub(crate) fn latitude_range(&self) -> [f64; 2] {
*self.latitude_range.get_or_init(|| {
let mut center = [[0.0; 2]];
self.lng_lats_from_world(&[[0.5, 0.5]], &mut center);
[self.latitude_limit(center[0], -90.0), self.latitude_limit(center[0], 90.0)]
})
}
fn crs_position(&self, world: [f64; 2]) -> [f64; 2] {
let TileMatrixSet { origin: [origin_x, origin_y], extent_at_zoom0: extent } = self.crs.tile_matrix_set;
[origin_x + world[0] * extent, origin_y - world[1] * extent]
}
fn finite_inverses(&self, positions: &[[f64; 2]], lng_lats: &mut [[f64; 2]]) {
self.crs.converter.inverse(positions, lng_lats);
for lng_lat in lng_lats {
if !is_answer(lng_lat) {
*lng_lat = NO_ANSWER;
}
}
}
fn own_answers(&self, world: &[[f64; 2]], lng_lats: &mut [[f64; 2]]) {
if world.is_empty() {
return;
}
let mut positions: Positions = world.iter().map(|point| self.crs_position(*point)).collect();
self.finite_inverses(&positions, lng_lats);
let Some(first) = lng_lats.iter().copied().find(is_answer) else {
return;
};
for (lng_lat, position) in lng_lats.iter_mut().zip(positions.iter_mut()) {
if !is_answer(lng_lat) {
*lng_lat = first;
*position = NO_ANSWER;
}
}
let mut back: Positions = smallvec![[0.0; 2]; world.len()];
self.crs.converter.forward(lng_lats, &mut back);
let tolerance = ROUND_TRIP_TOLERANCE * self.crs.tile_matrix_set.extent_at_zoom0;
for ((lng_lat, forward), position) in lng_lats.iter_mut().zip(&back).zip(&positions) {
let distance = (forward[0] - position[0]).hypot(forward[1] - position[1]);
if distance.is_nan() || distance > tolerance {
*lng_lat = NO_ANSWER;
}
}
}
fn answers_toward_center(&self, world: &[[f64; 2]], lng_lats: &mut [[f64; 2]]) {
let along_at =
|point: &[f64; 2], fraction: f64| [0.5 + (point[0] - 0.5) * fraction, 0.5 + (point[1] - 0.5) * fraction];
let mut answered = vec![0.0; world.len()];
let mut unanswered = vec![1.0; world.len()];
let mut along = vec![[0.0; 2]; world.len()];
for _ in 0..EDGE_SEARCH_STEPS {
for (((along, point), answered), unanswered) in along.iter_mut().zip(world).zip(&answered).zip(&unanswered)
{
*along = along_at(point, f64::midpoint(*answered, *unanswered));
}
self.own_answers(&along, lng_lats);
for ((lng_lat, answered), unanswered) in lng_lats.iter().zip(&mut answered).zip(&mut unanswered) {
let fraction = f64::midpoint(*answered, *unanswered);
if is_answer(lng_lat) {
*answered = fraction;
} else {
*unanswered = fraction;
}
}
}
for ((along, point), answered) in along.iter_mut().zip(world).zip(&answered) {
*along = along_at(point, *answered);
}
self.own_answers(&along, lng_lats);
}
fn latitude_limit(&self, center: [f64; 2], pole: f64) -> f64 {
let [center_longitude, center_latitude] = center;
let step = if pole > center_latitude { 1.0 } else { -1.0 };
let steps = ((pole - center_latitude).abs() - 1.0).ceil().max(0.0) as usize;
let toward_equator = |latitude: f64| if latitude >= 0.0 { latitude - 0.01 } else { latitude + 0.01 };
let mut lng_lats = Vec::with_capacity(2 * (steps + 1));
for latitude in
std::iter::once(center_latitude).chain((0..steps).map(|index| center_latitude + index as f64 * step + step))
{
lng_lats.extend([[center_longitude, latitude], [center_longitude, toward_equator(latitude)]]);
}
let mut positions = vec![[0.0; 2]; lng_lats.len()];
self.crs.converter.forward(&lng_lats, &mut positions);
let stretches: Vec<f64> = positions
.as_chunks::<2>()
.0
.iter()
.map(|[at, toward_equator]| (toward_equator[0] - at[0]).hypot(toward_equator[1] - at[1]))
.collect();
let Some((&at_center, beyond)) = stretches.split_first() else {
return pole;
};
let max_stretch = MAX_MERIDIAN_STRETCH * at_center;
if max_stretch.is_nan() || max_stretch <= 0.0 {
return pole;
}
match beyond.iter().position(|stretch| stretch.is_nan() || *stretch > max_stretch) {
Some(index) => center_latitude + index as f64 * step,
None => pole,
}
}
}
fn fall_back(
rest: &mut Vec<usize>,
inside: &mut Vec<[f64; 2]>,
lng_lats: &mut [[f64; 2]],
answer: impl FnOnce(&[[f64; 2]], &mut [[f64; 2]]),
) {
if rest.is_empty() {
return;
}
let mut found = vec![NO_ANSWER; rest.len()];
answer(inside, &mut found);
let (mut still, mut still_inside) = (Vec::new(), Vec::new());
for ((&index, &point), &found) in rest.iter().zip(inside.iter()).zip(&found) {
if is_answer(&found) {
lng_lats[index] = found;
} else {
still.push(index);
still_inside.push(point);
}
}
(*rest, *inside) = (still, still_inside);
}