diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index 7317c4afed..428bba8e5b 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -13,7 +13,8 @@ use std::collections::HashMap; -use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, Transformer, max_samples}; +use rustgis_data::raster::crs::grid_generation; +use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, Reprojection, Transformer, max_samples}; use rustgis_geom::Coord; use crate::georef::Fit; @@ -78,7 +79,9 @@ pub struct Options { pub name: String, } -/// Map coordinates of the fit, to and from the output's coordinate system. +/// Map coordinates in one coordinate system to another's through longitude/latitude: for the +/// footprints and bounds other commands size a grid by ([`footprint_in`], [`bounds_in`]), and +/// [`Route`] between two systems on one datum. struct Reproject { from: Transformer, to: Transformer, @@ -90,7 +93,7 @@ impl Reproject { Ok(Reproject { from: points.transformer()?, to: out.transformer()?, same: points == out }) } - /// Fit coordinates to output coordinates. + /// Coordinates in the first system to the second's. fn forward(&self, x: f64, y: f64) -> Option<(f64, f64)> { if self.same { return (x.is_finite() && y.is_finite()).then_some((x, y)); @@ -98,17 +101,48 @@ impl Reproject { let c = self.to.from_lonlat(self.from.to_lonlat(Coord::new(x, y))?)?; Some((c.x, c.y)) } +} - /// Output coordinates to fit coordinates. - fn back(&self, x: f64, y: f64) -> Option<(f64, f64)> { - if self.same { - return (x.is_finite() && y.is_finite()).then_some((x, y)); +/// Map coordinates in one coordinate system to another's as Project Raster and Georeference +/// place them. Between two datums, by the transformation between them ([`Crs::to`]) rather than +/// each datum's shift to WGS 84 and back; it falls back to WGS 84 where the datums have no +/// transformation between them or it can't place a point. Between two systems on one datum, +/// through longitude/latitude as before, so such a grid is sized and sampled as it always was: +/// the direct operation's rounding differs, which can move a grid's edge across a cell. +enum Route { + Direct(Reprojection), + Lonlat(Reproject), +} + +impl Route { + /// The route from `from` to `to`: direct when [`Crs::to`] shifts datum between them. Fails as + /// either system's transformer does. + fn new(from: Crs, to: Crs) -> Result { + let re = from.to(to)?; + if re.shifts_datum() { Ok(Route::Direct(re)) } else { Reproject::new(from, to).map(Route::Lonlat) } + } + + /// The place `(x, y)` in the second system, as an `(x, y)` pair. + fn point(&self, x: f64, y: f64) -> Option<(f64, f64)> { + match self { + Route::Direct(re) => re.point(Coord::new(x, y)).map(|c| (c.x, c.y)), + Route::Lonlat(re) => re.forward(x, y), } - let c = self.from.from_lonlat(self.to.to_lonlat(Coord::new(x, y))?)?; - Some((c.x, c.y)) } } +/// Runs `f`, refusing its result when datum grids arrived meanwhile ([`grid_generation`]): its +/// conversions, built again for them, may then have placed one raster by two transformations. +/// Nothing is kept from a refused run. +pub fn on_unchanged_grids(what: &str, f: impl FnOnce() -> Result) -> Result { + let generation = grid_generation(); + let out = f()?; + if grid_generation() != generation { + return Err(format!("datum grids arrived while {what} ran, so its cells may be placed by two transformations: run it again")); + } + Ok(out) +} + /// Reads pixels at fractional image positions. struct Sampler<'a> { r: &'a Raster, @@ -218,15 +252,22 @@ impl Sampler<'_> { /// `r` (in the full image's pixels, when `r` is an overview of it) and whose map coordinates are /// in `o.points_crs`. The grid covers the warped image's footprint. A colour or grey byte raster /// with neither alpha nor no-data gets an alpha band (0–255), so the cells outside the image are -/// see-through. Geographic output cells are square in degrees. +/// see-through. Geographic output cells are square in degrees. Map coordinates go between +/// `o.points_crs` and `o.crs` as [`Route`] takes them. Refused when datum grids arrive while it +/// runs ([`on_unchanged_grids`]). pub fn warp(r: &Raster, fit: &Fit, o: &Options) -> Result { - let re = Reproject::new(o.points_crs, o.crs)?; + on_unchanged_grids("the warp", || warp_now(r, fit, o)) +} + +/// [`warp`], whatever grids arrive. +fn warp_now(r: &Raster, fit: &Fit, o: &Options) -> Result { + let (forward, back) = (Route::new(o.points_crs, o.crs)?, Route::new(o.crs, o.points_crs)?); let (w, h) = (f64::from(r.width), f64::from(r.height)); // An overview's pixels are bigger than the full image's, which the fit is in; a grid of // posts read at a step also starts before the file's corner (each cell centered on its post). let (sx, sy) = r.file_pixels(); let (ox, oy) = r.file_origin(); - let place = |c: f64, row: f64| fit.to_map(c * sx + ox, row * sy + oy).and_then(|(x, y)| re.forward(x, y)); + let place = |c: f64, row: f64| fit.to_map(c * sx + ox, row * sy + oy).and_then(|(x, y)| forward.point(x, y)); let [min_x, min_y, max_x, max_y] = footprint(w, h, &place).ok_or("the image's edge can't be placed in the output coordinate system")?; if o.crs.is_geographic() && max_x - min_x > 180.0 { @@ -275,7 +316,7 @@ pub fn warp(r: &Raster, fit: &Fit, o: &Options) -> Result { let g = Grid { crs: o.crs, min_x, max_y, cell_x: cell, cell_y: cell, width: ow as usize, height: oh as usize }; // The image position of an output coordinate. let source = |x: f64, y: f64| -> Option<(f64, f64)> { - let (px, py) = re.back(x, y)?; + let (px, py) = back.point(x, y)?; let (c, row) = fit.to_pixel(px, py)?; let (c, row) = ((c - ox) / sx, (row - oy) / sy); (c.is_finite() && row.is_finite()).then_some((c, row)) @@ -387,14 +428,29 @@ impl Grid { } } -/// The bounds in `crs` of `r`'s footprint, and about the size of its pixel there. +/// The bounds in `crs` of `r`'s footprint, and about the size of its pixel there, through +/// longitude/latitude. pub fn footprint_in(r: &Raster, crs: Crs) -> Result<([f64; 4], f64), String> { r.require_coordinates()?; let re = Reproject::new(r.crs, crs)?; + footprint_by(r, crs, &|x, y| re.forward(x, y)) +} + +/// [`footprint_in`] placed as [`project`] places `r`'s pixels ([`Route`]), so a grid sized by it +/// holds what `project` samples. Between two systems on one datum, [`footprint_in`]. +pub fn projected_footprint(r: &Raster, crs: Crs) -> Result<([f64; 4], f64), String> { + r.require_coordinates()?; + let re = Route::new(r.crs, crs)?; + footprint_by(r, crs, &|x, y| re.point(x, y)) +} + +/// The bounds and pixel size of [`footprint_in`], `r`'s map coordinates converted to `crs` by +/// `to`. +fn footprint_by(r: &Raster, crs: Crs, to: &dyn Fn(f64, f64) -> Option<(f64, f64)>) -> Result<([f64; 4], f64), String> { let t = r.transform; let place = |c: f64, row: f64| { let p = t.to_world(c, row); - re.forward(p.x, p.y) + to(p.x, p.y) }; let (w, h) = (f64::from(r.width), f64::from(r.height)); let bounds = footprint(w, h, &place).ok_or_else(|| format!("{} can't be placed in {}", r.name, crs.label()))?; @@ -452,9 +508,9 @@ impl Method { } } -/// Projects `r` onto the grid `g`, through longitude/latitude when their coordinate systems -/// differ: each cell sampled at its centre, or (average, mode) taken from every pixel of `r` -/// whose centre falls in it. A cell no pixel centre falls in (a grid finer than the raster) takes +/// Projects `r` onto the grid `g`, its coordinates converted as [`Route`] takes them when their +/// systems differ (size the grid with [`projected_footprint`]): each cell sampled at its centre, +/// or (average, mode) taken from every pixel of `r` whose centre falls in it. A cell no pixel centre falls in (a grid finer than the raster) takes /// the pixel under its centre. Outside cells use 0 in every band when alpha is present or /// added; otherwise they use explicit no-data. Without either, they use NaN for floating-point /// data, RGB data with more than three bands, or when any band has class names, else 0. @@ -478,10 +534,10 @@ fn project_on(threads: Option, r: &Raster, g: &Grid, method: Method, name g.width, g.height, out_bands )); } - let re = Reproject::new(r.crs, g.crs)?; + let back = Route::new(g.crs, r.crs)?; let t = r.transform; let source = |x: f64, y: f64| -> Option<(f64, f64)> { - let (px, py) = re.back(x, y)?; + let (px, py) = back.point(x, y)?; let (c, row) = t.to_pixel(Coord::new(px, py)); (c.is_finite() && row.is_finite()).then_some((c, row)) }; @@ -1629,6 +1685,75 @@ mod tests { } } + /// Between two datums each cell is sampled where the direct operation puts it (DHDN to ETRS89's + /// transformation), not where each datum's shift to WGS 84 and back does, about 0.44 m away + /// here; on one thread and on several alike. + #[test] + fn a_projection_between_datums_takes_their_transformation() { + // 40 × 40 pixels of 1 m in Gauss-Krüger zone 3 on DHDN, its bands the column and row of a + // place, so bilinear sampling gives back where a cell was sampled. + let (gk3, utm32) = (Crs::from_epsg(31467).unwrap(), Crs::from_epsg(25832).unwrap()); + let gt = GeoTransform { origin_x: 3_500_000.0, origin_y: 5_400_040.0, pixel_width: 1.0, pixel_height: -1.0 }; + let (col, row): (Vec, Vec) = (0..1600).map(|i| ((i % 40) as f32 + 0.5, (i / 40) as f32 + 0.5)).unzip(); + let r = Raster::new("t", 40, 40, vec![col, row], gt, gk3, None, ColorHint::Gray, "Float32").unwrap(); + let (bounds, _) = projected_footprint(&r, utm32).unwrap(); + // Sized on the same route: the corners where the direct operation puts them, not where + // the way through WGS 84 does. + let corners = |to: &dyn Fn(Coord) -> Coord| { + let c: Vec = [(0.0, 0.0), (40.0, 0.0), (0.0, 40.0), (40.0, 40.0)].iter().map(|&(i, j)| to(gt.to_world(i, j))).collect(); + let (xs, ys) = (c.iter().map(|c| c.x), c.iter().map(|c| c.y)); + [ + xs.clone().fold(f64::MAX, f64::min), + ys.clone().fold(f64::MAX, f64::min), + xs.fold(f64::MIN, f64::max), + ys.fold(f64::MIN, f64::max), + ] + }; + let forward = gk3.to(utm32).unwrap(); + let sized = corners(&|c| forward.point(c).unwrap()); + assert!(bounds.iter().zip(sized).all(|(a, b)| (a - b).abs() < 1e-6), "{bounds:?} against {sized:?}"); + let (from, to) = (gk3.transformer().unwrap(), utm32.transformer().unwrap()); + let via = corners(&|c| to.from_lonlat(from.to_lonlat(c).unwrap()).unwrap()); + assert!(bounds.iter().zip(via).any(|(a, b)| (a - b).abs() > 0.2), "{bounds:?} through WGS 84 is {via:?}"); + let g = Grid::snapped(utm32, bounds, (1.0, 1.0), (0.0, 0.0)).unwrap(); + let out = project_on(Some(1), &r, &g, Method::Sample(Resampling::Bilinear), "p".into()).unwrap(); + let many = project_on(Some(4), &r, &g, Method::Sample(Resampling::Bilinear), "p".into()).unwrap(); + let bits = |r: &Raster| r.bands.iter().map(|b| b.data.iter().map(|v| v.to_bits()).collect::>()).collect::>(); + assert_eq!(bits(&out), bits(&many)); + let (direct, back) = (utm32.to(gk3).unwrap(), (utm32.transformer().unwrap(), gk3.transformer().unwrap())); + let pixel = |p: Coord| (p.x - gt.origin_x, gt.origin_y - p.y); + let mut checked = 0; + for j in 0..g.height { + for i in 0..g.width { + let at = Coord::new(g.min_x + (i as f64 + 0.5) * g.cell_x, g.max_y - (j as f64 + 0.5) * g.cell_y); + let want = pixel(direct.point(at).unwrap()); + // Away from the edge, where bilinear sampling is linear. + if !(1.0..39.0).contains(&want.0) || !(1.0..39.0).contains(&want.1) { + continue; + } + let got = (f64::from(out.bands[0].data[j * g.width + i]), f64::from(out.bands[1].data[j * g.width + i])); + assert!((got.0 - want.0).abs().max((got.1 - want.1).abs()) < 1e-3, "cell {i}, {j}: {got:?} against {want:?}"); + let via = pixel(back.1.from_lonlat(back.0.to_lonlat(at).unwrap()).unwrap()); + assert!((via.0 - want.0).hypot(via.1 - want.1) > 0.4, "cell {i}, {j}: {via:?} through WGS 84"); + checked += 1; + } + } + assert!(checked > 1000, "{checked} cells checked"); + } + + /// Between two systems on one datum (UTM 16N and World Mercator, both WGS 84), the grid is + /// sized as it always was, through longitude/latitude: the direct operation's rounding put the + /// east edge across a snapped cell boundary, one column short. + #[test] + fn a_projection_on_one_datum_is_sized_as_before() { + let (utm16, mercator) = (Crs::from_epsg(32616).unwrap(), Crs::from_epsg(3395).unwrap()); + let gt = GeoTransform { origin_x: 500_000.0, origin_y: 30.0, pixel_width: 1.0, pixel_height: -1.0 }; + let r = Raster::new("t", 40, 30, vec![vec![1.0; 1200]], gt, utm16, None, ColorHint::Gray, "Float32").unwrap(); + let (bounds, _) = projected_footprint(&r, mercator).unwrap(); + let g = Grid::snapped(mercator, bounds, (1.0, 1.0), (-9_684_795.699_014_802, 0.0)).unwrap(); + assert_eq!((g.width, g.height, g.min_x, g.max_y), (42, 31, -9_684_796.699_014_802, 31.0), "{bounds:?}"); + } + /// A raster projected to another system and back keeps its values in place, within a cell. #[test] fn a_projection_and_back_keeps_values_in_place() { diff --git a/crates/data/src/raster/crs.rs b/crates/data/src/raster/crs.rs index 9a53e37034..7cdaf4b461 100644 --- a/crates/data/src/raster/crs.rs +++ b/crates/data/src/raster/crs.rs @@ -1092,6 +1092,9 @@ pub(crate) struct DirectOperation { missing: Vec, /// Its pair's key ([`pair_key`]), what its notes are kept under. key: String, + /// Whether it changes datum: false between two systems on one datum, where it runs no + /// transformation (at the middle of the source's area of use, which no grid changes). + shifts: bool, } // What it noted and the session hasn't asked for yet is the pair's as it goes (built again when @@ -1171,6 +1174,12 @@ impl DirectPair { Some(DirectPair { source, target, from: from.clone(), to: to.clone(), first, built_for, again }) } + /// Whether it changes datum ([`DirectOperation`]'s `shifts`), as first built: grids change + /// which transformation it takes, not whether it takes one. + pub(crate) fn shifts_datum(&self) -> bool { + self.first.shifts + } + /// [`DirectOperation::point`], by the operation built for the grids there are now: as first /// built until grids arrive (one atomic load), then as built again (a read lock). pub(crate) fn point(&self, c: Coord, via: Coord) -> Option { @@ -1267,6 +1276,9 @@ fn build_direct( }; let at = [source, target].into_iter().find_map(|crs| area_of_use(crs).and_then(|c| from.from_lonlat(c))); let grids = at.and_then(|c| op.best_operation_grids_at(c.x, c.y, 0.0).ok()).unwrap_or_default(); + // No operation there only between two systems on one datum; a place it can't convert, or none + // known, counts as a shift. + let shifts = at.is_none_or(|c| !matches!(op.operation_at(c.x, c.y, 0.0), Ok(None))); if grids.iter().any(|g| !g.available && !g.optional) { let mut needs = needs_grid().lock().unwrap_or_else(|e| e.into_inner()); if !needs.iter().any(|d| d == key) { @@ -1274,7 +1286,7 @@ fn build_direct( } } let missing = grids.into_iter().filter(downloadable).filter_map(|g| Some(MissingGrid { url: g.url?, name: g.name })).collect(); - Some(std::sync::Arc::new(DirectOperation { op, turn, slack, missing, key: key.to_string() })) + Some(std::sync::Arc::new(DirectOperation { op, turn, slack, missing, key: key.to_string(), shifts })) } /// The datum grids the direct operation from `source` to `target` needs where the source's data diff --git a/crates/data/src/raster/reproject.rs b/crates/data/src/raster/reproject.rs index 5e477e797e..be1d80bc37 100644 --- a/crates/data/src/raster/reproject.rs +++ b/crates/data/src/raster/reproject.rs @@ -101,6 +101,16 @@ impl Reprojection { self.direct.is_some() } + /// Whether it takes a transformation between two datums where it can: the direct operation, + /// between systems on different datums. Between two systems on one datum it converts as the + /// way through WGS 84 does, but for rounding. + pub fn shifts_datum(&self) -> bool { + match &self.through { + Some(through) => through.0.shifts_datum() || through.1.shifts_datum(), + None => self.direct.as_ref().is_some_and(|d| d.shifts_datum()), + } + } + /// A place in the target system, or `None` where the source system has no such place or the /// target can't hold it. Each system's transformer judges what it is given, as a call of its /// own did: Web Mercator takes a latitude past 85.05° (an infinite one too) as 85.05°, where diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 2b3ea8d9a8..a361bf6ff9 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -518,10 +518,15 @@ fn project_raster(s: &mut Session, p: &Value) -> CmdResult { None | Some(Value::Null) => warp::Method::Sample(warp::Resampling::Nearest), Some(v) => v.as_str().and_then(warp::Method::parse).ok_or("resampling is nearest, bilinear, cubic, average or mode")?, }; - let grid = grid_param(s, p, r.crs, |crs| warp::footprint_in(&r, crs).map(|(bounds, pixel)| (bounds, Some(pixel))))?; let path = tif_path(p)?; let out_name = name(p, format!("{} projected", r.name))?; - let out = warp::project(&r, &grid, method, out_name.clone())?; + // Sized and sampled for the same datum grids: refused, before anything is kept, when one + // arrives between. + let (grid, out) = warp::on_unchanged_grids("Project Raster", || { + let grid = grid_param(s, p, r.crs, |crs| warp::projected_footprint(&r, crs).map(|(bounds, pixel)| (bounds, Some(pixel))))?; + let out = warp::project(&r, &grid, method, out_name.clone())?; + Ok((grid, out)) + })?; let used = method.used_on(&r); report_resampled_classes(s, &r, &out, used.id()); let mut info = json!({ diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 39b726b1d5..115d9fbb62 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -2023,7 +2023,10 @@ commands described here aren't on the tab or part of the extension, and run whet "pointsCrs": "EPSG:4326", "crs": 32613, "resampling": "bilinear", "cellSize": 5, "name": "warped", "path": "warped.tif"}`. `pointsCrs` is the coordinate system the points' x and y are in (default EPSG:4326) and `crs` the output's (default `pointsCrs`, so nothing is reprojected unless asked). - Each output cell is taken back through the fit, after reprojection, to the image and sampled there + Between two datums, positions go between `pointsCrs` and `crs` by the transformation PROJ picks + for the pair, and through WGS 84 where the datums have none or it can't place a point; on one + datum, through WGS 84 as before. A warp refuses, asking to run it again, when a datum grid arrives + while it runs. Each output cell is taken back through the fit, after reprojection, to the image and sampled there with `nearest`, `bilinear` (the default) or `cubic`; cells that fall outside the image are no data, or see-through for a colour image, which gains an alpha band for it (a grey byte image becomes grey with alpha; alpha is 0–255 in every pixel type). An image warped into a geographic @@ -2072,7 +2075,10 @@ commands described here aren't on the tab or part of the extension, and run whet "extent": "Study area", "resampling": "average", "path": "ndvi_100m.tif"}`. It has no pane yet: run it from the Script pane, the AI Assistant, the command line or Python. The result is a new layer (`name`, by default the layer's name with "projected"), and with `path` a cloud-optimised - GeoTIFF too. + GeoTIFF too. Between two datums, cells are placed and the grid sized by the transformation PROJ + picks for the pair rather than through WGS 84 (half a metre apart for DHDN and ETRS89), and + through WGS 84 where the datums have none or it can't place a point; on one datum, through WGS 84 + as before. It refuses, asking to run it again, when a datum grid arrives while it runs. - **The grid:** `crs` (by default the layer's), `cellSize` in its units (one number, or `[x, y]`; by default about the layer's pixel there), `origin`, a point a cell corner falls on (`[0, 0]` by default, so cell corners are whole multiples of the cell size and any two rasters