Skip to content
113 changes: 97 additions & 16 deletions crates/map/src/generalize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,70 @@ const SMOOTHED_FLOOR: usize = 768 << 20;
/// renderer does, and reads between the blocks' centres. The grid's edges stop the filter, a
/// whole turn's too. It holds what [`smoothing_bytes`] counts (about 3 times a `Float32` layer's
/// band for a grid many cells across both ways, up to about 9 times for one a row or a column
/// wide, whose filter lines are as long as itself), then the band, `together` times when that many
/// smoothings run at once (a relief's cast shadows and its sky): past what
/// [`rustgis_data::memory::planned`] gives, it is refused ([`Unlit::TooLarge`]). It looks at `stop`
/// before it holds anything and at each row and column ([`Unlit::Stopped`]).
pub fn smoothed(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop: &AtomicBool, together: usize) -> Result<Raster, Unlit> {
/// wide, whose filter lines are as long as itself), then the band while `traces` traces read it,
/// each with its own copy of the heights and its grid: past what [`traced_bytes`] counts for that
/// against [`rustgis_data::memory::planned`], it is refused ([`Unlit::TooLarge`]). It looks at
/// `stop` before it holds anything and at each row and column ([`Unlit::Stopped`]).
pub fn smoothed(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop: &AtomicBool, traces: usize) -> Result<Raster, Unlit> {
let limit = rustgis_data::memory::planned(SMOOTHED_FLOOR, usize::MAX, 1);
smoothed_within(r, band, mask, metres, stop, limit, together)
#[cfg(test)]
let limit = tests_hooks::limit(&r.name).unwrap_or(limit);
#[cfg(test)]
tests_hooks::ran(&r.name);
smoothed_within(r, band, mask, metres, stop, limit, traces)
}

/// The bytes a generalised relief's light grids hold for `r` over `metres` with `traces` traces
/// reading its smoothed heights: the smoothing's ([`smoothing_bytes`]), and each trace's own copy
/// of the heights (4 bytes a cell) and its grid (1).
pub fn traced_bytes(r: &Raster, metres: f64, traces: usize) -> usize {
let cells = (r.width as usize).saturating_mul(r.height as usize);
smoothing_bytes(r, metres).saturating_add(traces.max(1).saturating_mul(5).saturating_mul(cells))
}

/// Whether `traces` traces of `r` smoothed over `metres`, reading one smoothing together (a grid
/// that reads another's), fit the memory planned: [`traced_bytes`] for them all.
pub fn traces_fit(r: &Raster, metres: f64, traces: usize) -> Result<(), Unlit> {
let limit = rustgis_data::memory::planned(SMOOTHED_FLOOR, usize::MAX, 1);
#[cfg(test)]
let limit = tests_hooks::limit(&r.name).unwrap_or(limit);
let bytes = traced_bytes(r, metres, traces);
if bytes > limit { Err(Unlit::TraceTooLarge { traces, bytes, limit }) } else { Ok(()) }
}

/// Test hooks, by the raster's name so tests running at once don't meet: a limit in place of the
/// memory planned, and how many times a raster was smoothed.
#[cfg(test)]
mod tests_hooks {
use std::sync::Mutex;

static LIMITS: Mutex<Vec<(String, usize)>> = Mutex::new(Vec::new());
static RUNS: Mutex<Vec<String>> = Mutex::new(Vec::new());

pub(super) fn limit(name: &str) -> Option<usize> {
LIMITS.lock().ok()?.iter().find(|(n, _)| n == name).map(|(_, l)| *l)
}

pub(super) fn ran(name: &str) {
if let Ok(mut runs) = RUNS.lock() {
runs.push(name.into());
}
}

pub(crate) fn limit_for(name: &str, bytes: usize) {
if let Ok(mut limits) = LIMITS.lock() {
limits.push((name.into(), bytes));
}
}

pub(crate) fn smoothings_of(name: &str) -> usize {
RUNS.lock().map_or(0, |runs| runs.iter().filter(|n| *n == name).count())
}
}

#[cfg(test)]
pub(crate) use tests_hooks::{limit_for, smoothings_of};

/// The blocks, rows and cells to a block's side of `r` smoothed over `metres`.
fn blocks_of(r: &Raster, metres: f64) -> (i64, i64, i64) {
let (w, h) = (i64::from(r.width), i64::from(r.height));
Expand All @@ -117,7 +172,7 @@ fn line_cells(cols: i64, rows: i64) -> usize {
/// the smoothed band (4 a cell), and the filter's line with its two copies (24 a cell of it).
pub fn smoothing_bytes(r: &Raster, metres: f64) -> usize {
let (cols, rows, _) = blocks_of(r, metres);
let cells = r.width as usize * r.height as usize;
let cells = (r.width as usize).saturating_mul(r.height as usize);
(8 * (cols * rows) as usize).saturating_add(16 * cols as usize).saturating_add(4 * cells).saturating_add(24 * line_cells(cols, rows))
}

Expand Down Expand Up @@ -163,20 +218,20 @@ fn block_sums(
Ok(())
}

/// [`smoothed`] within `limit` bytes for `together` smoothings at once.
/// [`smoothed`] within `limit` bytes for `traces` traces reading it.
fn smoothed_within(
r: &Raster,
band: usize,
mask: &RasterMask,
metres: f64,
stop: &AtomicBool,
limit: usize,
together: usize,
traces: usize,
) -> Result<Raster, Unlit> {
let stopped = || stop.load(Ordering::Relaxed);
let (w, h) = (i64::from(r.width), i64::from(r.height));
let cells = usize::try_from(w * h).map_err(|_| Unlit::NoMemory)?;
let bytes = smoothing_bytes(r, metres).saturating_mul(together.max(1));
let bytes = traced_bytes(r, metres, traces);
if bytes > limit {
return Err(Unlit::TooLarge { bytes, limit });
}
Expand Down Expand Up @@ -302,24 +357,50 @@ mod tests {
assert_eq!(counts[0], (side * side) as f32);
}

/// The traces' phase is planned for too: each trace's own copy of the heights and its grid,
/// 5 bytes a cell, beside the smoothing (#3448 review).
#[test]
fn the_plan_counts_each_trace_beside_the_smoothing() {
let gt = GeoTransform { origin_x: 0.0, origin_y: 100.0 * 30.0, pixel_width: 30.0, pixel_height: -30.0 };
let r = Raster::new("even", 100, 100, vec![vec![250.0; 10_000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap();
let smoothing = smoothing_bytes(&r, 90.0);
assert_eq!(traced_bytes(&r, 90.0, 1), smoothing + 5 * 10_000);
assert_eq!(traced_bytes(&r, 90.0, 2), smoothing + 10 * 10_000);
}

/// A grid that reads another's smoothed heights plans for its own trace: refused when the
/// trace's copy and grid don't fit (#3466 review).
#[test]
fn a_grid_reading_shared_heights_plans_its_own_trace() {
let gt = GeoTransform { origin_x: 0.0, origin_y: 100.0 * 30.0, pixel_width: 30.0, pixel_height: -30.0 };
let r = Raster::new("joins", 100, 100, vec![vec![250.0; 10_000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap();
let two = traced_bytes(&r, 90.0, 2);
limit_for("joins", two - 1);
assert_eq!(traces_fit(&r, 90.0, 2).err(), Some(Unlit::TraceTooLarge { traces: 2, bytes: two, limit: two - 1 }));
let ok =
Raster::new("joins fits", 100, 100, vec![vec![250.0; 10_000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap();
limit_for("joins fits", two);
assert!(traces_fit(&ok, 90.0, 2).is_ok());
}

/// A grid whose smoothing would hold more than the memory planned for it is refused, saying
/// how much it needs and how much is planned, rather than run out of memory partway
/// (AGENTS.md). All it holds is counted: the blocks, the band, and the filter's three lines,
/// which a grid one row tall makes as long as itself; and as many times as smoothings run
/// together, a relief's cast shadows and its sky each smoothing its grid (#3448 review).
/// which a grid one row tall makes as long as itself; and each trace that reads it, a
/// relief's cast shadows and its sky (#3448 review).
#[test]
fn a_grid_past_the_memory_planned_is_refused() {
let even = |w: u32, h: u32| {
let gt = GeoTransform { origin_x: 0.0, origin_y: f64::from(h) * 30.0, pixel_width: 30.0, pixel_height: -30.0 };
Raster::new("even", w, h, vec![vec![250.0; (w * h) as usize]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap()
};
let at =
|r: &Raster, limit, together| smoothed_within(r, 0, &RasterMask::default(), 90.0, &AtomicBool::new(false), limit, together);
let at = |r: &Raster, limit, traces| smoothed_within(r, 0, &RasterMask::default(), 90.0, &AtomicBool::new(false), limit, traces);
let square = even(100, 100);
let need = smoothing_bytes(&square, 90.0);
let need = traced_bytes(&square, 90.0, 1);
assert_eq!(at(&square, need - 1, 1).err(), Some(Unlit::TooLarge { bytes: need, limit: need - 1 }));
assert!(at(&square, need, 1).is_ok());
assert_eq!(at(&square, need, 2).err(), Some(Unlit::TooLarge { bytes: 2 * need, limit: need }));
let two = traced_bytes(&square, 90.0, 2);
assert_eq!(at(&square, need, 2).err(), Some(Unlit::TooLarge { bytes: two, limit: need }));
// A row 4000 cells long: its lines are 24 bytes a cell, past the 12 a cell of the rest.
let row = even(4000, 1);
assert!(smoothing_bytes(&row, 90.0) >= 36 * 4000, "{}", smoothing_bytes(&row, 90.0));
Expand Down
Loading
Loading