From 37af3221dfe00705f0933593f42f1284478cb10c Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Wed, 11 Nov 2026 13:28:56 +0100 Subject: [PATCH 01/12] feat(analysis): Viewshed can read the ground between cells (bilinear heights), checked against known answers (#1252) --- crates/analysis/src/rasterops.rs | 178 +++++++++++++++++++++++++++-- crates/engine/src/cmd/workflows.rs | 9 +- crates/engine/src/tests.rs | 6 + docs/user-guide/analysis.md | 2 +- 4 files changed, 182 insertions(+), 13 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index fffdcc7f8f..8f5d644556 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -434,14 +434,72 @@ pub fn line_of_sight( const MAX_VIEWSHED_WORK: usize = 400_000_000; pub(crate) const MAX_IDW_WORK: usize = 400_000_000; +/// How a viewshed reads the ground between the observer and a cell. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Heights { + /// The cell each point of the ray falls in, as the viewshed always has. On ground that bulges + /// (a hill seen from its top), a cell nearer the observer than the point stands in for it and + /// can hide cells just inside the horizon. + #[default] + Nearest, + /// Between the cells' centres, in proportion to how near the point is to each (bilinear), as + /// GRASS's `r.viewshed` reads it: smoother, and right on bulging ground. Where one of those + /// cells has no data, the cell the point falls in, as [`Heights::Nearest`] reads it. + Bilinear, +} + +impl Heights { + /// The one named `name` (`nearest`, `bilinear`); `None` for any other. + pub fn named(name: &str) -> Option { + match name { + "nearest" => Some(Heights::Nearest), + "bilinear" => Some(Heights::Bilinear), + _ => None, + } + } + + /// The ground at a point of a ray, `(col, row)` in cells (whole numbers at cell centres). + fn at(self, r: &Raster, b: usize, col: f64, row: f64) -> Option { + let nearest = || r.value(b, col.round() as i64, row.round() as i64); + if self == Heights::Nearest { + return nearest(); + } + let (c0, r0) = (col.floor(), row.floor()); + let (tx, ty) = (col - c0, row - r0); + let (c0, r0) = (c0 as i64, r0 as i64); + let mut sum = 0.0f64; + // A neighbour weighing nothing (the point on its row or column) isn't read, so a point + // on a cell's centre line needs only the two cells it lies between. + for (dc, dr, wgt) in [(0, 0, (1.0 - tx) * (1.0 - ty)), (1, 0, tx * (1.0 - ty)), (0, 1, (1.0 - tx) * ty), (1, 1, tx * ty)] { + if wgt == 0.0 { + continue; + } + match r.value(b, c0 + dc, r0 + dr) { + Some(v) => sum += wgt * f64::from(v), + None => return nearest(), + } + } + Some(sum as f32) + } +} + /// Cells visible from an observer (1) or not (0) within `radius_m`; outside the radius no-data. -/// The Earth curves as visible light sees it (`SIGHT_RADIUS_M`). -pub fn viewshed(r: &Raster, b: usize, observer: Coord, height: f64, radius_m: f64) -> Result, String> { - viewshed_on(None, r, b, observer, height, radius_m) +/// The Earth curves as visible light sees it (`SIGHT_RADIUS_M`). The ground along each ray is read +/// as `heights` says. +pub fn viewshed(r: &Raster, b: usize, observer: Coord, height: f64, radius_m: f64, heights: Heights) -> Result, String> { + viewshed_on(None, r, b, observer, height, radius_m, heights) } /// [`viewshed`] on `threads` threads, or as many as its work calls for. -fn viewshed_on(threads: Option, r: &Raster, b: usize, observer: Coord, height: f64, radius_m: f64) -> Result, String> { +fn viewshed_on( + threads: Option, + r: &Raster, + b: usize, + observer: Coord, + height: f64, + radius_m: f64, + heights: Heights, +) -> Result, String> { let (oc, or) = r.pixel_at(observer).ok_or("the observer is outside the raster")?; let z0 = r.value(b, oc, or).ok_or("the observer stands on no-data")? as f64 + height; let (cx, cy) = r.cell_size_m(); @@ -501,8 +559,8 @@ fn viewshed_on(threads: Option, r: &Raster, b: usize, observer: Coord, he let mut visible = true; for s in 1..steps { let t = s as f64 / steps as f64; - let (c, rr) = ((oc as f64 + (col - oc) as f64 * t).round() as i64, (or as f64 + (row - or) as f64 * t).round() as i64); - let Some(zi) = r.value(b, c, rr) else { continue }; + let (c, rr) = (oc as f64 + (col - oc) as f64 * t, or as f64 + (row - or) as f64 * t); + let Some(zi) = heights.at(r, b, c, rr) else { continue }; let di = dist * t; if (zi as f64 - di * di / (2.0 * SIGHT_RADIUS_M) - z0) / di > target { visible = false; @@ -1596,11 +1654,11 @@ mod tests { for (at, radius, expected) in [(Coord::new(0.012, 44.990), 500.0, [207, 775, 5318]), (Coord::new(0.003, 44.985), 5_000.0, [185, 6050, 65])] { - let one = viewshed_on(Some(1), &dem, 0, at, 2.0, radius).unwrap_or_else(|e| panic!("{e}")); + let one = viewshed_on(Some(1), &dem, 0, at, 2.0, radius, Heights::Nearest).unwrap_or_else(|e| panic!("{e}")); let counts = [1.0, 0.0, NODATA].map(|k| one.iter().filter(|v| v.to_bits() == k.to_bits()).count()); assert_eq!(counts, expected, "radius {radius}"); for threads in [2, 7, 16] { - let many = viewshed_on(Some(threads), &dem, 0, at, 2.0, radius).unwrap_or_else(|e| panic!("{e}")); + let many = viewshed_on(Some(threads), &dem, 0, at, 2.0, radius, Heights::Nearest).unwrap_or_else(|e| panic!("{e}")); assert!(one.iter().map(|v| v.to_bits()).eq(many.iter().map(|v| v.to_bits())), "{threads} threads, radius {radius}"); } } @@ -1789,7 +1847,7 @@ mod tests { let eye = Coord::new(0.0005, 0.0); // √(2 · 7/6 · 6,371 km · 10 m), written out so that the test pins the radius. let horizon = 12_192.0; - let vs = viewshed(&flat, 0, eye, 10.0, 20_000.0).unwrap_or_else(|e| panic!("{e}")); + let vs = viewshed(&flat, 0, eye, 10.0, 20_000.0, Heights::Nearest).unwrap_or_else(|e| panic!("{e}")); let row = &vs[w as usize..2 * w as usize]; let last = row.iter().rposition(|v| *v == 1.0).unwrap_or(0); let (cx, _) = flat.cell_size_m(); @@ -1801,6 +1859,106 @@ mod tests { assert_eq!(seen(0.1155), Some(false)); } + /// Viewsheds on DEMs whose answer is known from their geometry: flat ground (the horizon at + /// √(2·R′·h)), a bowl (every cell seen), a dome (seen up to where the line from the eye + /// touches it, at √(h / k′)), and a wall (the cells in its shadow hidden). The Earth's + /// curvature for visible light (`SIGHT_RADIUS_M`) is part of each answer. Cells within a cell + /// and a half of a boundary, where a grid can't say which side a cell is on, aren't counted. + /// Bilinear heights get every other cell right on all four; nearest heights hide some of the + /// dome just inside its horizon, and are right on the other three. + #[test] + fn viewsheds_give_the_known_answers_of_flat_ground_a_bowl_a_dome_and_a_wall() { + // 201 × 201 cells of 0.00027° (about 30 m) on the equator, the observer at the centre. + let (n, half, step) = (201u32, 100i64, 0.00027); + let transform = GeoTransform { origin_x: 0.0, origin_y: step * f64::from(n) / 2.0, pixel_width: step, pixel_height: -step }; + let blank = Raster::new("dem", n, n, vec![vec![0.0; (n * n) as usize]], transform, Crs::LonLat, None, ColorHint::Gray, "Float32") + .unwrap_or_else(|e| panic!("{e}")); + let (cx, cy) = blank.cell_size_m(); + let at = |col: i64, row: i64| ((col - half) as f64 * cx, (row - half) as f64 * cy); + let dem = |z: &dyn Fn(f64, f64) -> f64| { + let mut r = blank.clone(); + if let Some(b) = r.bands.get_mut(0) { + for (i, v) in b.data.iter_mut().enumerate() { + let (x, y) = at(i as i64 % i64::from(n), i as i64 / i64::from(n)); + *v = z(x, y) as f32; + } + } + r + }; + let eye = Coord::new(step * (half as f64 + 0.5), step * (f64::from(n) / 2.0 - half as f64 - 0.5)); + let radius = 3_000.0; + let band = 1.5 * cx.max(cy); + let drop = |d: f64| d * d / (2.0 * SIGHT_RADIUS_M); + // Cells seen wrongly, and those counted, for `expected` (None: on a boundary, or outside). + let wrong = |r: &Raster, h: f64, heights: Heights, expected: &dyn Fn(i64, i64, f64) -> Option| { + let vs = viewshed(r, 0, eye, h, radius, heights).unwrap_or_else(|e| panic!("{e}")); + let (mut bad, mut counted) = (0usize, 0usize); + for row in 0..i64::from(n) { + for col in 0..i64::from(n) { + let (x, y) = at(col, row); + let d = x.hypot(y); + let Some(want) = (d > 0.0 && d <= radius).then(|| expected(col, row, d)).flatten() else { continue }; + let got = vs.get((row * i64::from(n) + col) as usize).copied(); + counted += 1; + bad += usize::from(got != Some(if want { 1.0 } else { 0.0 })); + } + } + (bad, counted) + }; + let before = |d: f64, edge: f64| if (d - edge).abs() <= band { None } else { Some(d < edge) }; + + // Flat ground, an eye 0.5 m up: the horizon at √(2·R′·h), about 2.7 km. + let flat = dem(&|_, _| 0.0); + let horizon = (2.0 * SIGHT_RADIUS_M * 0.5).sqrt(); + for heights in [Heights::Nearest, Heights::Bilinear] { + let (bad, counted) = wrong(&flat, 0.5, heights, &|_, _, d| before(d, horizon)); + assert!(bad == 0 && counted > 20_000, "flat, {heights:?}: {bad} of {counted} wrong"); + } + + // A bowl rising 4 m a kilometre squared (z = k·d², far steeper than the Earth curves + // away): every cell is seen. + let bowl = dem(&|x, y| 4e-6 * (x * x + y * y)); + for heights in [Heights::Nearest, Heights::Bilinear] { + let (bad, counted) = wrong(&bowl, 2.0, heights, &|_, _, _| Some(true)); + assert!(bad == 0 && counted > 20_000, "bowl, {heights:?}: {bad} of {counted} wrong"); + } + + // A dome falling 10 m a kilometre squared from its top, the eye 10 m up there: with the + // Earth's curve, the ground falls k′ = k + 1/(2R′) a metre squared, and the line from the + // eye touches it at √(h / k′), about 1 km; beyond, the dome hides the ground. + let k = 1e-5; + let dome = dem(&|x, y| 500.0 - k * (x * x + y * y)); + let edge = (10.0 / (k + 1.0 / (2.0 * SIGHT_RADIUS_M))).sqrt(); + let (bad, counted) = wrong(&dome, 10.0, Heights::Bilinear, &|_, _, d| before(d, edge)); + assert!(bad == 0 && counted > 20_000, "dome, bilinear: {bad} of {counted} wrong"); + let (bad_nearest, _) = wrong(&dome, 10.0, Heights::Nearest, &|_, _, d| before(d, edge)); + assert!(bad_nearest > 0, "nearest heights hide some of the dome just inside its horizon"); + + // A wall 50 m high, a column of cells 20 cells east of the eye (2 m up): beyond it, a cell + // is hidden when the wall's top stands above the line from the eye to it. Rays mostly east + // or west, which cross the wall at a cell's centre line, are counted; others cross it + // between columns, where where it stands depends on how the ground is read. + let wall_col = half + 20; + let wall = dem(&|x, _| if (x - 20.0 * cx).abs() < cx / 2.0 { 50.0 } else { 0.0 }); + let z0 = 2.0; + let shadow = |col: i64, row: i64, d: f64| -> Option { + let (dc, dr) = (col - half, row - half); + if col == wall_col || dr.abs() > dc.abs() { + return None; + } + if col < wall_col { + return Some(true); + } + let dw = d * (20.0 / dc as f64); + let over = (50.0 - drop(dw) - z0) / dw * d - (-drop(d) - z0); + if over.abs() < 1.0 { None } else { Some(over < 0.0) } + }; + for heights in [Heights::Nearest, Heights::Bilinear] { + let (bad, counted) = wrong(&wall, z0, heights, &shadow); + assert!(bad == 0 && counted > 10_000, "wall, {heights:?}: {bad} of {counted} wrong"); + } + } + /// A run past one thread's work, on one thread, is refused, naming the cap and the threads. #[test] fn idw_past_one_threads_work_is_refused_on_one_naming_the_cap() { @@ -2152,7 +2310,7 @@ mod tests { *v = if i % 20 == 10 { 500.0 } else { 0.0 }; } } - let vs = viewshed(&wall, 0, Coord::new(0.0025, 0.0105), 2.0, 5_000.0).unwrap_or_default(); + let vs = viewshed(&wall, 0, Coord::new(0.0025, 0.0105), 2.0, 5_000.0, Heights::Nearest).unwrap_or_default(); assert_eq!(vs[10 * 20 + 5], 1.0); assert_eq!(vs[10 * 20 + 15], 0.0); let (seen, prof) = diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 18206d192b..7719c05cc4 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -60,7 +60,7 @@ pub fn commands() -> Vec { r#"{"criteria": [{"layer": raster, "band"?: 1-based, "ranges": [[lo, hi, score]], "weight": number}], "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#, ), C::new("analysis.viewshed", "Visibility Analysis", "Analyze › Workflows", viewshed).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"layer": elevation raster, "lon", "lat", "band"?: 1-based, "height"?: observer metres, "radius"?: metres, "name"?: output, "ran"?: (internal: a viewshed the app has worked out)}"#), + .params(r#"{"layer": elevation raster, "lon", "lat", "band"?: 1-based, "height"?: observer metres, "radius"?: metres, "heights"?: "nearest" (default) | "bilinear" (the ground along each ray), "name"?: output, "ran"?: (internal: a viewshed the app has worked out)}"#), C::new("analysis.lineOfSight", "Line Of Sight", "Analyze › Workflows", line_of_sight).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"layer": elevation raster, "from": [lon, lat], "to": [lon, lat], "band"?: 1-based, "observerHeight"?: m, "targetHeight"?: m, "name"?: output}"#, ), @@ -1086,9 +1086,14 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { // The whole raster by default: its diagonal reaches every cell from any observer. let radius = f(p, "radius").unwrap_or((cx * dem.width as f64).hypot(cy * dem.height as f64)).clamp(1.0, 500_000.0); let height = f(p, "height").unwrap_or(1.7).clamp(0.0, 10_000.0); + // How the ground along each ray is read: the cell a point falls in, or between cells. + let heights = match ps(p, "heights") { + None => rasterops::Heights::Nearest, + Some(h) => rasterops::Heights::named(h).ok_or_else(|| format!("heights must be \"nearest\" or \"bilinear\", not \"{h}\""))?, + }; let name = out_name(p, format!("{}_viewshed", dem.name)); Ok(Box::new(move || { - let vs = rasterops::viewshed(&dem, band, at, height, radius)?; + let vs = rasterops::viewshed(&dem, band, at, height, radius, heights)?; let seen = vs.iter().filter(|v| **v == 1.0).count(); made(rasterops::derive(&dem, &name, vec![vs])?, Some(json!({"visibleCells": seen}))) })) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b1d5148fbe..9f754e5226 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9298,6 +9298,12 @@ fn analysis_workflows_models_scripts_and_raster_functions() { // On the flat northern edge: everything west of the wall is in view. let v = s.run("analysis.viewshed", &json!({"layer": dem, "lon": 10.0055, "lat": 45.0395, "height": 2})).unwrap(); assert!(v["visibleCells"].as_u64().unwrap() > 100, "{v}"); + // Bilinear heights read the ground between cells; any other name is refused, saying which + // there are. + let b = s.run("analysis.viewshed", &json!({"layer": dem, "lon": 10.0055, "lat": 45.0395, "height": 2, "heights": "bilinear"})).unwrap(); + assert!(b["visibleCells"].as_u64().unwrap() > 100, "{b}"); + let e = s.run("analysis.viewshed", &json!({"layer": dem, "lon": 10.0055, "lat": 45.0395, "heights": "cubic"})).unwrap_err(); + assert!(e.to_string().contains(r#"heights must be "nearest" or "bilinear", not "cubic""#), "{e}"); let los = s.run("analysis.lineOfSight", &json!({"layer": dem, "from": [10.0205, 45.0395], "to": [10.0355, 45.0395]})).unwrap(); assert_eq!(los["visible"], false); let los = s.run("analysis.lineOfSight", &json!({"layer": dem, "from": [10.0205, 45.0395], "to": [10.0055, 45.0395]})).unwrap(); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 7efd4ddc49..06e54d7184 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1224,7 +1224,7 @@ click them on the map: | Raster Functions | Slope, aspect, hillshade, NDVI, band math (`(b4-b3)/(b4+b3)`), remapping, thresholds, resampling | | Function Editor | Chains raster functions, each on the previous output | | Suitability Modeler | Scores rasters 1–10 and adds them with weights | -| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`) | +| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` reads it between the cells' centres instead, as GRASS's `r.viewshed` does, which is right on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon | | Exploratory 3D Analysis | A line of sight between two points, split into seen and hidden parts, with the same curvature and refraction | | Geostatistical Wizard | An IDW surface from feature values, using 12 nearest neighbours by default | | Network Analysis | The shortest (or cheapest, by a cost field) route over a line layer | From f59f6e4633bc3c75c95af556fe674610b8de6088 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Wed, 11 Nov 2026 13:51:59 +0100 Subject: [PATCH 02/12] fix(analysis): Viewshed says what no-data ground its rays crossed; Ground heights in the Workflows pane --- crates/analysis/src/rasterops.rs | 131 +++++++++++++++++++++-------- crates/engine/src/cmd/workflows.rs | 41 +++++++-- crates/engine/src/tests.rs | 60 +++++++++++-- crates/ui-egui/src/analysispane.rs | 21 +++++ docs/user-guide/analysis.md | 2 +- 5 files changed, 208 insertions(+), 47 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 8f5d644556..c905bad92c 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -442,27 +442,31 @@ pub enum Heights { /// can hide cells just inside the horizon. #[default] Nearest, - /// Between the cells' centres, in proportion to how near the point is to each (bilinear), as - /// GRASS's `r.viewshed` reads it: smoother, and right on bulging ground. Where one of those - /// cells has no data, the cell the point falls in, as [`Heights::Nearest`] reads it. + /// Between the cells' centres, in proportion to how near the point is to each (bilinear): + /// smoother, and right on bulging ground. Where one of those cells has no data, the cell the + /// point falls in, as [`Heights::Nearest`] reads it (counted: [`Viewshed::read_nearest`]). Bilinear, } impl Heights { - /// The one named `name` (`nearest`, `bilinear`); `None` for any other. + /// The one named `name` (`nearest`, `bilinear`, in any case); `None` for any other. pub fn named(name: &str) -> Option { - match name { - "nearest" => Some(Heights::Nearest), - "bilinear" => Some(Heights::Bilinear), - _ => None, + if name.eq_ignore_ascii_case("nearest") { + Some(Heights::Nearest) + } else if name.eq_ignore_ascii_case("bilinear") { + Some(Heights::Bilinear) + } else { + None } } - /// The ground at a point of a ray, `(col, row)` in cells (whole numbers at cell centres). - fn at(self, r: &Raster, b: usize, col: f64, row: f64) -> Option { - let nearest = || r.value(b, col.round() as i64, row.round() as i64); + /// The ground at a point of a ray, `(col, row)` in cells (whole numbers at cell centres), and + /// whether it is the nearest cell's, read in place of cells between which a neighbour has + /// no data. `None` where the point's own cell has no data. + fn at(self, r: &Raster, b: usize, col: f64, row: f64) -> Option<(f64, bool)> { + let nearest = |fell_back: bool| r.value(b, col.round() as i64, row.round() as i64).map(|v| (f64::from(v), fell_back)); if self == Heights::Nearest { - return nearest(); + return nearest(false); } let (c0, r0) = (col.floor(), row.floor()); let (tx, ty) = (col - c0, row - r0); @@ -476,17 +480,30 @@ impl Heights { } match r.value(b, c0 + dc, r0 + dr) { Some(v) => sum += wgt * f64::from(v), - None => return nearest(), + None => return nearest(true), } } - Some(sum as f32) + Some((sum, false)) } } +/// A viewshed: each cell visible (1) or not (0), no-data outside the radius, and how many cells' +/// rays read the ground less than fully. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Viewshed { + pub cells: Vec, + /// Cells whose ray crossed ground with no data, taken as hiding nothing there. + pub through_gaps: usize, + /// Cells whose ray, read [`Heights::Bilinear`], took the nearest cell's height somewhere, + /// a cell it would read between having no data. + pub read_nearest: usize, +} + /// Cells visible from an observer (1) or not (0) within `radius_m`; outside the radius no-data. /// The Earth curves as visible light sees it (`SIGHT_RADIUS_M`). The ground along each ray is read -/// as `heights` says. -pub fn viewshed(r: &Raster, b: usize, observer: Coord, height: f64, radius_m: f64, heights: Heights) -> Result, String> { +/// as `heights` says; ground with no data hides nothing, and the cells whose rays crossed some are +/// counted. +pub fn viewshed(r: &Raster, b: usize, observer: Coord, height: f64, radius_m: f64, heights: Heights) -> Result { viewshed_on(None, r, b, observer, height, radius_m, heights) } @@ -499,7 +516,7 @@ fn viewshed_on( height: f64, radius_m: f64, heights: Heights, -) -> Result, String> { +) -> Result { let (oc, or) = r.pixel_at(observer).ok_or("the observer is outside the raster")?; let z0 = r.value(b, oc, or).ok_or("the observer stands on no-data")? as f64 + height; let (cx, cy) = r.cell_size_m(); @@ -533,6 +550,8 @@ fn viewshed_on( let w = r.width as usize; let mut out = new_band(w, r.height as usize, NODATA)?; let window = out.chunks_mut(w).skip(usize::try_from(first).unwrap_or(0)).take(rows); + // Summed across threads: the same counts on any number. + let (through_gaps, read_nearest) = (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0)); crate::control::begin(rows); crate::parallel::for_each_row(window, threads, crate::control::Pace::default, |pace, i, line: &mut [f32]| { let row = first + i as i64; @@ -557,22 +576,39 @@ fn viewshed_on( return; } let mut visible = true; + let (mut gap, mut nearest) = (false, false); + // Along the longer axis the ray steps a whole cell at a time, so that coordinate is + // exact; along the other it falls between cells. + let (dc, dr) = (col - oc, row - or); + let along = |o: i64, d: i64, s: usize, t: f64| { + if d.unsigned_abs() as usize == steps { (o + d.signum() * s as i64) as f64 } else { o as f64 + d as f64 * t } + }; for s in 1..steps { let t = s as f64 / steps as f64; - let (c, rr) = (oc as f64 + (col - oc) as f64 * t, or as f64 + (row - or) as f64 * t); - let Some(zi) = heights.at(r, b, c, rr) else { continue }; + let (c, rr) = (along(oc, dc, s, t), along(or, dr, s, t)); + let Some((zi, fell_back)) = heights.at(r, b, c, rr) else { + gap = true; + continue; + }; + nearest |= fell_back; let di = dist * t; - if (zi as f64 - di * di / (2.0 * SIGHT_RADIUS_M) - z0) / di > target { + if (zi - di * di / (2.0 * SIGHT_RADIUS_M) - z0) / di > target { visible = false; break; } } + if gap { + through_gaps.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + if nearest { + read_nearest.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } if let Some(o) = line.get_mut(col as usize) { *o = if visible { 1.0 } else { 0.0 }; } } })?; - Ok(out) + Ok(Viewshed { cells: out, through_gaps: through_gaps.into_inner(), read_nearest: read_nearest.into_inner() }) } /// Inverse distance weighted interpolation of point values onto a grid in `crs`, from each cell's @@ -1654,12 +1690,16 @@ mod tests { for (at, radius, expected) in [(Coord::new(0.012, 44.990), 500.0, [207, 775, 5318]), (Coord::new(0.003, 44.985), 5_000.0, [185, 6050, 65])] { - let one = viewshed_on(Some(1), &dem, 0, at, 2.0, radius, Heights::Nearest).unwrap_or_else(|e| panic!("{e}")); + let one_run = viewshed_on(Some(1), &dem, 0, at, 2.0, radius, Heights::Nearest).unwrap_or_else(|e| panic!("{e}")); + // Rays crossing the DEM's no-data cells are counted, and as many on any thread count. + assert!(one_run.through_gaps > 0 && one_run.read_nearest == 0, "radius {radius}: {}", one_run.through_gaps); + let one = &one_run.cells; let counts = [1.0, 0.0, NODATA].map(|k| one.iter().filter(|v| v.to_bits() == k.to_bits()).count()); assert_eq!(counts, expected, "radius {radius}"); for threads in [2, 7, 16] { let many = viewshed_on(Some(threads), &dem, 0, at, 2.0, radius, Heights::Nearest).unwrap_or_else(|e| panic!("{e}")); - assert!(one.iter().map(|v| v.to_bits()).eq(many.iter().map(|v| v.to_bits())), "{threads} threads, radius {radius}"); + assert_eq!(many.through_gaps, one_run.through_gaps, "{threads} threads, radius {radius}"); + assert!(one.iter().map(|v| v.to_bits()).eq(many.cells.iter().map(|v| v.to_bits())), "{threads} threads, radius {radius}"); } } } @@ -1847,7 +1887,7 @@ mod tests { let eye = Coord::new(0.0005, 0.0); // √(2 · 7/6 · 6,371 km · 10 m), written out so that the test pins the radius. let horizon = 12_192.0; - let vs = viewshed(&flat, 0, eye, 10.0, 20_000.0, Heights::Nearest).unwrap_or_else(|e| panic!("{e}")); + let vs = viewshed(&flat, 0, eye, 10.0, 20_000.0, Heights::Nearest).unwrap_or_else(|e| panic!("{e}")).cells; let row = &vs[w as usize..2 * w as usize]; let last = row.iter().rposition(|v| *v == 1.0).unwrap_or(0); let (cx, _) = flat.cell_size_m(); @@ -1861,7 +1901,8 @@ mod tests { /// Viewsheds on DEMs whose answer is known from their geometry: flat ground (the horizon at /// √(2·R′·h)), a bowl (every cell seen), a dome (seen up to where the line from the eye - /// touches it, at √(h / k′)), and a wall (the cells in its shadow hidden). The Earth's + /// touches it, at √(h / k′)), and a wall lower than the eye (the cells in its shadow hidden, + /// those beyond it seen again). The Earth's /// curvature for visible light (`SIGHT_RADIUS_M`) is part of each answer. Cells within a cell /// and a half of a boundary, where a grid can't say which side a cell is on, aren't counted. /// Bilinear heights get every other cell right on all four; nearest heights hide some of the @@ -1891,7 +1932,7 @@ mod tests { let drop = |d: f64| d * d / (2.0 * SIGHT_RADIUS_M); // Cells seen wrongly, and those counted, for `expected` (None: on a boundary, or outside). let wrong = |r: &Raster, h: f64, heights: Heights, expected: &dyn Fn(i64, i64, f64) -> Option| { - let vs = viewshed(r, 0, eye, h, radius, heights).unwrap_or_else(|e| panic!("{e}")); + let vs = viewshed(r, 0, eye, h, radius, heights).unwrap_or_else(|e| panic!("{e}")).cells; let (mut bad, mut counted) = (0usize, 0usize); for row in 0..i64::from(n) { for col in 0..i64::from(n) { @@ -1934,13 +1975,20 @@ mod tests { let (bad_nearest, _) = wrong(&dome, 10.0, Heights::Nearest, &|_, _, d| before(d, edge)); assert!(bad_nearest > 0, "nearest heights hide some of the dome just inside its horizon"); - // A wall 50 m high, a column of cells 20 cells east of the eye (2 m up): beyond it, a cell - // is hidden when the wall's top stands above the line from the eye to it. Rays mostly east - // or west, which cross the wall at a cell's centre line, are counted; others cross it - // between columns, where where it stands depends on how the ground is read. + // A wall 1 m high, a column of cells 20 cells (about 600 m) east of an eye 2 m up: beyond it, + // a cell is hidden while the line from the eye over the wall's top passes above it, and + // seen again once the line has come down below the ground (at about 1.2 km on a flat + // Earth, a little farther with its curve). Rays mostly east or west, + // which cross the wall at a cell's centre line, are counted; others cross it between + // columns, where where it stands depends on how the ground is read. let wall_col = half + 20; - let wall = dem(&|x, _| if (x - 20.0 * cx).abs() < cx / 2.0 { 50.0 } else { 0.0 }); + let wall = dem(&|x, _| if (x - 20.0 * cx).abs() < cx / 2.0 { 1.0 } else { 0.0 }); let z0 = 2.0; + // How far the line over the wall's top passes above the cell (negative: below it). + let over = |col: i64, d: f64| { + let dw = d * (20.0 / (col - half) as f64); + (1.0 - drop(dw) - z0) / dw * d - (-drop(d) - z0) + }; let shadow = |col: i64, row: i64, d: f64| -> Option { let (dc, dr) = (col - half, row - half); if col == wall_col || dr.abs() > dc.abs() { @@ -1949,10 +1997,23 @@ mod tests { if col < wall_col { return Some(true); } - let dw = d * (20.0 / dc as f64); - let over = (50.0 - drop(dw) - z0) / dw * d - (-drop(d) - z0); - if over.abs() < 1.0 { None } else { Some(over < 0.0) } + let over = over(col, d); + if over.abs() < 0.05 { None } else { Some(over < 0.0) } }; + // Both sides of the shadow's edge are counted, not only the shadow. + let (mut hidden, mut seen_past) = (0usize, 0usize); + for row in 0..i64::from(n) { + for col in wall_col + 1..i64::from(n) { + let (x, y) = at(col, row); + let d = x.hypot(y); + match (d <= radius).then(|| shadow(col, row, d)).flatten() { + Some(false) => hidden += 1, + Some(true) => seen_past += 1, + None => {} + } + } + } + assert!(hidden > 1_000 && seen_past > 1_000, "{hidden} hidden, {seen_past} seen past the wall"); for heights in [Heights::Nearest, Heights::Bilinear] { let (bad, counted) = wrong(&wall, z0, heights, &shadow); assert!(bad == 0 && counted > 10_000, "wall, {heights:?}: {bad} of {counted} wrong"); @@ -2310,7 +2371,7 @@ mod tests { *v = if i % 20 == 10 { 500.0 } else { 0.0 }; } } - let vs = viewshed(&wall, 0, Coord::new(0.0025, 0.0105), 2.0, 5_000.0, Heights::Nearest).unwrap_or_default(); + let vs = viewshed(&wall, 0, Coord::new(0.0025, 0.0105), 2.0, 5_000.0, Heights::Nearest).unwrap_or_default().cells; assert_eq!(vs[10 * 20 + 5], 1.0); assert_eq!(vs[10 * 20 + 15], 0.0); let (seen, prof) = diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 7719c05cc4..50df2aa8f6 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1087,15 +1087,46 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { let radius = f(p, "radius").unwrap_or((cx * dem.width as f64).hypot(cy * dem.height as f64)).clamp(1.0, 500_000.0); let height = f(p, "height").unwrap_or(1.7).clamp(0.0, 10_000.0); // How the ground along each ray is read: the cell a point falls in, or between cells. - let heights = match ps(p, "heights") { - None => rasterops::Heights::Nearest, - Some(h) => rasterops::Heights::named(h).ok_or_else(|| format!("heights must be \"nearest\" or \"bilinear\", not \"{h}\""))?, + let heights = match p.get("heights") { + None | Some(Value::Null) => rasterops::Heights::Nearest, + Some(Value::String(h)) => { + rasterops::Heights::named(h).ok_or_else(|| format!("heights must be \"nearest\" or \"bilinear\", not \"{h}\""))? + } + Some(other) => return Err(format!("heights must be \"nearest\" or \"bilinear\", not {other}")), }; let name = out_name(p, format!("{}_viewshed", dem.name)); + let dem_name = dem.name.clone(); Ok(Box::new(move || { let vs = rasterops::viewshed(&dem, band, at, height, radius, heights)?; - let seen = vs.iter().filter(|v| **v == 1.0).count(); - made(rasterops::derive(&dem, &name, vec![vs])?, Some(json!({"visibleCells": seen}))) + let seen = vs.cells.iter().filter(|v| **v == 1.0).count(); + let (through_gaps, read_nearest) = (vs.through_gaps, vs.read_nearest); + let m = made(rasterops::derive(&dem, &name, vec![vs.cells])?, Some(json!({"visibleCells": seen})))?; + if through_gaps == 0 && read_nearest == 0 { + return Ok(m); + } + // Ground with no data hides nothing, and bilinear heights read the nearest cell beside + // it: said, with how many cells it touched. + let then: Then = Box::new(move |s: &mut Session, v: &mut Value| { + if through_gaps > 0 { + s.notify( + format!( + "{dem_name}: {through_gaps} cell(s) of the viewshed were seen across ground with no data, taken as hiding nothing" + ), + false, + ); + } + if read_nearest > 0 { + s.notify( + format!("{dem_name}: {read_nearest} cell(s) of the viewshed were seen with the nearest cell's height next to ground with no data, not between cells"), + false, + ); + } + if let Some(o) = v.as_object_mut() { + o.insert("acrossNoData".into(), json!(through_gaps)); + o.insert("readNearest".into(), json!(read_nearest)); + } + }); + Ok(Made { then: Some(then), ..m }) })) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9f754e5226..24779e7b08 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9246,6 +9246,48 @@ fn dem_b64() -> String { base64::engine::general_purpose::STANDARD.encode(geotiff::write(&r, 0).unwrap()) } +/// A viewshed whose rays cross ground with no data says how many cells it saw across it, taken as +/// hiding nothing, and, with bilinear heights, how many it saw with the nearest cell's height +/// beside it; one with data everywhere says neither (see +/// `analysis_workflows_models_scripts_and_raster_functions`). +#[test] +fn a_viewshed_says_what_ground_with_no_data_it_saw_across() { + use base64::Engine; + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; + let mut s = world(); + // Flat ground with a column of no-data cells five cells east of the observer. + let gt = GeoTransform { origin_x: 10.0, origin_y: 45.04, pixel_width: 0.001, pixel_height: -0.001 }; + let z: Vec = (0..1600).map(|i| if i % 40 == 15 { -9999.0 } else { 200.0 }).collect(); + let r = Raster::new("holes", 40, 40, vec![z], gt, Crs::LonLat, Some(-9999.0), ColorHint::Gray, "Float32").unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(geotiff::write(&r, 0).unwrap()); + s.run("layer.addDataBytes", &json!({"fileName": "holes.tif", "data": data})).unwrap(); + let dem = s.map().layers.iter().find(|l| l.is_raster()).unwrap().name.clone(); + let at = json!({"layer": dem, "lon": 10.0105, "lat": 45.0205, "height": 2}); + for heights in ["nearest", "bilinear"] { + let mark = s.notices.len(); + let mut p = at.clone(); + p["heights"] = json!(heights); + let v = s.run("analysis.viewshed", &p).unwrap(); + let across = v["acrossNoData"].as_u64().unwrap(); + assert!(across > 100, "{heights}: {v}"); + let said: Vec<&str> = s.notices[mark..].iter().map(|n| n.text.as_str()).collect(); + assert!( + said.iter().any(|t| t.contains(&format!("{across} cell(s) of the viewshed were seen across ground with no data"))), + "{heights}: {said:?}" + ); + let nearest = v["readNearest"].as_u64().unwrap(); + if heights == "nearest" { + assert_eq!(nearest, 0); + } else { + assert!(nearest > 100, "{v}"); + assert!( + said.iter().any(|t| t.contains(&format!("{nearest} cell(s) of the viewshed were seen with the nearest cell's height"))), + "{said:?}" + ); + } + } +} + #[test] fn analysis_workflows_models_scripts_and_raster_functions() { let mut s = world(); @@ -9298,12 +9340,18 @@ fn analysis_workflows_models_scripts_and_raster_functions() { // On the flat northern edge: everything west of the wall is in view. let v = s.run("analysis.viewshed", &json!({"layer": dem, "lon": 10.0055, "lat": 45.0395, "height": 2})).unwrap(); assert!(v["visibleCells"].as_u64().unwrap() > 100, "{v}"); - // Bilinear heights read the ground between cells; any other name is refused, saying which - // there are. - let b = s.run("analysis.viewshed", &json!({"layer": dem, "lon": 10.0055, "lat": 45.0395, "height": 2, "heights": "bilinear"})).unwrap(); - assert!(b["visibleCells"].as_u64().unwrap() > 100, "{b}"); - let e = s.run("analysis.viewshed", &json!({"layer": dem, "lon": 10.0055, "lat": 45.0395, "heights": "cubic"})).unwrap_err(); - assert!(e.to_string().contains(r#"heights must be "nearest" or "bilinear", not "cubic""#), "{e}"); + // Bilinear heights read the ground between cells: on this hill and wall they see at least + // what the nearest cells do (a cell nearer the top no longer stands in for the ground), and + // little more. Any other name, or a value that isn't one, is refused, saying which there are. + let b = s.run("analysis.viewshed", &json!({"layer": dem, "lon": 10.0055, "lat": 45.0395, "height": 2, "heights": "Bilinear"})).unwrap(); + let (near, bil) = (v["visibleCells"].as_u64().unwrap(), b["visibleCells"].as_u64().unwrap()); + assert!(bil >= near && bil <= near + near / 10, "nearest {near}, bilinear {bil}"); + // A DEM with every cell holding data: nothing to say about ground with none. + assert!(b.get("acrossNoData").is_none() && v.get("acrossNoData").is_none(), "{b}"); + for bad in [json!("cubic"), json!(1)] { + let e = s.run("analysis.viewshed", &json!({"layer": dem, "lon": 10.0055, "lat": 45.0395, "heights": bad})).unwrap_err(); + assert!(e.to_string().contains(r#"heights must be "nearest" or "bilinear", not "#), "{e}"); + } let los = s.run("analysis.lineOfSight", &json!({"layer": dem, "from": [10.0205, 45.0395], "to": [10.0355, 45.0395]})).unwrap(); assert_eq!(los["visible"], false); let los = s.run("analysis.lineOfSight", &json!({"layer": dem, "from": [10.0205, 45.0395], "to": [10.0055, 45.0395]})).unwrap(); diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 9a94af648c..736fda2b03 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -24,6 +24,8 @@ pub struct Workflow { pub field: String, pub number: String, pub number2: String, + /// The viewshed reads the ground between cells (bilinear heights), not the nearest cell. + pub bilinear: bool, pub text: String, pub function: String, pub chain: Vec, @@ -685,12 +687,31 @@ pub fn workflows(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { ui.add(egui::TextEdit::singleline(&mut app.workflow.number).hint_text(tl!("observer height m")).desired_width(110.0)); ui.add(egui::TextEdit::singleline(&mut app.workflow.number2).hint_text(tl!("radius m")).desired_width(80.0)); }); + // How the ground along each ray is read. + ui.horizontal(|ui| { + ui.label(tl!("Ground heights")); + let (nearest, between) = (tl!("Nearest cell"), tl!("Between cells (bilinear)")); + egui::ComboBox::from_id_salt("wf_v_heights") + .selected_text(if app.workflow.bilinear { between } else { nearest }) + .width(170.0) + .show_ui(ui, |ui| { + ui.selectable_value(&mut app.workflow.bilinear, false, nearest); + ui.selectable_value(&mut app.workflow.bilinear, true, between); + }) + .response + .on_hover_text(tl!( + "How the ground between the observer and a cell is read: the cell each point falls in, or between the cells' centres. Between cells is right on ground that bulges, a hill seen from its top, where the nearest cell can hide cells just inside the horizon." + )); + }); pick_button(app, ui, "viewshed", 1, "Click the observer on the map"); if let Some(p) = picked(app, "viewshed").and_then(|v| v.first().copied()) { let mut params = json!({"layer": app.workflow.layer, "lon": p.x, "lat": p.y, "height": num(&app.workflow.number, 1.7)}); if let Ok(r) = app.workflow.number2.trim().parse::() { params["radius"] = json!(r); } + if app.workflow.bilinear { + params["heights"] = json!("bilinear"); + } run(app, "analysis.viewshed", params); } } diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 06e54d7184..4a62afc6f8 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1224,7 +1224,7 @@ click them on the map: | Raster Functions | Slope, aspect, hillshade, NDVI, band math (`(b4-b3)/(b4+b3)`), remapping, thresholds, resampling | | Function Editor | Chains raster functions, each on the previous output | | Suitability Modeler | Scores rasters 1–10 and adds them with weights | -| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` reads it between the cells' centres instead, as GRASS's `r.viewshed` does, which is right on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon | +| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells** in the Workflows pane) reads it between the cells' centres instead, which is right on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon | | Exploratory 3D Analysis | A line of sight between two points, split into seen and hidden parts, with the same curvature and refraction | | Geostatistical Wizard | An IDW surface from feature values, using 12 nearest neighbours by default | | Network Analysis | The shortest (or cheapest, by a cost field) route over a line layer | From 8f8ddc65e22816276045c296f017e24ea14232ca Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Wed, 11 Nov 2026 15:39:28 +0100 Subject: [PATCH 03/12] fix(analysis): Viewshed counts only seen cells across no-data, reads exact positions between cells, and checks bilinear on several threads --- crates/analysis/src/rasterops.rs | 34 +++++++++++++++---------- crates/engine/src/cmd/workflows.rs | 2 +- crates/engine/src/tests.rs | 40 +++++++++++++++++++++--------- docs/user-guide/analysis.md | 2 +- 4 files changed, 51 insertions(+), 27 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index c905bad92c..a78ad6860c 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -492,7 +492,7 @@ impl Heights { #[derive(Clone, Debug, Default, PartialEq)] pub struct Viewshed { pub cells: Vec, - /// Cells whose ray crossed ground with no data, taken as hiding nothing there. + /// Cells seen across ground with no data, taken as hiding nothing there. pub through_gaps: usize, /// Cells whose ray, read [`Heights::Bilinear`], took the nearest cell's height somewhere, /// a cell it would read between having no data. @@ -577,15 +577,14 @@ fn viewshed_on( } let mut visible = true; let (mut gap, mut nearest) = (false, false); - // Along the longer axis the ray steps a whole cell at a time, so that coordinate is - // exact; along the other it falls between cells. + // Along the longer axis the ray steps a whole cell at a time; along the other it falls + // between cells. Both are one division of whole numbers, so exact wherever the point + // lies on a cell's centre line (and no neighbour is weighed by a rounding error). let (dc, dr) = (col - oc, row - or); - let along = |o: i64, d: i64, s: usize, t: f64| { - if d.unsigned_abs() as usize == steps { (o + d.signum() * s as i64) as f64 } else { o as f64 + d as f64 * t } - }; + let along = |o: i64, d: i64, s: usize| o as f64 + (d * s as i64) as f64 / steps as f64; for s in 1..steps { let t = s as f64 / steps as f64; - let (c, rr) = (along(oc, dc, s, t), along(or, dr, s, t)); + let (c, rr) = (along(oc, dc, s), along(or, dr, s)); let Some((zi, fell_back)) = heights.at(r, b, c, rr) else { gap = true; continue; @@ -597,7 +596,8 @@ fn viewshed_on( break; } } - if gap { + // A hidden cell stays hidden whatever the missing ground is: only those seen count. + if gap && visible { through_gaps.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } if nearest { @@ -1672,7 +1672,7 @@ mod tests { } /// Viewshed rows made on several threads see what one thread sees (#1252), with the radius - /// inside the raster and reaching past its edges. + /// inside the raster and reaching past its edges, with nearest and bilinear heights. #[test] fn viewshed_on_several_threads_is_viewshed_on_one() { let (w, h) = (90u32, 70u32); @@ -1691,15 +1691,23 @@ mod tests { [(Coord::new(0.012, 44.990), 500.0, [207, 775, 5318]), (Coord::new(0.003, 44.985), 5_000.0, [185, 6050, 65])] { let one_run = viewshed_on(Some(1), &dem, 0, at, 2.0, radius, Heights::Nearest).unwrap_or_else(|e| panic!("{e}")); - // Rays crossing the DEM's no-data cells are counted, and as many on any thread count. + // Cells seen across the DEM's no-data cells are counted; nearest heights read no + // neighbours, so none falls back. assert!(one_run.through_gaps > 0 && one_run.read_nearest == 0, "radius {radius}: {}", one_run.through_gaps); let one = &one_run.cells; let counts = [1.0, 0.0, NODATA].map(|k| one.iter().filter(|v| v.to_bits() == k.to_bits()).count()); assert_eq!(counts, expected, "radius {radius}"); + // Bilinear heights read next to the no-data cells, so some cells take a nearest height. + let bilinear = viewshed_on(Some(1), &dem, 0, at, 2.0, radius, Heights::Bilinear).unwrap_or_else(|e| panic!("{e}")); + assert!(bilinear.through_gaps > 0 && bilinear.read_nearest > 0, "radius {radius}: {}", bilinear.read_nearest); for threads in [2, 7, 16] { - let many = viewshed_on(Some(threads), &dem, 0, at, 2.0, radius, Heights::Nearest).unwrap_or_else(|e| panic!("{e}")); - assert_eq!(many.through_gaps, one_run.through_gaps, "{threads} threads, radius {radius}"); - assert!(one.iter().map(|v| v.to_bits()).eq(many.cells.iter().map(|v| v.to_bits())), "{threads} threads, radius {radius}"); + for (heights, one_run) in [(Heights::Nearest, &one_run), (Heights::Bilinear, &bilinear)] { + let many = viewshed_on(Some(threads), &dem, 0, at, 2.0, radius, heights).unwrap_or_else(|e| panic!("{e}")); + let what = format!("{heights:?}, {threads} threads, radius {radius}"); + assert_eq!((many.through_gaps, many.read_nearest), (one_run.through_gaps, one_run.read_nearest), "{what}"); + let bits = |c: &[f32]| c.iter().map(|v| v.to_bits()).collect::>(); + assert_eq!(bits(&one_run.cells), bits(&many.cells), "{what}"); + } } } } diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 50df2aa8f6..ac787d0f0e 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1117,7 +1117,7 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { } if read_nearest > 0 { s.notify( - format!("{dem_name}: {read_nearest} cell(s) of the viewshed were seen with the nearest cell's height next to ground with no data, not between cells"), + format!("{dem_name}: {read_nearest} cell(s) of the viewshed were worked out with the nearest cell's height next to ground with no data, not between cells"), false, ); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 24779e7b08..739244b08f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9255,21 +9255,36 @@ fn a_viewshed_says_what_ground_with_no_data_it_saw_across() { use base64::Engine; use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; let mut s = world(); - // Flat ground with a column of no-data cells five cells east of the observer. + // Flat ground with a column of no-data cells five cells east of the observer, and the same + // with a high wall ten cells farther, hiding what lies beyond it. let gt = GeoTransform { origin_x: 10.0, origin_y: 45.04, pixel_width: 0.001, pixel_height: -0.001 }; - let z: Vec = (0..1600).map(|i| if i % 40 == 15 { -9999.0 } else { 200.0 }).collect(); - let r = Raster::new("holes", 40, 40, vec![z], gt, Crs::LonLat, Some(-9999.0), ColorHint::Gray, "Float32").unwrap(); - let data = base64::engine::general_purpose::STANDARD.encode(geotiff::write(&r, 0).unwrap()); - s.run("layer.addDataBytes", &json!({"fileName": "holes.tif", "data": data})).unwrap(); - let dem = s.map().layers.iter().find(|l| l.is_raster()).unwrap().name.clone(); - let at = json!({"layer": dem, "lon": 10.0105, "lat": 45.0205, "height": 2}); + let mut dems = vec![]; + for (name, wall) in [("holes", 200.0), ("walled", 400.0)] { + let z: Vec = (0..1600) + .map(|i| match i % 40 { + 15 => -9999.0, + 25 => wall, + _ => 200.0, + }) + .collect(); + let r = Raster::new(name, 40, 40, vec![z], gt, Crs::LonLat, Some(-9999.0), ColorHint::Gray, "Float32").unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(geotiff::write(&r, 0).unwrap()); + s.run("layer.addDataBytes", &json!({"fileName": format!("{name}.tif"), "data": data})).unwrap(); + dems.push(s.map().layers.iter().rev().find(|l| l.is_raster() && l.name.starts_with(name)).unwrap().name.clone()); + } + let run = |s: &mut Session, dem: &str, heights: &str| { + s.run("analysis.viewshed", &json!({"layer": dem, "lon": 10.0105, "lat": 45.0205, "height": 2, "heights": heights})).unwrap() + }; for heights in ["nearest", "bilinear"] { + // Only cells seen are counted: those the wall hides would stay hidden whatever the + // missing ground is. + let walled = run(&mut s, &dems[1], heights); + let walled_across = walled["acrossNoData"].as_u64().unwrap(); let mark = s.notices.len(); - let mut p = at.clone(); - p["heights"] = json!(heights); - let v = s.run("analysis.viewshed", &p).unwrap(); + let v = run(&mut s, &dems[0], heights); let across = v["acrossNoData"].as_u64().unwrap(); - assert!(across > 100, "{heights}: {v}"); + assert!(across > 100 && across <= v["visibleCells"].as_u64().unwrap(), "{heights}: {v}"); + assert!(walled_across > 0 && walled_across + 100 < across, "{heights}: {walled_across} of {across}"); let said: Vec<&str> = s.notices[mark..].iter().map(|n| n.text.as_str()).collect(); assert!( said.iter().any(|t| t.contains(&format!("{across} cell(s) of the viewshed were seen across ground with no data"))), @@ -9281,7 +9296,8 @@ fn a_viewshed_says_what_ground_with_no_data_it_saw_across() { } else { assert!(nearest > 100, "{v}"); assert!( - said.iter().any(|t| t.contains(&format!("{nearest} cell(s) of the viewshed were seen with the nearest cell's height"))), + said.iter() + .any(|t| t.contains(&format!("{nearest} cell(s) of the viewshed were worked out with the nearest cell's height"))), "{said:?}" ); } diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 4a62afc6f8..2b4340082a 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1224,7 +1224,7 @@ click them on the map: | Raster Functions | Slope, aspect, hillshade, NDVI, band math (`(b4-b3)/(b4+b3)`), remapping, thresholds, resampling | | Function Editor | Chains raster functions, each on the previous output | | Suitability Modeler | Scores rasters 1–10 and adds them with weights | -| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells** in the Workflows pane) reads it between the cells' centres instead, which is right on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon | +| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells (bilinear)** in the Workflows pane) reads it between the cells' centres instead, which is right on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon. Ground with no data hides nothing, and next to it bilinear heights take the nearest cell's height; the analysis says how many cells this touched, in a notice and as `acrossNoData` and `readNearest` in its answer | | Exploratory 3D Analysis | A line of sight between two points, split into seen and hidden parts, with the same curvature and refraction | | Geostatistical Wizard | An IDW surface from feature values, using 12 nearest neighbours by default | | Network Analysis | The shortest (or cheapest, by a cost field) route over a line layer | From c7200a07a2a9d4e02a803c55000bc13f66975932 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Wed, 11 Nov 2026 16:21:02 +0100 Subject: [PATCH 04/12] fix(analysis): Viewshed counts only the radius's cells within the raster, so an empty radius works on any DEM --- crates/analysis/src/rasterops.rs | 44 ++++++++++++++++++------ crates/ui-egui/src/analysispane.rs | 55 ++++++++++++++++++++++++++---- 2 files changed, 81 insertions(+), 18 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index a78ad6860c..ed104853b1 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -523,21 +523,20 @@ fn viewshed_on( if !(cx > 0.0 && cy > 0.0 && radius_m.is_finite() && radius_m > 0.0) { return Err("the raster's cells or the radius have no size".into()); } - // A tiny declared cell size would make the window overflow: bound it before converting. - if radius_m / cx > 100_000.0 || radius_m / cy > 100_000.0 { - return Err("the radius covers too many cells; use a smaller radius".into()); - } + // In cells (saturating: a radius of more cells than an i64 holds still reaches past the + // raster). Only the radius's cells within the raster are worked out, so a radius reaching + // past it (the whole DEM's diagonal, by default) costs no more than the raster, which is + // already in memory; the time is bounded by the ray steps below. let rad_c = (radius_m / cx).ceil() as i64; let rad_r = (radius_m / cy).ceil() as i64; + let (first, last) = (or.saturating_sub(rad_r).max(0), or.saturating_add(rad_r).min(r.height as i64 - 1)); + let (left, right) = (oc.saturating_sub(rad_c).max(0), oc.saturating_add(rad_c).min(r.width as i64 - 1)); // Each cell walks a ray back to the observer: bound cells × ray length, not just cells. - let cells = (2 * rad_c + 1).saturating_mul(2 * rad_r + 1); - let ray_work = usize::try_from(cells.saturating_mul(rad_c.max(rad_r) / 2 + 1)).unwrap_or(usize::MAX); - if cells > 25_000_000 { - return Err("the radius covers too many cells; use a smaller radius".into()); - } + let cells = (right - left + 1).saturating_mul(last - first + 1); + let longest = (oc - left).max(right - oc).max(or - first).max(last - or); + let ray_work = usize::try_from(cells.saturating_mul(longest / 2 + 1)).unwrap_or(usize::MAX); // Each cell walks its own ray and writes only itself, so the rows within the radius are made // on several threads when the work is large (#1252), and may take as many times the work. - let (first, last) = ((or - rad_r).max(0), (or + rad_r).min(r.height as i64 - 1)); let rows = usize::try_from(last - first + 1).unwrap_or(0); let threads = threads.unwrap_or_else(|| crate::parallel::threads_for_rows(rows, ray_work, 0)); let cap = crate::parallel::work_cap(MAX_VIEWSHED_WORK, threads); @@ -555,7 +554,7 @@ fn viewshed_on( crate::control::begin(rows); crate::parallel::for_each_row(window, threads, crate::control::Pace::default, |pace, i, line: &mut [f32]| { let row = first + i as i64; - for col in (oc - rad_c).max(0)..=(oc + rad_c).min(r.width as i64 - 1) { + for col in left..=right { let (dx, dy) = ((col - oc) as f64 * cx, (row - or) as f64 * cy); let dist = dx.hypot(dy); if dist > radius_m { @@ -1671,6 +1670,29 @@ mod tests { assert!(grid::(4, 5).is_ok_and(|g| g.is_empty() && g.capacity() >= 20)); } + /// A radius reaching far past the raster (the whole DEM's diagonal, as the command takes by + /// default) counts only the raster's cells: a strip 6,000 cells long, seen from one end, is + /// worked out, though the square the radius spans holds 144 million cells, as is one whose + /// radius spans more cells than a number holds. + #[test] + fn a_viewshed_radius_past_the_raster_counts_only_its_cells() { + let transform = GeoTransform { origin_x: 0.0, origin_y: 0.001, pixel_width: 0.001, pixel_height: -0.001 }; + let strip = Raster::new("strip", 6_000, 1, vec![vec![100.0; 6_000]], transform, Crs::LonLat, None, ColorHint::Gray, "Float32") + .unwrap_or_else(|e| panic!("{e}")); + let (cx, _) = strip.cell_size_m(); + let vs = viewshed(&strip, 0, Coord::new(0.0005, 0.0005), 2.0, cx * 6_000.0, Heights::Nearest).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(vs.cells.len(), 6_000); + // Every cell worked out (none left no-data): seen up to the horizon, hidden past it. + assert!(vs.cells.iter().all(|v| *v == 1.0 || *v == 0.0), "every cell worked out"); + assert!(vs.cells.contains(&1.0) && vs.cells.contains(&0.0), "seen and hidden"); + // A radius of more cells than an i64 holds, on cells declared a millimetre wide. + let tiny = GeoTransform { pixel_width: 1e-8, pixel_height: -1e-8, ..transform }; + let strip = Raster::new("strip", 50, 1, vec![vec![100.0; 50]], tiny, Crs::LonLat, None, ColorHint::Gray, "Float32") + .unwrap_or_else(|e| panic!("{e}")); + let vs = viewshed(&strip, 0, Coord::new(5e-9, 0.001 - 5e-9), 2.0, 1e300, Heights::Nearest).unwrap_or_else(|e| panic!("{e}")); + assert!(vs.cells.iter().all(|v| *v == 1.0), "{:?}", vs.cells); + } + /// Viewshed rows made on several threads see what one thread sees (#1252), with the radius /// inside the raster and reaching past its edges, with nearest and bilinear heights. #[test] diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 736fda2b03..560956dbea 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -401,6 +401,19 @@ fn num(s: &str, d: f64) -> f64 { s.trim().parse().unwrap_or(d) } +/// The viewshed's parameters from the pane, seen from `at`: an empty radius field leaves the +/// radius out, so the command takes the whole DEM. +fn viewshed_params(w: &Workflow, at: rustgis_engine::geom::Coord) -> Value { + let mut params = json!({"layer": w.layer, "lon": at.x, "lat": at.y, "height": num(&w.number, 1.7)}); + if let Ok(r) = w.number2.trim().parse::() { + params["radius"] = json!(r); + } + if w.bilinear { + params["heights"] = json!("bilinear"); + } + params +} + /// The sections of the Workflows pane: (id, title). pub const SECTIONS: &[(&str, &str)] = &[ ("rasterFunctions", "Raster Functions"), @@ -705,13 +718,7 @@ pub fn workflows(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { }); pick_button(app, ui, "viewshed", 1, "Click the observer on the map"); if let Some(p) = picked(app, "viewshed").and_then(|v| v.first().copied()) { - let mut params = json!({"layer": app.workflow.layer, "lon": p.x, "lat": p.y, "height": num(&app.workflow.number, 1.7)}); - if let Ok(r) = app.workflow.number2.trim().parse::() { - params["radius"] = json!(r); - } - if app.workflow.bilinear { - params["heights"] = json!("bilinear"); - } + let params = viewshed_params(&app.workflow, p); run(app, "analysis.viewshed", params); } } @@ -2059,6 +2066,40 @@ mod tests { use super::*; use egui_kittest::kittest::Queryable; + /// An empty radius field (or one of spaces) runs the viewshed over the whole DEM, also one + /// whose radius square, the DEM's diagonal each way, holds far more cells than the DEM. + #[test] + fn a_viewshed_with_an_empty_radius_field_sees_the_whole_dem() { + use base64::Engine; + use rustgis_engine::geom::Coord; + let mut app = RustGisApp::with_sample(); + use rustgis_engine::data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; + // A strip 4,000 cells long and 2 high: the DEM's diagonal each way spans 8,001 × 8,001 + // cells, 64 million, of which 8,000 are the DEM's. + let (w, h) = (4_000u32, 2u32); + let gt = GeoTransform { origin_x: 10.0, origin_y: 45.002, pixel_width: 0.001, pixel_height: -0.001 }; + let dem = + Raster::new("strip", w, h, vec![vec![200.0; (w * h) as usize]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(geotiff::write(&dem, 0).unwrap()); + app.session.run("layer.addDataBytes", &json!({"fileName": "strip.tif", "data": data})).unwrap(); + let layer = app.session.map().layers.iter().rev().find(|l| l.is_raster()).unwrap().name.clone(); + // As the farthest radius the command takes: flat ground seen up to its horizon, a few km. + let mut far = json!({"layer": layer, "lon": 10.0005, "lat": 45.0005, "height": 2.0, "radius": 500_000.0}); + let seen = app.session.run("analysis.viewshed", &far).unwrap()["visibleCells"].as_u64().unwrap(); + assert!(seen > 20 && seen < u64::from(w * h), "{seen}"); + far.as_object_mut().unwrap().remove("radius"); + for radius in ["", " "] { + let workflow = Workflow { layer: layer.clone(), number: "2".into(), number2: radius.into(), ..Default::default() }; + let p = viewshed_params(&workflow, Coord::new(10.0005, 45.0005)); + assert_eq!(p, far, "radius {radius:?}"); + let v = app.session.run("analysis.viewshed", &p).unwrap_or_else(|e| panic!("radius {radius:?}: {e}")); + assert_eq!(v["visibleCells"].as_u64(), Some(seen), "radius {radius:?}: {v}"); + } + // A number in the field is the radius. + let workflow = Workflow { layer, number2: " 5000 ".into(), ..Default::default() }; + assert_eq!(viewshed_params(&workflow, Coord::new(10.0005, 45.0005))["radius"], json!(5000.0)); + } + /// A Script pane run works its tools out on a thread of its own: the results say Running… /// until it lands, runs land in the order asked, and one cancelled or left says so. #[cfg(not(target_arch = "wasm32"))] From c89817318918bd0116dd216d3e0fa52859b1ffe1 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Wed, 11 Nov 2026 16:46:04 +0100 Subject: [PATCH 05/12] fix(analysis): an empty viewshed radius covers the whole DEM past 500 km; bilinear heights described as an estimate --- crates/analysis/src/rasterops.rs | 2 +- crates/engine/src/cmd/workflows.rs | 10 +++++-- crates/ui-egui/src/analysispane.rs | 44 ++++++++++++++++++++---------- docs/user-guide/analysis.md | 2 +- 4 files changed, 38 insertions(+), 20 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index ed104853b1..d8c9809aeb 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -443,7 +443,7 @@ pub enum Heights { #[default] Nearest, /// Between the cells' centres, in proportion to how near the point is to each (bilinear): - /// smoother, and right on bulging ground. Where one of those cells has no data, the cell the + /// smoother, and closer on bulging ground, though still an estimate. Where one of those cells has no data, the cell the /// point falls in, as [`Heights::Nearest`] reads it (counted: [`Viewshed::read_nearest`]). Bilinear, } diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index ac787d0f0e..1ae270f7e4 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -60,7 +60,7 @@ pub fn commands() -> Vec { r#"{"criteria": [{"layer": raster, "band"?: 1-based, "ranges": [[lo, hi, score]], "weight": number}], "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#, ), C::new("analysis.viewshed", "Visibility Analysis", "Analyze › Workflows", viewshed).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"layer": elevation raster, "lon", "lat", "band"?: 1-based, "height"?: observer metres, "radius"?: metres, "heights"?: "nearest" (default) | "bilinear" (the ground along each ray), "name"?: output, "ran"?: (internal: a viewshed the app has worked out)}"#), + .params(r#"{"layer": elevation raster, "lon", "lat", "band"?: 1-based, "height"?: observer metres, "radius"?: metres (at most 500 km; default: the whole raster), "heights"?: "nearest" (default) | "bilinear" (the ground along each ray), "name"?: output, "ran"?: (internal: a viewshed the app has worked out)}"#), C::new("analysis.lineOfSight", "Line Of Sight", "Analyze › Workflows", line_of_sight).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"layer": elevation raster, "from": [lon, lat], "to": [lon, lat], "band"?: 1-based, "observerHeight"?: m, "targetHeight"?: m, "name"?: output}"#, ), @@ -1083,8 +1083,12 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { let at = Coord::new(f(p, "lon").ok_or("lon is required")?, f(p, "lat").ok_or("lat is required")?); let band = band_of(p, &dem)?; let (cx, cy) = dem.cell_size_m(); - // The whole raster by default: its diagonal reaches every cell from any observer. - let radius = f(p, "radius").unwrap_or((cx * dem.width as f64).hypot(cy * dem.height as f64)).clamp(1.0, 500_000.0); + // The whole raster by default, however large: its diagonal reaches every cell from any + // observer, and only the raster's cells are worked out. A radius given is at most 500 km. + let radius = match f(p, "radius") { + Some(r) => r.clamp(1.0, 500_000.0), + None => (cx * dem.width as f64).hypot(cy * dem.height as f64).max(1.0), + }; let height = f(p, "height").unwrap_or(1.7).clamp(0.0, 10_000.0); // How the ground along each ray is read: the cell a point falls in, or between cells. let heights = match p.get("heights") { diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 560956dbea..28ceb5ae54 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -713,7 +713,7 @@ pub fn workflows(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { }) .response .on_hover_text(tl!( - "How the ground between the observer and a cell is read: the cell each point falls in, or between the cells' centres. Between cells is right on ground that bulges, a hill seen from its top, where the nearest cell can hide cells just inside the horizon." + "How the ground between the observer and a cell is read: the cell each point falls in, or between the cells' centres. Between cells is an estimate too, but closer on ground that bulges, a hill seen from its top, where the nearest cell can hide cells just inside the horizon." )); }); pick_button(app, ui, "viewshed", 1, "Click the observer on the map"); @@ -2066,34 +2066,48 @@ mod tests { use super::*; use egui_kittest::kittest::Queryable; - /// An empty radius field (or one of spaces) runs the viewshed over the whole DEM, also one - /// whose radius square, the DEM's diagonal each way, holds far more cells than the DEM. + /// An empty radius field (or one of spaces) runs the viewshed over the whole DEM: one whose + /// radius square, the DEM's diagonal each way, holds far more cells than the DEM, and + /// reaching farther than the 500 km a radius given takes. #[test] fn a_viewshed_with_an_empty_radius_field_sees_the_whole_dem() { use base64::Engine; use rustgis_engine::geom::Coord; let mut app = RustGisApp::with_sample(); use rustgis_engine::data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; - // A strip 4,000 cells long and 2 high: the DEM's diagonal each way spans 8,001 × 8,001 + // A strip 4,000 cells long and 2 high, 0.002° (about 160 m) a cell: about 630 km, past + // the 500 km a radius given takes. The DEM's diagonal each way spans 8,001 × 8,001 // cells, 64 million, of which 8,000 are the DEM's. let (w, h) = (4_000u32, 2u32); - let gt = GeoTransform { origin_x: 10.0, origin_y: 45.002, pixel_width: 0.001, pixel_height: -0.001 }; + let gt = GeoTransform { origin_x: 10.0, origin_y: 45.004, pixel_width: 0.002, pixel_height: -0.002 }; let dem = Raster::new("strip", w, h, vec![vec![200.0; (w * h) as usize]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); let data = base64::engine::general_purpose::STANDARD.encode(geotiff::write(&dem, 0).unwrap()); app.session.run("layer.addDataBytes", &json!({"fileName": "strip.tif", "data": data})).unwrap(); let layer = app.session.map().layers.iter().rev().find(|l| l.is_raster()).unwrap().name.clone(); - // As the farthest radius the command takes: flat ground seen up to its horizon, a few km. - let mut far = json!({"layer": layer, "lon": 10.0005, "lat": 45.0005, "height": 2.0, "radius": 500_000.0}); - let seen = app.session.run("analysis.viewshed", &far).unwrap()["visibleCells"].as_u64().unwrap(); - assert!(seen > 20 && seen < u64::from(w * h), "{seen}"); - far.as_object_mut().unwrap().remove("radius"); - for radius in ["", " "] { + // Cells of a viewshed worked out (not left no-data), and whether the strip's far end is. + let worked = |app: &RustGisApp, name: &str| { + let r = app.session.map().layer_by_name(name).and_then(|l| l.raster.as_ref()?.data.clone()).unwrap(); + let n = (0..h as i64) + .flat_map(|row| (0..w as i64).map(move |col| (col, row))) + .filter(|&(c, rr)| r.value(0, c, rr).is_some()) + .count(); + (n, r.value(0, i64::from(w) - 1, 0).is_some()) + }; + let at = Coord::new(10.001, 45.001); + // A radius given is at most 500 km: the far end of the strip is left out. + app.session + .run("analysis.viewshed", &json!({"layer": layer, "lon": at.x, "lat": at.y, "height": 2.0, "radius": 1e9, "name": "given"})) + .unwrap(); + assert!(!worked(&app, "given").1); + for (i, radius) in ["", " "].into_iter().enumerate() { let workflow = Workflow { layer: layer.clone(), number: "2".into(), number2: radius.into(), ..Default::default() }; - let p = viewshed_params(&workflow, Coord::new(10.0005, 45.0005)); - assert_eq!(p, far, "radius {radius:?}"); - let v = app.session.run("analysis.viewshed", &p).unwrap_or_else(|e| panic!("radius {radius:?}: {e}")); - assert_eq!(v["visibleCells"].as_u64(), Some(seen), "radius {radius:?}: {v}"); + let mut p = viewshed_params(&workflow, at); + assert!(p.get("radius").is_none(), "radius {radius:?}: {p}"); + let name = format!("empty{i}"); + p["name"] = json!(name); + app.session.run("analysis.viewshed", &p).unwrap_or_else(|e| panic!("radius {radius:?}: {e}")); + assert_eq!(worked(&app, &name), ((w * h) as usize, true), "radius {radius:?}: every cell worked out"); } // A number in the field is the radius. let workflow = Workflow { layer, number2: " 5000 ".into(), ..Default::default() }; diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 2b4340082a..2e2ca43278 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1224,7 +1224,7 @@ click them on the map: | Raster Functions | Slope, aspect, hillshade, NDVI, band math (`(b4-b3)/(b4+b3)`), remapping, thresholds, resampling | | Function Editor | Chains raster functions, each on the previous output | | Suitability Modeler | Scores rasters 1–10 and adds them with weights | -| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells (bilinear)** in the Workflows pane) reads it between the cells' centres instead, which is right on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon. Ground with no data hides nothing, and next to it bilinear heights take the nearest cell's height; the analysis says how many cells this touched, in a notice and as `acrossNoData` and `readNearest` in its answer | +| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells (bilinear)** in the Workflows pane) reads it between the cells' centres instead. Both are estimates of the ground between cell centres; between cells is closer on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon. With no radius the viewshed covers the whole raster; a radius given is at most 500 km. Ground with no data hides nothing, and next to it bilinear heights take the nearest cell's height; the analysis says how many cells this touched, in a notice and as `acrossNoData` and `readNearest` in its answer | | Exploratory 3D Analysis | A line of sight between two points, split into seen and hidden parts, with the same curvature and refraction | | Geostatistical Wizard | An IDW surface from feature values, using 12 nearest neighbours by default | | Network Analysis | The shortest (or cheapest, by a cost field) route over a line layer | From e3bfe74fe89885e7b5ba694813448b1eb084db62 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Wed, 11 Nov 2026 18:44:21 +0100 Subject: [PATCH 06/12] =?UTF-8?q?fix(analysis):=20Viewshed=20refuses=20a?= =?UTF-8?q?=20radius=20that=20isn't=20one,=20says=20when=20it=20shortens?= =?UTF-8?q?=20one=20or=20its=20rays=20don't=20cross=20=C2=B1180=C2=B0,=20a?= =?UTF-8?q?nd=20weighs=20bilinear=20steps=20in=20its=20work=20cap?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/analysis/src/rasterops.rs | 7 +++-- crates/engine/src/cmd/workflows.rs | 42 ++++++++++++++++++++++++++---- crates/engine/src/tests.rs | 36 +++++++++++++++++++++++++ crates/ui-egui/src/analysispane.rs | 13 ++++++--- docs/user-guide/analysis.md | 2 +- 5 files changed, 88 insertions(+), 12 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index d8c9809aeb..3b4033ec2b 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -534,7 +534,9 @@ fn viewshed_on( // Each cell walks a ray back to the observer: bound cells × ray length, not just cells. let cells = (right - left + 1).saturating_mul(last - first + 1); let longest = (oc - left).max(right - oc).max(or - first).max(last - or); - let ray_work = usize::try_from(cells.saturating_mul(longest / 2 + 1)).unwrap_or(usize::MAX); + // A bilinear step reads four cells where a nearest one reads one: weighed as four. + let per_step = if heights == Heights::Bilinear { 4 } else { 1 }; + let ray_work = usize::try_from(cells.saturating_mul(longest / 2 + 1).saturating_mul(per_step)).unwrap_or(usize::MAX); // Each cell walks its own ray and writes only itself, so the rows within the radius are made // on several threads when the work is large (#1252), and may take as many times the work. let rows = usize::try_from(last - first + 1).unwrap_or(0); @@ -542,7 +544,8 @@ fn viewshed_on( let cap = crate::parallel::work_cap(MAX_VIEWSHED_WORK, threads); if ray_work > cap { return Err(format!( - "the radius takes {ray_work} ray steps, more than the {cap} this computer takes on {threads} thread(s); use a smaller radius{}", + "the radius takes {ray_work} ray steps{}, more than the {cap} this computer takes on {threads} thread(s); use a smaller radius{}", + if per_step > 1 { " (a step between cells counted as four)" } else { "" }, crate::parallel::UNCAPPED_HINT )); } diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 1ae270f7e4..0a0808a445 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1077,6 +1077,9 @@ fn viewshed(s: &mut Session, p: &Value) -> CmdResult { made_or_ran(s, p, "analysis.viewshed") } +/// The longest radius a viewshed is given; with none, it covers the whole raster. +const MAX_VIEWSHED_RADIUS_M: f64 = 500_000.0; + /// What a viewshed reads of the session, and the work that makes it. fn viewshed_work(s: &Session, p: &Value) -> Result { let dem = raster_of(s, ps(p, "layer").ok_or("layer is required")?)?; @@ -1085,10 +1088,20 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { let (cx, cy) = dem.cell_size_m(); // The whole raster by default, however large: its diagonal reaches every cell from any // observer, and only the raster's cells are worked out. A radius given is at most 500 km. - let radius = match f(p, "radius") { - Some(r) => r.clamp(1.0, 500_000.0), - None => (cx * dem.width as f64).hypot(cy * dem.height as f64).max(1.0), + let (radius, given) = match p.get("radius") { + None | Some(Value::Null) => ((cx * dem.width as f64).hypot(cy * dem.height as f64).max(1.0), None), + Some(v) => { + let r = f(p, "radius").filter(|r| *r > 0.0).ok_or_else(|| format!("radius must be a number of metres above 0, not {v}"))?; + (r.min(MAX_VIEWSHED_RADIUS_M), Some(r)) + } }; + // Shortened to the most a viewshed takes: said, with by how much. + let shortened = given.filter(|r| *r > MAX_VIEWSHED_RADIUS_M); + // A raster around the whole Earth (in longitude/latitude) has its east and west edges side + // by side, but rays don't cross from one to the other: said when the radius reaches an edge. + let round_the_earth = matches!(dem.crs, Crs::LonLat) && dem.transform.pixel_width.abs() * f64::from(dem.width) >= 359.999; + let to_edge = dem.pixel_at(at).map_or(0.0, |(c, _)| (c.min(i64::from(dem.width) - 1 - c) as f64 + 0.5) * cx); + let seam = round_the_earth && radius > to_edge; let height = f(p, "height").unwrap_or(1.7).clamp(0.0, 10_000.0); // How the ground along each ray is read: the cell a point falls in, or between cells. let heights = match p.get("heights") { @@ -1105,12 +1118,31 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { let seen = vs.cells.iter().filter(|v| **v == 1.0).count(); let (through_gaps, read_nearest) = (vs.through_gaps, vs.read_nearest); let m = made(rasterops::derive(&dem, &name, vec![vs.cells])?, Some(json!({"visibleCells": seen})))?; - if through_gaps == 0 && read_nearest == 0 { + if through_gaps == 0 && read_nearest == 0 && shortened.is_none() && !seam { return Ok(m); } // Ground with no data hides nothing, and bilinear heights read the nearest cell beside - // it: said, with how many cells it touched. + // it: said, with how many cells it touched. A radius shortened, and rays that don't + // cross the ±180° edge, said too. let then: Then = Box::new(move |s: &mut Session, v: &mut Value| { + if let Some(r) = shortened { + s.notify( + format!( + "{dem_name}: the radius of {:.0} km was taken as {:.0} km, the most a viewshed takes; with no radius it covers the whole raster", + r / 1000.0, + MAX_VIEWSHED_RADIUS_M / 1000.0 + ), + false, + ); + } + if seam { + s.notify( + format!( + "{dem_name}: the raster goes round the Earth, but the viewshed's rays don't cross its ±180° edge: ground just across it is worked out the long way round" + ), + false, + ); + } if through_gaps > 0 { s.notify( format!( diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 739244b08f..8eee594c8b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9304,6 +9304,42 @@ fn a_viewshed_says_what_ground_with_no_data_it_saw_across() { } } +/// A viewshed's radius: one past 500 km is shortened to it, said with by how much; text or 0 is +/// refused, naming it; on a raster round the Earth whose edge the radius reaches, the rays not +/// crossing its ±180° edge are said. +#[test] +fn a_viewshed_says_what_it_did_with_its_radius_and_the_seam() { + use base64::Engine; + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; + let mut s = world(); + // Flat ground round the Earth, 2° a cell. + let gt = GeoTransform { origin_x: -180.0, origin_y: 90.0, pixel_width: 2.0, pixel_height: -2.0 }; + let r = Raster::new("globe", 180, 90, vec![vec![0.0; 180 * 90]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(geotiff::write(&r, 0).unwrap()); + s.run("layer.addDataBytes", &json!({"fileName": "globe.tif", "data": data})).unwrap(); + let dem = s.map().layers.iter().find(|l| l.is_raster()).unwrap().name.clone(); + let said = |s: &mut Session, p: Value| { + let mark = s.notices.len(); + s.run("analysis.viewshed", &p).unwrap_or_else(|e| panic!("{p}: {e}")); + s.notices[mark..].iter().map(|n| n.text.clone()).collect::>() + }; + let seam = "rays don't cross its ±180° edge"; + // By the edge with no radius (the whole raster): the seam is said. + let notes = said(&mut s, json!({"layer": dem, "lon": -179.0, "lat": 0.0})); + assert!(notes.iter().any(|n| n.contains(seam)), "{notes:?}"); + // Mid-way with a radius not reaching an edge: nothing said. + let notes = said(&mut s, json!({"layer": dem, "lon": 0.0, "lat": 0.0, "radius": 50_000})); + assert!(notes.is_empty(), "{notes:?}"); + // 600 km is taken as 500 km, and said; 500 km from the edge's cell reaches it. + let notes = said(&mut s, json!({"layer": dem, "lon": -177.0, "lat": 0.0, "radius": 600_000})); + assert!(notes.iter().any(|n| n.contains("the radius of 600 km was taken as 500 km")), "{notes:?}"); + assert!(notes.iter().any(|n| n.contains(seam)), "{notes:?}"); + for bad in [json!("500km"), json!(0), json!(-5), json!(true)] { + let e = s.run("analysis.viewshed", &json!({"layer": dem, "lon": 0.0, "lat": 0.0, "radius": bad})).unwrap_err(); + assert_eq!(e, format!("radius must be a number of metres above 0, not {bad}")); + } +} + #[test] fn analysis_workflows_models_scripts_and_raster_functions() { let mut s = world(); diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 28ceb5ae54..9716a14fd4 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -405,8 +405,10 @@ fn num(s: &str, d: f64) -> f64 { /// radius out, so the command takes the whole DEM. fn viewshed_params(w: &Workflow, at: rustgis_engine::geom::Coord) -> Value { let mut params = json!({"layer": w.layer, "lon": at.x, "lat": at.y, "height": num(&w.number, 1.7)}); - if let Ok(r) = w.number2.trim().parse::() { - params["radius"] = json!(r); + // A number is the radius; other text goes as it is, for the command to refuse, naming it. + match w.number2.trim() { + "" => {} + r => params["radius"] = r.parse::().map_or_else(|_| json!(r), |r| json!(r)), } if w.bilinear { params["heights"] = json!("bilinear"); @@ -2109,9 +2111,12 @@ mod tests { app.session.run("analysis.viewshed", &p).unwrap_or_else(|e| panic!("radius {radius:?}: {e}")); assert_eq!(worked(&app, &name), ((w * h) as usize, true), "radius {radius:?}: every cell worked out"); } - // A number in the field is the radius. - let workflow = Workflow { layer, number2: " 5000 ".into(), ..Default::default() }; + // A number in the field is the radius; other text is refused, not taken as no radius. + let workflow = Workflow { layer: layer.clone(), number2: " 5000 ".into(), ..Default::default() }; assert_eq!(viewshed_params(&workflow, Coord::new(10.0005, 45.0005))["radius"], json!(5000.0)); + let workflow = Workflow { layer, number2: "500km".into(), ..Default::default() }; + let e = app.session.run("analysis.viewshed", &viewshed_params(&workflow, at)).unwrap_err(); + assert_eq!(e, r#"radius must be a number of metres above 0, not "500km""#); } /// A Script pane run works its tools out on a thread of its own: the results say Running… diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 2e2ca43278..ae2252f36a 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1224,7 +1224,7 @@ click them on the map: | Raster Functions | Slope, aspect, hillshade, NDVI, band math (`(b4-b3)/(b4+b3)`), remapping, thresholds, resampling | | Function Editor | Chains raster functions, each on the previous output | | Suitability Modeler | Scores rasters 1–10 and adds them with weights | -| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells (bilinear)** in the Workflows pane) reads it between the cells' centres instead. Both are estimates of the ground between cell centres; between cells is closer on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon. With no radius the viewshed covers the whole raster; a radius given is at most 500 km. Ground with no data hides nothing, and next to it bilinear heights take the nearest cell's height; the analysis says how many cells this touched, in a notice and as `acrossNoData` and `readNearest` in its answer | +| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells (bilinear)** in the Workflows pane) reads it between the cells' centres instead. Both are estimates of the ground between cell centres; between cells is closer on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon. With no radius the viewshed covers the whole raster; a radius given is at most 500 km (a longer one is shortened, and the analysis says so). On a raster round the whole Earth the rays don't cross its ±180° edge, which the analysis says when the radius reaches it. Ground with no data hides nothing, and next to it bilinear heights take the nearest cell's height; the analysis says how many cells this touched, in a notice and as `acrossNoData` and `readNearest` in its answer | | Exploratory 3D Analysis | A line of sight between two points, split into seen and hidden parts, with the same curvature and refraction | | Geostatistical Wizard | An IDW surface from feature values, using 12 nearest neighbours by default | | Network Analysis | The shortest (or cheapest, by a cost field) route over a line layer | From 236c838ea4529928ff83a4db03f7097416e26089 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Wed, 11 Nov 2026 19:56:01 +0100 Subject: [PATCH 07/12] fix(analysis): the Workflows pane sends a radius that isn't a finite number as text, for the viewshed to refuse; doc wording --- crates/analysis/src/rasterops.rs | 14 ++++++++------ crates/ui-egui/src/analysispane.rs | 11 +++++++---- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 3b4033ec2b..79f1074c71 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -443,8 +443,9 @@ pub enum Heights { #[default] Nearest, /// Between the cells' centres, in proportion to how near the point is to each (bilinear): - /// smoother, and closer on bulging ground, though still an estimate. Where one of those cells has no data, the cell the - /// point falls in, as [`Heights::Nearest`] reads it (counted: [`Viewshed::read_nearest`]). + /// smoother, and closer on bulging ground, though still an estimate. Where one of those cells + /// has no data, the cell the point falls in, as [`Heights::Nearest`] reads it (counted: + /// [`Viewshed::read_nearest`]). Bilinear, } @@ -464,7 +465,8 @@ impl Heights { /// whether it is the nearest cell's, read in place of cells between which a neighbour has /// no data. `None` where the point's own cell has no data. fn at(self, r: &Raster, b: usize, col: f64, row: f64) -> Option<(f64, bool)> { - let nearest = |fell_back: bool| r.value(b, col.round() as i64, row.round() as i64).map(|v| (f64::from(v), fell_back)); + let (nc, nr) = (col.round() as i64, row.round() as i64); + let nearest = |fell_back: bool| r.value(b, nc, nr).map(|v| (f64::from(v), fell_back)); if self == Heights::Nearest { return nearest(false); } @@ -1675,8 +1677,8 @@ mod tests { /// A radius reaching far past the raster (the whole DEM's diagonal, as the command takes by /// default) counts only the raster's cells: a strip 6,000 cells long, seen from one end, is - /// worked out, though the square the radius spans holds 144 million cells, as is one whose - /// radius spans more cells than a number holds. + /// worked out, though the square the radius spans holds 144 million cells. So is a radius of + /// more cells than an `i64` holds. #[test] fn a_viewshed_radius_past_the_raster_counts_only_its_cells() { let transform = GeoTransform { origin_x: 0.0, origin_y: 0.001, pixel_width: 0.001, pixel_height: -0.001 }; @@ -2013,7 +2015,7 @@ mod tests { // seen again once the line has come down below the ground (at about 1.2 km on a flat // Earth, a little farther with its curve). Rays mostly east or west, // which cross the wall at a cell's centre line, are counted; others cross it between - // columns, where where it stands depends on how the ground is read. + // columns, where it stands depends on how the ground is read. let wall_col = half + 20; let wall = dem(&|x, _| if (x - 20.0 * cx).abs() < cx / 2.0 { 1.0 } else { 0.0 }); let z0 = 2.0; diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 9716a14fd4..9ff9193323 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -408,7 +408,8 @@ fn viewshed_params(w: &Workflow, at: rustgis_engine::geom::Coord) -> Value { // A number is the radius; other text goes as it is, for the command to refuse, naming it. match w.number2.trim() { "" => {} - r => params["radius"] = r.parse::().map_or_else(|_| json!(r), |r| json!(r)), + // `inf`, `NaN` and `1e400` parse, but aren't numbers JSON holds (they'd be null, no radius). + r => params["radius"] = r.parse::().ok().filter(|r| r.is_finite()).map_or_else(|| json!(r), |r| json!(r)), } if w.bilinear { params["heights"] = json!("bilinear"); @@ -2114,9 +2115,11 @@ mod tests { // A number in the field is the radius; other text is refused, not taken as no radius. let workflow = Workflow { layer: layer.clone(), number2: " 5000 ".into(), ..Default::default() }; assert_eq!(viewshed_params(&workflow, Coord::new(10.0005, 45.0005))["radius"], json!(5000.0)); - let workflow = Workflow { layer, number2: "500km".into(), ..Default::default() }; - let e = app.session.run("analysis.viewshed", &viewshed_params(&workflow, at)).unwrap_err(); - assert_eq!(e, r#"radius must be a number of metres above 0, not "500km""#); + for text in ["500km", "inf", "NaN", "1e400", "-infinity"] { + let workflow = Workflow { layer: layer.clone(), number2: text.into(), ..Default::default() }; + let e = app.session.run("analysis.viewshed", &viewshed_params(&workflow, at)).unwrap_err(); + assert_eq!(e, format!(r#"radius must be a number of metres above 0, not "{text}""#)); + } } /// A Script pane run works its tools out on a thread of its own: the results say Running… From 92d4a60aa6856ce755877a807377e5375d36acb4 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Wed, 11 Nov 2026 20:25:55 +0100 Subject: [PATCH 08/12] fix(analysis): Viewshed's seam notice fits a radius given, any geographic CRS and a rounded cell size; acrossNoData/readNearest always answered; notices to a tenth of a km --- crates/analysis/src/rasterops.rs | 5 ++-- crates/engine/src/cmd/workflows.rs | 40 +++++++++++++++++++++--------- crates/engine/src/tests.rs | 24 +++++++++++++++--- docs/user-guide/analysis.md | 2 +- 4 files changed, 53 insertions(+), 18 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 79f1074c71..e9c6cc5527 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -437,7 +437,8 @@ pub(crate) const MAX_IDW_WORK: usize = 400_000_000; /// How a viewshed reads the ground between the observer and a cell. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Heights { - /// The cell each point of the ray falls in, as the viewshed always has. On ground that bulges + /// The cell each point of the ray falls in, as the viewshed has read it (each point now exact on + /// a cell's centre line, which can change a cell at a tie). On ground that bulges /// (a hill seen from its top), a cell nearer the observer than the point stands in for it and /// can hide cells just inside the horizon. #[default] @@ -1940,7 +1941,7 @@ mod tests { /// those beyond it seen again). The Earth's /// curvature for visible light (`SIGHT_RADIUS_M`) is part of each answer. Cells within a cell /// and a half of a boundary, where a grid can't say which side a cell is on, aren't counted. - /// Bilinear heights get every other cell right on all four; nearest heights hide some of the + /// Bilinear heights get every cell counted right on all four; nearest heights hide some of the /// dome just inside its horizon, and are right on the other three. #[test] fn viewsheds_give_the_known_answers_of_flat_ground_a_bowl_a_dome_and_a_wall() { diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 0a0808a445..d89709ae01 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1077,6 +1077,12 @@ fn viewshed(s: &mut Session, p: &Value) -> CmdResult { made_or_ran(s, p, "analysis.viewshed") } +/// `m` metres as a notice says it: in km to a tenth, or in metres in exponent form when past a +/// million km. +fn metres(m: f64) -> String { + if m < 1e9 { format!("{} km", (m / 100.0).round() / 10.0) } else { format!("{m:.1e} m") } +} + /// The longest radius a viewshed is given; with none, it covers the whole raster. const MAX_VIEWSHED_RADIUS_M: f64 = 500_000.0; @@ -1099,7 +1105,9 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { let shortened = given.filter(|r| *r > MAX_VIEWSHED_RADIUS_M); // A raster around the whole Earth (in longitude/latitude) has its east and west edges side // by side, but rays don't cross from one to the other: said when the radius reaches an edge. - let round_the_earth = matches!(dem.crs, Crs::LonLat) && dem.transform.pixel_width.abs() * f64::from(dem.width) >= 359.999; + // (Within half a cell of 360°: a cell size stored rounded falls a little short.) + let pw = dem.transform.pixel_width.abs(); + let round_the_earth = dem.crs.is_geographic() && pw * f64::from(dem.width) >= 360.0 - pw / 2.0; let to_edge = dem.pixel_at(at).map_or(0.0, |(c, _)| (c.min(i64::from(dem.width) - 1 - c) as f64 + 0.5) * cx); let seam = round_the_earth && radius > to_edge; let height = f(p, "height").unwrap_or(1.7).clamp(0.0, 10_000.0); @@ -1114,31 +1122,43 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { let name = out_name(p, format!("{}_viewshed", dem.name)); let dem_name = dem.name.clone(); Ok(Box::new(move || { - let vs = rasterops::viewshed(&dem, band, at, height, radius, heights)?; + let vs = rasterops::viewshed(&dem, band, at, height, radius, heights).map_err(|e| { + // With no radius given, the work is the whole raster's, not a radius's. + if given.is_none() && e.starts_with("the radius takes") { + e.replacen("the radius takes", "the whole raster (no radius given) takes", 1) + .replace("use a smaller radius", "give a radius") + } else { + e + } + })?; let seen = vs.cells.iter().filter(|v| **v == 1.0).count(); let (through_gaps, read_nearest) = (vs.through_gaps, vs.read_nearest); - let m = made(rasterops::derive(&dem, &name, vec![vs.cells])?, Some(json!({"visibleCells": seen})))?; + let answer = json!({"visibleCells": seen, "acrossNoData": through_gaps, "readNearest": read_nearest}); + let m = made(rasterops::derive(&dem, &name, vec![vs.cells])?, Some(answer))?; if through_gaps == 0 && read_nearest == 0 && shortened.is_none() && !seam { return Ok(m); } // Ground with no data hides nothing, and bilinear heights read the nearest cell beside // it: said, with how many cells it touched. A radius shortened, and rays that don't // cross the ±180° edge, said too. - let then: Then = Box::new(move |s: &mut Session, v: &mut Value| { + let then: Then = Box::new(move |s: &mut Session, _: &mut Value| { if let Some(r) = shortened { s.notify( format!( - "{dem_name}: the radius of {:.0} km was taken as {:.0} km, the most a viewshed takes; with no radius it covers the whole raster", - r / 1000.0, - MAX_VIEWSHED_RADIUS_M / 1000.0 + "{dem_name}: the radius of {} was taken as {}, the most a viewshed takes; with no radius it covers the whole raster", + metres(r), + metres(MAX_VIEWSHED_RADIUS_M) ), false, ); } if seam { + // Given a radius, the ground across the edge is too far the long way round to + // fall inside it; with none, the whole raster is worked out, that ground too. + let across = if given.is_some() { "left out of the viewshed" } else { "worked out the long way round" }; s.notify( format!( - "{dem_name}: the raster goes round the Earth, but the viewshed's rays don't cross its ±180° edge: ground just across it is worked out the long way round" + "{dem_name}: the raster goes round the Earth, but the viewshed's rays don't cross its ±180° edge: ground just across it is {across}" ), false, ); @@ -1157,10 +1177,6 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { false, ); } - if let Some(o) = v.as_object_mut() { - o.insert("acrossNoData".into(), json!(through_gaps)); - o.insert("readNearest".into(), json!(read_nearest)); - } }); Ok(Made { then: Some(then), ..m }) })) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8eee594c8b..1a7f0cab99 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9326,13 +9326,26 @@ fn a_viewshed_says_what_it_did_with_its_radius_and_the_seam() { let seam = "rays don't cross its ±180° edge"; // By the edge with no radius (the whole raster): the seam is said. let notes = said(&mut s, json!({"layer": dem, "lon": -179.0, "lat": 0.0})); - assert!(notes.iter().any(|n| n.contains(seam)), "{notes:?}"); + assert!(notes.iter().any(|n| n.contains(seam) && n.ends_with("worked out the long way round")), "{notes:?}"); // Mid-way with a radius not reaching an edge: nothing said. let notes = said(&mut s, json!({"layer": dem, "lon": 0.0, "lat": 0.0, "radius": 50_000})); assert!(notes.is_empty(), "{notes:?}"); // 600 km is taken as 500 km, and said; 500 km from the edge's cell reaches it. let notes = said(&mut s, json!({"layer": dem, "lon": -177.0, "lat": 0.0, "radius": 600_000})); assert!(notes.iter().any(|n| n.contains("the radius of 600 km was taken as 500 km")), "{notes:?}"); + // Given a radius, the ground across the edge is left out (too far the long way round). + assert!(notes.iter().any(|n| n.contains(seam) && n.ends_with("left out of the viewshed")), "{notes:?}"); + // Just past 500 km, said to a tenth of a km. + let notes = said(&mut s, json!({"layer": dem, "lon": 0.0, "lat": 0.0, "radius": 500_400})); + assert!(notes.iter().any(|n| n.contains("the radius of 500.4 km was taken as 500 km")), "{notes:?}"); + // A geographic coordinate system other than WGS 84, and a cell size stored rounded + // (180 × 1.99999° = 359.9998°): still round the Earth. + let gt = GeoTransform { origin_x: -180.0, origin_y: 90.0, pixel_width: 1.99999, pixel_height: -2.0 }; + let r = Raster::new("nad83", 180, 90, vec![vec![0.0; 180 * 90]], gt, Crs::Epsg(4269), None, ColorHint::Gray, "Float32").unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(geotiff::write(&r, 0).unwrap()); + s.run("layer.addDataBytes", &json!({"fileName": "nad83.tif", "data": data})).unwrap(); + let nad83 = s.map().layers.iter().find(|l| l.name.starts_with("nad83")).unwrap().name.clone(); + let notes = said(&mut s, json!({"layer": nad83, "lon": -179.0, "lat": 0.0})); assert!(notes.iter().any(|n| n.contains(seam)), "{notes:?}"); for bad in [json!("500km"), json!(0), json!(-5), json!(true)] { let e = s.run("analysis.viewshed", &json!({"layer": dem, "lon": 0.0, "lat": 0.0, "radius": bad})).unwrap_err(); @@ -9395,11 +9408,16 @@ fn analysis_workflows_models_scripts_and_raster_functions() { // Bilinear heights read the ground between cells: on this hill and wall they see at least // what the nearest cells do (a cell nearer the top no longer stands in for the ground), and // little more. Any other name, or a value that isn't one, is refused, saying which there are. + let mark = s.notices.len(); let b = s.run("analysis.viewshed", &json!({"layer": dem, "lon": 10.0055, "lat": 45.0395, "height": 2, "heights": "Bilinear"})).unwrap(); let (near, bil) = (v["visibleCells"].as_u64().unwrap(), b["visibleCells"].as_u64().unwrap()); assert!(bil >= near && bil <= near + near / 10, "nearest {near}, bilinear {bil}"); - // A DEM with every cell holding data: nothing to say about ground with none. - assert!(b.get("acrossNoData").is_none() && v.get("acrossNoData").is_none(), "{b}"); + // A DEM with every cell holding data: nothing to say about ground with none, and the answer + // says none. + assert!(s.notices[mark..].is_empty(), "{:?}", s.notices[mark..].iter().map(|n| &n.text).collect::>()); + for a in [&v, &b] { + assert_eq!((&a["acrossNoData"], &a["readNearest"]), (&json!(0), &json!(0)), "{a}"); + } for bad in [json!("cubic"), json!(1)] { let e = s.run("analysis.viewshed", &json!({"layer": dem, "lon": 10.0055, "lat": 45.0395, "heights": bad})).unwrap_err(); assert!(e.to_string().contains(r#"heights must be "nearest" or "bilinear", not "#), "{e}"); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index ae2252f36a..f137db1bb4 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1224,7 +1224,7 @@ click them on the map: | Raster Functions | Slope, aspect, hillshade, NDVI, band math (`(b4-b3)/(b4+b3)`), remapping, thresholds, resampling | | Function Editor | Chains raster functions, each on the previous output | | Suitability Modeler | Scores rasters 1–10 and adds them with weights | -| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells (bilinear)** in the Workflows pane) reads it between the cells' centres instead. Both are estimates of the ground between cell centres; between cells is closer on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon. With no radius the viewshed covers the whole raster; a radius given is at most 500 km (a longer one is shortened, and the analysis says so). On a raster round the whole Earth the rays don't cross its ±180° edge, which the analysis says when the radius reaches it. Ground with no data hides nothing, and next to it bilinear heights take the nearest cell's height; the analysis says how many cells this touched, in a notice and as `acrossNoData` and `readNearest` in its answer | +| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells (bilinear)** in the Workflows pane) reads it between the cells' centres instead. Both are estimates of the ground between cell centres; between cells is closer on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon. With no radius the viewshed covers the whole raster; a radius given is at most 500 km (a longer one is shortened, and the analysis says so). On a raster round the whole Earth the rays don't cross its ±180° edge, which the analysis says when the radius reaches it: given a radius, the ground just across the edge is left out; with none, it is worked out the long way round. The answer gives `acrossNoData` and `readNearest` (0 when there is nothing to say). Ground with no data hides nothing, and next to it bilinear heights take the nearest cell's height; the analysis says how many cells this touched, in a notice | | Exploratory 3D Analysis | A line of sight between two points, split into seen and hidden parts, with the same curvature and refraction | | Geostatistical Wizard | An IDW surface from feature values, using 12 nearest neighbours by default | | Network Analysis | The shortest (or cheapest, by a cost field) route over a line layer | From 737a04a5294f814ec621a5c0dc05035f9bf428fb Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Wed, 11 Nov 2026 22:12:18 +0100 Subject: [PATCH 09/12] =?UTF-8?q?fix(analysis):=20Viewshed's=20seam=20noti?= =?UTF-8?q?ce=20names=20the=20east=E2=80=93west=20edge=20and=20says=20when?= =?UTF-8?q?=20the=20radius=20reaches=20the=20far=20one;=20a=20height=20tha?= =?UTF-8?q?t=20isn't=20one=20is=20refused?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/engine/src/cmd/workflows.rs | 26 +++++++++++++++++++------- crates/engine/src/tests.rs | 30 +++++++++++++++++++++++++++--- crates/ui-egui/src/analysispane.rs | 22 ++++++++++++++++------ docs/user-guide/analysis.md | 2 +- 4 files changed, 63 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index d89709ae01..848af9a214 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -60,7 +60,7 @@ pub fn commands() -> Vec { r#"{"criteria": [{"layer": raster, "band"?: 1-based, "ranges": [[lo, hi, score]], "weight": number}], "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#, ), C::new("analysis.viewshed", "Visibility Analysis", "Analyze › Workflows", viewshed).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"layer": elevation raster, "lon", "lat", "band"?: 1-based, "height"?: observer metres, "radius"?: metres (at most 500 km; default: the whole raster), "heights"?: "nearest" (default) | "bilinear" (the ground along each ray), "name"?: output, "ran"?: (internal: a viewshed the app has worked out)}"#), + .params(r#"{"layer": elevation raster, "lon", "lat", "band"?: 1-based, "height"?: observer metres, 0 to 10,000 (default 1.7), "radius"?: metres (at most 500 km; default: the whole raster), "heights"?: "nearest" (default) | "bilinear" (the ground along each ray), "name"?: output, "ran"?: (internal: a viewshed the app has worked out)}"#), C::new("analysis.lineOfSight", "Line Of Sight", "Analyze › Workflows", line_of_sight).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"layer": elevation raster, "from": [lon, lat], "to": [lon, lat], "band"?: 1-based, "observerHeight"?: m, "targetHeight"?: m, "name"?: output}"#, ), @@ -1108,9 +1108,21 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { // (Within half a cell of 360°: a cell size stored rounded falls a little short.) let pw = dem.transform.pixel_width.abs(); let round_the_earth = dem.crs.is_geographic() && pw * f64::from(dem.width) >= 360.0 - pw / 2.0; - let to_edge = dem.pixel_at(at).map_or(0.0, |(c, _)| (c.min(i64::from(dem.width) - 1 - c) as f64 + 0.5) * cx); + let oc = dem.pixel_at(at).map_or(0, |(c, _)| c); + let to_edge = (oc.min(i64::from(dem.width) - 1 - oc) as f64 + 0.5) * cx; let seam = round_the_earth && radius > to_edge; - let height = f(p, "height").unwrap_or(1.7).clamp(0.0, 10_000.0); + // Whether the radius reaches the far edge's column (its centre on the observer's row, as the + // viewshed measures it), so the ground across the edge is worked out the long way round + // rather than left out. + let far = oc.max(i64::from(dem.width) - 1 - oc) as f64 * cx; + let both_edges = radius >= far; + // Refused, naming it, when it isn't a height a viewshed takes: never another one used. + let height = match p.get("height") { + None | Some(Value::Null) => 1.7, + Some(v) => f(p, "height") + .filter(|h| (0.0..=10_000.0).contains(h)) + .ok_or_else(|| format!("height must be a number of metres from 0 to 10,000, not {v}"))?, + }; // How the ground along each ray is read: the cell a point falls in, or between cells. let heights = match p.get("heights") { None | Some(Value::Null) => rasterops::Heights::Nearest, @@ -1153,12 +1165,12 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { ); } if seam { - // Given a radius, the ground across the edge is too far the long way round to - // fall inside it; with none, the whole raster is worked out, that ground too. - let across = if given.is_some() { "left out of the viewshed" } else { "worked out the long way round" }; + // Rays don't wrap across the edge: the ground across it is reached only through the + // raster, when the radius's window takes in the far edge's column too. + let across = if both_edges { "worked out the long way round" } else { "left out of the viewshed" }; s.notify( format!( - "{dem_name}: the raster goes round the Earth, but the viewshed's rays don't cross its ±180° edge: ground just across it is {across}" + "{dem_name}: the raster goes round the Earth, but the viewshed's rays don't cross its east–west edge: ground just across it is {across}" ), false, ); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1a7f0cab99..2399b2e67d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9306,7 +9306,8 @@ fn a_viewshed_says_what_ground_with_no_data_it_saw_across() { /// A viewshed's radius: one past 500 km is shortened to it, said with by how much; text or 0 is /// refused, naming it; on a raster round the Earth whose edge the radius reaches, the rays not -/// crossing its ±180° edge are said. +/// crossing its east–west edge are said: left out when the radius's window doesn't take in the +/// far edge, worked out the long way round when it does. #[test] fn a_viewshed_says_what_it_did_with_its_radius_and_the_seam() { use base64::Engine; @@ -9323,7 +9324,7 @@ fn a_viewshed_says_what_it_did_with_its_radius_and_the_seam() { s.run("analysis.viewshed", &p).unwrap_or_else(|e| panic!("{p}: {e}")); s.notices[mark..].iter().map(|n| n.text.clone()).collect::>() }; - let seam = "rays don't cross its ±180° edge"; + let seam = "rays don't cross its east–west edge"; // By the edge with no radius (the whole raster): the seam is said. let notes = said(&mut s, json!({"layer": dem, "lon": -179.0, "lat": 0.0})); assert!(notes.iter().any(|n| n.contains(seam) && n.ends_with("worked out the long way round")), "{notes:?}"); @@ -9333,7 +9334,7 @@ fn a_viewshed_says_what_it_did_with_its_radius_and_the_seam() { // 600 km is taken as 500 km, and said; 500 km from the edge's cell reaches it. let notes = said(&mut s, json!({"layer": dem, "lon": -177.0, "lat": 0.0, "radius": 600_000})); assert!(notes.iter().any(|n| n.contains("the radius of 600 km was taken as 500 km")), "{notes:?}"); - // Given a radius, the ground across the edge is left out (too far the long way round). + // Given a radius whose window doesn't reach the far edge, the ground across is left out. assert!(notes.iter().any(|n| n.contains(seam) && n.ends_with("left out of the viewshed")), "{notes:?}"); // Just past 500 km, said to a tenth of a km. let notes = said(&mut s, json!({"layer": dem, "lon": 0.0, "lat": 0.0, "radius": 500_400})); @@ -9347,6 +9348,29 @@ fn a_viewshed_says_what_it_did_with_its_radius_and_the_seam() { let nad83 = s.map().layers.iter().find(|l| l.name.starts_with("nad83")).unwrap().name.clone(); let notes = said(&mut s, json!({"layer": nad83, "lon": -179.0, "lat": 0.0})); assert!(notes.iter().any(|n| n.contains(seam)), "{notes:?}"); + // Stored from 0° to 360°, with its edge at 0°: the same. + let gt = GeoTransform { origin_x: 0.0, origin_y: 90.0, pixel_width: 2.0, pixel_height: -2.0 }; + let r = Raster::new("east", 180, 90, vec![vec![0.0; 180 * 90]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(geotiff::write(&r, 0).unwrap()); + s.run("layer.addDataBytes", &json!({"fileName": "east.tif", "data": data})).unwrap(); + let east = s.map().layers.iter().find(|l| l.name.starts_with("east")).unwrap().name.clone(); + let notes = said(&mut s, json!({"layer": east, "lon": 1.0, "lat": 0.0, "radius": 300_000})); + assert!(notes.iter().any(|n| n.contains(seam) && n.ends_with("left out of the viewshed")), "{notes:?}"); + // Near the pole, with cells of 90° (100 km each, as `cell_size_m` measures them there): a + // 350 km radius reaches the far column, so the ground across the edge is worked out through + // the raster. + let gt = GeoTransform { origin_x: -180.0, origin_y: 90.0, pixel_width: 90.0, pixel_height: -1.0 }; + let r = Raster::new("cap", 4, 1, vec![vec![0.0; 4]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(geotiff::write(&r, 0).unwrap()); + s.run("layer.addDataBytes", &json!({"fileName": "cap.tif", "data": data})).unwrap(); + let cap = s.map().layers.iter().find(|l| l.name.starts_with("cap")).unwrap().name.clone(); + let notes = said(&mut s, json!({"layer": cap, "lon": -170.0, "lat": 89.5, "radius": 350_000})); + assert!(notes.iter().any(|n| n.contains(seam) && n.ends_with("worked out the long way round")), "{notes:?}"); + // A radius between 2 and 3 cells: its window takes in the far column, + // but the far column's centre lies outside the radius, so the ground across is left out. + let (cx, _) = s.map().layer_by_name(&cap).and_then(|l| l.raster.as_ref()?.data.as_ref().map(|r| r.cell_size_m())).unwrap(); + let notes = said(&mut s, json!({"layer": cap, "lon": -170.0, "lat": 89.5, "radius": 2.5 * cx})); + assert!(notes.iter().any(|n| n.contains(seam) && n.ends_with("left out of the viewshed")), "{notes:?}"); for bad in [json!("500km"), json!(0), json!(-5), json!(true)] { let e = s.run("analysis.viewshed", &json!({"layer": dem, "lon": 0.0, "lat": 0.0, "radius": bad})).unwrap_err(); assert_eq!(e, format!("radius must be a number of metres above 0, not {bad}")); diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 9ff9193323..47a34944c9 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -404,12 +404,15 @@ fn num(s: &str, d: f64) -> f64 { /// The viewshed's parameters from the pane, seen from `at`: an empty radius field leaves the /// radius out, so the command takes the whole DEM. fn viewshed_params(w: &Workflow, at: rustgis_engine::geom::Coord) -> Value { - let mut params = json!({"layer": w.layer, "lon": at.x, "lat": at.y, "height": num(&w.number, 1.7)}); - // A number is the radius; other text goes as it is, for the command to refuse, naming it. - match w.number2.trim() { - "" => {} - // `inf`, `NaN` and `1e400` parse, but aren't numbers JSON holds (they'd be null, no radius). - r => params["radius"] = r.parse::().ok().filter(|r| r.is_finite()).map_or_else(|| json!(r), |r| json!(r)), + let mut params = json!({"layer": w.layer, "lon": at.x, "lat": at.y}); + // A number is the height or radius; other text goes as it is, for the command to refuse, + // naming it (`inf`, `NaN` and `1e400` parse, but aren't numbers JSON holds: they'd be null). + // Empty: the command's own (1.7 m up; the whole raster). + for (key, text) in [("height", &w.number), ("radius", &w.number2)] { + match text.trim() { + "" => {} + t => params[key] = t.parse::().ok().filter(|v| v.is_finite()).map_or_else(|| json!(t), |v| json!(v)), + } } if w.bilinear { params["heights"] = json!("bilinear"); @@ -2115,6 +2118,13 @@ mod tests { // A number in the field is the radius; other text is refused, not taken as no radius. let workflow = Workflow { layer: layer.clone(), number2: " 5000 ".into(), ..Default::default() }; assert_eq!(viewshed_params(&workflow, Coord::new(10.0005, 45.0005))["radius"], json!(5000.0)); + // So is the height, and an empty one is the command's 1.7 m. + for (text, e) in [("abc", r#"not "abc""#), ("1,7", r#"not "1,7""#), ("-3", "not -3.0")] { + let workflow = Workflow { layer: layer.clone(), number: text.into(), ..Default::default() }; + let got = app.session.run("analysis.viewshed", &viewshed_params(&workflow, at)).unwrap_err(); + assert!(got.starts_with("height must be a number of metres from 0 to 10,000") && got.ends_with(e), "{got}"); + } + assert!(viewshed_params(&Workflow { layer: layer.clone(), ..Default::default() }, at).get("height").is_none()); for text in ["500km", "inf", "NaN", "1e400", "-infinity"] { let workflow = Workflow { layer: layer.clone(), number2: text.into(), ..Default::default() }; let e = app.session.run("analysis.viewshed", &viewshed_params(&workflow, at)).unwrap_err(); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index f137db1bb4..fe04d728ea 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1224,7 +1224,7 @@ click them on the map: | Raster Functions | Slope, aspect, hillshade, NDVI, band math (`(b4-b3)/(b4+b3)`), remapping, thresholds, resampling | | Function Editor | Chains raster functions, each on the previous output | | Suitability Modeler | Scores rasters 1–10 and adds them with weights | -| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells (bilinear)** in the Workflows pane) reads it between the cells' centres instead. Both are estimates of the ground between cell centres; between cells is closer on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon. With no radius the viewshed covers the whole raster; a radius given is at most 500 km (a longer one is shortened, and the analysis says so). On a raster round the whole Earth the rays don't cross its ±180° edge, which the analysis says when the radius reaches it: given a radius, the ground just across the edge is left out; with none, it is worked out the long way round. The answer gives `acrossNoData` and `readNearest` (0 when there is nothing to say). Ground with no data hides nothing, and next to it bilinear heights take the nearest cell's height; the analysis says how many cells this touched, in a notice | +| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells (bilinear)** in the Workflows pane) reads it between the cells' centres instead. Both are estimates of the ground between cell centres; between cells is closer on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon. With no radius the viewshed covers the whole raster; a radius given is at most 500 km (a longer one is shortened, and the analysis says so). On a raster round the whole Earth the rays don't cross its east–west edge, which the analysis says when the radius reaches it: the ground just across the edge is left out, or, when the radius reaches the far edge through the raster too (always with no radius), worked out the long way round. The observer's height must be from 0 to 10,000 m. The answer gives `acrossNoData` and `readNearest` (0 when there is nothing to say). Ground with no data hides nothing, and next to it bilinear heights take the nearest cell's height; the analysis says how many cells this touched, in a notice | | Exploratory 3D Analysis | A line of sight between two points, split into seen and hidden parts, with the same curvature and refraction | | Geostatistical Wizard | An IDW surface from feature values, using 12 nearest neighbours by default | | Network Analysis | The shortest (or cheapest, by a cost field) route over a line layer | From 95e182949ea7a6c5676945d5ee7ae3d90d02506d Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 12 Nov 2026 06:33:44 +0100 Subject: [PATCH 10/12] fix(analysis): Viewshed weighs a bilinear step as two, says when ground across the edge is worked out only near the observer's row, bounds a radius given by the raster's diagonal; Viewshed Here reads the pane's ground heights --- crates/analysis/src/rasterops.rs | 28 ++++++++++-- crates/engine/src/cmd/workflows.rs | 68 +++++++++++++----------------- crates/engine/src/tests.rs | 42 +++++++++++++----- crates/ui-egui/src/analysispane.rs | 21 +++++---- crates/ui-egui/src/mapmenu.rs | 22 +++++++++- docs/user-guide/analysis.md | 2 +- 6 files changed, 120 insertions(+), 63 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index e9c6cc5527..7a5e8157ac 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -537,8 +537,11 @@ fn viewshed_on( // Each cell walks a ray back to the observer: bound cells × ray length, not just cells. let cells = (right - left + 1).saturating_mul(last - first + 1); let longest = (oc - left).max(right - oc).max(or - first).max(last - or); - // A bilinear step reads four cells where a nearest one reads one: weighed as four. - let per_step = if heights == Heights::Bilinear { 4 } else { 1 }; + // A ray steps a whole cell along its longer axis, so a bilinear point lies on a cell's + // centre line and reads the two cells it falls between ([`Heights::at`] skips a neighbour + // that weighs nothing; next to no data, the nearest cell too) where a nearest one reads one: + // weighed as two. + let per_step = if heights == Heights::Bilinear { 2 } else { 1 }; let ray_work = usize::try_from(cells.saturating_mul(longest / 2 + 1).saturating_mul(per_step)).unwrap_or(usize::MAX); // Each cell walks its own ray and writes only itself, so the rows within the radius are made // on several threads when the work is large (#1252), and may take as many times the work. @@ -548,7 +551,7 @@ fn viewshed_on( if ray_work > cap { return Err(format!( "the radius takes {ray_work} ray steps{}, more than the {cap} this computer takes on {threads} thread(s); use a smaller radius{}", - if per_step > 1 { " (a step between cells counted as four)" } else { "" }, + if per_step > 1 { " (a step between cells counted as two)" } else { "" }, crate::parallel::UNCAPPED_HINT )); } @@ -1699,6 +1702,25 @@ mod tests { assert!(vs.cells.iter().all(|v| *v == 1.0), "{:?}", vs.cells); } + /// A bilinear ray step is weighed as two in the work cap (it reads the two cells it falls + /// between), and a refusal says so: 1,000 × 1,000 cells from the middle on one thread take + /// 251 million nearest steps, under the cap, and 502 million weighed bilinear ones, over it. + #[test] + fn a_bilinear_viewshed_step_is_weighed_as_two_in_the_work_cap() { + let w = 1_000u32; + let transform = GeoTransform { origin_x: 0.0, origin_y: 45.0, pixel_width: 0.0003, pixel_height: -0.0003 }; + let dem = Raster::new("dem", w, w, vec![vec![0.0; (w * w) as usize]], transform, Crs::LonLat, None, ColorHint::Gray, "Float32") + .unwrap_or_else(|e| panic!("{e}")); + let middle = Coord::new(500.5 * 0.0003, 45.0 - 500.5 * 0.0003); + let e = viewshed_on(Some(1), &dem, 0, middle, 2.0, 1e9, Heights::Bilinear).unwrap_err(); + assert!( + e.starts_with(&format!( + "the radius takes 502000000 ray steps (a step between cells counted as two), more than the {MAX_VIEWSHED_WORK} this computer takes on 1 thread(s)" + )), + "{e}" + ); + } + /// Viewshed rows made on several threads see what one thread sees (#1252), with the radius /// inside the raster and reaching past its edges, with nearest and bilinear heights. #[test] diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 848af9a214..0c0f9ffd86 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -60,7 +60,7 @@ pub fn commands() -> Vec { r#"{"criteria": [{"layer": raster, "band"?: 1-based, "ranges": [[lo, hi, score]], "weight": number}], "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#, ), C::new("analysis.viewshed", "Visibility Analysis", "Analyze › Workflows", viewshed).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"layer": elevation raster, "lon", "lat", "band"?: 1-based, "height"?: observer metres, 0 to 10,000 (default 1.7), "radius"?: metres (at most 500 km; default: the whole raster), "heights"?: "nearest" (default) | "bilinear" (the ground along each ray), "name"?: output, "ran"?: (internal: a viewshed the app has worked out)}"#), + .params(r#"{"layer": elevation raster, "lon", "lat", "band"?: 1-based, "height"?: observer metres, 0 to 10,000 (default 1.7), "radius"?: metres (default: the whole raster), "heights"?: "nearest" (default) | "bilinear" (the ground along each ray), "name"?: output, "ran"?: (internal: a viewshed the app has worked out)}"#), C::new("analysis.lineOfSight", "Line Of Sight", "Analyze › Workflows", line_of_sight).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"layer": elevation raster, "from": [lon, lat], "to": [lon, lat], "band"?: 1-based, "observerHeight"?: m, "targetHeight"?: m, "name"?: output}"#, ), @@ -1077,15 +1077,6 @@ fn viewshed(s: &mut Session, p: &Value) -> CmdResult { made_or_ran(s, p, "analysis.viewshed") } -/// `m` metres as a notice says it: in km to a tenth, or in metres in exponent form when past a -/// million km. -fn metres(m: f64) -> String { - if m < 1e9 { format!("{} km", (m / 100.0).round() / 10.0) } else { format!("{m:.1e} m") } -} - -/// The longest radius a viewshed is given; with none, it covers the whole raster. -const MAX_VIEWSHED_RADIUS_M: f64 = 500_000.0; - /// What a viewshed reads of the session, and the work that makes it. fn viewshed_work(s: &Session, p: &Value) -> Result { let dem = raster_of(s, ps(p, "layer").ok_or("layer is required")?)?; @@ -1093,29 +1084,41 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { let band = band_of(p, &dem)?; let (cx, cy) = dem.cell_size_m(); // The whole raster by default, however large: its diagonal reaches every cell from any - // observer, and only the raster's cells are worked out. A radius given is at most 500 km. + // observer, and only the raster's cells are worked out. A radius given past the diagonal + // covers the same cells, so it is taken as the diagonal: nothing is left out. + let diagonal = (cx * dem.width as f64).hypot(cy * dem.height as f64).max(1.0); let (radius, given) = match p.get("radius") { - None | Some(Value::Null) => ((cx * dem.width as f64).hypot(cy * dem.height as f64).max(1.0), None), + None | Some(Value::Null) => (diagonal, None), Some(v) => { let r = f(p, "radius").filter(|r| *r > 0.0).ok_or_else(|| format!("radius must be a number of metres above 0, not {v}"))?; - (r.min(MAX_VIEWSHED_RADIUS_M), Some(r)) + (r.min(diagonal), Some(r)) } }; - // Shortened to the most a viewshed takes: said, with by how much. - let shortened = given.filter(|r| *r > MAX_VIEWSHED_RADIUS_M); // A raster around the whole Earth (in longitude/latitude) has its east and west edges side // by side, but rays don't cross from one to the other: said when the radius reaches an edge. // (Within half a cell of 360°: a cell size stored rounded falls a little short.) let pw = dem.transform.pixel_width.abs(); let round_the_earth = dem.crs.is_geographic() && pw * f64::from(dem.width) >= 360.0 - pw / 2.0; - let oc = dem.pixel_at(at).map_or(0, |(c, _)| c); - let to_edge = (oc.min(i64::from(dem.width) - 1 - oc) as f64 + 0.5) * cx; - let seam = round_the_earth && radius > to_edge; - // Whether the radius reaches the far edge's column (its centre on the observer's row, as the - // viewshed measures it), so the ground across the edge is worked out the long way round - // rather than left out. - let far = oc.max(i64::from(dem.width) - 1 - oc) as f64 * cx; - let both_edges = radius >= far; + let (oc, or) = dem.pixel_at(at).unwrap_or((0, 0)); + let (w, h) = (i64::from(dem.width), i64::from(dem.height)); + let (near, far) = (oc.min(w - 1 - oc), oc.max(w - 1 - oc)); + let seam = round_the_earth && radius > (near as f64 + 0.5) * cx; + // The ground just across the edge is the far edge's column, reached only through the raster: + // worked out the long way round in the rows where the radius reaches it (cell centres, as the + // viewshed measures them). The rows with ground across the edge within the radius are those + // where it reaches a cell one past the near edge. All of them are worked out when the radius + // reaches the far column in the farthest of those rows, none when it doesn't reach the far + // column even on the observer's row. + let reaches = |dc: i64, dr: i64| (dc as f64 * cx).hypot(dr as f64 * cy) <= radius; + // The rows are walked only on a raster round the Earth, at most its height. + let last_row = if seam { (0..=or.max(h - 1 - or)).take_while(|dr| reaches(near + 1, *dr)).last().unwrap_or(0) } else { 0 }; + let across = if !reaches(far, 0) { + "left out of the viewshed" + } else if reaches(far, last_row) { + "worked out the long way round" + } else { + "worked out the long way round near the observer's row and left out farther from it" + }; // Refused, naming it, when it isn't a height a viewshed takes: never another one used. let height = match p.get("height") { None | Some(Value::Null) => 1.7, @@ -1147,27 +1150,14 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { let (through_gaps, read_nearest) = (vs.through_gaps, vs.read_nearest); let answer = json!({"visibleCells": seen, "acrossNoData": through_gaps, "readNearest": read_nearest}); let m = made(rasterops::derive(&dem, &name, vec![vs.cells])?, Some(answer))?; - if through_gaps == 0 && read_nearest == 0 && shortened.is_none() && !seam { + if through_gaps == 0 && read_nearest == 0 && !seam { return Ok(m); } // Ground with no data hides nothing, and bilinear heights read the nearest cell beside - // it: said, with how many cells it touched. A radius shortened, and rays that don't - // cross the ±180° edge, said too. + // it: said, with how many cells it touched. Rays that don't cross the raster's east–west + // edge, said too. let then: Then = Box::new(move |s: &mut Session, _: &mut Value| { - if let Some(r) = shortened { - s.notify( - format!( - "{dem_name}: the radius of {} was taken as {}, the most a viewshed takes; with no radius it covers the whole raster", - metres(r), - metres(MAX_VIEWSHED_RADIUS_M) - ), - false, - ); - } if seam { - // Rays don't wrap across the edge: the ground across it is reached only through the - // raster, when the radius's window takes in the far edge's column too. - let across = if both_edges { "worked out the long way round" } else { "left out of the viewshed" }; s.notify( format!( "{dem_name}: the raster goes round the Earth, but the viewshed's rays don't cross its east–west edge: ground just across it is {across}" diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2399b2e67d..5833e7414e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9304,10 +9304,11 @@ fn a_viewshed_says_what_ground_with_no_data_it_saw_across() { } } -/// A viewshed's radius: one past 500 km is shortened to it, said with by how much; text or 0 is -/// refused, naming it; on a raster round the Earth whose edge the radius reaches, the rays not -/// crossing its east–west edge are said: left out when the radius's window doesn't take in the -/// far edge, worked out the long way round when it does. +/// A viewshed's radius: one past the raster's diagonal works out the same cells as none; text or +/// 0 is refused, naming it; on a raster round the Earth whose edge the radius reaches, the rays +/// not crossing its east–west edge are said: the ground across left out when the radius doesn't +/// reach the far edge's column, worked out the long way round when it does in every row it +/// reaches the near one, and partly when only near the observer's row. #[test] fn a_viewshed_says_what_it_did_with_its_radius_and_the_seam() { use base64::Engine; @@ -9331,14 +9332,16 @@ fn a_viewshed_says_what_it_did_with_its_radius_and_the_seam() { // Mid-way with a radius not reaching an edge: nothing said. let notes = said(&mut s, json!({"layer": dem, "lon": 0.0, "lat": 0.0, "radius": 50_000})); assert!(notes.is_empty(), "{notes:?}"); - // 600 km is taken as 500 km, and said; 500 km from the edge's cell reaches it. + // Given a radius reaching the near edge but not the far one, the ground across is left out. let notes = said(&mut s, json!({"layer": dem, "lon": -177.0, "lat": 0.0, "radius": 600_000})); - assert!(notes.iter().any(|n| n.contains("the radius of 600 km was taken as 500 km")), "{notes:?}"); - // Given a radius whose window doesn't reach the far edge, the ground across is left out. - assert!(notes.iter().any(|n| n.contains(seam) && n.ends_with("left out of the viewshed")), "{notes:?}"); - // Just past 500 km, said to a tenth of a km. - let notes = said(&mut s, json!({"layer": dem, "lon": 0.0, "lat": 0.0, "radius": 500_400})); - assert!(notes.iter().any(|n| n.contains("the radius of 500.4 km was taken as 500 km")), "{notes:?}"); + assert_eq!(notes.len(), 1, "{notes:?}"); + assert!(notes[0].contains(seam) && notes[0].ends_with("left out of the viewshed"), "{notes:?}"); + // A radius past the raster's diagonal works out the same cells as none, with nothing to say + // about the radius. + let visible = |s: &mut Session, p: Value| s.run("analysis.viewshed", &p).unwrap_or_else(|e| panic!("{p}: {e}"))["visibleCells"].clone(); + let (none, huge) = (json!({"layer": dem, "lon": 0.0, "lat": 0.0}), json!({"layer": dem, "lon": 0.0, "lat": 0.0, "radius": 1e12})); + assert_eq!(visible(&mut s, none.clone()), visible(&mut s, huge.clone())); + assert_eq!(said(&mut s, none), said(&mut s, huge)); // A geographic coordinate system other than WGS 84, and a cell size stored rounded // (180 × 1.99999° = 359.9998°): still round the Earth. let gt = GeoTransform { origin_x: -180.0, origin_y: 90.0, pixel_width: 1.99999, pixel_height: -2.0 }; @@ -9371,6 +9374,23 @@ fn a_viewshed_says_what_it_did_with_its_radius_and_the_seam() { let (cx, _) = s.map().layer_by_name(&cap).and_then(|l| l.raster.as_ref()?.data.as_ref().map(|r| r.cell_size_m())).unwrap(); let notes = said(&mut s, json!({"layer": cap, "lon": -170.0, "lat": 89.5, "radius": 2.5 * cx})); assert!(notes.iter().any(|n| n.contains(seam) && n.ends_with("left out of the viewshed")), "{notes:?}"); + // Three rows of 0.1° there: a radius of three cells reaches the far column on the observer's + // row only, so the ground across is worked out there and left out in the rows beside it; + // three cells and three rows reach it in every row. + let gt = GeoTransform { origin_x: -180.0, origin_y: 90.0, pixel_width: 90.0, pixel_height: -0.1 }; + let r = Raster::new("rows", 4, 3, vec![vec![0.0; 12]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(geotiff::write(&r, 0).unwrap()); + s.run("layer.addDataBytes", &json!({"fileName": "rows.tif", "data": data})).unwrap(); + let rows = s.map().layers.iter().find(|l| l.name.starts_with("rows")).unwrap().name.clone(); + let (cx, cy) = s.map().layer_by_name(&rows).and_then(|l| l.raster.as_ref()?.data.as_ref().map(|r| r.cell_size_m())).unwrap(); + let notes = said(&mut s, json!({"layer": rows, "lon": -170.0, "lat": 89.95, "radius": 3.0 * cx + 1.0})); + assert!(notes.iter().any(|n| n.contains(seam) && n.ends_with("near the observer's row and left out farther from it")), "{notes:?}"); + let notes = said(&mut s, json!({"layer": rows, "lon": -170.0, "lat": 89.95, "radius": (3.0 * cx).hypot(2.0 * cy) + 1.0})); + assert!(notes.iter().any(|n| n.contains(seam) && n.ends_with("worked out the long way round")), "{notes:?}"); + // From the second column, the far column is the one across the edge, two cells away either + // way: every cell across the edge within the radius is worked out, whatever the rows. + let notes = said(&mut s, json!({"layer": rows, "lon": -45.0, "lat": 89.95, "radius": 2.0 * cx + 1.0})); + assert!(notes.iter().any(|n| n.contains(seam) && n.ends_with("worked out the long way round")), "{notes:?}"); for bad in [json!("500km"), json!(0), json!(-5), json!(true)] { let e = s.run("analysis.viewshed", &json!({"layer": dem, "lon": 0.0, "lat": 0.0, "radius": bad})).unwrap_err(); assert_eq!(e, format!("radius must be a number of metres above 0, not {bad}")); diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 47a34944c9..0e4b8f5db0 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -2072,18 +2072,18 @@ mod tests { use super::*; use egui_kittest::kittest::Queryable; - /// An empty radius field (or one of spaces) runs the viewshed over the whole DEM: one whose - /// radius square, the DEM's diagonal each way, holds far more cells than the DEM, and - /// reaching farther than the 500 km a radius given takes. + /// An empty radius field (or one of spaces) runs the viewshed over the whole DEM, about + /// 630 km long: one whose radius square, the DEM's diagonal each way, holds far more cells + /// than the DEM. #[test] fn a_viewshed_with_an_empty_radius_field_sees_the_whole_dem() { use base64::Engine; use rustgis_engine::geom::Coord; let mut app = RustGisApp::with_sample(); use rustgis_engine::data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; - // A strip 4,000 cells long and 2 high, 0.002° (about 160 m) a cell: about 630 km, past - // the 500 km a radius given takes. The DEM's diagonal each way spans 8,001 × 8,001 - // cells, 64 million, of which 8,000 are the DEM's. + // A strip 4,000 cells long and 2 high, 0.002° (about 160 m) a cell: about 630 km. The + // DEM's diagonal each way spans 8,001 × 8,001 cells, 64 million, of which 8,000 are the + // DEM's. let (w, h) = (4_000u32, 2u32); let gt = GeoTransform { origin_x: 10.0, origin_y: 45.004, pixel_width: 0.002, pixel_height: -0.002 }; let dem = @@ -2101,11 +2101,16 @@ mod tests { (n, r.value(0, i64::from(w) - 1, 0).is_some()) }; let at = Coord::new(10.001, 45.001); - // A radius given is at most 500 km: the far end of the strip is left out. + // A radius given short of the far end leaves it out; one past the DEM's diagonal works + // out every cell, as an empty field does. + app.session + .run("analysis.viewshed", &json!({"layer": layer, "lon": at.x, "lat": at.y, "height": 2.0, "radius": 100_000, "name": "short"})) + .unwrap(); + assert!(!worked(&app, "short").1); app.session .run("analysis.viewshed", &json!({"layer": layer, "lon": at.x, "lat": at.y, "height": 2.0, "radius": 1e9, "name": "given"})) .unwrap(); - assert!(!worked(&app, "given").1); + assert_eq!(worked(&app, "given"), ((w * h) as usize, true)); for (i, radius) in ["", " "].into_iter().enumerate() { let workflow = Workflow { layer: layer.clone(), number: "2".into(), number2: radius.into(), ..Default::default() }; let mut p = viewshed_params(&workflow, at); diff --git a/crates/ui-egui/src/mapmenu.rs b/crates/ui-egui/src/mapmenu.rs index f84a351c29..df7fceb130 100644 --- a/crates/ui-egui/src/mapmenu.rs +++ b/crates/ui-egui/src/mapmenu.rs @@ -187,6 +187,16 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, c: Coord) { } } +/// A viewshed of `radius` metres from `c` on `dem`, reading the ground as the Workflows pane's +/// Ground heights says (`bilinear`): the pane its progress shows in. +fn viewshed_here(bilinear: bool, dem: &str, c: Coord, radius: f64, name: &str) -> serde_json::Value { + let mut p = json!({"layer": dem, "lon": c.x, "lat": c.y, "radius": radius, "name": name}); + if bilinear { + p["heights"] = json!("bilinear"); + } + p +} + /// Quick Analysis: the Buffer tool at a few distances, a viewshed and a line of sight on an /// elevation raster in the map, and the Buffer tool's own pane. fn quick_analysis(app: &mut RustGisApp, ui: &mut Ui, c: Coord) { @@ -212,7 +222,7 @@ fn quick_analysis(app: &mut RustGisApp, ui: &mut Ui, c: Coord) { { let name = i18n::fmt("Viewshed {radius}", &[("radius", &radius)]); // In the background on the desktop, its progress and Cancel in the Workflows pane. - let p = json!({"layer": dem, "lon": c.x, "lat": c.y, "radius": r, "name": name}); + let p = viewshed_here(app.workflow.bilinear, dem, c, r, &name); crate::analysispane::run_elsewhere(app, "visibility", "analysis.viewshed", p); ui.close(); } @@ -240,6 +250,16 @@ fn quick_analysis(app: &mut RustGisApp, ui: &mut Ui, c: Coord) { mod tests { use super::*; + /// Viewshed N km Here reads the ground between cells when the Workflows pane, where its + /// progress shows, is set to. + #[test] + fn a_viewshed_here_reads_the_ground_as_the_workflows_pane_says() { + let c = Coord::new(8.5, 47.4); + let nearest = viewshed_here(false, "dem", c, 2000.0, "Viewshed 2 km"); + assert_eq!(nearest, json!({"layer": "dem", "lon": 8.5, "lat": 47.4, "radius": 2000.0, "name": "Viewshed 2 km"})); + assert_eq!(viewshed_here(true, "dem", c, 2000.0, "Viewshed 2 km")["heights"], json!("bilinear")); + } + /// A place on a world copy reaches the commands within ±180 (they refuse it otherwise), and /// a failed action shows in the status bar instead of doing nothing. #[test] diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index fe04d728ea..6d7f3ffd9e 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1224,7 +1224,7 @@ click them on the map: | Raster Functions | Slope, aspect, hillshade, NDVI, band math (`(b4-b3)/(b4+b3)`), remapping, thresholds, resampling | | Function Editor | Chains raster functions, each on the previous output | | Suitability Modeler | Scores rasters 1–10 and adds them with weights | -| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells (bilinear)** in the Workflows pane) reads it between the cells' centres instead. Both are estimates of the ground between cell centres; between cells is closer on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon. With no radius the viewshed covers the whole raster; a radius given is at most 500 km (a longer one is shortened, and the analysis says so). On a raster round the whole Earth the rays don't cross its east–west edge, which the analysis says when the radius reaches it: the ground just across the edge is left out, or, when the radius reaches the far edge through the raster too (always with no radius), worked out the long way round. The observer's height must be from 0 to 10,000 m. The answer gives `acrossNoData` and `readNearest` (0 when there is nothing to say). Ground with no data hides nothing, and next to it bilinear heights take the nearest cell's height; the analysis says how many cells this touched, in a notice | +| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells (bilinear)** in the Workflows pane) reads it between the cells' centres instead. Both are estimates of the ground between cell centres; between cells is closer on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon. With no radius, or one longer than the raster's diagonal, the viewshed covers the whole raster. The map's **Viewshed N km Here** reads the ground as the Workflows pane's **Ground heights** says. On a raster round the whole Earth the rays don't cross its east–west edge, which the analysis says when the radius reaches it: the ground just across the edge is left out, worked out the long way round where the radius reaches the far edge through the raster too (always with no radius), or partly both, near the observer's row and not farther from it. The observer's height must be from 0 to 10,000 m. The answer gives `acrossNoData` and `readNearest` (0 when there is nothing to say). Ground with no data hides nothing, and next to it bilinear heights take the nearest cell's height; the analysis says how many cells this touched, in a notice | | Exploratory 3D Analysis | A line of sight between two points, split into seen and hidden parts, with the same curvature and refraction | | Geostatistical Wizard | An IDW surface from feature values, using 12 nearest neighbours by default | | Network Analysis | The shortest (or cheapest, by a cost field) route over a line layer | From 6b9b1b5a4f16b959b11ebfaaf0f92124145a2eab Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 12 Nov 2026 07:01:22 +0100 Subject: [PATCH 11/12] fix(analysis): Viewshed's seam notice only when the way across the edge is shorter; the user guide's Viewshed limit is its ray steps --- crates/engine/src/cmd/workflows.rs | 6 +++++- crates/engine/src/tests.rs | 17 ++++++++++++++--- docs/user-guide/analysis.md | 9 ++++++--- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 0c0f9ffd86..a290cc1584 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1102,7 +1102,11 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { let (oc, or) = dem.pixel_at(at).unwrap_or((0, 0)); let (w, h) = (i64::from(dem.width), i64::from(dem.height)); let (near, far) = (oc.min(w - 1 - oc), oc.max(w - 1 - oc)); - let seam = round_the_earth && radius > (near as f64 + 0.5) * cx; + // Only when the way across the edge is shorter than the way through the raster: the cell + // just across the near edge is `near + 1` cells away across it and `far` through the raster, + // and with no shorter way (the observer within a cell of the middle column) every cell is + // worked out as near as it is. + let seam = round_the_earth && near + 1 < far && radius > (near as f64 + 0.5) * cx; // The ground just across the edge is the far edge's column, reached only through the raster: // worked out the long way round in the rows where the radius reaches it (cell centres, as the // viewshed measures them). The rows with ground across the edge within the radius are those diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 5833e7414e..d5401734f8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9308,7 +9308,8 @@ fn a_viewshed_says_what_ground_with_no_data_it_saw_across() { /// 0 is refused, naming it; on a raster round the Earth whose edge the radius reaches, the rays /// not crossing its east–west edge are said: the ground across left out when the radius doesn't /// reach the far edge's column, worked out the long way round when it does in every row it -/// reaches the near one, and partly when only near the observer's row. +/// reaches the near one, and partly when only near the observer's row; nothing said when the way +/// across the edge is no shorter than through the raster. #[test] fn a_viewshed_says_what_it_did_with_its_radius_and_the_seam() { use base64::Engine; @@ -9388,9 +9389,19 @@ fn a_viewshed_says_what_it_did_with_its_radius_and_the_seam() { let notes = said(&mut s, json!({"layer": rows, "lon": -170.0, "lat": 89.95, "radius": (3.0 * cx).hypot(2.0 * cy) + 1.0})); assert!(notes.iter().any(|n| n.contains(seam) && n.ends_with("worked out the long way round")), "{notes:?}"); // From the second column, the far column is the one across the edge, two cells away either - // way: every cell across the edge within the radius is worked out, whatever the rows. + // way: nothing is shorter across the edge, so nothing is said. let notes = said(&mut s, json!({"layer": rows, "lon": -45.0, "lat": 89.95, "radius": 2.0 * cx + 1.0})); - assert!(notes.iter().any(|n| n.contains(seam) && n.ends_with("worked out the long way round")), "{notes:?}"); + assert!(notes.is_empty(), "{notes:?}"); + // Nor from the middle of an odd number of columns (2 of 5), each edge two cells away. + let gt = GeoTransform { origin_x: -180.0, origin_y: 90.0, pixel_width: 72.0, pixel_height: -0.1 }; + let r = Raster::new("odd", 5, 3, vec![vec![0.0; 15]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(geotiff::write(&r, 0).unwrap()); + s.run("layer.addDataBytes", &json!({"fileName": "odd.tif", "data": data})).unwrap(); + let odd = s.map().layers.iter().find(|l| l.name.starts_with("odd")).unwrap().name.clone(); + for p in [json!({"layer": odd, "lon": 0.0, "lat": 89.95}), json!({"layer": odd, "lon": 0.0, "lat": 89.95, "radius": 2.5 * cx})] { + let notes = said(&mut s, p); + assert!(notes.is_empty(), "{notes:?}"); + } for bad in [json!("500km"), json!(0), json!(-5), json!(true)] { let e = s.run("analysis.viewshed", &json!({"layer": dem, "lon": 0.0, "lat": 0.0, "radius": bad})).unwrap_err(); assert_eq!(e, format!("radius must be a number of metres above 0, not {bad}")); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 6d7f3ffd9e..85b38fafb0 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -103,8 +103,11 @@ times more work as the threads it runs on. Threads share cores and memory, so a can take up to about twice as long as a one-thread run at its own (measured on one machine, a Xeon Silver 4114; it can be longer on others); in the web app, on one thread, the limits stay as they are. The error names the limit on this computer and the threads it counted. The limits on memory -(the cells a grid may have, and those on the following pages) hold everywhere, as does Viewshed's on -its window: a radius covering more than 25 million cells, or 100,000 cells across, is refused. A +(the cells a grid may have, and those on the following pages) hold everywhere. Viewshed has no limit +on its window (a radius past the raster's diagonal is taken as the diagonal), only on its ray steps: +with no radius it covers the whole raster, so on a large one it can be refused where nobody can stop +the run (the web app, a script, the assistant). A smaller radius, or a run from its pane on the +desktop or with `rustgis-cli run`, gets it through. A tool's own default cell size still follows the one-thread limit, so it makes the same grid on any computer and from any caller; a finer cell size given is what a larger limit, or none, lets through. @@ -1224,7 +1227,7 @@ click them on the map: | Raster Functions | Slope, aspect, hillshade, NDVI, band math (`(b4-b3)/(b4+b3)`), remapping, thresholds, resampling | | Function Editor | Chains raster functions, each on the previous output | | Suitability Modeler | Scores rasters 1–10 and adds them with weights | -| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells (bilinear)** in the Workflows pane) reads it between the cells' centres instead. Both are estimates of the ground between cell centres; between cells is closer on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon. With no radius, or one longer than the raster's diagonal, the viewshed covers the whole raster. The map's **Viewshed N km Here** reads the ground as the Workflows pane's **Ground heights** says. On a raster round the whole Earth the rays don't cross its east–west edge, which the analysis says when the radius reaches it: the ground just across the edge is left out, worked out the long way round where the radius reaches the far edge through the raster too (always with no radius), or partly both, near the observer's row and not farther from it. The observer's height must be from 0 to 10,000 m. The answer gives `acrossNoData` and `readNearest` (0 when there is nothing to say). Ground with no data hides nothing, and next to it bilinear heights take the nearest cell's height; the analysis says how many cells this touched, in a notice | +| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells (bilinear)** in the Workflows pane) reads it between the cells' centres instead. Both are estimates of the ground between cell centres; between cells is closer on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon. With no radius, or one longer than the raster's diagonal, the viewshed covers the whole raster. The map's **Viewshed N km Here** reads the ground as the Workflows pane's **Ground heights** says. On a raster round the whole Earth the rays don't cross its east–west edge, which the analysis says when the radius reaches it and the way across is shorter: the ground just across the edge is left out, worked out the long way round where the radius reaches the far edge through the raster too (always with no radius), or partly both, near the observer's row and not farther from it. The observer's height must be from 0 to 10,000 m. The answer gives `acrossNoData` and `readNearest` (0 when there is nothing to say). Ground with no data hides nothing, and next to it bilinear heights take the nearest cell's height; the analysis says how many cells this touched, in a notice | | Exploratory 3D Analysis | A line of sight between two points, split into seen and hidden parts, with the same curvature and refraction | | Geostatistical Wizard | An IDW surface from feature values, using 12 nearest neighbours by default | | Network Analysis | The shortest (or cheapest, by a cost field) route over a line layer | From 1268f478bd5f0a327513b9d268557241665d2770 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 12 Nov 2026 07:27:36 +0100 Subject: [PATCH 12/12] fix(analysis): Viewshed's seam notice from the cell across the edge; a refusal names the whole raster itself; the counts defined --- crates/analysis/src/rasterops.rs | 20 ++++++++++++++++++-- crates/engine/src/cmd/workflows.rs | 21 ++++++--------------- crates/engine/src/tests.rs | 7 +++++-- docs/user-guide/analysis.md | 2 +- 4 files changed, 30 insertions(+), 20 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 7a5e8157ac..fdca36418b 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -549,8 +549,16 @@ fn viewshed_on( let threads = threads.unwrap_or_else(|| crate::parallel::threads_for_rows(rows, ray_work, 0)); let cap = crate::parallel::work_cap(MAX_VIEWSHED_WORK, threads); if ray_work > cap { + // A radius reaching the raster's farthest corner covers all of it (as with no radius + // given, the raster's diagonal): said as the whole raster, not as a radius to shorten. + let corner = ((oc.max(r.width as i64 - 1 - oc)) as f64 * cx).hypot((or.max(r.height as i64 - 1 - or)) as f64 * cy); + let (what, fix) = if radius_m >= corner { + ("the whole raster", "give a radius to cover only part of it") + } else { + ("the radius", "use a smaller radius") + }; return Err(format!( - "the radius takes {ray_work} ray steps{}, more than the {cap} this computer takes on {threads} thread(s); use a smaller radius{}", + "{what} takes {ray_work} ray steps{}, more than the {cap} this computer takes on {threads} thread(s); {fix}{}", if per_step > 1 { " (a step between cells counted as two)" } else { "" }, crate::parallel::UNCAPPED_HINT )); @@ -1705,6 +1713,8 @@ mod tests { /// A bilinear ray step is weighed as two in the work cap (it reads the two cells it falls /// between), and a refusal says so: 1,000 × 1,000 cells from the middle on one thread take /// 251 million nearest steps, under the cap, and 502 million weighed bilinear ones, over it. + /// A radius reaching every cell is refused as the whole raster; one short of the corners, + /// with the same window and steps, as a radius. #[test] fn a_bilinear_viewshed_step_is_weighed_as_two_in_the_work_cap() { let w = 1_000u32; @@ -1715,10 +1725,16 @@ mod tests { let e = viewshed_on(Some(1), &dem, 0, middle, 2.0, 1e9, Heights::Bilinear).unwrap_err(); assert!( e.starts_with(&format!( - "the radius takes 502000000 ray steps (a step between cells counted as two), more than the {MAX_VIEWSHED_WORK} this computer takes on 1 thread(s)" + "the whole raster takes 502000000 ray steps (a step between cells counted as two), more than the {MAX_VIEWSHED_WORK} this computer takes on 1 thread(s); give a radius to cover only part of it" )), "{e}" ); + // 600 of the longer cell side: past every edge (500 cells away), short of the corners + // (about 707 cells of the side's mean away; the cells are longer north–south at 45°). + let (cx, cy) = dem.cell_size_m(); + assert!(600.0 * cx.max(cy) < (500.0 * cx).hypot(500.0 * cy)); + let e = viewshed_on(Some(1), &dem, 0, middle, 2.0, 600.0 * cx.max(cy), Heights::Bilinear).unwrap_err(); + assert!(e.starts_with("the radius takes 502000000 ray steps") && e.contains("; use a smaller radius"), "{e}"); } /// Viewshed rows made on several threads see what one thread sees (#1252), with the radius diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index a290cc1584..80483c790c 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1087,11 +1087,10 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { // observer, and only the raster's cells are worked out. A radius given past the diagonal // covers the same cells, so it is taken as the diagonal: nothing is left out. let diagonal = (cx * dem.width as f64).hypot(cy * dem.height as f64).max(1.0); - let (radius, given) = match p.get("radius") { - None | Some(Value::Null) => (diagonal, None), + let radius = match p.get("radius") { + None | Some(Value::Null) => diagonal, Some(v) => { - let r = f(p, "radius").filter(|r| *r > 0.0).ok_or_else(|| format!("radius must be a number of metres above 0, not {v}"))?; - (r.min(diagonal), Some(r)) + f(p, "radius").filter(|r| *r > 0.0).ok_or_else(|| format!("radius must be a number of metres above 0, not {v}"))?.min(diagonal) } }; // A raster around the whole Earth (in longitude/latitude) has its east and west edges side @@ -1106,7 +1105,7 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { // just across the near edge is `near + 1` cells away across it and `far` through the raster, // and with no shorter way (the observer within a cell of the middle column) every cell is // worked out as near as it is. - let seam = round_the_earth && near + 1 < far && radius > (near as f64 + 0.5) * cx; + let seam = round_the_earth && near + 1 < far && (near as f64 + 1.0) * cx <= radius; // The ground just across the edge is the far edge's column, reached only through the raster: // worked out the long way round in the rows where the radius reaches it (cell centres, as the // viewshed measures them). The rows with ground across the edge within the radius are those @@ -1141,15 +1140,7 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { let name = out_name(p, format!("{}_viewshed", dem.name)); let dem_name = dem.name.clone(); Ok(Box::new(move || { - let vs = rasterops::viewshed(&dem, band, at, height, radius, heights).map_err(|e| { - // With no radius given, the work is the whole raster's, not a radius's. - if given.is_none() && e.starts_with("the radius takes") { - e.replacen("the radius takes", "the whole raster (no radius given) takes", 1) - .replace("use a smaller radius", "give a radius") - } else { - e - } - })?; + let vs = rasterops::viewshed(&dem, band, at, height, radius, heights)?; let seen = vs.cells.iter().filter(|v| **v == 1.0).count(); let (through_gaps, read_nearest) = (vs.through_gaps, vs.read_nearest); let answer = json!({"visibleCells": seen, "acrossNoData": through_gaps, "readNearest": read_nearest}); @@ -1179,7 +1170,7 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { } if read_nearest > 0 { s.notify( - format!("{dem_name}: {read_nearest} cell(s) of the viewshed were worked out with the nearest cell's height next to ground with no data, not between cells"), + format!("{dem_name}: {read_nearest} cell(s) were worked out with the nearest cell's height next to ground with no data, not between cells"), false, ); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d5401734f8..36486c95c8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9296,8 +9296,7 @@ fn a_viewshed_says_what_ground_with_no_data_it_saw_across() { } else { assert!(nearest > 100, "{v}"); assert!( - said.iter() - .any(|t| t.contains(&format!("{nearest} cell(s) of the viewshed were worked out with the nearest cell's height"))), + said.iter().any(|t| t.contains(&format!("{nearest} cell(s) were worked out with the nearest cell's height"))), "{said:?}" ); } @@ -9330,6 +9329,10 @@ fn a_viewshed_says_what_it_did_with_its_radius_and_the_seam() { // By the edge with no radius (the whole raster): the seam is said. let notes = said(&mut s, json!({"layer": dem, "lon": -179.0, "lat": 0.0})); assert!(notes.iter().any(|n| n.contains(seam) && n.ends_with("worked out the long way round")), "{notes:?}"); + // By the edge with a radius past the edge line but short of the cell across it (2° is about + // 222 km there): nothing across it is within the radius, so nothing said. + let notes = said(&mut s, json!({"layer": dem, "lon": -179.0, "lat": 0.0, "radius": 150_000})); + assert!(notes.is_empty(), "{notes:?}"); // Mid-way with a radius not reaching an edge: nothing said. let notes = said(&mut s, json!({"layer": dem, "lon": 0.0, "lat": 0.0, "radius": 50_000})); assert!(notes.is_empty(), "{notes:?}"); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 85b38fafb0..5dcde35cc3 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1227,7 +1227,7 @@ click them on the map: | Raster Functions | Slope, aspect, hillshade, NDVI, band math (`(b4-b3)/(b4+b3)`), remapping, thresholds, resampling | | Function Editor | Chains raster functions, each on the previous output | | Suitability Modeler | Scores rasters 1–10 and adds them with weights | -| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells (bilinear)** in the Workflows pane) reads it between the cells' centres instead. Both are estimates of the ground between cell centres; between cells is closer on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon. With no radius, or one longer than the raster's diagonal, the viewshed covers the whole raster. The map's **Viewshed N km Here** reads the ground as the Workflows pane's **Ground heights** says. On a raster round the whole Earth the rays don't cross its east–west edge, which the analysis says when the radius reaches it and the way across is shorter: the ground just across the edge is left out, worked out the long way round where the radius reaches the far edge through the raster too (always with no radius), or partly both, near the observer's row and not farther from it. The observer's height must be from 0 to 10,000 m. The answer gives `acrossNoData` and `readNearest` (0 when there is nothing to say). Ground with no data hides nothing, and next to it bilinear heights take the nearest cell's height; the analysis says how many cells this touched, in a notice | +| Visibility Analysis | A viewshed from a point on an elevation raster, with the Earth's curvature and the refraction of visible light (1/7, as `gdal_viewshed`). The ground along each ray is the cell each point falls in by default; `heights: "bilinear"` (**Ground heights › Between cells (bilinear)** in the Workflows pane) reads it between the cells' centres instead. Both are estimates of the ground between cell centres; between cells is closer on ground that bulges (a hill seen from its top), where the nearest cell can hide cells just inside the horizon. With no radius, or one longer than the raster's diagonal, the viewshed covers the whole raster. The map's **Viewshed N km Here** reads the ground as the Workflows pane's **Ground heights** says. On a raster round the whole Earth the rays don't cross its east–west edge, which the analysis says when the radius reaches it and the way across is shorter: the ground just across the edge is left out, worked out the long way round where the radius reaches the far edge through the raster too (always with no radius), or partly both, near the observer's row and not farther from it. The observer's height must be from 0 to 10,000 m. Ground with no data hides nothing, and next to it bilinear heights take the nearest cell's height; the analysis says how many cells this touched, in a notice. The answer gives both counts (0 when there is nothing to say): `acrossNoData` counts the visible cells whose rays crossed ground with no data (a hidden cell stays hidden whatever that ground is, so it isn't counted, and 0 doesn't mean no ray crossed any); `readNearest` counts every cell, visible or hidden, whose ray took a nearest height next to no data in bilinear mode | | Exploratory 3D Analysis | A line of sight between two points, split into seen and hidden parts, with the same curvature and refraction | | Geostatistical Wizard | An IDW surface from feature values, using 12 nearest neighbours by default | | Network Analysis | The shortest (or cheapest, by a cost field) route over a line layer |