From 3b1e6c403beff00ab4e4409747ccd2eb29b315d8 Mon Sep 17 00:00:00 2001 From: PawelKra <15887575+PawelKra@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:54:03 +0100 Subject: [PATCH 1/7] feat(geom): UTM and MGRS coordinate readouts, copies and search MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The status bar's coordinate readout now steps through decimal degrees, DMS, UTM (38S 444141 3684706) and MGRS (38S MB 44140 84706) on click, remembered as a preference (ui.coordinateFormat). The map's right-click menu shows and copies the coordinate in the same format, and search takes a UTM position or an MGRS reference as it takes a latitude and longitude. geom gets WGS 84 UTM forward and inverse with Krüger's series to sixth order (Karney 2011, J. Geodesy 85(8)), zones with the Norway and Svalbard exceptions, latitude bands, and MGRS after NGA.STND.0037: 100 km square letters, truncated digits at 1 m to 100 km, and a parser that checks the letters against the zone, the northing against the band (to the size of the cell it names) and the point against the zone. Points past 84° N or 80° S have no UTM or MGRS here (UPS is not done); the readout and the menu say so. Only a bare 100 km square is also looked for in tables, where it names Sentinel-2 tiles; a reference with digits is plainly a place. --- crates/data/tests/utm_vs_proj.rs | 98 ++ crates/engine/src/cmd/search.rs | 114 ++- crates/geom/src/lib.rs | 5 +- crates/geom/src/utm.rs | 1056 ++++++++++++++++++++ crates/ui-egui/src/chrome.rs | 12 +- crates/ui-egui/src/coordreadout.rs | 156 +++ crates/ui-egui/src/lib.rs | 22 + crates/ui-egui/src/mapmenu.rs | 43 +- crates/ui-egui/src/mapview.rs | 5 +- crates/ui-egui/tests/coordinate_readout.rs | 95 ++ docs/user-guide/index.md | 3 +- docs/user-guide/maps.md | 48 +- 12 files changed, 1632 insertions(+), 25 deletions(-) create mode 100644 crates/data/tests/utm_vs_proj.rs create mode 100644 crates/geom/src/utm.rs create mode 100644 crates/ui-egui/src/coordreadout.rs create mode 100644 crates/ui-egui/tests/coordinate_readout.rs diff --git a/crates/data/tests/utm_vs_proj.rs b/crates/data/tests/utm_vs_proj.rs new file mode 100644 index 0000000000..4b96b9205f --- /dev/null +++ b/crates/data/tests/utm_vs_proj.rs @@ -0,0 +1,98 @@ +//! The UTM series in `rustgis-geom` (Karney's Krüger series) against proj4rs, which reprojects +//! rasters and layers: the same places in every zone and band, both hemispheres, the Norway +//! and Svalbard zones and the zones' edges, within a millimetre. + +use rustgis_data::raster::Crs; +use rustgis_geom::{Coord, utm}; + +/// A small deterministic generator (no dependency). +struct Lcg(u64); +impl Lcg { + fn next(&mut self) -> f64 { + self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (self.0 >> 11) as f64 / (1u64 << 53) as f64 + } +} + +fn proj(zone: u8, north: bool) -> rustgis_data::raster::Transformer { + let south = if north { "" } else { " +south" }; + Crs::parse(&format!("+proj=utm +zone={zone}{south} +datum=WGS84 +units=m +no_defs")).unwrap().transformer().unwrap() +} + +/// Compares one place both ways; returns the largest difference in metres and degrees. +fn compare(t: &rustgis_data::raster::Transformer, p: Coord, zone: u8, north: bool) -> (f64, f64) { + let (e, n) = utm::to_utm_in_zone(p, zone, north).unwrap(); + let want = t.from_lonlat(p).unwrap(); + let dm = (e - want.x).abs().max((n - want.y).abs()); + assert!(dm < 1e-3, "zone {zone} north {north} at {p:?}: ours {e} {n}, proj4rs {} {}", want.x, want.y); + let back = utm::from_utm(zone, north, want.x, want.y).unwrap(); + let theirs = t.to_lonlat(want).unwrap(); + let dd = (back.x - theirs.x).abs().max((back.y - theirs.y).abs()); + // A millimetre is about 9e-9° of latitude. + assert!(dd < 1e-8, "zone {zone} north {north} at {p:?}: ours {back:?}, proj4rs {theirs:?}"); + (dm, dd) +} + +#[test] +fn random_places_in_every_zone_agree_with_proj4rs() { + let mut r = Lcg(2026); + let (mut worst_m, mut worst_deg) = (0.0f64, 0.0f64); + let mut count = 0; + for zone in 1u8..=60 { + for north in [true, false] { + let t = proj(zone, north); + for _ in 0..40 { + let lat = if north { r.next() * utm::UTM_MAX_LAT } else { -r.next() * -utm::UTM_MIN_LAT }; + // Across the zone and a little past its edges, as Norway's and Svalbard's do. + let lon = utm::central_meridian(zone) + (r.next() - 0.5) * 9.0; + let p = Coord::new(lon, lat); + let (m, d) = compare(&t, p, zone, north); + worst_m = worst_m.max(m); + worst_deg = worst_deg.max(d); + count += 1; + } + } + } + eprintln!("{count} places: largest difference {worst_m:.2e} m, {worst_deg:.2e}°"); +} + +#[test] +fn standard_zones_bands_and_exceptions_agree_with_proj4rs() { + let places = [ + // GeographicLib's GeoConvert example (Baghdad): 38n 444140.54 3684706.36. + (44.4, 33.3), + // Norway's 32V west of 6° E, and Bergen. + (3.5, 56.5), + (5.32, 60.39), + (11.99, 63.9), + // Svalbard's wide zones: their edges, 6° from the central meridian. + (0.01, 79.0), + (8.99, 72.1), + (9.01, 83.9), + (20.99, 75.0), + (21.01, 80.0), + (32.99, 77.0), + (33.01, 78.0), + (41.99, 83.99), + // The antimeridian, the equator, the band edges and the UTM limits. + (-180.0, 0.0), + (179.999, -0.001), + (-174.0, 8.0), + (0.0, -80.0), + (-0.001, 83.999), + (151.21, -33.87), + (-74.006, 40.7128), + ]; + for (lon, lat) in places { + let p = Coord::new(lon, lat); + let u = utm::to_utm(p).unwrap(); + let t = proj(u.zone, u.north()); + compare(&t, p, u.zone, u.north()); + let want = t.from_lonlat(p).unwrap(); + assert!((u.easting - want.x).abs() < 1e-3 && (u.northing - want.y).abs() < 1e-3, "{p:?} {u:?} {want:?}"); + // The EPSG codes the app reprojects with name the same systems. + let epsg = if u.north() { 32600 } else { 32700 } + u32::from(u.zone); + let by_code = Crs::from_epsg(epsg).unwrap().transformer().unwrap().from_lonlat(p).unwrap(); + assert!((by_code.x - want.x).abs() < 1e-6 && (by_code.y - want.y).abs() < 1e-6, "EPSG:{epsg}"); + } +} diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index 9c5ec3b904..a0d792d561 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -1,4 +1,5 @@ -//! The map's search box: one query matched against a coordinate, the map's layers, its +//! The map's search box: one query matched against a coordinate (a latitude and longitude, or a +//! UTM or MGRS grid reference), the map's layers, its //! bookmarks and the values in its layers' attribute tables. Places (geocoding) are the UI's, //! asked for on Enter: the public servers don't allow searching as one types. @@ -16,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).params( - r#"{"query": "a latitude and longitude (40.7, -74.0; 40°42'N 74°0'W), a layer, a bookmark or a value in a layer's table", "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), a layer, a bookmark or a value in a layer's table", "limit"?: 1–50, "go"?: true (the first hit) | index}"#, ), ] } @@ -96,7 +97,8 @@ fn digest(time_urls: &[(f64, String)]) -> u64 { /// What a search found. #[derive(Clone, Debug, PartialEq)] pub enum Hit { - /// A point typed as a latitude and longitude. + /// A point typed as a latitude and longitude, a UTM position or an MGRS reference (the centre + /// of the square it names). Coordinate { lon: f64, lat: f64 }, /// A layer whose name matches. Layer { id: u32, name: String }, @@ -139,8 +141,17 @@ pub fn search(s: &Session, query: &str, limit: usize) -> Results { if q.is_empty() { return out; } + // A query that is plainly a coordinate (a decimal point, a degree mark, a hemisphere, a UTM + // zone and band) isn't looked for in the tables; two whole numbers (an id, years, a range) + // may be either, and so may a bare 100 km MGRS square, which names Sentinel-2's tiles (33UVP); + // an MGRS reference with digits is plainly a coordinate. + let mut plainly_coordinate = false; if let Some(c) = parse_lat_lon(&q) { 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(c) = parse_grid_reference(&q) { + out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); + plainly_coordinate = rustgis_geom::parse_mgrs(&q).map_or(true, |m| m.digits > 0); } let needle = q.to_lowercase(); let map = s.map(); @@ -159,10 +170,6 @@ pub fn search(s: &Session, query: &str, limit: usize) -> Results { out.hits.push(Hit::Bookmark { name: b.name.clone() }); } } - // A query that is plainly a coordinate (a decimal point, a degree mark, a hemisphere) isn't - // looked for in the tables; two whole numbers (an id, years, a range) may be either. - let plainly_coordinate = matches!(out.hits.first(), Some(Hit::Coordinate { .. })) - && q.chars().any(|c| matches!(c, '.' | '°' | 'º' | '\'' | '′' | '"' | '″') || c.is_alphabetic()); if q.chars().count() >= MIN_FEATURE_QUERY && !plainly_coordinate { let number = q.parse::().ok().filter(|n| n.is_finite()); for l in map.layers.iter().filter(|l| !l.is_raster() && !l.graphics) { @@ -339,6 +346,16 @@ fn search_cmd(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"hits": r.hits.iter().map(Hit::to_json).collect::>(), "partial": r.partial})) } +/// A place typed as an MGRS reference (the centre of the square it names) or a UTM position, in +/// the forms [`rustgis_geom::parse_mgrs`] and [`rustgis_geom::parse_utm`] accept; `None` for +/// anything else, an ambiguous UTM zone letter or a reference that names no place. +pub fn parse_grid_reference(text: &str) -> Option { + match rustgis_geom::parse_mgrs(text) { + Ok(m) => m.centre().ok(), + Err(_) => rustgis_geom::parse_utm(text).ok(), + } +} + /// `lat, lon` rounded to six decimals (about 0.1 m), without trailing zeros. pub fn format_lat_lon(lat: f64, lon: f64) -> String { let r = |v: f64| { @@ -542,6 +559,89 @@ mod tests { assert_eq!(ll("51.5074,-0.1278"), Some((51.5074, -0.1278))); } + #[test] + fn grid_references_are_found() { + let s = Session::new(crate::sample::world_project()); + let near = |r: &Results, lon: f64, lat: f64| matches!(r.hits.first(), Some(Hit::Coordinate { lon: x, lat: y }) if (x - lon).abs() < 1e-4 && (y - lat).abs() < 1e-4); + // GeographicLib's GeoConvert example, 33.3° N 44.4° E: 38n 444140.54 3684706.36, + // 38SMB4414084706. + for q in [ + "38S 444141 3684706", + "38s 444140.54, 3684706.36", + "38 north 444141 3684706", + "38N 444141 3684706", + "38SMB4414084706", + "38S MB 44140 84706", + "38smb 44140 84706", + ] { + let r = search(&s, q, 50); + assert!(near(&r, 44.4, 33.3), "{q}: {r:?}"); + } + // A 100 km square is found at its centre. + let r = search(&s, "38SMB", 50); + let u = rustgis_geom::to_utm(match r.hits.first() { + Some(Hit::Coordinate { lon, lat }) => Coord::new(*lon, *lat), + other => panic!("{other:?}"), + }) + .unwrap(); + assert!((u.easting - 450_000.0).abs() < 1e-3 && (u.northing - 3_650_000.0).abs() < 1e-3, "{u:?}"); + // A table holding tile names is searched for an MGRS reference, not for a UTM position. + let mut s = s; + s.run( + "layer.addDataText", + &json!({"fileName": "tiles.csv", "text": "tile,lon,lat\n38SMB,44.5,33\n38S 444141 3684706,44.4,33.3\n"}), + ) + .unwrap(); + let r = search(&s, "38SMB", 50); + assert!(matches!(r.hits.first(), Some(Hit::Coordinate { .. })), "{r:?}"); + assert!(r.hits.iter().any(|h| matches!(h, Hit::Feature { value, .. } if value == "38SMB")), "{r:?}"); + let r = search(&s, "38S 444141 3684706", 50); + assert!(!r.hits.iter().any(|h| matches!(h, Hit::Feature { .. })), "{r:?}"); + // Only the bare 100 km square names a tile: a reference with digits is plainly a place. + s.run("layer.addDataText", &json!({"fileName": "refs.csv", "text": "ref,lon,lat\n38SMB4414084706,44.4,33.3\n"})).unwrap(); + let r = search(&s, "38SMB4414084706", 50); + assert!(matches!(r.hits.first(), Some(Hit::Coordinate { .. })), "{r:?}"); + assert!(!r.hits.iter().any(|h| matches!(h, Hit::Feature { .. })), "{r:?}"); + // The command goes there. + s.run("map.search", &json!({"query": "38SMB4414084706", "go": true})).unwrap(); + let centre = s.map().camera.center_lonlat(); + assert!((centre.x - 44.4).abs() < 1e-3 && (centre.y - 33.3).abs() < 1e-3, "{centre:?}"); + } + + #[test] + fn bad_grid_references_find_no_place() { + let s = Session::new(crate::sample::world_project()); + for q in [ + // Band S with a northing outside it may be the southern hemisphere. + "33S 412345 5523456", + // The northing isn't in band T; the square letters aren't zone 38's; odd digits. + "33T 412345 5523456", + "38SAB4414084706", + "38SMB441408470", + "38TMB4414084706", + // Polar (UPS) references aren't read. + "38Z 444141 3684706", + "38ZMB4414084706", + "99X 1 2", + "1C", + ] { + assert!(parse_grid_reference(q).is_none(), "{q}"); + assert!(!search(&s, q, 50).hits.iter().any(|h| matches!(h, Hit::Coordinate { .. })), "{q}"); + } + // MGRS-looking garbage never panics. + let mut r = 1u64; + let alphabet: Vec = "0123456789 ACHINOSUVXZacz.-,°\u{0}é٣".chars().collect(); + for _ in 0..5_000 { + let mut q = String::new(); + for _ in 0..(r % 24) { + r = r.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + q.push(alphabet[(r >> 33) as usize % alphabet.len()]); + } + let _ = parse_grid_reference(&q); + let _ = parse_lat_lon(&q); + } + } + #[test] fn non_coordinates_are_refused() { for t in diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 3fea71c6b4..a3d4396b56 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -1,4 +1,5 @@ -//! L0: coordinates, extents, the Web Mercator projection, geodesic measurement and map scale. +//! L0: coordinates, extents, the Web Mercator projection, geodesic measurement, map scale, and +//! UTM and MGRS coordinates ([`utm`]). //! //! Everything here is plain math with no I/O. Longitude/latitude are WGS 84 degrees; projected //! coordinates are Web Mercator metres (EPSG:3857). @@ -7,9 +8,11 @@ pub mod body; pub mod sinusoidal; pub mod triangulate; +pub mod utm; pub use body::{BODIES, Body}; pub use sinusoidal::Sinusoidal; +pub use utm::{GridError, Mgrs, Utm, format_mgrs, format_utm, parse_mgrs, parse_utm, to_mgrs, to_utm}; use std::sync::LazyLock; diff --git a/crates/geom/src/utm.rs b/crates/geom/src/utm.rs new file mode 100644 index 0000000000..e6bf6d4933 --- /dev/null +++ b/crates/geom/src/utm.rs @@ -0,0 +1,1056 @@ +//! WGS 84 Universal Transverse Mercator (UTM) and Military Grid Reference System (MGRS) +//! coordinates: the pointer readouts and the grid references typed into the search box. +//! +//! The projection is the Krüger series to sixth order in the third flattening n, as given by +//! Karney, C. F. F. (2011), "Transverse Mercator with an accuracy of a few nanometers", +//! Journal of Geodesy 85(8), 475–485, doi:10.1007/s00190-011-0445-3: the conformal latitude of +//! eqs. (7)–(9), the series of eqs. (11) and (35) forward and (15) and (36) back, and Newton's +//! method of eqs. (19)–(21) for the latitude from the conformal one. Within the UTM zones it is +//! accurate to well under a millimetre. +//! +//! The grid follows NGA's definition: NGA.STND.0037 (2014), "Universal Grids and Grid Reference +//! Systems" (formerly DMA TM 8358.1): 6° zones with the exceptions of southern Norway (32V runs +//! from 3° E to 12° E, 31V only to 3° E) and Svalbard (31X, 33X, 35X and 37X are 9° or 12° wide; +//! 32X, 34X and 36X don't exist), latitude bands C to X of 8° (X runs 12°, from 72° N to 84° N), +//! and the 100 km squares of the AA lettering scheme used on WGS 84: column letters A–H, J–R and +//! S–Z by zone in turn, row letters A–V (no I or O) from the equator, starting at F in even zones. +//! A reference truncates its easting and northing to its precision, it doesn't round them. +//! +//! Only the UTM latitudes, 80° S to 84° N, are covered: the polar areas use the Universal Polar +//! Stereographic (UPS) grid, which isn't implemented. There the functions return `None`, and a +//! typed polar reference is refused with [`GridError::Polar`]. + +use std::fmt; +use std::sync::LazyLock; + +use crate::Coord; + +/// The southern limit of the UTM zones (degrees). +pub const UTM_MIN_LAT: f64 = -80.0; +/// The northern limit of the UTM zones (degrees); 84° N itself is UPS. +pub const UTM_MAX_LAT: f64 = 84.0; + +/// WGS 84 semi-major axis (metres) and flattening. +const WGS84_A: f64 = 6_378_137.0; +const WGS84_F: f64 = 1.0 / 298.257_223_563; +/// UTM's scale on the central meridian, false easting and the southern false northing. +const K0: f64 = 0.9996; +const FALSE_EASTING: f64 = 500_000.0; +const FALSE_NORTHING_SOUTH: f64 = 10_000_000.0; +/// MGRS 100 km square side (metres) and the 2,000 km cycle of its row letters. +const SQUARE: f64 = 100_000.0; +const ROW_CYCLE: f64 = 2_000_000.0; +/// How far (degrees) a typed reference may lie outside its zone's longitudes, beyond the size of +/// the cell it names: references near a zone edge are often written in the neighbouring zone, and +/// the position they give is still the right one. A band's latitudes get no such allowance: the +/// band is the latitude's own letter, so a reference in the wrong band is refused. +const EDGE_SLOP_DEG: f64 = 0.5; +/// How far (degrees) a place may lie outside its band, or past the UTM limits, for rounding: about +/// a metre, the precision a UTM position is written to. +const ROUNDING_DEG: f64 = 1.0 / M_PER_DEG; +/// Metres per degree of latitude, roughly, for turning a cell's size into degrees. +const M_PER_DEG: f64 = 111_000.0; + +/// Latitude band letters from 80° S, 8° each (X runs to 84° N). +const BANDS: &[u8; 20] = b"CDEFGHJKLMNPQRSTUVWX"; +/// MGRS column letters of the zones 1, 4, 7…; 2, 5, 8…; and 3, 6, 9… +const COLUMNS: [&[u8; 8]; 3] = [b"ABCDEFGH", b"JKLMNPQR", b"STUVWXYZ"]; +/// MGRS row letters, repeating every 2,000 km of northing. +const ROWS: &[u8; 20] = b"ABCDEFGHJKLMNPQRSTUV"; +/// Even zones start their rows five letters on, at F (AA scheme). +const EVEN_ZONE_ROW_OFFSET: i64 = 5; + +/// The ellipsoid's constants for the series (Karney 2011, eqs. 14, 35, 36). +struct Series { + /// First eccentricity. + e: f64, + /// Rectifying radius A: a / (1 + n) (1 + n²/4 + n⁴/64 + n⁶/256). + rect: f64, + /// Forward coefficients α₁…α₆. + alpha: [f64; 6], + /// Inverse coefficients β₁…β₆. + beta: [f64; 6], +} + +static SERIES: LazyLock = LazyLock::new(|| { + let f = WGS84_F; + let n = f / (2.0 - f); + let (n2, n3, n4, n5, n6) = (n * n, n.powi(3), n.powi(4), n.powi(5), n.powi(6)); + Series { + e: (f * (2.0 - f)).sqrt(), + rect: WGS84_A / (1.0 + n) * (1.0 + n2 / 4.0 + n4 / 64.0 + n6 / 256.0), + alpha: [ + n / 2.0 - 2.0 / 3.0 * n2 + 5.0 / 16.0 * n3 + 41.0 / 180.0 * n4 - 127.0 / 288.0 * n5 + 7891.0 / 37800.0 * n6, + 13.0 / 48.0 * n2 - 3.0 / 5.0 * n3 + 557.0 / 1440.0 * n4 + 281.0 / 630.0 * n5 - 1_983_433.0 / 1_935_360.0 * n6, + 61.0 / 240.0 * n3 - 103.0 / 140.0 * n4 + 15061.0 / 26880.0 * n5 + 167_603.0 / 181_440.0 * n6, + 49561.0 / 161_280.0 * n4 - 179.0 / 168.0 * n5 + 6_601_661.0 / 7_257_600.0 * n6, + 34729.0 / 80640.0 * n5 - 3_418_889.0 / 1_995_840.0 * n6, + 212_378_941.0 / 319_334_400.0 * n6, + ], + beta: [ + n / 2.0 - 2.0 / 3.0 * n2 + 37.0 / 96.0 * n3 - 1.0 / 360.0 * n4 - 81.0 / 512.0 * n5 + 96199.0 / 604_800.0 * n6, + 1.0 / 48.0 * n2 + 1.0 / 15.0 * n3 - 437.0 / 1440.0 * n4 + 46.0 / 105.0 * n5 - 1_118_711.0 / 3_870_720.0 * n6, + 17.0 / 480.0 * n3 - 37.0 / 840.0 * n4 - 209.0 / 4480.0 * n5 + 5569.0 / 90720.0 * n6, + 4397.0 / 161_280.0 * n4 - 11.0 / 504.0 * n5 - 830_251.0 / 7_257_600.0 * n6, + 4583.0 / 161_280.0 * n5 - 108_847.0 / 3_991_680.0 * n6, + 20_648_693.0 / 638_668_800.0 * n6, + ], + } +}); + +/// tan of the conformal latitude from tan of the latitude, τ′(τ) (Karney 2011, eqs. 7–9). +fn conformal_tan(tau: f64) -> f64 { + let e = SERIES.e; + let sigma = (e * (e * tau / tau.hypot(1.0)).atanh()).sinh(); + tau * sigma.hypot(1.0) - sigma * tau.hypot(1.0) +} + +/// tan of the latitude from tan of the conformal latitude, by Newton's method (Karney 2011, +/// eqs. 19–21). +fn geographic_tan(taup: f64) -> Option { + let e2m = 1.0 - SERIES.e * SERIES.e; + let mut tau = taup / e2m; + for _ in 0..10 { + let tp = conformal_tan(tau); + let dtau = (taup - tp) * (1.0 + e2m * tau * tau) / (e2m * tp.hypot(1.0) * tau.hypot(1.0)); + tau += dtau; + if dtau.is_nan() || dtau.abs() <= 1e-15 * tau.abs().max(1.0) { + break; + } + } + tau.is_finite().then_some(tau) +} + +/// Transverse Mercator at scale K0: (x, y) in metres from the central meridian and the equator. +fn tm_forward(lat: f64, dlon: f64) -> Option<(f64, f64)> { + let s = &*SERIES; + let lam = dlon.to_radians(); + let taup = conformal_tan(lat.to_radians().tan()); + let xip = taup.atan2(lam.cos()); + let etap = (lam.sin() / taup.hypot(lam.cos())).asinh(); + let (mut xi, mut eta) = (xip, etap); + for (j, a) in s.alpha.iter().enumerate() { + let k = 2.0 * (j as f64 + 1.0); + xi += a * (k * xip).sin() * (k * etap).cosh(); + eta += a * (k * xip).cos() * (k * etap).sinh(); + } + let (x, y) = (K0 * s.rect * eta, K0 * s.rect * xi); + (x.is_finite() && y.is_finite()).then_some((x, y)) +} + +/// The inverse of [`tm_forward`]: (latitude, longitude from the central meridian) in degrees. +fn tm_inverse(x: f64, y: f64) -> Option<(f64, f64)> { + let s = &*SERIES; + let (xi, eta) = (y / (K0 * s.rect), x / (K0 * s.rect)); + let (mut xip, mut etap) = (xi, eta); + for (j, b) in s.beta.iter().enumerate() { + let k = 2.0 * (j as f64 + 1.0); + xip -= b * (k * xi).sin() * (k * eta).cosh(); + etap -= b * (k * xi).cos() * (k * eta).sinh(); + } + let taup = xip.sin() / etap.sinh().hypot(xip.cos()); + let lam = etap.sinh().atan2(xip.cos()); + let lat = geographic_tan(taup)?.atan().to_degrees(); + let dlon = lam.to_degrees(); + (lat.is_finite() && dlon.is_finite()).then_some((lat, dlon)) +} + +/// A longitude within [-180, 180). +fn wrap(lon: f64) -> f64 { + let l = (lon + 180.0).rem_euclid(360.0) - 180.0; + if l >= 180.0 { l - 360.0 } else { l } +} + +/// The longitude of a zone's central meridian (degrees). +pub fn central_meridian(zone: u8) -> f64 { + f64::from(zone) * 6.0 - 183.0 +} + +/// The UTM zone (1–60) of a place, with the exceptions for southern Norway and Svalbard; `None` +/// outside the UTM latitudes (80° S to 84° N) or for a non-finite place. Longitude 180° is zone 1. +pub fn utm_zone(c: Coord) -> Option { + if !c.is_finite() || !(UTM_MIN_LAT..UTM_MAX_LAT).contains(&c.y) { + return None; + } + let (lon, lat) = (wrap(c.x), c.y); + let mut zone = (((lon + 180.0) / 6.0).floor() as i64 + 1).clamp(1, 60); + if (56.0..64.0).contains(&lat) && (3.0..12.0).contains(&lon) { + zone = 32; + } + if (72.0..UTM_MAX_LAT).contains(&lat) && (0.0..42.0).contains(&lon) { + zone = match lon { + l if l < 9.0 => 31, + l if l < 21.0 => 33, + l if l < 33.0 => 35, + _ => 37, + }; + } + u8::try_from(zone).ok() +} + +/// The latitude band letter (C–X, without I and O) of a latitude; `None` outside 80° S to 84° N. +pub fn latitude_band(lat: f64) -> Option { + if !(UTM_MIN_LAT..UTM_MAX_LAT).contains(&lat) { + return None; + } + let i = (((lat - UTM_MIN_LAT) / 8.0).floor() as usize).min(BANDS.len() - 1); + BANDS.get(i).map(|b| char::from(*b)) +} + +/// The latitudes (south, north) a band letter covers; `None` for a letter that isn't a band. +pub fn band_latitudes(band: char) -> Option<(f64, f64)> { + let i = BANDS.iter().position(|b| char::from(*b) == band)?; + let south = UTM_MIN_LAT + 8.0 * i as f64; + Some((south, if band == 'X' { UTM_MAX_LAT } else { south + 8.0 })) +} + +/// The longitudes (west, east) a zone covers within a band, with the Norway and Svalbard +/// exceptions; `None` for a zone that doesn't exist there (32X, 34X, 36X) or out of range. +pub fn zone_longitudes(zone: u8, band: char) -> Option<(f64, f64)> { + if !(1..=60).contains(&zone) { + return None; + } + let cm = central_meridian(zone); + let span = match (band, zone) { + ('V', 31) => (0.0, 3.0), + ('V', 32) => (3.0, 12.0), + ('X', 32 | 34 | 36) => return None, + ('X', 31) => (0.0, 9.0), + ('X', 33) => (9.0, 21.0), + ('X', 35) => (21.0, 33.0), + ('X', 37) => (33.0, 42.0), + _ => (cm - 3.0, cm + 3.0), + }; + Some(span) +} + +/// A place in UTM: its zone, latitude band, and easting and northing in metres (northings in the +/// southern hemisphere carry the 10,000 km false northing). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Utm { + pub zone: u8, + pub band: char, + pub easting: f64, + pub northing: f64, +} + +impl Utm { + /// Whether the place is in the northern hemisphere (bands N to X). + pub fn north(&self) -> bool { + self.band >= 'N' + } +} + +impl fmt::Display for Utm { + /// `33U 412345 5523456`: zone and band, then easting and northing rounded to the metre. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}{} {:.0} {:.0}", self.zone, self.band, self.easting.round(), self.northing.round()) + } +} + +/// A place's UTM coordinates in its own zone; `None` outside 80° S to 84° N (the UPS areas) or +/// for a non-finite place. +pub fn to_utm(c: Coord) -> Option { + let zone = utm_zone(c)?; + let band = latitude_band(c.y)?; + let (easting, northing) = to_utm_in_zone(c, zone, band >= 'N')?; + Some(Utm { zone, band, easting, northing }) +} + +/// A place's easting and northing in a given zone and hemisphere, as a projection to that zone +/// works (EPSG:326zz north, 327zz south). `None` for a zone outside 1–60, a non-finite place, a +/// latitude past ±90° or a longitude more than 45° from the zone's central meridian, where the +/// series no longer holds. +pub fn to_utm_in_zone(c: Coord, zone: u8, north: bool) -> Option<(f64, f64)> { + if !(1..=60).contains(&zone) || !c.is_finite() || c.y.abs() > 90.0 { + return None; + } + let dlon = wrap(c.x - central_meridian(zone)); + if dlon.abs() > 45.0 { + return None; + } + let (x, y) = tm_forward(c.y, dlon)?; + Some((FALSE_EASTING + x, if north { y } else { y + FALSE_NORTHING_SOUTH })) +} + +/// The place (longitude, latitude) at an easting and northing in a zone and hemisphere. `None` +/// for a zone outside 1–60, non-finite values, or an easting or northing so far out that it +/// names no place (more than 1,000 km from the central meridian or past a pole). +pub fn from_utm(zone: u8, north: bool, easting: f64, northing: f64) -> Option { + if !(1..=60).contains(&zone) || !easting.is_finite() || !northing.is_finite() { + return None; + } + let x = easting - FALSE_EASTING; + let y = if north { northing } else { northing - FALSE_NORTHING_SOUTH }; + if x.abs() > 1_000_000.0 || y.abs() > K0 * SERIES.rect * std::f64::consts::FRAC_PI_2 { + return None; + } + let (lat, dlon) = tm_inverse(x, y)?; + Some(Coord::new(wrap(central_meridian(zone) + dlon), lat)) +} + +/// A place as `33U 412345 5523456`; `None` outside 80° S to 84° N. +pub fn format_utm(c: Coord) -> Option { + to_utm(c).map(|u| u.to_string()) +} + +/// An MGRS reference: zone, band, the 100 km square's column and row letters, and the easting +/// and northing within the square truncated to `digits` digits each (0–5: 100 km to 1 m). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Mgrs { + pub zone: u8, + pub band: char, + pub column: char, + pub row: char, + pub easting: u32, + pub northing: u32, + pub digits: u8, +} + +impl Mgrs { + /// The size of the cell the reference names, in metres (1 m for 5 digits, 100 km for 0). + pub fn precision_m(&self) -> f64 { + 10f64.powi(5 - i32::from(self.digits.min(5))) + } + + /// Without spaces: `33UVP1234523456`. + pub fn compact(&self) -> String { + format!("{}{}{}{}{}", self.zone, self.band, self.column, self.row, self.digit_groups().concat()) + } + + /// The easting and northing digits, zero-padded to the precision (empty for 100 km). + fn digit_groups(&self) -> [String; 2] { + let w = usize::from(self.digits.min(5)); + if w == 0 { + return [String::new(), String::new()]; + } + [format!("{:0w$}", self.easting), format!("{:0w$}", self.northing)] + } + + /// The centre of the cell the reference names, checked against its zone and band. + pub fn centre(&self) -> Result { + locate(self) + } +} + +impl fmt::Display for Mgrs { + /// `33U VP 12345 23456` (the readout's form; `33U VP` at 100 km). + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}{} {}{}", self.zone, self.band, self.column, self.row)?; + let [e, n] = self.digit_groups(); + if !e.is_empty() { + write!(f, " {e} {n}")?; + } + Ok(()) + } +} + +/// A place's MGRS reference to `digits` digits per axis (clamped to 0–5: 100 km to 1 m), +/// truncated as MGRS requires; `None` outside 80° S to 84° N (the UPS areas). +pub fn to_mgrs(c: Coord, digits: u8) -> Option { + let digits = digits.min(5); + let u = to_utm(c)?; + // Whole metres first, truncated, so the square letters and the digits agree at an edge. + let (e, n) = (u.easting.floor(), u.northing.floor()); + if !(SQUARE..9.0 * SQUARE).contains(&e) || !(0.0..=FALSE_NORTHING_SOUTH).contains(&n) { + return None; + } + let (e, n) = (e as i64, n as i64); + let set = COLUMNS.get(usize::from((u.zone - 1) % 3))?; + let column = char::from(*set.get(usize::try_from(e / 100_000 - 1).ok()?)?); + let offset = if u.zone.is_multiple_of(2) { EVEN_ZONE_ROW_OFFSET } else { 0 }; + let row = char::from(*ROWS.get(usize::try_from((n / 100_000 + offset).rem_euclid(20)).ok()?)?); + let scale = 10i64.pow(5 - u32::from(digits)); + Some(Mgrs { + zone: u.zone, + band: u.band, + column, + row, + easting: u32::try_from(e % 100_000 / scale).ok()?, + northing: u32::try_from(n % 100_000 / scale).ok()?, + digits, + }) +} + +/// A place as `33U VP 12345 23456` (1 m); `None` outside 80° S to 84° N. +pub fn format_mgrs(c: Coord) -> Option { + to_mgrs(c, 5).map(|m| m.to_string()) +} + +/// Why a typed UTM or MGRS reference was refused. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GridError { + /// Not written as a grid reference at all. + Syntax, + /// A zone outside 1–60. + Zone, + /// A letter that isn't a latitude band. + Band, + /// A polar (UPS) reference: bands A, B, Y and Z. + Polar, + /// 100 km square letters that the zone doesn't use. + Square, + /// An odd number of digits, more than ten, or two groups of different lengths. + Digits, + /// The northing doesn't fall in the latitude band given. + BandMismatch, + /// The place lies outside the zone (or the zone doesn't exist in that band). + OutsideZone, + /// `S` after a UTM zone with a northing outside band S: it may mean the southern hemisphere. + Ambiguous, +} + +impl fmt::Display for GridError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + GridError::Syntax => "not a UTM or MGRS grid reference", + GridError::Zone => "the UTM zone must be 1 to 60", + GridError::Band => "the latitude band must be a letter from C to X (not I or O)", + GridError::Polar => "polar (UPS) grid references, north of 84° N or south of 80° S, aren't supported", + GridError::Square => "the 100 km square letters aren't used in this zone", + GridError::Digits => "the grid digits must be an even count of 0 to 10, half for the easting and half for the northing", + GridError::BandMismatch => "the northing doesn't fall in the latitude band given", + GridError::OutsideZone => "the place lies outside the zone given", + GridError::Ambiguous => { + "S after the zone is latitude band S; for the southern hemisphere write the zone, then south (33 south 412345 3768000)" + } + }) + } +} + +impl std::error::Error for GridError {} + +/// Whether a place found from a zone and band lies in them, give or take `cell_m` (the size of +/// the cell a reference names), and for the zone's longitudes [`EDGE_SLOP_DEG`]. +fn check_place(p: Coord, zone: u8, band: char, cell_m: f64) -> Result<(), GridError> { + let (south, north) = band_latitudes(band).ok_or(GridError::Band)?; + let lat_slop = cell_m / M_PER_DEG + ROUNDING_DEG; + if p.y < south - lat_slop || p.y > north + lat_slop { + return Err(GridError::BandMismatch); + } + let (west, east) = zone_longitudes(zone, band).ok_or(GridError::OutsideZone)?; + let cm = central_meridian(zone); + let dlon = wrap(p.x - cm); + let lon_slop = cell_m / (M_PER_DEG * p.y.to_radians().cos().max(0.01)) + EDGE_SLOP_DEG; + if dlon < west - cm - lon_slop || dlon > east - cm + lon_slop { + return Err(GridError::OutsideZone); + } + Ok(()) +} + +/// The centre of the cell an MGRS reference names: the 2,000 km row cycle is settled by the band. +fn locate(m: &Mgrs) -> Result { + if !(1..=60).contains(&m.zone) { + return Err(GridError::Zone); + } + if matches!(m.band, 'A' | 'B' | 'Y' | 'Z') { + return Err(GridError::Polar); + } + if m.digits > 5 { + return Err(GridError::Digits); + } + let (south, _) = band_latitudes(m.band).ok_or(GridError::Band)?; + let set = COLUMNS.get(usize::from((m.zone - 1) % 3)).ok_or(GridError::Zone)?; + let col = set.iter().position(|c| char::from(*c) == m.column).ok_or(GridError::Square)?; + let row = ROWS.iter().position(|c| char::from(*c) == m.row).ok_or(GridError::Square)? as i64; + let offset = if m.zone.is_multiple_of(2) { EVEN_ZONE_ROW_OFFSET } else { 0 }; + let row = (row - offset).rem_euclid(20) as f64; + let cell = m.precision_m(); + if f64::from(m.easting) * cell >= SQUARE || f64::from(m.northing) * cell >= SQUARE { + return Err(GridError::Digits); + } + let easting = (col as f64 + 1.0) * SQUARE + f64::from(m.easting) * cell + cell / 2.0; + let northing = row * SQUARE + f64::from(m.northing) * cell + cell / 2.0; + let north = south >= 0.0; + // Of the five northings the letters can stand for (0 to 10,000 km), the one in the band. + let mut found = None; + for k in 0..5 { + let Some(p) = from_utm(m.zone, north, easting, northing + f64::from(k) * ROW_CYCLE) else { continue }; + match check_place(p, m.zone, m.band, cell) { + Ok(()) => { + found = Some(p); + break; + } + Err(GridError::OutsideZone) => return Err(GridError::OutsideZone), + Err(_) => {} + } + } + found.ok_or(GridError::BandMismatch) +} + +/// Most characters a typed grid reference may have. +const MAX_REF_CHARS: usize = 64; + +/// Reads a zone number (1–60, one or two digits) and the letter after it, skipping spaces. +fn zone_and_letter(chars: &mut std::iter::Peekable>) -> Result<(u8, char), GridError> { + while chars.next_if(|c| c.is_whitespace()).is_some() {} + let mut zone = String::new(); + while let Some(d) = chars.next_if(char::is_ascii_digit) { + zone.push(d); + } + if zone.is_empty() || zone.len() > 2 { + return Err(GridError::Syntax); + } + let zone: u8 = zone.parse().map_err(|_| GridError::Syntax)?; + if !(1..=60).contains(&zone) { + return Err(GridError::Zone); + } + while chars.next_if(|c| c.is_whitespace()).is_some() {} + let letter = chars.next().filter(char::is_ascii_alphabetic).ok_or(GridError::Syntax)?.to_ascii_uppercase(); + Ok((zone, letter)) +} + +/// Checks a band letter, telling the polar letters apart. +fn band_letter(letter: char) -> Result { + if matches!(letter, 'A' | 'B' | 'Y' | 'Z') { + return Err(GridError::Polar); + } + band_latitudes(letter).map(|_| letter).ok_or(GridError::Band) +} + +/// Reads an MGRS reference, case-insensitive, with or without spaces: `33UVP1234523456`, +/// `33U VP 12345 23456`, `33UVP 1234 2345`, `4QFJ` (100 km). The digits are an even count of 0 +/// to 10, as one run or as two groups of the same length. The square letters are checked against +/// the zone, and the northing against the band, so a reference that doesn't exist is refused +/// rather than placed somewhere else. Polar (UPS) references are refused with +/// [`GridError::Polar`]. +pub fn parse_mgrs(text: &str) -> Result { + let text = text.trim(); + if text.chars().count() > MAX_REF_CHARS { + return Err(GridError::Syntax); + } + let mut chars = text.chars().peekable(); + let (zone, band) = zone_and_letter(&mut chars)?; + let mut letters = [' '; 2]; + for l in letters.iter_mut() { + while chars.next_if(|c| c.is_whitespace()).is_some() {} + *l = chars.next().filter(char::is_ascii_alphabetic).ok_or(GridError::Syntax)?.to_ascii_uppercase(); + } + let rest: String = chars.collect(); + if rest.chars().any(|c| !c.is_ascii_digit() && !c.is_whitespace()) { + return Err(GridError::Syntax); + } + let groups: Vec<&str> = rest.split_whitespace().collect(); + let (e, n) = match groups.as_slice() { + [] => ("", ""), + [one] => { + if one.len() % 2 != 0 || one.len() > 10 { + return Err(GridError::Digits); + } + one.split_at(one.len() / 2) + } + [e, n] => { + if e.len() != n.len() || e.len() > 5 { + return Err(GridError::Digits); + } + (*e, *n) + } + _ => return Err(GridError::Digits), + }; + let band = band_letter(band)?; + let [column, row] = letters; + let digit = |s: &str| if s.is_empty() { Ok(0) } else { s.parse::().map_err(|_| GridError::Digits) }; + let m = Mgrs { + zone, + band, + column, + row, + easting: digit(e)?, + northing: digit(n)?, + digits: u8::try_from(e.len()).map_err(|_| GridError::Digits)?, + }; + locate(&m)?; + Ok(m) +} + +/// Reads a UTM position: a zone, then a latitude band letter or the hemisphere spelt out, then +/// the easting and northing in metres (decimals allowed; spaces or commas between). Accepted: +/// +/// - `33U 412345 5523456` or `33 U 412345 5523456`: zone and latitude band, as the readout +/// writes it. The northing must fall in the band. +/// - `33 north 412345 5523456`, `33 south 412345 4476544` (also `33north`, any case): zone and +/// hemisphere. +/// - `33N 412345 5523456`: band N lies wholly in the northern hemisphere, so a northing outside +/// band N is read as the northern hemisphere (both readings give the same place). +/// +/// `S` after the zone is band S (32° N to 40° N). A northing outside band S may mean the +/// southern hemisphere, so it is refused as [`GridError::Ambiguous`] rather than guessed. +/// Polar (UPS) references are refused. +pub fn parse_utm(text: &str) -> Result { + let text = text.trim(); + if text.chars().count() > MAX_REF_CHARS { + return Err(GridError::Syntax); + } + let mut chars = text.chars().peekable(); + let (zone, letter) = zone_and_letter(&mut chars)?; + let mut word = String::from(letter); + while let Some(c) = chars.next_if(char::is_ascii_alphabetic) { + word.push(c.to_ascii_uppercase()); + } + let rest: String = chars.collect(); + let nums: Vec<&str> = rest.split(|c: char| c.is_whitespace() || c == ',').filter(|s| !s.is_empty()).collect(); + let [es, ns] = nums.as_slice() else { return Err(GridError::Syntax) }; + let number = |s: &str| { + // Plain decimals only: no signs, exponents or "inf". + if s.is_empty() || !s.chars().all(|c| c.is_ascii_digit() || c == '.') { + return Err(GridError::Syntax); + } + s.parse::().ok().filter(|v| v.is_finite()).ok_or(GridError::Syntax) + }; + let (easting, northing) = (number(es)?, number(ns)?); + if !(0.0..1_000_000.0).contains(&easting) || !(0.0..=FALSE_NORTHING_SOUTH).contains(&northing) { + return Err(GridError::OutsideZone); + } + // A place from a hemisphere, checked against the band of its own latitude. + let by_hemisphere = |north: bool| -> Result { + let p = from_utm(zone, north, easting, northing).ok_or(GridError::OutsideZone)?; + if p.y >= UTM_MAX_LAT + ROUNDING_DEG || p.y < UTM_MIN_LAT - ROUNDING_DEG { + return Err(GridError::Polar); + } + let band = latitude_band(p.y.clamp(UTM_MIN_LAT, UTM_MAX_LAT - 1e-9)).ok_or(GridError::Polar)?; + check_place(p, zone, band, 1.0).map(|()| p) + }; + match word.as_str() { + "NORTH" => by_hemisphere(true), + "SOUTH" => by_hemisphere(false), + w if w.chars().count() == 1 => { + let band = band_letter(letter)?; + let north = band >= 'N'; + let p = from_utm(zone, north, easting, northing).ok_or(GridError::OutsideZone)?; + match check_place(p, zone, band, 1.0) { + Ok(()) => Ok(p), + Err(GridError::BandMismatch) if band == 'N' => by_hemisphere(true), + Err(GridError::BandMismatch) if band == 'S' => Err(GridError::Ambiguous), + Err(e) => Err(e), + } + } + _ => Err(GridError::Syntax), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn c(lon: f64, lat: f64) -> Coord { + Coord::new(lon, lat) + } + + /// A small deterministic generator for sweeps (no dependency). + struct Lcg(u64); + impl Lcg { + fn next(&mut self) -> f64 { + self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (self.0 >> 11) as f64 / (1u64 << 53) as f64 + } + } + + /// GeographicLib's GeoConvert documentation converts 33.3° N 44.4° E (Baghdad) to + /// `38n 444140.54 3684706.36` and MGRS `38SMB4414084706` + /// (https://geographiclib.sourceforge.io/C++/doc/GeoConvert.1.html). Also checked against + /// proj4rs in `crates/data/tests/utm_vs_proj.rs`. + #[test] + fn published_reference_point() { + let u = to_utm(c(44.4, 33.3)).unwrap(); + assert_eq!((u.zone, u.band), (38, 'S')); + assert!((u.easting - 444_140.54).abs() < 0.005, "{}", u.easting); + assert!((u.northing - 3_684_706.36).abs() < 0.005, "{}", u.northing); + assert_eq!(to_mgrs(c(44.4, 33.3), 5).unwrap().compact(), "38SMB4414084706"); + assert_eq!(format_utm(c(44.4, 33.3)).unwrap(), "38S 444141 3684706"); + assert_eq!(format_mgrs(c(44.4, 33.3)).unwrap(), "38S MB 44140 84706"); + } + + /// The equator at the prime meridian: GeographicLib's `GeoConvert -m` gives `31NAA6602100000`, + /// and just south of it the row letter wraps to V with the 10,000 km false northing. + #[test] + fn equator_and_prime_meridian() { + assert_eq!(to_mgrs(c(0.0, 0.0), 5).unwrap().compact(), "31NAA6602100000"); + let s = to_utm(c(0.0, -1e-7)).unwrap(); + assert_eq!(s.band, 'M'); + assert!(!s.north()); + assert!(s.northing > 9_999_980.0 && s.northing < FALSE_NORTHING_SOUTH, "{}", s.northing); + assert_eq!(to_mgrs(c(0.0, -1e-7), 5).unwrap().compact(), "31MAV6602199999"); + // On the central meridian the easting is exactly the false easting, the northing zero. + let u = to_utm(c(3.0, 0.0)).unwrap(); + assert!((u.easting - 500_000.0).abs() < 1e-6 && u.northing.abs() < 1e-6, "{u:?}"); + } + + /// The meridian distance at k0 = 0.9996: the quarter meridian of WGS 84 is 10,001,965.729 m + /// (Karney 2011, table 1's A·π/2), so 9,997,964.943 m at the pole on the central meridian. + #[test] + fn meridian_arc_matches_the_quarter_meridian() { + let (_, y) = tm_forward(90.0, 0.0).unwrap(); + assert!((y - 0.9996 * 10_001_965.729_313).abs() < 1e-3, "{y}"); + let (_, y) = tm_forward(45.0, 0.0).unwrap(); + // The WGS 84 meridian arc to 45° is 4,984,944.378 m (Karney 2011 / GeographicLib). + assert!((y - 0.9996 * 4_984_944.378).abs() < 1e-3, "{y}"); + } + + #[test] + fn round_trips_within_a_nanodegree() { + let mut r = Lcg(7); + for _ in 0..20_000 { + let lat = UTM_MIN_LAT + r.next() * (UTM_MAX_LAT - UTM_MIN_LAT); + let lon = -180.0 + r.next() * 360.0; + let u = to_utm(c(lon, lat)).unwrap(); + let back = from_utm(u.zone, u.north(), u.easting, u.northing).unwrap(); + assert!((back.y - lat).abs() < 1e-9, "{lon} {lat} {back:?}"); + assert!(wrap(back.x - lon).abs() < 1e-9, "{lon} {lat} {back:?}"); + assert!((100_000.0..900_000.0).contains(&u.easting), "{lon} {lat} {u:?}"); + } + // Far from the central meridian, as Svalbard's wide zones and a forced zone reach (up to + // the 1,000 km `from_utm` takes). + for (dlon, lat) in [(9.0, 72.0), (8.0, 10.0), (15.0, 60.0), (-8.0, -45.0)] { + let (e, n) = to_utm_in_zone(c(dlon + 3.0, lat), 31, lat >= 0.0).unwrap(); + let back = from_utm(31, lat >= 0.0, e, n).unwrap(); + assert!((back.y - lat).abs() < 1e-9 && (back.x - dlon - 3.0).abs() < 1e-9, "{dlon} {lat} {back:?}"); + } + } + + #[test] + fn zones_at_their_edges() { + assert_eq!(utm_zone(c(-180.0, 0.0)), Some(1)); + assert_eq!(utm_zone(c(180.0, 0.0)), Some(1)); + assert_eq!(utm_zone(c(179.999_999, 0.0)), Some(60)); + assert_eq!(utm_zone(c(540.0, 0.0)), Some(1)); + assert_eq!(utm_zone(c(-174.000_001, 0.0)), Some(1)); + assert_eq!(utm_zone(c(-174.0, 0.0)), Some(2)); + assert_eq!(utm_zone(c(0.0, 10.0)), Some(31)); + assert_eq!(utm_zone(c(-1e-9, 10.0)), Some(30)); + assert_eq!(utm_zone(c(6.0, 10.0)), Some(32)); + assert_eq!(utm_zone(c(5.999_999, 10.0)), Some(31)); + // Southern Norway: 32V from 3° E to 12° E between 56° N and 64° N. + assert_eq!(utm_zone(c(2.999_999, 60.0)), Some(31)); + assert_eq!(utm_zone(c(3.0, 60.0)), Some(32)); + assert_eq!(utm_zone(c(5.0, 60.0)), Some(32)); + assert_eq!(utm_zone(c(11.999, 60.0)), Some(32)); + assert_eq!(utm_zone(c(12.0, 60.0)), Some(33)); + assert_eq!(utm_zone(c(5.0, 55.999_999)), Some(31)); + assert_eq!(utm_zone(c(5.0, 56.0)), Some(32)); + assert_eq!(utm_zone(c(5.0, 63.999_999)), Some(32)); + assert_eq!(utm_zone(c(5.0, 64.0)), Some(31)); + // Svalbard: 31X 0–9° E, 33X 9–21° E, 35X 21–33° E, 37X 33–42° E from 72° N. + for (lon, zone) in [ + (-0.000_001, 30), + (0.0, 31), + (8.999, 31), + (9.0, 33), + (20.999, 33), + (21.0, 35), + (32.999, 35), + (33.0, 37), + (41.999, 37), + (42.0, 38), + ] { + assert_eq!(utm_zone(c(lon, 78.0)), Some(zone), "{lon}"); + } + assert_eq!(utm_zone(c(10.0, 71.999_999)), Some(32)); + assert_eq!(utm_zone(c(10.0, 72.0)), Some(33)); + // The UTM latitudes: 80° S included, 84° N not; the rest is UPS. + assert_eq!(utm_zone(c(0.0, -80.0)), Some(31)); + assert_eq!(utm_zone(c(0.0, -80.000_001)), None); + assert_eq!(utm_zone(c(0.0, 83.999_999)), Some(31)); + assert_eq!(utm_zone(c(0.0, 84.0)), None); + assert_eq!(utm_zone(c(f64::NAN, 0.0)), None); + assert_eq!(utm_zone(c(0.0, f64::INFINITY)), None); + } + + #[test] + fn bands_at_their_edges() { + assert_eq!(latitude_band(-80.0), Some('C')); + assert_eq!(latitude_band(-72.000_001), Some('C')); + assert_eq!(latitude_band(-72.0), Some('D')); + assert_eq!(latitude_band(-0.000_001), Some('M')); + assert_eq!(latitude_band(0.0), Some('N')); + assert_eq!(latitude_band(7.999_999), Some('N')); + assert_eq!(latitude_band(8.0), Some('P')); + assert_eq!(latitude_band(47.999), Some('T')); + assert_eq!(latitude_band(48.0), Some('U')); + assert_eq!(latitude_band(63.999), Some('V')); + assert_eq!(latitude_band(64.0), Some('W')); + assert_eq!(latitude_band(71.999), Some('W')); + assert_eq!(latitude_band(72.0), Some('X')); + assert_eq!(latitude_band(80.0), Some('X')); + assert_eq!(latitude_band(83.999_999), Some('X')); + assert_eq!(latitude_band(84.0), None); + assert_eq!(latitude_band(-80.000_001), None); + assert_eq!(latitude_band(f64::NAN), None); + // Every band round-trips through its latitudes, I and O skipped. + for (i, b) in "CDEFGHJKLMNPQRSTUVWX".chars().enumerate() { + let (s, n) = band_latitudes(b).unwrap(); + assert_eq!(s, -80.0 + 8.0 * i as f64); + assert_eq!(latitude_band(s), Some(b)); + assert_eq!(latitude_band(n - 1e-9), Some(b)); + } + assert_eq!(band_latitudes('X'), Some((72.0, 84.0))); + assert_eq!(band_latitudes('I'), None); + assert_eq!(band_latitudes('O'), None); + assert_eq!(band_latitudes('Y'), None); + } + + /// The 100 km square letters along the equator at each zone's central meridian (easting + /// 500 km: the fifth column letter) cycle through the three column sets and, in even zones, + /// start their rows at F. + #[test] + fn square_letters_by_zone_set_and_parity() { + let expect = ["EA", "NF", "WA", "EF", "NA", "WF"]; + for zone in 1u8..=60 { + let m = to_mgrs(c(central_meridian(zone), 0.0), 5).unwrap(); + assert_eq!(m.zone, zone); + let letters: String = [m.column, m.row].iter().collect(); + assert_eq!(letters, expect[usize::from((zone - 1) % 6)], "zone {zone}"); + } + // Across a zone edge on the equator: 31's first column (A), 30's last (Z), 32's first (J). + assert_eq!(to_mgrs(c(0.000_001, 0.5), 5).unwrap().column, 'A'); + assert_eq!(to_mgrs(c(-0.000_001, 0.5), 5).unwrap().column, 'Z'); + assert_eq!(to_mgrs(c(6.000_001, 0.5), 5).unwrap().column, 'J'); + assert_eq!(to_mgrs(c(5.999_999, 0.5), 5).unwrap().column, 'H'); + // Rows go up a letter every 100 km and wrap after V at 2,000 km. + let odd = |n: f64| to_mgrs(from_utm(31, true, 500_000.0, n).unwrap(), 5).unwrap().row; + assert_eq!(odd(50_000.0), 'A'); + assert_eq!(odd(150_000.0), 'B'); + assert_eq!(odd(1_950_000.0), 'V'); + assert_eq!(odd(2_050_000.0), 'A'); + let even = |n: f64| to_mgrs(from_utm(32, true, 500_000.0, n).unwrap(), 5).unwrap().row; + assert_eq!(even(50_000.0), 'F'); + assert_eq!(even(1_450_000.0), 'V'); + assert_eq!(even(1_550_000.0), 'A'); + // Norway's 32V: west of 6° E, in zone 32 with its J–R columns, not 31's A–H. + let m = to_mgrs(c(5.0, 60.0), 5).unwrap(); + assert_eq!((m.zone, m.band), (32, 'V')); + assert!("JKLMNPQR".contains(m.column), "{m}"); + // Svalbard's 33X at 10° E. + let m = to_mgrs(c(10.0, 78.0), 5).unwrap(); + assert_eq!((m.zone, m.band), (33, 'X')); + assert!("STUVWXYZ".contains(m.column), "{m}"); + } + + #[test] + fn mgrs_truncates_to_its_precision() { + // A place at easting 444,140.54 and northing 3,684,706.36 (38S MB). + let p = c(44.4, 33.3); + let want = ["38S MB", "38S MB 4 8", "38S MB 44 84", "38S MB 441 847", "38S MB 4414 8470", "38S MB 44140 84706"]; + for (d, w) in want.iter().enumerate() { + let m = to_mgrs(p, d as u8).unwrap(); + assert_eq!(m.to_string(), *w); + assert_eq!(m.precision_m(), 10f64.powi(5 - d as i32)); + } + // A place 0.9 m short of a metre is truncated to the metre below, not rounded up. + let near = from_utm(38, true, 444_140.9, 3_684_706.9).unwrap(); + assert_eq!(to_mgrs(near, 5).unwrap().compact(), "38SMB4414084706"); + let m = to_mgrs(near, 4).unwrap(); + assert_eq!((m.easting, m.northing), (4414, 8470)); + // More than five digits is clamped to five. + assert_eq!(to_mgrs(p, 9).unwrap().digits, 5); + // The UTM readout rounds instead. + assert_eq!(from_utm(38, true, 444_140.6, 3_684_706.4).map(format_utm), Some(Some("38S 444141 3684706".into()))); + assert!(to_mgrs(c(0.0, 84.0), 5).is_none()); + assert!(format_mgrs(c(0.0, -85.0)).is_none()); + } + + #[test] + fn mgrs_parses_every_precision_both_ways() { + let p = c(44.4, 33.3); + for d in 0u8..=5 { + let m = to_mgrs(p, d).unwrap(); + let cell = m.precision_m(); + for text in [m.to_string(), m.compact(), m.compact().to_lowercase(), format!(" {} ", m.to_string().to_lowercase())] { + let parsed = parse_mgrs(&text).unwrap_or_else(|e| panic!("{text}: {e}")); + assert_eq!(parsed, m, "{text}"); + let centre = parsed.centre().unwrap(); + // The centre of the cell lies within half a cell of the place, along each axis. + let u = to_utm(centre).unwrap(); + let pu = to_utm(p).unwrap(); + assert!((u.easting - pu.easting).abs() <= cell / 2.0 + 1.0, "{text} {u:?}"); + assert!((u.northing - pu.northing).abs() <= cell / 2.0 + 1.0, "{text} {u:?}"); + } + } + // A 1 m reference names its metre square; its centre is half a metre in. + let at = parse_mgrs("38SMB4414084706").unwrap().centre().unwrap(); + let u = to_utm(at).unwrap(); + assert!((u.easting - 444_140.5).abs() < 1e-6 && (u.northing - 3_684_706.5).abs() < 1e-6, "{u:?}"); + // Two groups, one group, spaces anywhere in the letters. + for t in ["38SMB 44140 84706", "38S MB4414084706", "38 S M B 44140 84706", "38smb4414084706"] { + assert_eq!(parse_mgrs(t).unwrap().compact(), "38SMB4414084706", "{t}"); + } + // Leading zero in the zone; a one-digit zone. + assert_eq!(parse_mgrs("04QFJ12345678").map(|m| m.zone), Ok(4)); + assert_eq!(parse_mgrs("4QFJ12345678").map(|m| (m.zone, m.digits)), Ok((4, 4))); + } + + #[test] + fn mgrs_round_trips_everywhere() { + let mut r = Lcg(11); + for _ in 0..5_000 { + let lat = UTM_MIN_LAT + r.next() * (UTM_MAX_LAT - UTM_MIN_LAT - 1e-6); + let lon = -180.0 + r.next() * 360.0; + let m = to_mgrs(c(lon, lat), 5).unwrap(); + let parsed = parse_mgrs(&m.compact()).unwrap_or_else(|e| panic!("{m} at {lon} {lat}: {e}")); + assert_eq!(parsed, m); + let back = to_utm(parsed.centre().unwrap()).unwrap(); + let u = to_utm(c(lon, lat)).unwrap(); + assert!((back.easting - u.easting).abs() <= 1.0 && (back.northing - u.northing).abs() <= 1.0, "{m} {u:?} {back:?}"); + } + } + + #[test] + fn invalid_mgrs_is_refused() { + for (t, e) in [ + ("", GridError::Syntax), + ("SMB4414084706", GridError::Syntax), + ("38", GridError::Syntax), + ("38S", GridError::Syntax), + ("38SM", GridError::Syntax), + ("38SMB441408470", GridError::Digits), + ("38SMB4414084706 1", GridError::Digits), + ("38SMB 4414 84706", GridError::Digits), + ("38SMB 441408 470600", GridError::Digits), + ("38SMB441408470612", GridError::Digits), + ("38SMB 1 2 3", GridError::Digits), + ("38SMB44140-84706", GridError::Syntax), + ("38SMB4414O84706", GridError::Syntax), + ("38SMB4414084706X", GridError::Syntax), + ("38S-MB", GridError::Syntax), + ("123SMB", GridError::Syntax), + ("0SMB", GridError::Zone), + ("61SMB", GridError::Zone), + ("38IMB", GridError::Band), + ("38OMB", GridError::Band), + ("38ZMB", GridError::Polar), + ("38AMB", GridError::Polar), + // Zone 38's columns are J–R (38 is in the second set): A–H and S–Z are other zones'. + ("38SAB4414084706", GridError::Square), + ("38SSB4414084706", GridError::Square), + // I and O are no row letters, W–Z are past V. + ("38SMI4414084706", GridError::Square), + ("38SMW4414084706", GridError::Square), + // 38S MB's letters repeat every 2,000 km of northing: at 15° N (band P), 33° N (S), + // 51° N (U) and 69° N (W). In band T (40°–48° N) or N (0°–8° N) they name no place. + ("38TMB4414084706", GridError::BandMismatch), + ("38NMB4414084706", GridError::BandMismatch), + ("38QMB4414084706", GridError::BandMismatch), + // Zone 33's westmost column S lies 350 km from the central meridian, beyond the + // zone's edge at 60° N (167 km). + ("33VSJ0000000000", GridError::OutsideZone), + // 31V runs only to 3° E (Norway); 32X doesn't exist (Svalbard). + ("31VGJ0000000000", GridError::OutsideZone), + ("32XNM0000000000", GridError::OutsideZone), + ] { + assert_eq!(parse_mgrs(t), Err(e), "{t}"); + } + // Garbage of every sort never panics. + for t in ["99999999999999999999", "1\u{0}", "١٢SMB", "38S MB 84706", "38ŞMB", &"9".repeat(200), "60X", "60XZZ", "1C"] { + let _ = parse_mgrs(t); + let _ = parse_utm(t); + } + } + + #[test] + fn utm_parses_band_and_hemisphere_forms() { + let p = c(15.3, 49.85); + let u = to_utm(p).unwrap(); + assert_eq!((u.zone, u.band), (33, 'U')); + let near = |q: Coord| (q.x - p.x).abs() < 1e-5 && (q.y - p.y).abs() < 1e-5; + let text = u.to_string(); + assert!(near(parse_utm(&text).unwrap()), "{text}"); + let (e, n) = (u.easting.round(), u.northing.round()); + for t in [ + format!("33u {e} {n}"), + format!("33 U {e}, {n}"), + format!("33 north {e} {n}"), + format!("33North {e} {n}"), + format!("33N {e} {n}"), + format!("33 n {e} {n}"), + format!("33U {:.2} {:.2}", u.easting, u.northing), + ] { + assert!(near(parse_utm(&t).unwrap_or_else(|e| panic!("{t}: {e}"))), "{t}"); + } + // The southern hemisphere, by band or spelt out. + let q = c(-58.4, -34.6); + let s = to_utm(q).unwrap(); + assert_eq!((s.zone, s.band), (21, 'H')); + for t in [s.to_string(), format!("21 south {:.0} {:.0}", s.easting, s.northing)] { + let got = parse_utm(&t).unwrap(); + assert!((got.x - q.x).abs() < 1e-5 && (got.y - q.y).abs() < 1e-5, "{t} {got:?}"); + } + // Band S (32°–40° N), as the readout writes Los Angeles. + let la = c(-118.25, 34.05); + let l = to_utm(la).unwrap(); + assert_eq!((l.zone, l.band), (11, 'S')); + let got = parse_utm(&l.to_string()).unwrap(); + assert!((got.x - la.x).abs() < 1e-5 && (got.y - la.y).abs() < 1e-5); + } + + #[test] + fn invalid_utm_is_refused() { + for (t, e) in [ + ("", GridError::Syntax), + ("33U", GridError::Syntax), + ("33U 412345", GridError::Syntax), + ("33U 412345 5523456 1", GridError::Syntax), + ("33U -412345 5523456", GridError::Syntax), + ("33U 4e5 5523456", GridError::Syntax), + ("33U inf 5523456", GridError::Syntax), + ("33U 412345m 5523456", GridError::Syntax), + ("33 east 412345 5523456", GridError::Syntax), + ("0U 412345 5523456", GridError::Zone), + ("61U 412345 5523456", GridError::Zone), + ("33I 412345 5523456", GridError::Band), + ("33Z 412345 5523456", GridError::Polar), + // 5,523 km north is 49.8° N: not band T (40°–48° N). + ("33T 412345 5523456", GridError::BandMismatch), + // Band S with a northing outside it could be the southern hemisphere. + ("33S 412345 5523456", GridError::Ambiguous), + ("33U 1000000 5523456", GridError::OutsideZone), + ("33U 412345 10000001", GridError::OutsideZone), + // An easting of 20 km is 480 km west of the central meridian, 6.7° at 49.8° N: + // beyond zone 33's western edge at 12° E. + ("33U 20000 5523456", GridError::OutsideZone), + // North of 84° N. + ("33 north 500000 9500000", GridError::Polar), + ] { + assert_eq!(parse_utm(t), Err(e), "{t}"); + } + } + + /// The band is the latitude's own letter: a place 0.2° (22 km) into band U written in band T + /// is refused, by UTM and by MGRS alike, while the right band reads it back. Past 84° N a + /// hemisphere-form position is polar, by however little. + #[test] + fn a_band_is_checked_to_the_cell_not_to_the_zone_edge() { + let p = c(15.0, 48.2); + let u = to_utm(p).unwrap(); + assert_eq!(u.band, 'U'); + let (e, n) = (u.easting.round(), u.northing.round()); + assert!(parse_utm(&format!("33U {e} {n}")).is_ok()); + assert_eq!(parse_utm(&format!("33T {e} {n}")), Err(GridError::BandMismatch)); + let m = to_mgrs(p, 5).unwrap().compact(); + assert!(parse_mgrs(&m).is_ok(), "{m}"); + let wrong = m.replacen("33U", "33T", 1); + assert_eq!(parse_mgrs(&wrong), Err(GridError::BandMismatch), "{wrong}"); + // A 100 km square straddling the band edge is still read in either band it touches. + let edge = to_mgrs(c(15.0, 48.0005), 0).unwrap().compact(); + assert!(parse_mgrs(&edge).is_ok(), "{edge}"); + // Just past 84° N, in the hemisphere form: polar. + let (e, n) = to_utm_in_zone(c(15.0, 84.05), 33, true).unwrap(); + assert_eq!(parse_utm(&format!("33 north {} {}", e.round(), n.round())), Err(GridError::Polar)); + let (e, n) = to_utm_in_zone(c(15.0, 83.95), 33, true).unwrap(); + assert!(parse_utm(&format!("33 north {} {}", e.round(), n.round())).is_ok()); + } + + #[test] + fn outside_utm_is_said_not_guessed() { + for p in [c(0.0, 84.0), c(10.0, 89.9), c(0.0, 90.0), c(-60.0, -80.5), c(0.0, -90.0), c(f64::NAN, 1.0)] { + assert!(to_utm(p).is_none(), "{p:?}"); + assert!(format_utm(p).is_none(), "{p:?}"); + assert!(format_mgrs(p).is_none(), "{p:?}"); + } + assert!(from_utm(0, true, 500_000.0, 0.0).is_none()); + assert!(from_utm(61, true, 500_000.0, 0.0).is_none()); + assert!(from_utm(31, true, f64::NAN, 0.0).is_none()); + assert!(from_utm(31, true, 5e6, 0.0).is_none()); + assert!(from_utm(31, true, 500_000.0, 1e7).is_none()); + assert!(to_utm_in_zone(c(100.0, 0.0), 31, true).is_none()); + assert!(to_utm_in_zone(c(3.0, 91.0), 31, true).is_none()); + } +} diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 3ad67d8cec..524825d291 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -303,16 +303,13 @@ pub fn status_bar(app: &mut RustGisApp, ui: &mut Ui) { } sep(ui, &t); // Pointer coordinates. - let coord = app - .map - .pointer_lonlat - .map(|c| if app.map.dms { rustgis_engine::geom::format_dms(c) } else { rustgis_engine::geom::format_lonlat(c) }); + let format = app.map.coord_format; let resp = ui.add( - egui::Label::new(egui::RichText::new(coord.unwrap_or_else(|| "—".into())).monospace().size(11.5).color(t.text_dim)) + egui::Label::new(egui::RichText::new(format.readout(app.map.pointer_lonlat)).monospace().size(11.5).color(t.text_dim)) .sense(Sense::click()), ); - if resp.on_hover_text(tl!("Click to switch between decimal degrees and DMS")).clicked() { - app.map.dms = !app.map.dms; + if resp.on_hover_text(format.hover()).clicked() { + let _ = app.run("ui.coordinateFormat", Value::Null); } let projection = match &app.session.map().projection { rustgis_engine::map::Projection::Globe => tl!("WGS 84 / Globe").to_string(), @@ -695,6 +692,7 @@ pub(crate) const UI_COMMANDS: &[(&str, &str, &str)] = &[ ("ui.map.gpu", "Toggle GPU Rendering", "View"), ("ui.importShapefile", "Import Shapefile with Projection…", "Home › Add"), ("ui.measurementUnits", "Toggle Imperial Measurements", "Home › Inspect › Measure"), + ("ui.coordinateFormat", "Next Coordinate Format", "View"), ("ui.moveSharedVertices", "Shared Vertices", "Edit › Features"), ("ui.traceEdges", "Trace", "Edit › Features"), ("ui.exportMap", "Export Map…", "Publish › Output"), diff --git a/crates/ui-egui/src/coordreadout.rs b/crates/ui-egui/src/coordreadout.rs new file mode 100644 index 0000000000..1ed8d10a73 --- /dev/null +++ b/crates/ui-egui/src/coordreadout.rs @@ -0,0 +1,156 @@ +//! How the pointer's coordinates read in the status bar and in the map's right-click menu: +//! decimal degrees, degrees-minutes-seconds, UTM or MGRS. 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. + +use rustgis_engine::geom::{self, Coord}; + +use crate::i18n; + +/// The preference that keeps the chosen format: its [`CoordReadout::code`]. +pub const PREF: &str = "coordinate_format"; + +/// A coordinate readout format. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum CoordReadout { + /// `12.3456° E 45.6789° N` + #[default] + Decimal, + /// `12°20′44.2″ E 45°40′44.0″ N` + Dms, + /// `33U 412345 5523456`: zone and latitude band, easting and northing in metres. + Utm, + /// `33U VP 12345 23456`: zone and band, the 100 km square, easting and northing to 1 m. + Mgrs, +} + +impl CoordReadout { + /// Every format, in the order a click steps through them. + pub const ALL: [CoordReadout; 4] = [CoordReadout::Decimal, CoordReadout::Dms, CoordReadout::Utm, CoordReadout::Mgrs]; + + /// The name commands and the preference use (never translated). + pub fn code(self) -> &'static str { + match self { + CoordReadout::Decimal => "decimal", + CoordReadout::Dms => "dms", + CoordReadout::Utm => "utm", + CoordReadout::Mgrs => "mgrs", + } + } + + /// The format a [`code`](Self::code) names, ignoring case and spaces around it. + pub fn from_code(code: &str) -> Option { + let code = code.trim(); + Self::ALL.into_iter().find(|f| f.code().eq_ignore_ascii_case(code)) + } + + /// The format after this one: decimal → DMS → UTM → MGRS → decimal. + pub fn next(self) -> Self { + match self { + CoordReadout::Decimal => CoordReadout::Dms, + CoordReadout::Dms => CoordReadout::Utm, + CoordReadout::Utm => CoordReadout::Mgrs, + CoordReadout::Mgrs => CoordReadout::Decimal, + } + } + + /// The format's name, translated in logical order, for filling into [`i18n::fmt`] messages. + pub fn label(self) -> &'static str { + match self { + CoordReadout::Decimal => tl_raw!("decimal degrees"), + CoordReadout::Dms => tl_raw!("degrees, minutes and seconds"), + CoordReadout::Utm => tl_raw!("UTM"), + CoordReadout::Mgrs => tl_raw!("MGRS"), + } + } + + /// The place in this format; for UTM and MGRS `None` outside their latitudes (80° S to + /// 84° N), and for every format `None` for a non-finite place. + pub fn format(self, c: Coord) -> Option { + if !c.is_finite() { + return None; + } + match self { + CoordReadout::Decimal => Some(geom::format_lonlat(c)), + CoordReadout::Dms => Some(geom::format_dms(c)), + CoordReadout::Utm => geom::format_utm(c), + CoordReadout::Mgrs => geom::format_mgrs(c), + } + } + + /// The status bar's readout of the pointer: `—` off the map, and a plain statement where UTM + /// and MGRS have no zone (the polar areas, which use UPS) rather than a wrong grid reference. + pub fn readout(self, c: Option) -> String { + match c { + None => "—".to_string(), + Some(c) if !c.is_finite() => "—".to_string(), + Some(c) => self.format(c).unwrap_or_else(|| outside_utm(self)), + } + } + + /// The status bar readout's hover text: the current format and what a click does. + pub fn hover(self) -> String { + i18n::fmt( + "Coordinates in {format}. Click to switch: decimal degrees, DMS, UTM, MGRS. UTM and MGRS cover 80° S to 84° N.", + &[("format", self.label())], + ) + } +} + +/// What the readout says where UTM and MGRS have no zone. +fn outside_utm(f: CoordReadout) -> String { + i18n::fmt("No {format} here: outside the UTM zones (80° S to 84° N)", &[("format", f.label())]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_click_steps_through_every_format_and_back() { + let mut f = CoordReadout::default(); + assert_eq!(f, CoordReadout::Decimal); + let mut seen = Vec::new(); + for _ in 0..4 { + seen.push(f); + f = f.next(); + } + assert_eq!(seen, CoordReadout::ALL); + assert_eq!(f, CoordReadout::Decimal); + } + + #[test] + fn codes_round_trip() { + for f in CoordReadout::ALL { + assert_eq!(CoordReadout::from_code(f.code()), Some(f)); + assert_eq!(CoordReadout::from_code(&format!(" {} ", f.code().to_uppercase())), Some(f)); + } + assert_eq!(CoordReadout::from_code("ups"), None); + assert_eq!(CoordReadout::from_code(""), None); + } + + #[test] + fn readouts_in_each_format() { + let p = Coord::new(44.4, 33.3); + assert_eq!(CoordReadout::Decimal.readout(Some(p)), "44.4000° E 33.3000° N"); + assert_eq!(CoordReadout::Dms.readout(Some(p)), "44°24′00.0″ E 33°18′00.0″ N"); + assert_eq!(CoordReadout::Utm.readout(Some(p)), "38S 444141 3684706"); + assert_eq!(CoordReadout::Mgrs.readout(Some(p)), "38S MB 44140 84706"); + for f in CoordReadout::ALL { + assert_eq!(f.readout(None), "—"); + assert_eq!(f.readout(Some(Coord::new(f64::NAN, 0.0))), "—"); + } + } + + #[test] + fn polar_places_say_they_are_outside_utm() { + let pole = Coord::new(10.0, 86.0); + for f in [CoordReadout::Utm, CoordReadout::Mgrs] { + assert_eq!(f.format(pole), None); + let r = f.readout(Some(pole)); + assert!(r.contains("outside the UTM zones") && r.contains(f.label()), "{r}"); + } + // Decimal and DMS read there as anywhere. + assert_eq!(CoordReadout::Dms.readout(Some(pole)), "10°00′00.0″ E 86°00′00.0″ N"); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a5e823b5db..94a47586cb 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -25,6 +25,7 @@ mod connectiontree; mod connectionui; #[cfg(not(target_arch = "wasm32"))] mod connectui; +mod coordreadout; mod cswui; mod cubesui; mod diagnosticlog; @@ -105,6 +106,7 @@ use serde_json::{Value, json}; pub use autosave::FolderStore; pub use autosave::{Recovery, RecoveryStore}; pub use chrome::{DoubleClick, TitlebarMetrics}; +pub use coordreadout::CoordReadout; pub use rustgis_assistant; pub use rustgis_engine; pub use widgets::big_split_menu; @@ -1225,6 +1227,14 @@ impl RustGisApp { .unwrap_or_else(|| "Meters".into()); self.ui.measurement_imperial = self.services.load_pref.as_ref().and_then(|load| load("measurement_units")).as_deref() == Some("imperial"); + // The pointer's coordinate format; an unknown or missing one reads as decimal degrees. + self.map.coord_format = self + .services + .load_pref + .as_ref() + .and_then(|load| load(coordreadout::PREF)) + .and_then(|code| CoordReadout::from_code(&code)) + .unwrap_or_default(); // The GPU map backend: RUSTGIS_GPU forces it on, else the saved preference. self.map.gpu_enabled = std::env::var_os("RUSTGIS_GPU").is_some() || self.services.load_pref.as_ref().and_then(|load| load("ui.map.gpu")).as_deref() == Some("1"); @@ -2350,6 +2360,18 @@ impl RustGisApp { save("measurement_units", if imperial { "imperial" } else { "metric" }); } } + "ui.coordinateFormat" => { + 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 decimal, dms, utm or mgrs").to_string())?, + _ => return Err(tl!("The coordinate format must be decimal, dms, utm or mgrs").into()), + }; + self.map.coord_format = format; + if let Some(save) = &self.services.save_pref { + save(coordreadout::PREF, format.code()); + } + } "ui.moveSharedVertices" => { let on = match p.get("on") { None => !self.map.move_shared_vertices, diff --git a/crates/ui-egui/src/mapmenu.rs b/crates/ui-egui/src/mapmenu.rs index bd111b768f..5d26df378a 100644 --- a/crates/ui-egui/src/mapmenu.rs +++ b/crates/ui-egui/src/mapmenu.rs @@ -6,7 +6,7 @@ use rustgis_engine::geom::Coord; use serde_json::json; use crate::widgets::{menu_row, submenu_row}; -use crate::{RustGisApp, i18n}; +use crate::{CoordReadout, RustGisApp, i18n}; /// Decimal places of the coordinates shown, copied and sent to Google (~0.1 m). const PRECISION: usize = 6; @@ -51,6 +51,19 @@ fn lat_lon(c: Coord) -> String { format!("{:.p$}, {:.p$}", c.y, c.x, p = PRECISION) } +/// The coordinate row: the text it shows and copies, in the readout's format, and whether it fell +/// back from it. Decimal degrees are `lat, lon` ([`lat_lon`]); north of 84° N or south of 80° S, +/// UTM and MGRS fall back to them (and the row's hover text says why). +fn coordinate_row(c: Coord, f: CoordReadout) -> (String, bool) { + match f { + CoordReadout::Decimal => (lat_lon(c), false), + _ => match f.format(c) { + Some(text) => (text, false), + None => (lat_lon(c), true), + }, + } +} + /// The place as a GeoJSON point feature. fn point_geojson(c: Coord) -> String { let f = json!({"type": "Feature", "geometry": {"type": "Point", "coordinates": [c.x, c.y]}, "properties": {}}); @@ -107,8 +120,17 @@ fn run(app: &mut RustGisApp, id: &str, params: serde_json::Value) { pub fn show(app: &mut RustGisApp, ui: &mut Ui, c: Coord) { let c = place(c); ui.set_min_width(240.0); - let coords = lat_lon(c); - if menu_row(ui, "locate", &coords, "", true).on_hover_text(tl!("Copy coordinates to the clipboard")).clicked() { + let format = app.map.coord_format; + let (coords, fell_back) = coordinate_row(c, format); + let hover = if fell_back { + i18n::fmt( + "Copy coordinates to the clipboard. No {format} here: outside the UTM zones (80° S to 84° N), so latitude and longitude", + &[("format", format.label())], + ) + } else { + tl!("Copy coordinates to the clipboard").to_string() + }; + if menu_row(ui, "locate", &coords, "", true).on_hover_text(hover).clicked() { ui.ctx().copy_text(coords); ui.close(); } @@ -240,4 +262,19 @@ mod tests { assert!((web_zoom(156_543.033_92, 0.0)).abs() < 1e-9); assert!(point_geojson(c).contains("\"Point\"")); } + + #[test] + fn the_coordinate_row_copies_the_chosen_format() { + let p = Coord::new(44.4, 33.3); + assert_eq!(coordinate_row(p, CoordReadout::Decimal), ("33.300000, 44.400000".into(), false)); + assert_eq!(coordinate_row(p, CoordReadout::Dms), ("44°24′00.0″ E 33°18′00.0″ N".into(), false)); + assert_eq!(coordinate_row(p, CoordReadout::Utm), ("38S 444141 3684706".into(), false)); + assert_eq!(coordinate_row(p, CoordReadout::Mgrs), ("38S MB 44140 84706".into(), false)); + // Where UTM has no zone, the row falls back to latitude and longitude (and says so). + let pole = Coord::new(10.0, 86.0); + for f in [CoordReadout::Utm, CoordReadout::Mgrs] { + assert_eq!(coordinate_row(pole, f), ("86.000000, 10.000000".into(), true), "{f:?}"); + } + assert!(!coordinate_row(pole, CoordReadout::Dms).1); + } } diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index c67b36a99d..9540a491a3 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -295,7 +295,8 @@ pub struct MapView { pub menu_lonlat: Option, /// The text graphic the context menu was opened on (layer id, row), for Edit Text. pub menu_text: Option<(u32, usize)>, - pub dms: bool, + /// How the pointer's coordinates read (status bar, right-click menu); a preference. + pub coord_format: crate::CoordReadout, pub render_ms: u64, pub notices_seen: usize, pub toasts: Vec, @@ -390,7 +391,7 @@ impl Default for MapView { pointer_lonlat: None, menu_lonlat: None, menu_text: None, - dms: false, + coord_format: crate::CoordReadout::Decimal, render_ms: 0, notices_seen: 0, toasts: Vec::new(), diff --git a/crates/ui-egui/tests/coordinate_readout.rs b/crates/ui-egui/tests/coordinate_readout.rs new file mode 100644 index 0000000000..edb9d5d98a --- /dev/null +++ b/crates/ui-egui/tests/coordinate_readout.rs @@ -0,0 +1,95 @@ +//! The status bar's coordinate readout: a click steps decimal → DMS → UTM → MGRS, the choice is +//! remembered as a preference, and the readout shows the pointer in it. + +use std::sync::{Arc, Mutex}; + +use egui_kittest::kittest::Queryable; +use rustgis_ui_egui::{CoordReadout, RustGisApp, Services}; +use serde_json::{Value, json}; + +fn harness(app: RustGisApp) -> egui_kittest::Harness<'static, RustGisApp> { + egui_kittest::Harness::builder().with_size(egui::vec2(1600.0, 900.0)).with_max_steps(64).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ) +} + +#[test] +fn the_format_cycles_persists_and_is_restored() { + let saved = Arc::new(Mutex::new(Vec::<(String, String)>::new())); + let writes = saved.clone(); + let mut app = RustGisApp::with_sample().with_services(Services { + save_pref: Some(Box::new(move |k, v| writes.lock().unwrap_or_else(|e| e.into_inner()).push((k.to_string(), v.to_string())))), + ..Services::default() + }); + assert_eq!(app.map.coord_format, CoordReadout::Decimal); + let mut seen = Vec::new(); + for _ in 0..4 { + app.run("ui.coordinateFormat", Value::Null).unwrap(); + seen.push(app.map.coord_format.code()); + } + assert_eq!(seen, ["dms", "utm", "mgrs", "decimal"]); + let writes: Vec = saved.lock().unwrap().iter().filter(|(k, _)| k == "coordinate_format").map(|(_, v)| v.clone()).collect(); + assert_eq!(writes, ["dms", "utm", "mgrs", "decimal"]); + 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": ""})] { + assert!(app.run("ui.coordinateFormat", bad.clone()).is_err(), "{bad}"); + assert_eq!(app.map.coord_format, CoordReadout::Mgrs, "{bad}"); + } + // A saved choice comes back; an unknown one reads as decimal degrees. + for (pref, want) in [("utm", CoordReadout::Utm), ("mgrs", CoordReadout::Mgrs), ("bogus", CoordReadout::Decimal)] { + let restored = RustGisApp::with_sample().with_services(Services { + load_pref: Some(Box::new(move |k| (k == "coordinate_format").then(|| pref.to_string()))), + ..Services::default() + }); + assert_eq!(restored.map.coord_format, want, "{pref}"); + } +} + +/// Points the mouse at the middle of the window, over the map, for a few frames. +fn hover_map(h: &mut egui_kittest::Harness<'_, RustGisApp>) { + for _ in 0..3 { + h.input_mut().events.push(egui::Event::PointerMoved(egui::pos2(800.0, 450.0))); + h.step(); + } +} + +#[test] +fn the_status_bar_reads_the_pointer_in_the_chosen_format_and_a_click_switches() { + let mut h = harness(RustGisApp::with_sample()); + // A view about 4 km across around Baghdad (38S MB 44140 84706, at 444141 3684706). + h.state_mut().run("map.goToXY", json!({"lon": 44.4, "lat": 33.3, "scale": 10000})).unwrap(); + hover_map(&mut h); + let at = h.state().map.pointer_lonlat.expect("the pointer is over the map"); + assert!((at.x - 44.4).abs() < 0.05 && (at.y - 33.3).abs() < 0.05, "{at:?}"); + let decimal = rustgis_engine::geom::format_lonlat(at); + h.get_by_label(&decimal).click(); + hover_map(&mut h); + assert_eq!(h.state().map.coord_format, CoordReadout::Dms); + let at = h.state().map.pointer_lonlat.unwrap(); + h.get_by_label(&rustgis_engine::geom::format_dms(at)); + h.get_by_label(&rustgis_engine::geom::format_dms(at)).click(); + hover_map(&mut h); + assert_eq!(h.state().map.coord_format, CoordReadout::Utm); + let utm = rustgis_engine::geom::format_utm(h.state().map.pointer_lonlat.unwrap()).unwrap(); + assert!(utm.starts_with("38S 44"), "{utm}"); + h.get_by_label(&utm).click(); + hover_map(&mut h); + assert_eq!(h.state().map.coord_format, CoordReadout::Mgrs); + let mgrs = rustgis_engine::geom::format_mgrs(h.state().map.pointer_lonlat.unwrap()).unwrap(); + 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::Decimal); + // Where UTM has no zone the readout says so rather than showing a wrong reference. + h.state_mut().run("ui.coordinateFormat", json!({"format": "mgrs"})).unwrap(); + h.state_mut().run("map.goToXY", json!({"lon": 10.0, "lat": 84.5, "scale": 10000})).unwrap(); + hover_map(&mut h); + assert!(h.state().map.pointer_lonlat.is_some_and(|c| c.y > 84.0)); + h.get_by_label("No MGRS here: outside the UTM zones (80° S to 84° N)"); +} diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index 4398d85e77..d17d7f917c 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -96,7 +96,8 @@ 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 switch between decimal degrees and DMS), the coordinate system (click it to change the + to step through decimal degrees, DMS, UTM and MGRS; 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 **Diagnostics**), a **Diagnostics** button, the last draw time, the frame rate and a **GPU**/**CPU** renderer switch. While agents control the desktop app, it also shows the MCP relay or file bridge. diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index d9744cb1e6..1fdcf78578 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -110,7 +110,8 @@ zooms to the one picked. The search goes to that server over the network; see The **search box** at the foot of the left pane searches the map as you type: a latitude and longitude (`40.7, -74.0`, `40.7N 74W` or `40°42'46"N 74°0'21"W`; latitude first unless the -letters or a number past ±90 say otherwise), the map's layers and bookmarks by name, and the +letters or a number past ±90 say otherwise), a UTM position or an MGRS reference (see +[Coordinate readouts](#coordinate-readouts)), the map's layers and bookmarks by name, and the values in its layers' attribute tables (the best few per layer, by the feature's name where it has one). Places come from Nominatim when you press ++enter++ on **Search places**, since the public servers don't allow searching as you type. The arrow keys move through the list and ++enter++ @@ -122,15 +123,54 @@ the command line or a script, and goes to a hit with `"go"`: rustgis-cli run --sample --cmd 'map.search={"query":"Tokyo","go":true}' ``` -**Right-click the map** for a menu about that place. Its first row shows the latitude and -longitude; click it to copy them. Below it, **Copy As GeoJSON** copies the place as a point -feature, **Center Map Here** and **Zoom In Here** move the view, and **Directions To Here** and +**Right-click the map** for a menu about that place. Its first row shows the place in the status +bar's coordinate format (latitude and longitude as `40.712800, -74.006000` for decimal degrees); +click it to copy it. North of 84° N and south of 80° S, where UTM and MGRS have no zone, it shows +and copies the latitude and longitude, and its hover text says why. Below it, **Copy As GeoJSON** +copies the place as a point feature, **Center Map Here** and **Zoom In Here** move the view, and **Directions To Here** and **Directions From Here** open the [Directions](#directions) pane. **Quick Analysis** runs a tool at the place: a buffer of 500 m, 1 km or 5 km (¼, 1 or 5 miles when the Directions pane is set to miles; `gp.bufferPoint`), a viewshed of 2, 5 or 15 km or a line of sight on an elevation raster in the map, and **Open In Geoprocessing…** opens the Buffer tool. **View In Google Maps** and **View In Google Earth** open the place in your browser at about the same zoom. +### Coordinate readouts + +The status bar shows the pointer's coordinates. Click them to step through four formats; the +choice is remembered and also sets the right-click menu's first row. The same place in each: + +| Format | Example | | +| --- | --- | --- | +| Decimal degrees | `15.3000° E 49.8500° N` | four decimal places | +| DMS | `15°18′00.0″ E 49°51′00.0″ N` | degrees, minutes and seconds | +| UTM | `33U 521567 5521996` | zone and latitude band, easting and northing in metres, rounded to the metre | +| MGRS | `33U WR 21566 21996` | zone and band, the 100 km square, easting and northing within it, truncated to the metre | + +UTM and MGRS are on WGS 84, with the zone exceptions for southern Norway (32V) and Svalbard (31X, +33X, 35X and 37X), and cover 80° S to 84° N. Nearer the poles they would need the Universal Polar +Stereographic grid, which RustGIS doesn't have: there the readout says it is outside the UTM +zones rather than show a wrong reference. Scripts set the format with +`ui.coordinateFormat={"format":"utm"}` (`decimal`, `dms`, `utm` or `mgrs`); without `format` +it steps to the next one. + +The [search box](#navigating) takes the same grid references, in any case: + +- **MGRS** with or without spaces: `33UWR2156621996`, `33U WR 21566 21996`, `33UWR 2156 2199`, + or a 100 km square alone, `33UWR`. The digits are an even count from 0 to 10, half for the + easting and half for the northing, and the search goes to the middle of the square they name. + A 100 km square is also looked for in the attribute tables, since Sentinel-2 tiles are named + after them. +- **UTM** as the readout writes it, zone and latitude band: `33U 521567 5521996`; or the zone + and hemisphere spelt out: `33 north 521567 5521996`, `21 south 371625 6170423`. `33N` reads + as the northern hemisphere when the northing isn't in band N, since both readings agree. + `S` after the zone is always band S (32° N to 40° N), as in `11S 384629 3768405` (Los + Angeles); with a northing outside band S it could mean the southern hemisphere, so it finds + nothing: write `south` instead. + +A reference that doesn't exist (square letters the zone doesn't use, a northing outside the band, +an odd number of digits, a place outside the zone) finds nothing rather than a place somewhere +else. + ### Directions **Directions** (Home › Navigate) plans a route between places and follows it turn by turn, with From 88c0f84817a6b71b8c474a7742efaddec81bd783 Mon Sep 17 00:00:00 2001 From: PawelKra <15887575+PawelKra@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:21:11 +0100 Subject: [PATCH 2/7] fix(geom): MGRS squares must reach their band, two-digit zones, grid refusals say why MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 100 km square was read in a band when its centre lay within a cell's size of it, about 0.9°, so 38TMJ, which ends at 39.7° N, was accepted in band T. The cell's lowest and highest latitudes now come from its corners (a cell never straddles the central meridian), and the cell must reach into the band, give or take the metre a position is rounded to. Just south of the equator a northing could round to the full 10,000 km false northing and give row A of band M, which reads back nowhere; it is kept a metre short, in row V. MGRS writes zones 1-9 with two digits (04QFJ), and still reads one. A UTM position past 84° N or 80° S is polar in the band form too, with the same one-metre allowance as the hemisphere form. Search kept the reason a grid reference was refused to itself, so a typo read as nothing found. The search list now says why (the band, the square letters, S that may mean south), map.search returns it as gridError, and "go" fails with it. UTM and MGRS are the Earth's grids: on another body's map the status bar shows "No UTM here", the right-click row copies latitude and longitude, and search reads no grid references. Where UTM has no zone the status bar now says "No UTM here" (the hover text says why), no wider than a reference, so it no longer pushes the status bar's other items aside. --- crates/engine/src/cmd/search.rs | 92 ++++++++-- crates/geom/src/utm.rs | 187 ++++++++++++++++++--- crates/ui-egui/src/chrome.rs | 7 +- crates/ui-egui/src/coordreadout.rs | 72 +++++--- crates/ui-egui/src/mapmenu.rs | 32 ++-- crates/ui-egui/src/searchbox.rs | 78 ++++++++- crates/ui-egui/tests/coordinate_readout.rs | 11 +- docs/user-guide/maps.md | 22 ++- 8 files changed, 420 insertions(+), 81 deletions(-) diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index a0d792d561..8998a74d4c 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -7,7 +7,7 @@ use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use rustgis_data::Value as Attr; -use rustgis_geom::{Coord, Extent}; +use rustgis_geom::{Coord, Extent, GridError}; use serde_json::{Value, json}; use super::{f, ps}; @@ -132,6 +132,10 @@ impl Hit { pub struct Results { pub hits: Vec, pub partial: Vec, + /// Why the query, written as a UTM position or an MGRS reference, names no place (a band + /// 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, } /// Searches the active map for `query`: a coordinate first, then layers, bookmarks and features. @@ -144,14 +148,21 @@ pub fn search(s: &Session, query: &str, limit: usize) -> Results { // A query that is plainly a coordinate (a decimal point, a degree mark, a hemisphere, a UTM // zone and band) isn't looked for in the tables; two whole numbers (an id, years, a range) // may be either, and so may a bare 100 km MGRS square, which names Sentinel-2's tiles (33UVP); - // an MGRS reference with digits is plainly a coordinate. + // an MGRS reference with digits is plainly a coordinate. UTM and MGRS are the Earth's grids, + // so on another body's map they name no place. let mut plainly_coordinate = false; if let Some(c) = parse_lat_lon(&q) { 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(c) = parse_grid_reference(&q) { - out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); - plainly_coordinate = rustgis_geom::parse_mgrs(&q).map_or(true, |m| m.digits > 0); + } else if s.map().body().is_earth() { + match read_grid_reference(&q) { + Ok(c) => { + out.hits.push(Hit::Coordinate { lon: c.x, lat: c.y }); + plainly_coordinate = rustgis_geom::parse_mgrs(&q).map_or(true, |m| m.digits > 0); + } + Err(GridError::Syntax) => {} + Err(e) => out.grid_error = Some(e), + } } let needle = q.to_lowercase(); let map = s.map(); @@ -339,20 +350,36 @@ fn search_cmd(s: &mut Session, p: &Value) -> CmdResult { ), }; if let Some(i) = pick { - let hit = - r.hits.get(i).ok_or_else(|| if r.hits.is_empty() { format!("nothing matches '{query}'") } else { format!("no hit {i}") })?; + let hit = 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}"), + })?; go_to(s, hit)?; } - Ok(json!({"hits": r.hits.iter().map(Hit::to_json).collect::>(), "partial": r.partial})) + let mut out = json!({"hits": r.hits.iter().map(Hit::to_json).collect::>(), "partial": r.partial}); + if let Some(e) = r.grid_error { + out["gridError"] = json!(e.to_string()); + } + Ok(out) } /// A place typed as an MGRS reference (the centre of the square it names) or a UTM position, in /// the forms [`rustgis_geom::parse_mgrs`] and [`rustgis_geom::parse_utm`] accept; `None` for /// anything else, an ambiguous UTM zone letter or a reference that names no place. pub fn parse_grid_reference(text: &str) -> Option { + read_grid_reference(text).ok() +} + +/// As [`parse_grid_reference`], with why a reference was refused: [`GridError::Syntax`] for text +/// written as neither form, otherwise the reason of the form it was written in. +pub fn read_grid_reference(text: &str) -> Result { match rustgis_geom::parse_mgrs(text) { - Ok(m) => m.centre().ok(), - Err(_) => rustgis_geom::parse_utm(text).ok(), + Ok(m) => m.centre(), + Err(mgrs) => match rustgis_geom::parse_utm(text) { + Err(GridError::Syntax) => Err(mgrs), + utm => utm, + }, } } @@ -628,6 +655,35 @@ mod tests { assert!(parse_grid_reference(q).is_none(), "{q}"); assert!(!search(&s, q, 50).hits.iter().any(|h| matches!(h, Hit::Coordinate { .. })), "{q}"); } + // The reason a reference was refused comes with the results and the command's answer, + // rather than reading as nothing found. + for (q, why) in [ + ("33S 412345 5523456", GridError::Ambiguous), + ("33T 412345 5523456", GridError::BandMismatch), + ("38SAB4414084706", GridError::Square), + ("38SMB441408470", GridError::Digits), + ("38TMB4414084706", GridError::BandMismatch), + ("38TMJ", GridError::BandMismatch), + ("38Z 444141 3684706", GridError::Polar), + ("38ZMB4414084706", GridError::Polar), + ("99X 1 2", GridError::Zone), + ("33U 1000000 5523456", GridError::OutsideZone), + ] { + assert_eq!(read_grid_reference(q), Err(why), "{q}"); + assert_eq!(search(&s, q, 50).grid_error, Some(why), "{q}"); + } + // Text not written as a grid reference, and references that read, carry no reason. + for q in ["1C", "Paris", "Countries", "12 Main St", "2020", "40.7, -74.0", "38SMB", "38S 444141 3684706", "10 20"] { + assert_eq!(search(&s, q, 50).grid_error, None, "{q}"); + } + let mut s = s; + let v = s.run("map.search", &json!({"query": "33S 412345 5523456"})).unwrap(); + assert!(v["gridError"].as_str().is_some_and(|e| e.contains("south")), "{v}"); + assert!(s.run("map.search", &json!({"query": "Paris"})).unwrap().get("gridError").is_none()); + let e = s.run("map.search", &json!({"query": "33S 412345 5523456", "go": true})).unwrap_err(); + assert!(e.contains("nothing matches") && e.contains("33 south"), "{e}"); + let e = s.run("map.search", &json!({"query": "Zzyzx Qq", "go": true})).unwrap_err(); + assert_eq!(e, "nothing matches 'Zzyzx Qq'"); // MGRS-looking garbage never panics. let mut r = 1u64; let alphabet: Vec = "0123456789 ACHINOSUVXZacz.-,°\u{0}é٣".chars().collect(); @@ -642,6 +698,22 @@ mod tests { } } + /// UTM and MGRS are the Earth's grids: on another body's map they find no place (and give + /// no reason), while a latitude and longitude still does. + #[test] + fn grid_references_are_the_earths() { + let mut s = Session::new(crate::sample::world_project()); + s.run("map.body", &json!({"name": "mars", "basemap": false})).unwrap(); + for q in ["38SMB4414084706", "38S 444141 3684706", "33S 412345 5523456"] { + let r = search(&s, q, 50); + assert!(!r.hits.iter().any(|h| matches!(h, Hit::Coordinate { .. })), "{q}: {r:?}"); + assert_eq!(r.grid_error, None, "{q}"); + } + assert!(matches!(search(&s, "33.3, 44.4", 50).hits.first(), Some(Hit::Coordinate { .. }))); + s.run("map.body", &json!({"name": "earth", "basemap": false})).unwrap(); + assert!(matches!(search(&s, "38SMB4414084706", 50).hits.first(), Some(Hit::Coordinate { .. }))); + } + #[test] fn non_coordinates_are_refused() { for t in diff --git a/crates/geom/src/utm.rs b/crates/geom/src/utm.rs index e6bf6d4933..bd0f638cf7 100644 --- a/crates/geom/src/utm.rs +++ b/crates/geom/src/utm.rs @@ -14,7 +14,9 @@ //! 32X, 34X and 36X don't exist), latitude bands C to X of 8° (X runs 12°, from 72° N to 84° N), //! and the 100 km squares of the AA lettering scheme used on WGS 84: column letters A–H, J–R and //! S–Z by zone in turn, row letters A–V (no I or O) from the equator, starting at F in even zones. -//! A reference truncates its easting and northing to its precision, it doesn't round them. +//! A reference truncates its easting and northing to its precision, it doesn't round them, and +//! writes the zone with two digits (`04QFJ`), so references line up and sort; one digit is read +//! as well. //! //! Only the UTM latitudes, 80° S to 84° N, are covered: the polar areas use the Universal Polar //! Stereographic (UPS) grid, which isn't implemented. There the functions return `None`, and a @@ -45,8 +47,8 @@ const ROW_CYCLE: f64 = 2_000_000.0; /// the position they give is still the right one. A band's latitudes get no such allowance: the /// band is the latitude's own letter, so a reference in the wrong band is refused. const EDGE_SLOP_DEG: f64 = 0.5; -/// How far (degrees) a place may lie outside its band, or past the UTM limits, for rounding: about -/// a metre, the precision a UTM position is written to. +/// How far (degrees) a place, or the nearest part of a cell, may lie outside its band, or past the +/// UTM limits, for rounding: about a metre, the precision a UTM position is written to. const ROUNDING_DEG: f64 = 1.0 / M_PER_DEG; /// Metres per degree of latitude, roughly, for turning a cell's size into degrees. const M_PER_DEG: f64 = 111_000.0; @@ -313,9 +315,9 @@ impl Mgrs { 10f64.powi(5 - i32::from(self.digits.min(5))) } - /// Without spaces: `33UVP1234523456`. + /// Without spaces: `33UVP1234523456`, `04QFJ12345678`. pub fn compact(&self) -> String { - format!("{}{}{}{}{}", self.zone, self.band, self.column, self.row, self.digit_groups().concat()) + format!("{:02}{}{}{}{}", self.zone, self.band, self.column, self.row, self.digit_groups().concat()) } /// The easting and northing digits, zero-padded to the precision (empty for 100 km). @@ -334,9 +336,9 @@ impl Mgrs { } impl fmt::Display for Mgrs { - /// `33U VP 12345 23456` (the readout's form; `33U VP` at 100 km). + /// `33U VP 12345 23456` (the readout's form; `33U VP` at 100 km; `04Q FJ …` in zones 1–9). fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}{} {}{}", self.zone, self.band, self.column, self.row)?; + write!(f, "{:02}{} {}{}", self.zone, self.band, self.column, self.row)?; let [e, n] = self.digit_groups(); if !e.is_empty() { write!(f, " {e} {n}")?; @@ -350,8 +352,13 @@ impl fmt::Display for Mgrs { pub fn to_mgrs(c: Coord, digits: u8) -> Option { let digits = digits.min(5); let u = to_utm(c)?; - // Whole metres first, truncated, so the square letters and the digits agree at an edge. - let (e, n) = (u.easting.floor(), u.northing.floor()); + // Whole metres first, truncated, so the square letters and the digits agree at an edge. Just + // south of the equator the northing can round up to the full 10,000 km false northing, which + // is the equator itself and row A of band N: it is kept a metre short, in row V of band M. + let (e, mut n) = (u.easting.floor(), u.northing.floor()); + if !u.north() { + n = n.min(FALSE_NORTHING_SOUTH - 1.0); + } if !(SQUARE..9.0 * SQUARE).contains(&e) || !(0.0..=FALSE_NORTHING_SOUTH).contains(&n) { return None; } @@ -420,12 +427,13 @@ impl fmt::Display for GridError { impl std::error::Error for GridError {} -/// Whether a place found from a zone and band lies in them, give or take `cell_m` (the size of -/// the cell a reference names), and for the zone's longitudes [`EDGE_SLOP_DEG`]. -fn check_place(p: Coord, zone: u8, band: char, cell_m: f64) -> Result<(), GridError> { +/// Whether a place found from a zone and band lies in them. `lats` are the lowest and highest +/// latitudes of the cell the reference names (the place's own for a UTM position): the cell must +/// reach into the band, give or take [`ROUNDING_DEG`]. The place may lie outside the zone's +/// longitudes by `cell_m` (the cell's size) and [`EDGE_SLOP_DEG`]. +fn check_place(p: Coord, lats: (f64, f64), zone: u8, band: char, cell_m: f64) -> Result<(), GridError> { let (south, north) = band_latitudes(band).ok_or(GridError::Band)?; - let lat_slop = cell_m / M_PER_DEG + ROUNDING_DEG; - if p.y < south - lat_slop || p.y > north + lat_slop { + if lats.1 < south - ROUNDING_DEG || lats.0 > north + ROUNDING_DEG { return Err(GridError::BandMismatch); } let (west, east) = zone_longitudes(zone, band).ok_or(GridError::OutsideZone)?; @@ -438,7 +446,25 @@ fn check_place(p: Coord, zone: u8, band: char, cell_m: f64) -> Result<(), GridEr Ok(()) } -/// The centre of the cell an MGRS reference names: the 2,000 km row cycle is settled by the band. +/// The lowest and highest latitudes of a grid cell (south-west corner `e0`, `n0`, side `cell`). +/// Along a line of constant easting the latitude grows with the northing, and along a line of +/// constant northing it lies farthest from the equator on the central meridian. A cell never +/// straddles the central meridian (its 500 km easting is a multiple of every cell size), so the +/// extremes are at its corners. `None` if a corner names no place (past a pole). +fn cell_latitudes(zone: u8, north: bool, e0: f64, n0: f64, cell: f64) -> Option<(f64, f64)> { + let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); + for e in [e0, e0 + cell] { + for n in [n0, n0 + cell] { + let p = from_utm(zone, north, e, n)?; + lo = lo.min(p.y); + hi = hi.max(p.y); + } + } + Some((lo, hi)) +} + +/// The centre of the cell an MGRS reference names: the 2,000 km row cycle is settled by the band, +/// which the cell must reach into. fn locate(m: &Mgrs) -> Result { if !(1..=60).contains(&m.zone) { return Err(GridError::Zone); @@ -459,14 +485,16 @@ fn locate(m: &Mgrs) -> Result { if f64::from(m.easting) * cell >= SQUARE || f64::from(m.northing) * cell >= SQUARE { return Err(GridError::Digits); } - let easting = (col as f64 + 1.0) * SQUARE + f64::from(m.easting) * cell + cell / 2.0; - let northing = row * SQUARE + f64::from(m.northing) * cell + cell / 2.0; + let e0 = (col as f64 + 1.0) * SQUARE + f64::from(m.easting) * cell; + let n0 = row * SQUARE + f64::from(m.northing) * cell; let north = south >= 0.0; // Of the five northings the letters can stand for (0 to 10,000 km), the one in the band. let mut found = None; for k in 0..5 { - let Some(p) = from_utm(m.zone, north, easting, northing + f64::from(k) * ROW_CYCLE) else { continue }; - match check_place(p, m.zone, m.band, cell) { + let n0 = n0 + f64::from(k) * ROW_CYCLE; + let Some(p) = from_utm(m.zone, north, e0 + cell / 2.0, n0 + cell / 2.0) else { continue }; + let Some(lats) = cell_latitudes(m.zone, north, e0, n0, cell) else { continue }; + match check_place(p, lats, m.zone, m.band, cell) { Ok(()) => { found = Some(p); break; @@ -608,7 +636,7 @@ pub fn parse_utm(text: &str) -> Result { return Err(GridError::Polar); } let band = latitude_band(p.y.clamp(UTM_MIN_LAT, UTM_MAX_LAT - 1e-9)).ok_or(GridError::Polar)?; - check_place(p, zone, band, 1.0).map(|()| p) + check_place(p, (p.y, p.y), zone, band, 1.0).map(|()| p) }; match word.as_str() { "NORTH" => by_hemisphere(true), @@ -617,7 +645,11 @@ pub fn parse_utm(text: &str) -> Result { let band = band_letter(letter)?; let north = band >= 'N'; let p = from_utm(zone, north, easting, northing).ok_or(GridError::OutsideZone)?; - match check_place(p, zone, band, 1.0) { + // Past 84° N or 80° S is polar, as in the hemisphere form, whatever the band says. + if p.y >= UTM_MAX_LAT + ROUNDING_DEG || p.y < UTM_MIN_LAT - ROUNDING_DEG { + return Err(GridError::Polar); + } + match check_place(p, (p.y, p.y), zone, band, 1.0) { Ok(()) => Ok(p), Err(GridError::BandMismatch) if band == 'N' => by_hemisphere(true), Err(GridError::BandMismatch) if band == 'S' => Err(GridError::Ambiguous), @@ -1038,6 +1070,119 @@ mod tests { assert!(parse_utm(&format!("33 north {} {}", e.round(), n.round())).is_ok()); } + /// Zones 1–9 are written with two digits, in the readout and without spaces, and read back. + #[test] + fn one_digit_zones_are_written_with_two() { + let m = to_mgrs(c(central_meridian(1), 0.5), 5).unwrap(); + assert_eq!(m.zone, 1); + assert!(m.to_string().starts_with("01N EA "), "{m}"); + assert!(m.compact().starts_with("01NEA"), "{}", m.compact()); + for text in [m.to_string(), m.compact(), m.compact().replacen("01", "1", 1)] { + assert_eq!(parse_mgrs(&text), Ok(m), "{text}"); + } + assert_eq!(to_mgrs(c(central_meridian(9), 10.0), 0).unwrap().to_string(), "09P WM"); + assert_eq!(to_mgrs(c(central_meridian(10), 10.0), 0).unwrap().to_string(), "10P ES"); + // UTM keeps the zone as it is numbered (EPSG:32604), like GeographicLib's `4n`. + assert!(format_utm(c(central_meridian(4), 20.0)).unwrap().starts_with("4Q ")); + } + + /// Just south of the equator the northing rounds to the full false northing (10,000 km, which + /// is the equator, row A of band N): the reference stays in row V of band M and reads back. + #[test] + fn a_northing_just_south_of_the_equator_stays_in_band_m() { + // A latitude a few 1e-15 degrees south: in band M, yet its northing rounds to 10,000 km. + let p = (1..400) + .map(|i| c(15.0, -1e-17 * f64::from(i) * 5.0)) + .find(|p| to_utm(*p).is_some_and(|u| u.band == 'M' && u.northing == FALSE_NORTHING_SOUTH)) + .expect("a place in band M whose northing rounds to the false northing"); + assert_eq!(to_utm(p).map(|u| u.zone), Some(33)); + for d in 0u8..=5 { + let m = to_mgrs(p, d).unwrap(); + assert_eq!((m.band, m.row), ('M', 'V'), "{m}"); + assert_eq!(parse_mgrs(&m.compact()), Ok(m), "{m}"); + } + assert_eq!(to_mgrs(p, 5).unwrap().northing, 99_999); + // The equator itself and the north are untouched. + assert_eq!(to_mgrs(c(15.0, 0.0), 5).unwrap().compact(), "33NWA0000000000"); + } + + /// A cell is read in a band only if it reaches into it. 38T MJ (4,300–4,400 km north, in zone + /// 38's rows) ends at 39.7° N, short of band T's 40° N, while 38T MK crosses 40° N and is read + /// in either band; 38S MJ lies in band S. + #[test] + fn a_square_must_reach_into_its_band() { + assert_eq!(parse_mgrs("38TMJ"), Err(GridError::BandMismatch)); + assert_eq!(parse_mgrs("38TMJ 5 9"), Err(GridError::BandMismatch)); + for ok in ["38TMK", "38SMK", "38SMJ", "38TMK 5 2", "38SMK 5 2"] { + assert!(parse_mgrs(ok).is_ok(), "{ok}"); + } + // 40° N is about 4,428 km north on the central meridian, in 38S MK's third 10 km row: + // the row above it isn't in band S, the row below it isn't in T. + assert_eq!(parse_mgrs("38SMK 5 4"), Err(GridError::BandMismatch)); + assert_eq!(parse_mgrs("38TMK 5 1"), Err(GridError::BandMismatch)); + // The 100 km square holding 48° N in zone 33, wide of the central meridian where the + // parallel bends south across the square: read in both bands. + for p in [c(12.1, 48.0001), c(12.1, 47.9999), c(17.9, 48.0001), c(17.9, 47.9999)] { + let m = to_mgrs(p, 0).unwrap(); + let other = if m.band == 'U' { 'T' } else { 'U' }; + let swapped = Mgrs { band: other, ..m }; + assert!(parse_mgrs(&m.compact()).is_ok(), "{m}"); + assert!(parse_mgrs(&swapped.compact()).is_ok(), "{swapped}"); + } + } + + /// Every reference the readout writes reads back to itself, at every precision, at random and + /// at the band edges (where a cell only partly in its band must still be read). + #[test] + fn every_precision_round_trips_at_band_edges() { + let mut r = Lcg(23); + let mut edges: Vec = (0..20).map(|i| UTM_MIN_LAT + 8.0 * f64::from(i)).collect(); + edges.push(UTM_MAX_LAT); + for edge in edges { + for off in [-0.3, -1e-4, -1e-7, 0.0, 1e-7, 1e-4, 0.3] { + let lat = edge + off; + if !(UTM_MIN_LAT..UTM_MAX_LAT).contains(&lat) { + continue; + } + for _ in 0..60 { + let lon = -180.0 + r.next() * 360.0; + for d in 0u8..=5 { + let m = to_mgrs(c(lon, lat), d).unwrap(); + assert_eq!(parse_mgrs(&m.compact()), Ok(m), "{m} at {lon} {lat}"); + } + } + } + } + for _ in 0..3_000 { + let p = c(-180.0 + r.next() * 360.0, UTM_MIN_LAT + r.next() * (UTM_MAX_LAT - UTM_MIN_LAT - 1e-6)); + let d = (r.next() * 6.0) as u8; + let m = to_mgrs(p, d).unwrap(); + assert_eq!(parse_mgrs(&m.to_string()), Ok(m), "{m} at {p:?}"); + } + } + + /// Past 84° N or 80° S by more than the metre a position is rounded to, a UTM position is + /// polar whether it is written with band X or C or with the hemisphere. + #[test] + fn utm_past_the_limits_is_polar_in_either_form() { + let metres = |m: f64| m / M_PER_DEG; + for (lat, band, north) in [(UTM_MAX_LAT + metres(1.5), 'X', true), (UTM_MIN_LAT - metres(1.5), 'C', false)] { + let (e, n) = to_utm_in_zone(c(15.0, lat), 33, north).unwrap(); + let (e, n) = (e.round(), n.round()); + let hemi = if north { "north" } else { "south" }; + assert_eq!(parse_utm(&format!("33{band} {e} {n}")), Err(GridError::Polar), "{lat}"); + assert_eq!(parse_utm(&format!("33 {hemi} {e} {n}")), Err(GridError::Polar), "{lat}"); + } + // Within the limits, by a metre, both forms read. + for (lat, band, north) in [(UTM_MAX_LAT - metres(1.0), 'X', true), (UTM_MIN_LAT + metres(1.0), 'C', false)] { + let (e, n) = to_utm_in_zone(c(15.0, lat), 33, north).unwrap(); + let (e, n) = (e.round(), n.round()); + let hemi = if north { "north" } else { "south" }; + assert!(parse_utm(&format!("33{band} {e} {n}")).is_ok(), "{lat}"); + assert!(parse_utm(&format!("33 {hemi} {e} {n}")).is_ok(), "{lat}"); + } + } + #[test] fn outside_utm_is_said_not_guessed() { for p in [c(0.0, 84.0), c(10.0, 89.9), c(0.0, 90.0), c(-60.0, -80.5), c(0.0, -90.0), c(f64::NAN, 1.0)] { diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 524825d291..c2187fbfec 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -304,9 +304,12 @@ pub fn status_bar(app: &mut RustGisApp, ui: &mut Ui) { sep(ui, &t); // Pointer coordinates. let format = app.map.coord_format; + let earth = app.session.map().body().is_earth(); let resp = ui.add( - egui::Label::new(egui::RichText::new(format.readout(app.map.pointer_lonlat)).monospace().size(11.5).color(t.text_dim)) - .sense(Sense::click()), + egui::Label::new( + egui::RichText::new(format.readout(app.map.pointer_lonlat, earth)).monospace().size(11.5).color(t.text_dim), + ) + .sense(Sense::click()), ); if resp.on_hover_text(format.hover()).clicked() { let _ = app.run("ui.coordinateFormat", Value::Null); diff --git a/crates/ui-egui/src/coordreadout.rs b/crates/ui-egui/src/coordreadout.rs index 1ed8d10a73..9fc3ceb80c 100644 --- a/crates/ui-egui/src/coordreadout.rs +++ b/crates/ui-egui/src/coordreadout.rs @@ -64,10 +64,16 @@ impl CoordReadout { } } + /// Whether this is a grid of the Earth (UTM, MGRS), which names no place on another body. + pub fn earth_only(self) -> bool { + matches!(self, CoordReadout::Utm | CoordReadout::Mgrs) + } + /// The place in this format; for UTM and MGRS `None` outside their latitudes (80° S to - /// 84° N), and for every format `None` for a non-finite place. - pub fn format(self, c: Coord) -> Option { - if !c.is_finite() { + /// 84° N) and on another body's map (`earth` false), and for every format `None` for a + /// non-finite place. + pub fn format(self, c: Coord, earth: bool) -> Option { + if !c.is_finite() || (self.earth_only() && !earth) { return None; } match self { @@ -78,30 +84,28 @@ impl CoordReadout { } } - /// The status bar's readout of the pointer: `—` off the map, and a plain statement where UTM - /// and MGRS have no zone (the polar areas, which use UPS) rather than a wrong grid reference. - pub fn readout(self, c: Option) -> String { + /// The status bar's readout of the pointer: `—` off the map, and a short statement where UTM + /// and MGRS have no zone (the polar areas, which use UPS, and other bodies) rather than a + /// wrong grid reference; the [`hover`](Self::hover) text says why. It is no wider than a + /// reference, so the status bar keeps its room. + pub fn readout(self, c: Option, earth: bool) -> String { match c { None => "—".to_string(), Some(c) if !c.is_finite() => "—".to_string(), - Some(c) => self.format(c).unwrap_or_else(|| outside_utm(self)), + Some(c) => self.format(c, earth).unwrap_or_else(|| i18n::fmt("No {format} here", &[("format", self.label())])), } } - /// The status bar readout's hover text: the current format and what a click does. + /// The status bar readout's hover text: the current format, what a click does, and where + /// UTM and MGRS read. pub fn hover(self) -> String { i18n::fmt( - "Coordinates in {format}. Click to switch: decimal degrees, DMS, UTM, MGRS. UTM and MGRS cover 80° S to 84° N.", + "Coordinates in {format}. Click to switch: decimal degrees, DMS, UTM, MGRS. UTM and MGRS cover the Earth from 80° S to 84° N.", &[("format", self.label())], ) } } -/// What the readout says where UTM and MGRS have no zone. -fn outside_utm(f: CoordReadout) -> String { - i18n::fmt("No {format} here: outside the UTM zones (80° S to 84° N)", &[("format", f.label())]) -} - #[cfg(test)] mod tests { use super::*; @@ -132,13 +136,15 @@ mod tests { #[test] fn readouts_in_each_format() { let p = Coord::new(44.4, 33.3); - assert_eq!(CoordReadout::Decimal.readout(Some(p)), "44.4000° E 33.3000° N"); - assert_eq!(CoordReadout::Dms.readout(Some(p)), "44°24′00.0″ E 33°18′00.0″ N"); - assert_eq!(CoordReadout::Utm.readout(Some(p)), "38S 444141 3684706"); - assert_eq!(CoordReadout::Mgrs.readout(Some(p)), "38S MB 44140 84706"); + assert_eq!(CoordReadout::Decimal.readout(Some(p), true), "44.4000° E 33.3000° N"); + assert_eq!(CoordReadout::Dms.readout(Some(p), true), "44°24′00.0″ E 33°18′00.0″ N"); + assert_eq!(CoordReadout::Utm.readout(Some(p), true), "38S 444141 3684706"); + assert_eq!(CoordReadout::Mgrs.readout(Some(p), true), "38S MB 44140 84706"); for f in CoordReadout::ALL { - assert_eq!(f.readout(None), "—"); - assert_eq!(f.readout(Some(Coord::new(f64::NAN, 0.0))), "—"); + for earth in [true, false] { + assert_eq!(f.readout(None, earth), "—"); + assert_eq!(f.readout(Some(Coord::new(f64::NAN, 0.0)), earth), "—"); + } } } @@ -146,11 +152,29 @@ mod tests { fn polar_places_say_they_are_outside_utm() { let pole = Coord::new(10.0, 86.0); for f in [CoordReadout::Utm, CoordReadout::Mgrs] { - assert_eq!(f.format(pole), None); - let r = f.readout(Some(pole)); - assert!(r.contains("outside the UTM zones") && r.contains(f.label()), "{r}"); + assert_eq!(f.format(pole, true), None); + let r = f.readout(Some(pole), true); + assert_eq!(r, format!("No {} here", f.label())); + // No wider than the reference it stands for, in the status bar. + assert!(r.chars().count() <= f.readout(Some(Coord::new(44.4, 33.3)), true).chars().count(), "{r}"); + assert!(f.hover().contains("80° S to 84° N")); } // Decimal and DMS read there as anywhere. - assert_eq!(CoordReadout::Dms.readout(Some(pole)), "10°00′00.0″ E 86°00′00.0″ N"); + assert_eq!(CoordReadout::Dms.readout(Some(pole), true), "10°00′00.0″ E 86°00′00.0″ N"); + } + + /// On another body's map UTM and MGRS, the Earth's grids, read nothing; degrees still do. + #[test] + fn grids_are_the_earths() { + let p = Coord::new(44.4, 33.3); + for f in [CoordReadout::Utm, CoordReadout::Mgrs] { + assert_eq!(f.format(p, false), None); + assert_eq!(f.readout(Some(p), false), format!("No {} here", f.label())); + assert!(f.earth_only()); + } + for f in [CoordReadout::Decimal, CoordReadout::Dms] { + assert_eq!(f.format(p, false), f.format(p, true)); + assert!(!f.earth_only()); + } } } diff --git a/crates/ui-egui/src/mapmenu.rs b/crates/ui-egui/src/mapmenu.rs index 5d26df378a..e0a828540b 100644 --- a/crates/ui-egui/src/mapmenu.rs +++ b/crates/ui-egui/src/mapmenu.rs @@ -53,11 +53,12 @@ fn lat_lon(c: Coord) -> String { /// The coordinate row: the text it shows and copies, in the readout's format, and whether it fell /// back from it. Decimal degrees are `lat, lon` ([`lat_lon`]); north of 84° N or south of 80° S, -/// UTM and MGRS fall back to them (and the row's hover text says why). -fn coordinate_row(c: Coord, f: CoordReadout) -> (String, bool) { +/// and on another body's map (`earth` false), UTM and MGRS fall back to them (and the row's hover +/// text says why). +fn coordinate_row(c: Coord, f: CoordReadout, earth: bool) -> (String, bool) { match f { CoordReadout::Decimal => (lat_lon(c), false), - _ => match f.format(c) { + _ => match f.format(c, earth) { Some(text) => (text, false), None => (lat_lon(c), true), }, @@ -121,8 +122,14 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, c: Coord) { let c = place(c); ui.set_min_width(240.0); let format = app.map.coord_format; - let (coords, fell_back) = coordinate_row(c, format); - let hover = if fell_back { + let earth = app.session.map().body().is_earth(); + let (coords, fell_back) = coordinate_row(c, format, earth); + let hover = if fell_back && !earth { + i18n::fmt( + "Copy coordinates to the clipboard. {format} is a grid of the Earth, so latitude and longitude", + &[("format", format.label())], + ) + } else if fell_back { i18n::fmt( "Copy coordinates to the clipboard. No {format} here: outside the UTM zones (80° S to 84° N), so latitude and longitude", &[("format", format.label())], @@ -266,15 +273,18 @@ mod tests { #[test] fn the_coordinate_row_copies_the_chosen_format() { let p = Coord::new(44.4, 33.3); - assert_eq!(coordinate_row(p, CoordReadout::Decimal), ("33.300000, 44.400000".into(), false)); - assert_eq!(coordinate_row(p, CoordReadout::Dms), ("44°24′00.0″ E 33°18′00.0″ N".into(), false)); - assert_eq!(coordinate_row(p, CoordReadout::Utm), ("38S 444141 3684706".into(), false)); - assert_eq!(coordinate_row(p, CoordReadout::Mgrs), ("38S MB 44140 84706".into(), false)); + assert_eq!(coordinate_row(p, CoordReadout::Decimal, true), ("33.300000, 44.400000".into(), false)); + assert_eq!(coordinate_row(p, CoordReadout::Dms, true), ("44°24′00.0″ E 33°18′00.0″ N".into(), false)); + assert_eq!(coordinate_row(p, CoordReadout::Utm, true), ("38S 444141 3684706".into(), false)); + assert_eq!(coordinate_row(p, CoordReadout::Mgrs, true), ("38S MB 44140 84706".into(), false)); // Where UTM has no zone, the row falls back to latitude and longitude (and says so). let pole = Coord::new(10.0, 86.0); for f in [CoordReadout::Utm, CoordReadout::Mgrs] { - assert_eq!(coordinate_row(pole, f), ("86.000000, 10.000000".into(), true), "{f:?}"); + assert_eq!(coordinate_row(pole, f, true), ("86.000000, 10.000000".into(), true), "{f:?}"); + // On another body's map as well: UTM and MGRS are the Earth's grids. + assert_eq!(coordinate_row(p, f, false), ("33.300000, 44.400000".into(), true), "{f:?}"); } - assert!(!coordinate_row(pole, CoordReadout::Dms).1); + assert!(!coordinate_row(pole, CoordReadout::Dms, true).1); + assert_eq!(coordinate_row(p, CoordReadout::Dms, false), coordinate_row(p, CoordReadout::Dms, true)); } } diff --git a/crates/ui-egui/src/searchbox.rs b/crates/ui-egui/src/searchbox.rs index f4849efdef..4186199b84 100644 --- a/crates/ui-egui/src/searchbox.rs +++ b/crates/ui-egui/src/searchbox.rs @@ -286,7 +286,12 @@ fn list_area(app: &mut RustGisApp, ui: &Ui, frame_r: Rect, list: &[Row], t: &Tok picked = Some(k); } } - if none { + // 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()); + if let Some(e) = grid { + note(ui, &grid_error_text(e), t.text_dim); + } else if none { note(ui, tl!("Nothing found"), t.text_dim); } }); @@ -373,10 +378,30 @@ fn describe(st: &State, row: &Row) -> (String, &'static str, String, Option String { + use rustgis_engine::geom::GridError as G; + let reason = match e { + G::Syntax => tl!("not a UTM or MGRS grid reference"), + G::Zone => tl!("the UTM zone must be 1 to 60"), + G::Band => tl!("the latitude band must be a letter from C to X (not I or O)"), + G::Polar => tl!("polar (UPS) grid references, north of 84° N or south of 80° S, aren't supported"), + G::Square => tl!("the 100 km square letters aren't used in this zone"), + G::Digits => tl!("the grid digits must be an even count of 0 to 10, half for the easting and half for the northing"), + G::BandMismatch => tl!("the northing doesn't fall in the latitude band given"), + G::OutsideZone => tl!("the place lies outside the zone given"), + G::Ambiguous => { + tl!("S after the zone is latitude band S; for the southern hemisphere write the zone, then south (33 south 412345 3768000)") + } + }; + crate::i18n::fmt("No place at this grid reference: {reason}", &[("reason", reason)]) +} + fn note(ui: &mut Ui, text: &str, color: Color32) { ui.horizontal(|ui| { ui.add_space(10.0); - ui.label(egui::RichText::new(text).size(12.0).color(color)); + // Wrapped at the list's width: a reason or an error can be longer than the list is wide. + ui.add(egui::Label::new(egui::RichText::new(text).size(12.0).color(color)).wrap()); }); } @@ -505,7 +530,7 @@ pub fn paint_marker(p: &egui::Painter, at: egui::Pos2, name: &str, t: &Tokens) { #[allow(clippy::unwrap_used)] mod tests { use egui::accesskit::Role; - use egui_kittest::kittest::Queryable; + use egui_kittest::kittest::{NodeT, Queryable}; use super::*; @@ -521,6 +546,53 @@ mod tests { assert!(h.query_by_role_and_label(Role::Button, "Cities").is_some()); } + /// A grid reference that names no place says why under the box, before places are searched + /// and after none are found; a query that isn't one says nothing of grids. + #[test] + fn a_refused_grid_reference_says_why() { + for (query, places, want) in [ + ("33S 412345 5523456", Places::Idle, Some("write the zone, then south")), + ("38TMJ", Places::Found(Vec::new()), Some("doesn't fall in the latitude band")), + ("Zzyzx Qq", Places::Found(Vec::new()), None), + ] { + let mut app = RustGisApp::with_sample(); + let results = search::search(&app.session, query, search::LIMIT); + let st = &mut app.ui.search; + st.query = query.into(); + st.searched = query.into(); + st.results = results; + st.places = places; + st.open = true; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 800.0)).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + show(app, ui, &Tokens::get(&ctx)); + }, + app, + ); + h.run(); + // The list stays up while the box has the focus (as when typing). + h.get_by_role(Role::TextInput).focus(); + h.run(); + // A label's text is its accessible value. + let grid = h + .query_all_by(|n| n.role() == Role::Label && n.value().is_some_and(|v| v.starts_with("No place at this grid reference"))) + .next() + .and_then(|n| n.accesskit_node().value()); + match want { + Some(w) => { + let label: String = grid.unwrap_or_else(|| panic!("{query}: no reason shown")); + assert!(label.contains(w), "{query}: {label}"); + } + None => { + assert!(grid.is_none(), "{query}"); + assert!(h.query_by_label("Nothing found").is_some(), "{query}"); + } + } + } + } + /// A number typed for one layer, then another layer picked in a list a places search left /// open: the number is set on the layer it was typed for, even when the other had the same /// value (#1194). The field is drawn after the box, as the right pane is. diff --git a/crates/ui-egui/tests/coordinate_readout.rs b/crates/ui-egui/tests/coordinate_readout.rs index edb9d5d98a..36116e9512 100644 --- a/crates/ui-egui/tests/coordinate_readout.rs +++ b/crates/ui-egui/tests/coordinate_readout.rs @@ -91,5 +91,14 @@ fn the_status_bar_reads_the_pointer_in_the_chosen_format_and_a_click_switches() h.state_mut().run("map.goToXY", json!({"lon": 10.0, "lat": 84.5, "scale": 10000})).unwrap(); hover_map(&mut h); assert!(h.state().map.pointer_lonlat.is_some_and(|c| c.y > 84.0)); - h.get_by_label("No MGRS here: outside the UTM zones (80° S to 84° N)"); + h.get_by_label("No MGRS here"); + // On another body's map UTM and MGRS, the Earth's grids, read nothing either. + h.state_mut().run("map.body", json!({"name": "mars", "basemap": false})).unwrap(); + h.state_mut().run("map.goToXY", json!({"lon": 44.4, "lat": 33.3, "scale": 10000})).unwrap(); + hover_map(&mut h); + assert!(h.state().map.pointer_lonlat.is_some_and(|c| (c.y - 33.3).abs() < 0.05)); + h.get_by_label("No MGRS here"); + h.state_mut().run("ui.coordinateFormat", json!({"format": "decimal"})).unwrap(); + hover_map(&mut h); + h.get_by_label(&rustgis_engine::geom::format_lonlat(h.state().map.pointer_lonlat.unwrap())); } diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 1fdcf78578..549365e509 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -125,8 +125,9 @@ rustgis-cli run --sample --cmd 'map.search={"query":"Tokyo","go":true}' **Right-click the map** for a menu about that place. Its first row shows the place in the status bar's coordinate format (latitude and longitude as `40.712800, -74.006000` for decimal degrees); -click it to copy it. North of 84° N and south of 80° S, where UTM and MGRS have no zone, it shows -and copies the latitude and longitude, and its hover text says why. Below it, **Copy As GeoJSON** +click it to copy it. North of 84° N and south of 80° S, where UTM and MGRS have no zone, and on +the map of another body than the Earth, it shows and copies the latitude and longitude, and its +hover text says why. Below it, **Copy As GeoJSON** copies the place as a point feature, **Center Map Here** and **Zoom In Here** move the view, and **Directions To Here** and **Directions From Here** open the [Directions](#directions) pane. **Quick Analysis** runs a tool at the place: a buffer of 500 m, 1 km or 5 km (¼, 1 or 5 miles when the Directions pane is set @@ -144,19 +145,21 @@ choice is remembered and also sets the right-click menu's first row. The same pl | Decimal degrees | `15.3000° E 49.8500° N` | four decimal places | | DMS | `15°18′00.0″ E 49°51′00.0″ N` | degrees, minutes and seconds | | UTM | `33U 521567 5521996` | zone and latitude band, easting and northing in metres, rounded to the metre | -| MGRS | `33U WR 21566 21996` | zone and band, the 100 km square, easting and northing within it, truncated 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 | UTM and MGRS are on WGS 84, with the zone exceptions for southern Norway (32V) and Svalbard (31X, 33X, 35X and 37X), and cover 80° S to 84° N. Nearer the poles they would need the Universal Polar -Stereographic grid, which RustGIS doesn't have: there the readout says it is outside the UTM -zones rather than show a wrong reference. Scripts set the format with +Stereographic grid, which RustGIS doesn't have: there the readout shows *No UTM here* (or +*No MGRS here*) rather than a wrong reference, and so it does on the map of another body than +the Earth, where degrees still read. Scripts set the format with `ui.coordinateFormat={"format":"utm"}` (`decimal`, `dms`, `utm` or `mgrs`); without `format` it steps to the next one. The [search box](#navigating) takes the same grid references, in any case: - **MGRS** with or without spaces: `33UWR2156621996`, `33U WR 21566 21996`, `33UWR 2156 2199`, - or a 100 km square alone, `33UWR`. The digits are an even count from 0 to 10, half for the + or a 100 km square alone, `33UWR`; a zone below 10 with or without its leading zero (`04QFJ`, + `4QFJ`). The digits are an even count from 0 to 10, half for the easting and half for the northing, and the search goes to the middle of the square they name. A 100 km square is also looked for in the attribute tables, since Sentinel-2 tiles are named after them. @@ -167,9 +170,10 @@ The [search box](#navigating) takes the same grid references, in any case: Angeles); with a northing outside band S it could mean the southern hemisphere, so it finds nothing: write `south` instead. -A reference that doesn't exist (square letters the zone doesn't use, a northing outside the band, -an odd number of digits, a place outside the zone) finds nothing rather than a place somewhere -else. +A reference that doesn't exist (square letters the zone doesn't use, a northing or a square +outside the band, an odd number of digits, a place outside the zone) finds nothing rather than a +place somewhere else, and the list says why; `map.search` returns the reason as `gridError`. On +the map of another body, grid references find nothing. ### Directions From 83a8dcd162bdc32889abb0dc1d7dd4d3b85fdc32 Mon Sep 17 00:00:00 2001 From: PawelKra <15887575+PawelKra@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:37:20 +0100 Subject: [PATCH 3/7] fix(ui): grid refusal reasons in logical order; finish the copy hover text The reasons a grid reference is refused are filled into the search list's message, which i18n::fmt puts in display order: they go in as tl_raw!, so right-to-left text isn't reordered twice. The right-click row's fallback hover text now says that latitude and longitude are copied. --- crates/ui-egui/src/mapmenu.rs | 4 ++-- crates/ui-egui/src/searchbox.rs | 19 ++++++++++--------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/mapmenu.rs b/crates/ui-egui/src/mapmenu.rs index e0a828540b..aadd5250b7 100644 --- a/crates/ui-egui/src/mapmenu.rs +++ b/crates/ui-egui/src/mapmenu.rs @@ -126,12 +126,12 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, c: Coord) { let (coords, fell_back) = coordinate_row(c, format, earth); let hover = if fell_back && !earth { i18n::fmt( - "Copy coordinates to the clipboard. {format} is a grid of the Earth, so latitude and longitude", + "Copy coordinates to the clipboard. {format} is a grid of the Earth, so latitude and longitude are copied", &[("format", format.label())], ) } else if fell_back { i18n::fmt( - "Copy coordinates to the clipboard. No {format} here: outside the UTM zones (80° S to 84° N), so latitude and longitude", + "Copy coordinates to the clipboard. No {format} here: outside the UTM zones (80° S to 84° N), so latitude and longitude are copied", &[("format", format.label())], ) } else { diff --git a/crates/ui-egui/src/searchbox.rs b/crates/ui-egui/src/searchbox.rs index 4186199b84..ed0d9cfa27 100644 --- a/crates/ui-egui/src/searchbox.rs +++ b/crates/ui-egui/src/searchbox.rs @@ -381,17 +381,18 @@ fn describe(st: &State, row: &Row) -> (String, &'static str, String, Option String { use rustgis_engine::geom::GridError as G; + // In logical order: the reason is filled into the message, which is put in display order. let reason = match e { - G::Syntax => tl!("not a UTM or MGRS grid reference"), - G::Zone => tl!("the UTM zone must be 1 to 60"), - G::Band => tl!("the latitude band must be a letter from C to X (not I or O)"), - G::Polar => tl!("polar (UPS) grid references, north of 84° N or south of 80° S, aren't supported"), - G::Square => tl!("the 100 km square letters aren't used in this zone"), - G::Digits => tl!("the grid digits must be an even count of 0 to 10, half for the easting and half for the northing"), - G::BandMismatch => tl!("the northing doesn't fall in the latitude band given"), - G::OutsideZone => tl!("the place lies outside the zone given"), + G::Syntax => tl_raw!("not a UTM or MGRS grid reference"), + G::Zone => tl_raw!("the UTM zone must be 1 to 60"), + G::Band => tl_raw!("the latitude band must be a letter from C to X (not I or O)"), + G::Polar => tl_raw!("polar (UPS) grid references, north of 84° N or south of 80° S, aren't supported"), + G::Square => tl_raw!("the 100 km square letters aren't used in this zone"), + G::Digits => tl_raw!("the grid digits must be an even count of 0 to 10, half for the easting and half for the northing"), + G::BandMismatch => tl_raw!("the northing doesn't fall in the latitude band given"), + G::OutsideZone => tl_raw!("the place lies outside the zone given"), G::Ambiguous => { - tl!("S after the zone is latitude band S; for the southern hemisphere write the zone, then south (33 south 412345 3768000)") + tl_raw!("S after the zone is latitude band S; for the southern hemisphere write the zone, then south (33 south 412345 3768000)") } }; crate::i18n::fmt("No place at this grid reference: {reason}", &[("reason", reason)]) From f0f09b8d356f65745e0ebc0776aee37fbda57694 Mon Sep 17 00:00:00 2001 From: PawelKra <15887575+PawelKra@users.noreply.github.com> Date: Wed, 4 Nov 2026 22:16:34 +0100 Subject: [PATCH 4/7] fix(ui): search list notes keep right-to-left rows in reading order The notes under the search box (why a grid reference names no place, nothing found, a places search that failed) now wrap at the list's width, and egui's own wrapping puts a back-to-front paragraph's rows out of order. They are shown with i18n::paragraph, which fits the rows first, so they take text in logical order: the grid reason is filled with the new i18n::fmt_raw (fmt without the display form), and the fixed notes go in as tl_raw!. --- crates/ui-egui/src/i18n/mod.rs | 11 +++++++-- crates/ui-egui/src/i18n/tests.rs | 11 +++++++++ crates/ui-egui/src/searchbox.rs | 38 +++++++++++++++++++++++++++----- 3 files changed, 52 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index 9384ae2e8d..a2423d19e4 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -401,6 +401,13 @@ pub fn location(loc: &str) -> String { /// logical order — [`t_raw`] (`tl_raw!`) for translated fragments, raw data as it is — /// for the finished message is transformed as a whole. pub fn fmt(template: &str, args: &[(&str, &str)]) -> String { + rtl::visual(&fmt_raw(template, args)) +} + +/// [`fmt`] in logical order, without the display form: for a message shown with +/// [`paragraph`], which fits a right-to-left message to its rows and puts each row in +/// display form itself. +pub fn fmt_raw(template: &str, args: &[(&str, &str)]) -> String { let template = tr_raw(current(), template); let mut out = String::with_capacity(template.len()); let mut rest = template; @@ -409,7 +416,7 @@ pub fn fmt(template: &str, args: &[(&str, &str)]) -> String { let Some((name, tail)) = after.split_once('}') else { out.push('{'); out.push_str(after); - return rtl::visual(&out); + return out; }; match args.iter().find(|(k, _)| *k == name) { Some((_, v)) => out.push_str(v), @@ -422,7 +429,7 @@ pub fn fmt(template: &str, args: &[(&str, &str)]) -> String { rest = tail; } out.push_str(rest); - rtl::visual(&out) + out } thread_local! { diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index a5e006a724..0d76bffa6c 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -44,6 +44,17 @@ fn lookup_fallback_and_tags() { assert_eq!(fmt("{n} of {total} selected", &[("n", "3"), ("total", "{n}")]), "3 of {n} selected"); } +/// `fmt_raw` fills a message in logical order, for `paragraph` to fit; `fmt` is the same +/// message in display form. +#[test] +fn fmt_raw_keeps_logical_order() { + let args = [("reason", "سلام abc")]; + assert_eq!(fmt_raw("{reason}", &args), "سلام abc"); + assert_eq!(fmt("{reason}", &args), rtl::visual("سلام abc")); + assert_ne!(fmt("{reason}", &args), fmt_raw("{reason}", &args)); + assert_eq!(fmt_raw("{reason} {", &args), "سلام abc {"); +} + #[test] fn bengali_registration_and_fallback() { let bn = Lang::from_code("bn").unwrap_or(Lang::EN); diff --git a/crates/ui-egui/src/searchbox.rs b/crates/ui-egui/src/searchbox.rs index ed0d9cfa27..048d8b5be5 100644 --- a/crates/ui-egui/src/searchbox.rs +++ b/crates/ui-egui/src/searchbox.rs @@ -292,7 +292,7 @@ fn list_area(app: &mut RustGisApp, ui: &Ui, frame_r: Rect, list: &[Row], t: &Tok if let Some(e) = grid { note(ui, &grid_error_text(e), t.text_dim); } else if none { - note(ui, tl!("Nothing found"), t.text_dim); + note(ui, tl_raw!("Nothing found"), t.text_dim); } }); // Places stay in sight under the map's matches: the row that searches them, or @@ -319,7 +319,7 @@ fn list_area(app: &mut RustGisApp, ui: &Ui, frame_r: Rect, list: &[Row], t: &Tok note(ui, &e, t.red); } if matches!(&st.places, Places::Found(p) if p.is_empty()) { - note(ui, tl!("No place found"), t.text_dim); + note(ui, tl_raw!("No place found"), t.text_dim); } if matches!(st.places, Places::Found(_)) { ui.horizontal(|ui| { @@ -381,7 +381,7 @@ fn describe(st: &State, row: &Row) -> (String, &'static str, String, Option String { use rustgis_engine::geom::GridError as G; - // In logical order: the reason is filled into the message, which is put in display order. + // In logical order: the message is fitted to the list's rows, each put in display order. let reason = match e { G::Syntax => tl_raw!("not a UTM or MGRS grid reference"), G::Zone => tl_raw!("the UTM zone must be 1 to 60"), @@ -395,14 +395,15 @@ fn grid_error_text(e: rustgis_engine::geom::GridError) -> String { tl_raw!("S after the zone is latitude band S; for the southern hemisphere write the zone, then south (33 south 412345 3768000)") } }; - crate::i18n::fmt("No place at this grid reference: {reason}", &[("reason", reason)]) + crate::i18n::fmt_raw("No place at this grid reference: {reason}", &[("reason", reason)]) } +/// `text`, in logical order, wrapped at the list's width: a reason or an error can be longer +/// than the list is wide, and a right-to-left one keeps its rows in reading order. fn note(ui: &mut Ui, text: &str, color: Color32) { ui.horizontal(|ui| { ui.add_space(10.0); - // Wrapped at the list's width: a reason or an error can be longer than the list is wide. - ui.add(egui::Label::new(egui::RichText::new(text).size(12.0).color(color)).wrap()); + crate::i18n::paragraph(ui, text, regular(12.0), color); }); } @@ -594,6 +595,31 @@ mod tests { } } + /// A reason in right-to-left text, longer than the list is wide, is broken into rows ahead of + /// the toolkit's wrapping, which would put a back-to-front paragraph's rows out of order; the + /// first row holds the start of the sentence. + #[test] + fn a_right_to_left_note_keeps_its_rows_in_reading_order() { + let text = "هیچ مکانی در این مرجع شبکه نیست زیرا حرف پس از منطقه کمربند عرض جغرافیایی است"; + // The interface fonts, which hold the Persian glyphs, are in from the next frame on. + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(220.0, 300.0)).build_ui(move |ui| { + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + let t = Tokens::get(ui.ctx()); + note(ui, text, t.text_dim); + }); + h.run(); + let shown: String = h.query_all_by_role(Role::Label).find_map(|n| n.value()).unwrap(); + let rows: Vec<&str> = shown.split('\n').collect(); + assert!(rows.len() > 1, "{shown:?}"); + assert!(rows[0].contains("هیچ"), "{shown:?}"); + assert!(!rows[0].contains("است"), "{shown:?}"); + } + /// A number typed for one layer, then another layer picked in a list a places search left /// open: the number is set on the layer it was typed for, even when the other had the same /// value (#1194). The field is drawn after the box, as the right pane is. From a2ae0abb453708b4393bf520908557f32320ad9b Mon Sep 17 00:00:00 2001 From: PawelKra <15887575+PawelKra@users.noreply.github.com> Date: Thu, 5 Nov 2026 08:39:09 +0100 Subject: [PATCH 5/7] fix(geom): the UTM readout states the hemisphere, not the latitude band MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The UTM readout wrote the MGRS latitude band after the zone (`38S 444141 3684706`). Bands aren't part of UTM, and in plain UTM the letter after the zone is commonly read as the hemisphere, so band S (32° N to 40° N) looked like the southern hemisphere and a northing read that way lands about 10,000 km away. NGA's Universal Grid System primer warns of the same confusion. The readout, the copied coordinates and the docs now spell the hemisphere out after the zone, as GeographicLib's GeoConvert writes its long form: `38north 444141 3684706`, `21south 371625 6170423`. A single letter can't be used for the south: typed `S` stays band S and a northing outside it is still refused as ambiguous, so `33S` wouldn't read back. The spelled-out form reads one way only and parses back to the same place in both hemispheres. MGRS keeps its bands; the band form is still read when typed. Reading the hemisphere form back also checks the zone against the band of a latitude within the rounded metre: a readout just south of 72° N in zones 32, 34 and 36, or by the edges of 31V and 32V, could otherwise read back a hair across the parallel, where the zones change, and be refused. --- crates/engine/src/cmd/search.rs | 7 + crates/geom/src/utm.rs | 179 ++++++++++++++++++--- crates/ui-egui/src/coordreadout.rs | 5 +- crates/ui-egui/src/mapmenu.rs | 11 +- crates/ui-egui/tests/coordinate_readout.rs | 4 +- docs/user-guide/maps.md | 12 +- 6 files changed, 189 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index 8998a74d4c..c5e21b2b8d 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -593,6 +593,8 @@ mod tests { // GeographicLib's GeoConvert example, 33.3° N 44.4° E: 38n 444140.54 3684706.36, // 38SMB4414084706. for q in [ + "38north 444141 3684706", + "38NORTH 444141 3684706", "38S 444141 3684706", "38s 444140.54, 3684706.36", "38 north 444141 3684706", @@ -604,6 +606,11 @@ mod tests { let r = search(&s, q, 50); assert!(near(&r, 44.4, 33.3), "{q}: {r:?}"); } + // The UTM readout of a southern place, zone and hemisphere, is found where it was read. + let ba = Coord::new(-58.4, -34.6); + let text = rustgis_geom::format_utm(ba).unwrap(); + assert!(text.starts_with("21south "), "{text}"); + assert!(near(&search(&s, &text, 50), ba.x, ba.y), "{text}"); // A 100 km square is found at its centre. let r = search(&s, "38SMB", 50); let u = rustgis_geom::to_utm(match r.hits.first() { diff --git a/crates/geom/src/utm.rs b/crates/geom/src/utm.rs index bd0f638cf7..f8bc01146b 100644 --- a/crates/geom/src/utm.rs +++ b/crates/geom/src/utm.rs @@ -241,12 +241,22 @@ impl Utm { pub fn north(&self) -> bool { self.band >= 'N' } + + /// The hemisphere spelt out, as the readout writes it after the zone: `north` or `south`. + pub fn hemisphere(&self) -> &'static str { + if self.north() { "north" } else { "south" } + } } impl fmt::Display for Utm { - /// `33U 412345 5523456`: zone and band, then easting and northing rounded to the metre. + /// `33north 412345 5523456`, `21south 371625 6170423`: the zone and the hemisphere spelt out + /// (GeographicLib's long form, as `GeoConvert -u -l` writes it), then the easting and northing + /// rounded to the metre. Latitude bands belong to MGRS: in plain UTM the letter after the zone + /// is commonly read as the hemisphere, so `38S` (band S, 32° N to 40° N) would be taken for + /// the southern hemisphere, and a single `S` can't be told apart from band S when the text is + /// read back. The spelt-out hemisphere reads one way only and parses back with [`parse_utm`]. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}{} {:.0} {:.0}", self.zone, self.band, self.easting.round(), self.northing.round()) + write!(f, "{}{} {:.0} {:.0}", self.zone, self.hemisphere(), self.easting.round(), self.northing.round()) } } @@ -291,7 +301,8 @@ pub fn from_utm(zone: u8, north: bool, easting: f64, northing: f64) -> Option Option { to_utm(c).map(|u| u.to_string()) } @@ -591,13 +602,13 @@ pub fn parse_mgrs(text: &str) -> Result { Ok(m) } -/// Reads a UTM position: a zone, then a latitude band letter or the hemisphere spelt out, then +/// Reads a UTM position: a zone, then the hemisphere spelt out or a latitude band letter, then /// the easting and northing in metres (decimals allowed; spaces or commas between). Accepted: /// -/// - `33U 412345 5523456` or `33 U 412345 5523456`: zone and latitude band, as the readout -/// writes it. The northing must fall in the band. -/// - `33 north 412345 5523456`, `33 south 412345 4476544` (also `33north`, any case): zone and -/// hemisphere. +/// - `33north 412345 5523456`, `33south 412345 4476544` (also `33 north`, any case): zone and +/// hemisphere, as the readout writes it. +/// - `33U 412345 5523456` or `33 U 412345 5523456`: zone and latitude band. The northing must +/// fall in the band. /// - `33N 412345 5523456`: band N lies wholly in the northern hemisphere, so a northing outside /// band N is read as the northern hemisphere (both readings give the same place). /// @@ -629,14 +640,28 @@ pub fn parse_utm(text: &str) -> Result { if !(0.0..1_000_000.0).contains(&easting) || !(0.0..=FALSE_NORTHING_SOUTH).contains(&northing) { return Err(GridError::OutsideZone); } - // A place from a hemisphere, checked against the band of its own latitude. + // A place from a hemisphere, checked against the band of its own latitude, or of a latitude + // within the metre it was rounded to: a readout just south of 72° N in zone 32, 34 or 36 can + // read back a hair north of it, where Svalbard's zones take over, and so can one by the edges + // of southern Norway's 32V. The band form allows the same. let by_hemisphere = |north: bool| -> Result { let p = from_utm(zone, north, easting, northing).ok_or(GridError::OutsideZone)?; if p.y >= UTM_MAX_LAT + ROUNDING_DEG || p.y < UTM_MIN_LAT - ROUNDING_DEG { return Err(GridError::Polar); } - let band = latitude_band(p.y.clamp(UTM_MIN_LAT, UTM_MAX_LAT - 1e-9)).ok_or(GridError::Polar)?; - check_place(p, (p.y, p.y), zone, band, 1.0).map(|()| p) + let band_at = |lat: f64| latitude_band(lat.clamp(UTM_MIN_LAT, UTM_MAX_LAT - 1e-9)).ok_or(GridError::Polar); + let own = band_at(p.y)?; + let first = check_place(p, (p.y, p.y), zone, own, 1.0); + if first.is_ok() { + return Ok(p); + } + for lat in [p.y - ROUNDING_DEG, p.y + ROUNDING_DEG] { + let band = band_at(lat)?; + if band != own && check_place(p, (p.y, p.y), zone, band, 1.0).is_ok() { + return Ok(p); + } + } + first.map(|()| p) }; match word.as_str() { "NORTH" => by_hemisphere(true), @@ -688,7 +713,7 @@ mod tests { assert!((u.easting - 444_140.54).abs() < 0.005, "{}", u.easting); assert!((u.northing - 3_684_706.36).abs() < 0.005, "{}", u.northing); assert_eq!(to_mgrs(c(44.4, 33.3), 5).unwrap().compact(), "38SMB4414084706"); - assert_eq!(format_utm(c(44.4, 33.3)).unwrap(), "38S 444141 3684706"); + assert_eq!(format_utm(c(44.4, 33.3)).unwrap(), "38north 444141 3684706"); assert_eq!(format_mgrs(c(44.4, 33.3)).unwrap(), "38S MB 44140 84706"); } @@ -875,7 +900,7 @@ mod tests { // More than five digits is clamped to five. assert_eq!(to_mgrs(p, 9).unwrap().digits, 5); // The UTM readout rounds instead. - assert_eq!(from_utm(38, true, 444_140.6, 3_684_706.4).map(format_utm), Some(Some("38S 444141 3684706".into()))); + assert_eq!(from_utm(38, true, 444_140.6, 3_684_706.4).map(format_utm), Some(Some("38north 444141 3684706".into()))); assert!(to_mgrs(c(0.0, 84.0), 5).is_none()); assert!(format_mgrs(c(0.0, -85.0)).is_none()); } @@ -997,20 +1022,129 @@ mod tests { ] { assert!(near(parse_utm(&t).unwrap_or_else(|e| panic!("{t}: {e}"))), "{t}"); } - // The southern hemisphere, by band or spelt out. + // The southern hemisphere, as the readout writes it, by band or spelt out with a space. let q = c(-58.4, -34.6); let s = to_utm(q).unwrap(); assert_eq!((s.zone, s.band), (21, 'H')); - for t in [s.to_string(), format!("21 south {:.0} {:.0}", s.easting, s.northing)] { + assert!(s.to_string().starts_with("21south "), "{s}"); + for t in [ + s.to_string(), + format!("21H {:.0} {:.0}", s.easting, s.northing), + format!("21 south {:.0} {:.0}", s.easting, s.northing), + format!("21SOUTH {:.0} {:.0}", s.easting, s.northing), + ] { let got = parse_utm(&t).unwrap(); assert!((got.x - q.x).abs() < 1e-5 && (got.y - q.y).abs() < 1e-5, "{t} {got:?}"); } - // Band S (32°–40° N), as the readout writes Los Angeles. + // Los Angeles is in band S (32°–40° N): the readout writes the hemisphere, and band S + // typed by hand still reads as the band. let la = c(-118.25, 34.05); let l = to_utm(la).unwrap(); assert_eq!((l.zone, l.band), (11, 'S')); - let got = parse_utm(&l.to_string()).unwrap(); - assert!((got.x - la.x).abs() < 1e-5 && (got.y - la.y).abs() < 1e-5); + assert!(l.to_string().starts_with("11north "), "{l}"); + let (e, n) = (l.easting.round(), l.northing.round()); + for t in [l.to_string(), format!("11S {e} {n}"), format!("11s {e} {n}")] { + let got = parse_utm(&t).unwrap_or_else(|e| panic!("{t}: {e}")); + assert!((got.x - la.x).abs() < 1e-5 && (got.y - la.y).abs() < 1e-5, "{t}"); + } + } + + /// The readout states the hemisphere, never a band letter, and reads back through + /// [`parse_utm`] to within the half metre it is rounded to, in its own zone and hemisphere. + fn assert_readout_round_trips(p: Coord) { + let u = to_utm(p).unwrap_or_else(|| panic!("{p:?} is in UTM")); + let text = format_utm(p).unwrap(); + let hemi = if p.y >= 0.0 { "north" } else { "south" }; + assert!(text.starts_with(&format!("{}{hemi} ", u.zone)), "{text} at {p:?}"); + assert_eq!(text, u.to_string()); + let back = parse_utm(&text).unwrap_or_else(|e| panic!("{text} at {p:?}: {e}")); + let (e, n) = to_utm_in_zone(back, u.zone, p.y >= 0.0).unwrap(); + assert!((e - u.easting).abs() <= 0.5 + 1e-6 && (n - u.northing).abs() <= 0.5 + 1e-6, "{text} at {p:?}: {e} {n}"); + // As typed in another case, too. + assert_eq!(parse_utm(&text.to_uppercase()), Ok(back), "{text}"); + } + + #[test] + fn the_readout_writes_the_hemisphere_and_reads_back() { + // Baghdad in band S, Buenos Aires in band H, Sydney, Cape Town, Ushuaia, Reykjavik. + for p in [c(44.4, 33.3), c(-58.4, -34.6), c(151.2, -33.87), c(18.42, -33.92), c(-68.3, -54.8), c(-21.9, 64.15)] { + assert_readout_round_trips(p); + } + assert_eq!(format_utm(c(151.2, -33.87)).map(|t| t[..8].to_string()), Some("56south ".into())); + // Either side of the equator, including a place south of it whose northing rounds to the + // full 10,000 km false northing. + for lat in [-0.3, -1e-4, -1e-7, -1e-12, 0.0, 1e-12, 1e-7, 1e-4, 0.3] { + for lon in [-177.0, 0.0, 3.0, 5.99, 44.4, 179.9] { + assert_readout_round_trips(c(lon, lat)); + } + } + let rounds_up = (1..400) + .map(|i| c(15.0, -1e-17 * f64::from(i) * 5.0)) + .find(|p| to_utm(*p).is_some_and(|u| u.band == 'M' && u.northing.round() == FALSE_NORTHING_SOUTH)) + .unwrap(); + assert!(format_utm(rounds_up).unwrap().starts_with("33south 500000 10000000"), "{:?}", format_utm(rounds_up)); + assert_readout_round_trips(rounds_up); + // Band X up to 84° N and band C down to 80° S, and the band edges between. + let metres = |m: f64| m / M_PER_DEG; + for lat in [UTM_MAX_LAT - metres(0.6), 83.9, 72.0, 72.0 - 1e-7, UTM_MIN_LAT, UTM_MIN_LAT + metres(0.6), -72.0, -72.0 - 1e-7] { + for lon in [-179.0, 4.0, 10.0, 25.0, 40.0, 100.0] { + assert_readout_round_trips(c(lon, lat)); + } + } + // Zones 1–9 keep one digit, in both hemispheres. + for zone in 1u8..=9 { + for lat in [-45.0, -1.0, 1.0, 45.0] { + let p = c(central_meridian(zone) + 2.9, lat); + assert!(format_utm(p).unwrap().starts_with(&format!("{zone}{}", if lat > 0.0 { "north " } else { "south " }))); + assert_readout_round_trips(p); + } + } + // Southern Norway's 32V and Svalbard's wide zones, also within a rounded metre of the + // parallels where the zones change (56°, 64° and 72° N), where the place read back can lie + // in the neighbouring band. + for p in [c(3.5, 60.0), c(11.9, 63.9), c(2.9, 60.0), c(8.9, 78.0), c(9.1, 78.0), c(41.9, 80.0)] { + assert_readout_round_trips(p); + } + for edge in [56.0, 64.0, 72.0] { + for off in [-1e-5, -1e-6, -1e-7, 0.0, 1e-7, 1e-6, 1e-5] { + for i in 0..=168 { + assert_readout_round_trips(c(f64::from(i) * 0.25, edge + off)); + } + } + } + let mut r = Lcg(31); + for _ in 0..20_000 { + let lat = UTM_MIN_LAT + r.next() * (UTM_MAX_LAT - UTM_MIN_LAT - 1e-6); + assert_readout_round_trips(c(-180.0 + r.next() * 360.0, lat)); + } + // No band letter anywhere: a letter after the zone would read as a band or a hemisphere. + for p in [c(44.4, 33.3), c(-58.4, -34.6)] { + let text = format_utm(p).unwrap(); + let zone_end = text.find(|ch: char| !ch.is_ascii_digit()).unwrap(); + assert!(text[zone_end..].starts_with("north ") || text[zone_end..].starts_with("south "), "{text}"); + } + // Where UTM has no zone the readout still writes nothing, and the hemisphere form of a + // polar position is refused. + for p in [c(0.0, 84.0), c(0.0, -80.000_1), c(0.0, 90.0)] { + assert!(format_utm(p).is_none(), "{p:?}"); + } + let (e, n) = to_utm_in_zone(c(15.0, 84.05), 33, true).unwrap(); + assert_eq!(parse_utm(&format!("33north {} {}", e.round(), n.round())), Err(GridError::Polar)); + let (e, n) = to_utm_in_zone(c(15.0, -80.05), 33, false).unwrap(); + assert_eq!(parse_utm(&format!("33south {} {}", e.round(), n.round())), Err(GridError::Polar)); + } + + /// The single letter `S` after a zone is still band S when typed: the readout's spelt-out + /// hemisphere doesn't loosen the refusal of a northing outside band S. + #[test] + fn a_typed_s_stays_band_s() { + let s = to_utm(c(-58.4, -34.6)).unwrap(); + let (e, n) = (s.easting.round(), s.northing.round()); + assert_eq!(parse_utm(&format!("21S {e} {n}")), Err(GridError::Ambiguous)); + assert_eq!(parse_utm(&format!("21s {e} {n}")), Err(GridError::Ambiguous)); + assert!(parse_utm(&format!("21south {e} {n}")).is_ok_and(|q| (q.y + 34.6).abs() < 1e-5)); + // An abbreviation of a hemisphere other than the single letter isn't read. + assert_eq!(parse_utm(&format!("21sou {e} {n}")), Err(GridError::Syntax)); } #[test] @@ -1082,8 +1216,13 @@ mod tests { } assert_eq!(to_mgrs(c(central_meridian(9), 10.0), 0).unwrap().to_string(), "09P WM"); assert_eq!(to_mgrs(c(central_meridian(10), 10.0), 0).unwrap().to_string(), "10P ES"); - // UTM keeps the zone as it is numbered (EPSG:32604), like GeographicLib's `4n`. - assert!(format_utm(c(central_meridian(4), 20.0)).unwrap().starts_with("4Q ")); + // UTM keeps the zone as it is numbered (EPSG:32604), like GeographicLib's `4n` and + // `4north`, and reads back. + let text = format_utm(c(central_meridian(4), 20.0)).unwrap(); + assert!(text.starts_with("4north "), "{text}"); + assert!(parse_utm(&text).is_ok_and(|q| (q.x - central_meridian(4)).abs() < 1e-5 && (q.y - 20.0).abs() < 1e-5), "{text}"); + let text = format_utm(c(central_meridian(9), -20.0)).unwrap(); + assert!(text.starts_with("9south "), "{text}"); } /// Just south of the equator the northing rounds to the full false northing (10,000 km, which diff --git a/crates/ui-egui/src/coordreadout.rs b/crates/ui-egui/src/coordreadout.rs index 9fc3ceb80c..6953ee3647 100644 --- a/crates/ui-egui/src/coordreadout.rs +++ b/crates/ui-egui/src/coordreadout.rs @@ -18,7 +18,7 @@ pub enum CoordReadout { Decimal, /// `12°20′44.2″ E 45°40′44.0″ N` Dms, - /// `33U 412345 5523456`: zone and latitude band, easting and northing in metres. + /// `33north 412345 5523456`: zone and hemisphere, easting and northing in metres. Utm, /// `33U VP 12345 23456`: zone and band, the 100 km square, easting and northing to 1 m. Mgrs, @@ -138,7 +138,8 @@ mod tests { let p = Coord::new(44.4, 33.3); assert_eq!(CoordReadout::Decimal.readout(Some(p), true), "44.4000° E 33.3000° N"); assert_eq!(CoordReadout::Dms.readout(Some(p), true), "44°24′00.0″ E 33°18′00.0″ N"); - assert_eq!(CoordReadout::Utm.readout(Some(p), true), "38S 444141 3684706"); + assert_eq!(CoordReadout::Utm.readout(Some(p), true), "38north 444141 3684706"); + assert_eq!(CoordReadout::Utm.readout(Some(Coord::new(-58.4, -34.6)), true), "21south 371625 6170423"); assert_eq!(CoordReadout::Mgrs.readout(Some(p), true), "38S MB 44140 84706"); for f in CoordReadout::ALL { for earth in [true, false] { diff --git a/crates/ui-egui/src/mapmenu.rs b/crates/ui-egui/src/mapmenu.rs index aadd5250b7..f84a351c29 100644 --- a/crates/ui-egui/src/mapmenu.rs +++ b/crates/ui-egui/src/mapmenu.rs @@ -275,8 +275,17 @@ mod tests { let p = Coord::new(44.4, 33.3); assert_eq!(coordinate_row(p, CoordReadout::Decimal, true), ("33.300000, 44.400000".into(), false)); assert_eq!(coordinate_row(p, CoordReadout::Dms, true), ("44°24′00.0″ E 33°18′00.0″ N".into(), false)); - assert_eq!(coordinate_row(p, CoordReadout::Utm, true), ("38S 444141 3684706".into(), false)); + assert_eq!(coordinate_row(p, CoordReadout::Utm, true), ("38north 444141 3684706".into(), false)); assert_eq!(coordinate_row(p, CoordReadout::Mgrs, true), ("38S MB 44140 84706".into(), false)); + // What is copied as UTM or MGRS is found again by the search box, in both hemispheres. + for q in [p, Coord::new(-58.4, -34.6), Coord::new(151.2, -33.87), Coord::new(3.0, -1e-7), Coord::new(-21.9, 64.15)] { + for f in [CoordReadout::Utm, CoordReadout::Mgrs] { + let (text, fell_back) = coordinate_row(q, f, true); + assert!(!fell_back, "{text}"); + let at = rustgis_engine::cmd::search::read_grid_reference(&text).unwrap_or_else(|e| panic!("{text}: {e}")); + assert!((at.x - q.x).abs() < 1e-4 && (at.y - q.y).abs() < 1e-4, "{text} {at:?}"); + } + } // Where UTM has no zone, the row falls back to latitude and longitude (and says so). let pole = Coord::new(10.0, 86.0); for f in [CoordReadout::Utm, CoordReadout::Mgrs] { diff --git a/crates/ui-egui/tests/coordinate_readout.rs b/crates/ui-egui/tests/coordinate_readout.rs index 36116e9512..e76ad3bb65 100644 --- a/crates/ui-egui/tests/coordinate_readout.rs +++ b/crates/ui-egui/tests/coordinate_readout.rs @@ -62,7 +62,7 @@ fn hover_map(h: &mut egui_kittest::Harness<'_, RustGisApp>) { #[test] fn the_status_bar_reads_the_pointer_in_the_chosen_format_and_a_click_switches() { let mut h = harness(RustGisApp::with_sample()); - // A view about 4 km across around Baghdad (38S MB 44140 84706, at 444141 3684706). + // A view about 4 km across around Baghdad (38S MB 44140 84706, at 38north 444141 3684706). h.state_mut().run("map.goToXY", json!({"lon": 44.4, "lat": 33.3, "scale": 10000})).unwrap(); hover_map(&mut h); let at = h.state().map.pointer_lonlat.expect("the pointer is over the map"); @@ -77,7 +77,7 @@ fn the_status_bar_reads_the_pointer_in_the_chosen_format_and_a_click_switches() hover_map(&mut h); assert_eq!(h.state().map.coord_format, CoordReadout::Utm); let utm = rustgis_engine::geom::format_utm(h.state().map.pointer_lonlat.unwrap()).unwrap(); - assert!(utm.starts_with("38S 44"), "{utm}"); + assert!(utm.starts_with("38north 44"), "{utm}"); h.get_by_label(&utm).click(); hover_map(&mut h); assert_eq!(h.state().map.coord_format, CoordReadout::Mgrs); diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 549365e509..1dc24e0792 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -144,9 +144,12 @@ choice is remembered and also sets the right-click menu's first row. The same pl | --- | --- | --- | | Decimal degrees | `15.3000° E 49.8500° N` | four decimal places | | DMS | `15°18′00.0″ E 49°51′00.0″ N` | degrees, minutes and seconds | -| UTM | `33U 521567 5521996` | zone and latitude band, easting and northing in metres, rounded to the metre | +| 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 | +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 +to 40° N) would be taken for the southern hemisphere, 10,000 km away. Latitude bands are MGRS's. UTM and MGRS are on WGS 84, with the zone exceptions for southern Norway (32V) and Svalbard (31X, 33X, 35X and 37X), and cover 80° S to 84° N. Nearer the poles they would need the Universal Polar Stereographic grid, which RustGIS doesn't have: there the readout shows *No UTM here* (or @@ -163,9 +166,10 @@ The [search box](#navigating) takes the same grid references, in any case: easting and half for the northing, and the search goes to the middle of the square they name. A 100 km square is also looked for in the attribute tables, since Sentinel-2 tiles are named after them. -- **UTM** as the readout writes it, zone and latitude band: `33U 521567 5521996`; or the zone - and hemisphere spelt out: `33 north 521567 5521996`, `21 south 371625 6170423`. `33N` reads - as the northern hemisphere when the northing isn't in band N, since both readings agree. +- **UTM** as the readout writes it, zone and hemisphere: `33north 521567 5521996`, + `21south 371625 6170423` (also with a space, `33 north …`); or zone and latitude band: + `33U 521567 5521996`. `33N` reads as the northern hemisphere when the northing isn't in band + N, since both readings agree. `S` after the zone is always band S (32° N to 40° N), as in `11S 384629 3768405` (Los Angeles); with a northing outside band S it could mean the southern hemisphere, so it finds nothing: write `south` instead. From 9d7f0c57464506a1272e18d562af895ebc9f5a6b Mon Sep 17 00:00:00 2001 From: PawelKra <15887575+PawelKra@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:30:18 +0100 Subject: [PATCH 6/7] fix(search): a number and a word get no grid-reference reason Search text such as `5 Ave`, `7 Bay`, `3 Rds` or `4K TV` has the shape of a 100 km MGRS square alone (a zone, a band and two letters), and when the letters named no square the search list showed "No place at this grid reference: ..." (polar bands, square letters the zone doesn't use, I or O) instead of "Nothing found", and `map.search` with `go` answered "as a grid reference, ...". A square written with spaces is as often a number and a word, so one that names no square now counts as text that isn't a grid reference; written as one word (`38TMJ`, `38SAB`) it still says why, and so does any reference with grid digits. The zone number was also refused as outside 1-60 before the rest of the text was read, so `75 Main St` or `99 Problems` got "the UTM zone must be 1 to 60". The zone is now checked once the text reads as a UTM position or an MGRS reference. The user guide says which squares give a reason. --- crates/engine/src/cmd/search.rs | 42 +++++++++++++++++++++++++++++++-- crates/geom/src/utm.rs | 19 +++++++++++---- docs/user-guide/maps.md | 6 +++-- 3 files changed, 59 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index c5e21b2b8d..796f7a8796 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -372,17 +372,29 @@ pub fn parse_grid_reference(text: &str) -> Option { } /// As [`parse_grid_reference`], with why a reference was refused: [`GridError::Syntax`] for text -/// written as neither form, otherwise the reason of the form it was written in. +/// written as neither form, otherwise the reason of the form it was written in. A 100 km square +/// alone written with spaces (`5 Ave`, `4K TV`) is a number and a word as often as a reference, +/// so one that names no square is [`GridError::Syntax`] too; written as one word (`38TMJ`), it +/// says why. pub fn read_grid_reference(text: &str) -> Result { match rustgis_geom::parse_mgrs(text) { Ok(m) => m.centre(), Err(mgrs) => match rustgis_geom::parse_utm(text) { + Err(GridError::Syntax) if spaced_square(text) => Err(GridError::Syntax), Err(GridError::Syntax) => Err(mgrs), utm => utm, }, } } +/// Whether `text` has spaces and no digits after its leading number: written so, an MGRS +/// reference is a 100 km square alone. +fn spaced_square(text: &str) -> bool { + let text = text.trim(); + let after_zone = text.trim_start_matches(|c: char| c.is_ascii_digit()); + text.contains(char::is_whitespace) && !after_zone.contains(|c: char| c.is_ascii_digit()) +} + /// `lat, lon` rounded to six decimals (about 0.1 m), without trailing zeros. pub fn format_lat_lon(lat: f64, lon: f64) -> String { let r = |v: f64| { @@ -671,6 +683,10 @@ mod tests { ("38SMB441408470", GridError::Digits), ("38TMB4414084706", GridError::BandMismatch), ("38TMJ", GridError::BandMismatch), + // A 100 km square written as one word, as a reference is, still says why. + ("38SAB", GridError::Square), + ("38zmb", GridError::Polar), + ("38S AB 44140 84706", GridError::Square), ("38Z 444141 3684706", GridError::Polar), ("38ZMB4414084706", GridError::Polar), ("99X 1 2", GridError::Zone), @@ -680,7 +696,27 @@ mod tests { assert_eq!(search(&s, q, 50).grid_error, Some(why), "{q}"); } // Text not written as a grid reference, and references that read, carry no reason. - for q in ["1C", "Paris", "Countries", "12 Main St", "2020", "40.7, -74.0", "38SMB", "38S 444141 3684706", "10 20"] { + // A number and a three-letter word (a polar band, a square letter the zone doesn't use, I + // or O, a zone past 60) is ordinary text, and so is a number past 60 before any words. + for q in [ + "1C", + "Paris", + "Countries", + "12 Main St", + "2020", + "40.7, -74.0", + "38SMB", + "38S 444141 3684706", + "10 20", + "5 Ave", + "7 Bay", + "3 Rds", + "2 Oak", + "99 Ave", + "4K TV", + "75 Main St", + "99 Problems", + ] { assert_eq!(search(&s, q, 50).grid_error, None, "{q}"); } let mut s = s; @@ -691,6 +727,8 @@ mod tests { assert!(e.contains("nothing matches") && e.contains("33 south"), "{e}"); let e = s.run("map.search", &json!({"query": "Zzyzx Qq", "go": true})).unwrap_err(); assert_eq!(e, "nothing matches 'Zzyzx Qq'"); + let e = s.run("map.search", &json!({"query": "5 Ave", "go": true})).unwrap_err(); + assert_eq!(e, "nothing matches '5 Ave'"); // MGRS-looking garbage never panics. let mut r = 1u64; let alphabet: Vec = "0123456789 ACHINOSUVXZacz.-,°\u{0}é٣".chars().collect(); diff --git a/crates/geom/src/utm.rs b/crates/geom/src/utm.rs index f8bc01146b..36bc4dac40 100644 --- a/crates/geom/src/utm.rs +++ b/crates/geom/src/utm.rs @@ -520,7 +520,9 @@ fn locate(m: &Mgrs) -> Result { /// Most characters a typed grid reference may have. const MAX_REF_CHARS: usize = 64; -/// Reads a zone number (1–60, one or two digits) and the letter after it, skipping spaces. +/// Reads a zone number (one or two digits) and the letter after it, skipping spaces. The zone +/// isn't checked to be 1–60 here (the caller does, once the rest reads as a reference): until +/// then, `75 Main St` is text. fn zone_and_letter(chars: &mut std::iter::Peekable>) -> Result<(u8, char), GridError> { while chars.next_if(|c| c.is_whitespace()).is_some() {} let mut zone = String::new(); @@ -531,9 +533,6 @@ fn zone_and_letter(chars: &mut std::iter::Peekable>) -> Resu return Err(GridError::Syntax); } let zone: u8 = zone.parse().map_err(|_| GridError::Syntax)?; - if !(1..=60).contains(&zone) { - return Err(GridError::Zone); - } while chars.next_if(|c| c.is_whitespace()).is_some() {} let letter = chars.next().filter(char::is_ascii_alphabetic).ok_or(GridError::Syntax)?.to_ascii_uppercase(); Ok((zone, letter)) @@ -626,6 +625,9 @@ pub fn parse_utm(text: &str) -> Result { while let Some(c) = chars.next_if(char::is_ascii_alphabetic) { word.push(c.to_ascii_uppercase()); } + if !matches!(word.as_str(), "NORTH" | "SOUTH") && word.chars().count() != 1 { + return Err(GridError::Syntax); + } let rest: String = chars.collect(); let nums: Vec<&str> = rest.split(|c: char| c.is_whitespace() || c == ',').filter(|s| !s.is_empty()).collect(); let [es, ns] = nums.as_slice() else { return Err(GridError::Syntax) }; @@ -637,6 +639,9 @@ pub fn parse_utm(text: &str) -> Result { s.parse::().ok().filter(|v| v.is_finite()).ok_or(GridError::Syntax) }; let (easting, northing) = (number(es)?, number(ns)?); + if !(1..=60).contains(&zone) { + return Err(GridError::Zone); + } if !(0.0..1_000_000.0).contains(&easting) || !(0.0..=FALSE_NORTHING_SOUTH).contains(&northing) { return Err(GridError::OutsideZone); } @@ -971,6 +976,10 @@ mod tests { ("123SMB", GridError::Syntax), ("0SMB", GridError::Zone), ("61SMB", GridError::Zone), + // The zone is judged once the text is written as a reference: a number past 60 + // before a word is ordinary text. + ("75 Main St", GridError::Syntax), + ("99 Problems", GridError::Syntax), ("38IMB", GridError::Band), ("38OMB", GridError::Band), ("38ZMB", GridError::Polar), @@ -1161,6 +1170,8 @@ mod tests { ("33 east 412345 5523456", GridError::Syntax), ("0U 412345 5523456", GridError::Zone), ("61U 412345 5523456", GridError::Zone), + ("75 Main St", GridError::Syntax), + ("64 Bit 32 16", GridError::Syntax), ("33I 412345 5523456", GridError::Band), ("33Z 412345 5523456", GridError::Polar), // 5,523 km north is 49.8° N: not band T (40°–48° N). diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 1dc24e0792..90fd616b8b 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -176,8 +176,10 @@ The [search box](#navigating) takes the same grid references, in any case: A reference that doesn't exist (square letters the zone doesn't use, a northing or a square outside the band, an odd number of digits, a place outside the zone) finds nothing rather than a -place somewhere else, and the list says why; `map.search` returns the reason as `gridError`. On -the map of another body, grid references find nothing. +place somewhere else, and the list says why; `map.search` returns the reason as `gridError`. A +100 km square written with spaces, such as `5 Ave` or `4K TV`, is as likely ordinary text, so one +that names no square gives no reason; written as one word, `38TMJ`, it does. On the map of +another body, grid references find nothing. ### Directions From c4d7c03d41579ada94582c352fc819a601648c72 Mon Sep 17 00:00:00 2001 From: PawelKra <15887575+PawelKra@users.noreply.github.com> Date: Fri, 6 Nov 2026 09:54:48 +0100 Subject: [PATCH 7/7] fix(ui): keep an unknown saved coordinate format until the user picks one A coordinate_format preference this version doesn't know, such as one a newer RustGIS saved, used to read silently as decimal degrees. Now it still reads as decimal degrees, but a notice says so, and the stored value stays as it is. Only ui.coordinateFormat (the status bar click or a script) saves the preference, so it is replaced only when the user picks a format. Tests check the notice, that drawing frames and saving another setting leave the stored format alone, and that a click saves the new choice. --- crates/ui-egui/src/lib.rs | 22 ++++++++----- crates/ui-egui/tests/coordinate_readout.rs | 38 ++++++++++++++++++++-- docs/user-guide/maps.md | 3 +- 3 files changed, 52 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index cf57db12fa..52af07c09d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1303,14 +1303,20 @@ impl RustGisApp { .unwrap_or_else(|| "Meters".into()); self.ui.measurement_imperial = self.services.load_pref.as_ref().and_then(|load| load("measurement_units")).as_deref() == Some("imperial"); - // The pointer's coordinate format; an unknown or missing one reads as decimal degrees. - self.map.coord_format = self - .services - .load_pref - .as_ref() - .and_then(|load| load(coordreadout::PREF)) - .and_then(|code| CoordReadout::from_code(&code)) - .unwrap_or_default(); + // The pointer's coordinate format; a missing one reads as decimal degrees. One this + // version doesn't know (a newer RustGIS may have saved it) is said and read as decimal + // degrees too. It stays saved until the user picks a format (`ui.coordinateFormat`). + if let Some(code) = self.services.load_pref.as_ref().and_then(|load| load(coordreadout::PREF)) { + match CoordReadout::from_code(&code) { + Some(format) => self.map.coord_format = format, + None => { + // Notices are shown as written, and the language is set only in `start`. + i18n::set_current(self.chosen_lang()); + self.session + .notify(tl!("The saved coordinate format isn't known to this version, so decimal degrees are shown."), false); + } + } + } // The GPU map backend: RUSTGIS_GPU forces it on, else the saved preference. self.map.gpu_enabled = std::env::var_os("RUSTGIS_GPU").is_some() || self.services.load_pref.as_ref().and_then(|load| load("ui.map.gpu")).as_deref() == Some("1"); diff --git a/crates/ui-egui/tests/coordinate_readout.rs b/crates/ui-egui/tests/coordinate_readout.rs index e76ad3bb65..c4ec1526a4 100644 --- a/crates/ui-egui/tests/coordinate_readout.rs +++ b/crates/ui-egui/tests/coordinate_readout.rs @@ -41,16 +41,50 @@ fn the_format_cycles_persists_and_is_restored() { assert!(app.run("ui.coordinateFormat", bad.clone()).is_err(), "{bad}"); assert_eq!(app.map.coord_format, CoordReadout::Mgrs, "{bad}"); } - // A saved choice comes back; an unknown one reads as decimal degrees. - for (pref, want) in [("utm", CoordReadout::Utm), ("mgrs", CoordReadout::Mgrs), ("bogus", CoordReadout::Decimal)] { + // A saved choice comes back, with nothing to say. + for (pref, want) in [("utm", CoordReadout::Utm), ("mgrs", CoordReadout::Mgrs)] { let restored = RustGisApp::with_sample().with_services(Services { load_pref: Some(Box::new(move |k| (k == "coordinate_format").then(|| pref.to_string()))), ..Services::default() }); assert_eq!(restored.map.coord_format, want, "{pref}"); + assert!(!said_unknown(&restored), "{pref}"); } } +fn said_unknown(app: &RustGisApp) -> bool { + app.session.notices.iter().any(|n| n.text.contains("saved coordinate format isn't known")) +} + +#[test] +fn an_unknown_saved_format_is_said_and_kept_until_the_user_picks_one() { + let saved = Arc::new(Mutex::new(Vec::<(String, String)>::new())); + let writes = saved.clone(); + let app = RustGisApp::with_sample().with_services(Services { + load_pref: Some(Box::new(|k| (k == "coordinate_format").then(|| "lambert".to_string()))), + save_pref: Some(Box::new(move |k, v| writes.lock().unwrap_or_else(|e| e.into_inner()).push((k.to_string(), v.to_string())))), + ..Services::default() + }); + let format_writes = + || saved.lock().unwrap().iter().filter(|(k, _)| k == "coordinate_format").map(|(_, v)| v.clone()).collect::>(); + // Read as decimal degrees, and said once. + assert_eq!(app.map.coord_format, CoordReadout::Decimal); + assert_eq!(app.session.notices.iter().filter(|n| n.text.contains("saved coordinate format isn't known")).count(), 1); + // Frames drawn and another setting saved leave the stored format alone. + let mut h = harness(app); + hover_map(&mut h); + h.state_mut().run("ui.measurementUnits", json!({"units": "imperial"})).unwrap(); + hover_map(&mut h); + assert!(saved.lock().unwrap().iter().any(|(k, _)| k == "measurement_units")); + assert!(format_writes().is_empty(), "{:?}", format_writes()); + // A click on the readout is the user's choice: it is saved. + let decimal = rustgis_engine::geom::format_lonlat(h.state().map.pointer_lonlat.expect("the pointer is over the map")); + h.get_by_label(&decimal).click(); + hover_map(&mut h); + assert_eq!(h.state().map.coord_format, CoordReadout::Dms); + assert_eq!(format_writes(), ["dms"]); +} + /// Points the mouse at the middle of the window, over the map, for a few frames. fn hover_map(h: &mut egui_kittest::Harness<'_, RustGisApp>) { for _ in 0..3 { diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index b5324f2e0d..468a25209e 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -157,7 +157,8 @@ Stereographic grid, which RustGIS doesn't have: there the readout shows *No UTM *No MGRS here*) rather than a wrong reference, and so it does on the map of another body than the Earth, where degrees still read. Scripts set the format with `ui.coordinateFormat={"format":"utm"}` (`decimal`, `dms`, `utm` or `mgrs`); without `format` -it steps to the next one. +it steps to the next one. A saved format this version doesn't know, say from a newer RustGIS, +reads as decimal degrees with a notice, and stays saved until you pick a format. The [search box](#navigating) takes the same grid references, in any case: