Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/imagery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<Crs>, String> {
pub(crate) fn crs_param(s: &mut Session, p: &Value, key: &str) -> Result<Option<Crs>, String> {
let (crs, warning) = crs_param_read(p, key)?;
if let Some(w) = warning {
s.warn(w);
Expand Down
3 changes: 2 additions & 1 deletion crates/engine/src/cmd/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ pub fn commands() -> Vec<C> {
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, "#,
Expand Down
81 changes: 81 additions & 0 deletions crates/engine/src/cmd/layout/publication/area.rs
Original file line number Diff line number Diff line change
@@ -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> {
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
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<Coord> = crate::cmd::workspace::places_in(map, plane, GRID).collect();
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
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<f64> = extent.as_array()?.iter().map(|x| x.as_f64().filter(|x| x.is_finite())).collect::<Option<_>>()?;
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
}
91 changes: 55 additions & 36 deletions crates/engine/src/cmd/layout/publication/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

use super::*;

mod area;
use area::*;
mod arrangement;
pub use arrangement::*;
mod coverage;
Expand Down Expand Up @@ -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<Vec<f64>> =
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();
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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
});
Expand Down Expand Up @@ -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
Expand All @@ -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);
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
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°.
Expand Down
5 changes: 2 additions & 3 deletions crates/engine/src/cmd/layout/publication/texts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,8 @@ pub(in crate::cmd::layout) fn texts_of(p: &Value, k: &str) -> Result<Option<Vec<
}
}

/// The extent's height over its width on the active map's projection, along its edges.
pub(in crate::cmd::layout) fn aspect(s: &Session, e: &Extent) -> Option<f64> {
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<f64> {
(ext.width() > 0.0 && ext.height() > 0.0).then(|| ext.height() / ext.width())
}

Expand Down
Loading
Loading