diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 41ac641245..b0e5f684ba 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -297,7 +297,7 @@ layout.import path? text? layout.move name? layout? to layout.new name? page? orientation? width? height? template? layout.page layout? page? orientation? width? height? decimal? color? -layout.publication profile? extent? name? title? subtitle? sources? reference? note? author? headings? locator? decimal? colorbar? veil? contextInLegend? northArrow? grid? scaleBar? legend? legendBox? style? paper? kicker? figures? accent? arrangement? coverage? +layout.publication profile? extent? crs? name? title? subtitle? sources? reference? note? author? headings? locator? decimal? colorbar? veil? contextInLegend? northArrow? grid? scaleBar? legend? legendBox? style? paper? kicker? figures? accent? arrangement? coverage? layout.remove name? layout? layout.removeElement layout? element layout.rename name? layout? newName diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 31127f4f70..adfa84996f 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -401,7 +401,7 @@ fn view_in_map_system(s: &Session) -> Result<(rustgis_geom::Extent, Crs), String } /// A coordinate system given as an EPSG code or any text [`Crs::parse`] reads. -fn crs_param(s: &mut Session, p: &Value, key: &str) -> Result, String> { +pub(crate) fn crs_param(s: &mut Session, p: &Value, key: &str) -> Result, String> { let (crs, warning) = crs_param_read(p, key)?; if let Some(w) = warning { s.warn(w); diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 88a808c7f9..2b904fc724 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -71,7 +71,8 @@ pub fn commands() -> Vec { C::new("layout.publication", "New Publication Layout", "Publish › Layout", publication).inputs(publication_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( concat!( r#"{"profile"?: "a4" (the default) | "letter"|"legal"|"tabloid"|"a5"|"a3"|"a2"|"a1"|"a0" (a sheet turned to portrait or landscape, whichever the area's map comes out larger on: its extent east to west against north to south, on the map's projection) | a size with its orientation: "a4-portrait"|"a4-landscape"|"letter-portrait"|"tabloid-landscape"|… for each of those sizes (a sheet: frame, title, subtitle, the map, a boxed footer, all scaled to the sheet)|"figure-1col" (90 mm)|"figure-1.5col" (140 mm)|"figure-2col" (190 mm)|"thesis-full" (160 × 225 mm)|"thesis-half" (160 × 110 mm) (a figure: the map edge to edge, its title and sources left to the caption), "#, - r#""extent"?: [west, south, east, north] in degrees that must fit (default: the map view), "#, + r#""extent"?: [west, south, east, north] in degrees that must fit (default: the map view), or in the map's coordinates with "crs", "#, + r#""crs"?: the map's own coordinate system ("EPSG:32633" on a map in it, "EPSG:3857" on a Web Mercator map): "extent" is then a rectangle in it, framed as it is rather than as the box in degrees around it; refused for any other system, on the globe and on another body's map, "#, r#""name"?: string, "#, r#""title"?: text, "#, r#""subtitle"?: text, "#, diff --git a/crates/engine/src/cmd/layout/publication/area.rs b/crates/engine/src/cmd/layout/publication/area.rs new file mode 100644 index 0000000000..2c38ae8ba0 --- /dev/null +++ b/crates/engine/src/cmd/layout/publication/area.rs @@ -0,0 +1,81 @@ +//! A publication's area given in the map's own coordinate system (#3322). + +use super::*; +use rustgis_data::raster::Crs; + +/// How finely a rectangle is sampled to find the places it covers: a grid of this many cells along +/// each side. Its inside is sampled as well as its edges, since a rectangle wider than its projection +/// has no edge on the Earth. +const GRID: u32 = 32; + +/// The longest side a rectangle may have, in ground metres: two Earth circumferences, past any +/// projection's reach. A longer one would have the frame's scale cut and the rectangle missed. +const LONGEST_SIDE_M: f64 = 4.0 * std::f64::consts::PI * rustgis_geom::EARTH_RADIUS_M; + +/// `extent` read in `crs`, which is the active map's own system: the area's size as a +/// longitude/latitude extent (for the graticule and the north arrow, which go by degrees), and the +/// rectangle itself in the map's coordinates, which is what the frame shows. +pub(super) fn in_map_system(s: &Session, extent: Option<&Value>, crs: Crs) -> Result<(Extent, Extent), String> { + let extent = extent.filter(|v| !v.is_null()).ok_or("crs goes with extent")?; + let map = s.map(); + // Web Mercator's own system is the Earth's: another body's map has none to name. + let own = map.own_system().filter(|_| map.body().is_earth()).ok_or( + "the map has no flat system of its own here (the globe, a world projection or another body's map): give extent in degrees without crs", + )?; + if crs != own { + return Err(format!( + "extent is in {}, but the map is in {}: give it in the map's system, or in degrees without crs", + crs.label(), + own.label() + )); + } + // Two finite sides can still be too far apart for their difference to be one. + let plane = match four_sides(extent) { + Some([w, so, e, n]) if w < e && so < n && (e - w).is_finite() && (n - so).is_finite() => Extent::new(w, so, e, n), + _ => return Err("extent is [west, south, east, north] in the map's coordinates with crs".into()), + }; + let places: Vec = crate::cmd::workspace::places_in(map, plane, GRID).collect(); + if places.is_empty() { + return Err("the extent names no place on the map".into()); + } + // The frame keeps its centre in longitude and latitude, and one it can't be drawn at is moved. + let center = map + .to_lonlat(plane.center()) + .filter(|c| rustgis_map::layout::frame_center_placed(map, *c)) + .ok_or("the extent's centre has no place on the map")?; + // Measured as the frame's fit measures it. + let per_unit = (map.flat().ground_per_unit(plane.center()) * map.body().ratio()).max(1e-9); + if plane.width().max(plane.height()) * per_unit > LONGEST_SIDE_M { + return Err("the extent is too large to frame: more than twice the Earth's circumference across".into()); + } + Ok((size_in_degrees(map, plane, center, &places), plane)) +} + +/// The four numbers of an `extent`, when it is a list of four finite ones. +pub(super) fn four_sides(extent: &Value) -> Option<[f64; 4]> { + let sides: Vec = extent.as_array()?.iter().map(|x| x.as_f64().filter(|x| x.is_finite())).collect::>()?; + sides.try_into().ok() +} + +/// An extent as large as `places`, those of `plane` centred on `center` (the part of a rectangle off +/// the Earth counts for nothing, though the frame still shows it): continuous over ±180°; and +/// around a pole, where the width in longitude says nothing, a square twice the way from the pole to +/// the farthest of them. +fn size_in_degrees(map: &rustgis_map::Map, plane: Extent, center: Coord, places: &[Coord]) -> Extent { + let flat = map.flat(); + let holds = |c: Coord| c.x >= plane.min_x && c.x <= plane.max_x && c.y >= plane.min_y && c.y <= plane.max_y; + // Only a pole the projection places: Web Mercator puts its own at 85°. + let pole = [90.0, -90.0].into_iter().find(|lat| { + let at = Coord::new(center.x, *lat); + rustgis_map::layout::frame_center_placed(map, at) && flat.forward_checked(at).is_some_and(holds) + }); + if let Some(pole) = pole { + let far = places.iter().map(|c| (c.y - pole).abs()).fold(0.0, f64::max); + return Extent::new(-far, -far, far, far); + } + let mut size = Extent::EMPTY; + for c in places { + size.expand(Coord::new(center.x + (c.x - center.x + 180.0).rem_euclid(360.0) - 180.0, c.y)); + } + size +} diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index 7d556d19f8..fb5ec5e91a 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -2,6 +2,8 @@ use super::*; +mod area; +use area::*; mod arrangement; pub use arrangement::*; mod coverage; @@ -87,28 +89,35 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let (auto, profile) = publication_profile(p)?; let (sheet, page_w, page_h) = (profile.sheet, profile.width, profile.height); let whole_globe = shows_whole_globe(s.map(), p); - let extent = match p.get("extent").filter(|v| !v.is_null()) { + // An extent in the map's own system (#3322): `plane` is that rectangle, framed as it is, and + // `extent` only says how large it is in degrees. + let in_own = match crate::cmd::imagery::crs_param(s, p, "crs")? { + Some(crs) => Some(in_map_system(s, p.get("extent"), crs)?), + None => None, + }; + let extent = match (in_own, p.get("extent").filter(|v| !v.is_null())) { + (Some((size, _)), _) => size, // The view; on a globe the whole Earth, as geoprocessing takes it (the globe camera's flat // extent means nothing there). - None if whole_globe => Extent::new(-180.0, -90.0, 180.0, 90.0), - None => { + (None, None) if whole_globe => Extent::new(-180.0, -90.0, 180.0, 90.0), + (None, None) => { let e = crate::cmd::workspace::view_extent(s); - Extent::new(e.min_x.max(-180.0), e.min_y.max(-90.0), e.max_x.min(180.0), e.max_y.min(90.0)) - } - Some(v) => { - let b: Option> = - v.as_array().filter(|a| a.len() == 4).and_then(|a| a.iter().map(|x| x.as_f64().filter(|x| x.is_finite())).collect()); - match b.as_deref() { - Some([w, so, e, n]) if w < e && so < n && *w >= -180.0 && *e <= 180.0 && *so >= -90.0 && *n <= 90.0 => { - Extent::new(*w, *so, *e, *n) - } - _ => return Err("extent is [west, south, east, north] in degrees".into()), + let e = Extent::new(e.min_x.max(-180.0), e.min_y.max(-90.0), e.max_x.min(180.0), e.max_y.min(90.0)); + if !(e.width() > 0.0 && e.height() > 0.0) { + return Err("the map's extent isn't known; give extent".into()); } + e } + (None, Some(v)) => match four_sides(v) { + Some([w, so, e, n]) if w < e && so < n && w >= -180.0 && e <= 180.0 && so >= -90.0 && n <= 90.0 => Extent::new(w, so, e, n), + _ => return Err("extent is [west, south, east, north] in degrees".into()), + }, }; - if !(extent.width() > 0.0 && extent.height() > 0.0) { - return Err("the map's extent isn't known; give extent".into()); - } + let rectangle = in_own.map(|(_, plane)| plane); + // Where the area lies on the map's projection, which shapes the page and the veil: the rectangle + // given, or the box around `extent` there. The frame is fitted to `rectangle` where there is + // one, else to `extent`; the graticule and the north arrow always go by `extent`. + let plane = rectangle.unwrap_or_else(|| projected_extent(s, &extent)); let one = |k: &str| texts_of(p, k).map(|t| t.map(|t| t.join(" ")).filter(|t| !t.trim().is_empty())); let (title, subtitle, note) = (one("title")?, one("subtitle")?, one("note")?); let sources = texts_of(p, "sources")?.unwrap_or_default(); @@ -171,7 +180,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu // No orientation asked: the one the area's map comes out larger on, from its extents east to // west and north to south on the map's projection and the room the style leaves the map. let profile = match &auto { - Some(size) if aspect(s, &extent).is_some_and(|a| landscape_suits(a, page_w.min(page_h), page_w.max(page_h), style)) => { + Some(size) if aspect(&plane).is_some_and(|a| landscape_suits(a, page_w.min(page_h), page_w.max(page_h), style)) => { let id = format!("{size}-landscape"); PUBLICATION_PROFILES.iter().find(|pr| pr.id == id).unwrap_or(profile) } @@ -951,7 +960,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let fh = if page_h > 0.0 { page_h - note_h } else { - let shape = aspect(s, &extent).unwrap_or_else(|| { + let shape = aspect(&plane).unwrap_or_else(|| { warnings.push("the extent's shape on the map's projection isn't known: the figure is 4 wide by 3 tall".into()); 0.75 }); @@ -983,7 +992,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu if passes == 0 { // The frame's height for the area at its width, with a seventh more of its surroundings. let area = (sheet && matches!(style, Style::Panel | Style::Editorial)) - .then(|| aspect(s, &extent)) + .then(|| aspect(&plane)) .flatten() .map(|a| (((lw - 2.0 * room_side).max(1.0) * a + 2.0 * room_end) * 1.15).max(40.0 * k)); // The least a sheet is cut to, with 1·k to spare (a pass may land 0.5 mm short): its @@ -1010,7 +1019,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu // The height the frame must grow to for its legend: none when the column holds it. let short = laid.3.filter(|_| legend.is_some() || colorbar).and_then(|c| { let inner = inner_frame((lw, lh), (room_side, room_end)); - let (center, scale) = fit_frame(s.map(), &extent, whole_globe, inner)?; + let (center, scale) = fit_frame(s.map(), &extent, rectangle.as_ref(), whole_globe, inner)?; // Read on a copy: the session's map is only changed after the last refusal. let mut map = s.map().clone(); let at = crate::render::layout::frame_render_scale(&map, center, scale); @@ -1060,8 +1069,8 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu warnings.push("the frame is too small to keep its grid's labels off the map's edges: they may cover them".into()); } let (inner_w, inner_h) = inner_frame((fw, fh), (room_side, room_end)); - let (center, scale) = - fit_frame(s.map(), &extent, whole_globe, (inner_w, inner_h)).ok_or("the extent can't be drawn on the map's projection")?; + let (center, scale) = fit_frame(s.map(), &extent, rectangle.as_ref(), whole_globe, (inner_w, inner_h)) + .ok_or("the extent can't be drawn on the map's projection")?; if whole_globe && center != s.map().center_lonlat() { warnings.push(format!( "the globe is centred at {:.1}° rather than the view's {:.1}° of latitude: nearer the pole, the frame can't draw it small enough to fit", @@ -1453,13 +1462,12 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu if let Some(known) = sizes.filter(|_| column.is_none() && content_h > 0.0) { let need = |room: (f64, f64)| known.iter().position(|size| whole(*size).0 <= room.0 && whole(*size).1 <= room.1); let flat = s.map().flat(); - let asked = projected_extent(s, &extent); - let at = flat.forward_checked(center).filter(|_| !asked.is_empty()); + let at = flat.forward_checked(center).filter(|_| !plane.is_empty()); if let Some(at) = at.filter(|_| coverage.as_ref().is_some_and(|c| need(free_room(c)).is_none())) { let (centred, asked_scale) = (center, scale); let continuous = coverage.as_ref().is_some_and(|(gw, gh, cells)| { - let mm = 1000.0 * flat.ground_per_unit(asked.center()) * s.map().body().ratio() / asked_scale; - let (half_w, half_h) = (asked.width() * mm / 2.0, asked.height() * mm / 2.0); + let mm = 1000.0 * flat.ground_per_unit(plane.center()) * s.map().body().ratio() / asked_scale; + let (half_w, half_h) = (plane.width() * mm / 2.0, plane.height() * mm / 2.0); let (gw, gh) = (*gw as usize, *gh as usize); let (mut inside, mut inside_drawn, mut outside, mut outside_drawn) = (0usize, 0usize, 0usize, 0usize); for (i, drawn) in cells.iter().enumerate() { @@ -1497,10 +1505,10 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu // A figure keeps its scale: its size is fixed, and a smaller scale costs it the most. for (factor, veil) in passes.into_iter().filter(|(factor, veil)| (!*veil || continuous) && (*factor == 1.0 || sheet)) { let tried = if factor == 1.0 { asked_scale } else { round_scale(asked_scale * factor) }; - let mm = 1000.0 * flat.ground_per_unit(asked.center()) * s.map().body().ratio() / tried; + let mm = 1000.0 * flat.ground_per_unit(plane.center()) * s.map().body().ratio() / tried; // How far the extent, centred, can go each way and stay inside that side's margin // (a figure labels only its left and bottom edges, so they differ). - let (half_w, half_h) = (asked.width() * mm / 2.0, asked.height() * mm / 2.0); + let (half_w, half_h) = (plane.width() * mm / 2.0, plane.height() * mm / 2.0); let to = |margin: f64, half_frame: f64, half_extent: f64| (half_frame - margin - half_extent).max(0.0); let (to_left, to_right) = (to(left, fw / 2.0, half_w), to(right, fw / 2.0, half_w)); let (to_top, to_bottom) = (to(top, fh / 2.0, half_h), to(bottom, fh / 2.0, half_h)); @@ -1595,12 +1603,12 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu // its middle while that scale moves a corner of it one cell of the coverage grid // at most, which the cut is exact to anyway; past that, it is drawn on its own // (what is context then judged on itself, for the legend too), once. - let here_mm = mm * flat.ground_per_unit(Coord::new(cx, cy)) / flat.ground_per_unit(asked.center()); + let here_mm = mm * flat.ground_per_unit(Coord::new(cx, cy)) / flat.ground_per_unit(plane.center()); let clip = ( - fx + fw / 2.0 + (asked.min_x - cx) * here_mm, - fy + fh / 2.0 - (asked.max_y - cy) * here_mm, - asked.width() * here_mm, - asked.height() * here_mm, + fx + fw / 2.0 + (plane.min_x - cx) * here_mm, + fy + fh / 2.0 - (plane.max_y - cy) * here_mm, + plane.width() * here_mm, + plane.height() * here_mm, ); let kept_whole = clip.0 >= fx + left - 0.5 && clip.1 >= fy + top - 0.5 @@ -2254,10 +2262,21 @@ fn has_color_scale(l: &rustgis_map::Layer) -> bool { } /// The centre and scale of a frame of `map` with `inner` mm (width, height) inside its grid's label -/// strips: `extent` fitted in it, or the whole globe filling it, centred where the view looks. -fn fit_frame(map: &rustgis_map::Map, extent: &Extent, whole_globe: bool, (w, h): (f64, f64)) -> Option<(Coord, f64)> { +/// strips: `rectangle` (in the map's coordinates) or else `extent` fitted in it, or the whole globe +/// filling it, centred where the view looks. +fn fit_frame( + map: &rustgis_map::Map, + extent: &Extent, + rectangle: Option<&Extent>, + whole_globe: bool, + (w, h): (f64, f64), +) -> Option<(Coord, f64)> { if !whole_globe { - return fit_scale(map, extent, w, h).map(|(center, scale)| (center, round_scale(scale))); + let fitted = match rectangle { + Some(plane) => rustgis_map::layout::fit_scale_plane(map, plane, w, h), + None => fit_scale(map, extent, w, h), + }; + return fitted.map(|(center, scale)| (center, round_scale(scale))); } // The globe seen whole fills the frame, centred where the view looks (#2337): fitting the // whole Earth's flat footprint instead drew it a fraction of the frame, around 0°, 0°. diff --git a/crates/engine/src/cmd/layout/publication/texts.rs b/crates/engine/src/cmd/layout/publication/texts.rs index 44202c03bd..aa12c1b5cc 100644 --- a/crates/engine/src/cmd/layout/publication/texts.rs +++ b/crates/engine/src/cmd/layout/publication/texts.rs @@ -118,9 +118,8 @@ pub(in crate::cmd::layout) fn texts_of(p: &Value, k: &str) -> Result Option { - let ext = projected_extent(s, e); +/// The height over the width of an area's rectangle in the map's coordinates. +pub(in crate::cmd::layout) fn aspect(ext: &Extent) -> Option { (ext.width() > 0.0 && ext.height() > 0.0).then(|| ext.height() / ext.width()) } diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs index 527519d673..e576f3cdc2 100644 --- a/crates/engine/src/cmd/workspace.rs +++ b/crates/engine/src/cmd/workspace.rs @@ -500,19 +500,22 @@ pub fn view_extent(s: &Session) -> Extent { /// The longitude/latitude extent a `size` view of map `m` shows. pub fn view_extent_of(m: &rustgis_map::Map, (w, h): (f64, f64)) -> Extent { - let e = m.camera.extent(w, h); let mut ll = Extent::EMPTY; - for i in 0..=8 { - for j in 0..=8 { - let c = Coord::new(e.min_x + e.width() * i as f64 / 8.0, e.min_y + e.height() * j as f64 / 8.0); - if let Some(x) = m.to_lonlat(c) { - ll.expand(x); - } - } + for c in places_in(m, m.camera.extent(w, h), 8) { + ll.expand(c); } ll } +/// The longitude/latitude of the points of a grid `steps` cells a side over `e`, a rectangle in map +/// `m`'s coordinates; those with no place on the Earth are left out. +pub(crate) fn places_in(m: &rustgis_map::Map, e: Extent, steps: u32) -> impl Iterator + '_ { + let at = move |min: f64, side: f64, i: u32| min + side * f64::from(i) / f64::from(steps); + (0..=steps) + .flat_map(move |i| (0..=steps).map(move |j| Coord::new(at(e.min_x, e.width(), i), at(e.min_y, e.height(), j)))) + .filter_map(move |c| m.to_lonlat(c)) +} + /// Connects active-map rendering to the common layer and raw tile route bindings. fn map_render_inputs(input: &super::InputContext<'_>, _: &Value) -> Result { Ok(super::tiles::render_inputs(input.map())) diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 3166835486..bdf8268a48 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -142,6 +142,7 @@ pub const CAPABILITIES: &[&str] = &[ "shaded-relief-aerial", "shaded-relief-terrain-type", "shaded-relief-flats", + "layout-publication-crs", ]; /// An offline area keeping the versions that lost a sync or a Bring Back /// (`OfflineArea::conflicts`, #2468): an older reader would save it again without them. diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 9bc2d6926b..09c5758e9f 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -192,6 +192,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("shaded-relief-aerial", command_sets_aerial), ("shaded-relief-terrain-type", command_sets_terrain_type), ("shaded-relief-flats", command_sets_flats), + ("layout-publication-crs", command_gives_publication_crs), ]; /// A saved `raster.symbology` that sets a Shaded Relief's detail on flat ground (#3143): an older @@ -240,6 +241,16 @@ fn command_sets_publication_legend(id: &str, params: &Value) -> bool { } } +/// A saved `layout.publication` that gives its extent in the map's system (`crs`, #3322): an older +/// reader ignores `crs` and reads the extent as degrees. +fn command_gives_publication_crs(id: &str, params: &Value) -> bool { + match id { + "layout.publication" => params.get("crs").is_some_and(|v| !v.is_null()), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_gives_publication_crs)), + _ => false, + } +} + /// A saved `raster.symbology` that sets a Shaded Relief's shadow softness (#3144): an older reader /// runs it without the key, saying nothing, so the shadows would be traced at the default disc. /// Read as the command reads it (its type, and a numeric string is its number): `null` and the @@ -1823,6 +1834,7 @@ mod tests { (&["layout-text-statistics"], "layout.addElement", json!({"kind": "text", "text": "{count:Cities}"})), (&["layout-publication-parts"], "layout.publication", json!({"grid": "none"})), (&["layout-publication-legend"], "layout.publication", json!({"legend": "none"})), + (&["layout-publication-crs"], "layout.publication", json!({"crs": "EPSG:3857"})), (&["shaded-relief-shadow-softness"], "raster.symbology", json!({"type": "shadedRelief", "shadowSoftness": 1.5})), // `null` is the default an older reader draws. (&[], "raster.symbology", json!({"type": "shadedRelief", "shadowSoftness": null})), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1734141af9..bf1416c0be 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -163,6 +163,9 @@ mod layout_report_text; #[path = "tests/layout_publication_locators.rs"] mod layout_publication_locators; +#[path = "tests/layout_publication_crs.rs"] +mod layout_publication_crs; + #[path = "tests/sde_connections.rs"] mod sde_connections; diff --git a/crates/engine/src/tests/layout_publication_crs.rs b/crates/engine/src/tests/layout_publication_crs.rs new file mode 100644 index 0000000000..e45d0aa0de --- /dev/null +++ b/crates/engine/src/tests/layout_publication_crs.rs @@ -0,0 +1,271 @@ +//! `layout.publication`'s `extent` in the map's coordinate system (`crs`, #3322): the rectangle +//! itself is framed, not the longitude/latitude box around it. + +use super::*; +use rustgis_geom::Coord; +use rustgis_map::layout::{ElementKind, Layout}; + +const NO_SYSTEM: &str = "the map has no flat system of its own here"; +const BAD_EXTENT: &str = "extent is [west, south, east, north] in the map's coordinates with crs"; +const UTM33: [f64; 4] = [500_000.0, 5_000_000.0, 600_000.0, 5_100_000.0]; + +fn on(projection: &str) -> Session { + let mut s = world(); + s.run("map.projection", &json!({"type": projection})).unwrap(); + s +} + +/// The result and the layout of a publication of `extent`, `extra`'s parameters over these. +fn publish(s: &mut Session, extent: [f64; 4], extra: Value) -> Result<(Value, Layout), String> { + let mut p = json!({"profile": "a4-portrait", "extent": extent}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let r = s.run("layout.publication", &p)?; + Ok((r, s.project.layouts.last().unwrap().clone())) +} + +fn in_map(s: &mut Session, extent: [f64; 4], crs: &str) -> Result<(Value, Layout), String> { + publish(s, extent, json!({"crs": crs})) +} + +fn frame(l: &Layout) -> (Coord, f64) { + l.elements + .iter() + .find_map(|e| match &e.kind { + ElementKind::MapFrame { center, scale, .. } if e.name == "Map Frame" => Some((*center, *scale)), + _ => None, + }) + .expect("the map frame") +} + +fn has_arrow(l: &Layout) -> bool { + l.elements.iter().any(|e| matches!(e.kind, ElementKind::NorthArrow { .. })) +} + +/// The longitude/latitude box around the corners and edges of a rectangle in the map's system. +fn box_around(s: &Session, [w, so, e, n]: [f64; 4]) -> [f64; 4] { + let mut ll = rustgis_geom::Extent::EMPTY; + for i in 0..=8 { + let t = f64::from(i) / 8.0; + let (x, y) = (w + (e - w) * t, so + (n - so) * t); + for c in [Coord::new(x, so), Coord::new(x, n), Coord::new(w, y), Coord::new(e, y)] { + ll.expand(s.map().to_lonlat(c).unwrap()); + } + } + [ll.min_x, ll.min_y, ll.max_x, ll.max_y] +} + +fn centred_on(s: &Session, l: &Layout, [w, so, e, n]: [f64; 4]) { + let want = s.map().to_lonlat(Coord::new((w + e) / 2.0, (so + n) / 2.0)).unwrap(); + let got = frame(l).0; + assert!((got.x - want.x).abs() < 1e-7 && (got.y - want.y).abs() < 1e-7, "{got:?} is not {want:?}"); +} + +#[test] +fn a_rectangle_in_the_maps_system_is_framed_itself() { + let mut s = on("EPSG:32633"); + let (_, l) = in_map(&mut s, UTM33, "EPSG:32633").unwrap(); + centred_on(&s, &l, UTM33); +} + +/// Far from the central meridian the longitude/latitude box around a rectangle projects larger. +#[test] +fn the_box_in_degrees_around_a_rectangle_frames_more() { + let rect = [900_000.0, 7_000_000.0, 1_500_000.0, 7_600_000.0]; + let mut s = on("EPSG:32633"); + let around = box_around(&s, rect); + let (_, exact) = in_map(&mut s, rect, "EPSG:32633").unwrap(); + let (_, boxed) = publish(&mut s, around, json!({})).unwrap(); + assert!(frame(&boxed).1 > frame(&exact).1, "{} is not larger than {}", frame(&boxed).1, frame(&exact).1); +} + +/// On Web Mercator the box in degrees is the rectangle, so the two ways give the same sheet. +#[test] +fn on_web_mercator_metres_and_degrees_lay_out_the_same_sheet() { + let degrees = [-46.8, -30.0, -38.5, -2.2]; + let a = rustgis_geom::lonlat_to_merc(Coord::new(degrees[0], degrees[1])); + let b = rustgis_geom::lonlat_to_merc(Coord::new(degrees[2], degrees[3])); + let metres = [a.x, a.y, b.x, b.y]; + for extra in [json!({}), json!({"profile": "a4"}), json!({"profile": "figure-1col"}), json!({"style": "panel"})] { + let mut s = world(); + let (_, l) = publish(&mut s, degrees, extra.clone()).unwrap(); + let mut with = extra.clone(); + with["crs"] = json!("EPSG:3857"); + let (_, m) = publish(&mut s, metres, with).unwrap(); + let boxes = |l: &Layout| l.elements.iter().map(|e| (e.name.clone(), e.x, e.y, e.w, e.h)).collect::>(); + assert_eq!(boxes(&l), boxes(&m), "{extra}"); + let ((c, sc), (d, sd)) = (frame(&l), frame(&m)); + assert!((c.x - d.x).abs() < 1e-7 && (c.y - d.y).abs() < 1e-7 && sc == sd, "{extra}: {c:?} {sc} {d:?} {sd}"); + } +} + +#[test] +fn an_extent_in_another_system_is_refused() { + let mismatch = "extent is in EPSG:32634, but the map is in EPSG:32633: give it in the map's system, or in degrees without crs"; + let mut s = on("EPSG:32633"); + assert_eq!(in_map(&mut s, UTM33, "EPSG:32634").unwrap_err(), mismatch); + for projection in ["globe", "robinson"] { + let mut s = on(projection); + let err = in_map(&mut s, UTM33, "EPSG:32633").unwrap_err(); + assert!(err.starts_with(NO_SYSTEM), "{projection}: {err}"); + assert!(s.project.layouts.is_empty(), "{projection}"); + } +} + +#[test] +fn a_crs_that_is_no_system_or_has_no_extent_is_refused() { + let mut s = on("EPSG:32633"); + let parsed = |text: &str| rustgis_data::raster::Crs::parse(text).unwrap_err(); + for (crs, said) in [ + (json!(""), parsed("")), + (json!("not a system"), parsed("not a system")), + (json!(true), "crs is an EPSG code such as 32613 or \"EPSG:32613\"".to_string()), + (json!(999_999), "unknown coordinate system EPSG:999999".to_string()), + ] { + assert_eq!(publish(&mut s, UTM33, json!({"crs": crs})).unwrap_err(), said, "{crs}"); + } + assert_eq!(s.run("layout.publication", &json!({"crs": "EPSG:32633"})).unwrap_err(), "crs goes with extent"); + for extent in [ + json!([600_000, 0, 500_000, 1]), + json!([0, 1, 1, 1]), + json!([0, 0, 1]), + json!([0, 0, 1, "1"]), + json!("view"), + json!([-1e308, 0, 1e308, 1]), + ] { + let err = s.run("layout.publication", &json!({"crs": "EPSG:32633", "extent": extent})).unwrap_err(); + assert_eq!(err, BAD_EXTENT, "{extent}"); + } + assert!(s.project.layouts.is_empty()); +} + +#[test] +fn a_rectangle_off_the_earth_is_refused() { + let mut s = on("EPSG:3035"); + let nowhere = in_map(&mut s, [1e9, 1e9, 2e9, 2e9], "EPSG:3035").unwrap_err(); + assert_eq!(nowhere, "the extent names no place on the map"); + let off_centre = in_map(&mut s, [3_300_000.0, 2_200_000.0, 1e9, 4_200_000.0], "EPSG:3035").unwrap_err(); + assert_eq!(off_centre, "the extent's centre has no place on the map"); + assert!(s.project.layouts.is_empty()); +} + +/// Its edges are all off the Earth: the places inside still say what it covers. +#[test] +fn a_rectangle_around_the_whole_projection_is_framed() { + let all = [-15_679_000.0, -16_790_000.0, 24_321_000.0, 23_210_000.0]; + let mut s = on("EPSG:3035"); + let (_, l) = in_map(&mut s, all, "EPSG:3035").unwrap(); + centred_on(&s, &l, all); +} + +#[test] +fn the_graticule_and_the_north_arrow_follow_the_rectangles_size() { + let mut s = on("EPSG:32633"); + let around = box_around(&s, UTM33); + let (exact, l) = in_map(&mut s, UTM33, "EPSG:32633").unwrap(); + let (boxed, _) = publish(&mut s, around, json!({})).unwrap(); + assert_eq!(exact["grid"], boxed["grid"]); + assert!(has_arrow(&l)); + // 100 km is about 1.3°, ten times that about 13°: the step is each one's own. + let (wide, _) = in_map(&mut s, [0.0, 4_500_000.0, 1_000_000.0, 5_500_000.0], "EPSG:32633").unwrap(); + assert_eq!((exact["grid"].as_f64(), wide["grid"].as_f64()), (Some(0.5), Some(5.0))); +} + +/// A rectangle over ±180° is as wide as it looks, not the whole world round. +#[test] +fn a_rectangle_over_the_antimeridian_keeps_its_size() { + let rect = [100_000.0, 0.0, 300_000.0, 200_000.0]; + let mut s = on("EPSG:32601"); + let west = s.map().to_lonlat(Coord::new(rect[0], rect[1])).unwrap().x; + let east = s.map().to_lonlat(Coord::new(rect[2], rect[1])).unwrap().x; + assert!(west > 0.0 && east < 0.0, "it crosses: {west} {east}"); + let (r, l) = in_map(&mut s, rect, "EPSG:32601").unwrap(); + assert!(r["grid"].as_f64().unwrap() <= 0.5, "{}", r["grid"]); + assert!(has_arrow(&l)); + centred_on(&s, &l, rect); +} + +/// Web Mercator draws its poles at 85°, so a rectangle there is around none. +#[test] +fn a_web_mercator_rectangle_is_around_no_pole() { + let mut s = world(); + let (r, _) = in_map(&mut s, [-5_000_000.0, 19_000_000.0, 5_000_000.0, 20_100_000.0], "EPSG:3857").unwrap(); + assert_eq!(r["grid"].as_f64(), Some(30.0)); +} + +/// A frame centred past 85° on Web Mercator would be drawn at 85°, away from the rectangle. +#[test] +fn a_rectangle_a_frame_cant_be_centred_on_is_refused() { + let mut s = world(); + let err = in_map(&mut s, [-5_000.0, 21_000_000.0, 5_000.0, 21_010_000.0], "EPSG:3857").unwrap_err(); + assert_eq!(err, "the extent's centre has no place on the map"); + assert!(s.project.layouts.is_empty()); +} + +/// Past two Earth circumferences the frame's scale would be cut and the rectangle missed. +#[test] +fn a_rectangle_too_large_to_frame_is_refused() { + let utm = [-1e9, -1e9, 1.0005e9, 1.01e9]; + let cases = [ + ("mercator", "EPSG:3857", [-1e10, -1e6, 1e10, 1e6]), + ("mercator", "EPSG:3857", [-5e307, 0.0, 5e307, 1.0]), + ("mercator", "EPSG:3857", [-8.9e307, -1.0, 8.9e307, 1.0]), + ("EPSG:32633", "EPSG:32633", utm), + ]; + for (projection, crs, rect) in cases { + let mut s = on(projection); + let err = in_map(&mut s, rect, crs).unwrap_err(); + assert_eq!(err, "the extent is too large to frame: more than twice the Earth's circumference across", "{rect:?}"); + assert!(s.project.layouts.is_empty(), "{rect:?}"); + } +} + +/// Too small for a height in degrees, still a rectangle: framed at the smallest the page shows. +#[test] +fn a_tiny_rectangle_is_framed() { + let mut s = world(); + in_map(&mut s, [0.0, 0.0, 1e-12, 1e-12], "EPSG:3857").unwrap(); +} + +/// Around a pole the width in longitude says nothing: the size is twice the way to the pole. +#[test] +fn a_rectangle_around_the_pole_takes_its_size_from_the_latitude() { + let mut s = on("EPSG:3031"); + let (small, l) = in_map(&mut s, [-400_000.0, -400_000.0, 400_000.0, 400_000.0], "EPSG:3031").unwrap(); + assert!(small["grid"].as_f64().unwrap() <= 5.0, "{}", small["grid"]); + assert!(has_arrow(&l)); + let (large, l) = in_map(&mut s, [-1_100_000.0, -1_100_000.0, 1_100_000.0, 1_100_000.0], "EPSG:3031").unwrap(); + assert_eq!(large["grid"].as_f64().unwrap(), 10.0); + assert!(!has_arrow(&l), "north turns all the way round the frame"); +} + +#[test] +fn the_sheet_turns_to_the_rectangles_shape() { + for (rect, tall) in + [([400_000.0, 5_000_000.0, 500_000.0, 5_300_000.0], true), ([400_000.0, 5_000_000.0, 700_000.0, 5_100_000.0], false)] + { + let mut s = on("EPSG:32633"); + let (_, l) = publish(&mut s, rect, json!({"profile": "a4", "crs": "EPSG:32633"})).unwrap(); + assert_eq!(l.height > l.width, tall, "{rect:?}: {}×{}", l.width, l.height); + let (_, figure) = publish(&mut s, rect, json!({"profile": "figure-1col", "crs": "EPSG:32633"})).unwrap(); + assert_eq!(figure.height > figure.width, tall, "{rect:?}: {}×{}", figure.width, figure.height); + } +} + +#[test] +fn a_saved_publication_with_a_crs_requires_its_capability() { + let requires = |crs: Value| { + let mut s = world(); + let step = json!({"tool": "layout.publication", "params": {"extent": [0, 0, 1, 1], "crs": crs}}); + s.project.models.push(serde_json::from_value(json!({"name": "Sheet", "steps": [step]})).unwrap()); + serde_json::to_value(&s.project).unwrap()["requires"].to_string().contains("layout-publication-crs") + }; + assert!(requires(json!("EPSG:32633"))); + assert!(requires(json!(32633))); + assert!(!requires(Value::Null)); +} + +#[test] +fn the_publication_crs_fixture_opens_and_keeps_its_requirement() { + let fixture = crate::Project::from_json(include_str!("../../../../schema/fixtures/layout_publication_crs.rgis")).unwrap(); + assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["layout-publication-crs"])); +} diff --git a/crates/map/src/layout/frame.rs b/crates/map/src/layout/frame.rs index 4aea6bfa5a..ba2023a1b0 100644 --- a/crates/map/src/layout/frame.rs +++ b/crates/map/src/layout/frame.rs @@ -126,9 +126,15 @@ pub fn fit_scale(map: &Map, e: &rustgis_geom::Extent, w_mm: f64, h_mm: f64) -> O ext.expand(p); } } - if ext.is_empty() { + fit_scale_plane(map, &ext, w_mm, h_mm) +} + +/// [`fit_scale`] for a rectangle in the map's own coordinates (the flat projection's). +pub fn fit_scale_plane(map: &Map, ext: &rustgis_geom::Extent, w_mm: f64, h_mm: f64) -> Option<(Coord, f64)> { + if ext.is_empty() || w_mm <= 0.0 || h_mm <= 0.0 { return None; } + let flat = map.flat(); let center = flat.inverse(ext.center())?; let per = (flat.ground_per_unit(ext.center()) * map.body().ratio()).max(1e-9); // A lone point gets a metre around it; anything larger fits as it is, down to a find a diff --git a/docs/maintaining.md b/docs/maintaining.md index 866119bc7b..e62a95aefe 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -417,6 +417,10 @@ object that gives something, #3095) requires `layout-publication-legend`, so an refuses it instead of making the default legend. `null`, a `legend` of `{}`, a blank `title` and an empty `exclude` need nothing. +A saved `layout.publication` that gives its extent in the map's coordinate system (`crs`, #3322) +requires `layout-publication-crs`, so an older reader refuses it instead of reading the extent as +degrees. A `crs` of `null` needs nothing. + ## New dependencies A proposal for a dependency answers: diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index b46d0b27df..280d6587e9 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -90,7 +90,12 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu - **The map**: the `extent` given (or the view) fitted north-up, without tilt, at a round scale, two significant figures, rounded up so it still fits within the strips the graticule's labels take inside the frame. A graticule's step follows the extent (2° for a state, 15′ for a city), - with labels on every edge of a sheet. + with labels on every edge of a sheet. With `crs`, the map's own coordinate system + (`"crs": "EPSG:32633"` on a map in it), `extent` is a rectangle in that system's units, and the + frame fits the rectangle itself rather than the box in degrees around it, which is larger where + the projection curves. Any other system is refused, as are the globe, world projections other + than Web Mercator, local views, another body's map and a rectangle more than twice the Earth's + circumference across. The north arrow, the legend (sized to what it lists), the scale bar with the numeric scale under it (in a box the size of the bar) and the locator sit in the frame's corners, clear of the graticule's labels. The **arrangement** says which corner is each one's. `classic` (the default favourite) puts the diff --git a/schema/fixtures/layout_publication_crs.rgis b/schema/fixtures/layout_publication_crs.rgis new file mode 100644 index 0000000000..cfd73c0dbc --- /dev/null +++ b/schema/fixtures/layout_publication_crs.rgis @@ -0,0 +1 @@ +{"format":2,"name":"Publication crs","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,"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":[{"name":"Sheet in metres","steps":[{"tool":"layout.publication","params":{"extent":[1000000,5000000,1200000,5100000],"crs":"EPSG:3857"}}]}],"workspaces":[],"link_views":false,"jobs":[],"offline_areas":[],"reports":[],"presentations":[],"notebooks":[],"dl_models":[],"shared":[],"data_stores":[],"requires":["layout-publication-crs"]} diff --git a/schema/project.schema.json b/schema/project.schema.json index 681fa14e11..46f707264f 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1302,7 +1302,8 @@ "shaded-relief-shadow-softness", "shaded-relief-aerial", "shaded-relief-terrain-type", - "shaded-relief-flats" + "shaded-relief-flats", + "layout-publication-crs" ], "type": "string" }, @@ -1433,7 +1434,8 @@ "shaded-relief-shadow-softness", "shaded-relief-aerial", "shaded-relief-terrain-type", - "shaded-relief-flats" + "shaded-relief-flats", + "layout-publication-crs" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2