diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 9bf5774d11..9e6a7c985b 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -474,7 +474,7 @@ pub fn status_bar(app: &mut RustGisApp, ui: &mut Ui) { let live = app.map.pointer_lonlat.is_some(); let resp = ui.add( egui::Label::new( - egui::RichText::new(format.readout(kept, earth)).monospace().size(11.5).color(if live { t.text_dim } else { t.text_disabled }), + egui::RichText::new(format.readout(kept, earth, crate::coordreadout::MapSystem::of(app.session.map()).as_ref())).monospace().size(11.5).color(if live { t.text_dim } else { t.text_disabled }), ) .sense(Sense::click()), ); diff --git a/crates/ui-egui/src/coordreadout.rs b/crates/ui-egui/src/coordreadout.rs index 80ecda3f28..0dddc97333 100644 --- a/crates/ui-egui/src/coordreadout.rs +++ b/crates/ui-egui/src/coordreadout.rs @@ -1,9 +1,10 @@ -//! 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. +//! How the pointer's coordinates read in the status bar and in the map's right-click menu: in the +//! map's own coordinate system, decimal degrees, degrees-minutes-seconds, UTM or MGRS. A click on +//! 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 rustgis_engine::map::projection::Flat; use crate::i18n; @@ -13,8 +14,11 @@ 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` + /// `2600000 mE 1200000 mN`: the map's own coordinates, as its coordinate system counts them + /// (on the globe and another body's map, decimal degrees; see [`MapSystem`]). #[default] + Map, + /// `12.3456° E 45.6789° N` Decimal, /// `12°20′44.2″ E 45°40′44.0″ N` Dms, @@ -26,11 +30,12 @@ pub enum CoordReadout { 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]; + pub const ALL: [CoordReadout; 5] = [CoordReadout::Map, 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::Map => "map", CoordReadout::Decimal => "decimal", CoordReadout::Dms => "dms", CoordReadout::Utm => "utm", @@ -44,19 +49,21 @@ impl CoordReadout { Self::ALL.into_iter().find(|f| f.code().eq_ignore_ascii_case(code)) } - /// The format after this one: decimal → DMS → UTM → MGRS → decimal. + /// The format after this one: map → decimal → DMS → UTM → MGRS → map. pub fn next(self) -> Self { match self { + CoordReadout::Map => CoordReadout::Decimal, CoordReadout::Decimal => CoordReadout::Dms, CoordReadout::Dms => CoordReadout::Utm, CoordReadout::Utm => CoordReadout::Mgrs, - CoordReadout::Mgrs => CoordReadout::Decimal, + CoordReadout::Mgrs => CoordReadout::Map, } } /// The format's name, translated in logical order, for filling into [`i18n::fmt`] messages. pub fn label(self) -> &'static str { match self { + CoordReadout::Map => tl_raw!("map coordinates"), CoordReadout::Decimal => tl_raw!("decimal degrees"), CoordReadout::Dms => tl_raw!("degrees, minutes and seconds"), CoordReadout::Utm => tl_raw!("UTM"), @@ -70,13 +77,18 @@ impl CoordReadout { } /// The place in this format; for UTM and MGRS, UPS in the polar areas (north of 84° N and - /// south of 80° S) and `None` on another body's map (`earth` false), and for every format - /// `None` for a non-finite place. - pub fn format(self, c: Coord, earth: bool) -> Option { + /// south of 80° S) and `None` on another body's map (`earth` false); in the map's coordinates + /// `None` where its projection doesn't reach, and decimal degrees without a flat Earth map + /// (`map` `None`); and for every format `None` for a non-finite place. + pub fn format(self, c: Coord, earth: bool, map: Option<&MapSystem>) -> Option { if !c.is_finite() || (self.earth_only() && !earth) { return None; } match self { + CoordReadout::Map => match map { + Some(m) => m.format(c), + None => Some(geom::format_lonlat(c)), + }, CoordReadout::Decimal => Some(geom::format_lonlat(c)), CoordReadout::Dms => Some(geom::format_dms(c)), CoordReadout::Utm => geom::format_utm(c), @@ -85,13 +97,14 @@ impl CoordReadout { } /// The status bar's readout of the pointer: `—` off the map, and a short statement on another - /// body's map, where the Earth's grids name no place, rather than a wrong grid reference. It is - /// no wider than a reference, so the status bar keeps its room. - pub fn readout(self, c: Option, earth: bool) -> String { + /// body's map, where the Earth's grids name no place, rather than a wrong grid reference (no + /// wider than that reference). Map coordinates can run wider: up to 13 characters for each + /// number, with three decimals far from the system's origin. + pub fn readout(self, c: Option, earth: bool, map: Option<&MapSystem>) -> String { match c { None => "—".to_string(), Some(c) if !c.is_finite() => "—".to_string(), - Some(c) => self.format(c, earth).unwrap_or_else(|| i18n::fmt("No {format} here", &[("format", self.label())])), + Some(c) => self.format(c, earth, map).unwrap_or_else(|| i18n::fmt("No {format} here", &[("format", self.label())])), } } @@ -99,12 +112,85 @@ impl CoordReadout { /// and MGRS read near the poles. pub fn hover(self) -> String { i18n::fmt( - "Coordinates in {format}. Click to switch: decimal degrees, DMS, UTM, MGRS. UTM and MGRS are grids of the Earth, read in UPS north of 84° N and south of 80° S.", + "Coordinates in {format}. Click to switch: map coordinates, decimal degrees, DMS, UTM, MGRS. Map coordinates are in the map's coordinate system, named beside them, and in degrees on the globe and on another body's map. UTM and MGRS are grids of the Earth, read in UPS north of 84° N and south of 80° S.", &[("format", self.label())], ) } } +/// The name [`MapSystem::name`] gives a projection. +fn system_name(p: &rustgis_engine::map::Projection) -> String { + let label = p.label(); + if matches!(p, rustgis_engine::map::Projection::WebMercator) || label.starts_with("EPSG:") || label.starts_with("ESRI:") { + label + } else { + p.code() + } +} + +/// A flat map of the Earth's own coordinates, as the map format reads them: its projection and +/// how many of its units a screen pixel spans, which sets the decimals shown. +pub struct MapSystem { + flat: Flat, + res: f64, + /// The system's name, never translated: see [`MapSystem::name`]. + name: String, +} + +impl MapSystem { + /// The system of a map: `None` on the globe and on another body's map, whose flat projection + /// is computed on the Earth's figure and so gives no coordinates of its own body. + pub fn of(map: &rustgis_engine::map::Map) -> Option { + (map.body().is_earth() && !map.projection.is_globe()).then(|| MapSystem { + flat: Flat::of(&map.projection), + res: map.camera.res, + name: system_name(&map.projection), + }) + } + + /// A system from its parts (tests). + pub fn new(flat: Flat, res: f64, name: &str) -> MapSystem { + MapSystem { flat, res, name: name.to_string() } + } + + /// The system's name, as it can be given back to `map.projection`: its EPSG or ESRI code + /// (`EPSG:2056`), `Web Mercator`, else the map's projection code (`robinson +lon_0=150`, + /// `local:7.4386,46.9511`), which, unlike a preset's or a local view's display name, names + /// the system exactly. + pub fn name(&self) -> &str { + &self.name + } + + /// The place's easting and northing, with as many decimals as a pixel needs (none at a metre + /// a pixel or more, up to three) and the unit: `2600000 mE 1200000 mN`, `ftE` and `ftN` in + /// international feet, `ftUSE` and `ftUSN` in US survey feet, and `E` and `N` alone in + /// another unit. A place on a world copy past the antimeridian reads as the same place within + /// ±180°. `None` where the projection doesn't reach (outside the area the map draws it over, + /// for LV95 a 60° cap around Bern, well past Switzerland) or folds, as the map draws nothing + /// there. + fn format(&self, c: Coord) -> Option { + let m = self.flat.forward_checked(Coord::new(crate::mapmenu::wrap_lon(c.x), c.y)).filter(|m| m.is_finite())?; + let decimals = if self.res.is_finite() && self.res > 0.0 { (-self.res.log10()).ceil().clamp(0.0, 3.0) as usize } else { 0 }; + let to_meter = match &self.flat { + Flat::Mercator => 1.0, + Flat::Custom(p) => p.to_meter(), + }; + let unit = if (to_meter - 1.0).abs() < 1e-9 { + "m" + } else if (to_meter - 0.3048).abs() < 1e-9 { + "ft" + } else if (to_meter - 1200.0 / 3937.0).abs() < 1e-9 { + "ftUS" + } else { + "" + }; + // Rounded first, then + 0.0: a coordinate that rounds to zero reads 0, not -0. + let scale = 10f64.powi(decimals as i32); + let shown = |v: f64| (v * scale).round() / scale + 0.0; + Some(format!("{:.d$} {unit}E {:.d$} {unit}N", shown(m.x), shown(m.y), d = decimals)) + } +} + #[cfg(test)] mod tests { use super::*; @@ -112,14 +198,14 @@ mod tests { #[test] fn a_click_steps_through_every_format_and_back() { let mut f = CoordReadout::default(); - assert_eq!(f, CoordReadout::Decimal); + assert_eq!(f, CoordReadout::Map); let mut seen = Vec::new(); - for _ in 0..4 { + for _ in 0..5 { seen.push(f); f = f.next(); } assert_eq!(seen, CoordReadout::ALL); - assert_eq!(f, CoordReadout::Decimal); + assert_eq!(f, CoordReadout::Map); } #[test] @@ -135,15 +221,15 @@ mod tests { #[test] fn readouts_in_each_format() { 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), "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"); + assert_eq!(CoordReadout::Decimal.readout(Some(p), true, None), "44.4000° E 33.3000° N"); + assert_eq!(CoordReadout::Dms.readout(Some(p), true, None), "44°24′00.0″ E 33°18′00.0″ N"); + assert_eq!(CoordReadout::Utm.readout(Some(p), true, None), "38north 444141 3684706"); + assert_eq!(CoordReadout::Utm.readout(Some(Coord::new(-58.4, -34.6)), true, None), "21south 371625 6170423"); + assert_eq!(CoordReadout::Mgrs.readout(Some(p), true, None), "38S MB 44140 84706"); for f in CoordReadout::ALL { for earth in [true, false] { - assert_eq!(f.readout(None, earth), "—"); - assert_eq!(f.readout(Some(Coord::new(f64::NAN, 0.0)), earth), "—"); + assert_eq!(f.readout(None, earth, None), "—"); + assert_eq!(f.readout(Some(Coord::new(f64::NAN, 0.0)), earth, None), "—"); } } } @@ -152,14 +238,14 @@ mod tests { fn polar_places_read_in_ups() { let pole = Coord::new(10.0, 86.0); // GeographicLib's `GeoConvert -u -l` and `-m` for the same place. - assert_eq!(CoordReadout::Utm.readout(Some(pole), true), "north 2077146 1562481"); - assert_eq!(CoordReadout::Mgrs.readout(Some(pole), true), "Z AC 77146 62481"); + assert_eq!(CoordReadout::Utm.readout(Some(pole), true, None), "north 2077146 1562481"); + assert_eq!(CoordReadout::Mgrs.readout(Some(pole), true, None), "Z AC 77146 62481"); for f in [CoordReadout::Utm, CoordReadout::Mgrs] { - assert_eq!(f.format(pole, true).as_deref(), Some(f.readout(Some(pole), true).as_str())); + assert_eq!(f.format(pole, true, None).as_deref(), Some(f.readout(Some(pole), true, None).as_str())); assert!(f.hover().contains("UPS")); } // Decimal and DMS read there as anywhere. - assert_eq!(CoordReadout::Dms.readout(Some(pole), true), "10°00′00.0″ E 86°00′00.0″ N"); + assert_eq!(CoordReadout::Dms.readout(Some(pole), true, None), "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. @@ -167,16 +253,71 @@ mod tests { 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); - let r = f.readout(Some(p), false); + assert_eq!(f.format(p, false, None), None); + let r = f.readout(Some(p), false, None); 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(p), true).chars().count(), "{r}"); + assert!(r.chars().count() <= f.readout(Some(p), true, None).chars().count(), "{r}"); assert!(f.earth_only()); } - for f in [CoordReadout::Decimal, CoordReadout::Dms] { - assert_eq!(f.format(p, false), f.format(p, true)); + for f in [CoordReadout::Map, CoordReadout::Decimal, CoordReadout::Dms] { + assert_eq!(f.format(p, false, None), f.format(p, true, None)); assert!(!f.earth_only()); } } + + /// The map's coordinates: Web Mercator's metres, an EPSG system's own units (Swiss LV95's + /// metres, a US State Plane system's feet), decimals as a pixel needs them, and degrees + /// without a flat Earth map. + #[test] + fn map_coordinates_read_in_the_maps_system() { + let bern = Coord::new(7.4386, 46.9511); + let lv95 = MapSystem::new(Flat::of(&rustgis_engine::map::Projection::Custom("EPSG:2056".into())), 2.0, "EPSG:2056"); + let r = CoordReadout::Map.readout(Some(bern), true, Some(&lv95)); + let (e, n) = r.split_once(" ").expect("an easting and a northing"); + let e: f64 = e.strip_suffix(" mE").expect("metres east").parse().expect("a number east"); + let n: f64 = n.strip_suffix(" mN").expect("metres north").parse().expect("a number north"); + // Bern's old observatory is the origin of the Swiss grid: E 2600000, N 1200000. + assert!((e - 2_600_000.0).abs() < 50.0 && (n - 1_200_000.0).abs() < 50.0, "{r}"); + assert!(!r.contains('.'), "{r}"); + // Zoomed in to 5 cm a pixel, two decimals. + let close = MapSystem::new(Flat::of(&rustgis_engine::map::Projection::Custom("EPSG:2056".into())), 0.05, "EPSG:2056"); + let r = CoordReadout::Map.readout(Some(bern), true, Some(&close)); + let decimals = |part: &str| part.split_once('.').map(|(_, d)| d.trim_end_matches([' ', 'm', 'E', 'N']).len()); + assert!(r.split(" ").all(|part| decimals(part) == Some(2)), "{r}"); + // Web Mercator: the origin, and a world copy past the antimeridian. + let merc = MapSystem::new(Flat::Mercator, 1000.0, "Web Mercator"); + assert_eq!(CoordReadout::Map.readout(Some(Coord::new(0.0, 0.0)), true, Some(&merc)), "0 mE 0 mN"); + assert_eq!( + CoordReadout::Map.readout(Some(Coord::new(370.0, 0.0)), true, Some(&merc)), + CoordReadout::Map.readout(Some(Coord::new(10.0, 0.0)), true, Some(&merc)) + ); + // NAD83 / Texas Central (ftUS), EPSG:2277. + let texas = MapSystem::new(Flat::of(&rustgis_engine::map::Projection::Custom("EPSG:2277".into())), 10.0, "EPSG:2277"); + let r = CoordReadout::Map.readout(Some(Coord::new(-97.74, 30.27)), true, Some(&texas)); + assert!(r.ends_with(" ftUSN") && r.contains(" ftUSE "), "{r}"); + // Outside the system's reach: said, not a wrong number. + let far = CoordReadout::Map.readout(Some(Coord::new(-150.0, -60.0)), true, Some(&lv95)); + assert_eq!(far, "No map coordinates here"); + // Its projection reaches well past Switzerland: London still has eastings and northings. + let london = CoordReadout::Map.readout(Some(Coord::new(-0.1276, 51.5072)), true, Some(&lv95)); + assert!(london.ends_with(" mN"), "{london}"); + // The globe and another body's map have no flat Earth system: degrees. + assert_eq!(CoordReadout::Map.readout(Some(bern), true, None), geom::format_lonlat(bern)); + assert!(CoordReadout::Map.hover().contains("map's coordinate system")); + } + + /// The copied name gives the system back: a code, never a preset's or a local view's + /// display name. + #[test] + fn the_system_is_named_so_it_can_be_given_back() { + use rustgis_engine::map::Projection; + assert_eq!(system_name(&Projection::WebMercator), "Web Mercator"); + assert_eq!(system_name(&Projection::from_code("EPSG:2056").expect("LV95")), "EPSG:2056"); + for code in ["robinson +lon_0=150", "local:7.4386,46.9511"] { + let p = Projection::from_code(code).expect(code); + let name = system_name(&p); + assert_eq!(Projection::from_code(&name).expect(&name), p, "{name}"); + } + } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 05c6535bcc..d877bdc6c2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -151,7 +151,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 coordreadout::{CoordReadout, MapSystem}; pub use rustgis_assistant; pub use rustgis_engine; pub use widgets::big_split_menu; @@ -1926,15 +1926,15 @@ 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; 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`). + // The pointer's coordinate format; a missing one reads in the map's coordinates. One this + // version doesn't know (a newer RustGIS may have saved it) is said and read in the map's + // coordinates 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 => { self.session - .notify(tl!("The saved coordinate format isn't known to this version, so decimal degrees are shown."), false); + .notify(tl!("The saved coordinate format isn't known to this version, so map coordinates are shown."), false); } } } @@ -4315,8 +4315,8 @@ impl RustGisApp { let format = match p.get("format") { None | Some(Value::Null) => self.map.coord_format.next(), Some(Value::String(v)) => CoordReadout::from_code(v) - .ok_or_else(|| tl!("The coordinate format must be decimal, dms, utm or mgrs").to_string())?, - _ => return Err(tl!("The coordinate format must be decimal, dms, utm or mgrs").into()), + .ok_or_else(|| tl!("The coordinate format must be map, decimal, dms, utm or mgrs").to_string())?, + _ => return Err(tl!("The coordinate format must be map, decimal, dms, utm or mgrs").into()), }; self.map.coord_format = format; self.save_pref(coordreadout::PREF, format.code()); diff --git a/crates/ui-egui/src/mapmenu.rs b/crates/ui-egui/src/mapmenu.rs index 7b896a345f..c25fff9b81 100644 --- a/crates/ui-egui/src/mapmenu.rs +++ b/crates/ui-egui/src/mapmenu.rs @@ -5,6 +5,7 @@ use egui::Ui; use rustgis_engine::geom::Coord; use serde_json::json; +use crate::coordreadout::MapSystem; use crate::widgets::{menu_row, submenu_row}; use crate::{CoordReadout, RustGisApp, i18n}; @@ -54,11 +55,18 @@ 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 and south of 80° S /// UTM and MGRS give UPS (`north …`, `Z …`); on another body's map (`earth` false) they fall back -/// to latitude and longitude (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, earth) { +/// to latitude and longitude (and the row's hover text says why). Map coordinates are the map's +/// own system's (`map`), followed by its name so the copy says which system they are in +/// (`2600173 mE 1200272 mN EPSG:2056`); without one (the globe, another body) they are latitude +/// and longitude, and where the system doesn't reach they fall back to them. +fn coordinate_row(c: Coord, f: CoordReadout, earth: bool, map: Option<&MapSystem>) -> (String, bool) { + match (f, map) { + (CoordReadout::Decimal, _) | (CoordReadout::Map, None) => (lat_lon(c), false), + (CoordReadout::Map, Some(m)) => match f.format(c, earth, map) { + Some(text) => (format!("{text} {}", m.name()), false), + None => (lat_lon(c), true), + }, + _ => match f.format(c, earth, map) { Some(text) => (text, false), None => (lat_lon(c), true), }, @@ -124,8 +132,12 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, c: Coord) { crate::shapeconvert::menu(app, ui); let format = app.map.coord_format; let earth = app.session.map().body().is_earth(); - let (coords, fell_back) = coordinate_row(c, format, earth); - let hover = if fell_back && !earth { + let system = MapSystem::of(app.session.map()); + let (coords, fell_back) = coordinate_row(c, format, earth, system.as_ref()); + let hover = if fell_back && format == CoordReadout::Map { + tl!("Copy coordinates to the clipboard. The map's coordinate system doesn't reach here, so latitude and longitude are copied") + .to_string() + } else if fell_back && !earth { i18n::fmt( "Copy coordinates to the clipboard. {format} is a grid of the Earth, so latitude and longitude are copied", &[("format", format.label())], @@ -289,14 +301,14 @@ 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, 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), ("38north 444141 3684706".into(), false)); - assert_eq!(coordinate_row(p, CoordReadout::Mgrs, true), ("38S MB 44140 84706".into(), false)); + assert_eq!(coordinate_row(p, CoordReadout::Decimal, true, None), ("33.300000, 44.400000".into(), false)); + assert_eq!(coordinate_row(p, CoordReadout::Dms, true, None), ("44°24′00.0″ E 33°18′00.0″ N".into(), false)); + assert_eq!(coordinate_row(p, CoordReadout::Utm, true, None), ("38north 444141 3684706".into(), false)); + assert_eq!(coordinate_row(p, CoordReadout::Mgrs, true, None), ("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); + let (text, fell_back) = coordinate_row(q, f, true, None); 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:?}"); @@ -305,15 +317,29 @@ mod tests { // Where UTM has no zone, the row gives UPS (`north …`, `Z …`), which reads back too. let pole = Coord::new(10.0, 86.0); for f in [CoordReadout::Utm, CoordReadout::Mgrs] { - let (text, fell_back) = coordinate_row(pole, f, true); + let (text, fell_back) = coordinate_row(pole, f, true, None); assert!(!fell_back && (text.starts_with("north ") || text.starts_with("Z ")), "{f:?}: {text}"); let at = rustgis_engine::cmd::search::read_grid_reference(&text).unwrap_or_else(|e| panic!("{text}: {e}")); assert!((at.x - pole.x).abs() < 1e-3 && (at.y - pole.y).abs() < 1e-4, "{text} {at:?}"); // On another body's map the row falls back to latitude and longitude (and says so): // UTM, MGRS and UPS are the Earth's grids. - assert_eq!(coordinate_row(p, f, false), ("33.300000, 44.400000".into(), true), "{f:?}"); + assert_eq!(coordinate_row(p, f, false, None), ("33.300000, 44.400000".into(), true), "{f:?}"); } - assert!(!coordinate_row(pole, CoordReadout::Dms, true).1); - assert_eq!(coordinate_row(p, CoordReadout::Dms, false), coordinate_row(p, CoordReadout::Dms, true)); + assert!(!coordinate_row(pole, CoordReadout::Dms, true, None).1); + assert_eq!(coordinate_row(p, CoordReadout::Dms, false, None), coordinate_row(p, CoordReadout::Dms, true, None)); + // Map coordinates: the map's own system's, and latitude and longitude without one (the + // globe, another body) or where the system doesn't reach (said in the row's hover text). + let merc = MapSystem::new(rustgis_engine::map::projection::Flat::Mercator, 1000.0, "Web Mercator"); + assert_eq!(coordinate_row(Coord::new(0.0, 0.0), CoordReadout::Map, true, Some(&merc)), ("0 mE 0 mN Web Mercator".into(), false)); + assert_eq!(coordinate_row(p, CoordReadout::Map, true, None), ("33.300000, 44.400000".into(), false)); + let lv95 = MapSystem::new( + rustgis_engine::map::projection::Flat::of(&rustgis_engine::map::Projection::Custom("EPSG:2056".into())), + 1.0, + "EPSG:2056", + ); + let (bern, _) = coordinate_row(Coord::new(7.4386, 46.9511), CoordReadout::Map, true, Some(&lv95)); + assert!(bern.starts_with("2599") && bern.ends_with(" mN EPSG:2056"), "{bern}"); + let far = Coord::new(-150.0, -60.0); + assert_eq!(coordinate_row(far, CoordReadout::Map, true, Some(&lv95)), ("-60.000000, -150.000000".into(), true)); } } diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index a977081f17..02e1648840 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -443,7 +443,7 @@ impl Default for MapView { kept_lonlat: None, menu_lonlat: None, menu_text: None, - coord_format: crate::CoordReadout::Decimal, + coord_format: crate::CoordReadout::default(), render_ms: 0, notices_seen: 0, toasts: Vec::new(), diff --git a/crates/ui-egui/tests/integration/coordinate_readout.rs b/crates/ui-egui/tests/integration/coordinate_readout.rs index c1aa8d6569..300faf584c 100644 --- a/crates/ui-egui/tests/integration/coordinate_readout.rs +++ b/crates/ui-egui/tests/integration/coordinate_readout.rs @@ -1,10 +1,10 @@ -//! 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. +//! The status bar's coordinate readout: a click steps map → 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 rustgis_ui_egui::{CoordReadout, MapSystem, RustGisApp, Services}; use serde_json::{Value, json}; fn harness(app: RustGisApp) -> egui_kittest::Harness<'static, RustGisApp> { @@ -26,15 +26,15 @@ fn the_format_cycles_persists_and_is_restored() { 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); + assert_eq!(app.map.coord_format, CoordReadout::Map); let mut seen = Vec::new(); - for _ in 0..4 { + for _ in 0..5 { app.run("ui.coordinateFormat", Value::Null).unwrap(); seen.push(app.map.coord_format.code()); } - assert_eq!(seen, ["dms", "utm", "mgrs", "decimal"]); + assert_eq!(seen, ["decimal", "dms", "utm", "mgrs", "map"]); let writes: Vec = saved.lock().unwrap().iter().filter(|(k, _)| k == "coordinate_format").map(|(_, v)| v.clone()).collect(); - assert_eq!(writes, ["dms", "utm", "mgrs", "decimal"]); + assert_eq!(writes, ["decimal", "dms", "utm", "mgrs", "map"]); app.run("ui.coordinateFormat", json!({"format": "MGRS"})).unwrap(); assert_eq!(app.map.coord_format, CoordReadout::Mgrs); for bad in [json!({"format": "ups"}), json!({"format": 3}), json!({"format": ""})] { @@ -42,7 +42,9 @@ fn the_format_cycles_persists_and_is_restored() { assert_eq!(app.map.coord_format, CoordReadout::Mgrs, "{bad}"); } // A saved choice comes back, with nothing to say. - for (pref, want) in [("utm", CoordReadout::Utm), ("mgrs", CoordReadout::Mgrs)] { + for (pref, want) in + [("utm", CoordReadout::Utm), ("mgrs", CoordReadout::Mgrs), ("decimal", CoordReadout::Decimal), ("map", CoordReadout::Map)] + { let restored = RustGisApp::with_sample().with_services(Services { load_pref: Some(Box::new(move |k| (k == "coordinate_format").then(|| pref.to_string()))), ..Services::default() @@ -67,8 +69,8 @@ fn an_unknown_saved_format_is_said_and_kept_until_the_user_picks_one() { }); 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); + // Read in the map's coordinates, and said once. + assert_eq!(app.map.coord_format, CoordReadout::Map); 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); @@ -78,11 +80,18 @@ fn an_unknown_saved_format_is_said_and_kept_until_the_user_picks_one() { 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(); + let shown = map_readout(&h); + h.get_by_label(&shown).click(); hover_map(&mut h); - assert_eq!(h.state().map.coord_format, CoordReadout::Dms); - assert_eq!(format_writes(), ["dms"]); + assert_eq!(h.state().map.coord_format, CoordReadout::Decimal); + assert_eq!(format_writes(), ["decimal"]); +} + +/// The readout in the map's coordinates of where the pointer is. +fn map_readout(h: &egui_kittest::Harness<'_, RustGisApp>) -> String { + let app = h.state(); + let at = app.map.pointer_lonlat.expect("the pointer is over the map"); + CoordReadout::Map.readout(Some(at), true, MapSystem::of(app.session.map()).as_ref()) } /// Points the mouse at the middle of the window, over the map, for a few frames. @@ -101,6 +110,13 @@ fn the_status_bar_reads_the_pointer_in_the_chosen_format_and_a_click_switches() 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:?}"); + // First in the map's own coordinates: Web Mercator's metres, about 4.94 million east. + let shown = map_readout(&h); + assert!(shown.starts_with("494") && shown.ends_with(" mN"), "{shown}"); + h.get_by_label(&shown).click(); + hover_map(&mut h); + assert_eq!(h.state().map.coord_format, CoordReadout::Decimal); + let at = h.state().map.pointer_lonlat.expect("the pointer is over the map"); let decimal = rustgis_engine::geom::format_lonlat(at); h.get_by_label(&decimal).click(); hover_map(&mut h); @@ -119,7 +135,7 @@ fn the_status_bar_reads_the_pointer_in_the_chosen_format_and_a_click_switches() assert!(mgrs.starts_with("38S MB 4"), "{mgrs}"); h.get_by_label(&mgrs).click(); hover_map(&mut h); - assert_eq!(h.state().map.coord_format, CoordReadout::Decimal); + assert_eq!(h.state().map.coord_format, CoordReadout::Map); // Where UTM has no zone the readout gives the polar grid, UPS (MGRS without a zone number). h.state_mut().run("ui.coordinateFormat", json!({"format": "mgrs"})).unwrap(); h.state_mut().run("map.goToXY", json!({"lon": 10.0, "lat": 84.5, "scale": 10000})).unwrap(); @@ -138,6 +154,31 @@ fn the_status_bar_reads_the_pointer_in_the_chosen_format_and_a_click_switches() 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())); + // There the map's coordinates, which its projection would give on the Earth's figure, read + // as degrees. + h.state_mut().run("ui.coordinateFormat", json!({"format": "map"})).unwrap(); + hover_map(&mut h); + h.get_by_label(&rustgis_engine::geom::format_lonlat(h.state().map.pointer_lonlat.unwrap())); +} + +/// A map in the Swiss grid (LV95) reads the pointer in its eastings and northings, in metres, as +/// does the right-click menu's first row; the globe reads degrees. +#[test] +fn a_map_in_lv95_reads_eastings_and_northings() { + let mut h = harness(RustGisApp::with_sample()); + h.state_mut().run("map.projection", json!({"type": "EPSG:2056"})).unwrap(); + h.state_mut().run("map.goToXY", json!({"lon": 7.4386, "lat": 46.9511, "scale": 10000})).unwrap(); + hover_map(&mut h); + let shown = map_readout(&h); + let (e, n) = shown.split_once(" ").expect("an easting and a northing"); + let e: f64 = e.strip_suffix(" mE").and_then(|v| v.parse().ok()).expect("metres east"); + let n: f64 = n.strip_suffix(" mN").and_then(|v| v.parse().ok()).expect("metres north"); + assert!((e - 2_600_000.0).abs() < 2_000.0 && (n - 1_200_000.0).abs() < 2_000.0, "{shown}"); + h.get_by_label(&shown); + h.state_mut().run("map.projection", json!({"type": "globe"})).unwrap(); + h.state_mut().run("map.goToXY", json!({"lon": 7.4386, "lat": 46.9511, "scale": 10000})).unwrap(); + hover_map(&mut h); + h.get_by_label(&rustgis_engine::geom::format_lonlat(h.state().map.pointer_lonlat.expect("the pointer is over the globe"))); } /// Moves the mouse onto the status bar, off the map, for a few frames. @@ -149,6 +190,7 @@ fn hover_status_bar(h: &mut egui_kittest::Harness<'_, RustGisApp>) { } fn readout_at_center(h: &mut egui_kittest::Harness<'_, RustGisApp>) -> String { + h.state_mut().run("ui.coordinateFormat", json!({"format": "decimal"})).unwrap(); h.state_mut().run("map.goToXY", json!({"lon": 44.4, "lat": 33.3, "scale": 10000})).unwrap(); hover_map(h); rustgis_engine::geom::format_lonlat(h.state().map.pointer_lonlat.expect("the pointer is over the map")) diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index 254b748f37..f5c598b3e5 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -3535,6 +3535,8 @@ fn save_project_dialog_needs_downloads() { #[test] fn map_context_menu_copies_the_clicked_coordinates() { let mut h = harness(); + // In decimal degrees (the default reads in the map's own coordinates). + h.state_mut().run("ui.coordinateFormat", json!({"format": "decimal"})).unwrap(); for _ in 0..4 { h.step(); } @@ -4134,6 +4136,8 @@ fn plugin_picks_take_a_place_on_the_map() { rp::load(rp::Package::from_zip(&rp::testing::pick_package("ui-pick")).unwrap(), "test").unwrap(); let _unload = Unload("ui-pick"); let mut h = harness(); + // The status bar in decimal degrees, as the pane shows the place. + h.state_mut().run("ui.coordinateFormat", json!({"format": "decimal"})).unwrap(); h.state_mut().run("ui.pane.plugin", json!({"id": "ui-pick"})).unwrap(); h.run_steps(3); let place = |h: &egui_kittest::Harness<'_, RustGisApp>, id: &str| h.state().session.plugin_panels["ui-pick"].values[id].clone(); diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index caf24f7e5c..077324387f 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -99,7 +99,7 @@ This guide walks through RustGIS by task. Each page covers one part of the app: and closes it when it is. **Pane Sets** keep the tabs open. - **Status bar**: the scale (type one, or pick from the list), the zoom level, bearing and pitch (click them to face north and look straight down again), the pointer's coordinates (click them - to step through decimal degrees, DMS, UTM and MGRS; see [Coordinate readouts](maps.md#coordinate-readouts)), + to step through map coordinates (the map's own system, the default), decimal degrees, DMS, UTM 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 **Messages**), a **Messages** button, the last draw time, the frame rate and a **GPU**/**CPU** diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 36e46a8ea8..030ebd600a 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -315,11 +315,12 @@ and **View In Google Earth** open the place in your browser at about the same zo The status bar shows the pointer's coordinates while it is over the map, and keeps the last position (dimmed) when it leaves, so you can move to the status bar and click it. It reads `—` until the pointer has been over the map, and again after you switch to another map or open another -project. Click the coordinates to step through four formats; the choice is remembered and also +project. Click the coordinates to step through five formats; the choice is remembered and also sets the right-click menu's first row. The same place in each: | Format | Example | Notes | | --- | --- | --- | +| Map coordinates | `1703188 mE 6420339 mN` | the default: easting and northing in the map's coordinate system, named beside them in the status bar (here Web Mercator), in its unit (`m`, `ft` for international feet, `ftUS` for US survey feet, no unit for another); whole units at a unit a pixel or more, up to three decimals as you zoom in | | 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 | `33north 521567 5521996` | zone and hemisphere (`33south …` south of the equator), easting and northing in metres, rounded to the metre | @@ -337,10 +338,17 @@ reference, which has no zone number: a letter for the half (Y for western longit eastern ones in the north, A and B in the south, with the 0° and 180° meridians in Z and B), the 100 km square and the digits, truncated, `Z AC 77146 62481`. 84° N itself is UPS, 80° S itself is UTM. On the map of another body than the Earth the readout shows *No UTM here* -(or *No MGRS here*) rather than a wrong reference, and 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. 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. +(or *No MGRS here*) rather than a wrong reference, and degrees still read. Map coordinates read in +degrees on the globe and on another body's map, since the map's projection is computed on the +Earth's figure; where the map's projection doesn't reach or folds over (the far side of a polar +or oblique projection), they read *No map coordinates here*, and the right-click menu's row copies +latitude and longitude instead. A projection can reach well beyond a national grid's area of use: +London on a map in LV95 still reads eastings and northings. In map coordinates the right-click +menu's row copies the system's name after them, `2600173 mE 1200272 mN EPSG:2056`, so the copy +says which system it is in. Scripts set the format with `ui.coordinateFormat={"format":"utm"}` (`map`, `decimal`, +`dms`, `utm` or `mgrs`); without `format` it steps to the next one. A saved format this version +doesn't know, say from a newer RustGIS, reads in map coordinates with a notice, and stays saved +until you pick a format. `map.convertPosition` gives a place in all of these forms at once, without moving the map, for scripts, Python and the AI Assistant. It takes the place as `map.goToXY` does: `lon` and `lat`