use crate::geom::{self, Lines};
use crate::grammar::Terrain as Spec;
use crate::output::Output;
use burin_map_core::atlas::Atlas;
use burin_map_core::script;
use burin_map_core::{Drawing, Region, Ring, Surface};
use geo::{BoundingRect, Coord, LineString, MultiPolygon, Polygon};
#[derive(Clone)]
pub struct Grid {
pub elev: Vec<f32>,
pub width: usize,
pub height: usize,
pub px_m: f64,
pub nw_lon: f64,
pub nw_lat: f64,
pub deg_per_px_lon: f64,
pub deg_per_px_lat: f64,
}
pub const MM_PER_PX: f64 = 0.15;
pub fn width_px(output: &Output, screen: Option<&crate::paint::Screen>) -> usize {
let (s, c) = output.bearing.to_radians().sin_cos();
let across = output.width_mm * c.abs() + output.height_mm * s.abs();
let per_px = screen.map_or(MM_PER_PX, |s| s.dot());
((across * (1.0 + 2.0 * TERRAIN_MARGIN)) / per_px).round().clamp(256.0, 4096.0) as usize
}
pub struct Placed {
pub x0: f64,
pub y0: f64,
pub east: (f64, f64),
pub south: (f64, f64),
}
impl Placed {
pub fn to_mm(&self, px: f64, py: f64) -> (f64, f64) {
(self.x0 + px * self.east.0 + py * self.south.0, self.y0 + px * self.east.1 + py * self.south.1)
}
pub fn to_px(&self, x: f64, y: f64) -> [f64; 2] {
let (dx, dy) = (x - self.x0, y - self.y0);
let (a, b, c, d) = (self.east.0, self.south.0, self.east.1, self.south.1);
let det = a * d - b * c;
[(d * dx - b * dy) / det, (a * dy - c * dx) / det]
}
}
impl Grid {
pub fn new(bounds: [f64; 4], merc: [f64; 4], elev: Vec<f32>, width: usize) -> Grid {
let height = elev.len() / width.max(1);
let height = height.max(1);
Grid {
elev,
width: width.max(1),
height,
px_m: (merc[2] - merc[0]) / width.max(1) as f64,
nw_lon: bounds[0],
nw_lat: bounds[3],
deg_per_px_lon: (bounds[2] - bounds[0]) / width.max(1) as f64,
deg_per_px_lat: (bounds[3] - bounds[1]) / height as f64,
}
}
pub fn placed(&self, projector: &crate::projection::Projector) -> Placed {
let (nx, ny) = projector.project(self.nw_lon, self.nw_lat);
let (ex, ey) = projector.project(self.nw_lon + self.deg_per_px_lon * self.width as f64, self.nw_lat);
let (sx, sy) = projector.project(self.nw_lon, self.nw_lat - self.deg_per_px_lat * self.height as f64);
let (w, h) = (self.width as f64, self.height as f64);
Placed { x0: nx, y0: ny, east: ((ex - nx) / w, (ey - ny) / w), south: ((sx - nx) / h, (sy - ny) / h) }
}
}
pub fn atlas_of(spec: &Spec) -> Result<Atlas, String> {
let mut atlas = Atlas::new();
if spec.shore {
atlas.shore(burin_map_core::water::Shoreline::default());
}
let mut body = serde_json::Map::new();
body.insert(
"draw".into(),
serde_json::Value::String(
match spec.draw {
crate::grammar::TerrainDraw::Lines => "lines",
crate::grammar::TerrainDraw::Fill => "fill",
crate::grammar::TerrainDraw::Dots => "dots",
}
.into(),
),
);
if let Some(color) = &spec.color {
body.insert(
if spec.draw == crate::grammar::TerrainDraw::Fill { "color".into() } else { "shade".into() },
color.clone(),
);
}
if let Some(width) = &spec.width {
body.insert("width".into(), width.clone());
}
if let Some(layer) = &spec.layer {
body.insert("layer".into(), serde_json::Value::String(layer.clone()));
}
if spec.angle != 0.0 {
body.insert("angle".into(), serde_json::json!(spec.angle));
}
if !spec.band.is_empty() {
body.insert("where".into(), serde_json::Value::Object(spec.band.clone()));
}
for (k, v) in &spec.style {
body.insert(k.clone(), v.clone());
}
let batch = script::batch_from(&serde_json::Value::Object(body))?;
atlas.batch(batch);
Ok(atlas)
}
pub fn draw(grid: &Grid, spec: &Spec) -> Result<Drawing, String> {
run(&atlas_of(spec)?, grid, &[], None)
}
pub fn draw_burin(
grid: &Grid,
spec: &crate::grammar::Burin,
regions: &[(&str, Region)],
water: Option<&[f32]>,
) -> Result<Drawing, String> {
run(&script::atlas_from(&spec.atlas)?, grid, regions, water)
}
fn run(atlas: &Atlas, grid: &Grid, regions: &[(&str, Region)], water: Option<&[f32]>) -> Result<Drawing, String> {
let surface = Surface::new(&grid.elev, grid.width, grid.height, grid.px_m as f32).regions(regions);
atlas.draw(&surface, water)
}
pub fn coverage_of(area: &MultiPolygon<f64>, grid: &Grid, at: &Placed) -> Vec<f32> {
const SUB: usize = 4;
let (w, h) = (grid.width, grid.height);
let mut cov = vec![0.0f32; w * h];
let mut edges: Vec<([f64; 2], [f64; 2])> = Vec::new();
for poly in &area.0 {
for ring in std::iter::once(poly.exterior()).chain(poly.interiors()) {
let pts: Vec<[f64; 2]> = ring.coords().map(|c| at.to_px(c.x, c.y)).collect();
for p in pts.windows(2) {
if p[0][1] != p[1][1] {
edges.push((p[0], p[1]));
}
}
}
}
let share = 1.0 / SUB as f32;
let mut xs: Vec<f64> = Vec::new();
for row in 0..h {
for sub in 0..SUB {
let y = row as f64 + (sub as f64 + 0.5) / SUB as f64;
xs.clear();
for (a, b) in &edges {
let (lo, hi) = if a[1] < b[1] { (a, b) } else { (b, a) };
if y >= lo[1] && y < hi[1] {
xs.push(lo[0] + (y - lo[1]) / (hi[1] - lo[1]) * (hi[0] - lo[0]));
}
}
xs.sort_by(f64::total_cmp);
for pair in xs.chunks_exact(2) {
let (x0, x1) = (pair[0].clamp(0.0, w as f64), pair[1].clamp(0.0, w as f64));
if x1 <= x0 {
continue;
}
let (c0, c1) = (x0.floor() as usize, (x1.ceil() as usize).min(w));
for x in c0..c1 {
let covered = (x1.min(x as f64 + 1.0) - x0.max(x as f64)).max(0.0) as f32;
cov[row * w + x] += covered * share;
}
}
}
}
for v in &mut cov {
*v = v.min(1.0);
}
cov
}
pub fn region_from_area(area: &MultiPolygon<f64>, at: &Placed) -> Region {
let mut rings = Vec::new();
for poly in &area.0 {
if poly.exterior().coords().count() >= 4 {
rings.push(ring_from_line(poly.exterior(), true, at));
}
for hole in poly.interiors() {
if hole.coords().count() >= 4 {
rings.push(ring_from_line(hole, false, at));
}
}
}
Region::Rings(rings)
}
fn ring_from_line(ls: &LineString<f64>, exterior: bool, at: &Placed) -> Ring {
Ring {
exterior,
points: ls
.coords()
.map(|c| at.to_px(c.x, c.y))
.collect(),
}
}
pub fn lines(d: &Drawing, at: &Placed) -> Lines {
let mut out: Lines = d
.paths
.iter()
.filter(|l| l.len() >= 2)
.map(|l| placed_line(l, at))
.collect();
for f in &d.fills {
out.extend(f.rings.iter().filter(|r| r.len() >= 2).map(|r| placed_line(r, at)));
}
out
}
pub fn smoothed(grid: &Grid, radius: f64) -> Grid {
let r = radius.round() as usize;
let mut out = grid.clone();
if r == 0 || grid.width == 0 || grid.height == 0 {
return out;
}
let (w, h) = (grid.width, grid.height);
let mut tmp = vec![0.0f32; w * h];
let pass = |src: &[f32], dst: &mut [f32], horizontal: bool| {
let (n, lines) = if horizontal { (w, h) } else { (h, w) };
let at = |line: usize, i: usize| if horizontal { line * w + i } else { i * w + line };
for line in 0..lines {
let mut sum = 0.0f64;
for k in 0..=r.min(n - 1) {
sum += src[at(line, k)] as f64;
}
sum += src[at(line, 0)] as f64 * r as f64;
for i in 0..n {
dst[at(line, i)] = (sum / (2 * r + 1) as f64) as f32;
let add = src[at(line, (i + r + 1).min(n - 1))] as f64;
let drop = src[at(line, i.saturating_sub(r))] as f64;
sum += add - drop;
}
}
};
for _ in 0..3 {
pass(&out.elev, &mut tmp, true);
pass(&tmp, &mut out.elev, false);
}
out
}
pub fn fill_area(d: &Drawing, at: &Placed) -> MultiPolygon<f64> {
use geo::BooleanOps;
let mut out = MultiPolygon::new(vec![]);
for f in &d.fills {
for r in f.rings.iter().filter(|r| r.len() >= 3) {
let mut ring = placed_line(r, at);
ring.close();
let poly = MultiPolygon::new(vec![Polygon::new(ring, vec![])]);
out = out.xor(&poly);
}
}
out
}
fn placed_line(l: &burin_map_core::Line, at: &Placed) -> LineString<f64> {
LineString::new(
l.iter()
.map(|p| {
let (x, y) = at.to_mm(p[0] as f64, p[1] as f64);
Coord { x, y }
})
.collect(),
)
}
pub fn layers(d: &Drawing, at: &Placed) -> Vec<(String, Lines)> {
let mut out: Vec<(String, Lines)> = Vec::new();
let mut start = 0usize;
let mut fills = d.fills.iter().peekable();
let push = |out: &mut Vec<(String, Lines)>, name: String, mine: Lines| match out
.iter_mut()
.find(|(n, _)| *n == name)
{
Some((_, all)) => all.extend(mine),
None => out.push((name, mine)),
};
for (i, (pen, end)) in d.runs.iter().enumerate() {
while fills.peek().is_some_and(|f| f.above <= i) {
let f = fills.next().unwrap();
let name = f.pen.layer.clone().unwrap_or_else(|| "terrain".into());
let mine: Lines = f.rings.iter().filter(|r| r.len() >= 2).map(|r| placed_line(r, at)).collect();
push(&mut out, name, mine);
}
let layer = pen.layer.clone().unwrap_or_else(|| "terrain".into());
let mine: Lines = d.paths[start..*end].iter().filter(|l| l.len() >= 2).map(|l| placed_line(l, at)).collect();
push(&mut out, layer, mine);
start = *end;
}
for f in fills {
let name = f.pen.layer.clone().unwrap_or_else(|| "terrain".into());
let mine: Lines = f.rings.iter().filter(|r| r.len() >= 2).map(|r| placed_line(r, at)).collect();
push(&mut out, name, mine);
}
out
}
pub fn frame(output: &Output) -> MultiPolygon<f64> {
MultiPolygon::new(vec![output.query_polygon()])
}
const TERRAIN_MARGIN: f64 = 0.05;
pub fn bounds_of(output: &Output) -> [f64; 4] {
let r = output.query_polygon().bounding_rect();
let Some(r) = r else {
return [0.0, 0.0, 0.0, 0.0];
};
let (gw, gh) = output.ground_size_m();
let (pad_x, pad_y) = (gw * TERRAIN_MARGIN, gh * TERRAIN_MARGIN);
let g = geographiclib_rs::Geodesic::wgs84();
use geographiclib_rs::DirectGeodesic;
let mid_lat = (r.min().y + r.max().y) / 2.0;
let mid_lon = (r.min().x + r.max().x) / 2.0;
let (_, east_lon): (f64, f64) = g.direct(mid_lat, mid_lon, 90.0, pad_x);
let (north_lat, _): (f64, f64) = g.direct(mid_lat, mid_lon, 0.0, pad_y);
let d_lon = (east_lon - mid_lon).abs();
let d_lat = (north_lat - mid_lat).abs();
[r.min().x - d_lon, r.min().y - d_lat, r.max().x + d_lon, r.max().y + d_lat]
}
pub fn point_in(a: &MultiPolygon<f64>, x: f64, y: f64) -> bool {
let p = geo::Point::new(x, y);
use geo::Contains;
a.0.iter().any(|poly: &Polygon<f64>| poly.contains(&p))
}
pub fn clip_to(lines: &Lines, area: &MultiPolygon<f64>) -> Lines {
geom::clip_lines(lines, area, false)
}
#[cfg(test)]
mod tests {
#[test]
fn a_turned_output_turns_the_grid_with_it() {
let at = Placed { x0: 10.0, y0: 20.0, east: (0.6, -0.5), south: (0.5, 0.6) };
let (x, y) = at.to_mm(30.0, 40.0);
assert!((x - (10.0 + 18.0 + 20.0)).abs() < 1e-9 && (y - (20.0 - 15.0 + 24.0)).abs() < 1e-9);
let back = at.to_px(x, y);
assert!((back[0] - 30.0).abs() < 1e-9 && (back[1] - 40.0).abs() < 1e-9);
}
use super::*;
use crate::profile::ProjectionMode;
fn an_output() -> Output {
Output {
center: (-122.3934746, 37.7955487),
width_mm: 152.4,
height_mm: 101.6,
scale: 10000.0,
bearing: 0.0,
projection: ProjectionMode::Utm,
tile_zoom: None,
}
}
#[test]
fn terrain_is_read_past_the_frame() {
let output = an_output();
let [w, s, e, n] = bounds_of(&output);
let frame = output.bounds();
let [fw, fs, fe, fn_] = frame;
assert!(w < fw && s < fs && e > fe && n > fn_, "padded: {w} {s} {e} {n} vs frame {frame:?}");
let (gw, _gh) = output.ground_size_m();
let g = geographiclib_rs::Geodesic::wgs84();
use geographiclib_rs::DirectGeodesic;
let mid_lat = fs + (fn_ - fs) / 2.0;
let mid_lon = fw + (fe - fw) / 2.0;
let (_, east_lon): (f64, f64) = g.direct(mid_lat, mid_lon, 90.0, gw * TERRAIN_MARGIN);
let want_d_lon = (east_lon - mid_lon).abs();
let got_d_lon = e - fe;
assert!((got_d_lon - want_d_lon).abs() < want_d_lon * 0.1, "margin {got_d_lon} vs {want_d_lon}");
assert!(got_d_lon < gw / 90.0 * 0.2, "a margin, not a second frame");
}
}