use std::sync::{Mutex, PoisonError};
#[cfg(feature = "geometry")]
use geo_types::{Coord, Geometry, LineString, Polygon};
use crate::Location;
#[cfg(feature = "geometry")]
use crate::area::AreaRules;
use crate::block::{Block, Select, TagMode};
#[cfg(feature = "geometry")]
use crate::block::{Tags, Way};
use crate::error::Result;
use crate::nodes::{BulkLoad as _, NodeRead, NodeReader, NodeStore};
use crate::reader::PbfReader;
#[cfg(feature = "geometry")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum GeometryError {
#[error("node {0} has no location")]
MissingNode(i64),
#[error("a line needs at least two nodes")]
TooFewNodes,
#[error("the way is not a closed ring")]
NotClosed,
}
#[derive(Debug)]
pub struct Locator<R> {
reader: R,
}
#[cfg(feature = "geometry")]
fn coord(loc: Location) -> Coord<f64> {
Coord {
x: loc.lon_degrees(),
y: loc.lat_degrees(),
}
}
impl<R: NodeReader> Locator<R> {
pub fn new(reader: R) -> Self {
Self { reader }
}
pub fn location(&mut self, id: i64) -> Option<Location> {
self.reader.get(u64::try_from(id).ok()?)
}
#[cfg(feature = "geometry")]
pub fn line_string<T: TagMode>(
&mut self,
way: &Way<'_, T>,
) -> Result<LineString<f64>, GeometryError> {
let coords: Vec<Coord<f64>> = match way.locations() {
#[allow(
clippy::cast_precision_loss,
reason = "nanodegrees of a location fit an f64 exactly"
)]
Some(locations) => locations
.map(|(lat, lon)| Coord {
x: lon as f64 / 1e9,
y: lat as f64 / 1e9,
})
.collect(),
None => way
.refs()
.map(|id| {
let loc = self.location(id).ok_or(GeometryError::MissingNode(id))?;
Ok(coord(loc))
})
.collect::<Result<_, _>>()?,
};
if coords.len() < 2 {
return Err(GeometryError::TooFewNodes);
}
Ok(LineString::new(coords))
}
#[cfg(feature = "geometry")]
pub fn polygon<T: TagMode>(&mut self, way: &Way<'_, T>) -> Result<Polygon<f64>, GeometryError> {
let ring = self.line_string(way)?;
if ring.0.len() < 4 || !ring.is_closed() {
return Err(GeometryError::NotClosed);
}
Ok(Polygon::new(ring, Vec::new()))
}
#[cfg(feature = "geometry")]
pub fn area_or_line(
&mut self,
way: &Way<'_, Tags>,
areas: &AreaRules,
) -> Result<Geometry<f64>, GeometryError> {
let line = self.line_string(way)?;
if line.0.len() >= 4 && line.is_closed() && areas.is_area(way.tags()) {
Ok(Polygon::new(line, Vec::new()).into())
} else {
Ok(line.into())
}
}
}
const LOAD_BATCH: usize = 1 << 20;
impl PbfReader {
pub fn load_nodes<S: NodeStore>(&self, store: &mut S) -> Result<u64> {
let stamp = self
.header()
.replication_sequence
.and_then(|s| u64::try_from(s).ok())
.unwrap_or(0);
let mut loader = store.bulk_load()?;
let mut batch = Vec::with_capacity(LOAD_BATCH);
let mut count = 0;
for block in self
.without_filters()
.par_ordered(Select::node_locations())?
{
let block = block?;
block.push_node_locations(&mut batch);
if batch.len() >= LOAD_BATCH {
loader.push_batch(&batch)?;
count += batch.len() as u64;
batch.clear();
}
}
loader.push_batch(&batch)?;
count += batch.len() as u64;
loader.finish(stamp)?;
Ok(count)
}
pub fn par_resolve<'s, T, S, F>(&self, select: Select<T>, store: &'s S, f: F) -> Result<()>
where
T: TagMode,
S: NodeRead,
S::Reader<'s>: Send,
F: Fn(Block<T>, &mut Locator<S::Reader<'s>>) -> Result<()> + Sync,
{
let idle = Mutex::new(Vec::new());
let take = || idle.lock().unwrap_or_else(PoisonError::into_inner).pop();
self.par_unordered(select, |block| {
let mut nodes = take().unwrap_or_else(|| Locator::new(store.reader()));
let result = f(block, &mut nodes);
idle.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(nodes);
result
})
}
}