From 054f15bf594930044036ede3047bc6cf46b2463f Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 21:05:56 -0300 Subject: [PATCH 1/4] fix(render): Shaded Relief blends its light between cells with Bilinear (#1880) With Bilinear resampling, a Shaded Relief pixel now takes the light of the four cells around it (hillshade times what the cast shadows leave) and blends them bilinearly, as the band values already are. A cell outside the grid, no data or masked is left out and the other weights scaled up; a whole-turn grid wraps. Each screen row keeps the last four lights. Nearest draws the same pixels as before: one cell's light now comes from one helper, Pass1::light, which the blend calls for each of the four cells. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/raster.rs | 169 ++++++++++++++++++++++++++++++++---- docs/user-guide/data.md | 5 ++ 2 files changed, 157 insertions(+), 17 deletions(-) diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 237d55d0cf..8f323e02af 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -671,6 +671,8 @@ impl Pass1<'_> { } // Nearest sampling: the last cell read, and the pixel it was read for. let mut last: Option<((i64, i64), usize)> = None; + // Bilinear relief: the last four cells' lights, by the first's column and row. + let mut quad: Option<((i64, i64), [Option; 4])> = None; for dx in 0..bw { let px = self.x0 + dx; let pos = match self.rotated { @@ -736,29 +738,84 @@ impl Pass1<'_> { } } } - if let (Some((az, alt, zf)), Some(b)) = (self.relief, self.bands.first()) { - let (ci, ri) = cell; - let centre = value(r, self.mask, *b, ci, ri, self.wrap_width).unwrap_or(0.0) as f64; - let mut z = [centre; 9]; - for (k, (dx, dy)) in - [(-1, -1), (0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)].into_iter().enumerate() - { - let (dx, dy) = (dx * self.east_north.0, dy * self.east_north.1); - z[k] = value(r, self.mask, *b, ci + dx, ri + dy, self.wrap_width).map(f64::from).unwrap_or(centre); - } + if let (Some(relief), Some(&b)) = (self.relief, self.bands.first()) { + // Bilinear: the light blended between the four cells around the point, as the + // band values are (#1880). Nearest, or no cell around it lit: its own cell's. + let blended = (self.resampling == Resampling::Bilinear).then(|| { + let (x, y) = (c - 0.5, row - 0.5); + let at = (x.floor() as i64, y.floor() as i64); + let lights = match quad { + Some((q, lights)) if q == at => lights, + _ => { + let lights = self.quad_lights(b, relief, at); + quad = Some((at, lights)); + lights + } + }; + blend(lights, x - x.floor(), y - y.floor()) + }); + let light = blended.flatten().unwrap_or_else(|| { + let centre = value(r, self.mask, b, cell.0, cell.1, self.wrap_width).unwrap_or(0.0); + self.light(b, relief, cell, f64::from(centre)) + }); if let Some(s) = shade.get_mut(i) { - *s = hillshade(&z, self.cell.0, self.cell.1, az, alt, zf); - if let Some((grid, strength)) = self.shadow - && let Some(lit) = grid.get(ri as usize * r.width as usize + ci as usize) - { - let left = 1.0 - strength * (1.0 - f64::from(*lit) / 255.0); - *s = (f64::from(*s) * left).round().clamp(0.0, 255.0) as u8; - } + *s = light.round().clamp(0.0, 255.0) as u8; } } } } } + + /// The light on the relief's cell `(ci, ri)`, from 0 to 255 and not rounded: the hillshade of + /// its 3 × 3 window, times what the cast shadows leave on it. `centre` is the cell's height, + /// and stands in for a neighbour that is no data, masked or outside the grid. Every light a + /// cell gets is worked out here, so that [`blend`] smooths each of them. + fn light(&self, band: usize, (az, alt, zf): (f64, f64, f64), (ci, ri): (i64, i64), centre: f64) -> f64 { + let r = self.r; + let mut z = [centre; 9]; + for (k, (dx, dy)) in [(-1, -1), (0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)].into_iter().enumerate() { + let (dx, dy) = (dx * self.east_north.0, dy * self.east_north.1); + z[k] = value(r, self.mask, band, ci + dx, ri + dy, self.wrap_width).map(f64::from).unwrap_or(centre); + } + let mut light = f64::from(hillshade(&z, self.cell.0, self.cell.1, az, alt, zf)); + if let Some((grid, strength)) = self.shadow + && let Some(lit) = grid.get(ri as usize * r.width as usize + ci as usize) + { + light *= 1.0 - strength * (1.0 - f64::from(*lit) / 255.0); + } + light + } + + /// The lights of the four cells whose centres are around a point, from the cell `(i, j)` at + /// its top left: `(i, j)`, `(i + 1, j)`, `(i, j + 1)` and `(i + 1, j + 1)`. A cell that is no + /// data, masked or outside the grid has none; a column past a whole turn's edge wraps. + fn quad_lights(&self, band: usize, relief: (f64, f64, f64), (i, j): (i64, i64)) -> [Option; 4] { + let (w, h) = (i64::from(self.r.width), i64::from(self.r.height)); + [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(di, dj)| { + let (ci, ri) = (self.wrap_width.map_or(i + di, |ww| (i + di).rem_euclid(ww)), j + dj); + if ci < 0 || ri < 0 || ci >= w || ri >= h { + return None; + } + let centre = value(self.r, self.mask, band, ci, ri, self.wrap_width)?; + Some(self.light(band, relief, (ci, ri), f64::from(centre))) + }) + } +} + +/// The four lights of [`Pass1::quad_lights`] blended bilinearly at `(fx, fy)` (0 to 1) from the +/// first. A cell without one is left out and the others' weights scaled up: the light is +/// clamped at the grid's edge, and a clipped or masked edge isn't darkened. At a cell's centre +/// this is that cell's light exactly. `None` when none of the four with a weight has a light. +fn blend(lights: [Option; 4], fx: f64, fy: f64) -> Option { + let weights = [(1.0 - fx) * (1.0 - fy), fx * (1.0 - fy), (1.0 - fx) * fy, fx * fy]; + let (mut sum, mut total) = (0.0, 0.0); + for (light, w) in lights.into_iter().zip(weights) { + if let Some(light) = light { + sum += w * light; + total += w; + } + } + (total > 0.0).then(|| sum / total) } /// Whether two pixels' band values are the same (NaN, no data, equal to itself). @@ -1238,4 +1295,82 @@ mod tests { } } } + + /// A row of 600 screen pixels across a relief of 6 × 3 cells of 100 m whose slope grows + /// eastward, lit from the west, its middle row drawn: cell `k` covers pixels `100 k - 1` to + /// `100 k + 98`, its centre on `100 k + 49`, and the last pixel is past the raster. The red + /// channel of each pixel, or `None` where it isn't drawn. `light` is a cast-shadow grid, drawn + /// at full strength. + fn relief_row(resampling: Resampling, nodata: Option, mask: &[f64], light: Option<&[u8]>) -> Vec> { + let gt = GeoTransform { origin_x: 0.0, origin_y: 300.0, pixel_width: 100.0, pixel_height: -100.0 }; + let data = [0.0, 0.0, 20.0, 60.0, 120.0, 200.0].repeat(3); + let r = Raster::new("relief", 6, 3, vec![data], gt, Crs::WebMercator, nodata, ColorHint::Gray, "Float32").unwrap(); + let mut style = RasterStyle::default_for(&r); + let shadow = if light.is_some() { 1.0 } else { 0.0 }; + style.renderer = RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 270.0, altitude: 45.0, z_factor: 1.0, shadow }; + style.resampling = resampling; + style.mask = RasterMask { values: mask.to_vec(), ..RasterMask::default() }; + let view = View { + width: 600.0, + height: 1.0, + pixels_per_point: 1.0, + camera: Camera { center: Coord::new(300.5, 150.0), res: 1.0, bearing: 0.0, pitch: 0.0 }, + sky: false, + }; + let mut pm = Pixmap::new(600, 1).unwrap(); + draw(&mut pm, &r, &style, None, &view, 1.0, false, Place::Flat(&Flat::Mercator, "mercator"), light); + (0..600).map(|x| pm.pixel(x, 0).filter(|p| p.alpha() > 0).map(|p| p.red())).collect() + } + + /// Bilinear relief blends the four cells' light (#1880): the same as Nearest at each cell's + /// centre and in the outer half of the edge cells, and in between from one centre's light to + /// the next, not in steps. Nearest keeps one light per cell. + #[test] + fn bilinear_relief_blends_the_light_between_cell_centres() { + let nearest = relief_row(Resampling::Nearest, None, &[], None); + let bilinear = relief_row(Resampling::Bilinear, None, &[], None); + let centre = |k: usize| nearest[100 * k + 49].unwrap(); + for k in 0..6 { + assert!(nearest[100 * k..100 * k + 98].iter().all(|v| *v == Some(centre(k))), "nearest, cell {k}"); + assert_eq!(bilinear[100 * k + 49], Some(centre(k)), "bilinear at the centre of cell {k}"); + } + assert!(bilinear[..49].iter().all(|v| *v == Some(centre(0))) && bilinear[550..599].iter().all(|v| *v == Some(centre(5)))); + for k in 1..4 { + let (a, b) = (centre(k), centre(k + 1)); + assert!(b > a + 5, "the slope grows toward the sun: {a} to {b}"); + let between: Vec = bilinear[100 * k + 49..=100 * k + 149].iter().map(|v| v.unwrap()).collect(); + assert!(between.windows(2).all(|w| w[0] <= w[1] && w[1] - w[0] <= 2), "cells {k} to {}: {between:?}", k + 1); + let middle = between[50]; + assert!(a < middle && middle < b, "cells {k} to {}: {middle} between {a} and {b}", k + 1); + } + } + + /// A no-data or masked cell is left out of the blend, the others' weights scaled up: next to + /// it the relief keeps its own cell's light, rather than darkening toward the hole. + #[test] + fn bilinear_relief_leaves_a_hidden_cell_out_of_the_blend() { + for (nodata, mask) in [(Some(120.0), &[][..]), (None, &[120.0][..])] { + let nearest = relief_row(Resampling::Nearest, nodata, mask, None); + let bilinear = relief_row(Resampling::Bilinear, nodata, mask, None); + // Cell 4 is hidden; cell 3's light runs on to its edge, and cell 5's from its own. + assert!(bilinear[399..499].iter().all(Option::is_none), "{nodata:?} {mask:?}"); + assert!(bilinear[349..399].iter().all(|v| v.is_some() && *v == nearest[349]), "{nodata:?} {mask:?}"); + assert!(bilinear[499..599].iter().all(|v| v.is_some() && *v == nearest[549]), "{nodata:?} {mask:?}"); + } + } + + /// The light cast shadows leave is blended with the hillshade: from a lit cell to a shadowed + /// one, Bilinear dims gradually where Nearest steps. + #[test] + fn bilinear_relief_blends_the_cast_shadows_too() { + // Cell 2 in full shadow in every row, the others lit. + let light: Vec = [255, 255, 0, 255, 255, 255].repeat(3); + let nearest = relief_row(Resampling::Nearest, None, &[], Some(&light)); + let bilinear = relief_row(Resampling::Bilinear, None, &[], Some(&light)); + let (lit, dark) = (nearest[149].unwrap(), nearest[249].unwrap()); + assert!(dark < lit && nearest[198] == Some(lit) && nearest[199] == Some(dark), "{lit} {dark}"); + assert_eq!((bilinear[149], bilinear[249]), (Some(lit), Some(dark))); + let middle = bilinear[199].unwrap(); + assert!(dark < middle && middle < lit, "{middle} between {dark} and {lit}"); + } } diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 038e25327e..d77836e08b 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1241,6 +1241,11 @@ whole image is held: either way the layer is drawn without them, and a notice sa outside the raster casts nothing on it, and a grid spanning 0 to 360° casts nothing across its seam. +With **Resampling** set to bilinear, a Shaded Relief layer's light (its hillshade and cast shadows) +is blended between the cells' centres, as its values are, so a cell drawn over many pixels shades +smoothly instead of in squares; nearest keeps one light per cell, as before. A cell with no data, +or masked, is left out of the blend, so it doesn't darken the relief next to it. + **Masking**, at the foot of the Symbology pane (`raster.mask`), hides pixel values from view without changing the data: values to draw as no data (a background of 0 or −9999 the file doesn't flag, QA flags, land cover classes such as `0, 254, 255`), and values outside, or inside, a range. The From e81310d0dccfe077b01f3205ff7789d575602d49 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 13 Nov 2026 01:25:08 -0300 Subject: [PATCH 2/4] perf(render): bilinear relief light where cells are small or neighbours (#1880 review) Where one screen pixel spans a cell or more, Bilinear Shaded Relief takes its own cell's light, as before: the blend can't be seen there, and each pixel would work out four new lights. Between cells, moving one cell east or west keeps two of the last four lights. A whole DEM fitted in a 1600 px export now costs what main does; at a cell of about 1.3 px the cost over main falls from about +60% to about +20%. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/raster.rs | 122 +++++++++++++++++++++++++++--------- 1 file changed, 91 insertions(+), 31 deletions(-) diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 8f323e02af..123713e61c 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -671,9 +671,13 @@ impl Pass1<'_> { } // Nearest sampling: the last cell read, and the pixel it was read for. let mut last: Option<((i64, i64), usize)> = None; - // Bilinear relief: the last four cells' lights, by the first's column and row. + // Bilinear relief: the last four cells' lights, by the first's column and row; and the + // last pixel that fell in the grid, with its source position. let mut quad: Option<((i64, i64), [Option; 4])> = None; - for dx in 0..bw { + let mut prev: Option<(usize, f64, f64)> = None; + // The source position of the pixel in column `dx` of this row, its column wrapped here, + // not in `source`: the grid's columns run on across a 0..360° seam. + let pos_at = |dx: usize| { let px = self.x0 + dx; let pos = match self.rotated { // Back-rotate the screen pixel about the centre, then find its source exactly. @@ -693,13 +697,21 @@ impl Pass1<'_> { } } }; - let Some((c, row)) = pos else { continue }; - // Wrapped here, not in `source`: the grid's columns run on across a 0..360° seam. - let c = r.wrap_col(c); + pos.map(|(c, row)| (r.wrap_col(c), row)) + }; + for dx in 0..bw { + let Some((c, row)) = pos_at(dx) else { continue }; if c < 0.0 || row < 0.0 || c >= r.width as f64 || row >= r.height as f64 { continue; } let i = dy * bw + dx; + // How many cells one screen pixel spans here, along the row: from the last pixel in + // the grid, or the next one on the row's first. + let last_drawn = prev.replace((dx, c, row)); + let span = || match last_drawn { + Some((pdx, pc, pr)) => (c - pc).hypot(row - pr) / (dx - pdx) as f64, + None => pos_at(dx + 1).map_or(0.0, |(nc, nr)| (nc - c).hypot(nr - row)), + }; // Truncating is flooring here (both are at least 0), and much cheaper. let cell = (c as i64, row as i64); // The same cell as the last pixel, sampled nearest: the same values. @@ -741,17 +753,24 @@ impl Pass1<'_> { if let (Some(relief), Some(&b)) = (self.relief, self.bands.first()) { // Bilinear: the light blended between the four cells around the point, as the // band values are (#1880). Nearest, or no cell around it lit: its own cell's. - let blended = (self.resampling == Resampling::Bilinear).then(|| { + // So too where a cell is a pixel across or less: the blend can't be seen there, + // and each pixel would work out four new lights. + let blended = (self.resampling == Resampling::Bilinear && span() < 1.0).then(|| { let (x, y) = (c - 0.5, row - 0.5); let at = (x.floor() as i64, y.floor() as i64); + let cell_light = |i, j| self.cell_light(b, relief, (i, j)); let lights = match quad { Some((q, lights)) if q == at => lights, - _ => { - let lights = self.quad_lights(b, relief, at); - quad = Some((at, lights)); - lights + // One cell east or west: two of the lights are the last four's. + Some(((qi, qj), [_, ne, _, se])) if qj == at.1 && qi + 1 == at.0 => { + [ne, cell_light(at.0 + 1, at.1), se, cell_light(at.0 + 1, at.1 + 1)] + } + Some(((qi, qj), [nw, _, sw, _])) if qj == at.1 && qi - 1 == at.0 => { + [cell_light(at.0, at.1), nw, cell_light(at.0, at.1 + 1), sw] } + _ => self.quad_lights(b, relief, at), }; + quad = Some((at, lights)); blend(lights, x - x.floor(), y - y.floor()) }); let light = blended.flatten().unwrap_or_else(|| { @@ -786,19 +805,21 @@ impl Pass1<'_> { light } + /// The light of the cell `(i, j)`, or none when it is no data, masked or outside the grid; a + /// column past a whole turn's edge wraps. + fn cell_light(&self, band: usize, relief: (f64, f64, f64), (i, j): (i64, i64)) -> Option { + let ci = self.wrap_width.map_or(i, |w| i.rem_euclid(w)); + if ci < 0 || j < 0 || ci >= i64::from(self.r.width) || j >= i64::from(self.r.height) { + return None; + } + let centre = value(self.r, self.mask, band, ci, j, self.wrap_width)?; + Some(self.light(band, relief, (ci, j), f64::from(centre))) + } + /// The lights of the four cells whose centres are around a point, from the cell `(i, j)` at - /// its top left: `(i, j)`, `(i + 1, j)`, `(i, j + 1)` and `(i + 1, j + 1)`. A cell that is no - /// data, masked or outside the grid has none; a column past a whole turn's edge wraps. + /// its top left: `(i, j)`, `(i + 1, j)`, `(i, j + 1)` and `(i + 1, j + 1)`. fn quad_lights(&self, band: usize, relief: (f64, f64, f64), (i, j): (i64, i64)) -> [Option; 4] { - let (w, h) = (i64::from(self.r.width), i64::from(self.r.height)); - [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(di, dj)| { - let (ci, ri) = (self.wrap_width.map_or(i + di, |ww| (i + di).rem_euclid(ww)), j + dj); - if ci < 0 || ri < 0 || ci >= w || ri >= h { - return None; - } - let centre = value(self.r, self.mask, band, ci, ri, self.wrap_width)?; - Some(self.light(band, relief, (ci, ri), f64::from(centre))) - }) + [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(di, dj)| self.cell_light(band, relief, (i + di, j + dj))) } } @@ -1300,10 +1321,15 @@ mod tests { /// eastward, lit from the west, its middle row drawn: cell `k` covers pixels `100 k - 1` to /// `100 k + 98`, its centre on `100 k + 49`, and the last pixel is past the raster. The red /// channel of each pixel, or `None` where it isn't drawn. `light` is a cast-shadow grid, drawn - /// at full strength. - fn relief_row(resampling: Resampling, nodata: Option, mask: &[f64], light: Option<&[u8]>) -> Vec> { - let gt = GeoTransform { origin_x: 0.0, origin_y: 300.0, pixel_width: 100.0, pixel_height: -100.0 }; - let data = [0.0, 0.0, 20.0, 60.0, 120.0, 200.0].repeat(3); + /// at full strength; a `mirrored` grid is stored right to left. + fn relief_row(resampling: Resampling, nodata: Option, mask: &[f64], light: Option<&[u8]>, mirrored: bool) -> Vec> { + let (origin_x, pixel_width) = if mirrored { (600.0, -100.0) } else { (0.0, 100.0) }; + let gt = GeoTransform { origin_x, origin_y: 300.0, pixel_width, pixel_height: -100.0 }; + let mut heights = [0.0, 0.0, 20.0, 60.0, 120.0, 200.0]; + if mirrored { + heights.reverse(); + } + let data = heights.repeat(3); let r = Raster::new("relief", 6, 3, vec![data], gt, Crs::WebMercator, nodata, ColorHint::Gray, "Float32").unwrap(); let mut style = RasterStyle::default_for(&r); let shadow = if light.is_some() { 1.0 } else { 0.0 }; @@ -1327,8 +1353,11 @@ mod tests { /// the next, not in steps. Nearest keeps one light per cell. #[test] fn bilinear_relief_blends_the_light_between_cell_centres() { - let nearest = relief_row(Resampling::Nearest, None, &[], None); - let bilinear = relief_row(Resampling::Bilinear, None, &[], None); + let nearest = relief_row(Resampling::Nearest, None, &[], None, false); + let bilinear = relief_row(Resampling::Bilinear, None, &[], None, false); + // Stored right to left, the cells are read westward: the same pixels (the last one, on + // the raster's edge, falls on the other side of it). + assert_eq!(relief_row(Resampling::Bilinear, None, &[], None, true)[..599], bilinear[..599]); let centre = |k: usize| nearest[100 * k + 49].unwrap(); for k in 0..6 { assert!(nearest[100 * k..100 * k + 98].iter().all(|v| *v == Some(centre(k))), "nearest, cell {k}"); @@ -1350,8 +1379,8 @@ mod tests { #[test] fn bilinear_relief_leaves_a_hidden_cell_out_of_the_blend() { for (nodata, mask) in [(Some(120.0), &[][..]), (None, &[120.0][..])] { - let nearest = relief_row(Resampling::Nearest, nodata, mask, None); - let bilinear = relief_row(Resampling::Bilinear, nodata, mask, None); + let nearest = relief_row(Resampling::Nearest, nodata, mask, None, false); + let bilinear = relief_row(Resampling::Bilinear, nodata, mask, None, false); // Cell 4 is hidden; cell 3's light runs on to its edge, and cell 5's from its own. assert!(bilinear[399..499].iter().all(Option::is_none), "{nodata:?} {mask:?}"); assert!(bilinear[349..399].iter().all(|v| v.is_some() && *v == nearest[349]), "{nodata:?} {mask:?}"); @@ -1365,12 +1394,43 @@ mod tests { fn bilinear_relief_blends_the_cast_shadows_too() { // Cell 2 in full shadow in every row, the others lit. let light: Vec = [255, 255, 0, 255, 255, 255].repeat(3); - let nearest = relief_row(Resampling::Nearest, None, &[], Some(&light)); - let bilinear = relief_row(Resampling::Bilinear, None, &[], Some(&light)); + let nearest = relief_row(Resampling::Nearest, None, &[], Some(&light), false); + let bilinear = relief_row(Resampling::Bilinear, None, &[], Some(&light), false); let (lit, dark) = (nearest[149].unwrap(), nearest[249].unwrap()); assert!(dark < lit && nearest[198] == Some(lit) && nearest[199] == Some(dark), "{lit} {dark}"); assert_eq!((bilinear[149], bilinear[249]), (Some(lit), Some(dark))); let middle = bilinear[199].unwrap(); assert!(dark < middle && middle < lit, "{middle} between {dark} and {lit}"); } + + /// Where a cell is a pixel across or less, Bilinear relief draws each cell's own light, as + /// before #1880: the blend couldn't be seen, and would work out four lights for each pixel. + #[test] + fn bilinear_relief_keeps_the_cells_light_when_a_cell_is_a_pixel_or_less() { + // 40 x 3 cells of 100 m with uneven heights, seen 24 pixels wide at `res` m a pixel. + let row = |resampling: Resampling, res: f64| { + let gt = GeoTransform { origin_x: 0.0, origin_y: 300.0, pixel_width: 100.0, pixel_height: -100.0 }; + let data = (0..120).map(|k| (k * 37 % 11) as f32 * 10.0).collect(); + let r = Raster::new("relief", 40, 3, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + let mut style = RasterStyle::default_for(&r); + style.renderer = + RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 270.0, altitude: 45.0, z_factor: 1.0, shadow: 0.0 }; + style.resampling = resampling; + let view = View { + width: 24.0, + height: 1.0, + pixels_per_point: 1.0, + camera: Camera { center: Coord::new(2000.0, 150.0), res, bearing: 0.0, pitch: 0.0 }, + sky: false, + }; + let mut pm = Pixmap::new(24, 1).unwrap(); + draw(&mut pm, &r, &style, None, &view, 1.0, false, Place::Flat(&Flat::Mercator, "mercator"), None); + (0..24).map(|x| pm.pixel(x, 0).map(|p| p.red())).collect::>() + }; + for res in [100.0, 150.0] { + assert_eq!(row(Resampling::Bilinear, res), row(Resampling::Nearest, res), "{res} m a pixel"); + } + // Two pixels to a cell: blended. + assert_ne!(row(Resampling::Bilinear, 50.0), row(Resampling::Nearest, 50.0)); + } } From ff3d84972b47417e0c85d95fe7117bdc7238caba Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 13 Nov 2026 09:39:27 -0300 Subject: [PATCH 3/4] fix(render): bilinear relief blends across a whole turn's seam (#1880 review) The pixel span that turns the light blend off counted columns the long way round across a 0-360 degree grid's seam (35.95 to 0.05 as 35.9 cells), so the pixel just across it took its own cell's light: a 1 px stripe on global DEMs. Columns are now counted the short way round. A test crosses the seam of a whole-turn grid whose cast-shadow light differs on either side; it also covers the column wrap in cell_light. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/raster.rs | 50 ++++++++++++++++++++++++++++++++++--- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 123713e61c..92d675ba5c 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -706,11 +706,16 @@ impl Pass1<'_> { } let i = dy * bw + dx; // How many cells one screen pixel spans here, along the row: from the last pixel in - // the grid, or the next one on the row's first. + // the grid, or the next one on the row's first. Across a whole turn's seam the columns + // are counted the short way round: 35.95 to 0.05 is a tenth of a cell, not 35.9. let last_drawn = prev.replace((dx, c, row)); + let cols_apart = |other: f64| { + let d = (c - other).abs(); + self.wrap_width.map_or(d, |w| d.min(w as f64 - d)) + }; let span = || match last_drawn { - Some((pdx, pc, pr)) => (c - pc).hypot(row - pr) / (dx - pdx) as f64, - None => pos_at(dx + 1).map_or(0.0, |(nc, nr)| (nc - c).hypot(nr - row)), + Some((pdx, pc, pr)) => cols_apart(pc).hypot(row - pr) / (dx - pdx) as f64, + None => pos_at(dx + 1).map_or(0.0, |(nc, nr)| cols_apart(nc).hypot(nr - row)), }; // Truncating is flooring here (both are at least 0), and much cheaper. let cell = (c as i64, row as i64); @@ -1433,4 +1438,43 @@ mod tests { // Two pixels to a cell: blended. assert_ne!(row(Resampling::Bilinear, 50.0), row(Resampling::Nearest, 50.0)); } + + /// A grid spanning one whole turn blends its light across the 0°/360° seam as anywhere else: + /// the cells on either side of it are neighbours, and a pixel just across it is a fraction of + /// a cell from the last one, not a whole turn. + #[test] + fn bilinear_relief_blends_across_a_whole_turns_seam() { + // 36 x 18 cells of 10 degrees, flat; the cast shadows leave no light on column 0 (0 to + // 10 degrees east) and all of it on the others. + let gt = GeoTransform { origin_x: 0.0, origin_y: 90.0, pixel_width: 10.0, pixel_height: -10.0 }; + let r = Raster::new("turn", 36, 18, vec![vec![0.0; 36 * 18]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let light: Vec = (0..36 * 18).map(|k| if k % 36 == 0 { 0 } else { 255 }).collect(); + // 80 pixels of half a degree across the seam, on row 8's centre (5 degrees north). + let view = View { + width: 80.0, + height: 1.0, + pixels_per_point: 1.0, + camera: Camera { center: lonlat_to_merc(Coord::new(0.0, 5.0)), res: 1_113_194.9 / 20.0, bearing: 0.0, pitch: 0.0 }, + sky: false, + }; + let row = |resampling: Resampling| { + let mut style = RasterStyle::default_for(&r); + style.renderer = + RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 315.0, altitude: 45.0, z_factor: 1.0, shadow: 1.0 }; + style.resampling = resampling; + let mut pm = Pixmap::new(80, 1).unwrap(); + draw(&mut pm, &r, &style, None, &view, 1.0, false, Place::Flat(&Flat::Mercator, "mercator"), Some(&light)); + (0..80).map(|x| pm.pixel(x, 0).unwrap().red()).collect::>() + }; + let (nearest, bilinear) = (row(Resampling::Nearest), row(Resampling::Bilinear)); + // Column 35's centre (5 degrees west) is on pixel 29.5, column 0's on 49.5; the seam lies + // between pixels 39 and 40. + let (lit, dark) = (nearest[29], nearest[50]); + assert!(dark + 20 < lit && nearest[39] == lit && nearest[40] == dark, "{nearest:?}"); + let across = &bilinear[30..=49]; + assert!(across.windows(2).all(|w| w[0] >= w[1]), "darkens steadily across the seam: {across:?}"); + for x in [39, 40] { + assert!(dark + 10 < bilinear[x] && bilinear[x] + 10 < lit, "pixel {x} blends: {across:?}"); + } + } } From 8a225ddf9a1ff1d9964ae347c39ebe9dfbe12140 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 13 Nov 2026 10:35:33 -0300 Subject: [PATCH 4/4] feat(render): bilinear relief blends the sky's ambient light too (#1880) Pass1::light now gives a cell's direct light (hillshade times what the cast shadows leave) and its ambient light (scaled by the sky it sees, #1871) together, and the bilinear blend mixes both with the same weights, so sky visibility no longer draws in cell squares under Bilinear. Nearest works both out as before and draws the same pixels. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/raster.rs | 110 ++++++++++++++++++++++-------------- docs/user-guide/data.md | 8 +-- 2 files changed, 73 insertions(+), 45 deletions(-) diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 6de3364504..5954d7e354 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -693,7 +693,7 @@ impl Pass1<'_> { let mut last: Option<((i64, i64), usize)> = None; // Bilinear relief: the last four cells' lights, by the first's column and row; and the // last pixel that fell in the grid, with its source position. - let mut quad: Option<((i64, i64), [Option; 4])> = None; + let mut quad: Option<((i64, i64), [Option; 4])> = None; let mut prev: Option<(usize, f64, f64)> = None; // The source position of the pixel in column `dx` of this row, its column wrapped here, // not in `source`: the grid's columns run on across a 0..360° seam. @@ -803,42 +803,45 @@ impl Pass1<'_> { self.light(b, relief, cell, f64::from(centre)) }); if let Some(s) = shade.get_mut(i) { - *s = light.round().clamp(0.0, 255.0) as u8; + *s = light.direct.round().clamp(0.0, 255.0) as u8; } - if let Some((grid, strength)) = self.sky - && let Some(seen) = grid.get(cell.1 as usize * r.width as usize + cell.0 as usize) + if self.sky.is_some() && let Some(a) = ambient.get_mut(i) { - *a = ((1.0 - strength * (1.0 - f64::from(*seen) / 255.0)) * 255.0).round().clamp(0.0, 255.0) as u8; + *a = light.ambient.round().clamp(0.0, 255.0) as u8; } } } } } - /// The light on the relief's cell `(ci, ri)`, from 0 to 255 and not rounded: the hillshade of - /// its 3 × 3 window, times what the cast shadows leave on it. `centre` is the cell's height, - /// and stands in for a neighbour that is no data, masked or outside the grid. Every light a - /// cell gets is worked out here, so that [`blend`] smooths each of them. - fn light(&self, band: usize, (az, alt, zf): (f64, f64, f64), (ci, ri): (i64, i64), centre: f64) -> f64 { + /// The lights on the relief's cell `(ci, ri)`, from 0 to 255 and not rounded: the direct + /// light, the hillshade of its 3 × 3 window times what the cast shadows leave on it; and the + /// ambient light, scaled by the sky the cell sees. `centre` is the cell's height, and stands in + /// for a neighbour that is no data, masked or outside the grid. Every light a cell gets is + /// worked out here, so that [`blend`] smooths each of them. + fn light(&self, band: usize, (az, alt, zf): (f64, f64, f64), (ci, ri): (i64, i64), centre: f64) -> Lit { let r = self.r; let mut z = [centre; 9]; for (k, (dx, dy)) in [(-1, -1), (0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)].into_iter().enumerate() { let (dx, dy) = (dx * self.east_north.0, dy * self.east_north.1); z[k] = value(r, self.mask, band, ci + dx, ri + dy, self.wrap_width).map(f64::from).unwrap_or(centre); } - let mut light = f64::from(hillshade(&z, self.cell.0, self.cell.1, az, alt, zf)); - if let Some((grid, strength)) = self.shadow - && let Some(lit) = grid.get(ri as usize * r.width as usize + ci as usize) - { - light *= 1.0 - strength * (1.0 - f64::from(*lit) / 255.0); + let at = ri as usize * r.width as usize + ci as usize; + // What a grid of 0 (none) to 255 (all) leaves of a light, at `strength`. + let left = |grid: Option<(&[u8], f64)>| { + grid.and_then(|(grid, strength)| grid.get(at).map(|v| 1.0 - strength * (1.0 - f64::from(*v) / 255.0))) + }; + let mut direct = f64::from(hillshade(&z, self.cell.0, self.cell.1, az, alt, zf)); + if let Some(left) = left(self.shadow) { + direct *= left; } - light + Lit { direct, ambient: left(self.sky).map_or(255.0, |left| left * 255.0) } } - /// The light of the cell `(i, j)`, or none when it is no data, masked or outside the grid; a + /// The lights of the cell `(i, j)`, or none when it is no data, masked or outside the grid; a /// column past a whole turn's edge wraps. - fn cell_light(&self, band: usize, relief: (f64, f64, f64), (i, j): (i64, i64)) -> Option { + fn cell_light(&self, band: usize, relief: (f64, f64, f64), (i, j): (i64, i64)) -> Option { let ci = self.wrap_width.map_or(i, |w| i.rem_euclid(w)); if ci < 0 || j < 0 || ci >= i64::from(self.r.width) || j >= i64::from(self.r.height) { return None; @@ -849,25 +852,34 @@ impl Pass1<'_> { /// The lights of the four cells whose centres are around a point, from the cell `(i, j)` at /// its top left: `(i, j)`, `(i + 1, j)`, `(i, j + 1)` and `(i + 1, j + 1)`. - fn quad_lights(&self, band: usize, relief: (f64, f64, f64), (i, j): (i64, i64)) -> [Option; 4] { + fn quad_lights(&self, band: usize, relief: (f64, f64, f64), (i, j): (i64, i64)) -> [Option; 4] { [(0, 0), (1, 0), (0, 1), (1, 1)].map(|(di, dj)| self.cell_light(band, relief, (i + di, j + dj))) } } -/// The four lights of [`Pass1::quad_lights`] blended bilinearly at `(fx, fy)` (0 to 1) from the -/// first. A cell without one is left out and the others' weights scaled up: the light is -/// clamped at the grid's edge, and a clipped or masked edge isn't darkened. At a cell's centre -/// this is that cell's light exactly. `None` when none of the four with a weight has a light. -fn blend(lights: [Option; 4], fx: f64, fy: f64) -> Option { +/// A relief cell's lights, from 0 to 255 and not rounded (see [`Pass1::light`]). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Lit { + direct: f64, + ambient: f64, +} + +/// The four cells' lights of [`Pass1::quad_lights`] blended bilinearly at `(fx, fy)` (0 to 1) +/// from the first, each light on its own. A cell without lights is left out and the others' +/// weights scaled up: the light is clamped at the grid's edge, and a clipped or masked edge isn't +/// darkened. At a cell's centre this is that cell's lights exactly. `None` when none of the four +/// with a weight has lights. +fn blend(lights: [Option; 4], fx: f64, fy: f64) -> Option { let weights = [(1.0 - fx) * (1.0 - fy), fx * (1.0 - fy), (1.0 - fx) * fy, fx * fy]; - let (mut sum, mut total) = (0.0, 0.0); + let (mut direct, mut ambient, mut total) = (0.0, 0.0, 0.0); for (light, w) in lights.into_iter().zip(weights) { if let Some(light) = light { - sum += w * light; + direct += w * light.direct; + ambient += w * light.ambient; total += w; } } - (total > 0.0).then(|| sum / total) + (total > 0.0).then(|| Lit { direct: direct / total, ambient: ambient / total }) } /// Whether two pixels' band values are the same (NaN, no data, equal to itself). @@ -1448,9 +1460,9 @@ mod tests { /// A row of 600 screen pixels across a relief of 6 × 3 cells of 100 m whose slope grows /// eastward, lit from the west, its middle row drawn: cell `k` covers pixels `100 k - 1` to /// `100 k + 98`, its centre on `100 k + 49`, and the last pixel is past the raster. The red - /// channel of each pixel, or `None` where it isn't drawn. `light` is a cast-shadow grid, drawn - /// at full strength; a `mirrored` grid is stored right to left. - fn relief_row(resampling: Resampling, nodata: Option, mask: &[f64], light: Option<&[u8]>, mirrored: bool) -> Vec> { + /// channel of each pixel, or `None` where it isn't drawn. The cast shadows and sky of `light`, + /// when given, are drawn at full strength; a `mirrored` grid is stored right to left. + fn relief_row(resampling: Resampling, nodata: Option, mask: &[f64], light: Lights, mirrored: bool) -> Vec> { let (origin_x, pixel_width) = if mirrored { (600.0, -100.0) } else { (0.0, 100.0) }; let gt = GeoTransform { origin_x, origin_y: 300.0, pixel_width, pixel_height: -100.0 }; let mut heights = [0.0, 0.0, 20.0, 60.0, 120.0, 200.0]; @@ -1460,9 +1472,9 @@ mod tests { let data = heights.repeat(3); let r = Raster::new("relief", 6, 3, vec![data], gt, Crs::WebMercator, nodata, ColorHint::Gray, "Float32").unwrap(); let mut style = RasterStyle::default_for(&r); - let shadow = if light.is_some() { 1.0 } else { 0.0 }; - style.renderer = - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 270.0, altitude: 45.0, z_factor: 1.0, shadow, sky: 0.0 }; + let full = |grid: Option<&[u8]>| if grid.is_some() { 1.0 } else { 0.0 }; + let (shadow, sky) = (full(light.shadow), full(light.sky)); + style.renderer = RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 270.0, altitude: 45.0, z_factor: 1.0, shadow, sky }; style.resampling = resampling; style.mask = RasterMask { values: mask.to_vec(), ..RasterMask::default() }; let view = View { @@ -1473,7 +1485,7 @@ mod tests { sky: false, }; let mut pm = Pixmap::new(600, 1).unwrap(); - draw(&mut pm, &r, &style, None, &view, 1.0, false, Place::Flat(&Flat::Mercator, "mercator"), Lights { shadow: light, sky: None }); + draw(&mut pm, &r, &style, None, &view, 1.0, false, Place::Flat(&Flat::Mercator, "mercator"), light); (0..600).map(|x| pm.pixel(x, 0).filter(|p| p.alpha() > 0).map(|p| p.red())).collect() } @@ -1482,11 +1494,11 @@ mod tests { /// the next, not in steps. Nearest keeps one light per cell. #[test] fn bilinear_relief_blends_the_light_between_cell_centres() { - let nearest = relief_row(Resampling::Nearest, None, &[], None, false); - let bilinear = relief_row(Resampling::Bilinear, None, &[], None, false); + let nearest = relief_row(Resampling::Nearest, None, &[], Lights::default(), false); + let bilinear = relief_row(Resampling::Bilinear, None, &[], Lights::default(), false); // Stored right to left, the cells are read westward: the same pixels (the last one, on // the raster's edge, falls on the other side of it). - assert_eq!(relief_row(Resampling::Bilinear, None, &[], None, true)[..599], bilinear[..599]); + assert_eq!(relief_row(Resampling::Bilinear, None, &[], Lights::default(), true)[..599], bilinear[..599]); let centre = |k: usize| nearest[100 * k + 49].unwrap(); for k in 0..6 { assert!(nearest[100 * k..100 * k + 98].iter().all(|v| *v == Some(centre(k))), "nearest, cell {k}"); @@ -1508,8 +1520,8 @@ mod tests { #[test] fn bilinear_relief_leaves_a_hidden_cell_out_of_the_blend() { for (nodata, mask) in [(Some(120.0), &[][..]), (None, &[120.0][..])] { - let nearest = relief_row(Resampling::Nearest, nodata, mask, None, false); - let bilinear = relief_row(Resampling::Bilinear, nodata, mask, None, false); + let nearest = relief_row(Resampling::Nearest, nodata, mask, Lights::default(), false); + let bilinear = relief_row(Resampling::Bilinear, nodata, mask, Lights::default(), false); // Cell 4 is hidden; cell 3's light runs on to its edge, and cell 5's from its own. assert!(bilinear[399..499].iter().all(Option::is_none), "{nodata:?} {mask:?}"); assert!(bilinear[349..399].iter().all(|v| v.is_some() && *v == nearest[349]), "{nodata:?} {mask:?}"); @@ -1523,8 +1535,8 @@ mod tests { fn bilinear_relief_blends_the_cast_shadows_too() { // Cell 2 in full shadow in every row, the others lit. let light: Vec = [255, 255, 0, 255, 255, 255].repeat(3); - let nearest = relief_row(Resampling::Nearest, None, &[], Some(&light), false); - let bilinear = relief_row(Resampling::Bilinear, None, &[], Some(&light), false); + let nearest = relief_row(Resampling::Nearest, None, &[], Lights { shadow: Some(&light), sky: None }, false); + let bilinear = relief_row(Resampling::Bilinear, None, &[], Lights { shadow: Some(&light), sky: None }, false); let (lit, dark) = (nearest[149].unwrap(), nearest[249].unwrap()); assert!(dark < lit && nearest[198] == Some(lit) && nearest[199] == Some(dark), "{lit} {dark}"); assert_eq!((bilinear[149], bilinear[249]), (Some(lit), Some(dark))); @@ -1532,6 +1544,22 @@ mod tests { assert!(dark < middle && middle < lit, "{middle} between {dark} and {lit}"); } + /// The ambient light the sky leaves is blended too: from a cell that sees the whole sky to one + /// that sees none of it, Bilinear dims gradually where Nearest steps. + #[test] + fn bilinear_relief_blends_the_sky_too() { + // Cell 2 sees no sky in every row, the others all of it. + let sky: Vec = [255, 255, 0, 255, 255, 255].repeat(3); + let light = Lights { shadow: None, sky: Some(&sky) }; + let nearest = relief_row(Resampling::Nearest, None, &[], light, false); + let bilinear = relief_row(Resampling::Bilinear, None, &[], light, false); + let (open, hidden) = (nearest[149].unwrap(), nearest[249].unwrap()); + assert!(hidden < open && nearest[198] == Some(open) && nearest[199] == Some(hidden), "{open} {hidden}"); + assert_eq!((bilinear[149], bilinear[249]), (Some(open), Some(hidden))); + let middle = bilinear[199].unwrap(); + assert!(hidden < middle && middle < open, "{middle} between {hidden} and {open}"); + } + /// Where a cell is a pixel across or less, Bilinear relief draws each cell's own light, as /// before #1880: the blend couldn't be seen, and would work out four lights for each pixel. #[test] diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index a0730f7b25..04375c2166 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1298,10 +1298,10 @@ exports, and said when it can't be drawn (in the browser over 500,000 cells, or GeoTIFF read in place) as cast shadows are. Terrain outside the raster, or farther than 100 cells, hides none of its sky. -With **Resampling** set to bilinear, a Shaded Relief layer's light (its hillshade and cast shadows) -is blended between the cells' centres, as its values are, so a cell drawn over many pixels shades -smoothly instead of in squares; nearest keeps one light per cell, as before. A cell with no data, -or masked, is left out of the blend, so it doesn't darken the relief next to it. +With **Resampling** set to bilinear, a Shaded Relief layer's light (its hillshade, cast shadows and +sky visibility) is blended between the cells' centres, as its values are, so a cell drawn over many +pixels shades smoothly instead of in squares; nearest keeps one light per cell, as before. A cell +with no data, or masked, is left out of the blend, so it doesn't darken the relief next to it. **Masking**, at the foot of the Symbology pane (`raster.mask`), hides pixel values from view without changing the data: values to draw as no data (a background of 0 or −9999 the file doesn't flag, QA