diff --git a/crates/data/src/raster/crs.rs b/crates/data/src/raster/crs.rs index 0479214c34..9a53e37034 100644 --- a/crates/data/src/raster/crs.rs +++ b/crates/data/src/raster/crs.rs @@ -839,7 +839,13 @@ impl Crs { /// semi-major axis isn't the Earth's ([`super::planetary`]). Its longitude/latitude are read as /// they are, on the Earth. pub fn is_planetary(self) -> bool { - self.custom_def().and_then(|d| super::planetary::proj4_axes(&d.proj4)).is_some_and(|(a, _)| super::planetary::off_earth(a)) + self.planetary_semi_major().is_some() + } + + /// The semi-major axis, in metres, of another body's system ([`Crs::is_planetary`]), which + /// tells the bodies apart; `None` for the Earth's. + pub fn planetary_semi_major(self) -> Option { + self.custom_def().and_then(|d| super::planetary::proj4_axes(&d.proj4)).map(|(a, _)| a).filter(|a| super::planetary::off_earth(*a)) } /// A transformer between this system and WGS 84 longitude/latitude, built once a run per diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 2f99f709a9..5d1db0a3ac 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -312,7 +312,7 @@ map.body name? basemap? map.camera lon? lat? scale? map.clipping mode distance? map.colorVision mode -map.convertPosition lon x lat y position? digits? +map.convertPosition lon x lat y crs? position? digits? map.displayType mode map.drawingMode mode map.duplicate map? name? @@ -323,7 +323,7 @@ map.exportOrbit path frames? turn? width? height? dpi? speed? map.extent map.findPlace query provider? url? limit? go? map.goToLink url -map.goToXY lon x lat y position? scale? bearing? pitch? +map.goToXY lon x lat y crs? position? scale? bearing? pitch? map.graticule on? type? crs? onTop? color? map.import path text data map.link diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 9065bf7312..27ce619cfd 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -47,7 +47,7 @@ fn first() -> String { pub fn commands() -> Vec { vec![ C::new("raster.georeference", "Georeference", "Imagery › Alignment", georeference).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"layer": raster, "points"?: [[column, row, lon, lat], …] (two or more; with "transform": [column, row, x, y, on?]), "extent"?: [minLon, minLat, maxLon, maxLat], "transform"?: "similarity"|"affine"|"projective"|"polynomial2"|"polynomial3"|"spline" (fits the points and warps the raster onto a north-up grid covering the warped image; without it the points and extent only shift and scale the grid), "pointsCrs"?: EPSG code or "EPSG:n" of the points' x and y (default 4326), "crs"?: the output's (default pointsCrs), "resampling"?: "nearest"|"bilinear"|"cubic" (default bilinear), "cellSize"?: output units (default about the source pixel's size on the ground), "name"?: new layer for the result (default replaces the layer's raster), "path"?: "*.tif" (also writes the warp as a cloud-optimised GeoTIFF)}"#, + r#"{"layer": raster, "points"?: [[column, row, lon, lat], …] (two or more; with "transform": [column, row, x, y, on?]), "extent"?: [minX, minY, maxX, maxY] in degrees, or in crs when given, | "view" (the map view, in the map's own system on a flat map of the Earth, so the raster fills the view as drawn); not with transform, "transform"?: "similarity"|"affine"|"projective"|"polynomial2"|"polynomial3"|"spline" (fits the points and warps the raster onto a north-up grid covering the warped image; without it the points and extent only shift and scale the grid), "pointsCrs"?: EPSG code or "EPSG:n" of the points' x and y (default 4326; with transform only, not with an extent), "crs"?: the output's (default pointsCrs); with an extent of four numbers, their system and the result's, "resampling"?: "nearest"|"bilinear"|"cubic" (default bilinear), "cellSize"?: output units (default about the source pixel's size on the ground), "name"?: new layer for the result (default replaces the layer's raster), "path"?: "*.tif" (also writes the warp as a cloud-optimised GeoTIFF); resampling, cellSize, name and path with transform only}"#, ), C::new("raster.project", "Project Raster", "Analyze › Raster", project_raster).inputs(project_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"layer": raster, "crs"?: EPSG code or "EPSG:n" of the output (default the layer's), "cellSize"?: number or [x, y] in the output's units (default about the layer's pixel there), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view" (default the layer's footprint), "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "resampling"?: "nearest" (default) | "bilinear" | "cubic" | "average" (the mean of the pixels whose centres fall in a cell) | "mode" (their most frequent value, the least of those tied), "name"?: new layer (default " projected"), "path"?: GeoTIFF to write it to}"#, @@ -250,17 +250,61 @@ fn rebuild(r: &Raster, transform: GeoTransform, crs: Crs, bands: Vec>) fn georeference(s: &mut Session, p: &Value) -> CmdResult { let layer = ps(p, "layer").ok_or("layer is required")?.to_string(); let r = raster(s, p)?; - if p.get("transform").is_some() { + if p.get("transform").is_some_and(|v| !v.is_null()) { + // A transform fits control points: an extent given beside it would be passed over. + if p.get("extent").is_some_and(|e| !e.is_null()) { + return Err("give either a transform with control points or an extent, not both".into()); + } return warp_to_fit(s, p, &layer, &r); } - let gt = if let Some(e) = p.get("extent").and_then(Value::as_array) { - let n: Vec = e.iter().filter_map(Value::as_f64).collect(); - let [x0, y0, x1, y1] = n.as_slice() else { return Err("extent is [minLon, minLat, maxLon, maxLat]".into()) }; + // An extent is placed in crs (or the map's system for "view"): pointsCrs, the control + // points' system, would be passed over. + if p.get("extent").is_some_and(|e| !e.is_null()) && crs_param_read(p, "pointsCrs")?.0.is_some() { + return Err("pointsCrs goes with control points and a transform, not with an extent (one of four numbers takes crs)".into()); + } + let mut crs = Crs::LonLat; + let extent = match p.get("extent") { + None | Some(Value::Null) => None, + Some(Value::String(v)) if v == "view" => { + if crs_param_read(p, "crs")?.0.is_some() { + return Err("crs goes with an extent of four numbers; \"view\" is in the map's own system".into()); + } + let (e, view_crs) = view_in_map_system(s)?; + crs = view_crs; + Some([e.min_x, e.min_y, e.max_x, e.max_y]) + } + Some(Value::Array(e)) => { + // Exactly four numbers: an entry that isn't one is refused, not passed over. + let n: Vec = e.iter().map_while(|v| v.as_f64().filter(|v| v.is_finite())).collect(); + let given = crs_param(s, p, "crs")?; + let ([x0, y0, x1, y1], 4) = (n.as_slice(), e.len()) else { + return Err("extent is [minX, minY, maxX, maxY] (degrees, or in crs)".into()); + }; + crs = given.unwrap_or(Crs::LonLat); + Some([*x0, *y0, *x1, *y1]) + } + Some(_) => return Err("extent is [minX, minY, maxX, maxY] (degrees, or in crs) or \"view\"".into()), + }; + // An extent places the raster on its own: control points beside it would be passed over. + if extent.is_some() && p.get("points").is_some_and(|v| !v.is_null()) { + return Err("give either an extent or control points, not both".into()); + } + // Without a transform the raster is placed where it is, its pixels kept: what only a warp + // uses (a new layer or file for its result, a cell size, a resampling) would be passed over, + // and the layer placed in place of a new one. Refused before anything is copied. + if let Some(key) = ["name", "path", "cellSize", "resampling"].into_iter().find(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + return Err(format!("{key} goes with a transform, which warps the raster into a new grid; without one the layer itself is placed")); + } + let gt = if let Some([x0, y0, x1, y1]) = extent { if !(x0 < x1 && y0 < y1) { - return Err("extent is [minLon, minLat, maxLon, maxLat]".into()); + return Err("extent is [minX, minY, maxX, maxY]: each min below its max".into()); } - GeoTransform { origin_x: *x0, origin_y: *y1, pixel_width: (x1 - x0) / r.width as f64, pixel_height: -(y1 - y0) / r.height as f64 } + GeoTransform { origin_x: x0, origin_y: y1, pixel_width: (x1 - x0) / r.width as f64, pixel_height: -(y1 - y0) / r.height as f64 } } else { + // Without a transform the points are degrees, placed as such. + if crs_param_read(p, "crs")?.0.is_some() || crs_param_read(p, "pointsCrs")?.0.is_some() { + return Err("control points without a transform are longitude and latitude: give transform to use pointsCrs and crs".into()); + } let pts: Vec<[f64; 4]> = p .get("points") .and_then(Value::as_array) @@ -300,7 +344,7 @@ fn georeference(s: &mut Session, p: &Value) -> CmdResult { } GeoTransform { origin_x: bx, origin_y: by, pixel_width: ax, pixel_height: ay } }; - let mut out = rebuild(&r, gt, Crs::LonLat, copied(&r)?)?; + let mut out = rebuild(&r, gt, crs, copied(&r)?)?; // The same pixels, so the same values rounded when the file was read. out.rounded = r.rounded.clone(); out.rounded_some = r.rounded_some.clone(); @@ -309,6 +353,53 @@ fn georeference(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"layer": v["layer"], "extent": [e.min_x, e.min_y, e.max_x, e.max_y]})) } +/// The map view's rectangle and the system it is in, for fitting a raster to it: on a flat map of +/// the Earth, the view in the map's own units and system (Web Mercator's EPSG:3857, the map's EPSG +/// or ESRI code, or the definition of a preset or local view), so the raster fills the view as +/// drawn; on the globe and another body's map, the longitude and latitude box the view shows. +fn view_in_map_system(s: &Session) -> Result<(rustgis_geom::Extent, Crs), String> { + let m = s.map(); + let (w, h) = s.view_size; + // A turned or tilted view isn't a north-up rectangle a raster's grid can fill. + if m.camera.bearing != 0.0 || m.camera.pitch != 0.0 { + return Err("the map is turned or tilted: face north and look straight down (Reset North) to fit a raster to the view".into()); + } + let flat_earth = m.body().is_earth() && !m.projection.is_globe(); + if flat_earth { + let e = m.camera.extent(w, h); + let crs = match &m.projection { + rustgis_map::Projection::Custom(code) => match rustgis_map::projection::Projector::new(code)?.crs() { + Some(c) => c, + None => Crs::parse(&rustgis_map::projection::lookup(code)?.0)?, + }, + _ => Crs::WebMercator, + }; + if [e.min_x, e.min_y, e.max_x, e.max_y].iter().any(|v| !v.is_finite()) || e.is_empty() { + return Err("the map view shows no area to fit to".into()); + } + // A world copy past the antimeridian is the same place within the world's ±180°; a view + // wider than the world has no single place. + if matches!(m.projection, rustgis_map::Projection::WebMercator) { + let world = 2.0 * std::f64::consts::PI * rustgis_geom::MERCATOR_R; + if e.width() > world || e.height() > world { + return Err("the map view is wider than the world: zoom in to fit a raster to it".into()); + } + let shift = ((e.min_x + world / 2.0) / world).floor() * world; + let shift = if e.max_x - shift > world / 2.0 + 1e-6 { shift + world } else { shift }; + if e.min_x - shift < -world / 2.0 - 1e-6 { + return Err("the map view crosses the antimeridian: pan it to one side to fit a raster to it".into()); + } + return Ok((rustgis_geom::Extent::new(e.min_x - shift, e.min_y, e.max_x - shift, e.max_y), crs)); + } + return Ok((e, crs)); + } + let e = super::workspace::view_extent_of(m, (w, h)); + if e.is_empty() { + return Err("the map view shows no part of the map to fit to".into()); + } + Ok((e, Crs::LonLat)) +} + /// A coordinate system given as an EPSG code or any text [`Crs::parse`] reads. fn crs_param(s: &mut Session, p: &Value, key: &str) -> Result, String> { let (crs, warning) = crs_param_read(p, key)?; diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs index 235419f966..cf8057bee1 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -42,10 +42,10 @@ pub fn commands() -> Vec { .params(r#"{"extent": [minLon, minLat, maxLon, maxLat]}"#), C::new("map.goToXY", "By Coordinates…", "Home › Navigate › Locate", go_to_xy).roles(&[]).effects(crate::policy::Effects::NONE) .view() - .params(r#"{"lon" | "x": degrees (-74.006, or text such as 74°0′22″W), "lat" | "y": degrees (40.7128, or text such as 40°42′46″N), "position"?: text in place of lon and lat, as the search box reads it, latitude first (40.7128, -74.006; 18north 583959 4507351; 18TWL8395907350), "scale"?: number, "bearing"?: degrees clockwise from north, "pitch"?: degrees of tilt (0 to 85)}"#), + .params(r#"{"lon" | "x": degrees (-74.006, or text such as 74°0′22″W), or with crs the easting in that system, "lat" | "y": degrees (40.7128, or text such as 40°42′46″N), or with crs the northing, "crs"?: the system x and y are in: "map" (the map's own, as the status bar reads it), an EPSG or ESRI code or other system text (EPSG:2056), or a layer's name (the system it was read in); default degrees, "position"?: text in place of lon and lat, as the search box reads it, latitude first (40.7128, -74.006; 18north 583959 4507351; 18TWL8395907350; 2600000 mE 1200000 mN EPSG:2056, as the map's right-click menu copies it), "scale"?: number, "bearing"?: degrees clockwise from north, "pitch"?: degrees of tilt (0 to 85)}"#), C::new("map.convertPosition", "Convert Position", "Home › Navigate › Locate", convert_position).roles(&[]).effects(crate::policy::Effects::NONE) .view() - .params(r#"{"lon" | "x": degrees (-74.006, or text such as 74°0′22″W), "lat" | "y": degrees (40.7128, or text such as 40°42′46″N), "position"?: text in place of lon and lat, as the search box reads it, latitude first (40.7128, -74.006; 18north 583959 4507351; 18TWL8395907350; Z AC 77146 62481), "digits"?: MGRS digits per axis, 0 (100 km) to 5 (1 m, the default)}"#), + .params(r#"{"lon" | "x": degrees (-74.006, or text such as 74°0′22″W), or with crs the easting in that system, "lat" | "y": degrees (40.7128, or text such as 40°42′46″N), or with crs the northing, "crs"?: the system x and y are in: "map" (the map's own), an EPSG or ESRI code or other system text (EPSG:2056), or a layer's name (the system it was read in); default degrees, "position"?: text in place of lon and lat, as the search box reads it, latitude first (40.7128, -74.006; 18north 583959 4507351; 18TWL8395907350; Z AC 77146 62481; 2600000 mE 1200000 mN EPSG:2056), "digits"?: MGRS digits per axis, 0 (100 km) to 5 (1 m, the default)}"#), C::new("map.goToLink", "Go To Map Link", "Home › Navigate", go_to_link).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"url": a map link ending in #zoom/lat/lon[/bearing[/pitch]] (as MapLibre writes them; also #map=…), or just zoom/lat/lon[/bearing[/pitch]]}"#), @@ -372,6 +372,9 @@ pub(crate) fn read_position(map: &Map, text: &str) -> Result<(Coord, PositionRea && digits.chars().filter(|&c| c == '.').count() <= 1 }; let words: Vec<&str> = text.split(|c: char| c == ',' || c.is_whitespace()).filter(|w| !w.is_empty()).collect(); + if let Some(read) = read_system_position(map, text) { + return read.map(|c| (c, PositionRead::AsWritten)); + } if words.len() == 2 && words.iter().all(plain) { return Err("latitude must be within ±90 and longitude within ±180".into()); } @@ -396,6 +399,305 @@ pub(crate) fn read_position(map: &Map, text: &str) -> Result<(Coord, PositionRea } } +/// A coordinate system a place's coordinates are given in, ready to give the place's longitude and +/// latitude. +pub(crate) enum System { + /// A map's own (a flat projection, as the map draws it). + Flat(rustgis_map::projection::Flat), + /// A system as data names it. + Data(rustgis_data::raster::Transformer), +} + +impl System { + /// The system data names `crs`: Web Mercator as the map draws it, whose unit is the metre + /// (its conversion gives no parameters to read one from), else by its conversion. + fn of_crs(crs: rustgis_data::raster::Crs) -> Result { + if crs == rustgis_data::raster::Crs::WebMercator { + return Ok(System::Flat(rustgis_map::projection::Flat::Mercator)); + } + if let Some(e) = axes_refused(crs) { + return Err(e); + } + crs.transformer().map(System::Data) + } + + /// The unit it counts in as the readout writes it: `m`, `ft` (international) or `ftUS`; `None` + /// for another (degrees, a rarer foot). + pub(crate) fn unit(&self) -> Option<&'static str> { + let to_meter = match self { + System::Flat(rustgis_map::projection::Flat::Mercator) => 1.0, + System::Flat(rustgis_map::projection::Flat::Custom(p)) => p.to_meter(), + System::Data(t) => { + // Degrees aren't a length. + let p = t.params()?; + if p.method == "longlat" || p.method == "latlong" { + return None; + } + p.to_meter + } + }; + [("m", 1.0), ("ft", 0.3048), ("ftUS", 1200.0 / 3937.0)].into_iter().find(|(_, k)| (to_meter - k).abs() < 1e-9).map(|(u, _)| u) + } + + /// Whether it counts in degrees (a geographic system): a map's own never does. + fn is_geographic(&self) -> bool { + matches!(self, System::Data(t) if t.is_geographic()) + } + + /// The longitude and latitude of `at`, a place in this system; `None` where it names none: + /// where the inverse gives no place, or one that doesn't map back to `at` (to a centimetre, or + /// a millionth of the coordinate's size, up to two of its units) because the system's formulas don't reach so far. + pub(crate) fn to_lonlat(&self, at: Coord) -> Option { + if !at.is_finite() { + return None; + } + let (c, back) = match self { + System::Flat(f) => { + let c = f.inverse(at)?; + (c, f.forward_checked(c)) + } + System::Data(t) => { + let c = t.to_lonlat(at)?; + (c, t.from_lonlat(c)) + } + }; + let back = back?; + // To a hundredth of the system's unit (a centimetre in metres), or a millionth of the + // coordinate's size up to two units (2 m, 2 ft): an inverse that + // iterates (Robinson's, to about 1.5e-5°, some 1.6 m) comes back that close; a place past + // the formulas' reach doesn't. + let close = |a: f64, b: f64| (a - b).abs() <= 0.01_f64.max((a.abs() * 1e-6).min(2.0)); + (c.is_finite() && (-180.0..=180.0).contains(&c.x) && (-90.0..=90.0).contains(&c.y) && close(back.x, at.x) && close(back.y, at.y)) + .then_some(c) + } +} + +/// Why a system X and Y can't be given in: they are an easting and a northing, and one counted +/// west or south, or northing first (Lo29's westing and southing), would take them mirrored or +/// swapped, so it is refused, as the readout refuses to write in one. `None` for one counted east, +/// then north, and for degrees (their own branch reads them). +fn axes_refused(crs: rustgis_data::raster::Crs) -> Option { + let axes = crs.axis_directions(); + (!crs.is_geographic() && axes != [(1.0, 0.0), (0.0, 1.0)]).then(|| { + // The direction's larger component names it (`signum` of 0 is 1, so it can't). + let name = |(x, y): (f64, f64)| match (x.abs() >= y.abs(), x > 0.0, y > 0.0) { + (true, true, _) => "an easting", + (true, false, _) => "a westing", + (false, _, true) => "a northing", + (false, _, false) => "a southing", + }; + format!( + "{} counts {}, then {}, not an easting, then a northing: give the place in degrees, or in a system counted east, then north", + crs.label(), + name(axes[0]), + name(axes[1]) + ) + }) +} + +/// The system a layer's coordinates are given in, as Go To XY reads them: a raster's, its +/// pixels' (also one only assumed, as its pixels are placed in it); a layer of features', the one +/// it was read in. `None` for a layer of features that names none (longitude and latitude), and +/// for a raster with no pixels loaded, whose system is unknown ([`system_of`] refuses it, so check +/// that before taking `None` for degrees). Not +/// [`super::project::layer_system`], which leaves assumed systems out as the project's own. +pub fn layer_coordinates_system(l: &rustgis_map::Layer) -> Option { + match &l.raster { + Some(r) => r.data.as_ref().map(|d| d.crs), + None => l.dataset.crs, + } +} + +/// The system `name` gives: `map`, the map's own (the flat projection it draws in, not the globe +/// or another body's map); a layer of the map by that name, the system it was read in (longitude +/// and latitude for one that names none); else a code or other text a map's projection or data's +/// system takes (`EPSG:2056`, `Web Mercator`, `robinson +lon_0=150`, a PROJ string), which names +/// an Earth system, so none on another body's map (as [`read_system_position`] refuses it). +pub(crate) fn system_of(map: &Map, name: &str) -> Result { + let name = name.trim(); + if name.eq_ignore_ascii_case("map") { + if !map.body().is_earth() || map.projection.is_globe() { + return Err("the map has no flat system of its own here (the globe, or another body's map): give degrees".into()); + } + return Ok(System::Flat(map.flat())); + } + // A layer's name first, so a layer named as a system (`Albers`, `2056`) means the layer. + if let Some(l) = map.layer_by_name(name) { + // A raster with no pixels (still being read, or its file couldn't be) names no system: its + // system is unknown, not longitude and latitude. + if l.raster.as_ref().is_some_and(|r| r.data.is_none()) { + return Err(format!("layer '{name}' has no pixels loaded, so its system is unknown: wait until it has opened, or reload it")); + } + // A feature layer that names no system holds longitude and latitude. + let crs = layer_coordinates_system(l).unwrap_or(rustgis_data::raster::Crs::LonLat); + // A projection of the Earth names no place on another body's map, as its code doesn't; + // degrees are that map's own, and another body's projection is its own. + if !map.body().is_earth() && !crs.is_geographic() && !crs.is_planetary() { + return Err(format!("layer '{name}' is in {}, a system of the Earth, and names no place on this map", crs.label())); + } + // Nor does another body's projection on the Earth's map: its inverse gives that body's + // degrees, not the Earth's. (Its degrees are read as they are, as data reads them.) + if map.body().is_earth() && !crs.is_geographic() && crs.is_planetary() { + return Err(format!("layer '{name}' is in {}, a system of another body, and names no place on the Earth's map", crs.label())); + } + // Nor one body's projection on another's: Mars's inverse gives no place on the Moon. + if let Some(body) = other_body(map, crs.planetary_semi_major()).filter(|_| !crs.is_geographic()) { + return Err(format!("layer '{name}' is in {}, a system of {body}, and names no place on this map", crs.label())); + } + return System::of_crs(crs).map_err(|e| format!("layer '{name}': {e}")); + } + if let Some(named) = named_system(name) { + let (system, semi_major) = named?; + let planetary = semi_major.is_some(); + // An Earth system names no place on another body's map; that body's own does. Another + // body's projection names none on the Earth's. + if !map.body().is_earth() && !planetary { + return Err(format!("{name} is a system of the Earth and names no place on this map")); + } + if map.body().is_earth() && planetary && !system.is_geographic() { + return Err(format!("{name} is a system of another body and names no place on the Earth's map")); + } + if let Some(body) = other_body(map, semi_major).filter(|_| !system.is_geographic()) { + return Err(format!("{name} is a system of {body} and names no place on this map")); + } + return Ok(system); + } + Err(format!("'{name}' is neither \"map\", a coordinate system (EPSG:2056), nor a layer's name")) +} + +/// The body, said for a notice, that a system of another body than the Earth's +/// (`semi_major`, [`rustgis_data::raster::Crs::planetary_semi_major`]) is of, when the map is of +/// yet another body: their semi-major axes differ by more than a percent (the nearest pair of +/// bodies a map takes, Titan and Ganymede, differ by 2%). `None` on the Earth's map, for the +/// Earth's systems, and for the map's own body's. +fn other_body(map: &Map, semi_major: Option) -> Option { + let body = map.body(); + let a = semi_major.filter(|_| !body.is_earth())?; + if (a - body.a).abs() <= body.a * 0.01 { + return None; + } + let named = rustgis_geom::body::BODIES.iter().find(|b| !b.is_earth() && (a - b.a).abs() <= b.a * 0.01); + Some(named.map_or_else(|| format!("another body (a radius of {:.0} km)", a / 1000.0), |b| b.name.to_string())) +} + +/// A system named by a map projection's code (as the readout's copy names it) or by text data's +/// systems take, and whether it is another body's than the Earth's (a planetary PROJ string or +/// code); `None` for text that names neither, an error for one named but refused (counted +/// otherwise than east, then north). The globe names no flat system. +fn named_system(name: &str) -> Option), String>> { + // `map` is the map's own ([`system_of`]), not Web Mercator, which `Projection::from_code` + // takes it for. + if name.trim().eq_ignore_ascii_case("map") { + return None; + } + // A code a map projection takes is read as the map draws it, but counted as data names it: + // its axes and its body are the system's. + let crs = rustgis_data::raster::Crs::parse(name).ok(); + match Projection::from_code(name) { + Ok(Projection::Globe) => None, + Ok(p) => Some(match crs.and_then(axes_refused) { + Some(e) => Err(e), + None => Ok((System::Flat(rustgis_map::projection::Flat::of(&p)), crs.and_then(|c| c.planetary_semi_major()))), + }), + Err(_) => { + let c = crs?; + Some(System::of_crs(c).map(|s| (s, c.planetary_semi_major()))) + } + } +} + +/// A place written in a named system, as the map's right-click menu copies one: an easting and a +/// northing, each with an optional unit and axis letter (`2600000 mE`, `1200000 mN`; `ftE`, +/// `ftUSN`, a bare `E`), then the system (`EPSG:2056`, `Web Mercator`). `None` for text not +/// written so; an error for a system that names no flat Earth system here, or a place it names +/// none at. +pub(crate) fn read_system_position(map: &Map, text: &str) -> Option> { + let mut rest = text.trim(); + let mut numbers = [0.0; 2]; + let mut units: Vec<&str> = Vec::new(); + for (i, axis) in ['E', 'N'].into_iter().enumerate() { + numbers[i] = next_word(&mut rest)?.parse::().ok().filter(|v| v.is_finite())?; + // An optional unit and axis letter. + let mut after = rest; + let word = next_word(&mut after).unwrap_or(""); + if let Some(unit) = + ["ftUS", "ft", "m", ""].into_iter().find(|u| word.strip_prefix(u).is_some_and(|l| l.len() == 1 && l.starts_with(axis))) + { + rest = after; + if !unit.is_empty() { + units.push(unit); + } + } + } + let system = rest.trim_start_matches(|c: char| c == ',' || c.is_whitespace()).trim(); + // Only a system's name: a letter, so a third number (a height) isn't taken for one; and no + // WKT, which typed text would otherwise add to the table of systems files read. + if !system.chars().next().is_some_and(char::is_alphabetic) || system.contains('[') { + return None; + } + let (found, semi_major) = if system.eq_ignore_ascii_case("map") { + match system_of(map, "map") { + Ok(s) => (s, None), + Err(e) => return Some(Err(e)), + } + } else { + match named_system(system)? { + Ok(found) => found, + Err(e) => return Some(Err(e)), + } + }; + // An Earth system names no place on another body's map; that body's own does. Another + // body's projection names none on the Earth's. + let planetary = semi_major.is_some(); + if !map.body().is_earth() && !planetary { + return Some(Err(format!("{system} is a system of the Earth and names no place on this map"))); + } + if map.body().is_earth() && planetary && !found.is_geographic() { + return Some(Err(format!("{system} is a system of another body and names no place on the Earth's map"))); + } + if let Some(body) = other_body(map, semi_major).filter(|_| !found.is_geographic()) { + return Some(Err(format!("{system} is a system of {body} and names no place on this map"))); + } + // Degrees are written latitude first, as a position without a system reads them, while this + // form takes an easting first: the order would be a guess, so a system in degrees is refused. + if found.is_geographic() { + return Some(Err(format!( + "{system} counts in degrees: give the position without a system, latitude then longitude (or with N, S, E and W)" + ))); + } + // A unit written must be the system's: feet aren't read as metres. + if let Some(unit) = units.iter().find(|u| Some(**u) != found.unit()) { + let theirs = found.unit().unwrap_or("another unit"); + return Some(Err(format!("{system} counts in {theirs}, not {unit}"))); + } + let at = Coord::new(numbers[0], numbers[1]); + // Two numbers that read as a latitude and a longitude before `map` are degrees typed with the + // map's name, not metres a few steps from the map's origin: said, not taken for metres. + // Two numbers that read as a latitude and a longitude before a projected system (`map`, or + // a code) are degrees typed with its name, not a place a few steps from its origin: said, not + // taken for its units. Only numbers without a unit: `50 mE 30 mN map` says it is metres. + let degrees = at.x.abs() <= 180.0 && at.y.abs() <= 180.0 && (at.x.abs() <= 90.0 || at.y.abs() <= 90.0); + if degrees && units.is_empty() { + // With a unit it counts in, how to say these are its units after all. + let hint = + found.unit().map(|u| format!(", or write its unit after each number ({} {u}E {} {u}N)", at.x, at.y)).unwrap_or_default(); + return Some(Err(format!( + "{} {} {system} reads as degrees, not as a place in {system}: give degrees without a system, latitude then longitude{hint}", + at.x, at.y + ))); + } + Some(found.to_lonlat(at).ok_or_else(|| format!("{} {} names no place in {system}", at.x, at.y))) +} + +/// The next word of `rest` (words are parted by spaces and commas), moving past it. +fn next_word<'a>(rest: &mut &'a str) -> Option<&'a str> { + let t = rest.trim_start_matches(|c: char| c == ',' || c.is_whitespace()); + let end = t.find(|c: char| c == ',' || c.is_whitespace()).unwrap_or(t.len()); + let (w, r) = t.split_at(end); + *rest = r; + (!w.is_empty()).then_some(w) +} + /// What reading a typed position assumed. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum PositionRead { @@ -553,10 +855,18 @@ fn typed_place(map: &Map, p: &Value, moving: bool) -> Result<(Coord, Option return Err("position must be text, such as \"40.7128, -74.006\" or \"18TWL8395907350\"".into()), }; let given = |k: &str| !matches!(p.get(k), None | Some(Value::Null)); + let crs = match p.get("crs") { + None | Some(Value::Null) => None, + Some(Value::String(t)) if !t.trim().is_empty() => Some(t.trim()), + Some(_) => return Err("crs must be \"map\", a coordinate system such as \"EPSG:2056\", or a layer's name".into()), + }; let (lon, lat, notice) = if let Some(text) = position { if ["lon", "lat", "x", "y"].iter().any(|k| given(k)) { return Err("give a position or lon and lat, not both".into()); } + if crs.is_some() { + return Err("crs goes with x and y; a position names its own system (2600000 mE 1200000 mN EPSG:2056)".into()); + } let (c, read) = read_position(map, text)?; let reference = || text.trim().to_string().into(); let said = match read { @@ -577,6 +887,24 @@ fn typed_place(map: &Map, p: &Value, moving: bool) -> Result<(Coord, Option Result { + let key = keys.iter().find(|k| given(k)).ok_or_else(|| format!("{} is required (or a position)", keys[1]))?; + match p.get(*key) { + Some(Value::String(t)) => t.trim().parse::().ok(), + _ => f(p, key), + } + .filter(|v| v.is_finite()) + .ok_or_else(|| format!("{key} must be a number in {crs}")) + }; + // Both names of one axis: one would be passed over. + if ["lon", "x"].iter().all(|k| given(k)) || ["lat", "y"].iter().all(|k| given(k)) { + return Err("give x and y, or lon and lat, not both".into()); + } + let at = Coord::new(axis(["lon", "x"])?, axis(["lat", "y"])?); + let c = system_of(map, crs)?.to_lonlat(at).ok_or_else(|| format!("{} {} names no place in {crs}", at.x, at.y))?; + (c.x, c.y, None) } else { // A number, or text in degrees or degrees, minutes and seconds (`74°0′22″W`). let axis = |keys: [&str; 2], latitude: bool| -> Result { diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index 07c65cb3dd..1f148e8788 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -17,7 +17,7 @@ pub fn commands() -> Vec { vec![ // Not a view command: going to a feature selects it. C::new("map.search", "Search", "Map", search_cmd).inputs(search_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"query": "a latitude and longitude (40.7, -74.0; 40°42'N 74°0'W), a UTM position (33U 412345 5523456; 33 north 412345 5523456) or an MGRS reference (33UVP1234523456; 33U VP 12345 23456), north of 84° N or south of 80° S UPS (north 2077146 1562481) or polar MGRS (Z AC 77146 62481; ZAC7714662481), a layer, a bookmark or a value in a layer's table. Polar text that may be a name or a code (BAG123456) lists table hits first and answers coordinateMayBeText", "limit"?: 1–50, "go"?: true (the first hit) | index}"#, + r#"{"query": "a latitude and longitude (40.7, -74.0; 40°42'N 74°0'W), a UTM position (33U 412345 5523456; 33 north 412345 5523456) or an MGRS reference (33UVP1234523456; 33U VP 12345 23456), north of 84° N or south of 80° S UPS (north 2077146 1562481) or polar MGRS (Z AC 77146 62481; ZAC7714662481), an easting and northing with their system as the map's right-click menu copies them (2600000 mE 1200000 mN EPSG:2056; answers positionError when that names no place), a layer, a bookmark or a value in a layer's table. Polar text that may be a name or a code (BAG123456) lists table hits first and answers coordinateMayBeText", "limit"?: 1–50, "go"?: true (the first hit) | index}"#, ), ] } @@ -136,6 +136,11 @@ pub struct Results { /// that doesn't hold its northing, square letters the zone doesn't use, `S` that may mean /// south); `None` when it isn't written as one, or reads. pub grid_error: Option, + /// Why the query, written as an easting and a northing with their system (as the map's + /// right-click menu copies them), names no place: a unit the system doesn't count in, a + /// system of the Earth on another body's map, a place outside the system. `None` when it isn't + /// written so, or reads. + pub position_error: Option, /// Whether the coordinate among the hits was read from text that may as well be a name or a /// code: a polar (UPS) reference, which starts with a letter (`BAG123456`), unless it is /// plainly a place ([`plainly_polar_place`]). The search box still @@ -167,9 +172,21 @@ fn search_map(map: &rustgis_map::Map, query: &str, limit: usize) -> Results { // place comes after their hits, so a feature named so is found first. let mut plainly_coordinate = false; let mut polar_place = None; - if let Some(c) = parse_lat_lon(&q) { + // Read once: it may name a system whose conversion is made then, and the search box asks as + // you type. + let lat_lon = parse_lat_lon(&q); + let in_system = if lat_lon.is_none() { super::navigate::read_system_position(map, &q) } else { None }; + if let Some(c) = lat_lon { out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); plainly_coordinate = q.chars().any(|c| matches!(c, '.' | '°' | 'º' | '\'' | '′' | '"' | '″') || c.is_alphabetic()); + } else if let Some(Ok(c)) = in_system { + // An easting and a northing in a named system, as the map's right-click menu copies them + // (`2600000 mE 1200000 mN EPSG:2056`). Plainly one when the system is a code; a name + // (`12 34 robinson`) may be a feature's too, so the tables are searched as well. + out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); + plainly_coordinate = q.contains(':'); + } else if let Some(Err(e)) = in_system { + out.position_error = Some(e); } else if map.body().is_earth() { match read_grid_reference(&q) { Ok(c) if letter_led(&q) && !plainly_polar_place(&q) => polar_place = Some(c), @@ -368,10 +385,11 @@ fn search_request(map: &rustgis_map::Map, p: &Value) -> Result<(Results, Option< ), }; if let Some(i) = pick { - r.hits.get(i).ok_or_else(|| match (r.hits.is_empty(), r.grid_error) { - (true, Some(e)) => format!("nothing matches '{query}': as a grid reference, {e}"), - (true, None) => format!("nothing matches '{query}'"), - (false, _) => format!("no hit {i}"), + r.hits.get(i).ok_or_else(|| match (r.hits.is_empty(), r.grid_error, &r.position_error) { + (true, Some(e), _) => format!("nothing matches '{query}': as a grid reference, {e}"), + (true, None, Some(e)) => format!("nothing matches '{query}': as a position, {e}"), + (true, None, None) => format!("nothing matches '{query}'"), + (false, ..) => format!("no hit {i}"), })?; } Ok((r, pick)) @@ -405,6 +423,9 @@ fn search_cmd(s: &mut Session, p: &Value) -> CmdResult { if let Some(e) = r.grid_error { out["gridError"] = json!(e.to_string()); } + if let Some(e) = &r.position_error { + out["positionError"] = json!(e); + } if r.coordinate_may_be_text { // The coordinate hit came from polar grid text that may as well be a name or a code. out["coordinateMayBeText"] = json!(true); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 520cdb06e2..83edddca81 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -49,6 +49,8 @@ mod write_notices; #[path = "tests/held_layers.rs"] mod held_layers; +#[path = "tests/map_system_places.rs"] +mod map_system_places; #[path = "tests/project_crs.rs"] mod project_crs; diff --git a/crates/engine/src/tests/map_system_places.rs b/crates/engine/src/tests/map_system_places.rs new file mode 100644 index 0000000000..a98daebfd9 --- /dev/null +++ b/crates/engine/src/tests/map_system_places.rs @@ -0,0 +1,379 @@ +//! Places in the map's or a layer's own system (#2032 C2f-8): Go To XY and Convert Position take +//! an easting and a northing in a named system (`crs`), and a typed position reads them as the +//! map's right-click menu copies them (`2600000 mE 1200000 mN EPSG:2056`), in the search box +//! too; Georeference's Fit To Map View places the raster in the map's own system. + +use rustgis_geom::Coord; +use serde_json::{Value, json}; + +use super::{out_raster, scan_layer, world}; +use crate::Session; + +/// Bern's old observatory, the Swiss grid's origin: E 2600000, N 1200000 in LV95 (EPSG:2056). +const BERN: Coord = Coord { x: 7.438_632, y: 46.951_082 }; + +fn near_bern(s: &Session) -> bool { + let c = s.map().center_lonlat(); + (c.x - BERN.x).abs() < 2e-3 && (c.y - BERN.y).abs() < 2e-3 +} + +fn away(s: &mut Session) { + s.run("map.goToXY", &json!({"lon": 2.35, "lat": 48.85})).unwrap(); + assert!(!near_bern(s)); +} + +#[test] +fn go_to_xy_takes_an_easting_and_northing_in_a_named_system() { + let mut s = world(); + // On the Web Mercator map, in LV95 by its code, as numbers or text. + for (x, y) in [(json!(2_600_000), json!(1_200_000)), (json!("2600000"), json!(" 1200000 "))] { + away(&mut s); + s.run("map.goToXY", &json!({"x": x, "y": y, "crs": "EPSG:2056"})).unwrap(); + assert!(near_bern(&s), "{:?}", s.map().center_lonlat()); + } + // In the map's own system: Web Mercator's metres here, then LV95's on a map drawn in it. + let merc = rustgis_geom::lonlat_to_merc(BERN); + away(&mut s); + s.run("map.goToXY", &json!({"x": merc.x, "y": merc.y, "crs": "map"})).unwrap(); + assert!(near_bern(&s)); + s.run("map.projection", &json!({"type": "EPSG:2056"})).unwrap(); + away(&mut s); + s.run("map.goToXY", &json!({"x": 2_600_000, "y": 1_200_000, "crs": "MAP"})).unwrap(); + assert!(near_bern(&s)); + // In a layer's system: the sample's Cities are in degrees. + away(&mut s); + s.run("map.goToXY", &json!({"x": BERN.x, "y": BERN.y, "crs": "Cities"})).unwrap(); + assert!(near_bern(&s)); + // A system in degrees in a typed position: refused, as degrees are typed latitude first + // without one, and this form takes the easting first. + for system in ["EPSG:4326", "EPSG:4258"] { + let e = s.run("map.goToXY", &json!({"position": format!("40.7128, -74.006 {system}")})).unwrap_err(); + assert!(e.contains("counts in degrees"), "{system}: {e}"); + } + // Both names of an axis: refused, not one passed over. + let e = s.run("map.goToXY", &json!({"x": 2_600_000, "lon": 7.4, "y": 1_200_000, "crs": "EPSG:2056"})).unwrap_err(); + assert!(e.contains("not both"), "{e}"); + // Convert Position gives the same place. + let v = s.run("map.convertPosition", &json!({"x": 2_600_000, "y": 1_200_000, "crs": "EPSG:2056"})).unwrap(); + assert!((v["lon"].as_f64().unwrap() - BERN.x).abs() < 2e-3 && (v["lat"].as_f64().unwrap() - BERN.y).abs() < 2e-3, "{v}"); +} + +#[test] +fn a_position_with_its_system_reads_as_the_menu_copies_it() { + let mut s = world(); + for text in + ["2600000 mE 1200000 mN EPSG:2056", "2600000 1200000 EPSG:2056", "2600000, 1200000, epsg:2056", "2600000 E 1200000 N EPSG:2056"] + { + away(&mut s); + s.run("map.goToXY", &json!({"position": text})).unwrap_or_else(|e| panic!("{text}: {e}")); + assert!(near_bern(&s), "{text}: {:?}", s.map().center_lonlat()); + } + // Web Mercator by the name the readout copies, and in feet. + let merc = rustgis_geom::lonlat_to_merc(BERN); + away(&mut s); + s.run("map.goToXY", &json!({"position": format!("{:.2} mE {:.2} mN Web Mercator", merc.x, merc.y)})).unwrap(); + assert!(near_bern(&s)); + let v = s.run("map.convertPosition", &json!({"position": "2300000 ftUSE 10070000 ftUSN EPSG:2277"})).unwrap(); + let (lon, lat) = (v["lon"].as_f64().unwrap_or(0.0), v["lat"].as_f64().unwrap_or(0.0)); + assert!((-100.5..-95.0).contains(&lon) && (29.5..31.5).contains(&lat), "Texas Central, near Austin: {v}"); + // The search box finds it. + let hits = s.run("map.search", &json!({"query": "2600000 mE 1200000 mN EPSG:2056"})).unwrap(); + let found = hits.to_string(); + assert!(found.contains("7.43") && found.contains("46.95"), "{found}"); +} + +#[test] +fn places_in_a_system_are_refused_with_a_reason() { + let mut s = world(); + let err = |s: &mut Session, p: Value| s.run("map.goToXY", &p).expect_err(&p.to_string()); + assert!(err(&mut s, json!({"x": 1, "y": 2, "crs": "nowhere"})).contains("neither")); + assert!(err(&mut s, json!({"x": "a", "y": 2, "crs": "EPSG:2056"})).contains("number")); + assert!(err(&mut s, json!({"position": "2600000 1200000 EPSG:2056", "crs": "EPSG:2056"})).contains("position")); + assert!(err(&mut s, json!({"x": 1, "y": 2, "crs": 5})).contains("crs")); + // Far beyond the system's reach, no place. + assert!(err(&mut s, json!({"x": 1e9, "y": 1e9, "crs": "EPSG:2056"})).contains("no place")); + // The globe has no flat system of its own. + s.run("map.projection", &json!({"type": "globe"})).unwrap(); + assert!(err(&mut s, json!({"x": 1, "y": 2, "crs": "map"})).contains("globe")); + // A unit the system doesn't count in names no place, and the search says why. + let v = s.run("map.search", &json!({"query": "2600000 ftE 1200000 ftN EPSG:2056"})).unwrap(); + assert_eq!(v["hits"], json!([]), "{v}"); + assert!(v["positionError"].as_str().is_some_and(|e| e.contains("counts in m, not ft")), "{v}"); + let e = s.run("map.search", &json!({"query": "2600000 ftE 1200000 ftN EPSG:2056", "go": true})).unwrap_err(); + assert!(e.contains("as a position") && e.contains("not ft"), "{e}"); + assert!(s.run("map.search", &json!({"query": "2600000 mE 1200000 mN EPSG:2056"})).unwrap().get("positionError").is_none()); +} + +/// On another body's map, a code names an Earth system: refused, not read as that body's +/// degrees, by `crs` as by a typed position. +#[test] +fn an_earth_system_names_no_place_on_another_body() { + let mut s = world(); + let err = |s: &mut Session, p: Value| s.run("map.goToXY", &p).expect_err(&p.to_string()); + s.run("map.body", &json!({"name": "mars", "basemap": false})).unwrap(); + for p in [json!({"x": 2_600_000, "y": 1_200_000, "crs": "EPSG:2056"}), json!({"position": "2600000 1200000 EPSG:2056"})] { + assert!(err(&mut s, p.clone()).contains("system of the Earth"), "{p}"); + let e = s.run("map.convertPosition", &p).expect_err(&p.to_string()); + assert!(e.contains("system of the Earth"), "{p}: {e}"); + } + // Nor does a layer held in a projection of the Earth, named as the system. + let mut swiss = rustgis_data::Dataset::new("Swiss", rustgis_data::GeometryType::Point, vec![]); + swiss.crs = Some(rustgis_data::raster::Crs::Epsg(2056)); + s.map_mut().add_dataset(swiss); + let p = json!({"x": 2_600_000, "y": 1_200_000, "crs": "Swiss"}); + assert!(err(&mut s, p.clone()).contains("a system of the Earth"), "{p}"); + let e = s.run("map.convertPosition", &p).expect_err(&p.to_string()); + assert!(e.contains("a system of the Earth"), "{e}"); + // A projection of Mars, given by its PROJ text as `crs`, is that map's own: it names a place + // there. (A typed position names its system by a name, which starts with a letter.) + let p = json!({"x": 100_000, "y": 200_000, "crs": "+proj=eqc +a=3396190 +b=3396190 +units=m +no_defs"}); + let v = s.run("map.convertPosition", &p).unwrap_or_else(|e| panic!("{p}: {e}")); + // 100 km east along Mars's equator: 100000 / 3396190 rad. + let lon = v["lon"].as_f64().unwrap(); + assert!((lon - (100_000.0f64 / 3_396_190.0).to_degrees()).abs() < 1e-6, "{v}"); +} + +/// Degrees typed before a projected system's code are refused as before `map`; with units written +/// they are its units. +#[test] +fn degrees_typed_with_a_systems_code_are_refused() { + let mut s = world(); + let e = s.run("map.goToXY", &json!({"position": "46.95 7.44 EPSG:2056"})).unwrap_err(); + assert!(e.contains("reads as degrees") && e.contains("46.95 mE"), "{e}"); + let v = s.run("map.search", &json!({"query": "46.95 7.44 EPSG:2056"})).unwrap(); + assert!(v["positionError"].as_str().is_some_and(|e| e.contains("reads as degrees")), "{v}"); +} + +/// Another body's projection names no place on the Earth's map: its inverse gives that body's +/// degrees, not the Earth's. +#[test] +fn another_bodys_projection_names_no_place_on_the_earth() { + let mut s = world(); + let p = json!({"x": 100_000, "y": 200_000, "crs": "+proj=eqc +a=3396190 +b=3396190 +units=m +no_defs"}); + let e = s.run("map.goToXY", &p).unwrap_err(); + assert!(e.contains("a system of another body"), "{e}"); + let mut mars = rustgis_data::Dataset::new("Mars plan", rustgis_data::GeometryType::Point, vec![]); + mars.crs = Some(rustgis_data::raster::Crs::parse("+proj=eqc +a=3396190 +b=3396190 +units=m +no_defs").unwrap()); + s.map_mut().add_dataset(mars); + let e = s.run("map.convertPosition", &json!({"x": 100_000, "y": 200_000, "crs": "Mars plan"})).unwrap_err(); + assert!(e.contains("a system of another body"), "{e}"); +} + +/// A raster whose pixels couldn't be read names no system: refused with the reason, not taken +/// for longitude and latitude. +#[test] +fn a_raster_with_no_pixels_names_no_system() { + let mut s = world(); + scan_layer(&mut s, "relief"); + let id = s.map().layer_by_name("relief").unwrap().id; + s.map_mut().layer_mut(id).unwrap().raster.as_mut().unwrap().data = None; + let e = s.run("map.goToXY", &json!({"x": 40, "y": 30, "crs": "relief"})).unwrap_err(); + assert!(e.contains("has no pixels loaded"), "{e}"); +} + +/// One body's projection names no place on another body's map either: Mars's inverse gives no +/// place on the Moon. The Moon's own projection does. +#[test] +fn a_projection_of_mars_names_no_place_on_the_moon() { + let mut s = world(); + s.run("map.body", &json!({"name": "moon", "basemap": false})).unwrap(); + let p = json!({"x": 100_000, "y": 200_000, "crs": "+proj=eqc +a=3396190 +b=3396190 +units=m +no_defs"}); + let e = s.run("map.goToXY", &p).unwrap_err(); + assert!(e.contains("a system of Mars"), "{e}"); + let mut mars = rustgis_data::Dataset::new("Mars plan", rustgis_data::GeometryType::Point, vec![]); + mars.crs = Some(rustgis_data::raster::Crs::parse("+proj=eqc +a=3396190 +b=3396190 +units=m +no_defs").unwrap()); + s.map_mut().add_dataset(mars); + let e = s.run("map.convertPosition", &json!({"x": 100_000, "y": 200_000, "crs": "Mars plan"})).unwrap_err(); + assert!(e.contains("a system of Mars"), "{e}"); + let moon = json!({"x": 100_000, "y": 200_000, "crs": "+proj=eqc +a=1737400 +b=1737400 +units=m +no_defs"}); + let v = s.run("map.convertPosition", &moon).unwrap_or_else(|e| panic!("{e}")); + assert!((v["lon"].as_f64().unwrap() - (100_000.0f64 / 1_737_400.0).to_degrees()).abs() < 1e-6, "{v}"); +} + +/// Degrees typed before `map` (latitude first, as without a system) are refused with the reason, +/// not read as metres a few steps from the map's origin; in the search box too. +#[test] +fn degrees_typed_with_the_maps_name_are_refused() { + let mut s = world(); + for text in ["40.7, -74.0 map", "-74.0 40.7 map"] { + let e = s.run("map.goToXY", &json!({"position": text})).unwrap_err(); + assert!(e.contains("reads as degrees"), "{text}: {e}"); + let v = s.run("map.search", &json!({"query": text})).unwrap(); + assert!(v["positionError"].as_str().is_some_and(|e| e.contains("reads as degrees")), "{text}: {v}"); + } + // Metres in the map's own system still go. + let merc = rustgis_geom::lonlat_to_merc(BERN); + away(&mut s); + s.run("map.goToXY", &json!({"position": format!("{:.0} {:.0} map", merc.x, merc.y)})).unwrap(); + assert!(near_bern(&s)); + // Small numbers with a unit written say they are metres: taken as such, by the map's origin. + s.run("map.goToXY", &json!({"position": "50 mE 30 mN map"})).unwrap(); + let c = s.map().center_lonlat(); + assert!(c.x.abs() < 1e-3 && c.y.abs() < 1e-3, "{c:?}"); +} + +/// A position in Web Mercator by a name only data's systems take is in metres, as Web Mercator +/// is: a unit of metres written with it is its own. +#[test] +fn web_mercator_by_any_name_counts_in_metres() { + let mut s = world(); + let merc = rustgis_geom::lonlat_to_merc(BERN); + // Names a map projection doesn't take, so they come by data's systems. + for name in ["EPSG:102100", "EPSG:102113"] { + assert_eq!(rustgis_data::raster::Crs::parse(name).ok(), Some(rustgis_data::raster::Crs::WebMercator), "{name}"); + assert!(rustgis_map::Projection::from_code(name).is_err(), "{name}"); + away(&mut s); + let text = format!("{:.2} mE {:.2} mN {name}", merc.x, merc.y); + s.run("map.goToXY", &json!({"position": text})).unwrap_or_else(|e| panic!("{text}: {e}")); + assert!(near_bern(&s), "{name}"); + } +} + +/// Fit To Map View on a projected map places the raster in the map's own system over the view's +/// rectangle, not over a box of degrees. +#[test] +fn fit_to_view_places_the_raster_in_the_maps_system() { + let mut s = world(); + s.view_size = (800.0, 600.0); + scan_layer(&mut s, "scan"); + s.run("map.projection", &json!({"type": "EPSG:2056"})).unwrap(); + s.run("map.goToXY", &json!({"lon": BERN.x, "lat": BERN.y, "scale": 50_000})).unwrap(); + let v = s.run("raster.georeference", &json!({"layer": "scan", "extent": "view"})).unwrap(); + let r = out_raster(&s, &v); + assert_eq!(r.crs, rustgis_data::raster::Crs::Epsg(2056)); + let view = s.map().camera.extent(800.0, 600.0); + let t = r.transform; + let (right, bottom) = (t.origin_x + t.pixel_width * f64::from(r.width), t.origin_y + t.pixel_height * f64::from(r.height)); + for (a, b) in [(t.origin_x, view.min_x), (bottom, view.min_y), (right, view.max_x), (t.origin_y, view.max_y)] { + assert!((a - b).abs() < 1e-6, "{t:?} against the view {view:?}"); + } + // On Web Mercator, in its metres. + s.run("map.projection", &json!({"type": "mercator"})).unwrap(); + let v = s.run("raster.georeference", &json!({"layer": "scan", "extent": "view"})).unwrap(); + assert_eq!(out_raster(&s, &v).crs, rustgis_data::raster::Crs::WebMercator); + // A world copy past the antimeridian is fitted where it is within the world. + s.run("map.goToXY", &json!({"lon": 170.0, "lat": 0.0, "scale": 50_000})).unwrap(); + let world = 2.0 * std::f64::consts::PI * rustgis_geom::MERCATOR_R; + s.map_mut().camera.center.x += world; + let v = s.run("raster.georeference", &json!({"layer": "scan", "extent": "view"})).unwrap(); + let t = out_raster(&s, &v).transform; + assert!((t.origin_x - (s.map().camera.center.x - world)).abs() < 50_000.0, "{t:?}"); + // A turned or tilted view, or control points with a system but no transform, are refused. + s.run("map.setBearing", &json!({"bearing": 30})).unwrap(); + let e = s.run("raster.georeference", &json!({"layer": "scan", "extent": "view"})).unwrap_err(); + assert!(e.contains("turned or tilted"), "{e}"); + let e = s + .run("raster.georeference", &json!({"layer": "scan", "points": [[0, 0, 7, 47], [10, 10, 8, 46]], "crs": "EPSG:2056"})) + .unwrap_err(); + assert!(e.contains("transform"), "{e}"); + // Four numbers in a named system; degrees without one. + let v = s + .run("raster.georeference", &json!({"layer": "scan", "extent": [2_599_000, 1_199_000, 2_601_000, 1_201_000], "crs": "EPSG:2056"})) + .unwrap(); + assert_eq!(out_raster(&s, &v).crs, rustgis_data::raster::Crs::Epsg(2056)); + let v = s.run("raster.georeference", &json!({"layer": "scan", "extent": [7.0, 46.0, 8.0, 47.0]})).unwrap(); + assert_eq!(out_raster(&s, &v).crs, rustgis_data::raster::Crs::LonLat); + assert!(s.run("raster.georeference", &json!({"layer": "scan", "extent": "view", "crs": "EPSG:2056"})).is_err()); + // What an extent doesn't use is refused, not passed over: control points' system, and an + // extent beside a transform. + let e = + s.run("raster.georeference", &json!({"layer": "scan", "extent": [7.0, 46.0, 8.0, 47.0], "pointsCrs": "EPSG:2056"})).unwrap_err(); + assert!(e.contains("pointsCrs goes with control points"), "{e}"); + let e = s + .run( + "raster.georeference", + &json!({"layer": "scan", "extent": [7.0, 46.0, 8.0, 47.0], "transform": "affine", "points": [[0, 0, 7.0, 47.0], [10, 0, 8.0, 47.0], [0, 10, 7.0, 46.0]]}), + ) + .unwrap_err(); + assert!(e.contains("not both"), "{e}"); + // Control points beside an extent, with no transform: refused, the layer as it was. + let before = s.map().layer_by_name("scan").unwrap().raster.as_ref().unwrap().data.as_ref().unwrap().transform; + let e = s + .run( + "raster.georeference", + &json!({"layer": "scan", "extent": [7.0, 46.0, 8.0, 47.0], "points": [[0, 0, 7.0, 47.0], [10, 10, 8.0, 46.0]]}), + ) + .unwrap_err(); + assert!(e.contains("an extent or control points, not both"), "{e}"); + // What only a warp uses is refused without a transform, the layer placed nowhere new. + for (key, value) in + [("name", json!("aligned")), ("path", json!("aligned.tif")), ("cellSize", json!(0.01)), ("resampling", json!("cubic"))] + { + let mut p = json!({"layer": "scan", "extent": [7.0, 46.0, 8.0, 47.0]}); + p[key] = value; + let e = s.run("raster.georeference", &p).unwrap_err(); + assert!(e.contains(&format!("{key} goes with a transform")), "{key}: {e}"); + } + assert!(s.map().layer_by_name("aligned").is_none()); + assert_eq!(s.map().layer_by_name("scan").unwrap().raster.as_ref().unwrap().data.as_ref().unwrap().transform, before); + // An entry that isn't a number is refused, not passed over, and nothing is placed. + let before = s.map().layers.len(); + for extent in [json!([0, 0, null, 10, 10]), json!([7, 46, 8, 47, "x"]), json!([7, 46, 8, "47"])] { + let e = s.run("raster.georeference", &json!({"layer": "scan", "extent": extent})).unwrap_err(); + assert!(e.contains("[minX, minY, maxX, maxY]"), "{extent}: {e}"); + } + assert_eq!(s.map().layers.len(), before); +} + +/// A layer named as a system means the layer; `map` after a position is the map's own system; a +/// unit that isn't the system's is refused rather than read as metres. +#[test] +fn names_and_units_mean_what_they_say() { + let mut s = world(); + // The sample's Cities, in degrees, renamed as LV95's bare code. + s.run("layer.rename", &json!({"layer": "Cities", "name": "2056"})).unwrap(); + away(&mut s); + s.run("map.goToXY", &json!({"x": BERN.x, "y": BERN.y, "crs": "2056"})).unwrap(); + assert!(near_bern(&s), "the layer, not EPSG:2056: {:?}", s.map().center_lonlat()); + s.run("map.projection", &json!({"type": "EPSG:2056"})).unwrap(); + away(&mut s); + s.run("map.goToXY", &json!({"position": "2600000 mE 1200000 mN map"})).unwrap(); + assert!(near_bern(&s), "{:?}", s.map().center_lonlat()); + let e = s.run("map.goToXY", &json!({"position": "2600000 ftE 1200000 ftN EPSG:2056"})).unwrap_err(); + assert!(e.contains("counts in m, not ft"), "{e}"); +} + +/// A raster layer's system is its pixels' (a raster names none on its features): named in `crs`, +/// an LV95 raster takes an easting and a northing in LV95. +#[test] +fn a_raster_layers_system_is_its_pixels() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; + let mut s = world(); + let gt = GeoTransform { origin_x: 2_599_000.0, origin_y: 1_201_000.0, pixel_width: 100.0, pixel_height: -100.0 }; + let r = Raster::new("relief", 20, 20, vec![vec![1.0; 400]], gt, Crs::Epsg(2056), None, ColorHint::Gray, "Float32").unwrap(); + let bytes = geotiff::write(&r, 0).unwrap(); + crate::cmd::raster::add_raster(&mut s, "relief", rustgis_map::RasterLayer::from_bytes(r, "relief.tif".to_string(), bytes)).unwrap(); + away(&mut s); + s.run("map.goToXY", &json!({"x": 2_600_000, "y": 1_200_000, "crs": "relief"})).unwrap(); + assert!(near_bern(&s)); +} + +/// X and Y are an easting and a northing: a system counted west, then south (as South Africa's +/// Lo systems are) would take them mirrored, so it is refused with the reason. +#[test] +fn a_system_counted_other_than_east_then_north_is_refused() { + let mut s = world(); + let lo29 = "+proj=tmerc +lat_0=0 +lon_0=29 +k=1 +x_0=0 +y_0=0 +axis=wsu +ellps=WGS84 +units=m +no_defs"; + let e = s.run("map.goToXY", &json!({"x": 10_000, "y": 3_000_000, "crs": lo29})).unwrap_err(); + assert!(e.contains("counts a westing, then a southing"), "{e}"); + // By its EPSG code too (a code a map projection also takes), and as a typed position. + let e = s.run("map.goToXY", &json!({"x": 10_000, "y": 3_000_000, "crs": "EPSG:22275"})).unwrap_err(); + assert!(e.contains("counts a westing, then a southing"), "{e}"); + let e = s.run("map.goToXY", &json!({"position": "10000 3000000 EPSG:22275"})).unwrap_err(); + assert!(e.contains("counts a westing, then a southing"), "{e}"); + // A system whose EPSG definition names the northing first (LAEA Europe) still takes an + // easting, then a northing, as RustGIS holds and writes its coordinates. + s.run("map.goToXY", &json!({"position": "4200000 2600000 EPSG:3035"})).unwrap(); +} + +/// A place in Robinson, whose inverse iterates (to about 1.5e-5°, some 1.6 m), is taken: its +/// round trip comes back within a millionth of the coordinate's size. +#[test] +fn a_place_in_robinson_is_taken() { + let mut s = world(); + let robinson = rustgis_data::raster::Crs::parse("ESRI:54030").unwrap(); + let at = robinson.transformer().unwrap().from_lonlat(rustgis_geom::Coord::new(20.0, 30.0)).unwrap(); + let v = s.run("map.convertPosition", &json!({"x": at.x, "y": at.y, "crs": "ESRI:54030"})).unwrap(); + let (lon, lat) = (v["lon"].as_f64().unwrap(), v["lat"].as_f64().unwrap()); + assert!((lon - 20.0).abs() < 1e-4 && (lat - 30.0).abs() < 1e-4, "{v}"); +} diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 4d21922cc7..9e6c27325f 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -1189,17 +1189,9 @@ pub fn workflows(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { .small() .weak(), ); + // In the map's own system on a flat map, so the raster fills the view as drawn. if ui.button(tl!("Fit To Map View")).clicked() { - let m = app.session.map(); - let (w, h) = app.session.view_size; - let e = m.camera.extent(w, h); - let (a, b) = ( - m.to_lonlat(rustgis_engine::geom::Coord::new(e.min_x, e.min_y)), - m.to_lonlat(rustgis_engine::geom::Coord::new(e.max_x, e.max_y)), - ); - if let (Some(a), Some(b)) = (a, b) { - run(app, "raster.georeference", json!({"layer": app.workflow.layer, "extent": [a.x, a.y, b.x, b.y]})); - } + run(app, "raster.georeference", json!({"layer": app.workflow.layer, "extent": "view"})); } ui.add( egui::TextEdit::multiline(&mut app.workflow.text) diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 9e6a7c985b..5e60137f42 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -472,9 +472,17 @@ pub fn status_bar(app: &mut RustGisApp, ui: &mut Ui) { // dimmed then, to tell it from a live one. let kept = app.map.kept_pointer_lonlat(app.session.map().instance_id(), app.session.opened); let live = app.map.pointer_lonlat.is_some(); + // Layer coordinates name their system, the active layer's, which the map's beside + // them isn't. + let system = format.system(app.session.map(), app.session.active_layer); + let mut text = format.readout(kept, earth, system.as_ref()); + // Named only beside a position: with none yet, the dash stands alone. + if let Some(s) = system.as_ref().filter(|_| format == crate::CoordReadout::Layer && kept.is_some()) { + text = format!("{text} {}", s.name()); + } let resp = ui.add( egui::Label::new( - egui::RichText::new(format.readout(kept, earth, crate::coordreadout::MapSystem::of(app.session.map()).as_ref())).monospace().size(11.5).color(if live { t.text_dim } else { t.text_disabled }), + egui::RichText::new(text).monospace().size(11.5).color(if live { t.text_dim } else { t.text_disabled }), ) .sense(Sense::click()), ); diff --git a/crates/ui-egui/src/coordreadout.rs b/crates/ui-egui/src/coordreadout.rs index 0dddc97333..b5ed92b0b1 100644 --- a/crates/ui-egui/src/coordreadout.rs +++ b/crates/ui-egui/src/coordreadout.rs @@ -1,5 +1,6 @@ //! How the pointer's coordinates read in the status bar and in the map's right-click menu: in the -//! map's own coordinate system, decimal degrees, degrees-minutes-seconds, UTM or MGRS. A click on +//! map's own coordinate system, decimal degrees, degrees-minutes-seconds, UTM, MGRS or the active +//! layer's coordinate system. A click on //! the status bar readout steps through them in that order (`ui.coordinateFormat`), and the choice //! is remembered between sessions as the `coordinate_format` preference. @@ -18,6 +19,10 @@ pub enum CoordReadout { /// (on the globe and another body's map, decimal degrees; see [`MapSystem`]). #[default] Map, + /// `2600000 mE 1200000 mN`: the active layer's coordinates, in the projected system it was + /// read in (decimal degrees for a layer in degrees, or with no layer active; see + /// [`MapSystem::of_layer`]). + Layer, /// `12.3456° E 45.6789° N` Decimal, /// `12°20′44.2″ E 45°40′44.0″ N` @@ -30,12 +35,14 @@ pub enum CoordReadout { impl CoordReadout { /// Every format, in the order a click steps through them. - pub const ALL: [CoordReadout; 5] = [CoordReadout::Map, CoordReadout::Decimal, CoordReadout::Dms, CoordReadout::Utm, CoordReadout::Mgrs]; + pub const ALL: [CoordReadout; 6] = + [CoordReadout::Map, CoordReadout::Decimal, CoordReadout::Dms, CoordReadout::Utm, CoordReadout::Mgrs, CoordReadout::Layer]; /// The name commands and the preference use (never translated). pub fn code(self) -> &'static str { match self { CoordReadout::Map => "map", + CoordReadout::Layer => "layer", CoordReadout::Decimal => "decimal", CoordReadout::Dms => "dms", CoordReadout::Utm => "utm", @@ -49,14 +56,15 @@ impl CoordReadout { Self::ALL.into_iter().find(|f| f.code().eq_ignore_ascii_case(code)) } - /// The format after this one: map → decimal → DMS → UTM → MGRS → map. + /// The format after this one: map → decimal → DMS → UTM → MGRS → layer → map. pub fn next(self) -> Self { match self { CoordReadout::Map => CoordReadout::Decimal, + CoordReadout::Layer => CoordReadout::Map, CoordReadout::Decimal => CoordReadout::Dms, CoordReadout::Dms => CoordReadout::Utm, CoordReadout::Utm => CoordReadout::Mgrs, - CoordReadout::Mgrs => CoordReadout::Map, + CoordReadout::Mgrs => CoordReadout::Layer, } } @@ -64,6 +72,7 @@ impl CoordReadout { pub fn label(self) -> &'static str { match self { CoordReadout::Map => tl_raw!("map coordinates"), + CoordReadout::Layer => tl_raw!("layer coordinates"), CoordReadout::Decimal => tl_raw!("decimal degrees"), CoordReadout::Dms => tl_raw!("degrees, minutes and seconds"), CoordReadout::Utm => tl_raw!("UTM"), @@ -76,16 +85,27 @@ impl CoordReadout { matches!(self, CoordReadout::Utm | CoordReadout::Mgrs) } + /// The system the map and layer formats read in: the map's own ([`MapSystem::of`]) or the + /// active layer's ([`MapSystem::of_layer`]); `None` for the other formats. + pub fn system(self, map: &rustgis_engine::map::Map, active: Option) -> Option { + match self { + CoordReadout::Map => MapSystem::of(map), + CoordReadout::Layer => MapSystem::of_layer(map, active), + _ => None, + } + } + /// The place in this format; for UTM and MGRS, UPS in the polar areas (north of 84° N and - /// south of 80° S) and `None` on another body's map (`earth` false); in the map's coordinates - /// `None` where its projection doesn't reach, and decimal degrees without a flat Earth map - /// (`map` `None`); and for every format `None` for a non-finite place. + /// south of 80° S) and `None` on another body's map (`earth` false); in the map's or the + /// layer's coordinates (`map`, [`CoordReadout::system`]) `None` where the system doesn't + /// reach, and decimal degrees without one (`map` `None`); and for every format `None` for a + /// non-finite place. pub fn format(self, c: Coord, earth: bool, map: Option<&MapSystem>) -> Option { if !c.is_finite() || (self.earth_only() && !earth) { return None; } match self { - CoordReadout::Map => match map { + CoordReadout::Map | CoordReadout::Layer => match map { Some(m) => m.format(c), None => Some(geom::format_lonlat(c)), }, @@ -112,7 +132,7 @@ impl CoordReadout { /// and MGRS read near the poles. pub fn hover(self) -> String { i18n::fmt( - "Coordinates in {format}. Click to switch: map coordinates, decimal degrees, DMS, UTM, MGRS. Map coordinates are in the map's coordinate system, named beside them, and in degrees on the globe and on another body's map. UTM and MGRS are grids of the Earth, read in UPS north of 84° N and south of 80° S.", + "Coordinates in {format}. Click to switch: map coordinates, decimal degrees, DMS, UTM, MGRS, layer coordinates. Map coordinates are in the map's coordinate system, named beside them, and in degrees on the globe and on another body's map. Layer coordinates are in the projected coordinate system the active layer was read in, named beside them, and in degrees for a layer in degrees, with no layer active and on another body's map. UTM and MGRS are grids of the Earth, read in UPS north of 84° N and south of 80° S.", &[("format", self.label())], ) } @@ -128,10 +148,33 @@ fn system_name(p: &rustgis_engine::map::Projection) -> String { } } -/// A flat map of the Earth's own coordinates, as the map format reads them: its projection and -/// how many of its units a screen pixel spans, which sets the decimals shown. +/// The conversion of a layer's system, kept from the last frame that asked for the same system: +/// a system read from a file without a code (WKT) is otherwise built again each frame. +fn layer_conversion(crs: rustgis_engine::data::raster::Crs) -> Option { + static LAST: std::sync::Mutex> = + std::sync::Mutex::new(None); + let mut last = LAST.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(t) = last.as_ref().filter(|(kept, _)| *kept == crs).map(|(_, t)| t.clone()) { + return Some(t); + } + let t = crs.transformer().ok()?; + *last = Some((crs, t.clone())); + Some(t) +} + +/// How a system gives a place's coordinates from its longitude and latitude. +enum Plane { + /// A map's flat projection, as the map draws it (Web Mercator's too, for a layer in it). + Flat(Flat), + /// A layer's projected system, by its conversion, with the metres in one of its units. + Data(rustgis_engine::data::raster::Transformer, f64), +} + +/// A flat system of the Earth's own coordinates, the map's or a layer's, as the map and layer +/// formats read them: its projection and how many of its units a screen pixel spans, which sets +/// the decimals shown. pub struct MapSystem { - flat: Flat, + plane: Plane, res: f64, /// The system's name, never translated: see [`MapSystem::name`]. name: String, @@ -142,15 +185,48 @@ impl MapSystem { /// is computed on the Earth's figure and so gives no coordinates of its own body. pub fn of(map: &rustgis_engine::map::Map) -> Option { (map.body().is_earth() && !map.projection.is_globe()).then(|| MapSystem { - flat: Flat::of(&map.projection), + plane: Plane::Flat(Flat::of(&map.projection)), res: map.camera.res, name: system_name(&map.projection), }) } + /// The projected system the layer `active` was read in (a feature layer's, a raster's): `None` + /// with no such layer, for one in degrees (longitude and latitude in any datum, which read as + /// decimal degrees), on another body's map, for a system whose conversion can't be made or + /// gives no unit, and for one whose axes aren't east, then north (a westing and southing, + /// `+axis=wsu`, or a northing first), which an easting and northing would mislabel. A pixel + /// spans the map's ground resolution, in the system's units. The conversion is kept for the + /// next frame while the layer's system stays the same. + pub fn of_layer(map: &rustgis_engine::map::Map, active: Option) -> Option { + use rustgis_engine::data::raster::Crs; + if !map.body().is_earth() { + return None; + } + let l = map.layer(active?)?; + // A raster's system is its pixels', as Go To XY reads it. + let crs = rustgis_engine::cmd::navigate::layer_coordinates_system(l)?; + if crs.is_geographic() || crs.is_geocentric() || crs.is_planetary() { + return None; + } + let ground = map.ground_res(); + let (plane, to_meter) = if crs == Crs::WebMercator { + (Plane::Flat(Flat::Mercator), 1.0) + } else { + let t = layer_conversion(crs)?; + if t.axis_directions() != [(1.0, 0.0), (0.0, 1.0)] { + return None; + } + let to_meter = t.params().map(|p| p.to_meter).filter(|m| m.is_finite() && *m > 0.0)?; + (Plane::Data(t, to_meter), to_meter) + }; + let name = if crs == Crs::WebMercator { "Web Mercator".to_string() } else { crs.label() }; + Some(MapSystem { plane, res: ground / to_meter, name }) + } + /// A system from its parts (tests). pub fn new(flat: Flat, res: f64, name: &str) -> MapSystem { - MapSystem { flat, res, name: name.to_string() } + MapSystem { plane: Plane::Flat(flat), res, name: name.to_string() } } /// The system's name, as it can be given back to `map.projection`: its EPSG or ESRI code @@ -169,11 +245,17 @@ impl MapSystem { /// for LV95 a 60° cap around Bern, well past Switzerland) or folds, as the map draws nothing /// there. fn format(&self, c: Coord) -> Option { - let m = self.flat.forward_checked(Coord::new(crate::mapmenu::wrap_lon(c.x), c.y)).filter(|m| m.is_finite())?; + let c = Coord::new(crate::mapmenu::wrap_lon(c.x), c.y); + let m = match &self.plane { + Plane::Flat(f) => f.forward_checked(c), + Plane::Data(t, _) => t.from_lonlat(c), + } + .filter(|m| m.is_finite())?; let decimals = if self.res.is_finite() && self.res > 0.0 { (-self.res.log10()).ceil().clamp(0.0, 3.0) as usize } else { 0 }; - let to_meter = match &self.flat { - Flat::Mercator => 1.0, - Flat::Custom(p) => p.to_meter(), + let to_meter = match &self.plane { + Plane::Flat(Flat::Mercator) => 1.0, + Plane::Flat(Flat::Custom(p)) => p.to_meter(), + Plane::Data(_, to_meter) => *to_meter, }; let unit = if (to_meter - 1.0).abs() < 1e-9 { "m" @@ -200,7 +282,7 @@ mod tests { let mut f = CoordReadout::default(); assert_eq!(f, CoordReadout::Map); let mut seen = Vec::new(); - for _ in 0..5 { + for _ in 0..CoordReadout::ALL.len() { seen.push(f); f = f.next(); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c0f8871dc9..9b24ed9590 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -47,6 +47,13 @@ pub struct Dialogs { pub a: String, pub b: String, pub c: String, + /// Go To XY: the system its X and Y are in: empty for degrees, `map` for the map's own, or a + /// layer's name for the system it was read in. + pub xy_system: String, + /// Go To XY: the system `xy_system` named when its X and Y were filled ([`xy_key`]): the + /// map's projection, or a layer's, changing under the same entry makes them numbers in another + /// system. + pub xy_named: String, pub d: String, pub e: String, /// Add From Database: load the PostgreSQL table whole, to be edited and saved back. @@ -229,9 +236,9 @@ impl Dialogs { "goToXY" => { // The map's center, the longitude within ±180 even when the view has been panned // past the antimeridian. - let c = s.map().center_lonlat(); - self.a = format!("{:.4}", crate::mapmenu::wrap_lon(c.x)); - self.b = format!("{:.4}", c.y); + // In degrees, as every dialog opens afresh, the boxes' system noted. + [self.a, self.b] = center_in(s.map(), "").unwrap_or_default(); + self.xy_named = xy_key(s.map(), ""); } "bookmark" => self.text = rustgis_engine::cmd::navigate::new_bookmark_name(s.map()), "camera" => { @@ -434,29 +441,83 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { "selectByAttributes" => close = select_by_attributes(app, ui, &t), "goToXY" => { // UTM and MGRS are the Earth's grids, so another body's map offers degrees alone. - // A grid reference, once typed, is where Go goes: the degree boxes gray out. + // A grid reference, once typed, is where Go goes: the X and Y boxes gray out. let earth = app.session.map().body().is_earth(); let by_grid = earth && !app.dialogs.text.trim().is_empty(); + let (systems, left_out) = xy_systems(app.session.map()); + // A system gone (its layer removed or renamed) leaves degrees, and the boxes empty: + // their numbers were in that system, not degrees. + if !systems.iter().any(|(id, _)| *id == app.dialogs.xy_system) { + if !app.dialogs.xy_system.is_empty() { + app.dialogs.a.clear(); + app.dialogs.b.clear(); + } + app.dialogs.xy_system.clear(); + app.dialogs.xy_named = xy_key(app.session.map(), ""); + } + // The same entry naming another system now (the map's projection changed, or a + // layer's system was defined): the boxes take the center in it, or are emptied. + let named = xy_key(app.session.map(), &app.dialogs.xy_system); + if named != app.dialogs.xy_named { + [app.dialogs.a, app.dialogs.b] = center_in(app.session.map(), &app.dialogs.xy_system).unwrap_or_default(); + app.dialogs.xy_named = named; + } + let degrees = app.dialogs.xy_system.is_empty(); egui::Grid::new("xy").num_columns(2).spacing(vec2(10.0, 8.0)).show(ui, |ui| { - let input_label = ui.label(tl!("Longitude (X)")); - ui.add_enabled( - !by_grid, - egui::TextEdit::singleline(&mut app.dialogs.a).hint_text("-74.006 · 74°0′22″W").desired_width(300.0), - ) - .labelled_by(input_label.id); + if systems.len() > 1 { + let input_label = ui.label(tl!("Coordinates in")); + let shown = systems.iter().find(|(id, _)| *id == app.dialogs.xy_system).map(|(_, l)| l.clone()).unwrap_or_default(); + let mut picked = None; + egui::ComboBox::from_id_salt("xy_system") + .selected_text(shown) + .width(300.0) + .show_ui(ui, |ui| { + for (id, label) in &systems { + if ui.selectable_label(*id == app.dialogs.xy_system, label).clicked() { + picked = Some(id.clone()); + } + } + // Said, not dropped quietly: the systems past the first ones listed. + if left_out > 0 { + let n = left_out.to_string(); + ui.label( + egui::RichText::new(crate::i18n::fmt( + "{n} more systems of layers not listed; map.goToXY takes any by its layer's name", + &[("n", &n)], + )) + .color(t.text_dim), + ); + } + }) + .response + .labelled_by(input_label.id); + if let Some(id) = picked.filter(|id| *id != app.dialogs.xy_system) { + // The boxes show the map's center in the system picked; empty when it + // has none there, so numbers in the old system aren't read in the new. + [app.dialogs.a, app.dialogs.b] = center_in(app.session.map(), &id).unwrap_or_default(); + app.dialogs.xy_named = xy_key(app.session.map(), &id); + app.dialogs.xy_system = id; + } + ui.end_row(); + } + let (x, y, x_hint, y_hint) = if degrees { + (tl!("Longitude (X)"), tl!("Latitude (Y)"), "-74.006 · 74°0′22″W", "40.7128 · 40°42′46″N") + } else { + (tl!("Easting (X)"), tl!("Northing (Y)"), "2600000", "1200000") + }; + let input_label = ui.label(x); + ui.add_enabled(!by_grid, egui::TextEdit::singleline(&mut app.dialogs.a).hint_text(x_hint).desired_width(300.0)) + .labelled_by(input_label.id); ui.end_row(); - let input_label = ui.label(tl!("Latitude (Y)")); - ui.add_enabled( - !by_grid, - egui::TextEdit::singleline(&mut app.dialogs.b).hint_text("40.7128 · 40°42′46″N").desired_width(300.0), - ) - .labelled_by(input_label.id); + let input_label = ui.label(y); + ui.add_enabled(!by_grid, egui::TextEdit::singleline(&mut app.dialogs.b).hint_text(y_hint).desired_width(300.0)) + .labelled_by(input_label.id); ui.end_row(); if earth { - let input_label = ui.label(tl!("Or grid reference")); + let input_label = ui.label(tl!("Or position")); ui.add( egui::TextEdit::singleline(&mut app.dialogs.text) - .hint_text("18TWL8395907350 · 18north 583959 4507351") + .hint_text("18TWL8395907350 · 2600000 mE 1200000 mN EPSG:2056") .desired_width(300.0), ) .labelled_by(input_label.id); @@ -468,18 +529,24 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { ui.end_row(); }); // Below the boxes, wrapped to the dialog's width rather than widening it. - let hint = if earth { - tl!("Degrees as decimals or degrees, minutes and seconds; or a UTM or MGRS reference in place of both.") - } else { - tl!("Degrees as decimals or degrees, minutes and seconds.") + let hint = match (earth, degrees) { + (true, true) => tl!( + "Degrees as decimals or degrees, minutes and seconds; or a UTM or MGRS reference, or an easting and northing with their system as the map's right-click menu copies them, in place of both." + ), + (true, false) => tl!( + "The easting and northing in the system chosen; or a UTM or MGRS reference, or an easting and northing with their system, in place of both." + ), + (false, _) => tl!("Degrees as decimals or degrees, minutes and seconds."), }; ui.label(egui::RichText::new(hint).weak()); close = buttons(app, ui, "Go", |app| { let grid = app.dialogs.text.trim(); let mut p = if app.session.map().body().is_earth() && !grid.is_empty() { json!({"position": grid}) - } else { + } else if app.dialogs.xy_system.is_empty() { json!({"lon": app.dialogs.a.trim(), "lat": app.dialogs.b.trim()}) + } else { + json!({"x": app.dialogs.a.trim(), "y": app.dialogs.b.trim(), "crs": app.dialogs.xy_system}) }; // The command refuses a scale it can't use: commas go only where they group // thousands (50,000), so a decimal comma (1,5) is refused, not read as 15. @@ -1062,6 +1129,88 @@ pub fn open_dxf_path(app: &mut RustGisApp, path: &str) -> Result open_dxf(app, path, DxfSource::Path(path.to_string())) } +/// The systems Go To XY offers, as (what `map.goToXY` takes as `crs`, its label): degrees; on a +/// flat map of the Earth, the map's own; and each layer read in a projected system, by name (at +/// most [`XY_LAYER_SYSTEMS`], the first of each system). Also how many more systems the layers +/// have that the list leaves out, for the list to say. +fn xy_systems(map: &rustgis_engine::map::Map) -> (Vec<(String, String)>, usize) { + let mut v = vec![(String::new(), tl!("Degrees (longitude, latitude)").to_string())]; + if map.body().is_earth() && !map.projection.is_globe() { + v.push(("map".into(), crate::i18n::fmt("The map's system ({system})", &[("system", &map.projection.label())]))); + let (mut seen, mut left_out) = (Vec::new(), Vec::new()); + for l in &map.layers { + // A layer named `map` would be taken for the map's own system, and one whose name another + // layer has first would be taken for that one. + // By the name as `map.goToXY` reads it, trimmed (a layer named " map " is the map's). + let found_by_name = map.layer_by_name(l.name.trim()).is_some_and(|f| f.id == l.id); + // Only a system of the Earth counted east, then north: X and Y are an easting and a + // northing, and another body's projection names no place on the Earth's map. + let Some(crs) = rustgis_engine::cmd::navigate::layer_coordinates_system(l).filter(|c| { + !c.is_geographic() + && !c.is_planetary() + && c.axis_directions() == [(1.0, 0.0), (0.0, 1.0)] + && !l.name.trim().eq_ignore_ascii_case("map") + && found_by_name + }) else { + continue; + }; + if seen.contains(&crs) || left_out.contains(&crs) { + continue; + } + if seen.len() >= XY_LAYER_SYSTEMS { + left_out.push(crs); + continue; + } + seen.push(crs); + v.push(( + l.name.clone(), + crate::i18n::fmt("Layer {layer} ({system})", &[("layer", &l.name), ("system", &short(&crs.definition_text()))]), + )); + } + return (v, left_out.len()); + } + (v, 0) +} + +/// The most layers' systems Go To XY's list offers, so a project of many doesn't make it a long +/// scroll; the others are said under it, and still taken by a layer's name in `map.goToXY`. +const XY_LAYER_SYSTEMS: usize = 20; + +/// The system a Go To XY entry (`id`, as [`xy_systems`] lists it) names now: degrees, the map's +/// projection, or the system a layer was read in, by its definition (not the list's wording, +/// which a change of language rewrites). +fn xy_key(map: &rustgis_engine::map::Map, id: &str) -> String { + match id { + "" => String::new(), + "map" => format!("map {}", map.projection.code()), + layer => map + .layer_by_name(layer.trim()) + .and_then(rustgis_engine::cmd::navigate::layer_coordinates_system) + .map(|c| format!("layer {}", c.definition_text())) + .unwrap_or_default(), + } +} + +/// `text` cut to 60 characters, with an ellipsis when cut (a PROJ definition in a list). +fn short(text: &str) -> String { + if text.chars().nth(60).is_some() { format!("{}…", text.chars().take(59).collect::()) } else { text.to_string() } +} + +/// The map's center in a Go To XY system (see [`xy_systems`]), as the X and Y boxes show it: degrees +/// to four decimals, else to two. +fn center_in(map: &rustgis_engine::map::Map, system: &str) -> Option<[String; 2]> { + let c = map.center_lonlat(); + let c = rustgis_engine::geom::Coord::new(crate::mapmenu::wrap_lon(c.x), c.y); + let at = match system { + "" => return Some([format!("{:.4}", c.x), format!("{:.4}", c.y)]), + "map" => map.flat().forward(c)?, + layer => { + rustgis_engine::cmd::navigate::layer_coordinates_system(map.layer_by_name(layer.trim())?)?.transformer().ok()?.from_lonlat(c)? + } + }; + at.is_finite().then(|| [format!("{:.2}", at.x), format!("{:.2}", at.y)]) +} + /// The current map's coordinate system, as a DXF import can be given it: Web Mercator and the /// globe as their EPSG codes; another flat projection as its EPSG code or, for a preset, what the /// map projects with, which is the map's exactly (a definition `Crs::parse` reads). @@ -3689,6 +3838,47 @@ mod tests { assert_eq!(h.state().session.map().projection.code(), "EPSG:2056"); } + /// Go To XY with the map's own system picked: when the map's projection changes while the + /// dialog is open, X and Y take the center in the new system, never the old numbers read in + /// it; numbers typed stay as they are frame after frame. + #[test] + fn go_to_xy_follows_the_maps_system_changing_under_it() { + let mut app = RustGisApp::with_sample(); + app.run("map.projection", json!({"type": "EPSG:2056"})).unwrap(); + app.run("map.goToXY", json!({"lon": 7.44, "lat": 46.95})).unwrap(); + app.dialogs.open("goToXY", &app.session).unwrap(); + app.dialogs.xy_system = "map".into(); + let frame = |app: RustGisApp| { + let mut h = egui_kittest::Harness::builder() + .with_size(vec2(1400.0, 1000.0)) + .with_max_steps(8) + .with_context_setup(|ctx| crate::theme::install_fonts(ctx, &[], None)) + .build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(2); + h.into_state() + }; + let mut app = frame(app); + let lv95 = center_in(app.session.map(), "map").unwrap(); + assert_eq!([app.dialogs.a.clone(), app.dialogs.b.clone()], lv95, "the center in LV95"); + assert!(app.dialogs.a.parse::().unwrap() > 2_000_000.0, "{}", app.dialogs.a); + app.run("map.projection", json!({"type": "mercator"})).unwrap(); + let mut app = frame(app); + let mercator = center_in(app.session.map(), "map").unwrap(); + assert_eq!([app.dialogs.a.clone(), app.dialogs.b.clone()], mercator, "the center in Web Mercator, not LV95's numbers"); + assert_eq!(app.dialogs.xy_system, "map"); + // Numbers typed stay. + app.dialogs.a = "830000".into(); + let app = frame(app); + assert_eq!(app.dialogs.a, "830000"); + } + /// In the app, Escape in a coordinate system box closes its list, not the dialog, and the /// Escape shortcut (the Explore tool) doesn't take it; Enter in the blank box takes no recent /// system, while ↓ then Enter does. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e095f26fcc..1ec68694ee 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -4315,8 +4315,8 @@ impl RustGisApp { let format = match p.get("format") { None | Some(Value::Null) => self.map.coord_format.next(), Some(Value::String(v)) => CoordReadout::from_code(v) - .ok_or_else(|| tl!("The coordinate format must be map, decimal, dms, utm or mgrs").to_string())?, - _ => return Err(tl!("The coordinate format must be map, decimal, dms, utm or mgrs").into()), + .ok_or_else(|| tl!("The coordinate format must be map, layer, decimal, dms, utm or mgrs").to_string())?, + _ => return Err(tl!("The coordinate format must be map, layer, decimal, dms, utm or mgrs").into()), }; self.map.coord_format = format; self.save_pref(coordreadout::PREF, format.code()); diff --git a/crates/ui-egui/src/mapmenu.rs b/crates/ui-egui/src/mapmenu.rs index c25fff9b81..5b778d356f 100644 --- a/crates/ui-egui/src/mapmenu.rs +++ b/crates/ui-egui/src/mapmenu.rs @@ -58,11 +58,12 @@ fn lat_lon(c: Coord) -> String { /// to latitude and longitude (and the row's hover text says why). Map coordinates are the map's /// own system's (`map`), followed by its name so the copy says which system they are in /// (`2600173 mE 1200272 mN EPSG:2056`); without one (the globe, another body) they are latitude -/// and longitude, and where the system doesn't reach they fall back to them. +/// and longitude, and where the system doesn't reach they fall back to them. Layer coordinates are +/// the active layer's projected system's alike (latitude and longitude without one). fn coordinate_row(c: Coord, f: CoordReadout, earth: bool, map: Option<&MapSystem>) -> (String, bool) { match (f, map) { - (CoordReadout::Decimal, _) | (CoordReadout::Map, None) => (lat_lon(c), false), - (CoordReadout::Map, Some(m)) => match f.format(c, earth, map) { + (CoordReadout::Decimal, _) | (CoordReadout::Map | CoordReadout::Layer, None) => (lat_lon(c), false), + (CoordReadout::Map | CoordReadout::Layer, Some(m)) => match f.format(c, earth, map) { Some(text) => (format!("{text} {}", m.name()), false), None => (lat_lon(c), true), }, @@ -132,11 +133,14 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, c: Coord) { crate::shapeconvert::menu(app, ui); let format = app.map.coord_format; let earth = app.session.map().body().is_earth(); - let system = MapSystem::of(app.session.map()); + let system = format.system(app.session.map(), app.session.active_layer); let (coords, fell_back) = coordinate_row(c, format, earth, system.as_ref()); let hover = if fell_back && format == CoordReadout::Map { tl!("Copy coordinates to the clipboard. The map's coordinate system doesn't reach here, so latitude and longitude are copied") .to_string() + } else if fell_back && format == CoordReadout::Layer { + tl!("Copy coordinates to the clipboard. The active layer's coordinate system doesn't reach here, so latitude and longitude are copied") + .to_string() } else if fell_back && !earth { i18n::fmt( "Copy coordinates to the clipboard. {format} is a grid of the Earth, so latitude and longitude are copied", @@ -342,4 +346,25 @@ mod tests { let far = Coord::new(-150.0, -60.0); assert_eq!(coordinate_row(far, CoordReadout::Map, true, Some(&lv95)), ("-60.000000, -150.000000".into(), true)); } + + /// Layer coordinates copy the active layer's projected system's easting and northing with its + /// code, as Go To XY reads them back, and latitude and longitude without such a layer. + #[test] + fn the_layer_row_copies_the_layers_system_by_its_code() { + use rustgis_engine::data::{Dataset, GeometryType, raster::Crs}; + let mut s = rustgis_engine::Session::new(rustgis_engine::Project::default()); + let mut ds = Dataset::new("laea", GeometryType::Point, Vec::new()); + ds.crs = Some(Crs::from_epsg(3035).unwrap()); + let id = s.map_mut().add_dataset(ds); + let p = Coord::new(15.3, 49.85); + let laea = CoordReadout::Layer.system(s.map(), Some(id)); + let (row, fell_back) = coordinate_row(p, CoordReadout::Layer, true, laea.as_ref()); + assert!(!fell_back && row.ends_with(" mN EPSG:3035"), "{row}"); + // The copy is a position Go To XY reads, at the same place. + s.run("map.goToXY", &serde_json::json!({"position": row})).unwrap(); + let c = s.map().center_lonlat(); + assert!((c.x - 15.3).abs() < 1e-4 && (c.y - 49.85).abs() < 1e-4, "{row}: {c:?}"); + // No layer active: latitude and longitude. + assert_eq!(coordinate_row(p, CoordReadout::Layer, true, CoordReadout::Layer.system(s.map(), None).as_ref()), (lat_lon(p), false)); + } } diff --git a/crates/ui-egui/src/searchbox.rs b/crates/ui-egui/src/searchbox.rs index ae9dc12894..21d3b57b37 100644 --- a/crates/ui-egui/src/searchbox.rs +++ b/crates/ui-egui/src/searchbox.rs @@ -291,8 +291,12 @@ fn list_area(app: &mut RustGisApp, ui: &Ui, frame_r: Rect, list: &[Row], t: &Tok // A grid reference that names no place says why (the band, the square letters, S // that may mean south), also while places can still be searched for it. let grid = st.results.grid_error.filter(|_| st.query == st.searched && st.results.hits.is_empty()); + // So does an easting and northing with their system that names none (#2032 C2f-8). + let position = st.results.position_error.as_ref().filter(|_| st.query == st.searched && st.results.hits.is_empty()); if let Some(e) = grid { note(ui, &grid_error_text(e), t.text_dim); + } else if let Some(e) = position { + note(ui, &crate::i18n::fmt_raw("No place at this position: {reason}", &[("reason", e.as_str())]), t.text_dim); } else if none { note(ui, tl_raw!("Nothing found"), t.text_dim); } diff --git a/crates/ui-egui/tests/integration/coordinate_readout.rs b/crates/ui-egui/tests/integration/coordinate_readout.rs index 300faf584c..69df889005 100644 --- a/crates/ui-egui/tests/integration/coordinate_readout.rs +++ b/crates/ui-egui/tests/integration/coordinate_readout.rs @@ -1,4 +1,4 @@ -//! The status bar's coordinate readout: a click steps map → decimal → DMS → UTM → MGRS, the choice +//! The status bar's coordinate readout: a click steps map → decimal → DMS → UTM → MGRS → layer, the choice //! is remembered as a preference, and the readout shows the pointer in it. use std::sync::{Arc, Mutex}; @@ -28,13 +28,13 @@ fn the_format_cycles_persists_and_is_restored() { }); assert_eq!(app.map.coord_format, CoordReadout::Map); let mut seen = Vec::new(); - for _ in 0..5 { + for _ in 0..6 { app.run("ui.coordinateFormat", Value::Null).unwrap(); seen.push(app.map.coord_format.code()); } - assert_eq!(seen, ["decimal", "dms", "utm", "mgrs", "map"]); + assert_eq!(seen, ["decimal", "dms", "utm", "mgrs", "layer", "map"]); let writes: Vec = saved.lock().unwrap().iter().filter(|(k, _)| k == "coordinate_format").map(|(_, v)| v.clone()).collect(); - assert_eq!(writes, ["decimal", "dms", "utm", "mgrs", "map"]); + assert_eq!(writes, ["decimal", "dms", "utm", "mgrs", "layer", "map"]); app.run("ui.coordinateFormat", json!({"format": "MGRS"})).unwrap(); assert_eq!(app.map.coord_format, CoordReadout::Mgrs); for bad in [json!({"format": "ups"}), json!({"format": 3}), json!({"format": ""})] { @@ -42,9 +42,13 @@ fn the_format_cycles_persists_and_is_restored() { assert_eq!(app.map.coord_format, CoordReadout::Mgrs, "{bad}"); } // A saved choice comes back, with nothing to say. - for (pref, want) in - [("utm", CoordReadout::Utm), ("mgrs", CoordReadout::Mgrs), ("decimal", CoordReadout::Decimal), ("map", CoordReadout::Map)] - { + for (pref, want) in [ + ("utm", CoordReadout::Utm), + ("mgrs", CoordReadout::Mgrs), + ("decimal", CoordReadout::Decimal), + ("map", CoordReadout::Map), + ("layer", CoordReadout::Layer), + ] { let restored = RustGisApp::with_sample().with_services(Services { load_pref: Some(Box::new(move |k| (k == "coordinate_format").then(|| pref.to_string()))), ..Services::default() @@ -135,6 +139,17 @@ fn the_status_bar_reads_the_pointer_in_the_chosen_format_and_a_click_switches() assert!(mgrs.starts_with("38S MB 4"), "{mgrs}"); h.get_by_label(&mgrs).click(); hover_map(&mut h); + assert_eq!(h.state().map.coord_format, CoordReadout::Layer); + // The sample's layers are in longitude and latitude: layer coordinates read in degrees. + let at = h.state().map.pointer_lonlat.unwrap(); + let layer = CoordReadout::Layer.readout( + Some(at), + true, + CoordReadout::Layer.system(h.state().session.map(), h.state().session.active_layer).as_ref(), + ); + assert_eq!(layer, rustgis_engine::geom::format_lonlat(at)); + h.get_by_label(&layer).click(); + hover_map(&mut h); assert_eq!(h.state().map.coord_format, CoordReadout::Map); // Where UTM has no zone the readout gives the polar grid, UPS (MGRS without a zone number). h.state_mut().run("ui.coordinateFormat", json!({"format": "mgrs"})).unwrap(); @@ -257,3 +272,66 @@ fn the_position_is_dropped_on_another_map_or_project() { assert!(h.query_by_label(&decimal).is_none()); h.get_by_label("—"); } + +/// Layer coordinates read in the projected system the active layer was read in, in its unit, as +/// `cs2cs` gives them; in degrees for a layer in degrees, with no layer active and on another +/// body's map; and say so where the system doesn't reach. +#[test] +fn layer_coordinates_read_in_the_active_layers_system() { + use rustgis_engine::data::{Dataset, GeometryType, raster::Crs}; + let mut app = RustGisApp::with_sample(); + fn add_to(app: &mut RustGisApp, crs: Option) -> u32 { + let mut ds = Dataset::new("held", GeometryType::Point, Vec::new()); + ds.crs = crs; + app.session.map_mut().add_dataset(ds) + } + let (laea, texas, merc, lonlat, nad27) = ( + add_to(&mut app, Some(Crs::from_epsg(3035).unwrap())), + add_to(&mut app, Some(Crs::from_epsg(2277).unwrap())), + add_to(&mut app, Some(Crs::WebMercator)), + add_to(&mut app, None), + add_to(&mut app, Some(Crs::from_epsg(4267).unwrap())), + ); + let read = |app: &RustGisApp, id: Option, at: rustgis_engine::geom::Coord| { + CoordReadout::Layer.readout( + Some(at), + app.session.map().body().is_earth(), + CoordReadout::Layer.system(app.session.map(), id).as_ref(), + ) + }; + let number = + |part: &str, suffix: &str| -> f64 { part.trim().strip_suffix(suffix).unwrap_or_else(|| panic!("{part}")).parse().unwrap() }; + // ETRS89 / LAEA Europe: `echo "49.85 15.3" | cs2cs EPSG:4326 EPSG:3035` gives N 2984581.1, E 4701839.1. + let p = rustgis_engine::geom::Coord::new(15.3, 49.85); + let r = read(&app, Some(laea), p); + let (e, n) = r.split_once(" ").unwrap(); + assert!((number(e, " mE") - 4_701_839.1).abs() < 1.0 && (number(n, " mN") - 2_984_581.1).abs() < 1.0, "{r}"); + assert_eq!(CoordReadout::Layer.system(app.session.map(), Some(laea)).unwrap().name(), "EPSG:3035"); + // Texas Central in US survey feet. + let r = read(&app, Some(texas), rustgis_engine::geom::Coord::new(-97.74, 30.27)); + assert!(r.contains(" ftUSE ") && r.ends_with(" ftUSN"), "{r}"); + // Web Mercator in its metres. + let r = read(&app, Some(merc), rustgis_engine::geom::Coord::new(0.0, 0.0)); + assert_eq!(r, "0 mE 0 mN"); + assert_eq!(CoordReadout::Layer.system(app.session.map(), Some(merc)).unwrap().name(), "Web Mercator"); + // In degrees: a layer in longitude/latitude, one in another datum's degrees, none active. + for id in [Some(lonlat), Some(nad27), None] { + assert!(CoordReadout::Layer.system(app.session.map(), id).is_none(), "{id:?}"); + assert_eq!(read(&app, id, p), rustgis_engine::geom::format_lonlat(p), "{id:?}"); + } + // A westing and southing (South Africa's Lo29, `+axis=wsu`) would be mislabelled as an + // easting and northing: degrees instead. + let lo29 = Crs::parse("+proj=tmerc +lat_0=0 +lon_0=29 +k=1 +x_0=0 +y_0=0 +axis=wsu +ellps=WGS84 +units=m +no_defs").unwrap(); + assert_ne!(lo29.axis_directions(), [(1.0, 0.0), (0.0, 1.0)]); + let lo29 = add_to(&mut app, Some(lo29)); + assert!(CoordReadout::Layer.system(app.session.map(), Some(lo29)).is_none()); + assert_eq!( + read(&app, Some(lo29), rustgis_engine::geom::Coord::new(29.0, -26.0)), + rustgis_engine::geom::format_lonlat(rustgis_engine::geom::Coord::new(29.0, -26.0)) + ); + // The hover names the format. + assert!(CoordReadout::Layer.hover().contains("active layer")); + // On another body's map, degrees. + app.run("map.body", json!({"name": "mars", "basemap": false})).unwrap(); + assert!(CoordReadout::Layer.system(app.session.map(), Some(laea)).is_none()); +} diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index f5c598b3e5..18da4fa356 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -4808,6 +4808,61 @@ fn by_coordinates_reads_x_y_and_a_grid_reference() { assert!((c.y - 40.7128).abs() < 1e-3 && (c.x + 74.006).abs() < 1e-3, "{c:?}"); } +/// On a projected map By Coordinates offers the map's own system: picked, the boxes show the map's +/// center as an easting and a northing, and Go goes to the easting and northing typed. A position +/// written as the right-click menu copies it, with its system, goes there too. +#[test] +fn by_coordinates_takes_an_easting_and_northing_in_the_maps_system() { + let mut h = harness(); + h.state_mut().run("map.projection", json!({"type": "EPSG:2056"})).unwrap(); + h.state_mut().run("map.goToXY", json!({"lon": 8.54, "lat": 47.37, "scale": 50_000})).unwrap(); + h.state_mut().run("ui.dialog", json!({"name": "goToXY"})).unwrap(); + h.step(); + assert_eq!(h.state().dialogs.xy_system, "", "degrees first"); + h.step(); + h.get_by_label("Coordinates in").click(); + h.step(); + h.step(); + h.get_by_label("The map's system (EPSG:2056)").click(); + h.step(); + assert_eq!(h.state().dialogs.xy_system, "map"); + // Zürich, about E 2683000, N 1247000. + let (e, n): (f64, f64) = (h.state().dialogs.a.parse().unwrap(), h.state().dialogs.b.parse().unwrap()); + assert!((e - 2_683_000.0).abs() < 2_000.0 && (n - 1_247_000.0).abs() < 2_000.0, "{e} {n}"); + h.step(); + h.get_by_label("Easting (X)"); + h.state_mut().dialogs.a = "2600000".into(); + h.state_mut().dialogs.b = "1200000".into(); + h.step(); + h.get_by_label("Go").click(); + h.step(); + assert_eq!(h.state().dialogs.open, None, "{:?}", h.state().dialogs.error); + let c = h.state().session.map().center_lonlat(); + assert!((c.x - 7.4386).abs() < 2e-3 && (c.y - 46.9511).abs() < 2e-3, "Bern: {c:?}"); + // The menu's copy, pasted into the position box. + h.state_mut().run("map.goToXY", json!({"lon": 8.54, "lat": 47.37})).unwrap(); + h.state_mut().run("ui.dialog", json!({"name": "goToXY"})).unwrap(); + h.step(); + h.state_mut().dialogs.text = "2600000 mE 1200000 mN EPSG:2056".into(); + h.step(); + h.get_by_label("Go").click(); + h.step(); + assert_eq!(h.state().dialogs.open, None, "{:?}", h.state().dialogs.error); + let c = h.state().session.map().center_lonlat(); + assert!((c.x - 7.4386).abs() < 2e-3 && (c.y - 46.9511).abs() < 2e-3, "Bern: {c:?}"); + // The system picked gone (the map turned to the globe, with no flat system of its own): back + // to degrees with the boxes empty, so its easting and northing aren't sent as degrees. + h.state_mut().run("ui.dialog", json!({"name": "goToXY"})).unwrap(); + h.step(); + h.state_mut().dialogs.xy_system = "map".into(); + h.state_mut().dialogs.a = "2600000".into(); + h.state_mut().dialogs.b = "1200000".into(); + h.state_mut().run("map.projection", json!({"type": "globe"})).unwrap(); + h.step(); + let d = &h.state().dialogs; + assert_eq!((d.xy_system.as_str(), d.a.as_str(), d.b.as_str()), ("", "", "")); +} + /// Panned past the antimeridian, By Coordinates still opens on a longitude within ±180, so Go on /// the text it wrote goes there. #[test] diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 87ff24fe8a..ea42746460 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1990,8 +1990,23 @@ The Imagery tab's groups open their tools in the Workflows pane. The tab belongs images are in another geographic system (NAD83, say), the run says so. A geographic `crs` other than EPSG:4326 is refused. - **Georeference** places a raster from control points (column, row, longitude, latitude) or - stretches it over the map view. Those only shift and scale a north-up grid, as RustGIS's - geotransform has no rotation. With `transform` (`raster.georeference`) the points are fitted by any + stretches it over the map view (**Fit To Map View**, `"extent": "view"`). Those only shift and + scale a north-up grid, as RustGIS's geotransform has no rotation. Fitted to the view, the raster + is placed in the map's own system on a flat map of the Earth (Web Mercator's EPSG:3857, the map's + EPSG or ESRI code, or a preset's definition), so it fills the view as drawn; on the globe and + another body's map, over the longitude and latitude box the view shows. A turned or tilted map + is refused (Reset North first), as is a Web Mercator view wider than the world or across the + antimeridian; a view of a world copy past it is fitted to the same place within ±180°. Control + points without `transform` are longitude and latitude, and `pointsCrs` or `crs` with them is + refused. An `extent` of four + numbers is in degrees, or in `crs` when given (`{"extent": [2599000, 1199000, 2601000, 1201000], + "crs": "EPSG:2056"}`), and the raster is placed in that system; an entry that isn't a number is + refused, not passed over. An extent goes without control points, `transform` and `pointsCrs`: + any of them beside it is refused, as none would be used. So are `name`, `path`, `cellSize` and + `resampling` without `transform`, as only a warp makes a new raster; without one the layer itself + is placed. The `extent` it answers is in longitude/latitude, whatever system the raster is + placed in. + With `transform` (`raster.georeference`) the points are fitted by any of the Control Point Fit transforms and the raster is warped onto a new north-up grid covering the warped image: `{"layer": "scan", "transform": "spline", "points": [[column, row, x, y], …], "pointsCrs": "EPSG:4326", "crs": 32613, "resampling": "bilinear", "cellSize": 5, "name": "warped", diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index 077324387f..ec73cc5674 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -99,7 +99,7 @@ This guide walks through RustGIS by task. Each page covers one part of the app: and closes it when it is. **Pane Sets** keep the tabs open. - **Status bar**: the scale (type one, or pick from the list), the zoom level, bearing and pitch (click them to face north and look straight down again), the pointer's coordinates (click them - to step through map coordinates (the map's own system, the default), decimal degrees, DMS, UTM and MGRS; see [Coordinate readouts](maps.md#coordinate-readouts)), + to step through map coordinates (the map's own system, the default), decimal degrees, DMS, UTM, MGRS and layer coordinates (the active layer's projected system); see [Coordinate readouts](maps.md#coordinate-readouts)), the coordinate system (click it to change the projection), the selection count (with a button to clear it), the latest notice (click to open **Messages**), a **Messages** button, the last draw time, the frame rate and a **GPU**/**CPU** diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 3550ecc2a0..124a6eab99 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -14,9 +14,28 @@ Europe, Africa, Americas and East Asia), and **Locate**: **By Coordinates…** p (X) and latitude (Y), each in decimal degrees or degrees, minutes and seconds (`-74.006` or `74°0'22"W`; `40.7128` or `40°42'46"N`; an N or S in the longitude is refused, not swapped), or on the Earth's map to a UTM or MGRS grid reference in place of both (`18north 583959 4507351`, -`18TWL8395907350`). `map.goToXY` takes the same: `lon` and `lat` as numbers or text, or a -`position` read as the search box reads it, latitude first; two bare numbers there are said back -as the latitude and longitude they were read as. A reference that names no place says why; an +`18TWL8395907350`). On a flat map of the Earth, **Coordinates in** also offers the map's own +system and each layer's projected system: X and Y are then an easting and a northing there, +starting at the map's center. The position box (and the search box) also reads an easting and a +northing followed by their system, as the right-click menu copies them in map coordinates +(`2600000 mE 1200000 mN EPSG:2056`, `2600000 1200000 EPSG:2056`; the system as a code, `Web +Mercator`, a projection preset, or `map` for the map's own). A system in degrees is refused there, +as degrees go without a system, latitude first, and so are numbers that read as degrees typed +before a projected system with no unit written (`46.95 7.44 EPSG:2056`); with a unit written +after each number they are the system's. A layer in a projection of the Earth names +no place on another body's map, nor does another body's projection on the Earth's map (or on a +third body's: Mars's on the Moon's), and the dialog doesn't offer one. X and Y are an easting and a +northing: a system counted west or south, or northing first, is refused (and not offered in the +dialog), and a raster layer gives the system its pixels are in (one with no +pixels loaded, still opening or unreadable, is refused). A unit written (`m`, `ft`, `ftUS`) +must be the system's: feet in a system of metres are refused, not read as metres; the search +box then says why, and `map.search` returns the reason as `positionError`. On another body's map, a +system named by a code is the Earth's and is refused. `map.goToXY` takes the same: `lon` and `lat` as numbers or +text, or `x` and `y` with `crs` (`"map"`, a layer's name for the system it was read in, or a +code such as `EPSG:2056`; a layer named like a code means the layer), or a `position` read as the search box reads it, latitude first; two +bare numbers there are said back as the latitude and longitude they were read as. A place a +system's formulas don't reach (one that doesn't project back to the same easting and northing) +is refused. A reference that names no place says why; an MGRS reference coarser than a meter (`18TWL`) goes to the center of its square and says so. **By Place or Address…** finds a place or address with a geocoder. **New Bookmark…** @@ -315,7 +334,7 @@ and **View In Google Earth** open the place in your browser at about the same zo The status bar shows the pointer's coordinates while it is over the map, and keeps the last position (dimmed) when it leaves, so you can move to the status bar and click it. It reads `—` until the pointer has been over the map, and again after you switch to another map or open another -project. Click the coordinates to step through five formats; the choice is remembered and also +project. Click the coordinates to step through six formats; the choice is remembered and also sets the right-click menu's first row. The same place in each: | Format | Example | Notes | @@ -325,6 +344,7 @@ sets the right-click menu's first row. The same place in each: | DMS | `15°18′00.0″ E 49°51′00.0″ N` | degrees, minutes and seconds | | UTM | `33north 521567 5521996` | zone and hemisphere (`33south …` south of the equator), easting and northing in metres, rounded to the metre | | MGRS | `33U WR 21566 21996` | zone (two digits: `04Q FJ …`) and band, the 100 km square, easting and northing within it, truncated to the metre | +| Layer coordinates | `4701839 mE 2984581 mN` | easting and northing in the projected coordinate system the active layer was read in (here ETRS89 / LAEA Europe, EPSG:3035), named beside them, in its unit, as map coordinates are; in decimal degrees for a layer in degrees, on another body's map, with no layer active, or in a system whose axes aren't east, then north (a westing and southing, such as South Africa's Lo grids) | UTM states the hemisphere, as GeographicLib's `GeoConvert -u -l` writes it, not the latitude band: in plain UTM a letter after the zone is commonly read as the hemisphere, so `38S` (band S, 32° N @@ -345,7 +365,10 @@ or oblique projection), they read *No map coordinates here*, and the right-click latitude and longitude instead. A projection can reach well beyond a national grid's area of use: London on a map in LV95 still reads eastings and northings. In map coordinates the right-click menu's row copies the system's name after them, `2600173 mE 1200272 mN EPSG:2056`, so the copy -says which system it is in. Scripts set the format with `ui.coordinateFormat={"format":"utm"}` (`map`, `decimal`, +says which system it is in; in layer coordinates, the layer's system's code (`… EPSG:3035`), so the copy +pastes back into **Go To XY**'s position box and the search box (a system with no EPSG code is named +by its name, which they don't read). Where the layer's system doesn't reach, the row copies latitude +and longitude. Scripts set the format with `ui.coordinateFormat={"format":"utm"}` (`map`, `layer`, `decimal`, `dms`, `utm` or `mgrs`); without `format` it steps to the next one. A saved format this version doesn't know, say from a newer RustGIS, reads in map coordinates with a notice, and stays saved until you pick a format.