crates/korp-map-quality/src/land.rs
//! **The land reference** — where the land is, independent of the system under test.
//!
//! "No black land" needs to know which pixels are land. The reference is built ONCE from
//! the region's own full-resolution `natural=coastline` ways (the served
//! `ways.multilinestring.parquet`, every vertex) and the region's clip polygon
//! (`crates/korp-map/assets/sweden.poly`), by korp-map's landmass rule
//! (`crates/korp-map/src/landmass.rs`): join the ways end to end on their exact
//! endpoint coordinates; a closed ring is an island (land on the left: counter-clockwise);
//! an open chain is the clip's edge and is closed along the clip ring in the direction
//! that makes it counter-clockwise (the mainland) or straight across when its ends are
//! within 5 km (an island the cut sliced). The rings are stored once, quantised to 1e-7°
//! (about 1 cm) and zstd-packed, and every run of the harness rasterises them per view.
//!
//! Lakes are inside the land (they are not coastline): a lake the viewer leaves
//! unfilled is black land, which is exactly what the metric must see.
use std::collections::HashMap;
use std::io::{Read, Write};
use std::path::Path;
use serde::Serialize;
use crate::geo::{Grid, ground_m};
use crate::raster::{self, Rule};
use crate::wire::Pt;
/// The tag fragment of a coastline way, as osm-katana writes `tags`.
pub const COASTLINE_TAG: &str = r#""natural":"coastline""#;
/// An open chain whose ends are closer than this is closed straight across.
pub const CLOSE_DIRECT_M: f64 = 5_000.0;
const MAGIC: &[u8; 8] = b"KMQLAND1";
const Q: f64 = 1e7;
/// The land rings of a region.
#[derive(Clone, Debug, Default)]
pub struct LandRef {
pub rings: Vec<Vec<Pt>>,
/// `[minlon, minlat, maxlon, maxlat]` per ring.
pub bboxes: Vec<[f64; 4]>,
}
/// What the build saw.
#[derive(Clone, Debug, Default, Serialize)]
pub struct BuildReport {
pub coastline_ways: usize,
pub closed_rings: usize,
pub open_chains: usize,
pub closed_by_clip: usize,
pub closed_direct: usize,
pub refused: Vec<String>,
pub land_rings: usize,
pub vertices: usize,
pub clockwise_rings: usize,
}
impl LandRef {
#[must_use]
pub fn new(rings: Vec<Vec<Pt>>) -> Self {
let bboxes = rings.iter().map(|r| bbox_of(r)).collect();
Self { rings, bboxes }
}
/// Rasterise the land onto `grid`: `true` = land.
#[must_use]
pub fn mask(&self, grid: &Grid) -> Vec<bool> {
let vb = grid.bbox();
let mut m = vec![false; grid.len()];
let w = grid.width as usize;
let rings = self
.rings
.iter()
.zip(&self.bboxes)
.filter(|(_, b)| b[0] <= vb[2] && b[2] >= vb[0] && b[1] <= vb[3] && b[3] >= vb[1])
.map(|(r, _)| r.iter().map(|p| grid.to_px(p[0], p[1])).collect::<Vec<_>>())
.collect::<Vec<_>>();
raster::fill(
grid.width,
grid.height,
rings.iter().map(Vec::as_slice),
Rule::Positive,
|y, x0, x1| {
m[y * w + x0..y * w + x1].fill(true);
},
);
m
}
/// Write the packed reference.
pub fn save(&self, path: &Path) -> Result<(), String> {
let mut raw = Vec::new();
raw.extend_from_slice(MAGIC);
varint(&mut raw, self.rings.len() as u64);
for r in &self.rings {
varint(&mut raw, r.len() as u64);
let (mut px, mut py) = (0i64, 0i64);
for p in r {
let (x, y) = ((p[0] * Q).round() as i64, (p[1] * Q).round() as i64);
varint(&mut raw, zigzag(x - px));
varint(&mut raw, zigzag(y - py));
(px, py) = (x, y);
}
}
let packed = zstd::encode_all(raw.as_slice(), 9).map_err(|e| e.to_string())?;
let mut f = std::fs::File::create(path).map_err(|e| format!("{path:?}: {e}"))?;
f.write_all(&packed).map_err(|e| e.to_string())
}
/// Read a packed reference.
pub fn load(path: &Path) -> Result<Self, String> {
let mut packed = Vec::new();
std::fs::File::open(path)
.and_then(|mut f| f.read_to_end(&mut packed))
.map_err(|e| format!("{path:?}: {e}"))?;
let raw = zstd::decode_all(packed.as_slice()).map_err(|e| format!("{path:?}: {e}"))?;
if raw.len() < 8 || &raw[..8] != MAGIC {
return Err(format!("{path:?} is not a land reference"));
}
let mut at = 8;
let n = unvarint(&raw, &mut at)? as usize;
let mut rings = Vec::with_capacity(n);
for _ in 0..n {
let k = unvarint(&raw, &mut at)? as usize;
let mut r = Vec::with_capacity(k);
let (mut x, mut y) = (0i64, 0i64);
for _ in 0..k {
x += unzigzag(unvarint(&raw, &mut at)?);
y += unzigzag(unvarint(&raw, &mut at)?);
r.push([x as f64 / Q, y as f64 / Q]);
}
rings.push(r);
}
Ok(Self::new(rings))
}
}
/// Build the reference from a region's native way files — the open ways
/// (`ways.multilinestring.parquet`) and the closed ones (`ways.multipolygon.parquet`:
/// osm-katana files a closed coastline way, i.e. an island, as a polygon) — and its clip
/// `.poly` text.
pub fn build(
lines: &Path,
areas: Option<&Path>,
poly: &str,
) -> Result<(LandRef, BuildReport), String> {
let mut rep = BuildReport::default();
let mut runs = scan_coastline(lines, crate::view::Kind::Lines, &mut rep)?;
if let Some(a) = areas {
runs.extend(scan_coastline(a, crate::view::Kind::Areas, &mut rep)?);
}
rep.coastline_ways = runs.len();
let (closed, chains) = assemble(runs);
rep.closed_rings = closed.len();
rep.open_chains = chains.len();
let clip = poly_rings(poly)
.into_iter()
.max_by_key(Vec::len)
.unwrap_or_default();
let mut rings = Vec::with_capacity(closed.len() + chains.len());
for r in closed {
rings.push(r);
}
for c in chains {
match close_chain(&c, &clip) {
Some((r, by_clip)) => {
if by_clip {
rep.closed_by_clip += 1;
} else {
rep.closed_direct += 1;
}
rings.push(r);
}
None => rep.refused.push(format!(
"open coastline chain of {} vertices ({:.0} m between its ends) could not be closed",
c.len(),
ground_m((c[0][0], c[0][1]), (c[c.len() - 1][0], c[c.len() - 1][1]))
)),
}
}
rings.retain(|r| r.len() >= 4 && signed_area(r) != 0.0);
rep.clockwise_rings = rings.iter().filter(|r| signed_area(r) < 0.0).count();
rep.land_rings = rings.len();
rep.vertices = rings.iter().map(Vec::len).sum();
Ok((LandRef::new(rings), rep))
}
/// Every coastline way's coordinate runs, from a GeoParquet native multilinestring or
/// multipolygon file (a polygon gives its outer ring).
fn scan_coastline(
ways: &Path,
kind: crate::view::Kind,
rep: &mut BuildReport,
) -> Result<Vec<Vec<Pt>>, String> {
use parquet::arrow::ProjectionMask;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
let f = std::fs::File::open(ways).map_err(|e| format!("{ways:?}: {e}"))?;
let b = ParquetRecordBatchReaderBuilder::try_new(f).map_err(|e| format!("{ways:?}: {e}"))?;
let descr = b.metadata().file_metadata().schema_descr_ptr();
let leaves: Vec<usize> = (0..descr.num_columns())
.filter(|&i| {
let p = descr.column(i).path().string();
p == "tags" || p == "id" || p.starts_with("geometry.") && !p.starts_with("geometry_")
})
.collect();
let mask = ProjectionMask::leaves(&descr, leaves);
let reader = b
.with_projection(mask)
.with_batch_size(16_384)
.build()
.map_err(|e| e.to_string())?;
let mut runs = Vec::new();
for batch in reader {
let batch = batch.map_err(|e| e.to_string())?;
let tags = batch
.column_by_name("tags")
.and_then(|c| arrow_array::cast::AsArray::as_string_opt::<i32>(c))
.ok_or("no Utf8 tags column")?;
// Keep only coastline rows, then decode them with the wire's own reader.
use arrow_array::Array;
let keep: arrow_array::BooleanArray = (0..batch.num_rows())
.map(|i| Some(!tags.is_null(i) && tags.value(i).contains(COASTLINE_TAG)))
.collect();
let sub = arrow_select_filter(&batch, &keep)?;
let mut fs = Vec::new();
crate::wire::decode_batch(kind, &sub, &mut fs)?;
for f in fs {
let ls: Vec<Vec<Pt>> = match f.geom {
crate::wire::Geom::Lines(ls) => ls,
crate::wire::Geom::Areas(ps) => ps
.into_iter()
.filter_map(|p| p.into_iter().next())
.collect(),
crate::wire::Geom::Point(_) => Vec::new(),
};
{
for l in ls {
if l.len() >= 2 {
runs.push(l);
} else {
rep.refused.push(format!(
"coastline way {} has a run of {} vertex",
f.id,
l.len()
));
}
}
}
}
}
Ok(runs)
}
fn arrow_select_filter(
b: &arrow_array::RecordBatch,
keep: &arrow_array::BooleanArray,
) -> Result<arrow_array::RecordBatch, String> {
arrow_select::filter::filter_record_batch(b, keep).map_err(|e| e.to_string())
}
type Key = (u64, u64);
fn key(p: Pt) -> Key {
(p[0].to_bits(), p[1].to_bits())
}
/// Join runs end to end into `(closed rings, open chains)` (korp-map `landmass::assemble`).
#[must_use]
pub fn assemble(runs: Vec<Vec<Pt>>) -> (Vec<Vec<Pt>>, Vec<Vec<Pt>>) {
let mut ends: HashMap<Key, Vec<usize>> = HashMap::with_capacity(runs.len() * 2);
for (i, r) in runs.iter().enumerate() {
ends.entry(key(r[0])).or_default().push(i);
ends.entry(key(r[r.len() - 1])).or_default().push(i);
}
let one_free = |k: Key, used: &[bool]| -> Option<usize> {
let mut found = None;
for &j in ends.get(&k)? {
if used[j] {
continue;
}
if found.is_some() {
return None;
}
found = Some(j);
}
found
};
let mut used = vec![false; runs.len()];
let (mut rings, mut chains) = (Vec::new(), Vec::new());
for i in 0..runs.len() {
if used[i] {
continue;
}
used[i] = true;
let mut run = runs[i].clone();
while run[0] != run[run.len() - 1] {
let tail = run[run.len() - 1];
let Some(j) = one_free(key(tail), &used) else {
break;
};
used[j] = true;
let w = &runs[j];
if w[0] == tail {
run.extend_from_slice(&w[1..]);
} else {
run.extend(w.iter().rev().skip(1).copied());
}
}
while run[0] != run[run.len() - 1] {
let head = run[0];
let Some(j) = one_free(key(head), &used) else {
break;
};
used[j] = true;
let w = &runs[j];
let mut pre: Vec<Pt> = if w[w.len() - 1] == head {
w[..w.len() - 1].to_vec()
} else {
w.iter().rev().take(w.len() - 1).copied().collect()
};
pre.extend_from_slice(&run);
run = pre;
}
if run[0] == run[run.len() - 1] && run.len() > 3 {
rings.push(run);
} else {
chains.push(run);
}
}
(rings, chains)
}
/// Close an open chain: straight across when its ends are near, else along the clip ring
/// in the direction that gives a counter-clockwise (land-inside) ring. The bool says
/// whether the clip closed it.
#[must_use]
pub fn close_chain(chain: &[Pt], clip: &[Pt]) -> Option<(Vec<Pt>, bool)> {
if chain.len() < 3 {
return None;
}
let (start, end) = (chain[0], chain[chain.len() - 1]);
if ground_m((start[0], start[1]), (end[0], end[1])) <= CLOSE_DIRECT_M {
let mut r = chain.to_vec();
r.push(start);
return (r.len() > 3).then_some((r, false));
}
let mut clip = clip.to_vec();
if clip.len() >= 3 && clip[0] != clip[clip.len() - 1] {
clip.push(clip[0]);
}
if clip.len() < 4 {
return None;
}
let n = clip.len() - 1;
let nearest = |p: Pt| -> usize {
let (mut bi, mut bd) = (0usize, f64::MAX);
for (i, q) in clip[..n].iter().enumerate() {
let d = (q[0] - p[0]).powi(2) + (q[1] - p[1]).powi(2);
if d < bd {
(bi, bd) = (i, d);
}
}
bi
};
let (ie, is) = (nearest(end), nearest(start));
let walk = |step: isize| -> Vec<Pt> {
let mut out = Vec::new();
let mut i = ie;
for _ in 0..=n {
i = ((i as isize + step).rem_euclid(n as isize)) as usize;
out.push(clip[i]);
if i == is {
break;
}
}
out
};
let mut best: Option<Vec<Pt>> = None;
for step in [1isize, -1] {
let mut r = chain.to_vec();
r.extend(walk(step));
r.push(start);
if signed_area(&r) > 0.0
&& best
.as_ref()
.is_none_or(|b| signed_area(&r) > signed_area(b))
{
best = Some(r);
}
}
best.map(|r| (r, true))
}
/// Shoelace area in degrees², counter-clockwise positive.
#[must_use]
pub fn signed_area(r: &[Pt]) -> f64 {
let mut s = 0.0;
for w in r.windows(2) {
s += w[0][0] * w[1][1] - w[1][0] * w[0][1];
}
s / 2.0
}
#[must_use]
pub fn bbox_of(r: &[Pt]) -> [f64; 4] {
let mut b = [f64::MAX, f64::MAX, f64::MIN, f64::MIN];
for p in r {
b[0] = b[0].min(p[0]);
b[1] = b[1].min(p[1]);
b[2] = b[2].max(p[0]);
b[3] = b[3].max(p[1]);
}
b
}
/// The rings of an Osmosis `.poly` file (`!` holes are ignored: the clip is the outer).
#[must_use]
pub fn poly_rings(poly: &str) -> Vec<Vec<Pt>> {
let (mut rings, mut cur, mut hole) = (Vec::new(), Vec::new(), false);
for line in poly.lines() {
let t = line.trim();
if t.eq_ignore_ascii_case("END") {
if cur.len() >= 3 && !hole {
rings.push(std::mem::take(&mut cur));
}
cur.clear();
continue;
}
let mut it = t.split_whitespace();
match (it.next(), it.next(), it.next()) {
(Some(a), Some(b), None) => {
if let (Ok(x), Ok(y)) = (a.parse::<f64>(), b.parse::<f64>()) {
cur.push([x, y]);
}
}
(Some(name), None, None) => hole = name.starts_with('!'),
_ => {}
}
}
rings
}
fn varint(out: &mut Vec<u8>, mut v: u64) {
while v >= 0x80 {
out.push((v as u8) | 0x80);
v >>= 7;
}
out.push(v as u8);
}
fn unvarint(b: &[u8], at: &mut usize) -> Result<u64, String> {
let (mut v, mut s) = (0u64, 0);
loop {
let c = *b.get(*at).ok_or("truncated land reference")?;
*at += 1;
v |= u64::from(c & 0x7f) << s;
if c < 0x80 {
return Ok(v);
}
s += 7;
if s > 63 {
return Err("bad varint".into());
}
}
}
fn zigzag(v: i64) -> u64 {
((v << 1) ^ (v >> 63)) as u64
}
fn unzigzag(v: u64) -> i64 {
((v >> 1) as i64) ^ -((v & 1) as i64)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn runs_join_into_an_island_and_a_chain() {
// A square island in two halves (one reversed), and a lone open run.
let a = vec![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]];
let b = vec![[0.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
let c = vec![[5.0, 5.0], [6.0, 5.0], [6.0, 6.0]];
let (rings, chains) = assemble(vec![a, b, c]);
assert_eq!(rings.len(), 1);
assert_eq!(rings[0].len(), 5);
assert_eq!(chains.len(), 1);
}
#[test]
fn a_mainland_chain_closes_along_the_clip_counter_clockwise() {
// Clip: a big box. Chain: a coast running west→east across the middle, land on its
// left (north). Closing must walk the clip's northern half.
let clip = vec![
[0.0, 0.0],
[10.0, 0.0],
[10.0, 5.0],
[10.0, 10.0],
[0.0, 10.0],
[0.0, 5.0],
[0.0, 0.0],
];
let chain = vec![[0.0, 5.0], [5.0, 4.0], [10.0, 5.0]];
let (r, by_clip) = close_chain(&chain, &clip).expect("closes");
assert!(by_clip);
assert!(signed_area(&r) > 0.0);
assert!(r.iter().any(|p| p == &[10.0, 10.0]) && r.iter().any(|p| p == &[0.0, 10.0]));
assert!(
!r.iter().any(|p| p == &[0.0, 0.0] || p == &[10.0, 0.0]),
"{r:?}"
);
}
#[test]
fn save_and_load_round_trip_to_a_centimetre() {
let dir = std::env::temp_dir().join(format!("kmq-land-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let p = dir.join("l.bin");
let l = LandRef::new(vec![vec![
[18.0686123, 59.3293456],
[18.1, 59.3],
[18.2, 59.4],
[18.0686123, 59.3293456],
]]);
l.save(&p).unwrap();
let m = LandRef::load(&p).unwrap();
for (a, b) in l.rings[0].iter().zip(&m.rings[0]) {
assert!((a[0] - b[0]).abs() < 1e-7 && (a[1] - b[1]).abs() < 1e-7);
}
std::fs::remove_dir_all(dir).ok();
}
#[test]
fn the_mask_fills_the_island() {
use crate::geo::{Grid, zoom_for_res};
let g = Grid::new(18.0, 59.0, zoom_for_res(100.0, 59.0), 200, 100);
let b = g.bbox();
let (cx, cy) = ((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0);
let (dx, dy) = ((b[2] - b[0]) / 4.0, (b[3] - b[1]) / 4.0);
let island = vec![
[cx - dx, cy - dy],
[cx + dx, cy - dy],
[cx + dx, cy + dy],
[cx - dx, cy + dy],
[cx - dx, cy - dy],
];
let m = LandRef::new(vec![island]).mask(&g);
let n = m.iter().filter(|&&v| v).count();
assert!((n as i64 - 100 * 50).abs() < 200, "{n}");
assert!(m[50 * 200 + 100] && !m[0]);
}
#[test]
fn poly_sections_and_holes() {
let p = "x\nx_1\n 0 0\n 1 0\n 1 1\nEND\n!h\n 0.2 0.2\n 0.3 0.2\n 0.3 0.3\nEND\nEND\n";
let r = poly_rings(p);
assert_eq!(r.len(), 1);
assert_eq!(r[0].len(), 3);
}
}