From e31f19038866838fe3b84fc68a973133e66e0b1a Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:44:49 -0600 Subject: [PATCH 01/14] feat(map): an MGRS grid on the map, its squares named (#1042 piece 8) --- crates/engine/src/cmd/navigate.rs | 2 +- crates/engine/src/project.rs | 1 + crates/engine/src/project_capabilities.rs | 8 +- crates/engine/src/tests.rs | 27 +- crates/engine/tests/project_save_roundtrip.rs | 2 +- crates/map/src/graticule.rs | 15 +- crates/map/src/lib.rs | 2 +- crates/render/src/lib.rs | 133 ++++- crates/render/src/mapgrid.rs | 526 ++++++++++++++++-- crates/render/src/mesh.rs | 5 +- crates/ui-egui/src/ribbon.rs | 9 +- docs/user-guide/maps.md | 14 +- schema/project.schema.json | 6 +- 13 files changed, 667 insertions(+), 83 deletions(-) diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs index 06c5726476..b67bd77849 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -76,7 +76,7 @@ pub fn commands() -> Vec { C::new("map.basemap", "Basemap", "Home › Add", basemap).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name": "paper"|"midnight"|"ocean"|"atlas"|"blank", "keepTiles"?: bool (keeps the web tile basemaps over it)}"#), C::new("map.graticule", "Graticule", "View › Display", graticule).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"on"?: bool (toggles when omitted, on when a type or crs is given), "type"?: "degrees"|"measured"|"utm", "crs"?: a projected system for the measured grid (EPSG:2056, WKT or a PROJ string; "" or null: the map's own when projected, else the UTM zone at the view's centre)}"#), + .params(r#"{"on"?: bool (toggles when omitted, on when a type or crs is given), "type"?: "degrees"|"measured"|"utm"|"mgrs", "crs"?: a projected system for the measured grid (EPSG:2056, WKT or a PROJ string; "" or null: the map's own when projected, else the UTM zone at the view's centre)}"#), C::new("map.reloadWebLayers", "Reload Web Layers", "View › Display", |_, _| { // The map view draws again when the tile cache's generation moves. crate::render::rustgis_tiles::cache::clear(); diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 8546cc5425..a8b83fbd67 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -83,6 +83,7 @@ pub const CAPABILITIES: &[&str] = &[ "tabulate-intersection-unit", "layout-element-background", "picture-markers", + "graticule-mgrs", ]; /// The most entries a document's `requires` may list: past it the document is refused without /// the rest being read. diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 6db6e7d965..19b3a33f68 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -191,9 +191,12 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { } fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static str> { - let (mut block, mut water, mut shore, mut relief, mut light, mut legends, mut pictures) = - (false, false, false, false, false, false, false); + let (mut block, mut water, mut shore, mut relief, mut light, mut legends, mut pictures, mut mgrs) = + (false, false, false, false, false, false, false, false); for map in maps { + // An older reader doesn't know the MGRS graticule (#1042 piece 8): it refuses the + // project by name rather than failing to read the type. + mgrs |= map.graticule_type == rustgis_map::graticule::GraticuleType::Mgrs; if let Some(t) = &map.view.terrain { block |= t.block.is_some(); water |= t.water.is_some(); @@ -215,6 +218,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (light, "shaded-relief-light"), (legends, "normalized-legend-urls"), (pictures, "picture-markers"), + (mgrs, "graticule-mgrs"), ] .into_iter() .filter_map(|(used, name)| used.then_some(name)) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e1ed12c095..1224a0cf79 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12652,6 +12652,19 @@ fn a_viewshed_says_what_it_did_with_its_radius_and_the_seam() { } } +/// An older RustGIS doesn't know the MGRS graticule (#1042 piece 8): a project showing it names +/// it among what it requires, so that reader refuses the project by name; other types need nothing. +#[test] +fn an_mgrs_graticule_is_required_by_name_in_the_saved_project() { + let mut s = world(); + s.run("map.graticule", &json!({"on": true, "type": "utm"})).unwrap(); + assert!(serde_json::to_value(&s.project).unwrap().get("requires").is_none()); + s.run("map.graticule", &json!({"on": true, "type": "mgrs"})).unwrap(); + assert_eq!(serde_json::to_value(&s.project).unwrap()["requires"], json!(["graticule-mgrs"])); + s.run("map.graticule", &json!({"type": "degrees"})).unwrap(); + assert!(serde_json::to_value(&s.project).unwrap().get("requires").is_none()); +} + /// The graticule's type and the measured grid's coordinate system (#1042): a type or system given /// shows it; no parameters toggle it as before; a system that isn't projected, can't be read, or /// is given for another type is refused, naming it; a project keeps them, and one without them @@ -12669,9 +12682,19 @@ fn the_graticule_takes_a_type_and_a_measured_grids_system() { assert!(!s.map().graticule && s.map().graticule_type == GraticuleType::Utm); let r = s.run("map.graticule", &json!({"type": "measured", "crs": " EPSG:2056 "})).unwrap(); assert_eq!(r, json!({"on": true, "type": "measured", "crs": "EPSG:2056"})); + // MGRS (#1042), named in any case, and kept with the project; it takes no system either. + let r = s.run("map.graticule", &json!({"type": " Mgrs "})).unwrap(); + // (The measured grid's system is kept for when it is picked again.) + assert_eq!(r, json!({"on": true, "type": "mgrs", "crs": "EPSG:2056"})); + let back = crate::Project::from_json(&serde_json::to_string(&s.project).unwrap()).unwrap(); + assert_eq!(back.map().graticule_type, GraticuleType::Mgrs); + let got = s.run("map.graticule", &json!({"type": "mgrs", "crs": "EPSG:2056"})).unwrap_err(); + assert!(got.starts_with("crs is the measured grid's; the graticule is \"mgrs\""), "{got}"); + let r = s.run("map.graticule", &json!({"type": "measured", "crs": " EPSG:2056 "})).unwrap(); + assert_eq!(r, json!({"on": true, "type": "measured", "crs": "EPSG:2056"})); for (p, e) in [ - (json!({"type": "mgrs"}), "type must be one of degrees, measured, utm, not \"mgrs\""), - (json!({"type": 3}), "type must be one of \"degrees\", \"measured\", \"utm\", not 3"), + (json!({"type": "ups"}), "type must be one of degrees, measured, utm, mgrs, not \"ups\""), + (json!({"type": 3}), "type must be one of \"degrees\", \"measured\", \"utm\", \"mgrs\", not 3"), (json!({"crs": "EPSG:4326"}), "crs: EPSG:4326 is geographic"), (json!({"crs": "EPSG:4978"}), "crs: EPSG:4978 is geocentric"), (json!({"type": "utm", "crs": "EPSG:2056"}), "crs is the measured grid's; the graticule is \"utm\""), diff --git a/crates/engine/tests/project_save_roundtrip.rs b/crates/engine/tests/project_save_roundtrip.rs index 526d916070..019a7b8102 100644 --- a/crates/engine/tests/project_save_roundtrip.rs +++ b/crates/engine/tests/project_save_roundtrip.rs @@ -123,7 +123,7 @@ fn step() -> impl Strategy { prop::sample::select(vec!["Albers Equal Area Conic +lat_1=29.5 +lat_2=45.5", "EPSG:3857", "EPSG:4326"]) .prop_map(|t| ("map.projection", json!({"type": t}))), (-180.0..180.0f64).prop_map(|b| ("map.setBearing", json!({"bearing": b}))), - prop::sample::select(vec!["degrees", "measured", "utm"]).prop_map(|t| ("map.graticule", json!({"on": true, "type": t}))), + prop::sample::select(vec!["degrees", "measured", "utm", "mgrs"]).prop_map(|t| ("map.graticule", json!({"on": true, "type": t}))), (-180.0..180.0f64, -85.0..85.0f64, number()) .prop_map(|(x, y, s)| ("map.camera", json!({"lon": x, "lat": y, "scale": s * 1e5 + 1.0}))), name().prop_map(|n| ("map.new", json!({"name": n}))), diff --git a/crates/map/src/graticule.rs b/crates/map/src/graticule.rs index 59dcd823d3..ac2740773f 100644 --- a/crates/map/src/graticule.rs +++ b/crates/map/src/graticule.rs @@ -1,5 +1,6 @@ //! What the map's graticule draws (#1042): latitudes and longitudes, a measured grid of eastings -//! and northings in one projected system, or the UTM zones with each zone's own grid. +//! and northings in one projected system, the UTM zones with each zone's own grid, or the MGRS +//! grid with its grid zone designations and 100 km squares named. use serde::{Deserialize, Serialize}; @@ -16,10 +17,15 @@ pub enum GraticuleType { /// The UTM zones (WGS 84) and their latitude bands, with the Norway and Svalbard exceptions, /// and in each zone its own eastings and northings once few zones are in view. Utm, + /// The MGRS grid (NGA.STND.0037): the UTM zones and bands as grid zone designations, and in + /// each of a few in view its own grid at a power of ten that suits the scale (100 km to + /// 100 m), the 100 km lines heavier, named by grid zone designation or 100 km square. Nothing + /// is drawn in the polar areas (UPS) yet. + Mgrs, } impl GraticuleType { - pub const ALL: [GraticuleType; 3] = [GraticuleType::Degrees, GraticuleType::Measured, GraticuleType::Utm]; + pub const ALL: [GraticuleType; 4] = [GraticuleType::Degrees, GraticuleType::Measured, GraticuleType::Utm, GraticuleType::Mgrs]; /// The name a command takes. pub fn code(self) -> &'static str { @@ -27,6 +33,7 @@ impl GraticuleType { GraticuleType::Degrees => "degrees", GraticuleType::Measured => "measured", GraticuleType::Utm => "utm", + GraticuleType::Mgrs => "mgrs", } } @@ -36,6 +43,7 @@ impl GraticuleType { GraticuleType::Degrees => "Latitude and Longitude", GraticuleType::Measured => "Measured Grid", GraticuleType::Utm => "UTM Zones", + GraticuleType::Mgrs => "MGRS", } } @@ -67,7 +75,8 @@ mod tests { assert_eq!(GraticuleType::from_name(&t.code().to_uppercase()), Some(t)); } assert_eq!(GraticuleType::from_name(" utm "), Some(GraticuleType::Utm)); - assert_eq!(GraticuleType::from_name("mgrs"), None); + assert_eq!(GraticuleType::from_name("Mgrs"), Some(GraticuleType::Mgrs)); + assert_eq!(GraticuleType::from_name("ups"), None); } #[test] diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 72972f3fa8..74dba21690 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -1530,7 +1530,7 @@ pub struct Map { pub bookmarks: Vec, #[serde(default = "yes")] pub graticule: bool, - /// What the graticule draws: latitudes and longitudes, a measured grid or the UTM zones. + /// What the graticule draws: latitudes and longitudes, a measured grid, the UTM zones or MGRS. #[serde(default, skip_serializing_if = "graticule::GraticuleType::is_degrees")] pub graticule_type: graticule::GraticuleType, /// A measured graticule's coordinate system (`EPSG:2056`, WKT or a PROJ string): none is the diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 45534373c9..7c994cc2b2 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4204,8 +4204,12 @@ fn render_frame( } if map.graticule && grat.a() > 0 { let p = paint(grat, 1.0); - // A measured or UTM graticule's lines (#1042), else latitudes and longitudes. - let grid = mapgrid::lines(map, view); + // A measured, UTM or MGRS graticule's lines (#1042), else latitudes and longitudes; the + // MGRS grid's grid zone designations and 100 km lines (`major`) are drawn heavier. + let (major, grid) = match mapgrid::lines(map, view) { + Some(g) => (g.major, Some(g.minor)), + None => (Vec::new(), None), + }; let step = if view.camera.res > 8000.0 { 30.0 } else if view.camera.res > 2000.0 { @@ -4230,32 +4234,42 @@ fn render_frame( } lines }); - let lines = if globe.is_some() { - lines - } else if custom { - // Parallels are cut at the map's edge like any line (#209). - match flat.project(&Geometry::Line(lines)) { - Geometry::Line(parts) => parts, - _ => Vec::new(), + let project = |lines: Vec>| -> Vec> { + if globe.is_some() { + lines + } else if custom { + // Parallels are cut at the map's edge like any line (#209). + match flat.project(&Geometry::Line(lines)) { + Geometry::Line(parts) => parts, + _ => Vec::new(), + } + } else { + lines.into_iter().map(|l| l.into_iter().map(lonlat_to_merc).collect()).collect() } - } else { - lines.into_iter().map(|l| l.into_iter().map(lonlat_to_merc).collect()).collect() }; - if gpu { - let mut e = Extent::EMPTY; - for l in &lines { - for c in l { - e.expand(*c); - } + let (lines, major) = (project(lines), project(major)); + // The minor lines always (as every graticule drew its lines before #1042's MGRS grid), + // the major ones over them when there are any. + for (lines, width, always) in [(lines, 0.6f32, true), (major, 1.2, false)] { + if !always && lines.is_empty() { + continue; } - flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty)?; - let tessellated = !e.is_empty() && mesh::collect_graticule(&mut cmds, &lines, &e, grat, ctx.ppp, map_per_px).is_ok(); - if !tessellated { - ctx.line(&mut pm, &lines, &p, 0.6); - cpu_dirty = true; + if gpu { + let mut e = Extent::EMPTY; + for l in &lines { + for c in l { + e.expand(*c); + } + } + flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty)?; + let tessellated = !e.is_empty() && mesh::collect_graticule(&mut cmds, &lines, &e, grat, width, ctx.ppp, map_per_px).is_ok(); + if !tessellated { + ctx.line(&mut pm, &lines, &p, width); + cpu_dirty = true; + } + } else { + ctx.line(&mut pm, &lines, &p, width); } - } else { - ctx.line(&mut pm, &lines, &p, 0.6); } } @@ -5652,7 +5666,51 @@ fn render_frame( }; post::apply(pm.pixels(), &map.view.effects, vision, &lonlat); } - let labels = placed.labels; + let mut labels = placed.labels; + let mut label_layers = label_layers; + // The MGRS graticule's names (#1042), over the placed labels and apart from their collisions, + // with no layer of their own in a recording. A tilted view's bands draw none: their places + // would repeat from band to band. + if map.graticule && grat.a() > 0 && matches!(labels_to, Labels::Own | Labels::Turned(_)) { + let color = Rgba::rgb(grat.r(), grat.g(), grat.b()); + for (text, x, y) in mapgrid::labels(map, view, |t| text::measure(t, mapgrid::LABEL_PT, false)) { + // Into the turned view's screen, as the placed labels are. + let (x, y) = match turned { + Some(to) => { + let (sx, sy) = to.to_screen(view.camera.to_map(f64::from(x), f64::from(y), view.width, view.height)); + if !((0.0..=to.width).contains(&sx) && (0.0..=to.height).contains(&sy)) { + continue; + } + (sx as f32, sy as f32) + } + None => (x, y), + }; + labels.push(PlacedLabel { + text, + x, + y, + size: mapgrid::LABEL_PT, + color, + halo: Some(halo_for(color)), + halo_width: None, + bold: false, + icon: None, + align: 0.0, + framed: false, + italic: false, + spacing: 0.0, + font: None, + line_align: TextAlign::Center, + angle: None, + collide: Default::default(), + glyphs: Vec::new(), + background: None, + }); + if pm.is_recording() { + label_layers.push((u32::MAX, String::new())); + } + } + } let attribution = tile_out.attribution; let tiles_pending = tile_out.pending; let tile_errors = tile_out.errors; @@ -8672,6 +8730,31 @@ mod tests { assert!(!world().is_empty()); } + /// The MGRS graticule's names (#1042) come with the frame's placed labels, after them, in the + /// graticule's color with a halo, on a turned view too; another graticule has none, nor does + /// a hidden one. + #[test] + fn the_mgrs_graticule_names_come_with_the_labels() { + let mut m = Map::new("Map"); + m.graticule_type = rustgis_map::graticule::GraticuleType::Mgrs; + let camera = Camera { center: lonlat_to_merc(Coord::new(14.5, 48.2)), res: 500.0, bearing: 0.0, pitch: 0.0 }; + let view = View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera, sky: false }; + let grid = |m: &mut Map, view: &View| -> Vec { + render(m, view).unwrap().labels.into_iter().filter(|l| l.size == mapgrid::LABEL_PT && l.halo.is_some()).collect() + }; + let named = grid(&mut m, &view); + assert!(named.iter().any(|l| l.text == "33U VP"), "{:?}", named.iter().map(|l| &l.text).collect::>()); + let (.., grat) = m.palette(); + assert!(named.iter().all(|l| (l.color.r(), l.color.g(), l.color.b(), l.color.a()) == (grat.r(), grat.g(), grat.b(), 255))); + let turned = View { camera: Camera { bearing: 30.0, ..camera }, ..view }; + assert!(!grid(&mut m, &turned).is_empty()); + m.graticule_type = rustgis_map::graticule::GraticuleType::Utm; + assert!(grid(&mut m, &view).is_empty()); + m.graticule_type = rustgis_map::graticule::GraticuleType::Mgrs; + m.graticule = false; + assert!(grid(&mut m, &view).is_empty()); + } + #[test] fn a_selected_text_graphic_is_framed_with_its_label() { let mut m = Map::new("Map"); diff --git a/crates/render/src/mapgrid.rs b/crates/render/src/mapgrid.rs index 37e946b0a8..79651fcf90 100644 --- a/crates/render/src/mapgrid.rs +++ b/crates/render/src/mapgrid.rs @@ -1,9 +1,13 @@ -//! The lines of the map's measured and UTM graticules (#1042), in longitude/latitude for the +//! The lines of the map's measured, UTM and MGRS graticules (#1042), in longitude/latitude for the //! graticule's drawing to project like its latitudes and longitudes. A measured grid is a layout's //! measured grid (#1012) over the view; the UTM one draws the zones and latitude bands, and in each -//! zone in view its own eastings and northings. +//! zone in view its own eastings and northings. The MGRS one (NGA.STND.0037) draws the same zones +//! and bands as grid zone designations, each one's grid at a power of ten that suits the scale, and +//! names the grid zone designations or the 100 km squares in view. -use rustgis_geom::utm::{UTM_MAX_LAT, UTM_MIN_LAT, band_latitudes, zone_longitudes}; +use rustgis_geom::utm::{ + UTM_MAX_LAT, UTM_MIN_LAT, band_latitudes, from_utm, latitude_band, square_letters, to_utm_in_zone, utm_zone, zone_longitudes, +}; use rustgis_geom::{Coord, Extent}; use rustgis_map::Map; use rustgis_map::globe::Globe; @@ -23,22 +27,46 @@ const MAX_GRIDDED_CELLS: usize = 8; /// The points a meridian or a parallel is drawn with, per degree. const PER_DEGREE: f64 = 2.0; -/// The graticule's lines in longitude/latitude for a measured or UTM graticule; `None` for +/// The side of an MGRS 100 km square, in meters: the MGRS grid's coarsest step. +const SQUARE: f64 = 100_000.0; +/// The MGRS grid's finest step, in meters. +const MGRS_FINEST: f64 = 100.0; +/// The most grid zone designations in view whose grid is drawn finer than 100 km: four meet at a +/// corner; past them the view is wide enough for 100 km lines. +const FEW_CELLS: usize = 4; +/// The size of the MGRS graticule's labels, in points (as a layout's MGRS square labels). +pub(crate) const LABEL_PT: f32 = 10.0; +/// The places across and down a 100 km square (and half as many across a grid zone designation) +/// whose middle on the screen places its label. +const LABEL_SAMPLES: u32 = 8; +/// The most 100 km squares of one grid zone designation looked at for names in one view. +const MAX_SQUARES: i64 = 400; + +/// A graticule's lines in longitude/latitude, in two weights: the MGRS grid's grid zone +/// designations and 100 km lines are `major`, drawn heavier; every other line is `minor`. +#[derive(Debug, Default)] +pub(crate) struct GridLines { + pub(crate) major: Vec>, + pub(crate) minor: Vec>, +} + +/// The graticule's lines in longitude/latitude for a measured, UTM or MGRS graticule; `None` for /// latitudes and longitudes, which the graticule draws itself. They cover the view and the margin /// around it the GPU moves a frame's meshes within while panning ([`crate::GPU_CULL_MARGIN`]), at /// the step the view itself suits. -pub(crate) fn lines(map: &Map, view: &View) -> Option>> { +pub(crate) fn lines(map: &Map, view: &View) -> Option { if map.graticule_type == GraticuleType::Degrees { return None; } let globe = map.projection.is_globe().then(|| Globe::new(&view.camera, view.width, view.height)); let (shown, around) = (in_view(map, view, globe.as_ref(), 0.0), in_view(map, view, globe.as_ref(), crate::GPU_CULL_MARGIN)); let center = at(map, view, globe.as_ref(), view.width / 2.0, view.height / 2.0).or_else(|| shown.get(shown.len() / 2).copied()); - let Some(center) = center else { return Some(Vec::new()) }; + let Some(center) = center else { return Some(GridLines::default()) }; Some(match map.graticule_type { - GraticuleType::Degrees => Vec::new(), - GraticuleType::Measured => measured(map, center, &shown, &around), - GraticuleType::Utm => utm(center, &shown, &around), + GraticuleType::Degrees => GridLines::default(), + GraticuleType::Measured => GridLines { minor: measured(map, center, &shown, &around), major: Vec::new() }, + GraticuleType::Utm => zones(center, &shown, &around, false), + GraticuleType::Mgrs => zones(center, &shown, &around, true), }) } @@ -68,14 +96,33 @@ fn in_view(map: &Map, view: &View, globe: Option<&Globe>, margin: f64) -> Vec Option { +/// How far the places `shown` reach across or down, the more of the two, in `tr`'s system. +fn span_over(tr: &rustgis_data::raster::Transformer, shown: &[Coord]) -> Option { let mut m = Extent::EMPTY; for c in shown.iter().filter_map(|c| tr.from_lonlat(*c)) { m.expand(c); } - (!m.is_empty() && m.width().is_finite() && m.height().is_finite()) - .then(|| nice_step(m.width().max(m.height()), rustgis_map::layout::MIN_MEASURED_STEP)) + (!m.is_empty() && m.width().is_finite() && m.height().is_finite()).then(|| m.width().max(m.height())) +} + +/// The step that draws about eight lines across the places `shown`, in `tr`'s system. +fn step_over(tr: &rustgis_data::raster::Transformer, shown: &[Coord]) -> Option { + span_over(tr, shown).map(|span| nice_step(span, rustgis_map::layout::MIN_MEASURED_STEP)) +} + +/// The MGRS grid's step for a view `span` meters across (the more of across and down) showing +/// `cells` grid zone designations: the power of ten, from 100 m to 100 km, that draws between +/// three and thirty lines across it (NGA.STND.0037 asks for a power of ten that suits the scale); +/// 100 km while more than [`FEW_CELLS`] grid zone designations show. +fn mgrs_step(span: f64, cells: usize) -> f64 { + if cells > FEW_CELLS { + return SQUARE; + } + let (finest, coarsest) = (MGRS_FINEST.log10(), SQUARE.log10()); + let power = (span / 3.0).log10().floor(); + // (A view of no width, or a span that isn't a number: the finest step.) + let power = if power.is_nan() { finest } else { power.clamp(finest, coarsest) }; + 10f64.powi(power as i32) } /// A measured grid over the view and around it: the layout's measured grid in the map's graticule @@ -113,49 +160,73 @@ fn extents(places: &[Coord]) -> Vec { vec![e] } -/// The UTM zones and latitude bands in view and around it, and in each of a few zones in view its -/// eastings and northings, one step apart in all of them (the step the view suits in the zone at -/// its centre). +/// Every UTM zone-and-band cell (grid zone designation): its zone, band, and longitudes and +/// latitudes, with the Norway and Svalbard exceptions. +fn cells() -> impl Iterator { + BANDS.chars().flat_map(|band| { + (1..=60u8).filter_map(move |zone| { + let (south, north) = band_latitudes(band)?; + let (west, east) = zone_longitudes(zone, band)?; + Some((zone, band, Extent { min_x: west, min_y: south, max_x: east, max_y: north })) + }) + }) +} + +/// How many zone-and-band cells the view itself shows (`shown`: places over it). +fn cells_seen(shown: &[Coord]) -> usize { + let seen_parts = extents(shown); + cells().filter(|(_, _, c)| seen_parts.iter().any(|e| overlaps(c, e))).count() +} + +/// The UTM graticule's lines (all of them minor; see [`zones`]). +#[cfg(test)] fn utm(center: Coord, shown: &[Coord], around: &[Coord]) -> Vec> { + zones(center, shown, around, false).minor +} + +/// The UTM zones and latitude bands in view and around it, and in each of a few zones in view its +/// own grid, one step apart in all of them, cut at the zone's edges. For UTM (`mgrs` false) the +/// step is the one the view suits in the zone at its center, and every line is minor; for MGRS a +/// power of ten ([`mgrs_step`]), with the zones' edges and the 100 km lines major. +fn zones(center: Coord, shown: &[Coord], around: &[Coord], mgrs: bool) -> GridLines { + let mut out = GridLines::default(); let parts = extents(around); if parts.is_empty() { - return Vec::new(); + return out; } let has_lon = |lon: f64, south: f64, north: f64| parts.iter().any(|e| e.min_x <= lon && lon <= e.max_x && e.min_y <= north && south <= e.max_y); - let mut lines = Vec::new(); + let edges = if mgrs { &mut out.major } else { &mut out.minor }; // Each zone's western edge within each band, and the last zone's eastern one at 180°, so the // Norway and Svalbard zones are drawn as they are. - let mut cells = Vec::new(); for band in BANDS.chars() { let Some((south, north)) = band_latitudes(band) else { continue }; - for zone in 1..=60u8 { - let Some((west, east)) = zone_longitudes(zone, band) else { continue }; - cells.push((zone, band, Extent { min_x: west, min_y: south, max_x: east, max_y: north })); - if has_lon(west, south, north) { - lines.push(meridian(west, south, north)); + for (_, _, cell) in cells().filter(|(_, b, _)| *b == band) { + if has_lon(cell.min_x, south, north) { + edges.push(meridian(cell.min_x, south, north)); } } if has_lon(180.0, south, north) { - lines.push(meridian(180.0, south, north)); + edges.push(meridian(180.0, south, north)); } } // The bands' edges, and the zones' southern and northern limits. - let edges = BANDS.chars().filter_map(|b| band_latitudes(b).map(|(south, _)| south)).chain([UTM_MAX_LAT]); - for lat in edges { + let lats = BANDS.chars().filter_map(|b| band_latitudes(b).map(|(south, _)| south)).chain([UTM_MAX_LAT]); + for lat in lats { for e in parts.iter().filter(|e| e.min_y <= lat && lat <= e.max_y) { - lines.push(parallel(lat, e.min_x.max(-180.0), e.max_x.min(180.0))); + edges.push(parallel(lat, e.min_x.max(-180.0), e.max_x.min(180.0))); } } // Eastings and northings when few zone-and-band cells are in the view itself (not counting // the margin, so they don't come and go as it pans), drawn over the margin too. - let seen_parts = extents(shown); - let seen_cells = cells.iter().filter(|(_, _, c)| seen_parts.iter().any(|e| overlaps(c, e))).count(); + let seen_cells = cells_seen(shown); if seen_cells == 0 || seen_cells > MAX_GRIDDED_CELLS { - return lines; + return out; } - let in_view: Vec<_> = cells.into_iter().filter_map(|(z, b, c)| parts.iter().find(|e| overlaps(&c, e)).map(|e| (z, b, c, *e))).collect(); - let Some(step) = zone_transformer(center).and_then(|tr| step_over(&tr, shown)) else { return lines }; + let in_view: Vec<_> = cells().filter_map(|(z, b, c)| parts.iter().find(|e| overlaps(&c, e)).map(|e| (z, b, c, *e))).collect(); + let step = zone_transformer(center) + .and_then(|tr| if mgrs { span_over(&tr, shown).map(|span| mgrs_step(span, seen_cells)) } else { step_over(&tr, shown) }); + let Some(step) = step else { return out }; for (zone, band, cell, e) in in_view { let north = band >= 'N'; let epsg = if north { 32_600 } else { 32_700 } + u32::from(zone); @@ -178,11 +249,181 @@ fn utm(center: Coord, shown: &[Coord], around: &[Coord]) -> Vec> { let g = Grid { kind: GridKind::Measured, step, labels: false, ..Grid::default() }; let mut zone_lines = Vec::new(); measured_lines(&g, &tr, &frame, false, &mut zone_lines); - for (pts, _, _) in zone_lines { - lines.extend(clip(&pts, &cell)); + for (pts, _, easting) in zone_lines { + // An MGRS line at a whole 100 km (its first point's easting or northing) bounds squares. + let value = pts.first().and_then(|c| tr.from_lonlat(*c)).map(|p| if easting { p.x } else { p.y }); + let major = mgrs && value.is_some_and(|v| (v - (v / SQUARE).round() * SQUARE).abs() < 1.0); + let to = if major { &mut out.major } else { &mut out.minor }; + to.extend(clip(&pts, &cell)); } } - lines + out +} + +/// The MGRS graticule's labels on `view` (text, and its center in the view's points), none for +/// another type. Zoomed out, or while the 100 km squares are too small on the screen to name, each +/// grid zone designation in view is named (`33U`) at the middle of what shows of it; zoomed in, +/// each 100 km square of each one, by its letters (`VP`), with its grid zone designation (`33U VP`) +/// when more than one is in view. A label goes only where all of it stays within its zone and +/// square and the view, so a zone or square cut too small isn't named. Nothing is named in the polar +/// areas (UPS). `width` measures a text across in points at [`LABEL_PT`]. +pub(crate) fn labels(map: &Map, view: &View, width: impl Fn(&str) -> f32) -> Vec<(String, f32, f32)> { + if map.graticule_type != GraticuleType::Mgrs { + return Vec::new(); + } + let globe = map.projection.is_globe().then(|| Globe::new(&view.camera, view.width, view.height)); + let globe = globe.as_ref(); + let (w, h) = (view.width, view.height); + let on_view = |(x, y): (f64, f64)| (0.0..=w).contains(&x) && (0.0..=h).contains(&y); + // Where a place is drawn, on the view or off it (on a globe, only on its near side). + let project = |c: Coord| -> Option<(f64, f64)> { + let s = match globe { + Some(g) => g.forward(c)?, + None => view.to_screen(map.to_map(c)?), + }; + (s.0.is_finite() && s.1.is_finite()).then_some(s) + }; + // Where a place is on the view, if it is on it. + let screen = |c: Coord| project(c).filter(|s| on_view(*s)); + let place = |x: f64, y: f64| at(map, view, globe, x, y); + let shown = in_view(map, view, globe, 0.0); + let parts = extents(&shown); + let seen: Vec<(u8, char, Extent)> = cells().filter(|(_, _, c)| parts.iter().any(|e| overlaps(c, e))).collect(); + if seen.is_empty() { + return Vec::new(); + } + // A 100 km square's side on the screen at the view's center, from a kilometer's. + let label_h = f64::from(LABEL_PT) * 1.33 * 1.2; + let square_pt = place(w / 2.0, h / 2.0).and_then(|c| { + let (zone, north) = (utm_zone(c)?, c.y >= 0.0); + let (e, n) = to_utm_in_zone(c, zone, north)?; + let (sx, sy) = screen(c)?; + let side = |p: Option| p.and_then(project).map(|(x, y)| (x - sx).hypot(y - sy) * SQUARE / 1000.0); + Some(side(from_utm(zone, north, e + 1000.0, n))?.min(side(from_utm(zone, north, e, n + 1000.0))?)) + }); + // Squares named once the 100 km lines are drawn and a square is three labels tall. + let squares = seen.len() <= MAX_GRIDDED_CELLS && square_pt.is_some_and(|s| s >= 3.0 * label_h); + // The grid zone designations in view: with more than one, a square's name carries its own. + let mut gzds: Vec<(u8, char)> = shown.iter().filter_map(|c| Some((utm_zone(*c)?, latitude_band(c.y)?))).collect(); + gzds.sort_unstable(); + gzds.dedup(); + let one_gzd = gzds.len() <= 1; + let mut out: Vec<(String, f32, f32)> = Vec::new(); + let mut named = std::collections::BTreeSet::new(); + for (zone, band, cell) in seen { + let north = band >= 'N'; + let gzd = format!("{zone:02}{band}"); + let in_cell = |c: Coord| utm_zone(c) == Some(zone) && latitude_band(c.y) == Some(band); + for e in parts.iter().filter(|e| overlaps(&cell, e)) { + let part = Extent { + min_x: cell.min_x.max(e.min_x), + min_y: cell.min_y.max(e.min_y), + max_x: cell.max_x.min(e.max_x), + max_y: cell.max_y.min(e.max_y), + }; + if !squares { + let samples = grid_of(LABEL_SAMPLES / 2, part.min_x, part.min_y, part.max_x, part.max_y).filter(|c| in_cell(*c)); + let Some((x, y)) = middle(samples.filter_map(&screen)) else { continue }; + let fits = |c: Coord| in_cell(c); + if !named.contains(&(zone, band, 0, 0)) && label_fits(&gzd, (x, y), &width, label_h, on_view, place, fits) { + named.insert((zone, band, 0, 0)); + out.push((gzd.clone(), x as f32, y as f32)); + } + continue; + } + // The squares the part reaches, by its edges' eastings and northings in the zone. + let mut m = Extent::EMPTY; + for c in frame_of(&part) { + if let Some((x, y)) = to_utm_in_zone(c, zone, north) { + m.expand(Coord::new(x, y)); + } + } + if m.is_empty() { + continue; + } + let (pad_x, pad_y) = (m.width() * 0.01, m.height() * 0.01); + let (e0, e1) = (((m.min_x - pad_x) / SQUARE).floor() as i64, ((m.max_x + pad_x) / SQUARE).floor() as i64); + let (n0, n1) = (((m.min_y - pad_y) / SQUARE).floor() as i64, ((m.max_y + pad_y) / SQUARE).floor() as i64); + if (e1 - e0 + 1).saturating_mul(n1 - n0 + 1) > MAX_SQUARES { + continue; + } + for (ie, inn) in (e0..=e1).flat_map(|ie| (n0..=n1).map(move |inn| (ie, inn))) { + let (se, sn) = (ie as f64 * SQUARE, inn as f64 * SQUARE); + let Some((column, row)) = square_letters(zone, se + SQUARE / 2.0, sn + SQUARE / 2.0) else { continue }; + // What of the square the part reaches, sampled in the zone's grid. + let (x0, x1) = (se.max(m.min_x - pad_x), (se + SQUARE).min(m.max_x + pad_x)); + let (y0, y1) = (sn.max(m.min_y - pad_y), (sn + SQUARE).min(m.max_y + pad_y)); + if x0 >= x1 || y0 >= y1 { + continue; + } + let samples = + grid_of(LABEL_SAMPLES, x0, y0, x1, y1).filter_map(|p| from_utm(zone, north, p.x, p.y)).filter(|c| in_cell(*c)); + let Some((x, y)) = middle(samples.filter_map(&screen)) else { continue }; + let text = if one_gzd { format!("{column}{row}") } else { format!("{gzd} {column}{row}") }; + let fits = |c: Coord| { + in_cell(c) + && to_utm_in_zone(c, zone, north) + .is_some_and(|(x, y)| (x / SQUARE).floor() as i64 == ie && (y / SQUARE).floor() as i64 == inn) + }; + if !named.contains(&(zone, band, ie, inn)) && label_fits(&text, (x, y), &width, label_h, on_view, place, fits) { + named.insert((zone, band, ie, inn)); + out.push((text, x as f32, y as f32)); + } + } + } + } + out +} + +/// `n` places across and down a box, at the middles of its cells. +fn grid_of(n: u32, x0: f64, y0: f64, x1: f64, y1: f64) -> impl Iterator { + (0..n).flat_map(move |i| { + (0..n).map(move |j| { + let (ti, tj) = ((f64::from(i) + 0.5) / f64::from(n), (f64::from(j) + 0.5) / f64::from(n)); + Coord::new(x0 + (x1 - x0) * ti, y0 + (y1 - y0) * tj) + }) + }) +} + +/// A longitude/latitude box's edges, eight points a side. +fn frame_of(b: &Extent) -> Vec { + (0..=8) + .flat_map(|i| { + let t = f64::from(i) / 8.0; + let (x, y) = (b.min_x + b.width() * t, b.min_y + b.height() * t); + [Coord::new(x, b.min_y), Coord::new(x, b.max_y), Coord::new(b.min_x, y), Coord::new(b.max_x, y)] + }) + .collect() +} + +/// The middle of points on the screen; `None` for none. +fn middle(points: impl Iterator) -> Option<(f64, f64)> { + let (mut sx, mut sy, mut n) = (0.0, 0.0, 0u32); + for (x, y) in points { + (sx, sy, n) = (sx + x, sy + y, n + 1); + } + (n > 0).then(|| (sx / f64::from(n), sy / f64::from(n))) +} + +/// Whether a label `text` centered at `(x, y)` (points), with a little room around it, lies on the +/// view (`on_view`) and over the place it names (`fits`, for the places under its corners, its +/// edges' middles and its center, as `place` finds them). +fn label_fits( + text: &str, + (x, y): (f64, f64), + width: impl Fn(&str) -> f32, + label_h: f64, + on_view: impl Fn((f64, f64)) -> bool, + place: impl Fn(f64, f64) -> Option, + fits: impl Fn(Coord) -> bool, +) -> bool { + let (hw, hh) = (f64::from(width(text)) / 2.0 + 2.0, label_h / 2.0 + 2.0); + [(-1.0, -1.0), (0.0, -1.0), (1.0, -1.0), (-1.0, 0.0), (0.0, 0.0), (1.0, 0.0), (-1.0, 1.0), (0.0, 1.0), (1.0, 1.0)].iter().all( + |&(kx, ky)| { + let p = (x + kx * hw, y + ky * hh); + on_view(p) && place(p.0, p.1).is_some_and(&fits) + }, + ) } /// The transformer of the UTM zone at `c` (by its 6° zone and hemisphere), made once a code. @@ -301,10 +542,10 @@ mod tests { let (mut m, view) = winterthur("EPSG:2056"); assert!(lines(&m, &view).is_none(), "latitudes and longitudes"); m.graticule_type = GraticuleType::Measured; - let own = lines(&m, &view).unwrap(); + let own = lines(&m, &view).unwrap().minor; assert!(straight_in(&own, 2056), "{own:?}"); m.graticule_crs = Some("EPSG:32632".into()); - let utm = lines(&m, &view).unwrap(); + let utm = lines(&m, &view).unwrap().minor; assert!(straight_in(&utm, 32632) && !straight_in(&utm, 2056)); // On a Web Mercator map with no system given: the UTM zone at the view's centre (32N). let (mut m, _) = winterthur("EPSG:3857"); @@ -312,7 +553,7 @@ mod tests { let center = m.to_map(Coord::new(8.73, 47.5)).unwrap(); let view = View { camera: rustgis_map::camera::Camera::new(center, 10.0), ..view }; m.graticule_type = GraticuleType::Measured; - assert!(straight_in(&lines(&m, &view).unwrap(), 32632)); + assert!(straight_in(&lines(&m, &view).unwrap().minor, 32632)); } /// The grid covers the margin around the view that the GPU pans a frame within, so panning @@ -331,7 +572,7 @@ mod tests { } let mut drawn = Extent::EMPTY; let mut eastings = Vec::new(); - for l in lines(&m, &view).unwrap() { + for l in lines(&m, &view).unwrap().minor { let pts: Vec = l.iter().map(|c| tr.from_lonlat(*c).unwrap()).collect(); pts.iter().for_each(|p| drawn.expand(*p)); if pts.iter().all(|p| (p.x - pts[0].x).abs() < 0.01) { @@ -447,4 +688,209 @@ mod tests { // Lines on both sides. assert!(inner.iter().any(|l| l.iter().all(|c| c.x < 12.0)) && inner.iter().any(|l| l.iter().all(|c| c.x > 12.0))); } + + /// Places over a longitude/latitude box, 13 a side. + fn over(w: f64, s: f64, e: f64, n: f64) -> Vec { + (0..=12) + .flat_map(|i| (0..=12).map(move |j| Coord::new(w + (e - w) * f64::from(i) / 12.0, s + (n - s) * f64::from(j) / 12.0))) + .collect() + } + + /// A Web Mercator map with the MGRS graticule, its view 800 × 600 points centered on `lon`, + /// `lat` at `res` Web Mercator meters a point. + fn mgrs_view(lon: f64, lat: f64, res: f64) -> (Map, View) { + let mut m = Map::new("m"); + m.graticule_type = GraticuleType::Mgrs; + let center = m.to_map(Coord::new(lon, lat)).unwrap(); + let camera = rustgis_map::camera::Camera::new(center, res); + (m, View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera, sky: false }) + } + + /// The MGRS labels on a view, with each character 6 points across. + fn labels_on(m: &Map, view: &View) -> Vec<(String, f32, f32)> { + labels(m, view, |t| t.chars().count() as f32 * 6.0) + } + + /// Whether each label names the place under its center as `to_mgrs` does (`name` writes it). + fn name_their_places(m: &Map, view: &View, labels: &[(String, f32, f32)], name: impl Fn(&rustgis_geom::Mgrs) -> String) { + let globe = m.projection.is_globe().then(|| Globe::new(&view.camera, view.width, view.height)); + for (text, x, y) in labels { + let c = at(m, view, globe.as_ref(), f64::from(*x), f64::from(*y)).unwrap(); + let r = rustgis_geom::to_mgrs(c, 0).unwrap(); + assert_eq!(text, &name(&r), "at {c:?}"); + } + } + + fn gzd(r: &rustgis_geom::Mgrs) -> String { + format!("{:02}{}", r.zone, r.band) + } + + /// A line's easting (`true`) or northing in `tr`'s system, when it keeps one. + fn grid_value(l: &[Coord], tr: &rustgis_data::raster::Transformer) -> Option<(bool, f64)> { + let pts: Vec = l.iter().filter_map(|c| tr.from_lonlat(*c)).collect(); + let first = pts.first()?; + if pts.iter().all(|p| (p.x - first.x).abs() < 0.01) { + Some((true, first.x)) + } else if pts.iter().all(|p| (p.y - first.y).abs() < 0.01) { + Some((false, first.y)) + } else { + None + } + } + + /// The MGRS grid's step is a power of ten, three to thirty lines across the view, from 100 km + /// to 100 m, and 100 km while more than four grid zone designations show. + #[test] + fn the_mgrs_step_is_a_power_of_ten_by_scale() { + for (span, cells, step) in [ + (2e6, 2, 1e5), + (4e5, 1, 1e5), + (2e5, 1, 1e4), + (3.1e4, 1, 1e4), + (2.9e4, 1, 1e3), + (3.1e3, 4, 1e3), + (2.9e3, 1, 100.0), + (50.0, 1, 100.0), + (0.0, 1, 100.0), + (f64::NAN, 1, 100.0), + (f64::INFINITY, 1, 1e5), + (3.1e3, 5, 1e5), + ] { + assert_eq!(mgrs_step(span, cells), step, "{span} m, {cells} cells"); + } + } + + /// Zoomed in on zone 33U, the MGRS grid draws 100 km, 10 km, 1 km, then 100 m lines (finest), + /// the 100 km ones (the central meridian's 500 km easting among them) major, the finer minor; + /// zoomed out over several zones, 100 km lines only, all major. + #[test] + fn the_mgrs_grid_steps_by_scale_with_its_100_km_lines_major() { + let tr = rustgis_data::raster::Crs::from_epsg(32633).unwrap().transformer().unwrap(); + for (res, step) in [(100.0, 1e4), (10.0, 1e3), (1.0, 100.0), (0.1, 100.0)] { + let (m, view) = mgrs_view(15.0, 49.5, res); + let g = lines(&m, &view).unwrap(); + let minor: Vec<_> = g.minor.iter().filter_map(|l| grid_value(l, &tr)).collect(); + let major: Vec<_> = g.major.iter().filter_map(|l| grid_value(l, &tr)).collect(); + assert!(!minor.is_empty() && minor.len() == g.minor.len(), "{res}: {} of {}", minor.len(), g.minor.len()); + for (_, v) in &minor { + let whole = |s: f64| (v / s - (v / s).round()).abs() < 1e-6; + assert!(whole(step) && !whole(1e5), "{res}: {v} at {step}"); + } + assert!(major.iter().any(|(e, v)| *e && (v - 500_000.0).abs() < 0.01), "{res}: {major:?}"); + assert!(major.iter().all(|(_, v)| (v / 1e5 - (v / 1e5).round()).abs() < 1e-6), "{res}: {major:?}"); + } + // About 7° across: zones 32 to 34, so 100 km lines only. + let (m, view) = mgrs_view(15.0, 49.5, 1000.0); + let g = lines(&m, &view).unwrap(); + assert!(g.minor.is_empty() && g.major.len() > 20, "{} minor, {} major", g.minor.len(), g.major.len()); + } + + /// Other graticules draw no major lines and no labels. + #[test] + fn other_graticules_keep_one_weight_and_no_labels() { + let (mut m, view) = mgrs_view(15.0, 49.5, 10.0); + assert!(!labels_on(&m, &view).is_empty()); + for t in [GraticuleType::Measured, GraticuleType::Utm] { + m.graticule_type = t; + let g = lines(&m, &view).unwrap(); + assert!(g.major.is_empty() && !g.minor.is_empty(), "{t:?}"); + assert!(labels_on(&m, &view).is_empty(), "{t:?}"); + } + m.graticule_type = GraticuleType::Degrees; + assert!(lines(&m, &view).is_none() && labels_on(&m, &view).is_empty()); + } + + /// The MGRS grid keeps to each grid zone designation as UTM's does: near Salzburg each zone's + /// lines stay on its side of 12° E; in southern Norway 32V reaches west of 6° E, so zone 32's + /// lines cross 6° E; across the antimeridian zone 60's edge at 180° is drawn, major. + #[test] + fn mgrs_lines_keep_to_their_grid_zone_designation() { + let seen = over(11.6, 47.3, 12.4, 47.7); + let g = zones(Coord::new(12.0, 47.5), &seen, &seen, true); + let all: Vec<_> = g.major.iter().chain(&g.minor).collect(); + for l in &all { + assert!(l.iter().all(|c| c.x <= 12.0 + 1e-9) || l.iter().all(|c| c.x >= 12.0 - 1e-9), "across 12° E: {l:?}"); + } + assert!(all.iter().any(|l| l.iter().all(|c| c.x < 12.0)) && all.iter().any(|l| l.iter().all(|c| c.x > 12.0))); + // Southern Norway: no edge at 6° E in band V, and zone 32's grid across it. + let seen = over(5.5, 59.8, 6.5, 60.2); + let g = zones(Coord::new(6.0, 60.0), &seen, &seen, true); + assert!(!g.major.iter().any(|l| l.iter().all(|c| (c.x - 6.0).abs() < 1e-9))); + let tr = rustgis_data::raster::Crs::from_epsg(32632).unwrap().transformer().unwrap(); + let grid: Vec<_> = g.minor.iter().filter(|l| grid_value(l, &tr).is_some()).collect(); + assert!(grid.len() > 4 && grid.iter().any(|l| l.iter().any(|c| c.x < 6.0) && l.iter().any(|c| c.x > 6.0)), "{}", grid.len()); + // Svalbard's band X: its edges at 9°, 21° and 33° E, none at 12° E. + let seen = over(0.0, 74.0, 40.0, 82.0); + let g = zones(Coord::new(20.0, 78.0), &seen, &seen, true); + let edge = |lon: f64| g.major.iter().any(|l| l.iter().all(|c| (c.x - lon).abs() < 1e-9) && l.iter().any(|c| c.y > 76.0)); + assert!(edge(9.0) && edge(21.0) && edge(33.0) && !edge(12.0)); + // Fiji, across the antimeridian. + let seen: Vec = + over(179.4, -17.6, 180.6, -17.0).into_iter().map(|c| Coord::new(if c.x > 180.0 { c.x - 360.0 } else { c.x }, c.y)).collect(); + let g = zones(Coord::new(179.9, -17.3), &seen, &seen, true); + assert!(g.major.iter().any(|l| l.iter().all(|c| (c.x - 180.0).abs() < 1e-9))); + let inner = g.minor.iter().chain(&g.major).filter(|l| !l.iter().all(|c| (c.x - l[0].x).abs() < 1e-9)).count(); + assert!(inner > 4, "{inner}"); + } + + /// The 100 km squares are named by their letters at their places, checked against + /// GeographicLib's GeoConvert (`GeoConvert -m -p 0`): 48.5° N 14.5° E is 33U VP, 47.8° N + /// 14.5° E 33T VN, 52° N 15° E 33U WT. With two grid zone designations in view each name + /// carries its own; with one, the letters alone. + #[test] + fn mgrs_squares_are_named_by_their_letters() { + let (m, view) = mgrs_view(14.5, 48.2, 500.0); + let got = labels_on(&m, &view); + let texts: Vec<&str> = got.iter().map(|(t, _, _)| t.as_str()).collect(); + assert!(texts.contains(&"33U VP") && texts.contains(&"33T VN"), "{texts:?}"); + name_their_places(&m, &view, &got, |r| format!("{} {}{}", gzd(r), r.column, r.row)); + let (m, view) = mgrs_view(15.0, 52.0, 300.0); + let got = labels_on(&m, &view); + let texts: Vec<&str> = got.iter().map(|(t, _, _)| t.as_str()).collect(); + assert!(texts.contains(&"WT") && texts.iter().all(|t| t.len() == 2), "{texts:?}"); + name_their_places(&m, &view, &got, |r| format!("{}{}", r.column, r.row)); + // Zoomed in to a few hundred meters, within one square (52° N 15.3° E: 33U WT). + let (m, view) = mgrs_view(15.3, 52.0, 0.5); + let got = labels_on(&m, &view); + assert_eq!(got.iter().map(|(t, _, _)| t.as_str()).collect::>(), ["WT"]); + let (_, x, y) = &got[0]; + assert!((f64::from(*x) - 400.0).abs() < 1.0 && (f64::from(*y) - 300.0).abs() < 1.0, "in the middle: {x}, {y}"); + } + + /// Zoomed out, the grid zone designations are named, not the squares, on a flat map and on a + /// globe; across the antimeridian on a globe both zone 60's and zone 1's squares are named + /// (60K ZF and 01K AA by GeoConvert at 17.3° S, 179.9° E and W). + #[test] + fn zoomed_out_mgrs_names_its_grid_zone_designations() { + let (mut m, view) = mgrs_view(15.0, 48.0, 20_000.0); + let got = labels_on(&m, &view); + assert!(got.len() > 10 && got.iter().any(|(t, _, _)| t == "33U"), "{got:?}"); + name_their_places(&m, &view, &got, gzd); + m.projection = rustgis_map::Projection::Globe; + let camera = rustgis_map::camera::Camera::new(rustgis_geom::lonlat_to_merc(Coord::new(15.0, 48.0)), 20_000.0); + let view = View { camera, ..view }; + let got = labels_on(&m, &view); + assert!(got.len() > 10 && got.iter().any(|(t, _, _)| t == "33U"), "{got:?}"); + name_their_places(&m, &view, &got, gzd); + let camera = rustgis_map::camera::Camera::new(rustgis_geom::lonlat_to_merc(Coord::new(179.9, -17.3)), 300.0); + let view = View { camera, ..view }; + let got = labels_on(&m, &view); + let texts: Vec<&str> = got.iter().map(|(t, _, _)| t.as_str()).collect(); + assert!(texts.contains(&"60K ZF") && texts.contains(&"01K AA"), "{texts:?}"); + name_their_places(&m, &view, &got, |r| format!("{} {}{}", gzd(r), r.column, r.row)); + } + + /// A square cut too small for its name isn't named: with five points of zone 34 at the view's + /// right edge only zone 33's squares are, with two hundred zone 34's too. + #[test] + fn a_square_cut_too_small_is_not_named() { + let per_pt = 50.0 / 111_319.490_793; + let (m, view) = mgrs_view(18.0 - 395.0 * per_pt, 49.5, 50.0); + let got = labels_on(&m, &view); + assert!(!got.is_empty() && got.iter().all(|(t, _, _)| t.starts_with("33U ")), "{got:?}"); + let (m, view) = mgrs_view(18.0 - 200.0 * per_pt, 49.5, 50.0); + let got = labels_on(&m, &view); + assert!(got.iter().any(|(t, _, _)| t.starts_with("34U ")) && got.iter().any(|(t, _, _)| t.starts_with("33U ")), "{got:?}"); + name_their_places(&m, &view, &got, |r| format!("{} {}{}", gzd(r), r.column, r.row)); + } } diff --git a/crates/render/src/mesh.rs b/crates/render/src/mesh.rs index f44fec783f..e41cbf0a06 100644 --- a/crates/render/src/mesh.rs +++ b/crates/render/src/mesh.rs @@ -560,18 +560,19 @@ pub(crate) fn collect_basemap( Ok(()) } -/// The graticule lines (already in map units). +/// The graticule lines (already in map units), `width` points wide. pub(crate) fn collect_graticule( cmds: &mut Vec, lines: &[Vec], ext: &Extent, grat: Rgba, + width: f32, ppp: f32, map_per_px: f64, ) -> Result<(), TessError> { let origin = origin_for(ext, map_per_px)?; let (mut v, mut i) = (Vec::new(), Vec::new()); - extend_mesh(&mut v, &mut i, stroke_lines(lines, origin, premul(grat), 0.6 * ppp, map_per_px, NO_LIMIT))?; + extend_mesh(&mut v, &mut i, stroke_lines(lines, origin, premul(grat), width * ppp, map_per_px, NO_LIMIT))?; if !i.is_empty() { cmds.push(DrawCmd::Mesh { origin, vertices: v, indices: i }); } diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 759bcbb7b7..7c2247166a 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1881,12 +1881,12 @@ fn view_tab(app: &mut RustGisApp, ui: &mut Ui) { app, "graticule", "Graticule", - "Show or hide the graticule over the basemap: latitudes and longitudes, a measured grid or the UTM zones.", + "Show or hide the graticule over the basemap: latitudes and longitudes, a measured grid, the UTM zones or the MGRS grid.", "map.graticule", Value::Null, g, "Graticule options", - "What the graticule draws: latitudes and longitudes, a measured grid or the UTM zones.", + "What the graticule draws: latitudes and longitudes, a measured grid, the UTM zones or the MGRS grid.", true, graticule_menu, ); @@ -5476,6 +5476,11 @@ mod tests { h.get_by_label("UTM Zones").click(); h.run(); assert!(h.state().session.map().graticule && h.state().session.map().graticule_type == GraticuleType::Utm); + h.get_by_label("Graticule options").click(); + h.run(); + h.get_by_label("MGRS").click(); + h.run(); + assert!(h.state().session.map().graticule && h.state().session.map().graticule_type == GraticuleType::Mgrs); // A system typed as an EPSG code: clicking into the field keeps the menu open. h.get_by_label("Graticule options").click(); h.run(); diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index dc70e594a5..25ddda6fdc 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -743,8 +743,18 @@ picking one shows it: southern Norway's and Svalbard's wider zones. Once no more than eight zone-and-band areas are in view, each also gets its own eastings and northings, at the same interval in all of them and cut at the zone's edges. - -The grids have no labels on the map; the status bar reads coordinates in UTM or MGRS. Like the +- **MGRS**: the Military Grid Reference System's grid (`"mgrs"` in the command): the same zones + and bands as grid zone designations, drawn heavier. Once no more than eight are in view, each gets + its own grid at a power of ten that suits the scale, between three and thirty lines across the + view: 100 km, then 10 km, 1 km and, zoomed in closest, 100 m (100 km while more than four grid + zone designations show). The 100 km lines, the edges of the 100 km squares, stay heavier than the + finer ones. Zoomed out, each grid zone designation is named (`33U`); once the 100 km squares are + large enough on the screen, each is named by its letters (`VP`), with its grid zone designation + (`33U VP`) when more than one is in view. A zone or square cut too small for its name isn't + named, and the names aren't drawn on a tilted view. Nothing is drawn yet north of 84° N or south + of 80° S, where MGRS uses UPS. + +Only the MGRS grid is labeled on the map; the status bar reads coordinates in UTM or MGRS. Like the latitudes and longitudes, they aren't drawn on the copies of the world a flat map shows past ±180°. The type and system are saved with the map; a project whose measured grid names a system this version can't use (one in degrees, or a PROJ string the web app can't read) opens without it, diff --git a/schema/project.schema.json b/schema/project.schema.json index e9feded082..ee6a473bf6 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1064,7 +1064,8 @@ "table-export-order", "tabulate-intersection-unit", "layout-element-background", - "picture-markers" + "picture-markers", + "graticule-mgrs" ], "type": "string" }, @@ -1140,7 +1141,8 @@ "table-export-order", "tabulate-intersection-unit", "layout-element-background", - "picture-markers" + "picture-markers", + "graticule-mgrs" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2 From cfe989767dae124fcff2a2d8fa287d887aceca63 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:22:13 -0600 Subject: [PATCH 02/14] feat(map): the grid can go on top of the layers, in a color of its own --- crates/engine/src/cmd/navigate.rs | 43 +++- crates/engine/src/project.rs | 2 + crates/engine/src/project_capabilities.rs | 31 ++- crates/engine/src/tests.rs | 89 ++++++- crates/engine/tests/project_save_roundtrip.rs | 7 +- crates/map/src/lib.rs | 16 ++ crates/render/src/lib.rs | 233 ++++++++++++------ crates/ui-egui/src/mapview.rs | 1 + crates/ui-egui/src/ribbon.rs | 66 ++++- docs/user-guide/maps.md | 13 + schema/project.schema.json | 8 +- 11 files changed, 425 insertions(+), 84 deletions(-) diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs index b67bd77849..a42cbb2b61 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -76,7 +76,7 @@ pub fn commands() -> Vec { C::new("map.basemap", "Basemap", "Home › Add", basemap).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name": "paper"|"midnight"|"ocean"|"atlas"|"blank", "keepTiles"?: bool (keeps the web tile basemaps over it)}"#), C::new("map.graticule", "Graticule", "View › Display", graticule).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"on"?: bool (toggles when omitted, on when a type or crs is given), "type"?: "degrees"|"measured"|"utm"|"mgrs", "crs"?: a projected system for the measured grid (EPSG:2056, WKT or a PROJ string; "" or null: the map's own when projected, else the UTM zone at the view's centre)}"#), + .params(r##"{"on"?: bool (toggles when omitted, on when a type or crs is given), "type"?: "degrees"|"measured"|"utm"|"mgrs", "crs"?: a projected system for the measured grid (EPSG:2056, WKT or a PROJ string; "" or null: the map's own when projected, else the UTM zone at the view's centre), "onTop"?: bool (the lines over the layers, under the labels; false: with the basemap, under the layers), "color"?: "#RRGGBB"|"#RRGGBBAA" ("" or null: the basemap's)}"##), C::new("map.reloadWebLayers", "Reload Web Layers", "View › Display", |_, _| { // The map view draws again when the tile cache's generation moves. crate::render::rustgis_tiles::cache::clear(); @@ -774,9 +774,24 @@ fn set_bearing(s: &mut Session, p: &Value) -> CmdResult { /// Shows or hides the map's graticule, and sets what it draws: a type or a coordinate system /// given shows it too. A coordinate system is for the measured grid, and refused (naming it) when -/// it can't be read or isn't projected. +/// it can't be read or isn't projected. Whether its lines go over the layers, and their color, +/// are set without showing or hiding it. fn graticule(s: &mut Session, p: &Value) -> CmdResult { use rustgis_map::graticule::GraticuleType; + let on_top = match p.get("onTop") { + None | Some(Value::Null) => None, + Some(v) => Some(super::bool_value(v).ok_or_else(|| format!("onTop must be true or false, not {v}"))?), + }; + let color = match p.get("color") { + None => None, + Some(Value::Null) => Some(None), + Some(Value::String(c)) if c.trim().is_empty() => Some(None), + Some(v) => Some(Some( + v.as_str() + .and_then(rustgis_map::Rgba::from_hex) + .ok_or_else(|| format!("color must be #RRGGBB or #RRGGBBAA (\"\" or null for the basemap's), not {v}"))?, + )), + }; let kind = match p.get("type") { None | Some(Value::Null) => None, Some(Value::String(t)) => Some(GraticuleType::from_name(t).ok_or_else(|| { @@ -820,12 +835,32 @@ fn graticule(s: &mut Session, p: &Value) -> CmdResult { return Err(format!("crs is the measured grid's; the graticule is \"{}\" (give \"type\": \"measured\")", kind_after.code())); } let set = kind.is_some() || crs.is_some(); - m.graticule = super::b(p, "on").unwrap_or(if set { true } else { !m.graticule }); + // Only the lines' place or color given: shown or hidden as it was. + let styled = on_top.is_some() || color.is_some(); + m.graticule = super::b(p, "on").unwrap_or(if set { + true + } else if styled { + m.graticule + } else { + !m.graticule + }); m.graticule_type = kind_after; if let Some(c) = crs { m.graticule_crs = c; } - Ok(json!({"on": m.graticule, "type": m.graticule_type.code(), "crs": m.graticule_crs})) + if let Some(t) = on_top { + m.graticule_on_top = t; + } + if let Some(c) = color { + m.graticule_color = c; + } + Ok(json!({ + "on": m.graticule, + "type": m.graticule_type.code(), + "crs": m.graticule_crs, + "onTop": m.graticule_on_top, + "color": m.graticule_color.map(rustgis_map::Rgba::hex), + })) } fn basemap(s: &mut Session, p: &Value) -> CmdResult { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index a8b83fbd67..66c23f8838 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -84,6 +84,8 @@ pub const CAPABILITIES: &[&str] = &[ "layout-element-background", "picture-markers", "graticule-mgrs", + "graticule-on-top", + "graticule-color", ]; /// The most entries a document's `requires` may list: past it the document is refused without /// the rest being read. diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 19b3a33f68..e311c934c4 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -85,8 +85,30 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("tabulate-intersection-unit", command_uses_tabulate_unit), ("layout-element-background", command_uses_element_background), ("picture-markers", command_uses_picture_marker), + ("graticule-on-top", command_puts_graticule_on_top), + ("graticule-color", command_colors_graticule), ]; +/// A saved `map.graticule` that draws the grid over the layers: an older reader ignores the key +/// and leaves it under them. `false` is what that reader does anyway. +fn command_puts_graticule_on_top(id: &str, params: &Value) -> bool { + match id { + "map.graticule" => params.get("onTop").is_some_and(|v| v.as_bool() == Some(true)), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_puts_graticule_on_top)), + _ => false, + } +} + +/// A saved `map.graticule` that gives the grid a color of its own: an older reader ignores the +/// key and draws the palette's. `null` or `""` only goes back to the palette. +fn command_colors_graticule(id: &str, params: &Value) -> bool { + match id { + "map.graticule" => params.get("color").and_then(Value::as_str).is_some_and(|c| !c.trim().is_empty()), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_colors_graticule)), + _ => false, + } +} + /// A layout command that gives an element a background: an older reader warns that it ignores /// the key and makes the element without one. `null` only takes a background away, which an /// older reader's elements never have. @@ -191,12 +213,15 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { } fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static str> { - let (mut block, mut water, mut shore, mut relief, mut light, mut legends, mut pictures, mut mgrs) = - (false, false, false, false, false, false, false, false); + let (mut block, mut water, mut shore, mut relief, mut light, mut legends, mut pictures, mut mgrs, mut on_top, mut grid_color) = + (false, false, false, false, false, false, false, false, false, false); for map in maps { // An older reader doesn't know the MGRS graticule (#1042 piece 8): it refuses the // project by name rather than failing to read the type. mgrs |= map.graticule_type == rustgis_map::graticule::GraticuleType::Mgrs; + // Nor the graticule drawn over the layers or in a color of its own: it would save them away. + on_top |= map.graticule_on_top; + grid_color |= map.graticule_color.is_some(); if let Some(t) = &map.view.terrain { block |= t.block.is_some(); water |= t.water.is_some(); @@ -219,6 +244,8 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (legends, "normalized-legend-urls"), (pictures, "picture-markers"), (mgrs, "graticule-mgrs"), + (on_top, "graticule-on-top"), + (grid_color, "graticule-color"), ] .into_iter() .filter_map(|(used, name)| used.then_some(name)) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1224a0cf79..8b19bdaa60 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12665,6 +12665,87 @@ fn an_mgrs_graticule_is_required_by_name_in_the_saved_project() { assert!(serde_json::to_value(&s.project).unwrap().get("requires").is_none()); } +/// A saved task or script that puts the graticule on top or colors it names that among what the +/// project requires, so an older RustGIS refuses it rather than running it without the key; one +/// that only goes back to the defaults (false, null, "") names nothing. +#[test] +fn saved_graticule_settings_are_required_by_name() { + let s = world(); + let with_task = |params: Value| { + let mut project = s.project.clone(); + project.tasks = vec![ + serde_json::from_value(json!({"name": "Grid", "steps": [{"title": "Grid", "command": "map.graticule", "params": params}]})) + .unwrap(), + ]; + serde_json::to_value(&project).unwrap().get("requires").cloned() + }; + assert_eq!(with_task(json!({"onTop": true})), Some(json!(["graticule-on-top"]))); + assert_eq!(with_task(json!({"color": "#ff000080"})), Some(json!(["graticule-color"]))); + assert_eq!(with_task(json!({"onTop": true, "color": "#000"})), Some(json!(["graticule-on-top", "graticule-color"]))); + for defaults in [json!({"onTop": false}), json!({"color": null}), json!({"color": " "}), json!({"type": "utm"})] { + assert_eq!(with_task(defaults.clone()), None, "{defaults}"); + } + // In a script, too. + let mut project = s.project.clone(); + project.tasks = vec![ + serde_json::from_value( + json!({"name": "Script", "steps": [{"title": "Run", "command": "script.run", "params": {"script": "map.graticule {\"onTop\": true}"}}]}), + ) + .unwrap(), + ]; + assert_eq!(serde_json::to_value(&project).unwrap()["requires"], json!(["graticule-on-top"])); +} + +/// The graticule's lines over the layers, and their color (#1042): set without showing or hiding +/// it, reset to the basemap's with null or "", refused (naming the value) when not a true/false or +/// a #RRGGBB/#RRGGBBAA color with nothing changed; a project names each among what it requires +/// only when a map uses it, and keeps them. +#[test] +fn the_graticule_goes_on_top_in_a_color_of_its_own() { + let mut s = world(); + let on = s.map().graticule; + let r = s.run("map.graticule", &json!({"onTop": true, "color": "#ff000080"})).unwrap(); + assert_eq!((r["on"].clone(), r["onTop"].clone(), r["color"].clone()), (json!(on), json!(true), json!("#FF000080"))); + assert_eq!(s.map().graticule_color, Some(rustgis_map::Rgba::new(255, 0, 0, 128))); + let r = s.run("map.graticule", &json!({"color": "#00FF00"})).unwrap(); + assert_eq!((r["on"].clone(), r["onTop"].clone(), r["color"].clone()), (json!(on), json!(true), json!("#00FF00"))); + for (p, e) in [ + (json!({"onTop": "maybe"}), "onTop must be true or false, not \"maybe\""), + (json!({"onTop": [1]}), "onTop must be true or false, not [1]"), + (json!({"color": "red"}), "color must be #RRGGBB or #RRGGBBAA (\"\" or null for the basemap's), not \"red\""), + (json!({"color": "#12345"}), "color must be #RRGGBB or #RRGGBBAA"), + (json!({"color": 255}), "color must be #RRGGBB or #RRGGBBAA (\"\" or null for the basemap's), not 255"), + ] { + let got = s.run("map.graticule", &p).unwrap_err(); + assert!(got.starts_with(e), "{p}: {got}"); + } + // Unchanged by the refusals. + assert!(s.map().graticule_on_top); + assert_eq!(s.map().graticule_color, Some(rustgis_map::Rgba::rgb(0, 255, 0))); + assert_eq!(s.map().graticule_rgba(), rustgis_map::Rgba::rgb(0, 255, 0)); + // Saved, required by name, and back. + let v = serde_json::to_value(&s.project).unwrap(); + assert_eq!(v["requires"], json!(["graticule-on-top", "graticule-color"])); + let back = crate::Project::from_json(&v.to_string()).unwrap(); + assert!(back.map().graticule_on_top); + assert_eq!(back.map().graticule_color, Some(rustgis_map::Rgba::rgb(0, 255, 0))); + // Reset: under the layers, in the basemap's color; neither saved nor required. + let r = s.run("map.graticule", &json!({"onTop": false, "color": null})).unwrap(); + assert_eq!((r["onTop"].clone(), r["color"].clone()), (json!(false), json!(null))); + s.run("map.graticule", &json!({"color": "#123456"})).unwrap(); + s.run("map.graticule", &json!({"color": " "})).unwrap(); + assert_eq!(s.map().graticule_color, None); + assert_eq!(s.map().graticule_rgba(), s.map().palette().3); + assert_eq!(s.map().graticule, on); + let text = serde_json::to_string(&s.project).unwrap(); + assert!(!text.contains("graticule_on_top") && !text.contains("graticule_color") && !text.contains("\"requires\""), "{text}"); + // An older reader that knows neither refuses such a project by name. + let mut v = v; + v["requires"] = json!(["graticule-on-top", "graticule-color", "graticule-later"]); + let e = crate::Project::from_json(&v.to_string()).unwrap_err(); + assert!(e.contains("graticule-later"), "{e}"); +} + /// The graticule's type and the measured grid's coordinate system (#1042): a type or system given /// shows it; no parameters toggle it as before; a system that isn't projected, can't be read, or /// is given for another type is refused, naming it; a project keeps them, and one without them @@ -12676,22 +12757,22 @@ fn the_graticule_takes_a_type_and_a_measured_grids_system() { assert_eq!(s.map().graticule_type, GraticuleType::Degrees); s.run("map.graticule", &json!({"on": false})).unwrap(); let r = s.run("map.graticule", &json!({"type": "UTM"})).unwrap(); - assert_eq!(r, json!({"on": true, "type": "utm", "crs": null})); + assert_eq!(r, json!({"on": true, "type": "utm", "crs": null, "onTop": false, "color": null})); // No parameters: toggled, the type kept. s.run("map.graticule", &json!({})).unwrap(); assert!(!s.map().graticule && s.map().graticule_type == GraticuleType::Utm); let r = s.run("map.graticule", &json!({"type": "measured", "crs": " EPSG:2056 "})).unwrap(); - assert_eq!(r, json!({"on": true, "type": "measured", "crs": "EPSG:2056"})); + assert_eq!(r, json!({"on": true, "type": "measured", "crs": "EPSG:2056", "onTop": false, "color": null})); // MGRS (#1042), named in any case, and kept with the project; it takes no system either. let r = s.run("map.graticule", &json!({"type": " Mgrs "})).unwrap(); // (The measured grid's system is kept for when it is picked again.) - assert_eq!(r, json!({"on": true, "type": "mgrs", "crs": "EPSG:2056"})); + assert_eq!(r, json!({"on": true, "type": "mgrs", "crs": "EPSG:2056", "onTop": false, "color": null})); let back = crate::Project::from_json(&serde_json::to_string(&s.project).unwrap()).unwrap(); assert_eq!(back.map().graticule_type, GraticuleType::Mgrs); let got = s.run("map.graticule", &json!({"type": "mgrs", "crs": "EPSG:2056"})).unwrap_err(); assert!(got.starts_with("crs is the measured grid's; the graticule is \"mgrs\""), "{got}"); let r = s.run("map.graticule", &json!({"type": "measured", "crs": " EPSG:2056 "})).unwrap(); - assert_eq!(r, json!({"on": true, "type": "measured", "crs": "EPSG:2056"})); + assert_eq!(r, json!({"on": true, "type": "measured", "crs": "EPSG:2056", "onTop": false, "color": null})); for (p, e) in [ (json!({"type": "ups"}), "type must be one of degrees, measured, utm, mgrs, not \"ups\""), (json!({"type": 3}), "type must be one of \"degrees\", \"measured\", \"utm\", \"mgrs\", not 3"), diff --git a/crates/engine/tests/project_save_roundtrip.rs b/crates/engine/tests/project_save_roundtrip.rs index 019a7b8102..038b91e173 100644 --- a/crates/engine/tests/project_save_roundtrip.rs +++ b/crates/engine/tests/project_save_roundtrip.rs @@ -123,7 +123,12 @@ fn step() -> impl Strategy { prop::sample::select(vec!["Albers Equal Area Conic +lat_1=29.5 +lat_2=45.5", "EPSG:3857", "EPSG:4326"]) .prop_map(|t| ("map.projection", json!({"type": t}))), (-180.0..180.0f64).prop_map(|b| ("map.setBearing", json!({"bearing": b}))), - prop::sample::select(vec!["degrees", "measured", "utm", "mgrs"]).prop_map(|t| ("map.graticule", json!({"on": true, "type": t}))), + ( + prop::sample::select(vec!["degrees", "measured", "utm", "mgrs"]), + any::(), + prop::sample::select(vec![Value::Null, json!("#FF0000"), json!("#00FF0080")]), + ) + .prop_map(|(t, top, c)| ("map.graticule", json!({"on": true, "type": t, "onTop": top, "color": c}))), (-180.0..180.0f64, -85.0..85.0f64, number()) .prop_map(|(x, y, s)| ("map.camera", json!({"lon": x, "lat": y, "scale": s * 1e5 + 1.0}))), name().prop_map(|n| ("map.new", json!({"name": n}))), diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 74dba21690..b70d9c1f31 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -1537,6 +1537,13 @@ pub struct Map { /// map's own when it is projected, else the UTM zone (WGS 84) at the view's centre. #[serde(default, skip_serializing_if = "Option::is_none")] pub graticule_crs: Option, + /// The graticule's lines drawn over the map's layers and web tile layers (just under the + /// labels), rather than with the basemap under them, where filled layers hide them. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub graticule_on_top: bool, + /// The graticule's color (with its opacity): none is the basemap palette's. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub graticule_color: Option, /// Flat map or 3D globe. #[serde(default)] pub projection: Projection, @@ -1676,6 +1683,8 @@ impl Map { graticule: true, graticule_type: graticule::GraticuleType::Degrees, graticule_crs: None, + graticule_on_top: false, + graticule_color: None, projection: Projection::WebMercator, popup_mode: PopupMode::Topmost, label_display: LabelDisplay::default(), @@ -2831,6 +2840,11 @@ impl Map { (grey, grey, Rgba::new(0, 0, 0, 0), grat) } + /// The graticule's color: the one set for it, else the basemap palette's. + pub fn graticule_rgba(&self) -> Rgba { + self.graticule_color.unwrap_or(self.palette().3) + } + /// Whether the built-in world outline is drawn: where the palette's land and water differ, so /// not on the blank basemap or another body. pub fn draws_world_outline(&self) -> bool { @@ -3063,6 +3077,8 @@ impl Map { graticule: _, graticule_type: _, graticule_crs: _, + graticule_on_top: _, + graticule_color: _, projection: _, popup_mode: _, label_display: _, diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 7c994cc2b2..3c4952c3af 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4124,7 +4124,7 @@ fn render_frame( }; // Basemap. - let (water, land, outline, grat) = map.palette(); + let (water, land, outline, _) = map.palette(); match &globe { Some(g) => globe_backdrop(pm.pixels(), g, water, space(view, map), view.pixels_per_point as f32), None if !gpu => pm.fill(tiny_skia::Color::from_rgba8(water.r(), water.g(), water.b(), 255)), @@ -4202,75 +4202,86 @@ fn render_frame( } } } - if map.graticule && grat.a() > 0 { - let p = paint(grat, 1.0); - // A measured, UTM or MGRS graticule's lines (#1042), else latitudes and longitudes; the - // MGRS grid's grid zone designations and 100 km lines (`major`) are drawn heavier. - let (major, grid) = match mapgrid::lines(map, view) { - Some(g) => (g.major, Some(g.minor)), - None => (Vec::new(), None), - }; - let step = if view.camera.res > 8000.0 { - 30.0 - } else if view.camera.res > 2000.0 { - 15.0 - } else if view.camera.res > 400.0 { - 5.0 - } else { - 1.0 - }; - let (lat_max, lat_min) = if globe.is_some() { (90.0, -90.0) } else { (85.0, -85.0) }; - let lines = grid.unwrap_or_else(|| { - let mut lines = Vec::new(); - let mut lon = -180.0; - while lon <= 180.0 { - lines.push((0..=36).map(|i| Coord::new(lon, lat_min + (lat_max - lat_min) * i as f64 / 36.0)).collect::>()); - lon += step; - } - let mut lat = -90.0 + step; - while lat < 90.0 { - lines.push((0..=72).map(|i| Coord::new(-180.0 + i as f64 * 5.0, lat)).collect::>()); - lat += step; - } - lines - }); - let project = |lines: Vec>| -> Vec> { - if globe.is_some() { - lines - } else if custom { - // Parallels are cut at the map's edge like any line (#209). - match flat.project(&Geometry::Line(lines)) { - Geometry::Line(parts) => parts, - _ => Vec::new(), - } - } else { - lines.into_iter().map(|l| l.into_iter().map(lonlat_to_merc).collect()).collect() - } - }; - let (lines, major) = (project(lines), project(major)); - // The minor lines always (as every graticule drew its lines before #1042's MGRS grid), - // the major ones over them when there are any. - for (lines, width, always) in [(lines, 0.6f32, true), (major, 1.2, false)] { - if !always && lines.is_empty() { - continue; - } - if gpu { - let mut e = Extent::EMPTY; - for l in &lines { - for c in l { - e.expand(*c); + // The graticule's lines: with the basemap, under the layers and web tile layers, or over them + // all (`graticule_on_top`), still under the labels. + let grat = map.graticule_rgba(); + macro_rules! draw_graticule { + () => {{ + if map.graticule && grat.a() > 0 { + let p = paint(grat, 1.0); + // A measured, UTM or MGRS graticule's lines (#1042), else latitudes and longitudes; the + // MGRS grid's grid zone designations and 100 km lines (`major`) are drawn heavier. + let (major, grid) = match mapgrid::lines(map, view) { + Some(g) => (g.major, Some(g.minor)), + None => (Vec::new(), None), + }; + let step = if view.camera.res > 8000.0 { + 30.0 + } else if view.camera.res > 2000.0 { + 15.0 + } else if view.camera.res > 400.0 { + 5.0 + } else { + 1.0 + }; + let (lat_max, lat_min) = if globe.is_some() { (90.0, -90.0) } else { (85.0, -85.0) }; + let lines = grid.unwrap_or_else(|| { + let mut lines = Vec::new(); + let mut lon = -180.0; + while lon <= 180.0 { + lines.push((0..=36).map(|i| Coord::new(lon, lat_min + (lat_max - lat_min) * i as f64 / 36.0)).collect::>()); + lon += step; + } + let mut lat = -90.0 + step; + while lat < 90.0 { + lines.push((0..=72).map(|i| Coord::new(-180.0 + i as f64 * 5.0, lat)).collect::>()); + lat += step; + } + lines + }); + let project = |lines: Vec>| -> Vec> { + if globe.is_some() { + lines + } else if custom { + // Parallels are cut at the map's edge like any line (#209). + match flat.project(&Geometry::Line(lines)) { + Geometry::Line(parts) => parts, + _ => Vec::new(), + } + } else { + lines.into_iter().map(|l| l.into_iter().map(lonlat_to_merc).collect()).collect() + } + }; + let (lines, major) = (project(lines), project(major)); + // The minor lines always (as every graticule drew its lines before #1042's MGRS grid), + // the major ones over them when there are any. + for (lines, width, always) in [(lines, 0.6f32, true), (major, 1.2, false)] { + if !always && lines.is_empty() { + continue; + } + if gpu { + let mut e = Extent::EMPTY; + for l in &lines { + for c in l { + e.expand(*c); + } + } + flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty)?; + let tessellated = + !e.is_empty() && mesh::collect_graticule(&mut cmds, &lines, &e, grat, width, ctx.ppp, map_per_px).is_ok(); + if !tessellated { + ctx.line(&mut pm, &lines, &p, width); + cpu_dirty = true; + } + } else { + ctx.line(&mut pm, &lines, &p, width); } } - flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty)?; - let tessellated = !e.is_empty() && mesh::collect_graticule(&mut cmds, &lines, &e, grat, width, ctx.ppp, map_per_px).is_ok(); - if !tessellated { - ctx.line(&mut pm, &lines, &p, width); - cpu_dirty = true; - } - } else { - ctx.line(&mut pm, &lines, &p, width); } - } + }}; + } + if !map.graticule_on_top { + draw_graticule!(); } // Web tile layers, at their places in the drawing order (#808): those under all the map's @@ -5563,6 +5574,9 @@ fn render_frame( if let Some(id) = below { draw_tiles!(Some(id)); } + if map.graticule_on_top { + draw_graticule!(); + } // A band of a tilted view: the sun's glint on the terrain's water, over the water's own fill. if matches!(labels_to, Labels::Tilted(..) | Labels::Shared) && let Some(g) = TILT_GLINT.with(|g| g.borrow().clone()) @@ -5669,8 +5683,8 @@ fn render_frame( let mut labels = placed.labels; let mut label_layers = label_layers; // The MGRS graticule's names (#1042), over the placed labels and apart from their collisions, - // with no layer of their own in a recording. A tilted view's bands draw none: their places - // would repeat from band to band. + // with no layer of their own in a recording, in the graticule's color made opaque. A tilted + // view's bands draw none: their places would repeat from band to band. if map.graticule && grat.a() > 0 && matches!(labels_to, Labels::Own | Labels::Turned(_)) { let color = Rgba::rgb(grat.r(), grat.g(), grat.b()); for (text, x, y) in mapgrid::labels(map, view, |t| text::measure(t, mapgrid::LABEL_PT, false)) { @@ -8755,6 +8769,87 @@ mod tests { assert!(grid(&mut m, &view).is_empty()); } + /// The graticule's lines are drawn with the basemap, so an opaque filled layer hides them, + /// unless they are on top (over the layers, under the labels), in every type; a color set for + /// them is used, with its opacity, and the MGRS names take it opaque. On the GPU the lines' + /// meshes come before the layer's, or after it when on top. + #[test] + fn the_graticule_draws_over_the_layers_when_on_top_in_its_own_color() { + use rustgis_map::graticule::GraticuleType; + let mut m = Map::new("Map"); + let id = square_layer(&mut m, "cover", -40.0, -40.0, 80.0); + let red = Rgba::rgb(255, 0, 0); + if let Some(l) = m.layer_mut(id) { + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { fill: red, stroke_width: 0.0, ..l.symbol(0) }); + } + // Lines through the view's center whatever the step, at four pixels a point so that the + // thinnest (0.6 pt) has pixels it covers whole. + let camera = Camera { center: lonlat_to_merc(Coord::new(0.0, 0.0)), res: 6000.0, bearing: 0.0, pitch: 0.0 }; + let view = View { width: 100.0, height: 75.0, pixels_per_point: 4.0, camera, sky: false }; + let pixels = |m: &mut Map| -> Vec<[u8; 4]> { + render(m, &view) + .unwrap() + .pixmap + .pixels() + .iter() + .map(|p| { + let c = p.demultiply(); + [c.red(), c.green(), c.blue(), c.alpha()] + }) + .collect() + }; + let not_red = |px: &[[u8; 4]]| px.iter().filter(|p| p[..3] != [255, 0, 0]).count(); + // Under the layer: all of it the layer's fill, the default grid as much as a set one. + assert_eq!(not_red(&pixels(&mut m)), 0); + m.graticule_color = Some(Rgba::rgb(0, 0, 255)); + assert_eq!(not_red(&pixels(&mut m)), 0); + // On top: the lines over the fill, in their color. + m.graticule_on_top = true; + for t in GraticuleType::ALL { + m.graticule_type = t; + let px = pixels(&mut m); + assert!(px.contains(&[0, 0, 255, 255]), "{t:?}"); + } + m.graticule_type = GraticuleType::Degrees; + // The basemap's color when none is set, now seen over the fill too. + m.graticule_color = None; + assert!(not_red(&pixels(&mut m)) > 0); + // A color's opacity is kept: half see-through blue over red. + m.graticule_color = Some(Rgba::new(0, 0, 255, 128)); + let px = pixels(&mut m); + assert!(px.iter().any(|p| p[0] > 100 && p[0] < 160 && p[2] > 100 && p[2] < 160), "half blue over red"); + assert!(!px.contains(&[0, 0, 255, 255])); + // Hidden: none either way. + m.graticule = false; + assert_eq!(not_red(&pixels(&mut m)), 0); + m.graticule = true; + // The MGRS names in the set color, made opaque. + m.graticule_type = GraticuleType::Mgrs; + let near = View { camera: Camera { center: lonlat_to_merc(Coord::new(14.5, 48.2)), res: 500.0, ..camera }, ..view }; + let named: Vec = + render(&mut m, &near).unwrap().labels.into_iter().filter(|l| l.size == mapgrid::LABEL_PT && l.halo.is_some()).collect(); + assert!(!named.is_empty() && named.iter().all(|l| l.color == Rgba::rgb(0, 0, 255))); + // On the GPU: the grid's mesh (its color) after the layer's when on top, before it when not. + m.graticule_type = GraticuleType::Degrees; + m.graticule_color = Some(Rgba::rgb(0, 0, 255)); + let blue = [0.0f32, 0.0, 1.0, 1.0]; + for on_top in [false, true] { + m.graticule_on_top = on_top; + let Some(RenderOutput::Gpu(scene)) = render_backend(&mut m, &view, Backend::Gpu) else { panic!("gpu scene") }; + let meshes: Vec = scene + .cmds + .iter() + .filter_map(|c| match c { + gpu_scene::DrawCmd::Mesh { vertices, .. } => Some(vertices.iter().any(|v| v.color == blue)), + _ => None, + }) + .collect(); + let (grid, layer) = (meshes.iter().position(|g| *g), meshes.iter().rposition(|g| !*g)); + let (Some(grid), Some(layer)) = (grid, layer) else { panic!("{meshes:?}") }; + assert_eq!(grid > layer, on_top, "{meshes:?}"); + } + } + #[test] fn a_selected_text_graphic_is_framed_with_its_label() { let mut m = Map::new("Map"); diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 0ce619f3cf..14dcc78f28 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -4805,6 +4805,7 @@ fn shown_layers(session: &rustgis_engine::Session) -> u64 { let map = project.map(); (&session.path, &project.name, project.active_map, &map.name, map.basemap, map.graticule, map.graticule_type, &map.graticule_crs) .hash(&mut h); + (map.graticule_on_top, map.graticule_color).hash(&mut h); for l in &map.layers { (l.id, l.visible).hash(&mut h); } diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 7c2247166a..f89e7a47e0 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1832,8 +1832,8 @@ fn analysis_groups(app: &mut RustGisApp, ui: &mut Ui) { }); } -/// View › Display › Graticule's menu: the graticule's type (choosing one shows it), and the -/// measured grid's coordinate system. +/// View › Display › Graticule's menu: the graticule's type (choosing one shows it), whether its +/// lines go over the layers, their color, and the measured grid's coordinate system. fn graticule_menu(ui: &mut Ui, app: &mut RustGisApp) { use rustgis_engine::map::graticule::GraticuleType; let (on, kind) = (app.session.map().graticule, app.session.map().graticule_type); @@ -1846,6 +1846,39 @@ fn graticule_menu(ui: &mut Ui, app: &mut RustGisApp) { } } ui.separator(); + // Under the layers, filled ones hide the lines; over them, only the labels are on top. + let mut on_top = app.session.map().graticule_on_top; + if ui + .checkbox(&mut on_top, tl!("Draw on top of layers")) + .on_hover_text(tl!("Draw the grid lines over the map's layers, under the labels; off: under the layers")) + .changed() + && let Err(e) = app.run("map.graticule", json!({"onTop": on_top})) + { + app.session.notify(e, true); + } + let set = app.session.map().graticule_color.is_some(); + let mut color = crate::theme::c32(app.session.map().graticule_rgba()); + ui.horizontal(|ui| { + let name = ui.label(tl!("Grid color")); + // Named by its label, for a screen reader. + let resp = crate::widgets::color_button(ui, &mut color).on_hover_text(tl!("The grid's color and opacity")).labelled_by(name.id); + if resp.changed() { + crate::widgets::one_step_per_press(app, &resp); + if let Err(e) = app.run("map.graticule", json!({"color": crate::theme::rgba(color).hex8()})) { + app.session.notify(e, true); + } + } + if ui + .add_enabled(set, egui::Button::new(tl!("Default"))) + .on_hover_text(tl!("The basemap's grid color")) + .on_disabled_hover_text(tl!("The grid already has the basemap's color")) + .clicked() + && let Err(e) = app.run("map.graticule", json!({"color": null})) + { + app.session.notify(e, true); + } + }); + ui.separator(); let name = ui.label(tl!("Measured grid's coordinate system")); ui.horizontal(|ui| { let edit = ui.add(egui::TextEdit::singleline(&mut app.ui.graticule_crs_input).hint_text("2056").desired_width(90.0)).on_hover_text( @@ -5509,6 +5542,35 @@ mod tests { ); } + /// View › Display › Graticule's menu: "Draw on top of layers" puts the lines over the layers + /// and back, without showing or hiding the grid; "Default" is offered only once a color is set, + /// and takes the grid back to the basemap's. + #[test] + fn the_graticule_menu_draws_it_on_top_and_resets_its_color() { + use egui_kittest::kittest::NodeT; + let mut h = tab_harness(RustGisApp::with_sample(), view_tab); + let on = h.state().session.map().graticule; + assert!(!h.state().session.map().graticule_on_top); + h.get_by_label("Graticule options").click(); + h.run(); + assert!(h.get_by_label("Default").accesskit_node().is_disabled(), "no color set yet"); + // The color button, named by its label. + h.get_by_role_and_label(egui::accesskit::Role::ColorWell, "Grid color"); + h.get_by_label("Draw on top of layers").click(); + h.run(); + assert!(h.state().session.map().graticule_on_top); + assert_eq!(h.state().session.map().graticule, on); + // Still open: unticked again. + h.get_by_label("Draw on top of layers").click(); + h.run(); + assert!(!h.state().session.map().graticule_on_top); + h.state_mut().session.run("map.graticule", &json!({"color": "#FF000080"})).unwrap(); + h.run(); + h.get_by_label("Default").click(); + h.run(); + assert_eq!(h.state().session.map().graticule_color, None); + } + /// The language list names every language in English while the interface is English, with the /// language's own name as the tooltip; in another language each keeps its own name, or its /// English one where no font can draw it. diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 25ddda6fdc..15f3a821c8 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -760,6 +760,19 @@ latitudes and longitudes, they aren't drawn on the copies of the world a flat ma this version can't use (one in degrees, or a PROJ string the web app can't read) opens without it, and says so. +Two more settings in the same menu apply to every type, and are saved with the map: + +- **Draw on top of layers** (`"onTop"` in the command; off by default): by default the grid lines + are drawn with the basemap, under the map's layers and web tile layers, so a filled layer hides + them. With it on, they are drawn over every layer and tile layer, still under the labels. +- **Grid color** (`"color"`: `"#RRGGBB"` or `"#RRGGBBAA"`, with its opacity): the lines' color. By + default it is the basemap's own grid color, which is faint; **Default** (`null` or `""` in the + command) goes back to it. The MGRS names take the same color, fully opaque. Major and minor + lines keep their widths. + +Neither setting shows or hides the grid. A project that uses either needs a RustGIS that knows +it: an older one refuses to open it rather than drop the setting. + **Global** shows a globe; **Local** a flat view centred where you are (azimuthal equidistant; not in the web app, which doesn't include that projection). **Wireframe** draws polygons as outlines; **Raise Priority** and **Lower Priority** change a diff --git a/schema/project.schema.json b/schema/project.schema.json index ee6a473bf6..27c18d9388 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1065,7 +1065,9 @@ "tabulate-intersection-unit", "layout-element-background", "picture-markers", - "graticule-mgrs" + "graticule-mgrs", + "graticule-on-top", + "graticule-color" ], "type": "string" }, @@ -1142,7 +1144,9 @@ "tabulate-intersection-unit", "layout-element-background", "picture-markers", - "graticule-mgrs" + "graticule-mgrs", + "graticule-on-top", + "graticule-color" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2 From c45945e5f1fb445ca103cbfb9a282b4764591a2c Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:20:55 -0600 Subject: [PATCH 03/14] fix(map): saved grid settings and MGRS steps are required by name; names pause and stay in a turned view --- crates/engine/src/cmd/navigate.rs | 6 ++- crates/engine/src/project_capabilities.rs | 29 +++++++++++--- crates/engine/src/tests.rs | 45 +++++++++++++++++++--- crates/render/src/lib.rs | 44 ++++++++++++++++++--- crates/render/src/mapgrid.rs | 47 +++++++++++------------ docs/user-guide/maps.md | 7 ++-- 6 files changed, 132 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs index a42cbb2b61..68f6062705 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -76,7 +76,7 @@ pub fn commands() -> Vec { C::new("map.basemap", "Basemap", "Home › Add", basemap).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name": "paper"|"midnight"|"ocean"|"atlas"|"blank", "keepTiles"?: bool (keeps the web tile basemaps over it)}"#), C::new("map.graticule", "Graticule", "View › Display", graticule).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r##"{"on"?: bool (toggles when omitted, on when a type or crs is given), "type"?: "degrees"|"measured"|"utm"|"mgrs", "crs"?: a projected system for the measured grid (EPSG:2056, WKT or a PROJ string; "" or null: the map's own when projected, else the UTM zone at the view's centre), "onTop"?: bool (the lines over the layers, under the labels; false: with the basemap, under the layers), "color"?: "#RRGGBB"|"#RRGGBBAA" ("" or null: the basemap's)}"##), + .params(r##"{"on"?: bool (toggles when omitted, on when a type or crs is given), "type"?: "degrees"|"measured"|"utm"|"mgrs", "crs"?: a projected system for the measured grid (EPSG:2056, WKT or a PROJ string; "" or null: the map's own when projected, else the UTM zone at the view's centre), "onTop"?: bool (the lines over the layers, under the labels; false or null: with the basemap, under the layers), "color"?: "#RRGGBB"|"#RRGGBBAA" ("" or null: the basemap's)}"##), C::new("map.reloadWebLayers", "Reload Web Layers", "View › Display", |_, _| { // The map view draws again when the tile cache's generation moves. crate::render::rustgis_tiles::cache::clear(); @@ -779,7 +779,9 @@ fn set_bearing(s: &mut Session, p: &Value) -> CmdResult { fn graticule(s: &mut Session, p: &Value) -> CmdResult { use rustgis_map::graticule::GraticuleType; let on_top = match p.get("onTop") { - None | Some(Value::Null) => None, + None => None, + // As for the color: null puts the default back (under the layers). + Some(Value::Null) => Some(false), Some(v) => Some(super::bool_value(v).ok_or_else(|| format!("onTop must be true or false, not {v}"))?), }; let color = match p.get("color") { diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index e311c934c4..36727e2cbe 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -85,25 +85,42 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("tabulate-intersection-unit", command_uses_tabulate_unit), ("layout-element-background", command_uses_element_background), ("picture-markers", command_uses_picture_marker), + ("graticule-mgrs", command_draws_mgrs_graticule), ("graticule-on-top", command_puts_graticule_on_top), ("graticule-color", command_colors_graticule), ]; -/// A saved `map.graticule` that draws the grid over the layers: an older reader ignores the key -/// and leaves it under them. `false` is what that reader does anyway. +/// A saved `map.graticule` that switches to the MGRS grid, its type read as the command reads it: +/// an older reader refuses the type, so the command would fail there. +fn command_draws_mgrs_graticule(id: &str, params: &Value) -> bool { + match id { + "map.graticule" => params + .get("type") + .and_then(Value::as_str) + .and_then(rustgis_map::graticule::GraticuleType::from_name) + .is_some_and(|t| t == rustgis_map::graticule::GraticuleType::Mgrs), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_draws_mgrs_graticule)), + _ => false, + } +} + +/// A saved `map.graticule` that sets whether the grid draws over the layers, or puts the default +/// back with `null`: an older reader ignores the key, and without `on`, `type` or `crs` it toggles +/// the grid where this one keeps it as it is, so any value needs it. fn command_puts_graticule_on_top(id: &str, params: &Value) -> bool { match id { - "map.graticule" => params.get("onTop").is_some_and(|v| v.as_bool() == Some(true)), + "map.graticule" => params.get("onTop").is_some(), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_puts_graticule_on_top)), _ => false, } } -/// A saved `map.graticule` that gives the grid a color of its own: an older reader ignores the -/// key and draws the palette's. `null` or `""` only goes back to the palette. +/// A saved `map.graticule` that sets the grid's color, or puts the palette's back with `null` or +/// `""`: an older reader ignores the key, and without `on`, `type` or `crs` it toggles the grid +/// where this one keeps it as it is, so any value needs it. fn command_colors_graticule(id: &str, params: &Value) -> bool { match id { - "map.graticule" => params.get("color").and_then(Value::as_str).is_some_and(|c| !c.trim().is_empty()), + "map.graticule" => params.get("color").is_some(), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_colors_graticule)), _ => false, } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8b19bdaa60..eb43810d1a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12665,9 +12665,9 @@ fn an_mgrs_graticule_is_required_by_name_in_the_saved_project() { assert!(serde_json::to_value(&s.project).unwrap().get("requires").is_none()); } -/// A saved task or script that puts the graticule on top or colors it names that among what the -/// project requires, so an older RustGIS refuses it rather than running it without the key; one -/// that only goes back to the defaults (false, null, "") names nothing. +/// A saved task or script that sets whether the graticule is on top, or its color, names that among +/// what the project requires, so an older RustGIS refuses it rather than running it without the +/// key (and toggling the grid instead); one that sets neither names nothing. #[test] fn saved_graticule_settings_are_required_by_name() { let s = world(); @@ -12682,8 +12682,16 @@ fn saved_graticule_settings_are_required_by_name() { assert_eq!(with_task(json!({"onTop": true})), Some(json!(["graticule-on-top"]))); assert_eq!(with_task(json!({"color": "#ff000080"})), Some(json!(["graticule-color"]))); assert_eq!(with_task(json!({"onTop": true, "color": "#000"})), Some(json!(["graticule-on-top", "graticule-color"]))); - for defaults in [json!({"onTop": false}), json!({"color": null}), json!({"color": " "}), json!({"type": "utm"})] { - assert_eq!(with_task(defaults.clone()), None, "{defaults}"); + // Any value, null included: an older reader would toggle the grid where this one keeps it, even + // for the defaults, and `onTop` reads "true" and 1 as true. + for on_top in [json!(null), json!(false), json!("true"), json!(1)] { + assert_eq!(with_task(json!({"onTop": on_top})), Some(json!(["graticule-on-top"])), "{on_top}"); + } + for color in [json!(null), json!(""), json!(" ")] { + assert_eq!(with_task(json!({"color": color})), Some(json!(["graticule-color"])), "{color}"); + } + for nothing in [json!({"type": "utm"}), json!({"on": false})] { + assert_eq!(with_task(nothing.clone()), None, "{nothing}"); } // In a script, too. let mut project = s.project.clone(); @@ -12696,6 +12704,29 @@ fn saved_graticule_settings_are_required_by_name() { assert_eq!(serde_json::to_value(&project).unwrap()["requires"], json!(["graticule-on-top"])); } +/// A saved command that switches the graticule to MGRS names the MGRS grid among what the project +/// requires, its type read as the command reads it; other types don't. +#[test] +fn saved_commands_switching_to_mgrs_require_it() { + let s = world(); + let with_step = |command: &str, params: Value| { + let mut project = s.project.clone(); + project.tasks = vec![ + serde_json::from_value(json!({"name": "Grid", "steps": [{"title": "Grid", "command": command, "params": params}]})).unwrap(), + ]; + serde_json::to_value(&project).unwrap().get("requires").cloned() + }; + for mgrs in ["mgrs", " MGRS ", "Mgrs"] { + assert_eq!(with_step("map.graticule", json!({"type": mgrs})), Some(json!(["graticule-mgrs"])), "{mgrs}"); + } + for other in [json!("utm"), json!("degrees"), json!("measured"), json!("ups"), json!(null), json!(1)] { + assert_eq!(with_step("map.graticule", json!({"type": other})), None, "{other}"); + } + let script = |line: &str| with_step("script.run", json!({"script": line})); + assert_eq!(script("map.graticule {\"type\": \"mgrs\"}"), Some(json!(["graticule-mgrs"]))); + assert_eq!(script("map.graticule {\"type\": \"utm\"}"), None); +} + /// The graticule's lines over the layers, and their color (#1042): set without showing or hiding /// it, reset to the basemap's with null or "", refused (naming the value) when not a true/false or /// a #RRGGBB/#RRGGBBAA color with nothing changed; a project names each among what it requires @@ -12734,6 +12765,10 @@ fn the_graticule_goes_on_top_in_a_color_of_its_own() { assert_eq!((r["onTop"].clone(), r["color"].clone()), (json!(false), json!(null))); s.run("map.graticule", &json!({"color": "#123456"})).unwrap(); s.run("map.graticule", &json!({"color": " "})).unwrap(); + // `onTop: null` puts the default back too, without showing or hiding the grid. + s.run("map.graticule", &json!({"onTop": true})).unwrap(); + let r = s.run("map.graticule", &json!({"onTop": null})).unwrap(); + assert_eq!((r["on"].clone(), r["onTop"].clone()), (json!(on), json!(false))); assert_eq!(s.map().graticule_color, None); assert_eq!(s.map().graticule_rgba(), s.map().palette().3); assert_eq!(s.map().graticule, on); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 3c4952c3af..428266eff4 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5684,15 +5684,19 @@ fn render_frame( let mut label_layers = label_layers; // The MGRS graticule's names (#1042), over the placed labels and apart from their collisions, // with no layer of their own in a recording, in the graticule's color made opaque. A tilted - // view's bands draw none: their places would repeat from band to band. - if map.graticule && grat.a() > 0 && matches!(labels_to, Labels::Own | Labels::Turned(_)) { + // view's bands draw none: their places would repeat from band to band. Paused labels pause + // them too (and so drapes and tilt patches, drawn paused, leave them out). + if map.graticule && grat.a() > 0 && !map.label_display.paused && matches!(labels_to, Labels::Own | Labels::Turned(_)) { let color = Rgba::rgb(grat.r(), grat.g(), grat.b()); - for (text, x, y) in mapgrid::labels(map, view, |t| text::measure(t, mapgrid::LABEL_PT, false)) { - // Into the turned view's screen, as the placed labels are. + let measure = |t: &str| text::measure(t, mapgrid::LABEL_PT, false); + for (text, x, y) in mapgrid::labels(map, view, measure) { + // Into the turned view's screen, as the placed labels are, and only a name all of + // which shows there: the north-up frame reaches past the turned view's edges. let (x, y) = match turned { Some(to) => { let (sx, sy) = to.to_screen(view.camera.to_map(f64::from(x), f64::from(y), view.width, view.height)); - if !((0.0..=to.width).contains(&sx) && (0.0..=to.height).contains(&sy)) { + let (hw, hh) = mapgrid::label_reach(measure(&text)); + if !(hw <= sx && sx <= to.width - hw && hh <= sy && sy <= to.height - hh) { continue; } (sx as f32, sy as f32) @@ -8769,6 +8773,36 @@ mod tests { assert!(grid(&mut m, &view).is_empty()); } + /// The MGRS names pause with the labels; on a turned view, a name is kept only when all of it + /// shows, never cut at the view's edge. + #[test] + fn mgrs_names_pause_and_keep_within_a_turned_view() { + let mut m = Map::new("Map"); + m.graticule_type = rustgis_map::graticule::GraticuleType::Mgrs; + let camera = Camera { center: lonlat_to_merc(Coord::new(14.5, 48.2)), res: 500.0, bearing: 30.0, pitch: 0.0 }; + let view = View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera, sky: false }; + let grid = |m: &mut Map, view: &View| -> Vec { + render(m, view).unwrap().labels.into_iter().filter(|l| l.size == mapgrid::LABEL_PT && l.halo.is_some()).collect() + }; + // Views over several places, so some names fall near the turned view's edges. + for i in 0..12 { + let at = Coord::new(12.0 + 0.37 * f64::from(i), 47.0 + 0.23 * f64::from(i)); + let v = View { camera: Camera { center: lonlat_to_merc(at), ..camera }, ..view }; + let named = grid(&mut m, &v); + assert!(!named.is_empty()); + for l in &named { + let hw = f64::from(text::measure(&l.text, mapgrid::LABEL_PT, false)) / 2.0; + let hh = f64::from(mapgrid::LABEL_PT) * 1.33 * 1.2 / 2.0; + let (x, y) = (f64::from(l.x), f64::from(l.y)); + assert!(x - hw >= 0.0 && x + hw <= v.width && y - hh >= 0.0 && y + hh <= v.height, "{} at {x}, {y}", l.text); + } + } + m.label_display.paused = true; + for v in [view, View { camera: Camera { bearing: 0.0, ..camera }, ..view }] { + assert!(grid(&mut m, &v).is_empty()); + } + } + /// The graticule's lines are drawn with the basemap, so an opaque filled layer hides them, /// unless they are on top (over the layers, under the labels), in every type; a color set for /// them is used, with its opacity, and the MGRS names take it opaque. On the GPU the lines' diff --git a/crates/render/src/mapgrid.rs b/crates/render/src/mapgrid.rs index 79651fcf90..03c7911f5e 100644 --- a/crates/render/src/mapgrid.rs +++ b/crates/render/src/mapgrid.rs @@ -36,6 +36,8 @@ const MGRS_FINEST: f64 = 100.0; const FEW_CELLS: usize = 4; /// The size of the MGRS graticule's labels, in points (as a layout's MGRS square labels). pub(crate) const LABEL_PT: f32 = 10.0; +/// A label's height in points: a line of [`LABEL_PT`] text. +const LABEL_H: f64 = LABEL_PT as f64 * 1.33 * 1.2; /// The places across and down a 100 km square (and half as many across a grid zone designation) /// whose middle on the screen places its label. const LABEL_SAMPLES: u32 = 8; @@ -172,12 +174,6 @@ fn cells() -> impl Iterator { }) } -/// How many zone-and-band cells the view itself shows (`shown`: places over it). -fn cells_seen(shown: &[Coord]) -> usize { - let seen_parts = extents(shown); - cells().filter(|(_, _, c)| seen_parts.iter().any(|e| overlaps(c, e))).count() -} - /// The UTM graticule's lines (all of them minor; see [`zones`]). #[cfg(test)] fn utm(center: Coord, shown: &[Coord], around: &[Coord]) -> Vec> { @@ -197,11 +193,13 @@ fn zones(center: Coord, shown: &[Coord], around: &[Coord], mgrs: bool) -> GridLi let has_lon = |lon: f64, south: f64, north: f64| parts.iter().any(|e| e.min_x <= lon && lon <= e.max_x && e.min_y <= north && south <= e.max_y); let edges = if mgrs { &mut out.major } else { &mut out.minor }; + // (Made once a frame: the map redraws often.) + let all: Vec<(u8, char, Extent)> = cells().collect(); // Each zone's western edge within each band, and the last zone's eastern one at 180°, so the - // Norway and Svalbard zones are drawn as they are. - for band in BANDS.chars() { - let Some((south, north)) = band_latitudes(band) else { continue }; - for (_, _, cell) in cells().filter(|(_, b, _)| *b == band) { + // Norway and Svalbard zones are drawn as they are. (`cells` gives them band by band.) + for band_cells in all.chunk_by(|a, b| a.1 == b.1) { + let Some((south, north)) = band_cells.first().map(|(_, _, c)| (c.min_y, c.max_y)) else { continue }; + for (_, _, cell) in band_cells { if has_lon(cell.min_x, south, north) { edges.push(meridian(cell.min_x, south, north)); } @@ -219,11 +217,12 @@ fn zones(center: Coord, shown: &[Coord], around: &[Coord], mgrs: bool) -> GridLi } // Eastings and northings when few zone-and-band cells are in the view itself (not counting // the margin, so they don't come and go as it pans), drawn over the margin too. - let seen_cells = cells_seen(shown); + let seen_parts = extents(shown); + let seen_cells = all.iter().filter(|(_, _, c)| seen_parts.iter().any(|e| overlaps(c, e))).count(); if seen_cells == 0 || seen_cells > MAX_GRIDDED_CELLS { return out; } - let in_view: Vec<_> = cells().filter_map(|(z, b, c)| parts.iter().find(|e| overlaps(&c, e)).map(|e| (z, b, c, *e))).collect(); + let in_view: Vec<_> = all.iter().filter_map(|&(z, b, c)| parts.iter().find(|e| overlaps(&c, e)).map(|e| (z, b, c, *e))).collect(); let step = zone_transformer(center) .and_then(|tr| if mgrs { span_over(&tr, shown).map(|span| mgrs_step(span, seen_cells)) } else { step_over(&tr, shown) }); let Some(step) = step else { return out }; @@ -239,13 +238,7 @@ fn zones(center: Coord, shown: &[Coord], around: &[Coord], mgrs: bool) -> GridLi max_x: cell.max_x.min(e.max_x), max_y: cell.max_y.min(e.max_y), }; - let frame: Vec = (0..=8) - .flat_map(|i| { - let t = f64::from(i) / 8.0; - let (x, y) = (part.min_x + part.width() * t, part.min_y + part.height() * t); - [Coord::new(x, part.min_y), Coord::new(x, part.max_y), Coord::new(part.min_x, y), Coord::new(part.max_x, y)] - }) - .collect(); + let frame = frame_of(&part); let g = Grid { kind: GridKind::Measured, step, labels: false, ..Grid::default() }; let mut zone_lines = Vec::new(); measured_lines(&g, &tr, &frame, false, &mut zone_lines); @@ -293,7 +286,6 @@ pub(crate) fn labels(map: &Map, view: &View, width: impl Fn(&str) -> f32) -> Vec return Vec::new(); } // A 100 km square's side on the screen at the view's center, from a kilometer's. - let label_h = f64::from(LABEL_PT) * 1.33 * 1.2; let square_pt = place(w / 2.0, h / 2.0).and_then(|c| { let (zone, north) = (utm_zone(c)?, c.y >= 0.0); let (e, n) = to_utm_in_zone(c, zone, north)?; @@ -302,7 +294,7 @@ pub(crate) fn labels(map: &Map, view: &View, width: impl Fn(&str) -> f32) -> Vec Some(side(from_utm(zone, north, e + 1000.0, n))?.min(side(from_utm(zone, north, e, n + 1000.0))?)) }); // Squares named once the 100 km lines are drawn and a square is three labels tall. - let squares = seen.len() <= MAX_GRIDDED_CELLS && square_pt.is_some_and(|s| s >= 3.0 * label_h); + let squares = seen.len() <= MAX_GRIDDED_CELLS && square_pt.is_some_and(|s| s >= 3.0 * LABEL_H); // The grid zone designations in view: with more than one, a square's name carries its own. let mut gzds: Vec<(u8, char)> = shown.iter().filter_map(|c| Some((utm_zone(*c)?, latitude_band(c.y)?))).collect(); gzds.sort_unstable(); @@ -325,7 +317,7 @@ pub(crate) fn labels(map: &Map, view: &View, width: impl Fn(&str) -> f32) -> Vec let samples = grid_of(LABEL_SAMPLES / 2, part.min_x, part.min_y, part.max_x, part.max_y).filter(|c| in_cell(*c)); let Some((x, y)) = middle(samples.filter_map(&screen)) else { continue }; let fits = |c: Coord| in_cell(c); - if !named.contains(&(zone, band, 0, 0)) && label_fits(&gzd, (x, y), &width, label_h, on_view, place, fits) { + if !named.contains(&(zone, band, 0, 0)) && label_fits(&gzd, (x, y), &width, on_view, place, fits) { named.insert((zone, band, 0, 0)); out.push((gzd.clone(), x as f32, y as f32)); } @@ -365,7 +357,7 @@ pub(crate) fn labels(map: &Map, view: &View, width: impl Fn(&str) -> f32) -> Vec && to_utm_in_zone(c, zone, north) .is_some_and(|(x, y)| (x / SQUARE).floor() as i64 == ie && (y / SQUARE).floor() as i64 == inn) }; - if !named.contains(&(zone, band, ie, inn)) && label_fits(&text, (x, y), &width, label_h, on_view, place, fits) { + if !named.contains(&(zone, band, ie, inn)) && label_fits(&text, (x, y), &width, on_view, place, fits) { named.insert((zone, band, ie, inn)); out.push((text, x as f32, y as f32)); } @@ -412,12 +404,11 @@ fn label_fits( text: &str, (x, y): (f64, f64), width: impl Fn(&str) -> f32, - label_h: f64, on_view: impl Fn((f64, f64)) -> bool, place: impl Fn(f64, f64) -> Option, fits: impl Fn(Coord) -> bool, ) -> bool { - let (hw, hh) = (f64::from(width(text)) / 2.0 + 2.0, label_h / 2.0 + 2.0); + let (hw, hh) = label_reach(width(text)); [(-1.0, -1.0), (0.0, -1.0), (1.0, -1.0), (-1.0, 0.0), (0.0, 0.0), (1.0, 0.0), (-1.0, 1.0), (0.0, 1.0), (1.0, 1.0)].iter().all( |&(kx, ky)| { let p = (x + kx * hw, y + ky * hh); @@ -426,6 +417,12 @@ fn label_fits( ) } +/// How far a label `width` points across reaches from its center, across and down (points), with +/// a little room around it. +pub(crate) fn label_reach(width: f32) -> (f64, f64) { + (f64::from(width) / 2.0 + 2.0, LABEL_H / 2.0 + 2.0) +} + /// The transformer of the UTM zone at `c` (by its 6° zone and hemisphere), made once a code. fn zone_transformer(c: Coord) -> Option> { rustgis_data::ogc::warp::transformer(rustgis_map::layout::utm_epsg(c.x, c.y.clamp(UTM_MIN_LAT, UTM_MAX_LAT - 1e-9))) diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 15f3a821c8..2127f4d143 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -762,9 +762,10 @@ and says so. Two more settings in the same menu apply to every type, and are saved with the map: -- **Draw on top of layers** (`"onTop"` in the command; off by default): by default the grid lines - are drawn with the basemap, under the map's layers and web tile layers, so a filled layer hides - them. With it on, they are drawn over every layer and tile layer, still under the labels. +- **Draw on top of layers** (`"onTop"` in the command; off by default, and `null` goes back to + it): by default the grid lines are drawn with the basemap, under the map's layers and web tile + layers, so a filled layer hides them. With it on, they are drawn over every layer and tile + layer, still under the labels. - **Grid color** (`"color"`: `"#RRGGBB"` or `"#RRGGBBAA"`, with its opacity): the lines' color. By default it is the basemap's own grid color, which is faint; **Default** (`null` or `""` in the command) goes back to it. The MGRS names take the same color, fully opaque. Major and minor From ab7d7bb97cd5f493fa4dbe2cfc9292b77c7a7553 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:07:06 -0600 Subject: [PATCH 04/14] =?UTF-8?q?fix(map):=20an=20empty=20grid=20pass=20dr?= =?UTF-8?q?aws=20nothing=20on=20the=20GPU;=20names=20past=2084=C2=B0N=20an?= =?UTF-8?q?d=20across=20zones=20read=20right?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/render/src/lib.rs | 31 ++++++++++++++++++++++---- crates/render/src/mapgrid.rs | 43 +++++++++++++++++++++++++++++------- docs/user-guide/maps.md | 2 +- 3 files changed, 63 insertions(+), 13 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 428266eff4..21aeafb246 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4253,10 +4253,10 @@ fn render_frame( } }; let (lines, major) = (project(lines), project(major)); - // The minor lines always (as every graticule drew its lines before #1042's MGRS grid), - // the major ones over them when there are any. - for (lines, width, always) in [(lines, 0.6f32, true), (major, 1.2, false)] { - if !always && lines.is_empty() { + // The minor lines, then the major ones over them. An empty set (an MGRS view + // zoomed out has only major lines) draws nothing: no CPU image in the GPU scene. + for (lines, width) in [(lines, 0.6f32), (major, 1.2)] { + if lines.is_empty() { continue; } if gpu { @@ -8884,6 +8884,29 @@ mod tests { } } + /// An MGRS view at the 100 km step has major lines only; on the GPU its empty set of minor + /// lines adds no CPU image to the scene, under the layers or on top of them. + #[test] + fn an_mgrs_grid_of_major_lines_only_adds_no_image_on_the_gpu() { + let mut m = Map::new("Map"); + m.graticule_type = rustgis_map::graticule::GraticuleType::Mgrs; + let camera = Camera { center: lonlat_to_merc(Coord::new(14.5, 48.2)), res: 2000.0, bearing: 0.0, pitch: 0.0 }; + let view = View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera, sky: false }; + let grid = mapgrid::lines(&m, &view).unwrap(); + assert!(grid.minor.is_empty() && !grid.major.is_empty(), "{} minor, {} major", grid.minor.len(), grid.major.len()); + let images = |m: &mut Map| { + let Some(RenderOutput::Gpu(scene)) = render_backend(m, &view, Backend::Gpu) else { panic!("gpu scene") }; + scene.cmds.iter().filter(|c| matches!(c, gpu_scene::DrawCmd::Image { .. })).count() + }; + m.graticule = false; + let without = images(&mut m); + m.graticule = true; + for on_top in [false, true] { + m.graticule_on_top = on_top; + assert_eq!(images(&mut m), without, "on top: {on_top}"); + } + } + #[test] fn a_selected_text_graphic_is_framed_with_its_label() { let mut m = Map::new("Map"); diff --git a/crates/render/src/mapgrid.rs b/crates/render/src/mapgrid.rs index 03c7911f5e..e716a126d7 100644 --- a/crates/render/src/mapgrid.rs +++ b/crates/render/src/mapgrid.rs @@ -285,9 +285,12 @@ pub(crate) fn labels(map: &Map, view: &View, width: impl Fn(&str) -> f32) -> Vec if seen.is_empty() { return Vec::new(); } - // A 100 km square's side on the screen at the view's center, from a kilometer's. - let square_pt = place(w / 2.0, h / 2.0).and_then(|c| { - let (zone, north) = (utm_zone(c)?, c.y >= 0.0); + // A 100 km square's side on the screen, from a kilometer's, at the view's center or else the + // first place in view in a grid zone designation (a view centered past 84° N still shows + // band X). + let square_pt = place(w / 2.0, h / 2.0).into_iter().chain(shown.iter().copied()).find_map(|c| { + let &(zone, band, _) = seen.iter().find(|(_, _, cell)| cell.contains(c))?; + let north = band >= 'N'; let (e, n) = to_utm_in_zone(c, zone, north)?; let (sx, sy) = screen(c)?; let side = |p: Option| p.and_then(project).map(|(x, y)| (x - sx).hypot(y - sy) * SQUARE / 1000.0); @@ -295,11 +298,9 @@ pub(crate) fn labels(map: &Map, view: &View, width: impl Fn(&str) -> f32) -> Vec }); // Squares named once the 100 km lines are drawn and a square is three labels tall. let squares = seen.len() <= MAX_GRIDDED_CELLS && square_pt.is_some_and(|s| s >= 3.0 * LABEL_H); - // The grid zone designations in view: with more than one, a square's name carries its own. - let mut gzds: Vec<(u8, char)> = shown.iter().filter_map(|c| Some((utm_zone(*c)?, latitude_band(c.y)?))).collect(); - gzds.sort_unstable(); - gzds.dedup(); - let one_gzd = gzds.len() <= 1; + // With more than one grid zone designation reaching into the view, a square's name carries + // its own: every named square is in one of the `seen` cells. + let one_gzd = seen.len() <= 1; let mut out: Vec<(String, f32, f32)> = Vec::new(); let mut named = std::collections::BTreeSet::new(); for (zone, band, cell) in seen { @@ -890,4 +891,30 @@ mod tests { assert!(got.iter().any(|(t, _, _)| t.starts_with("34U ")) && got.iter().any(|(t, _, _)| t.starts_with("33U ")), "{got:?}"); name_their_places(&m, &view, &got, |r| format!("{} {}{}", gzd(r), r.column, r.row)); } + + /// A view of 33U with a narrow strip of 34U at its right edge (north up and turned), or of + /// 33T at its bottom, names its squares with their grid zone designations. + #[test] + fn a_narrow_strip_of_another_grid_zone_designation_prefixes_the_names() { + let per_pt = 50.0 / 111_319.490_793; + for bearing in [0.0, 30.0] { + for (lon, lat) in [(18.0 - 360.0 * per_pt, 49.5), (15.0, 48.0 + 270.0 * per_pt * 0.66)] { + let (m, mut view) = mgrs_view(lon, lat, 50.0); + view.camera.bearing = bearing; + let got = labels_on(&m, &view); + assert!(!got.is_empty() && got.iter().all(|(t, _, _)| t.len() == 6), "{bearing}: {got:?}"); + name_their_places(&m, &view, &got, |r| format!("{} {}{}", gzd(r), r.column, r.row)); + } + } + } + + /// A view centered past 84° N, where no UTM zone is, names the band X squares it shows (the + /// view reaches down to about 83.9° N). + #[test] + fn a_view_centered_past_84_north_names_band_x_squares() { + let (m, view) = mgrs_view(15.0, 84.3, 1500.0); + let got = labels_on(&m, &view); + assert!(!got.is_empty() && got.iter().all(|(t, _, _)| t.len() == 2), "{got:?}"); + name_their_places(&m, &view, &got, |r| format!("{}{}", r.column, r.row)); + } } diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 2127f4d143..f48a2370aa 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -765,7 +765,7 @@ Two more settings in the same menu apply to every type, and are saved with the m - **Draw on top of layers** (`"onTop"` in the command; off by default, and `null` goes back to it): by default the grid lines are drawn with the basemap, under the map's layers and web tile layers, so a filled layer hides them. With it on, they are drawn over every layer and tile - layer, still under the labels. + layer, still under the labels. They then also draw over the highlights of selected features. - **Grid color** (`"color"`: `"#RRGGBB"` or `"#RRGGBBAA"`, with its opacity): the lines' color. By default it is the basemap's own grid color, which is faint; **Default** (`null` or `""` in the command) goes back to it. The MGRS names take the same color, fully opaque. Major and minor From bf8e75b0fd90d7bcc76c936d8ea71e56926e903f Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:08:56 -0600 Subject: [PATCH 05/14] test(engine): a fixture project with an MGRS grid on top in its own color --- crates/engine/src/project_capabilities.rs | 22 ++++++++++++++++++++++ schema/fixtures/graticule_mgrs.rgis | 1 + 2 files changed, 23 insertions(+) create mode 100644 schema/fixtures/graticule_mgrs.rgis diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 36727e2cbe..dd650595e5 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -315,6 +315,28 @@ mod tests { serde_json::from_slice(bytes).unwrap() } + /// A saved MGRS graticule drawn on top in a color of its own (#1042 piece 8) reads back as it + /// was, and saving names all three again; a map without them names none. + #[test] + fn graticule_mgrs_fixture_reads_its_grid() { + use rustgis_map::graticule::GraticuleType; + let fixture = Project::from_json(include_str!("../../../schema/fixtures/graticule_mgrs.rgis")).unwrap(); + let saved = serde_json::to_value(&fixture).unwrap(); + assert_eq!(saved["requires"], json!(["graticule-mgrs", "graticule-on-top", "graticule-color"])); + let map = &fixture.maps[0]; + assert_eq!(map.graticule_type, GraticuleType::Mgrs); + assert!(map.graticule && map.graticule_on_top); + assert_eq!(map.graticule_color.map(|c| (c.r(), c.g(), c.b(), c.a())), Some((48, 48, 48, 153))); + let reopened = Project::from_json(&saved.to_string()).unwrap(); + assert_eq!(serde_json::to_value(&reopened).unwrap(), saved); + let mut plain = fixture; + let map = &mut plain.maps[0]; + map.graticule_type = GraticuleType::Utm; + map.graticule_on_top = false; + map.graticule_color = None; + assert!(serde_json::to_value(&plain).unwrap().get("requires").is_none()); + } + /// A saved image marker reads back as the image it was, and saving names it again. #[test] fn picture_markers_fixture_reads_its_image() { diff --git a/schema/fixtures/graticule_mgrs.rgis b/schema/fixtures/graticule_mgrs.rgis new file mode 100644 index 0000000000..81d165a426 --- /dev/null +++ b/schema/fixtures/graticule_mgrs.rgis @@ -0,0 +1 @@ +{"requires":["graticule-mgrs","graticule-on-top","graticule-color"],"format":2,"name":"graticule_mgrs","maps":[{"name":"Map","layers":[],"basemap":"Paper","camera":{"center":{"x":0.0,"y":2000000.0},"res":30000.0,"bearing":0.0,"pitch":0.0},"bookmarks":[],"graticule":true,"graticule_type":"mgrs","graticule_on_top":true,"graticule_color":[48,48,48,153],"projection":"WebMercator","popup_mode":"Topmost","label_display":{"paused":false,"locked":false,"show_unplaced":false},"editing":{"relationships":[],"snapping":{"enabled":false,"tolerance_px":10.0,"vertex":true,"edge":true,"end":true},"topology":[],"settings":{"enabled":true,"show_vertices":true,"elevation":"None","ground_to_grid":null}},"swipe":null,"view":{"effects":{"stars":true,"sun_time":null,"weather":"None","vignette":false,"edges":false,"tilt_shift":false,"grain":false,"brightness":0.0,"contrast":0.0,"saturation":0.0,"sepia":0.0},"wireframe":false,"clip_distance":null,"terrain":null},"animation":[],"next_layer_id":1}],"active_map":0,"tables":[],"next_table_id":1,"gp_history":[],"layouts":[],"folders":[],"styles":[],"ramps":[],"tasks":[],"gp_env":{"extent":null,"cell_size":null},"models":[],"workspaces":[],"link_views":false,"jobs":[],"offline_areas":[],"reports":[],"presentations":[],"notebooks":[],"dl_models":[],"shared":[],"data_stores":[]} \ No newline at end of file From b27881235678444b5cbc10c6af32c4d947ef1438 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:40:30 -0600 Subject: [PATCH 06/14] style: format after the main merge, and end the MGRS fixture with a newline --- crates/engine/src/project_capabilities.rs | 15 +++++++++++++-- schema/fixtures/graticule_mgrs.rgis | 2 +- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 960d93d9a0..ea82d34f81 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -279,8 +279,19 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { } fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static str> { - let (mut block, mut water, mut shore, mut relief, mut light, mut legends, mut sized, mut pictures, mut mgrs, mut on_top, mut grid_color) = - (false, false, false, false, false, false, false, false, false, false, false); + let ( + mut block, + mut water, + mut shore, + mut relief, + mut light, + mut legends, + mut sized, + mut pictures, + mut mgrs, + mut on_top, + mut grid_color, + ) = (false, false, false, false, false, false, false, false, false, false, false); for map in maps { // An older reader doesn't know the MGRS graticule (#1042 piece 8): it refuses the // project by name rather than failing to read the type. diff --git a/schema/fixtures/graticule_mgrs.rgis b/schema/fixtures/graticule_mgrs.rgis index 81d165a426..5498a807b2 100644 --- a/schema/fixtures/graticule_mgrs.rgis +++ b/schema/fixtures/graticule_mgrs.rgis @@ -1 +1 @@ -{"requires":["graticule-mgrs","graticule-on-top","graticule-color"],"format":2,"name":"graticule_mgrs","maps":[{"name":"Map","layers":[],"basemap":"Paper","camera":{"center":{"x":0.0,"y":2000000.0},"res":30000.0,"bearing":0.0,"pitch":0.0},"bookmarks":[],"graticule":true,"graticule_type":"mgrs","graticule_on_top":true,"graticule_color":[48,48,48,153],"projection":"WebMercator","popup_mode":"Topmost","label_display":{"paused":false,"locked":false,"show_unplaced":false},"editing":{"relationships":[],"snapping":{"enabled":false,"tolerance_px":10.0,"vertex":true,"edge":true,"end":true},"topology":[],"settings":{"enabled":true,"show_vertices":true,"elevation":"None","ground_to_grid":null}},"swipe":null,"view":{"effects":{"stars":true,"sun_time":null,"weather":"None","vignette":false,"edges":false,"tilt_shift":false,"grain":false,"brightness":0.0,"contrast":0.0,"saturation":0.0,"sepia":0.0},"wireframe":false,"clip_distance":null,"terrain":null},"animation":[],"next_layer_id":1}],"active_map":0,"tables":[],"next_table_id":1,"gp_history":[],"layouts":[],"folders":[],"styles":[],"ramps":[],"tasks":[],"gp_env":{"extent":null,"cell_size":null},"models":[],"workspaces":[],"link_views":false,"jobs":[],"offline_areas":[],"reports":[],"presentations":[],"notebooks":[],"dl_models":[],"shared":[],"data_stores":[]} \ No newline at end of file +{"requires":["graticule-mgrs","graticule-on-top","graticule-color"],"format":2,"name":"graticule_mgrs","maps":[{"name":"Map","layers":[],"basemap":"Paper","camera":{"center":{"x":0.0,"y":2000000.0},"res":30000.0,"bearing":0.0,"pitch":0.0},"bookmarks":[],"graticule":true,"graticule_type":"mgrs","graticule_on_top":true,"graticule_color":[48,48,48,153],"projection":"WebMercator","popup_mode":"Topmost","label_display":{"paused":false,"locked":false,"show_unplaced":false},"editing":{"relationships":[],"snapping":{"enabled":false,"tolerance_px":10.0,"vertex":true,"edge":true,"end":true},"topology":[],"settings":{"enabled":true,"show_vertices":true,"elevation":"None","ground_to_grid":null}},"swipe":null,"view":{"effects":{"stars":true,"sun_time":null,"weather":"None","vignette":false,"edges":false,"tilt_shift":false,"grain":false,"brightness":0.0,"contrast":0.0,"saturation":0.0,"sepia":0.0},"wireframe":false,"clip_distance":null,"terrain":null},"animation":[],"next_layer_id":1}],"active_map":0,"tables":[],"next_table_id":1,"gp_history":[],"layouts":[],"folders":[],"styles":[],"ramps":[],"tasks":[],"gp_env":{"extent":null,"cell_size":null},"models":[],"workspaces":[],"link_views":false,"jobs":[],"offline_areas":[],"reports":[],"presentations":[],"notebooks":[],"dl_models":[],"shared":[],"data_stores":[]} From 3e752227bfc77b2ca76cd9301e3ab987d2a7309d Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:40:30 -0600 Subject: [PATCH 07/14] fix(ui): the grid color keeps its RGB when only its opacity changes; the guide says MGRS names draw over the layers as labels do --- crates/ui-egui/src/ribbon.rs | 14 +++++++++----- docs/user-guide/maps.md | 2 ++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 6c3c51e6bb..a7164c3be8 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1878,14 +1878,18 @@ fn graticule_menu(ui: &mut Ui, app: &mut RustGisApp) { app.session.notify(e, true); } let set = app.session.map().graticule_color.is_some(); - let mut color = crate::theme::c32(app.session.map().graticule_rgba()); + let current = app.session.map().graticule_rgba(); ui.horizontal(|ui| { let name = ui.label(tl!("Grid color")); - // Named by its label, for a screen reader. - let resp = crate::widgets::color_button(ui, &mut color).on_hover_text(tl!("The grid's color and opacity")).labelled_by(name.id); - if resp.changed() { + // Named by its label, for a screen reader. The saved color's RGB is kept at no opacity + // (`rgba_button`), so raising only the opacity keeps the color. + let (resp, picked) = crate::widgets::rgba_button(ui, current); + let resp = resp.on_hover_text(tl!("The grid's color and opacity")).labelled_by(name.id); + if resp.changed() + && let Some(picked) = picked + { crate::widgets::one_step_per_press(app, &resp); - if let Err(e) = app.run("map.graticule", json!({"color": crate::theme::rgba(color).hex8()})) { + if let Err(e) = app.run("map.graticule", json!({"color": picked.hex8()})) { app.session.notify(e, true); } } diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index f48a2370aa..8e98d11327 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -766,6 +766,8 @@ Two more settings in the same menu apply to every type, and are saved with the m it): by default the grid lines are drawn with the basemap, under the map's layers and web tile layers, so a filled layer hides them. With it on, they are drawn over every layer and tile layer, still under the labels. They then also draw over the highlights of selected features. + The MGRS names are labels, so they're drawn over the layers either way, as the layers' own + labels are: a filled layer can hide the lines under a name but not the name. - **Grid color** (`"color"`: `"#RRGGBB"` or `"#RRGGBBAA"`, with its opacity): the lines' color. By default it is the basemap's own grid color, which is faint; **Default** (`null` or `""` in the command) goes back to it. The MGRS names take the same color, fully opaque. Major and minor From 8833795b719251a92244f7c76402171d3a534873 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:22:10 -0600 Subject: [PATCH 08/14] docs(map): MGRS names go with the lines at no opacity and pause with the labels; the grid color is saved when the picker gives one --- crates/ui-egui/src/ribbon.rs | 4 +--- docs/user-guide/maps.md | 3 ++- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index a7164c3be8..002ba4c2d1 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1885,9 +1885,7 @@ fn graticule_menu(ui: &mut Ui, app: &mut RustGisApp) { // (`rgba_button`), so raising only the opacity keeps the color. let (resp, picked) = crate::widgets::rgba_button(ui, current); let resp = resp.on_hover_text(tl!("The grid's color and opacity")).labelled_by(name.id); - if resp.changed() - && let Some(picked) = picked - { + if let Some(picked) = picked { crate::widgets::one_step_per_press(app, &resp); if let Err(e) = app.run("map.graticule", json!({"color": picked.hex8()})) { app.session.notify(e, true); diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 8e98d11327..a3c5e8f14a 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -767,7 +767,8 @@ Two more settings in the same menu apply to every type, and are saved with the m layers, so a filled layer hides them. With it on, they are drawn over every layer and tile layer, still under the labels. They then also draw over the highlights of selected features. The MGRS names are labels, so they're drawn over the layers either way, as the layers' own - labels are: a filled layer can hide the lines under a name but not the name. + labels are: a filled layer can hide the lines under a name but not the name. They go with the + lines when the grid's opacity is 0, and pause with the labels. - **Grid color** (`"color"`: `"#RRGGBB"` or `"#RRGGBBAA"`, with its opacity): the lines' color. By default it is the basemap's own grid color, which is faint; **Default** (`null` or `""` in the command) goes back to it. The MGRS names take the same color, fully opaque. Major and minor From 8aeacfccdb27fcbfc6a940da071a5ca18be901bd Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:07:13 -0600 Subject: [PATCH 09/14] test(ui): the grid color keeps its RGB when only its opacity is raised --- crates/ui-egui/src/ribbon.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 002ba4c2d1..72cd433f88 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -5614,6 +5614,40 @@ mod tests { assert_eq!(h.state().session.map().graticule_color, None); } + /// The graticule menu's color picker keeps a saved color's RGB at no opacity: raising only the + /// opacity of `#33669900` saves `#33669980`, not black at that opacity. Drives the same + /// `rgba_button` the menu calls, fed the color the menu feeds it (`graticule_rgba`), typing the + /// opacity into the picker's A number, then saves what it picked through `map.graticule` as the + /// menu does. (The picker is driven on its own: kittest closes the menu on the click that opens + /// the picker's popup.) + #[test] + fn the_graticule_color_keeps_its_rgb_when_only_the_opacity_is_raised() { + let mut app = RustGisApp::with_sample(); + app.session.run("map.graticule", &json!({"color": "#33669900"})).unwrap(); + let current = app.session.map().graticule_rgba(); + assert_eq!(current.hex8(), "#33669900"); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state( + |ui, picked: &mut Option| { + if let (_, Some(c)) = crate::widgets::rgba_button(ui, current) { + *picked = Some(c); + } + }, + None, + ); + h.get_by_role(egui::accesskit::Role::ColorWell).click(); + h.run(); + // A transparent picker edits linear values; the picker's numbers are R, G, B, A. + h.query_all_by_role(egui::accesskit::Role::SpinButton).nth(3).unwrap().focus(); + h.run(); + h.event(egui::Event::Text("0.5".into())); + h.run(); + h.key_press(egui::Key::Enter); + h.run(); + let picked = h.state().expect("the picker gave a color"); + app.session.run("map.graticule", &json!({"color": picked.hex8()})).unwrap(); + assert_eq!(app.session.map().graticule_rgba().hex8(), "#33669980"); + } + /// The language list names every language in English while the interface is English, with the /// language's own name as the tooltip; in another language each keeps its own name, or its /// English one where no font can draw it. From fab4a4f64db8d4ed8612ac9882c5266366406ed7 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:44:24 -0600 Subject: [PATCH 10/14] test(engine): the saved-task grid color test uses a valid color --- crates/engine/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6e3f92b87a..93224a7f47 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -14072,7 +14072,7 @@ fn saved_graticule_settings_are_required_by_name() { }; assert_eq!(with_task(json!({"onTop": true})), Some(json!(["graticule-on-top"]))); assert_eq!(with_task(json!({"color": "#ff000080"})), Some(json!(["graticule-color"]))); - assert_eq!(with_task(json!({"onTop": true, "color": "#000"})), Some(json!(["graticule-on-top", "graticule-color"]))); + assert_eq!(with_task(json!({"onTop": true, "color": "#000000"})), Some(json!(["graticule-on-top", "graticule-color"]))); // Any value, null included: an older reader would toggle the grid where this one keeps it, even // for the defaults, and `onTop` reads "true" and 1 as true. for on_top in [json!(null), json!(false), json!("true"), json!(1)] { From af971faa3a5777fcc3548d8b8ee06f6625e1b708 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:05:44 -0600 Subject: [PATCH 11/14] fix(map): a map's look keeps and compares the grid drawn over the layers and its own color --- crates/map/src/look.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/map/src/look.rs b/crates/map/src/look.rs index 65437a452a..ac728765f1 100644 --- a/crates/map/src/look.rs +++ b/crates/map/src/look.rs @@ -247,6 +247,8 @@ impl MapLook { graticule, graticule_type, graticule_crs, + graticule_on_top, + graticule_color, projection, popup_mode, label_display, @@ -276,6 +278,8 @@ impl MapLook { graticule: *graticule, graticule_type: *graticule_type, graticule_crs: graticule_crs.clone(), + graticule_on_top: *graticule_on_top, + graticule_color: *graticule_color, projection: projection.clone(), popup_mode: *popup_mode, label_display: *label_display, @@ -313,6 +317,8 @@ impl MapLook { graticule, graticule_type, graticule_crs, + graticule_on_top, + graticule_color, projection, popup_mode: _, label_display, @@ -338,6 +344,8 @@ impl MapLook { && *graticule == map.graticule && *graticule_type == map.graticule_type && *graticule_crs == map.graticule_crs + && *graticule_on_top == map.graticule_on_top + && *graticule_color == map.graticule_color && *projection == map.projection && *label_display == map.label_display && *label_lock == map.label_lock @@ -502,5 +510,12 @@ mod tests { assert!(!grouped.same(&MapLook::of(&map))); map.graticule = !map.graticule; assert!(!before.same(&MapLook::of(&map))); + // The grid drawn over the layers, or in a color of its own, draws differently too. + let gridded = MapLook::of(&map); + map.graticule_on_top = !map.graticule_on_top; + assert!(!gridded.same(&MapLook::of(&map)), "the grid over the layers"); + let on_top = MapLook::of(&map); + map.graticule_color = Some(crate::Rgba::rgb(51, 102, 153)); + assert!(!on_top.same(&MapLook::of(&map)), "the grid's own color"); } } From c77d4daf85aec70b94ab5bc6406e322275277589 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:10:37 -0600 Subject: [PATCH 12/14] docs(render): the MGRS label check is a sample of nine points, as label_fits says --- crates/render/src/mapgrid.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/render/src/mapgrid.rs b/crates/render/src/mapgrid.rs index 19ae239d4f..1c8ed57b4c 100644 --- a/crates/render/src/mapgrid.rs +++ b/crates/render/src/mapgrid.rs @@ -257,8 +257,9 @@ fn zones(center: Coord, shown: &[Coord], around: &[Coord], mgrs: bool) -> GridLi /// another type. Zoomed out, or while the 100 km squares are too small on the screen to name, each /// grid zone designation in view is named (`33U`) at the middle of what shows of it; zoomed in, /// each 100 km square of each one, by its letters (`VP`), with its grid zone designation (`33U VP`) -/// when more than one is in view. A label goes only where all of it stays within its zone and -/// square and the view, so a zone or square cut too small isn't named. Nothing is named in the polar +/// when more than one is in view. A label goes only where its corners, edge middles and center all +/// stay within its zone and square and the view (a sample, [`label_fits`]), so a zone or square cut +/// too small isn't named. Nothing is named in the polar /// areas (UPS). `width` measures a text across in points at [`LABEL_PT`]. pub(crate) fn labels(map: &Map, view: &View, width: impl Fn(&str) -> f32) -> Vec<(String, f32, f32)> { if map.graticule_type != GraticuleType::Mgrs { From ddc9fa633cfd28cf62da351e903c5276bac64e17 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 21 Nov 2026 13:50:48 -0500 Subject: [PATCH 13/14] Address Claude review feedback - map.graticule's "on" parameter says the grid is kept as it is when only onTop or color is given, as the command does, so the Assistant and MCP don't expect it to toggle. --- crates/engine/src/cmd/navigate.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs index 02d2f05c3b..e10af903c0 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -79,7 +79,7 @@ pub fn commands() -> Vec { C::new("map.basemap", "Basemap", "Home › Add", basemap).roles(&[]).effects(crate::policy::Effects::NONE) .params(r##"{"name": "paper"|"midnight"|"ocean"|"atlas"|"blank", "keepTiles"?: bool (keeps the web tile basemaps over it), "color"?: "#RRGGBB" (blank: the paper's colour, drawn where a blank map draws white, the tilted view's sky included; null or #FFFFFF: white; default: as it was. Another basemap takes the paper off and keeps its own colours; a color given with it is said as a warning)}"##), C::new("map.graticule", "Graticule", "View › Display", graticule).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r##"{"on"?: bool (toggles when omitted, on when a type or crs is given), "type"?: "degrees"|"measured"|"utm"|"mgrs", "crs"?: a projected system for the measured grid (EPSG:2056, WKT or a PROJ string; "" or null: the map's own when projected, else the UTM zone at the view's centre), "onTop"?: bool (the lines over the layers, under the labels; false or null: with the basemap, under the layers), "color"?: "#RRGGBB"|"#RRGGBBAA" ("" or null: the basemap's)}"##), + .params(r##"{"on"?: bool (toggles when omitted, on when a type or crs is given, kept as it is when only onTop or color is given), "type"?: "degrees"|"measured"|"utm"|"mgrs", "crs"?: a projected system for the measured grid (EPSG:2056, WKT or a PROJ string; "" or null: the map's own when projected, else the UTM zone at the view's centre), "onTop"?: bool (the lines over the layers, under the labels; false or null: with the basemap, under the layers), "color"?: "#RRGGBB"|"#RRGGBBAA" ("" or null: the basemap's)}"##), C::new("map.reloadWebLayers", "Reload Web Layers", "View › Display", |_, _| { // The map view draws again when the tile cache's generation moves. crate::render::rustgis_tiles::cache::clear(); From cd96a0bef1651ae53293499e9fc615d04503d7c2 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 21 Nov 2026 14:02:11 -0500 Subject: [PATCH 14/14] Address Claude review feedback - An on-top grid whose lines Lyon refused leaves a picture; a turned or tilted GPU stand-in now checks for one after drawing it, as it does after the layers, instead of returning a frame with a flat picture. --- crates/render/src/lib.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 1509200002..c59803f435 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5975,6 +5975,11 @@ fn render_frame( } if map.graticule_on_top { draw_graticule!(); + // The grid's lines left as a picture (Lyon refused them) spoil a turned or tilted + // stand-in as a layer's would. + if pictureless && (cpu_dirty || holds_picture(&cmds)) { + return None; + } } if let Some(plan) = cached.take() { frame_cache::keep(plan, captured, captured_alone);