1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
//! Node locations for ways: loading a file's nodes into a node location store, looking them up by thread, and, with
//! the `geometry` feature, ways as geo-types geometries.
use std::sync::{Mutex, PoisonError};
#[cfg(feature = "geometry")]
use geo_types::{Coord, Geometry, LineString, MultiPolygon, 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;
#[cfg(feature = "geometry")]
use crate::multipolygon::{closed_rings, even_odd};
use crate::nodes::{BulkLoad as _, NodeRead, NodeReader, NodeStore};
use crate::reader::PbfReader;
/// Why a way or a relation has no geometry.
#[cfg(feature = "geometry")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum GeometryError {
/// A node of the way, or of a ring of the relation, has no location: the store does not have it, as when the way
/// leaves an extract.
#[error("node {0} has no location")]
MissingNode(i64),
/// A line needs two nodes or more.
#[error("a line needs at least two nodes")]
TooFewNodes,
/// An area needs a closed way of four nodes or more, the last at the location of the first.
#[error("the way is not a closed ring")]
NotClosed,
/// The member ways of a relation join into no closed ring of four nodes or more, or the rings they join into cover
/// no area.
#[error("the member ways join into no closed ring")]
NoRing,
}
/// Looks up the locations of ways' nodes in a node location store, for one thread. Make one per thread with
/// [`Locator::new`], or get one from [`PbfReader::par_resolve`].
#[derive(Debug)]
pub struct Locator<R> {
reader: R,
}
/// A location as a geo-types coordinate in degrees.
#[cfg(feature = "geometry")]
pub(crate) fn coord(loc: Location) -> Coord<f64> {
Coord {
x: loc.lon_degrees(),
y: loc.lat_degrees(),
}
}
impl<R: NodeReader> Locator<R> {
/// Looks up locations with `reader`, which a store's [`NodeRead::reader`] makes.
pub fn new(reader: R) -> Self {
Self { reader }
}
/// The location of node `id`, if the store has it.
pub fn location(&mut self, id: i64) -> Option<Location> {
self.reader.get(u64::try_from(id).ok()?)
}
/// The location of node `id`, or the error that it has none.
#[cfg(feature = "geometry")]
fn located(&mut self, id: i64) -> Result<Location, GeometryError> {
self.location(id).ok_or(GeometryError::MissingNode(id))
}
/// The way as a line: its nodes' locations, in order: those the file stores on the way, or else the store's.
#[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() {
// Nanodegrees within ±180° are exact in an `f64`. Dividing rounds correctly where multiplying by an inexact
// `1e-9` does not, so a location gives the same degrees as the same one in 1e-7 units does.
#[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| self.located(id).map(coord))
.collect::<Result<_, _>>()?,
};
if coords.len() < 2 {
return Err(GeometryError::TooFewNodes);
}
Ok(LineString::new(coords))
}
/// The way as an area without holes: a closed way of four nodes or more.
#[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()))
}
/// The area of a multipolygon or boundary relation, from the node IDs of its member ways, in any order and
/// direction, as valid polygons.
///
/// The ways are joined end to end, where they share an end node, into closed rings; a way listed twice counts once,
/// and chains of ways that do not close are left out, as are rings of fewer than four nodes. Roles are not read:
/// the area is where a point is inside an odd number of rings, so a ring inside another is a hole and a ring inside
/// that an island, whatever their roles say, and an edge two rings share cancels out. Rings that touch at a node
/// are split there into separate rings; rings that cross, which OpenStreetMap does not allow, get a vertex where
/// they cross, rounded to 1e-7 degrees, and outer rings that overlap leave the overlap out. Outer rings run
/// counterclockwise, holes clockwise. Locations are kept exactly.
///
/// Fails if a node of a closed ring has no location, or if the rings cover no area.
#[cfg(feature = "geometry")]
pub fn multi_polygon<'w>(
&mut self,
ways: impl IntoIterator<Item = &'w [i64]>,
) -> Result<MultiPolygon<f64>, GeometryError> {
let rings = closed_rings(ways)
.iter()
.map(|ids| ids.iter().map(|&id| self.located(id)).collect())
.collect::<Result<Vec<Vec<_>>, _>>()?;
let area = even_odd(&rings);
if area.0.is_empty() {
return Err(GeometryError::NoRing);
}
Ok(area)
}
/// The way as an area if it is closed and `areas` say its tags make it one, and as a line otherwise.
#[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())
}
}
}
/// The nodes [`PbfReader::load_nodes`] hands a store at once. A block holds about 8,000 nodes, and stores encode only
/// large batches on all threads.
const LOAD_BATCH: usize = 1 << 20;
impl PbfReader {
/// Loads the locations of the file's nodes into `store`, which must be empty or hold an interrupted load of the
/// same file, and returns their number. The file must be sorted by type and ID, as published files are; the
/// store's stamp becomes the file's replication sequence, or 0. Nodes with negative IDs, which only editors'
/// files have, are left out. Blocks of ways and relations are skipped unread where the file allows it.
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)
}
/// Calls `f` for every block on the pool, as [`par_unordered`](Self::par_unordered) does, with a [`Locator`] of
/// `store` for the thread it runs on, to turn ways into geometries.
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,
{
// One `Locator` per thread at a time: each keeps the store's blocks it read decoded, for the ways that follow.
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
})
}
}