From fbf7898e436fde595e78311af6737069e16f6e80 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 05:16:11 -0300 Subject: [PATCH 1/3] perf(render): a generalised relief reads at most 2^24 cells a draw, its work space within its budget, on the draw's threads (#3145) - Past 2^24 cells in view, a block is the mean of a regular sample of its cells rather than of them all, so a whole large DEM's view reads a bounded number of cells. - The filter's line buffers count toward the 64 MiB budget; past it the block size grows by as little as fits. - Blocks sit on the grid, at multiples of their size, so a part of the view is smoothed in the same blocks as the whole. - The blocks' rows are read and filtered along the rows on the draw's threads. Part of #3145. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/raster.rs | 189 +++++++++++++++++++++++++++++------- 1 file changed, 152 insertions(+), 37 deletions(-) diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 2dbb3c35d3..5ee49a34e5 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -598,7 +598,7 @@ fn draw_with( Vec::new() }; let reached = if rotated { &turned } else { &grid }; - bands.first().map(|&b| Smoothed::new(generalize, r, &style.mask, b, full_turn_width(r), reached)) + bands.first().map(|&b| Smoothed::new(generalize, r, &style.mask, b, full_turn_width(r), reached, threads)) } _ => None, }, @@ -868,10 +868,23 @@ fn cells_reached(r: &Raster, grid: &[Option<(f64, f64)>], wrap_width: Option, tmp: &mut /// The heights a generalised Shaded Relief (#3145) lights, for one draw: over the cells the view /// reaches, and the filter's reach past them, the valid heights smoothed with a Gaussian of a /// size in metres (three box passes each way), no data left out (each height is the filter's -/// weighted mean of the valid ones). With more cells than [`MAX_SMOOTH_CELLS`], or a Gaussian -/// wider than [`MAX_SIGMA_CELLS`] cells, it smooths the mean heights of square blocks of them and -/// reads between the blocks' centres. +/// weighted mean of the valid ones). With more cells than [`MAX_SMOOTH_CELLS`] (its work space +/// counted), or a Gaussian wider than [`MAX_SIGMA_CELLS`] cells, it smooths square blocks of cells +/// and reads between the blocks' centres. A block is the mean height of its cells, or, past +/// [`MAX_SMOOTH_READS`] cells, of a regular sample of them. Blocks sit on the grid, at multiples of +/// their size, so where the view is doesn't move them. struct Smoothed { /// The first column and row of the cells it covers, and how many columns and rows of them. origin: (i64, i64), @@ -957,11 +972,22 @@ struct Smoothed { } impl Smoothed { - fn new(metres: f64, r: &Raster, mask: &RasterMask, band: usize, wrap_width: Option, grid: &[Option<(f64, f64)>]) -> Smoothed { - Smoothed::within(metres, r, mask, band, wrap_width, grid, MAX_SMOOTH_CELLS) + fn new( + metres: f64, + r: &Raster, + mask: &RasterMask, + band: usize, + wrap_width: Option, + grid: &[Option<(f64, f64)>], + threads: usize, + ) -> Smoothed { + let limits = SmoothLimits { cells: MAX_SMOOTH_CELLS, reads: MAX_SMOOTH_READS }; + Smoothed::within(metres, r, mask, band, wrap_width, grid, limits, threads) } - /// [`Smoothed::new`] in at most `max_cells` blocks. + /// [`Smoothed::new`] in at most `limits.cells` blocks, or their worth of work space, reading at + /// most about `limits.reads` cells, the rows read and filtered on `threads` threads. + #[expect(clippy::too_many_arguments, reason = "new's settings, and the limits and threads tests choose")] fn within( metres: f64, r: &Raster, @@ -969,9 +995,10 @@ impl Smoothed { band: usize, wrap_width: Option, grid: &[Option<(f64, f64)>], - max_cells: usize, + limits: SmoothLimits, + threads: usize, ) -> Smoothed { - let (sy, max_cells) = (generalise_sigma(metres, r, 0.0).1, max_cells.max(1)); + let (sy, max_cells, threads) = (generalise_sigma(metres, r, 0.0).1, limits.cells.max(1), threads.max(1)); let mut step = 1i64; loop { // The filter's reach: along the rows, as far as it is widest, at the rows nearest a pole. @@ -987,36 +1014,59 @@ impl Smoothed { } let reach_x = smoothing_reach(widest, step); let ((c0, c1), (r0, r1)) = cells_reached(r, grid, wrap_width, (reach_x, reach_y)); + // On the grid's multiples of the block's size. + let (c0, r0) = (c0.div_euclid(step) * step, r0.div_euclid(step) * step); let span = ((c1 - c0).max(0), (r1 - r0).max(0)); let (cols, rows) = ((span.0 + step - 1) / step, (span.1 + step - 1) / step); - let blocks = usize::try_from(cols.saturating_mul(rows)).unwrap_or(usize::MAX); - if blocks > max_cells { - step *= ((blocks as f64 / max_cells as f64).sqrt().ceil() as i64).max(2); + // In `f64`s: the blocks' sums and counts, and each thread's line and the passes' two + // copies of it, as long as the longest row or column with the boxes' reach either side. + let line = cols.max(rows).saturating_add(2 * (reach_x.max(reach_y) / step + 1)); + let words = cols.saturating_mul(rows).saturating_mul(2).saturating_add(line.saturating_mul(3 * threads as i64 + 3)); + let budget = 2 * max_cells as i64; + if words > budget { + step = ((step as f64 * (words as f64 / budget as f64).sqrt()).ceil() as i64).max(step + 1); continue; } - // Each block's sum of valid heights and their count, then both smoothed alike. + let blocks = (cols * rows) as usize; + // Every `every`-th cell of a block each way, so as to read at most about the cap. + let per_block = (limits.reads.max(1) / blocks.max(1)).max(1) as f64; + let every = ((step as f64 / per_block.sqrt()).ceil() as i64).clamp(1, step); + // Each block's sum of the valid heights read and their count, then both smoothed alike. let (mut sums, mut counts) = (vec![0.0; blocks], vec![0.0; blocks]); - for j in 0..span.1 { - for i in 0..span.0 { - if let Some(v) = value(r, mask, band, c0 + i, r0 + j, wrap_width) { - let at = ((j / step) * cols + i / step) as usize; - sums[at] += f64::from(v); - counts[at] += 1.0; + let width = cols.max(1) as usize; + let band_rows = (rows.max(1) as usize).div_ceil(threads); + each_chunk( + threads, + sums.chunks_mut(band_rows * width).zip(counts.chunks_mut(band_rows * width)).enumerate(), + |(k, (sums, counts))| { + let (mut buf, mut tmp) = (Vec::new(), Vec::new()); + for (n, (sums, counts)) in sums.chunks_mut(width).zip(counts.chunks_mut(width)).enumerate() { + let j = (k * band_rows + n) as i64; + let first = every / 2; + for (i, (sum, count)) in sums.iter_mut().zip(counts.iter_mut()).enumerate() { + let (bc, br) = (c0 + i as i64 * step, r0 + j * step); + for row in (br + first..(br + step).min(r1)).step_by(every as usize) { + for col in (bc + first..(bc + step).min(c1)).step_by(every as usize) { + if let Some(v) = value(r, mask, band, col, row, wrap_width) { + (*sum, *count) = (*sum + f64::from(v), *count + 1.0); + } + } + } + } + let radii = box_radii(sx((r0 + j * step) as f64 + step as f64 / 2.0) / step as f64); + box_passes(sums, radii, &mut buf, &mut tmp); + box_passes(counts, radii, &mut buf, &mut tmp); } - } - } + }, + ); let (mut line, mut buf, mut tmp) = (Vec::new(), Vec::new(), Vec::new()); for grid in [&mut sums, &mut counts] { - for (j, row) in grid.chunks_mut(cols.max(1) as usize).enumerate() { - let centre = (r0 + j as i64 * step) as f64 + step as f64 / 2.0; - box_passes(row, box_radii(sx(centre) / step as f64), &mut buf, &mut tmp); - } - for c in 0..cols as usize { + for c in 0..width { line.clear(); - line.extend(grid.iter().skip(c).step_by(cols as usize).copied()); + line.extend(grid.iter().skip(c).step_by(width).copied()); box_passes(&mut line, box_radii(sy / step as f64), &mut buf, &mut tmp); for (k, v) in line.iter().enumerate() { - grid[k * cols as usize + c] = *v; + grid[k * width + c] = *v; } } } @@ -2495,15 +2545,15 @@ mod tests { let mask = RasterMask::default(); for r in [ valley_in_metres(), - gullied_valley(Crs::LonLat, GeoTransform { origin_x: -180.0, origin_y: 2.4, pixel_width: 5.625, pixel_height: -0.1 }), + gullied_valley(Crs::LonLat, GeoTransform { origin_x: -180.0, origin_y: 12.0, pixel_width: 5.625, pixel_height: -0.5 }), ] { let (cols, rows, wrap) = (i64::from(r.width), i64::from(r.height), full_turn_width(&r)); let at = |c: i64, row: i64| Some((c as f64 + 0.5, row as f64 + 0.5)); let all: Vec<_> = (0..cols * rows).map(|i| at(i % cols, i / cols)).collect(); let west: Vec<_> = (0..rows).flat_map(|row| [at(0, row), at(1, row)]).collect(); let metres = 3.0 * r.cell_size_ground_m().0; - let whole = Smoothed::new(metres, &r, &mask, 0, wrap, &all); - let part = Smoothed::new(metres, &r, &mask, 0, wrap, &west); + let whole = Smoothed::new(metres, &r, &mask, 0, wrap, &all, 1); + let part = Smoothed::new(metres, &r, &mask, 0, wrap, &west, 1); assert!(part.span.0 < cols + 2 * wrap.unwrap_or(0), "{:?}: a part", r.crs); for (c, row) in (0..rows).flat_map(|row| (0..2).map(move |c| (c, row))) { let (a, b) = (whole.height((c, row), wrap), part.height((c, row), wrap)); @@ -2516,8 +2566,17 @@ mod tests { assert!(a.zip(b).is_some_and(|(a, b)| (a - b).abs() < 1e-9), "the seam's other side: {a:?} {b:?}"); } // In blocks of two cells or more, with the size of the Gaussian twice as wide. - let blocks = Smoothed::within(2.0 * metres, &r, &mask, 0, wrap, &all, (cols * rows / 3) as usize); - let fine = Smoothed::new(2.0 * metres, &r, &mask, 0, wrap, &all); + let blocks = Smoothed::within( + 2.0 * metres, + &r, + &mask, + 0, + wrap, + &all, + SmoothLimits { cells: (cols * rows / 3) as usize, reads: MAX_SMOOTH_READS }, + 1, + ); + let fine = Smoothed::new(2.0 * metres, &r, &mask, 0, wrap, &all, 1); assert!(blocks.step >= 2 && blocks.heights.len() <= (cols * rows / 3) as usize, "{}", blocks.step); for (c, row) in (8..rows - 8).flat_map(|row| (8..cols - 8).map(move |c| (c, row))) { let (a, b) = (fine.height((c, row), wrap).unwrap(), blocks.height((c, row), wrap).unwrap()); @@ -2563,7 +2622,7 @@ mod tests { fn a_generalisation_past_the_widest_kernel_is_smoothed_in_blocks() { let r = valley_in_metres(); let all: Vec<_> = (0..64 * 48).map(|i| Some(((i % 64) as f64 + 0.5, (i / 64) as f64 + 0.5))).collect(); - let at = |metres| Smoothed::new(metres, &r, &RasterMask::default(), 0, None, &all); + let at = |metres| Smoothed::new(metres, &r, &RasterMask::default(), 0, None, &all, 1); let (widest, past) = (at(MAX_SIGMA_CELLS * 30.0), at(30_000.0)); assert_eq!(widest.step, 1); assert!(past.step >= 4, "{}", past.step); @@ -2581,7 +2640,7 @@ mod tests { assert_eq!(wrap, Some(4)); let metres = 2.5 * generalise_sigma(1.0, &r, 1.5).0.recip(); let all: Vec<_> = (0..12).map(|i| Some(((i % 4) as f64 + 0.5, (i / 4) as f64 + 0.5))).collect(); - let smoothed = Smoothed::new(metres, &r, &RasterMask::default(), 0, wrap, &all); + let smoothed = Smoothed::new(metres, &r, &RasterMask::default(), 0, wrap, &all, 1); // The three boxes' kernel, wrapped round the four columns. let mut kernel = vec![1.0]; for rad in box_radii(2.5) { @@ -2602,6 +2661,62 @@ mod tests { } } + /// Past the cap on reads, a block is the mean of a regular sample of its cells: with a read a + /// block, its middle cell. Here the cells between the middles stand a kilometre up, and no + /// height comes near them; with reads to spare, every cell counts. + #[test] + fn past_the_cap_a_view_reads_one_cell_a_block() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 60.0 * 30.0, pixel_width: 30.0, pixel_height: -30.0 }; + let data = (0..60 * 60).map(|i| if i % 60 % 3 == 1 && i / 60 % 3 == 1 { 500.0 + (i % 60) as f32 } else { 1500.0 }).collect(); + let r = Raster::new("middles", 60, 60, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + let all: Vec<_> = (0..60 * 60).map(|i| Some(((i % 60) as f64 + 0.5, (i / 60) as f64 + 0.5))).collect(); + let at = |reads| Smoothed::within(30.0, &r, &RasterMask::default(), 0, None, &all, SmoothLimits { cells: 500, reads }, 1); + let (sampled, every) = (at(400), at(3600)); + assert_eq!((sampled.step, every.step), (3, 3)); + for (c, row) in (0..60 * 60).map(|i| (i % 60, i / 60)) { + let h = sampled.height((c, row), None).unwrap(); + assert!((500.0..=560.0).contains(&h), "{c}, {row}: {h}"); + assert!(every.height((c, row), None).unwrap() > 1300.0, "{c}, {row}: every cell"); + } + } + + /// The filter's work space counts toward the cap too: a view one block wide and many tall + /// (each pass's line as long as the view) is smoothed in larger blocks. + #[test] + fn the_filters_lines_count_toward_the_cap() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 4000.0 * 30.0, pixel_width: 30.0, pixel_height: -30.0 }; + let r = Raster::new("tall", 2, 4000, vec![vec![100.0; 8000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + let all: Vec<_> = (0..8000).map(|i| Some(((i % 2) as f64 + 0.5, (i / 2) as f64 + 0.5))).collect(); + let limits = SmoothLimits { cells: 8000, reads: MAX_SMOOTH_READS }; + let smoothed = Smoothed::within(30.0, &r, &RasterMask::default(), 0, None, &all, limits, 1); + assert!(smoothed.step >= 2, "{}", smoothed.step); + assert!(smoothed.height((1, 2000), None).is_some_and(|h| (h - 100.0).abs() < 1e-9)); + } + + /// Blocks sit on the grid, not on the view: a part of the view far from the grid's edges is + /// smoothed in the same blocks as the whole, so its heights are the whole's. On any number of + /// threads, the same heights. + #[test] + fn blocks_are_the_grids_wherever_the_view_is() { + let (cols, rows) = (2400i64, 8i64); + let gt = GeoTransform { origin_x: 0.0, origin_y: rows as f64 * 30.0, pixel_width: 30.0, pixel_height: -30.0 }; + let data = (0..cols * rows).map(|i| 500.0 + 40.0 * ((i % cols) as f32 * 0.05).sin() + (i / cols) as f32).collect(); + let r = Raster::new("long", cols as u32, rows as u32, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + let at = |c: i64, row: i64| Some((c as f64 + 0.5, row as f64 + 0.5)); + let all: Vec<_> = (0..cols * rows).map(|i| at(i % cols, i / cols)).collect(); + let part: Vec<_> = (0..rows).flat_map(|row| (1199..1203).map(move |c| at(c, row))).collect(); + let mask = RasterMask::default(); + let whole = Smoothed::new(9000.0, &r, &mask, 0, None, &all, 1); + let small = Smoothed::new(9000.0, &r, &mask, 0, None, &part, 1); + assert!(whole.step >= 2 && small.step == whole.step && small.origin.0 > 0, "{} {} {:?}", whole.step, small.step, small.origin); + let threads = Smoothed::new(9000.0, &r, &mask, 0, None, &all, 4); + for (c, row) in (0..rows).flat_map(|row| (1199..1203).map(move |c| (c, row))) { + let (a, b) = (whole.height((c, row), None).unwrap(), small.height((c, row), None).unwrap()); + assert!((a - b).abs() < 1e-9, "{c}, {row}: {a} {b}"); + assert_eq!(threads.height((c, row), None), Some(a), "{c}, {row}: threads"); + } + } + /// Three box passes add up to about the Gaussian's spread (within a fifth of a cell from one /// cell up to the widest), none under half a cell or for a size that isn't one. #[test] From 4a9e4dd0719d23295eadfb6331f17d3fba517462 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 06:13:56 -0300 Subject: [PATCH 2/3] fix(render): a generalised relief's blocks don't depend on the threads, its sample keeps within the reads, and a tiny budget ends (#3145) From review: - The block size is chosen for one worker; more workers run only where their lines fit the budget, so a raster is smoothed alike on any number of threads. - A block's sample is counted as it is read, and made sparser until the reads fit the cap (8-cell blocks could read 17.6 Mi cells). - Past the grid's size a block stops growing, so a budget below the work space's floor ends. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/raster.rs | 87 ++++++++++++++++++++++++++++++++----- 1 file changed, 76 insertions(+), 11 deletions(-) diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 5ee49a34e5..c97329be67 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -951,6 +951,24 @@ fn box_passes(line: &mut [f64], radii: [usize; 3], buf: &mut Vec, tmp: &mut line.copy_from_slice(&buf[reach..reach + line.len()]); } +/// How sparse the sample of a block of `step` cells a side is: every `every`-th cell each way, from +/// `every / 2`, as dense as keeps `blocks` such blocks within `reads` cells read, the cells counted +/// as the sample reads them; every cell when they fit, one a block at the sparsest. +fn sample_every(step: i64, blocks: usize, reads: usize) -> i64 { + let read = |every: i64| { + let per_side = (step - every / 2 + every - 1) / every; + i64::try_from(blocks).unwrap_or(i64::MAX).saturating_mul(per_side.saturating_mul(per_side)) + }; + let reads = i64::try_from(reads).unwrap_or(i64::MAX); + let per_block = (reads / i64::try_from(blocks.max(1)).unwrap_or(i64::MAX)).max(1) as f64; + // From just under the estimate, as few steps as reach it. + let mut every = (((step as f64 / per_block.sqrt()).ceil() as i64) - 1).clamp(1, step.max(1)); + while every < step && read(every) > reads { + every += 1; + } + every +} + /// The heights a generalised Shaded Relief (#3145) lights, for one draw: over the cells the view /// reaches, and the filter's reach past them, the valid heights smoothed with a Gaussian of a /// size in metres (three box passes each way), no data left out (each height is the filter's @@ -1018,25 +1036,29 @@ impl Smoothed { let (c0, r0) = (c0.div_euclid(step) * step, r0.div_euclid(step) * step); let span = ((c1 - c0).max(0), (r1 - r0).max(0)); let (cols, rows) = ((span.0 + step - 1) / step, (span.1 + step - 1) / step); - // In `f64`s: the blocks' sums and counts, and each thread's line and the passes' two - // copies of it, as long as the longest row or column with the boxes' reach either side. + // In `f64`s: the blocks' sums and counts, the passes down the columns (a line and its + // two copies), and a worker's two copies of a row, each line as long as the longest row + // or column with the boxes' reach either side. The block size is chosen for one worker, + // so it is the same on any number of threads; more work only where their lines fit. + // Past the grid's size a block can't grow any use, whatever the budget. let line = cols.max(rows).saturating_add(2 * (reach_x.max(reach_y) / step + 1)); - let words = cols.saturating_mul(rows).saturating_mul(2).saturating_add(line.saturating_mul(3 * threads as i64 + 3)); + let base = cols.saturating_mul(rows).saturating_mul(2).saturating_add(line.saturating_mul(3)); let budget = 2 * max_cells as i64; - if words > budget { + let words = base.saturating_add(line.saturating_mul(2)); + if words > budget && step <= i64::from(r.width.max(r.height)) { step = ((step as f64 * (words as f64 / budget as f64).sqrt()).ceil() as i64).max(step + 1); continue; } + let workers = (budget.saturating_sub(base) / line.saturating_mul(2).max(1)).clamp(1, threads as i64) as usize; let blocks = (cols * rows) as usize; - // Every `every`-th cell of a block each way, so as to read at most about the cap. - let per_block = (limits.reads.max(1) / blocks.max(1)).max(1) as f64; - let every = ((step as f64 / per_block.sqrt()).ceil() as i64).clamp(1, step); + // Every `every`-th cell of a block each way, so as to read at most the cap. + let every = sample_every(step, blocks, limits.reads.max(1)); // Each block's sum of the valid heights read and their count, then both smoothed alike. let (mut sums, mut counts) = (vec![0.0; blocks], vec![0.0; blocks]); let width = cols.max(1) as usize; - let band_rows = (rows.max(1) as usize).div_ceil(threads); + let band_rows = (rows.max(1) as usize).div_ceil(workers); each_chunk( - threads, + workers, sums.chunks_mut(band_rows * width).zip(counts.chunks_mut(band_rows * width)).enumerate(), |(k, (sums, counts))| { let (mut buf, mut tmp) = (Vec::new(), Vec::new()); @@ -2539,7 +2561,8 @@ mod tests { /// The smoothed heights over a part of the view are the whole grid's (the filter's reach past /// it is read), across a whole turn's seam too; in blocks, when too many cells are in view, - /// they stay close to them; outside the cells covered there are none. + /// they stay within a metre and a half of them (blocks of 3 cells, a Gaussian of 6, gullies 4 m + /// deep); outside the cells covered there are none. #[test] fn smoothed_heights_in_part_of_the_view_are_the_whole_grids() { let mask = RasterMask::default(); @@ -2580,7 +2603,7 @@ mod tests { assert!(blocks.step >= 2 && blocks.heights.len() <= (cols * rows / 3) as usize, "{}", blocks.step); for (c, row) in (8..rows - 8).flat_map(|row| (8..cols - 8).map(move |c| (c, row))) { let (a, b) = (fine.height((c, row), wrap).unwrap(), blocks.height((c, row), wrap).unwrap()); - assert!((a - b).abs() < 1.0, "{c}, {row}: {a} {b}"); + assert!((a - b).abs() < 1.5, "{c}, {row}: {a} {b}"); } } } @@ -2717,6 +2740,48 @@ mod tests { } } + /// A view smoothed within a tight budget keeps its blocks on any number of threads: what the + /// threads' lines need comes out of the workers, not the block size (#3435 review). With a + /// budget below what any block size needs, it still ends, in blocks the grid's size. + #[test] + fn the_budget_sets_the_blocks_whatever_the_threads() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 40.0 * 30.0, pixel_width: 30.0, pixel_height: -30.0 }; + let data = (0..40 * 40).map(|i| if i == 20 * 40 + 20 { 100.0 } else { 0.0 }).collect(); + let r = Raster::new("spike", 40, 40, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + let all: Vec<_> = (0..40 * 40).map(|i| Some(((i % 40) as f64 + 0.5, (i / 40) as f64 + 0.5))).collect(); + let at = |cells, threads| { + Smoothed::within(30.0, &r, &RasterMask::default(), 0, None, &all, SmoothLimits { cells, reads: MAX_SMOOTH_READS }, threads) + }; + let (one, eight) = (at(1800, 1), at(1800, 8)); + assert_eq!((one.step, eight.step), (1, 1)); + assert_eq!(one.heights, eight.heights); + for threads in [1, 8] { + let least = at(1, threads); + assert!(least.step >= 1 && least.step <= 64, "{threads}: {}", least.step); + assert!(least.height((20, 20), None).is_some_and(f64::is_finite), "{threads}"); + } + } + + /// The cells read a block, counted as the sample reads them, keep the reads within the cap; + /// a sample no sparser than it needs, and every cell when they fit (#3435 review). + #[test] + fn a_blocks_sample_keeps_the_reads_within_the_cap() { + let read = |step: i64, every: i64| { + let per_side = (step - every / 2 + every - 1) / every; + per_side * per_side + }; + for (step, blocks, reads) in + [(8, 1_960_000, MAX_SMOOTH_READS), (3, 400, 3600), (3, 400, 400), (7, 1000, 9000), (16, 70_000, MAX_SMOOTH_READS)] + { + let every = sample_every(step, blocks, reads); + assert!(blocks as i64 * read(step, every) <= reads as i64 || every == step, "{step} {blocks} {reads}: {every}"); + if every > 1 { + assert!(blocks as i64 * read(step, every - 1) > reads as i64, "{step} {blocks} {reads}: {every} could be less"); + } + } + assert_eq!(sample_every(3, 400, 3600), 1); + } + /// Three box passes add up to about the Gaussian's spread (within a fifth of a cell from one /// cell up to the widest), none under half a cell or for a size that isn't one. #[test] From a85cd76879f44ad184aea327f4f6589af8de0453 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 06:27:42 -0300 Subject: [PATCH 3/3] fix(render): a view narrower than a generalised relief's block reads its cells (#3145) From review: a raster one cell wide, smoothed in blocks, was sampled from past its edge, so no cell was read and its light was drawn flat. Every cell is read when the cells in view fit the cap, and a block's sample starts within the block where it is narrower. Part of #3145. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/raster.rs | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index c97329be67..7124421885 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -1052,7 +1052,8 @@ impl Smoothed { let workers = (budget.saturating_sub(base) / line.saturating_mul(2).max(1)).clamp(1, threads as i64) as usize; let blocks = (cols * rows) as usize; // Every `every`-th cell of a block each way, so as to read at most the cap. - let every = sample_every(step, blocks, limits.reads.max(1)); + let cells = span.0.saturating_mul(span.1); + let every = if cells <= limits.reads as i64 { 1 } else { sample_every(step, blocks, limits.reads.max(1)) }; // Each block's sum of the valid heights read and their count, then both smoothed alike. let (mut sums, mut counts) = (vec![0.0; blocks], vec![0.0; blocks]); let width = cols.max(1) as usize; @@ -1064,11 +1065,13 @@ impl Smoothed { let (mut buf, mut tmp) = (Vec::new(), Vec::new()); for (n, (sums, counts)) in sums.chunks_mut(width).zip(counts.chunks_mut(width)).enumerate() { let j = (k * band_rows + n) as i64; - let first = every / 2; for (i, (sum, count)) in sums.iter_mut().zip(counts.iter_mut()).enumerate() { let (bc, br) = (c0 + i as i64 * step, r0 + j * step); - for row in (br + first..(br + step).min(r1)).step_by(every as usize) { - for col in (bc + first..(bc + step).min(c1)).step_by(every as usize) { + let (ce, re) = ((bc + step).min(c1), (br + step).min(r1)); + // From `every / 2` in, or a block's last cell where it is narrower. + let (fc, fr) = ((every / 2).min(ce - bc - 1).max(0), (every / 2).min(re - br - 1).max(0)); + for row in (br + fr..re).step_by(every as usize) { + for col in (bc + fc..ce).step_by(every as usize) { if let Some(v) = value(r, mask, band, col, row, wrap_width) { (*sum, *count) = (*sum + f64::from(v), *count + 1.0); } @@ -2762,6 +2765,24 @@ mod tests { } } + /// A view narrower than a block (a raster one cell wide) reads its cells: every one when they + /// fit the cap, and a sample that reaches into each block that has cells when they don't + /// (#3435 review: a column one cell wide was sampled past its edge and drawn flat). + #[test] + fn a_view_narrower_than_a_block_samples_its_cells() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 3000.0 * 30.0, pixel_width: 30.0, pixel_height: -30.0 }; + let r = Raster::new("column", 1, 3000, vec![vec![100.0; 3000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + let all: Vec<_> = (0..3000).map(|row| Some((0.5, row as f64 + 0.5))).collect(); + for reads in [3000, 700] { + let smoothed = Smoothed::within(30.0, &r, &RasterMask::default(), 0, None, &all, SmoothLimits { cells: 400, reads }, 1); + assert!(smoothed.step >= 2, "{reads}: {}", smoothed.step); + for row in (0..3000).step_by(7) { + let h = smoothed.height((0, row), None); + assert!(h.is_some_and(|h| (h - 100.0).abs() < 1e-9), "{reads}: {row}: {h:?}"); + } + } + } + /// The cells read a block, counted as the sample reads them, keep the reads within the cap; /// a sample no sparser than it needs, and every cell when they fit (#3435 review). #[test]