From 9b56f3cfa6c0e03012c9bc014bee88643a57a20f Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 28 Nov 2026 14:47:35 -0300 Subject: [PATCH] feat(layout): raster profiles beside a map frame (#2863 part 2) A Profile element draws, beside a map frame, a raster's profile along one of the frame's section lines: under or over it for a horizontal line, right or left of it for a vertical one. Each sample is read at its point of the line on the page, taken back through the frame's projection, so the curve is straight across from the place it comes from. Its box is the frame's side, which it follows when the frame is moved or resized; dragged or resized, it changes its gap and thickness. It reads any band of a raster held whole, bilinearly, a sample a cell up to 10,000 (Raster::bilinear, moved into rustgis-data from analysis' elevation_at, which now calls it), and draws a line filled under it or not, a value axis (round or given min and max), a distance axis along the ground, guides, a unit, a title and the section's names. One that can't be drawn (a tilted or globe frame, a raster read in place, a band it lacks, no data) draws its placeholder and says why, in its commands, the layout view, exports and reports. A layout with one requires layout-profile. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/rasterops.rs | 16 +- crates/data/src/raster/mod.rs | 19 + crates/engine/command-surface.txt | 4 +- crates/engine/src/cmd/layer.rs | 10 +- crates/engine/src/cmd/layout.rs | 39 +- crates/engine/src/cmd/layout/elements.rs | 6 + crates/engine/src/cmd/layout/export.rs | 22 ++ crates/engine/src/cmd/layout/inputs.rs | 18 + crates/engine/src/cmd/layout/profile.rs | 327 ++++++++++++++++ crates/engine/src/cmd/layout/update.rs | 14 + crates/engine/src/cmd/report.rs | 24 ++ crates/engine/src/project.rs | 1 + crates/engine/src/project_capabilities.rs | 23 ++ crates/engine/src/tests.rs | 2 + crates/engine/src/tests/layout_files.rs | 1 + crates/engine/src/tests/layout_profiles.rs | 191 ++++++++++ crates/map/src/layout.rs | 38 ++ crates/map/src/layout/elements.rs | 36 +- crates/map/src/layout/profile.rs | 228 +++++++++++ crates/map/src/layout/tests.rs | 91 +++++ crates/render/src/layout.rs | 6 + crates/render/src/layout/profile.rs | 423 +++++++++++++++++++++ crates/render/src/layout/profile_tests.rs | 254 +++++++++++++ crates/ui-egui/src/icons.rs | 18 + crates/ui-egui/src/layoutview.rs | 16 + crates/ui-egui/src/ribbon.rs | 6 + docs/maintaining.md | 7 + docs/user-guide/layouts.md | 25 ++ schema/fixtures/layout_profile.rgis | 27 ++ schema/project.schema.json | 2 + 30 files changed, 1858 insertions(+), 36 deletions(-) create mode 100644 crates/engine/src/cmd/layout/profile.rs create mode 100644 crates/engine/src/tests/layout_profiles.rs create mode 100644 crates/map/src/layout/profile.rs create mode 100644 crates/render/src/layout/profile.rs create mode 100644 crates/render/src/layout/profile_tests.rs create mode 100644 schema/fixtures/layout_profile.rgis diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index bff3ab6e21..b12955ba3b 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -611,21 +611,9 @@ fn dist_m(a: Coord, b: Coord) -> f64 { rustgis_geom::haversine_m(a, b) } -/// Elevation (bilinear) at a longitude/latitude point. +/// Elevation (bilinear) at a longitude/latitude point ([`Raster::bilinear`]). pub fn elevation_at(r: &Raster, b: usize, ll: Coord) -> Option { - let w = r.transformer().from_lonlat(ll)?; - let (x, y) = r.transform.to_pixel(w); - let (x, y) = (x - 0.5, y - 0.5); - let (c0, r0) = (x.floor() as i64, y.floor() as i64); - let (fx, fy) = (x - c0 as f64, y - r0 as f64); - let v = |c: i64, rr: i64| r.value(b, c, rr).map(f64::from); - let (a, b2, c, d) = (v(c0, r0), v(c0 + 1, r0), v(c0, r0 + 1), v(c0 + 1, r0 + 1)); - match (a, b2, c, d) { - (Some(a), Some(b2), Some(c), Some(d)) => { - Some(a * (1.0 - fx) * (1.0 - fy) + b2 * fx * (1.0 - fy) + c * (1.0 - fx) * fy + d * fx * fy) - } - _ => v(x.round() as i64, y.round() as i64), - } + r.bilinear(b, ll) } /// An elevation profile along a path: (distance from the start in metres, point, elevation). diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 435eab9865..9821418973 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -1350,6 +1350,25 @@ impl Raster { if wrapped < w { wrapped } else { c } } + /// The value of `band` at a longitude/latitude point, read bilinearly between the four cell + /// centres around it, in the raster's own system: the nearest cell's where one of the four is + /// no-data or off the grid, and `None` where that one is too. The elevation profiles read + /// this (`profile.*`, and a layout's profiles beside a map frame, #2863). + pub fn bilinear(&self, band: usize, lonlat: Coord) -> Option { + let w = self.transformer.from_lonlat(lonlat)?; + let (x, y) = self.transform.to_pixel(w); + let (x, y) = (x - 0.5, y - 0.5); + let (c0, r0) = (x.floor() as i64, y.floor() as i64); + let (fx, fy) = (x - c0 as f64, y - r0 as f64); + let v = |c: i64, r: i64| self.value(band, c, r).map(f64::from); + match (v(c0, r0), v(c0 + 1, r0), v(c0, r0 + 1), v(c0 + 1, r0 + 1)) { + (Some(a), Some(b), Some(c), Some(d)) => { + Some(a * (1.0 - fx) * (1.0 - fy) + b * fx * (1.0 - fy) + c * (1.0 - fx) * fy + d * fx * fy) + } + _ => v(x.round() as i64, y.round() as i64), + } + } + /// Cell size in the raster's units (x, y). pub fn cell_size(&self) -> (f64, f64) { (self.transform.pixel_width.abs(), self.transform.pixel_height.abs()) diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 0854ed4f51..49cfd91df8 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -282,7 +282,7 @@ layer.transparency layer? value layer.visibility layer? visible? layer.zoomTo layer? layout.activate name layout -layout.addElement layout? kind frame? of? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? allClasses? hideOther? showNoData? exclude? columns? textSize? classLabels? showLayerNames? orientation? ticks? tickSide? reverse? fill? width? radius? dash? dir? head? angle? length? image? path? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? hideLabels? barOutline? rows? step? type? crs? short? mgrs? labels? style? tickLength? format? hemisphere? edges? labelOrientation? labelSize? off? name? direction? at? outline? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? x? y? w? h? background? +layout.addElement layout? kind frame? of? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? allClasses? hideOther? showNoData? exclude? columns? textSize? classLabels? showLayerNames? orientation? ticks? tickSide? reverse? fill? width? radius? dash? dir? head? angle? length? image? path? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? hideLabels? barOutline? rows? step? type? crs? short? mgrs? labels? style? tickLength? format? hemisphere? edges? labelOrientation? labelSize? off? name? direction? at? section? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? outline? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? x? y? w? h? background? layout.addFrame layout? shape? points? map? x? y? w? h? layout.arrange layout? element to layout.arrangement favourite? save? arrangement? remove? @@ -304,7 +304,7 @@ layout.save layout? path layout.series layout? layer nameField? frame? margin? off? layout.seriesPage layout? page layout.seriesRefresh layout? -layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? allClasses? hideOther? showNoData? exclude? labels? classLabels? columns? textSize? showLayerNames? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? border? section? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? barOutline? hideLabels? rows? background? +layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? allClasses? hideOther? showNoData? exclude? labels? classLabels? columns? textSize? showLayerNames? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? border? section? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? barOutline? hideLabels? rows? background? locator.find locator? text limit? zoom? map.activate name map.addTiles url kind? name? bounds? attribution? minZoom? maxZoom? tileSize? singleImage? tms? subdomains? layers? styleLayers? opacity? blend? resampling? overlay? top? replace? id? view? start? end? unit? interval? dates? legend? connection? diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index c5d55e0d74..fb2ff6b6cf 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -7557,6 +7557,7 @@ fn references_follow_layer(s: &mut Session, old: &str, new: &str) { replace(layer) } ElementKind::Colorbar { frame, layer: Some(layer), .. } if frames.contains(frame) => replace(layer), + ElementKind::Profile(p) if frames.contains(&p.frame) => replace(&mut p.layer), ElementKind::Text { text, .. } if texts_read_this_map => { match renamed_statistics(text, rustgis_map::layout::MAX_TEXT_CHARS, braces, &mut replace) { Renamed::To(renamed) => *text = renamed, @@ -7718,10 +7719,10 @@ fn removed_notice(keys: [&'static str; 2], count: usize, named: &[&str]) -> Opti Some(crate::notice_text::NoticeText::format(key, [("count", count.to_string().into()), ("names", names.into())])) } -/// After layers called `names` are removed: a table's, chart's or colorbar's layer, and a text's -/// layer statistics (#2853), keep the name, so a layer of that name brings them back, and are drawn -/// without it meanwhile: how many elements, said once. Which elements read the active map is as for -/// a rename (`references_follow_layer`). +/// After layers called `names` are removed: a table's, chart's, colorbar's or profile's layer, and a +/// text's layer statistics (#2853), keep the name, so a layer of that name brings them back, and are +/// drawn without it meanwhile: how many elements, said once. Which elements read the active map is +/// as for a rename (`references_follow_layer`). fn layouts_follow_removal(s: &mut Session, names: &[String]) { use rustgis_map::layout::ElementKind; @@ -7739,6 +7740,7 @@ fn layouts_follow_removal(s: &mut Session, names: &[String]) { vec![layer] } ElementKind::Colorbar { frame, layer: Some(layer), .. } if frames.contains(frame) => vec![layer], + ElementKind::Profile(p) if frames.contains(&p.frame) => vec![&p.layer], ElementKind::Text { text, .. } if texts_read_this_map => { rustgis_map::layout::stat_tokens(text).iter().map(|t| t.layer).collect() } diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index ce11f715d0..f065b7bd7d 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -44,6 +44,8 @@ use legend::*; pub(crate) use legend::{legend_columns_param, legend_fit_param, legend_names_param}; mod page; use page::*; +mod profile; +use profile::*; mod publication; pub use publication::*; mod series; @@ -183,12 +185,12 @@ pub fn commands() -> Vec { C::new("layout.addElement", "Add Element", "Publish › Map Surrounds", add_element).inputs(element_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params( concat!( r##"{"layout"?, "##, - r##""kind": "northArrow"|"scaleBar"|"legend"|"colorbar"|"text"|"dynamicText"|"picture"|"table"|"chart"|"rectangle" (a neatline framing the page unless any of x, y, w, h is given)|"ellipse"|"circle"|"line"|"arrow"|"extentIndicator"|"grid"|"section" (a section line over a map frame, named at both ends, A and A', up to 26 a frame; as a grid or an extentIndicator, it adds no element: the reply's "element" is its frame, the one layout.update changes it on with "section", and "section" its name), "##, + r##""kind": "northArrow"|"scaleBar"|"legend"|"colorbar"|"text"|"dynamicText"|"picture"|"table"|"chart"|"rectangle" (a neatline framing the page unless any of x, y, w, h is given)|"ellipse"|"circle"|"line"|"arrow"|"extentIndicator"|"grid"|"section" (a section line over a map frame, named at both ends, A and A', up to 26 a frame; as a grid or an extentIndicator, it adds no element: the reply's "element" is its frame, the one layout.update changes it on with "section", and "section" its name)|"profile" (a raster's profile along a section line of the frame, beside the frame on the side the line runs along, lined up with it: each sample is read at its point of the page line, through the frame's projection, so the curve is straight across from the place it comes from; its box is the frame's side, which it follows when the frame is moved or resized; a tilted frame, one on the globe, or a raster read in place draws none, which a notice and exports say), "##, r##""frame"?: element id (default: the first map frame), "##, r##""of"?: frame id (extentIndicator, which also takes "color" and "width" in points, default red and 2), "##, r##""text"? (a text's words; {count:Layer}, {sum:Layer:field}, {mean:Layer:field}, {min:Layer:field} and {max:Layer:field} show the layer's figure, as {scale} shows the scale: of the first map frame's map, over the features the layer's definition query keeps, with the layout's decimal mark; one with no figure shows as written and says why), "##, r##""size"?, "##, - r##""color"?: "#RRGGBB"|"#RRGGBBAA" (text, dynamicText, line, arrow, rectangle, ellipse, circle: its outline; extentIndicator; grid; section, default #A8431F; scaleBar; legend, colorbar, table, chart: the ink of its text and lines, default #222222, a chart's bars and a colorbar's colours keeping theirs, and a table drawn without its white cells; refused for other kinds), "##, + r##""color"?: "#RRGGBB"|"#RRGGBBAA" (text, dynamicText, line, arrow, rectangle, ellipse, circle: its outline; extentIndicator; grid; section, default #A8431F; scaleBar; legend, colorbar, table, chart, profile: the ink of its text and lines, default #222222, a chart's bars and a colorbar's colours keeping theirs, and a table drawn without its white cells; refused for other kinds), "##, r##""bold"?: bool (text), "##, r##""italic"?: bool, "##, r##""align"?: "left"|"center"|"right", "##, @@ -200,7 +202,7 @@ pub fn commands() -> Vec { r##""case"?: "none"|"upper"|"lower" (text, dynamicText: drawn in upper or lower case once its dynamic text is filled in, its text kept as typed; default none; refused for other kinds), "##, r##""font"?: "sans"|"serif"|an installed font family's name, as labels.fonts lists them (text, dynamicText; a family not installed here is drawn in its fallback, and a serif where none is installed in the sans, with a warning; refused for other kinds), "##, r##""fallback"?: "sans"|"serif" (a named font's, where it isn't installed; default its own class, else sans), "##, - r##""title"?: legend title (default "Legend"); chart: its own title ("" for none; default: its field, or the statistic of its field by the group), "##, + r##""title"?: legend title (default "Legend"); chart: its own title ("" for none; default: its field, or the statistic of its field by the group); profile: written over its curve ("" for none; default its layer's name), "##, r##""allClasses"?: bool (legend: every class, not only those the frame draws), "##, r##""hideOther"?: bool (legend: leave out ), "##, r##""showNoData"?: bool (legend: include Graduated Colors’ missing-value symbol; default false), "##, @@ -213,7 +215,7 @@ pub fn commands() -> Vec { r##""ticks"?: 2..21 (colorbar: labelled values, ends included), "##, r##""tickSide"?: "below"|"above"|"right"|"left" (colorbar), "##, r##""reverse"?: bool (colorbar: high values first), "##, - r##""fill"?: "#RRGGBBAA" (rectangle, ellipse, circle, northArrow; scaleBar: the alternating bar's light divisions, default white; refused for other kinds), "##, + r##""fill"?: "#RRGGBBAA" (rectangle, ellipse, circle, northArrow; scaleBar: the alternating bar's light divisions, default white; profile: under its curve, default #D8C8A8, null for none; refused for other kinds), "##, r##""width"?: outline width in points (rectangle, ellipse, circle; 0 for none) or line width in points (line, grid; section, 0.1 to 20, default 1.5), "##, r##""radius"?: mm, 0 to 50 (rectangle: rounded corners), "##, r##""dash"?: [points, …] (line, arrow, section, and a rectangle's, ellipse's or circle's outline: dash, gap, … in turn, as layer.lineStrokes takes it, at most 8, each 0 to 500; an arrow's heads stay solid; [] or null for solid; refused, null too, for other kinds), "##, @@ -223,7 +225,7 @@ pub fn commands() -> Vec { r##""length"?: mm (line, arrow), "##, r##""image"?: base64, "##, r##""path"?: picture file, "##, - r##""layer"?: (table, chart; colorbar: a raster layer, default the top visible raster with a colour scale, not drawn by classes, which a legend lists), "##, + r##""layer"?: (table, chart; colorbar: a raster layer, default the top visible raster with a colour scale, not drawn by classes, which a legend lists; profile: a raster layer held whole, not read in place, default the top one shown), "##, r##""field"?: (chart: a numeric field, default the layer's first; any field when it groups and counts, default then the field it groups by), "##, r##""label"?: a field (chart: each bar's label when not grouped), "##, r##""group"?: a field (chart: a bar per value of this field, its statistic of field over that value's features; blank values make one "(blank)" bar; default none, a bar per feature), "##, @@ -238,7 +240,7 @@ pub fn commands() -> Vec { r##""classes"?: bool (chart: each bar in the colour its features have on the map, by the layer's symbology classes: a bar per feature its feature's, a grouped bar the colour its features share; a bar whose features have several, which a warning counts, and an Other bar keep barColor; default false), "##, r##""labelAlign"?: "left" (the default)|"right" (chart: bars running across have their labels at the left of their column, or at its right against the bars), "##, r##""mirror"?: bool (chart: drawn as its mirror image, its text reading as ever: bars running across from the right, their labels at the right, or columns hanging from the top, their labels over them; beside a chart drawn the usual way the two face each other; default false), "##, - r##""max"?: a number above 0|"auto" (chart: the value at the far end of its bars' room, so charts given the same one share a scale; a bar past it runs to that end, which a warning counts; default "auto", its bars' own), "##, + r##""max"?: a number above 0|"auto" (chart: the value at the far end of its bars' room, so charts given the same one share a scale; a bar past it runs to that end, which a warning counts; default "auto", its bars' own; profile: any number, the value at its top, above "min"; default the samples' most, rounded up), "##, r##""hideLabels"?: bool (chart: its labels left out, their room given to the bars; default false), "##, r##""barOutline"?: {"color"?: "#RRGGBB"|"#RRGGBBAA" (default #222222), "width"?: points, 0 to 5 (default 0.5; 0 for none)} (chart: a line round each bar, or each stretch of a stacked one; default none) (label, group, statistic, order, bars, other, stack, values, decimals, barColor, classes, labelAlign, mirror, max, hideLabels and barOutline refused for other kinds unless null, as showNoData is, a scaleBar's decimals aside), "##, r##""rows"?, "##, @@ -259,8 +261,18 @@ pub fn commands() -> Vec { r##""name"?: a section's name, up to 20 characters, its frame's only one of that name (section, default the first free letter; a grid and an extent indicator refuse it, other kinds say they ignore it), "##, r##""direction"?: "horizontal" (the default)|"vertical" (section: across the whole frame, straight on the page, named at its left and right ends or its top and bottom ones; refused for other kinds), "##, r##""at"?: [longitude, latitude] (section: the place the line runs through and keeps to when the frame is moved, turned or rescaled, default the frame's centre; a line whose place is outside the frame isn't drawn, which a notice and exports say; refused for other kinds), "##, + r##""section"?: a section line's name (profile: the line it follows, default the frame's first; refused for other kinds), "##, + r##""band"?: 1-based (profile: the band read, default 1, its value whatever the raster holds), "##, + r##""side"?: "bottom"|"top" (profile of a horizontal section line, default bottom)|"left"|"right" (of a vertical one, default right), "##, + r##""gap"?: mm, 0 to 100 (profile: between the frame and it, default 3), "##, + r##""thickness"?: mm, 10 to 300 (profile: across it, default 30), "##, + r##""unit"?: text, one line, up to 100 characters (profile: after its value axis' numbers, such as "m"; default none), "##, + r##""lineColor"?: "#RRGGBB"|"#RRGGBBAA" (profile: its curve, default #3C3228), "##, + r##""lineWidth"?: points, 0.1 to 10 (profile: its curve, default 1), "##, + r##""min"?: number (profile: the value at its base; with "max", which must be above it, two profiles share a scale; default the samples' least, rounded down), "##, + r##""guides"?: bool (profile: lines at its value axis' numbers, default true), "##, r##""outline"?: "#RRGGBB" (northArrow, or a rectangle's, ellipse's or circle's outline instead of color; refused for other kinds), "##, - r##""units"?: "auto"|"kilometers"|"meters"|"miles"|"feet", "##, + r##""units"?: "auto"|"kilometers"|"meters"|"miles"|"feet" (scaleBar; profile: its distance axis, from the section line's A end along the ground), "##, r##""divisions"?: 1..10, at most 10 with divisionsBeforeZero together, more refused (scaleBar, whose "color" is its lines, dark divisions and labels, default #222222), "##, r##""subdivisions"?: 0..10 (scaleBar: parts the first division after zero is cut into, not labelled; 0 or 1 leaves it whole), "##, r##""divisionsBeforeZero"?: 0..2 (scaleBar: whole divisions left of zero, labelled with negatives, counted toward the ten in all with "divisions", more refused), "##, @@ -288,7 +300,7 @@ pub fn commands() -> Vec { r##""locked"?: bool (a locked element takes no other change until unlocked; "locked": false unlocks it and may come with changes), "##, r##""text"? (a text's words; {count:Layer}, {sum:Layer:field}, {mean:Layer:field}, {min:Layer:field} and {max:Layer:field} show the layer's figure, as {scale} shows the scale: of the first map frame's map, over the features the layer's definition query keeps, with the layout's decimal mark; one with no figure shows as written and says why), "##, r##""size"?, "##, - r##""color"? (text, line, rectangle, ellipse: its outline; scaleBar: its lines, dark divisions and labels; legend, colorbar, table, chart: its ink, as in layout.addElement, null giving it the default again; refused for other elements), "##, + r##""color"? (text, line, rectangle, ellipse: its outline; scaleBar: its lines, dark divisions and labels; legend, colorbar, table, chart, profile: its ink, as in layout.addElement, null giving it the default again; refused for other elements), "##, r##""bold"?, "##, r##""italic"?, "##, r##""align"?, "##, @@ -356,7 +368,16 @@ pub fn commands() -> Vec { r##""classes"?: bool, "##, r##""labelAlign"?: "left"|"right", "##, r##""mirror"?: bool, "##, - r##""max"?: a number above 0|"auto"|null (null or "auto" giving it its bars' own again), "##, + r##""max"?: a number above 0|"auto"|null (null or "auto" giving it its bars' own again; profile: a number, or null for its samples' own), "##, + r##""band"?, "##, + r##""side"?, "##, + r##""gap"?, "##, + r##""thickness"?, "##, + r##""unit"?, "##, + r##""lineColor"?, "##, + r##""lineWidth"?, "##, + r##""min"?, "##, + r##""guides"? (profile, as in layout.addElement: "section" its line's name, "layer" its raster, "fill", "min" and "max" null for none or its samples' own, "color" its ink; its x, y, w and h set its gap and thickness, along its frame it keeping the frame's), "##, r##""barOutline"?: {"color"?, "width"?: points, 0 to 5, a wider one held to 5, the keys not given keeping the outline's}|null (null or a width of 0 for none), "##, r##""hideLabels"?: bool (chart, as in layout.addElement: null leaves each other one as it is; refused for other elements unless null), "##, r##""rows"?, "##, diff --git a/crates/engine/src/cmd/layout/elements.rs b/crates/engine/src/cmd/layout/elements.rs index 91e695b957..d2e91b933c 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -18,6 +18,8 @@ pub(in crate::cmd::layout) fn duplicate_element(s: &mut Session, p: &Value) -> C c.visible = e.visible; c.background = e.background; } + // A profile's copy keeps beside the same frame: its box is the frame's side. + l.fit_profiles(); crate::cmd::say_name_cut(s, "Duplicate Element", "the copy's name", &e.name, &name); // Its offset can take a text's ink past the page's edge, as a move does (#2703); the lines it // loses are the original's, said when it was set. @@ -260,6 +262,10 @@ pub(crate) fn color(p: &Value, k: &str, d: Rgba) -> Result { pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResult { let kind = ps(p, "kind").ok_or("kind is required")?; + // A profile reads its own keys (#2863 part 2), several of them other kinds' too. + if kind == "profile" { + return add_profile(s, p); + } if kind != "legend" && kind != "scaleBar" && p.get("textSize").is_some_and(|v| !v.is_null()) { return Err(ONLY_LAYOUT_TEXT_SIZE.into()); } diff --git a/crates/engine/src/cmd/layout/export.rs b/crates/engine/src/cmd/layout/export.rs index 2fb140a179..50de17e82f 100644 --- a/crates/engine/src/cmd/layout/export.rs +++ b/crates/engine/src/cmd/layout/export.rs @@ -83,6 +83,11 @@ pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]> if let Some(r) = region { gaps.retain(|g, _| layout.element(g.frame).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); } + let mut profiles: ProfileNotes = + rustgis_render::layout::profiles_not_drawn(&layout, &s.project.maps).into_iter().map(|n| (n, 1)).collect(); + if let Some(r) = region { + profiles.retain(|n, _| layout.element(n.element).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); + } let ((img, mut unfitted), mut charts) = rustgis_render::layout::drawn_charts(|| { rustgis_render::layout::unfitted_legends(|| { crate::cmd::share::saying_shadows(s, "The layout", |s| match region { @@ -106,6 +111,9 @@ pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]> if let Some(note) = rustgis_render::layout::sections_notice(&gaps, 1) { s.warn(note); } + for note in rustgis_render::layout::profiles_notice(&profiles, 1) { + s.warn(note); + } img.encode_png().map_err(|e| e.to_string()) } @@ -152,6 +160,9 @@ pub(in crate::cmd) fn chart_notice_lines_in<'a>( /// The section lines an export doesn't draw, each with the pages it is missing from. type SectionGaps = BTreeMap; +/// What an export's profiles say ([`rustgis_render::layout::profiles_not_drawn`]), each with the +/// pages it is said on. +type ProfileNotes = BTreeMap; /// What `view_map` draws when it is given a `layout`: the layout's frames' maps and their tiles, /// as exporting it reads them, rather than the active map's. `None` without a `layout`. @@ -211,6 +222,7 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( let (mut left_out, mut by_corners): (Vec<(usize, u32, String, &'static str)>, Vec<(usize, u32, String)>) = (Vec::new(), Vec::new()); let mut clipped = BTreeMap::new(); let mut gaps = SectionGaps::new(); + let mut profiles = ProfileNotes::new(); let render_pages = || -> Result<(Vec, Option>), String> { let mut out = Vec::new(); let mut png = None; @@ -236,6 +248,9 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( for gap in rustgis_render::layout::sections_not_drawn(layout, &s.project.maps) { *gaps.entry(gap).or_default() += 1; } + for note in rustgis_render::layout::profiles_not_drawn(layout, &s.project.maps) { + *profiles.entry(note).or_default() += 1; + } // Each page is kept as vectors (its pictures compressed) as soon as it's drawn, within // a memory budget. if pdf { @@ -303,6 +318,9 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( if let Some(note) = rustgis_render::layout::sections_notice(&gaps, pages.len()) { s.warn(note); } + for note in rustgis_render::layout::profiles_notice(&profiles, pages.len()) { + s.warn(note); + } say_unfitted_legends(s, &unfitted); for note in chart_notice_lines(&saved, &charts) { s.warn(note); @@ -535,6 +553,7 @@ pub(in crate::cmd::layout) fn layout_svg(s: &mut Session, li: usize, dpi: f64) - let clipped = rustgis_render::layout::clipped_text(layout, &s.project.maps, dpi, &info); let note = rustgis_render::layout::clipped_text_notice(layout, &clipped); let gaps = rustgis_render::layout::sections_not_drawn(layout, &s.project.maps).into_iter().map(|g| (g, 1)).collect(); + let profiles: ProfileNotes = rustgis_render::layout::profiles_not_drawn(layout, &s.project.maps).into_iter().map(|n| (n, 1)).collect(); let ((drawn, unfitted), charts) = rustgis_render::layout::drawn_charts(|| { rustgis_render::layout::unfitted_legends(|| rustgis_render::svg::layout_svg(layout, &mut s.project.maps, dpi, &info)) }); @@ -543,6 +562,9 @@ pub(in crate::cmd::layout) fn layout_svg(s: &mut Session, li: usize, dpi: f64) - for note in [note, rustgis_render::layout::sections_notice(&gaps, 1)].into_iter().flatten() { s.warn(note); } + for note in rustgis_render::layout::profiles_notice(&profiles, 1) { + s.warn(note); + } say_unfitted_legends(s, &unfitted); for note in chart_notes { s.warn(note); diff --git a/crates/engine/src/cmd/layout/inputs.rs b/crates/engine/src/cmd/layout/inputs.rs index 2305481ddc..bfa0d64a4f 100644 --- a/crates/engine/src/cmd/layout/inputs.rs +++ b/crates/engine/src/cmd/layout/inputs.rs @@ -81,6 +81,17 @@ pub(in crate::cmd::layout) fn series_page_inputs(input: &crate::cmd::InputContex pub(in crate::cmd::layout) fn element_inputs(input: &crate::cmd::InputContext<'_>, p: &Value) -> Result { let s = input; let kind = ps(p, "kind").ok_or("kind is required")?; + // A profile reads the raster it draws (#2863 part 2). + if kind == "profile" { + let layout = s.project.layouts.get(index(input, p)?).ok_or("no layout")?; + let frame = frame_of(layout, p)?; + let map = frame_map(input, layout, frame)?; + let name = added_profile_layer(map, p)?; + let mut inputs = crate::cmd::Inputs::named(map, [name.as_str()])?; + inputs.maps.push(map.instance_id()); + inputs.state = json!({"layout":index(input,p)?,"frame":frame}); + return Ok(inputs); + } if !matches!(kind, "table" | "chart" | "colorbar" | "legend") { let mut inputs = object_inputs(input, p)?; if matches!(kind, "northArrow" | "scaleBar" | "extentIndicator" | "grid" | "section") { @@ -222,6 +233,12 @@ pub(in crate::cmd::layout) fn update_inputs(input: &crate::cmd::InputContext<'_> inputs.extend(crate::cmd::Inputs::named(frame_map(input, l, *frame)?, [name.as_str()])?); } } + // A profile's new raster (#2863 part 2). + Some(ElementKind::Profile(profile)) if ps(p, "layer").is_some_and(|n| !n.trim().is_empty()) => { + let map = frame_map(input, l, profile.frame)?; + let name = added_profile_layer(map, p)?; + inputs.extend(crate::cmd::Inputs::named(map, [name.as_str()])?); + } Some(ElementKind::Legend { frame, .. }) => { let (names, labels) = (legend_exclude(input, l, *frame, p)?, legend_labels(input, l, *frame, p)?); let classes = legend_class_labels(input, l, *frame, p)?; @@ -282,6 +299,7 @@ pub(in crate::cmd::layout) fn element_selectors(kind: &ElementKind) -> Option json!({"frame":frame,"layer":layer}), + ElementKind::Profile(p) => json!({"frame":p.frame,"layer":p.layer,"section":p.section}), ElementKind::NorthArrow { frame, .. } | ElementKind::ScaleBar { frame, .. } => json!({"frame":frame}), _ => return None, }) diff --git a/crates/engine/src/cmd/layout/profile.rs b/crates/engine/src/cmd/layout/profile.rs new file mode 100644 index 0000000000..9e8e8005a5 --- /dev/null +++ b/crates/engine/src/cmd/layout/profile.rs @@ -0,0 +1,327 @@ +//! A raster's profile beside its map frame (#2863 part 2): what `layout.addElement` and +//! `layout.update` read for one, and what they say of it. + +use rustgis_map::layout::{ + MAX_PROFILE_BAND, MAX_PROFILE_TEXT, PROFILE_GAPS, PROFILE_LINE_WIDTHS, PROFILE_THICKNESSES, Profile, ProfileSide, +}; + +use super::*; + +/// The keys of a profile's own, which `layout.addElement` and `layout.update` read. +const PROFILE_KEYS: &[&str] = &[ + "section", + "layer", + "band", + "side", + "gap", + "thickness", + "title", + "unit", + "lineColor", + "lineWidth", + "fill", + "min", + "max", + "units", + "guides", + "color", +]; +/// What `layout.addElement` reads for a profile, besides [`PROFILE_KEYS`]. +const ADD_PROFILE_KEYS: &[&str] = &["layout", "kind", "frame", "background"]; +/// What `layout.update` reads for a profile, besides [`PROFILE_KEYS`]: `x`, `y`, `w` and `h` as its +/// gap and thickness ([`Profile::take_rect`]). +const UPDATE_PROFILE_KEYS: &[&str] = &["layout", "element", "name", "visible", "locked", "background", "x", "y", "w", "h"]; + +/// A profile's keys that null gives back their default: no fill, the samples' own ends, the dark +/// grey ink. +const PROFILE_NULL_KEYS: &[&str] = &["fill", "min", "max", "color", "background"]; + +/// Whether element `id` of layout `li` is a profile. +pub(in crate::cmd::layout) fn is_profile(s: &Session, li: usize, id: u32) -> bool { + s.project.layouts.get(li).and_then(|l| l.element(id)).is_some_and(|e| e.kind.is_profile()) +} + +/// A frame's map, its section lines and its box (x, y, w, h in mm). +fn frame_parts<'a>(s: &'a Session, l: &'a Layout, frame: u32) -> Result<(&'a Map, &'a [Section], (f64, f64, f64, f64)), String> { + let e = l.element(frame).ok_or_else(|| format!("no element {frame}"))?; + let ElementKind::MapFrame { map, sections, .. } = &e.kind else { + return Err(format!("element {frame} isn't a map frame")); + }; + let m = s.project.maps.iter().find(|m| m.name.eq_ignore_ascii_case(map)).ok_or_else(|| format!("no map '{map}'"))?; + Ok((m, sections, (e.x, e.y, e.w, e.h))) +} + +/// Why `layer` can't be profiled, if it can't: a profile reads a raster held whole, as a remote or +/// tiled one read in place gives only the overview drawn, which changes with the scale. +fn not_held_whole(layer: &rustgis_map::Layer) -> Option { + let rl = layer.raster.as_ref()?; + let why = if rl.in_place || rl.tiled { + "is read in place, a part at a time" + } else if rl.data.as_ref().is_some_and(|r| r.overview.is_some()) { + "holds only an overview of its file" + } else { + return None; + }; + Some(format!("'{}' {why}: a profile reads a raster held whole", layer.name)) +} + +/// The raster layer of `map` named `name` (any case), as the map spells it, if a profile can read it. +fn profile_layer(map: &Map, name: &str) -> Result { + let layer = + map.layer_by_name(name).filter(|l| l.is_raster()).ok_or_else(|| format!("no raster layer '{}' in {}", name.trim(), map.name))?; + match not_held_whole(layer) { + Some(why) => Err(why), + None => Ok(layer.name.clone()), + } +} + +/// The top raster the map shows that a profile can read: a new profile's layer unless given one. +fn first_profile_layer(map: &Map) -> Result { + let found = map.layers.iter().filter(|l| l.is_raster() && map.shows(l)).find(|l| not_held_whole(l).is_none()); + found.map(|l| l.name.clone()).ok_or_else(|| format!("{} shows no raster a profile can read: give a layer", map.name)) +} + +/// The bands of `map`'s layer `name` when its pixels are read. +fn bands_of(map: &Map, name: &str) -> Option { + map.layer_by_name(name).and_then(|l| l.raster.as_ref()).and_then(|r| r.data.as_ref()).map(|r| r.bands.len()) +} + +/// A number given as `k`, or null for none, when `p` has it: `Some(None)` for null. +fn number_or_null(p: &Value, k: &str) -> Result>, String> { + match p.get(k) { + None => Ok(None), + Some(Value::Null) => Ok(Some(None)), + Some(v) => v.as_f64().filter(|v| v.is_finite()).map(|v| Some(Some(v))).ok_or_else(|| format!("{k} is a number, or null")), + } +} + +/// A profile with the options in `p` over `base`'s, in layout `l`, and what was held to its limits; +/// a bad value is an error, leaving nothing changed. +fn profile_params(s: &Session, l: &Layout, p: &Value, mut base: Profile) -> Result<(Profile, Vec), String> { + let (map, sections, _) = frame_parts(s, l, base.frame)?; + let mut held = Vec::new(); + if let Some(n) = given_name(p, "section", "a section line's name")? { + let found = Section::find(sections, n).and_then(|i| sections.get(i)); + base.section = found.map(|s| s.name.clone()).ok_or_else(|| format!("the frame has no section line '{}'", n.trim()))?; + } + let line = Section::find(sections, &base.section).and_then(|i| sections.get(i)).map(|s| s.line); + match given_name(p, "side", "bottom, top, left or right")? { + Some(v) => { + let side = ProfileSide::from_name(v).ok_or_else(|| format!("unknown side '{v}' (bottom, top, left or right)"))?; + if let Some(line) = line.filter(|line| !side.suits(*line)) { + let sides = if side.is_horizontal() { "left or right" } else { "bottom or top" }; + return Err(format!("a profile of a {} section line goes {sides} of its frame", line.code())); + } + base.side = side; + } + // Moved to a line running the other way, it goes to that line's side. + None => { + if let Some(line) = line.filter(|line| !base.side.suits(*line)) { + base.side = ProfileSide::default_for(line); + } + } + } + if let Some(n) = given_name(p, "layer", "a raster layer's name")? { + base.layer = profile_layer(map, n)?; + } + if let Some(v) = given_num(p, "band", "a band number from 1")? { + if v.fract() != 0.0 || v < 1.0 || v > f64::from(MAX_PROFILE_BAND) { + return Err(format!("band is a whole number from 1 to {MAX_PROFILE_BAND}")); + } + base.band = v as u32; + } + if let Some(n) = bands_of(map, &base.layer).filter(|n| base.band as usize > *n) { + return Err(format!("'{}' has {n} band(s): band is 1 to {n}", base.layer)); + } + let mut mm = |k: &str, range: (f64, f64), v: &mut f64| -> Result<(), String> { + if let Some(n) = given_num(p, k, "a number of mm")? { + let kept = n.clamp(range.0, range.1); + if kept != n { + held.push(format!("{k} {n} held to {kept} ({} to {} mm)", range.0, range.1)); + } + *v = kept; + } + Ok(()) + }; + mm("gap", PROFILE_GAPS, &mut base.gap)?; + mm("thickness", PROFILE_THICKNESSES, &mut base.thickness)?; + for (k, text) in [("title", &mut base.title), ("unit", &mut base.unit)] { + if let Some(t) = given_name(p, k, "text")? { + let t = crate::cmd::within(k, "a profile's title or unit", t, MAX_PROFILE_TEXT)?; + if t.contains(['\n', '\r']) { + return Err(format!("{k} is one line")); + } + *text = t.trim().to_string(); + } + } + base.line_color = color(p, "lineColor", base.line_color)?; + if let Some(w) = given_num(p, "lineWidth", "a number of points")? { + let kept = w.clamp(PROFILE_LINE_WIDTHS.0, PROFILE_LINE_WIDTHS.1); + if kept != w { + held.push(format!("lineWidth {w} held to {kept} ({} to {} points)", PROFILE_LINE_WIDTHS.0, PROFILE_LINE_WIDTHS.1)); + } + base.line_width = kept; + } + match p.get("fill") { + None => {} + Some(Value::Null) => base.fill = None, + Some(_) => base.fill = Some(color(p, "fill", base.line_color)?), + } + if let Some(v) = number_or_null(p, "min")? { + base.min = v; + } + if let Some(v) = number_or_null(p, "max")? { + base.max = v; + } + if let (Some(lo), Some(hi)) = (base.min, base.max) + && lo >= hi + { + return Err(format!("min ({lo}) is below max ({hi})")); + } + if let Some(v) = given_name(p, "units", "auto, kilometers, meters, miles or feet")? { + base.units = ScaleUnits::from_name(v).ok_or_else(|| format!("unknown units '{v}' (auto, kilometers, meters, miles or feet)"))?; + } + match p.get("guides").filter(|v| !v.is_null()) { + Some(Value::Bool(v)) => base.guides = *v, + Some(_) => return Err("guides is true or false".into()), + None => {} + } + if p.get("color").is_some() { + base.color = given_color(p, "color")?; + } + Ok((base, held)) +} + +/// `layout.addElement` for a profile (#2863 part 2): along a section line of its frame (its first +/// unless named), of a raster of the frame's map (the top one shown unless named), on the side the +/// line runs along, its box the frame's side ([`Profile::rect`]). +pub(in crate::cmd::layout) fn add_profile(s: &mut Session, p: &Value) -> CmdResult { + let keys: Vec<&str> = ADD_PROFILE_KEYS.iter().chain(PROFILE_KEYS).copied().collect(); + if ["x", "y", "w", "h"].iter().any(|k| gives(p, k)) { + return Err("a profile's box is its frame's side: give it a gap and a thickness (mm), not x, y, w or h".into()); + } + only_add_keys(p, "a profile", &keys, &["name"])?; + let background = match element_background(p, None)? { + BackgroundParam::Set(b) => Some(b), + BackgroundParam::Absent | BackgroundParam::Remove => None, + }; + let li = index(s, p)?; + let l = s.project.layouts.get(li).ok_or("no layout")?; + let frame = frame_of(l, p)?; + let (map, sections, frame_box) = frame_parts(s, l, frame)?; + let first = sections.first().ok_or("the frame has no section line: add one first (layout.addElement with kind section)")?; + let layer = if gives(p, "layer") { String::new() } else { first_profile_layer(map)? }; + let base = Profile::new(frame, first.name.clone(), layer, ProfileSide::default_for(first.line)); + let (mut new, held) = profile_params(s, l, p, base)?; + // Titled with its layer's name unless given one ("" for none), as a colorbar is. + if p.get("title").is_none_or(Value::is_null) { + new.title = new.layer.chars().take(MAX_PROFILE_TEXT).collect(); + } + let rect = new.rect(frame_box); + let l = s.project.layouts.get_mut(li).ok_or("no layout")?; + let id = l.add("Profile", rect, ElementKind::Profile(new)); + if let Some(e) = l.element_mut(id) { + e.background = background; + } + say_held(s, "Add Element", held); + if gives(p, "name") { + s.notify("Add Element ignores \"name\" for a profile: only a section takes one (layout.update names an element)", false); + } + say_profile_drawn(s, li, id); + Ok(json!({"element": id})) +} + +/// `layout.update` for a profile: its own options, its name, visibility, lock and background, and +/// `x`, `y`, `w` and `h` read as its gap and thickness, along its frame it keeping the frame's. +pub(in crate::cmd::layout) fn update_profile(s: &mut Session, p: &Value, li: usize, id: u32) -> CmdResult { + let keys: Vec<&str> = UPDATE_PROFILE_KEYS.iter().chain(PROFILE_KEYS).copied().collect(); + if let Some(k) = p.as_object().and_then(|o| o.keys().find(|k| !keys.contains(&k.as_str()) && gives(p, k))) { + let shown: String = k.chars().take(40).map(|c| if c.is_control() { '?' } else { c }).collect(); + return Err(format!("layout.update: a profile takes no \"{shown}\" (it reads {})", keys.join(", "))); + } + let l = s.project.layouts.get(li).ok_or("no layout")?; + let e = l.element(id).ok_or_else(|| format!("no element {id}"))?; + let ElementKind::Profile(current) = &e.kind else { return Err(format!("element {id} isn't a profile")) }; + let changes = p.as_object().is_some_and(|o| { + o.iter().any(|(k, v)| { + (!v.is_null() || PROFILE_NULL_KEYS.contains(&k.as_str())) && !matches!(k.as_str(), "layout" | "element" | "locked") + }) + }); + if changes && b(p, "locked") != Some(false) { + unlocked(l, id)?; + } + let new_name = crate::cmd::name_given(p, "an element's name", 200)?; + let new_background = match element_background(p, e.background)? { + BackgroundParam::Set(b) => Some(Some(b)), + BackgroundParam::Remove => Some(None), + BackgroundParam::Absent => None, + }; + let boxed = ["x", "y", "w", "h"].iter().any(|k| gives(p, k)); + if boxed && (gives(p, "gap") || gives(p, "thickness")) { + return Err("give a profile a gap and thickness, or x, y, w and h, not both".into()); + } + let (mut new, mut held) = profile_params(s, l, p, current.clone())?; + let (_, _, frame_box) = frame_parts(s, l, new.frame)?; + if boxed { + let rect = (f(p, "x").unwrap_or(e.x), f(p, "y").unwrap_or(e.y), f(p, "w").unwrap_or(e.w), f(p, "h").unwrap_or(e.h)); + if new.take_rect(frame_box, rect) { + let ((g0, g1), (t0, t1)) = (PROFILE_GAPS, PROFILE_THICKNESSES); + held.push(format!("its gap held to {} ({g0} to {g1} mm) and thickness to {} ({t0} to {t1} mm)", new.gap, new.thickness)); + } + } + let reread = ["section", "layer", "band", "side"].iter().any(|k| gives(p, k)); + let l = s.project.layouts.get_mut(li).ok_or("no layout")?; + let e = l.element_mut(id).ok_or_else(|| format!("no element {id}"))?; + e.kind = ElementKind::Profile(new); + if let Some(n) = new_name { + e.name = n; + } + if let Some(v) = b(p, "visible") { + e.visible = v; + } + if let Some(v) = b(p, "locked") { + e.locked = v; + } + if let Some(v) = new_background { + e.background = v; + } + l.fit_profiles(); + say_held(s, "Element Properties", held); + if reread { + say_profile_drawn(s, li, id); + } + Ok(Value::Null) +} + +/// Says that profile `id` of layout `li` isn't drawn, and why, or that it is read at fewer samples +/// than its raster's cells along its section line, when it is. +pub(in crate::cmd::layout) fn say_profile_drawn(s: &mut Session, li: usize, id: u32) { + let Some(l) = s.project.layouts.get(li) else { return }; + let notes = rustgis_render::layout::profiles_not_drawn(l, &s.project.maps); + let notes = notes.into_iter().filter(|n| n.element == id).map(|n| (n, 1)).collect(); + for note in rustgis_render::layout::profiles_notice(¬es, 1) { + s.warn(note); + } +} + +/// The profiles of section line `old` of frame `frame` named `new` instead, after the line was +/// renamed: they follow it. +pub(in crate::cmd::layout) fn profiles_follow_section(l: &mut Layout, frame: u32, old: &str, new: &str) { + for e in &mut l.elements { + if let ElementKind::Profile(p) = &mut e.kind + && p.frame == frame + && p.section.eq_ignore_ascii_case(old) + { + p.section = new.to_string(); + } + } +} + +/// The raster layer `layout.addElement` reads for a profile, for its inputs: the one given, else the +/// top one its frame's map shows that it can read. +pub(in crate::cmd::layout) fn added_profile_layer(map: &Map, p: &Value) -> Result { + match given_name(p, "layer", "a raster layer's name")? { + Some(n) => profile_layer(map, n), + None => first_profile_layer(map), + } +} diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index 3574cff500..e3e4ab6fa4 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -147,6 +147,12 @@ pub(in crate::cmd::layout) fn restyle(kind: &ElementKind, p: &Value) -> Result CmdResult { let id = element_id(p)?; + // A profile reads its own keys (#2863 part 2), several of them other kinds' too. + if let Ok(li) = index(s, p) + && is_profile(s, li, id) + { + return update_profile(s, p, li, id); + } // The first frame's map as it is, to say what the texts lose only when it changes (#2853). let map_before = index(s, p).ok().and_then(|li| first_frame_map(s, li)); // Checked before anything changes, so a bad value leaves the element as it was. @@ -831,6 +837,14 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { if let Some((_, Some(name))) = &new_sections { say_section_not_drawn(s, li, id, name); } + // A frame moved or resized takes its profiles with it, and a section line renamed its + // profiles (#2863). + if let Some(l) = s.project.layouts.get_mut(li) { + if let (Some((_, Some(new))), Some(old)) = (&new_sections, p.get("section").and_then(|v| ps(v, "name"))) { + profiles_follow_section(l, id, old.trim(), new); + } + l.fit_profiles(); + } say_held(s, "Element Properties", held); if let Some(w) = font_told { return Ok(json!({"warning": w})); diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index 2a27412a0b..1a1d4e4beb 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -1273,6 +1273,30 @@ fn say_sections_not_drawn(s: &mut Session, pages: &[rustgis_render::report::Page if let Some(note) = rustgis_render::layout::sections_notice(&gaps, 1) { s.warn(format!("The report: {note}")); } + say_profiles_not_drawn(s, pages, n); +} + +/// Says what the profiles (#2863 part 2) of the layouts of the first `n` of `pages` say, as +/// [`say_sections_not_drawn`] says their section lines: one notice of a kind, each profile named +/// with its layout. +fn say_profiles_not_drawn(s: &mut Session, pages: &[rustgis_render::report::Page], n: usize) { + let mut seen = Vec::new(); + let mut notes = std::collections::BTreeMap::new(); + for page in pages.iter().take(n) { + let rustgis_render::report::Page::Layout(li) = page else { continue }; + if seen.contains(li) { + continue; + } + seen.push(*li); + let Some(layout) = s.project.layouts.get(*li) else { continue }; + for mut note in rustgis_render::layout::profiles_not_drawn(layout, &s.project.maps) { + note.layout.clone_from(&layout.name); + notes.insert(note, 1); + } + } + for note in rustgis_render::layout::profiles_notice(¬es, 1) { + s.warn(format!("The report: {note}")); + } } /// Runs `f`, and returns its result with the legends it drew under a fit still cut and the charts diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 9c32ea295f..4746b856a1 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -114,6 +114,7 @@ pub const CAPABILITIES: &[&str] = &[ "blank-paper", "layout-frame-border", "layout-section", + "layout-profile", NATIVE_COORDINATES, "layout-text-size", "layout-legend-fit", diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 201f64f145..9b245930c7 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -169,6 +169,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("blank-paper", command_uses_blank_paper), ("layout-frame-border", command_uses_frame_border), ("layout-section", command_uses_section), + ("layout-profile", command_uses_profile), ("layout-text-size", command_uses_text_size), ("layout-legend-fit", command_uses_legend_fit), ("layout-legend-class-labels", command_uses_legend_class_labels), @@ -489,6 +490,26 @@ fn command_uses_section(id: &str, params: &Value) -> bool { } } +/// The keys of `layout.update` only a profile reads (#2863 part 2), besides a `section` given as a +/// name, which a map frame takes as an object. +const PROFILE_ONLY_KEYS: &[&str] = &["band", "side", "gap", "thickness", "unit", "lineColor", "lineWidth", "guides", "min"]; + +/// A layout command that adds or changes a profile beside a map frame (#2863 part 2): an older +/// reader refuses the kind `profile`, and the keys only a profile reads. +fn command_uses_profile(id: &str, params: &Value) -> bool { + match id { + "layout.addElement" => params.get("kind").and_then(Value::as_str).is_some_and(|k| k.trim().eq_ignore_ascii_case("profile")), + "layout.update" => { + PROFILE_ONLY_KEYS.iter().any(|k| params.get(*k).is_some_and(|v| !v.is_null())) + || params.get("section").is_some_and(Value::is_string) + } + // A layout file, read as `layout.import` reads it, which `report.existingTemplate` also does. + "layout.import" | "report.existingTemplate" => imported_layout_uses(params, &["\"Profile\""], |e| e.kind.is_profile()), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_profile)), + _ => false, + } +} + /// A `layout.page` command that gives the page a colour other than white (#2855), read as the /// command reads it: an older reader ignores `color` and opens the page white. A `layout.import` /// whose layout has one needs it too. @@ -1271,6 +1292,7 @@ fn layout_capabilities(layouts: &[rustgis_map::layout::Layout]) -> Vec<&'static (elements().any(charts_outlined), "layout-chart-outline"), (elements().any(|e| e.kind.has_custom_border()), "layout-frame-border"), (elements().any(|e| e.kind.has_sections()), "layout-section"), + (elements().any(|e| e.kind.is_profile()), "layout-profile"), (elements().any(|e| e.kind.has_custom_text_size()), "layout-text-size"), (elements().any(legends_fitting), "layout-legend-fit"), (elements().any(legend_labels_classes), "layout-legend-class-labels"), @@ -1586,6 +1608,7 @@ mod tests { (&["blank-paper"], "map.basemap", json!({"name": "blank", "color": "#112233"})), (&["layout-frame-border"], "layout.update", json!({"element": 1, "border": {}})), (&["layout-section"], "layout.update", json!({"element": 1, "section": {"name": "A", "y": 0}})), + (&["layout-profile"], "layout.update", json!({"element": 2, "thickness": 20})), (&["layout-text-size"], "layout.update", json!({"element": 1, "textSize": 12})), (&["layout-legend-fit"], "layout.update", json!({"element": 1, "fit": "adjustSize"})), (&["layout-legend-class-labels"], "layout.update", json!({"element": 1, "classLabels": {"a": {"x": "X"}}})), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 228a95f994..6fd1ffd888 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -111,6 +111,8 @@ mod elevation_tiles; #[path = "tests/layout_files.rs"] mod layout_files; +#[path = "tests/layout_profiles.rs"] +mod layout_profiles; #[path = "tests/layout_sections.rs"] mod layout_sections; diff --git a/crates/engine/src/tests/layout_files.rs b/crates/engine/src/tests/layout_files.rs index f1eed5eda6..0c18dc242d 100644 --- a/crates/engine/src/tests/layout_files.rs +++ b/crates/engine/src/tests/layout_files.rs @@ -125,6 +125,7 @@ fn a_saved_layout_file_requires_what_its_elements_use_and_reads_back_the_same() ("outline", include_str!("../../../../schema/fixtures/layout_chart_outline.rgis")), ("border", include_str!("../../../../schema/fixtures/layout_frame_border.rgis")), ("section", include_str!("../../../../schema/fixtures/layout_section.rgis")), + ("profile", include_str!("../../../../schema/fixtures/layout_profile.rgis")), ("legend-text", include_str!("../../../../schema/fixtures/layout_legend_text.rgis")), ("legend-fit", include_str!("../../../../schema/fixtures/layout_legend_fit.rgis")), ("legend-class-labels", include_str!("../../../../schema/fixtures/layout_legend_class_labels.rgis")), diff --git a/crates/engine/src/tests/layout_profiles.rs b/crates/engine/src/tests/layout_profiles.rs new file mode 100644 index 0000000000..b7b8991a8d --- /dev/null +++ b/crates/engine/src/tests/layout_profiles.rs @@ -0,0 +1,191 @@ +//! Profiles beside a layout's map frame (#2863 part 2): the commands, what they say, and how a +//! profile agrees with `profile.create`. + +use crate::{Session, sample}; +use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; +use rustgis_geom::Coord; +use rustgis_map::layout::{ElementKind, Profile, ProfileSide}; +use serde_json::{Value, json}; + +/// A layout with a frame of the sample's map round (10, 50), a raster "DEM" of one degree's hundred +/// metres of latitude over it, and the frame's id. +fn with_dem() -> (Session, u64) { + let mut s = Session::new(sample::world_project()); + let (n, cell) = (400usize, 0.05); + let data = (0..n * n).map(|i| ((60.0 - ((i / n) as f64 + 0.5) * cell) * 100.0) as f32).collect(); + let gt = GeoTransform { origin_x: 0.0, origin_y: 60.0, pixel_width: cell, pixel_height: -cell }; + let r = Raster::new("dem", n as u32, n as u32, vec![data], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + s.map_mut().add_raster("DEM", rustgis_map::RasterLayer::from_path(r, "dem.tif")); + s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap(); + let frame = u64::from(s.project.layouts[0].first_frame().unwrap()); + s.run("layout.update", &json!({"element": frame, "center": [10, 50], "scale": 1e7})).unwrap(); + (s, frame) +} + +fn profile(s: &Session, id: u64) -> (Profile, [f64; 4]) { + let e = s.project.layouts[0].element(id as u32).expect("the element"); + match &e.kind { + ElementKind::Profile(p) => (p.clone(), [e.x, e.y, e.w, e.h]), + _ => panic!("a profile"), + } +} + +fn frame_box(s: &Session, frame: u64) -> [f64; 4] { + let e = s.project.layouts[0].element(frame as u32).expect("the frame"); + [e.x, e.y, e.w, e.h] +} + +fn said(s: &Session, mark: u64) -> Vec { + s.notices_since(mark).iter().map(|n| n.text.clone()).collect() +} + +/// A profile is added along a section line of its frame (its first unless named), of the top +/// raster shown unless named, beside the frame on the side the line runs along; it follows the +/// frame when moved or resized, its section line and layer when renamed, and goes with the frame; +/// a box asked of it is its gap and thickness; and all of it is undone. +#[test] +fn a_profile_is_added_follows_its_frame_and_is_undone() { + let (mut s, frame) = with_dem(); + let err = s.run("layout.addElement", &json!({"kind": "profile"})).unwrap_err(); + assert!(err.contains("the frame has no section line"), "{err}"); + s.run("layout.addElement", &json!({"kind": "section", "at": [10, 50]})).unwrap(); + let mark = s.notice_mark(); + let id = s.run("layout.addElement", &json!({"kind": "profile", "unit": "m", "layout": 0, "text": null})).unwrap()["element"] + .as_u64() + .unwrap(); + assert!(said(&s, mark).is_empty(), "{:?}", said(&s, mark)); + let (p, at) = profile(&s, id); + assert_eq!( + (p.section.as_str(), p.layer.as_str(), p.side, p.title.as_str(), p.unit.as_str()), + ("A", "DEM", ProfileSide::Bottom, "DEM", "m") + ); + let [fx, fy, fw, fh] = frame_box(&s, frame); + assert_eq!(at, [fx, fy + fh + p.gap, fw, p.thickness]); + // Refused, nothing changed: a side across its line, a key it doesn't read, a box of its own. + for (bad, says) in [ + (json!({"kind": "profile", "side": "left"}), "goes bottom or top of its frame"), + (json!({"kind": "profile", "rows": 5}), "a profile takes no \"rows\""), + (json!({"kind": "profile", "x": 5}), "a profile's box is its frame's side"), + (json!({"kind": "profile", "layer": "Countries"}), "no raster layer 'Countries'"), + (json!({"kind": "profile", "band": 2}), "'DEM' has 1 band(s)"), + (json!({"kind": "profile", "min": 9, "max": 1}), "min (9) is below max (1)"), + ] { + let err = s.run("layout.addElement", &bad).unwrap_err(); + assert!(err.contains(says), "{bad}: {err}"); + } + assert_eq!(s.project.layouts[0].elements.iter().filter(|e| e.kind.is_profile()).count(), 1); + // The frame moved and resized: the profile with it. + s.run("layout.update", &json!({"element": frame, "x": 20, "y": 30, "w": 120})).unwrap(); + let (p, at) = profile(&s, id); + assert_eq!(at, [20.0, 30.0 + fh + p.gap, 120.0, p.thickness]); + // Dragged along the frame and away from it: only its gap follows; held to its limits, said. + s.run("layout.update", &json!({"element": id, "x": 60, "y": at[1] + 4.0})).unwrap(); + let (p, at) = profile(&s, id); + assert_eq!((at[0], p.gap), (20.0, 7.0)); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "thickness": 1000, "fill": null, "lineColor": "#1F5C84"})).unwrap(); + assert!(said(&s, mark).iter().any(|n| n.contains("thickness 1000 held to 300")), "{:?}", said(&s, mark)); + let (p, _) = profile(&s, id); + assert_eq!((p.thickness, p.fill, p.line_color.hex()), (300.0, None, "#1F5C84".to_string())); + let err = s.run("layout.update", &json!({"element": id, "gap": 2, "y": 9})).unwrap_err(); + assert!(err.contains("not both"), "{err}"); + let err = s.run("layout.update", &json!({"element": id, "rows": 3})).unwrap_err(); + assert!(err.contains("a profile takes no \"rows\""), "{err}"); + // Its section line and its layer renamed: it follows them. + s.run("layout.update", &json!({"element": frame, "section": {"name": "a", "newName": "Serra"}})).unwrap(); + s.run("layer.rename", &json!({"layer": "DEM", "name": "Relevo"})).unwrap(); + let (p, _) = profile(&s, id); + assert_eq!((p.section.as_str(), p.layer.as_str()), ("Serra", "Relevo")); + // Its frame removed, it goes with it; undone, both are back. + s.run("layout.removeElement", &json!({"element": frame})).unwrap(); + assert!(s.project.layouts[0].element(id as u32).is_none()); + s.run("edit.undo", &Value::Null).unwrap(); + assert!(s.project.layouts[0].element(id as u32).is_some()); +} + +/// A profile its page can't draw says so when it is added and when the page is exported: beside a +/// tilted frame, one notice naming it and why. +#[test] +fn a_profile_not_drawn_is_said() { + let (mut s, frame) = with_dem(); + s.run("layout.addElement", &json!({"kind": "section", "at": [10, 50], "direction": "vertical"})).unwrap(); + s.run("layout.update", &json!({"element": frame, "pitch": 40})).unwrap(); + let mark = s.notice_mark(); + let id = s.run("layout.addElement", &json!({"kind": "profile"})).unwrap()["element"].as_u64().unwrap(); + assert_eq!(profile(&s, id).0.side, ProfileSide::Right, "a vertical line's beside the frame"); + let notes = said(&s, mark); + assert!(notes.len() == 1 && notes[0].contains("1 profile(s) not drawn") && notes[0].contains("tilted"), "{notes:?}"); + // Each way the page is drawn says it once: a PNG, a PDF, the layout view's picture. + let drawn: Vec<(&str, Box)> = vec![ + ("png", Box::new(|s| drop(crate::cmd::layout::layout_bytes(s, 0, false, 48.0, false).unwrap()))), + ("pdf", Box::new(|s| drop(crate::cmd::layout::layout_bytes(s, 0, true, 48.0, true).unwrap()))), + ("view", Box::new(|s| drop(crate::cmd::layout::layout_png(s, 0, 48.0, None).unwrap()))), + ]; + let profile_notes = |s: &Session, mark: u64| said(s, mark).into_iter().filter(|n| n.contains("profile(s)")).collect::>(); + for (how, export) in &drawn { + let mark = s.notice_mark(); + export(&mut s); + assert_eq!(profile_notes(&s, mark), notes, "{how}"); + } + // Flat again, it is drawn, and nothing is said. + s.run("layout.update", &json!({"element": frame, "pitch": 0})).unwrap(); + for (how, export) in &drawn { + let mark = s.notice_mark(); + export(&mut s); + assert!(profile_notes(&s, mark).is_empty(), "{how}: {:?}", said(&s, mark)); + } +} + +/// The Mantiqueira of #2863: a vertical section line of a UTM 23S frame through the Pedra da Mina, +/// whose profile `profile.create` gave again within 0.11 m over 1,600 samples of the Copernicus DEM. +/// On a relief of that frame, the profile's samples and `profile.create`'s between the line's ends, +/// as many, agree as closely: a vertical line of a UTM frame strays little from the straight line +/// of longitude and latitude between its ends. +#[test] +fn the_mantiqueira_profile_agrees_with_profile_create() { + let mut s = Session::new(sample::world_project()); + s.run("map.projection", &json!({"type": "EPSG:31983"})).unwrap(); + let crs = Crs::from_epsg(31983).unwrap(); + let to = crs.transformer().unwrap(); + let mid = to.from_lonlat(Coord::new(-44.715, -22.412)).unwrap(); + let (cols, rows, cell) = (1600usize, 1000usize, 30.0); + let (x0, y0) = (((mid.x - 24_000.0) / cell).round() * cell, ((mid.y + 15_000.0) / cell).round() * cell); + // Ridges and valleys a few kilometres across, some 2,000 m of relief, as the Mantiqueira's. + let z = |e: f64, n: f64| 1500.0 + 600.0 * (e / 2_300.0).sin() * (n / 1_700.0).cos() + 300.0 * ((e + n) / 900.0).sin(); + let data = (0..rows * cols).map(|i| z(x0 + ((i % cols) as f64 + 0.5) * cell, y0 - ((i / cols) as f64 + 0.5) * cell) as f32).collect(); + let gt = GeoTransform { origin_x: x0, origin_y: y0, pixel_width: cell, pixel_height: -cell }; + let r = Raster::new("dem", cols as u32, rows as u32, vec![data], gt, crs, None, ColorHint::Gray, "Float32").unwrap(); + s.map_mut().add_raster("DEM", rustgis_map::RasterLayer::from_path(r, "dem.tif")); + s.run("layout.new", &json!({"page": "a4", "orientation": "landscape", "template": "blank"})).unwrap(); + s.run("layout.addFrame", &json!({})).unwrap(); + let frame = u64::from(s.project.layouts[0].first_frame().unwrap()); + s.run( + "layout.update", + &json!({"element": frame, "x": 30, "y": 34, "w": 186, "h": 112, "center": [-44.715, -22.412], "scale": 200_000}), + ) + .unwrap(); + s.run("layout.addElement", &json!({"kind": "section", "direction": "vertical", "at": [-44.8429, -22.4282]})).unwrap(); + let id = s.run("layout.addElement", &json!({"kind": "profile", "unit": "m"})).unwrap()["element"].as_u64().unwrap(); + let (p, _) = profile(&s, id); + let (samples, _) = rustgis_render::layout::profile_samples(&s.project.layouts[0], &s.project.maps, &p).unwrap(); + // The line's ends on the ground, as the frame shows them. + let map = &s.project.maps[0]; + let ElementKind::MapFrame { center, scale, .. } = &s.project.layouts[0].element(frame as u32).unwrap().kind else { panic!("a frame") }; + let cam = rustgis_map::layout::frame_camera(map, *center, *scale, 0.0, 0.0); + let (fw, fh) = (186.0 * rustgis_map::layout::PT_PER_MM, 112.0 * rustgis_map::layout::PT_PER_MM); + let (x, _) = cam.try_to_screen(map.to_map(Coord::new(-44.8429, -22.4282)).unwrap(), fw, fh).unwrap(); + let ends: Vec<[f64; 2]> = + [0.0, fh].iter().map(|y| map.to_lonlat(cam.try_to_map(x, *y, fw, fh).unwrap()).unwrap()).map(|c| [c.x, c.y]).collect(); + let n = samples.values.len(); + assert!(n > 700, "a sample a cell: {n}"); + let got = s.run("profile.create", &json!({"layer": "DEM", "points": ends, "samples": n})).unwrap(); + let theirs: Vec = got["samples"].as_array().unwrap().iter().map(|r| r["elevation"].as_f64().unwrap()).collect(); + assert_eq!(theirs.len(), n); + let off = samples.values.iter().zip(&theirs).map(|(a, b)| (a.unwrap() - b).abs()).fold(0.0, f64::max); + assert!(off < 0.5, "{off} m apart"); + // Its length is the frame's height on the ground (112 mm at 1:200,000, the UTM scale factor + // aside) on the ellipsoid; profile.create's, on the sphere, a few tenths of a percent longer. + let (ours, theirs) = (*samples.metres.last().unwrap(), got["length"].as_f64().unwrap()); + assert!((ours / 22_400.0 - 1.0).abs() < 0.002, "{ours} m"); + assert!((theirs / ours - 1.0).abs() < 0.006, "{theirs} m against {ours} m"); +} diff --git a/crates/map/src/layout.rs b/crates/map/src/layout.rs index 708b4a516d..871d9f7b51 100644 --- a/crates/map/src/layout.rs +++ b/crates/map/src/layout.rs @@ -22,6 +22,7 @@ mod grid; mod legend; mod lines; mod north; +mod profile; mod scale_bar; mod section; mod stats; @@ -35,6 +36,7 @@ pub use grid::*; pub use legend::*; pub use lines::*; pub use north::*; +pub use profile::*; pub use scale_bar::*; pub use section::*; pub use stats::*; @@ -465,6 +467,31 @@ impl Layout { self.elements.len() != before } + /// Each map frame's box (x, y, w, h in mm), by its id. + fn frame_boxes(&self) -> BTreeMap { + let frames = self.elements.iter().filter(|e| matches!(e.kind, ElementKind::MapFrame { .. })); + frames.map(|e| (e.id, (e.x, e.y, e.w, e.h))).collect() + } + + /// Puts each profile beside its frame (#2863), as [`Profile::rect`] lays it, after the frame + /// was moved or resized, or the profile's side, gap or thickness changed. How many moved. + pub fn fit_profiles(&mut self) -> usize { + let boxes = self.frame_boxes(); + let mut moved = 0; + for e in &mut self.elements { + if let ElementKind::Profile(p) = &e.kind + && let Some(frame) = boxes.get(&p.frame) + { + let (x, y, w, h) = p.rect(*frame); + if (e.x, e.y, e.w, e.h) != (x, y, w, h) { + (e.x, e.y, e.w, e.h) = (x, y, w, h); + moved += 1; + } + } + } + moved + } + /// Keeps the page and elements sane after loading or editing (layout files are untrusted): /// sizes in range, unique element ids, and no references to missing frames. Returns what it /// changed, so a project reader can say so. @@ -663,6 +690,7 @@ impl Layout { *width = finite_or(*width, 1.0).clamp(0.0, 50.0) } ElementKind::Line { width, .. } => *width = finite_or(*width, 1.0).clamp(0.1, 50.0), + ElementKind::Profile(p) => cut |= p.clamp(), _ => {} } // A map frame draws its map and its paper itself: a background on one (a hand-edited @@ -681,6 +709,9 @@ impl Layout { // References must point at map frames that exist. let frames: std::collections::HashSet = self.elements.iter().filter(|e| matches!(e.kind, ElementKind::MapFrame { .. })).map(|e| e.id).collect(); + // A profile's box is its frame's side (#2863): one saved elsewhere (a hand-edited file) is + // put back beside it. + let boxes = self.frame_boxes(); let (mut adjusted, mut cut_count) = (0usize, 0usize); let elements = std::mem::take(&mut self.elements); for (mut e, (mut changed, cut)) in elements.into_iter().zip(changed) { @@ -693,6 +724,13 @@ impl Layout { *extent_of = None; changed = true; } + if let ElementKind::Profile(p) = &e.kind + && let Some(frame) = boxes.get(&p.frame) + { + let (x, y, w, h) = p.rect(*frame); + changed |= (e.x, e.y, e.w, e.h) != (x, y, w, h); + (e.x, e.y, e.w, e.h) = (x, y, w, h); + } adjusted = adjusted.saturating_add(usize::from(changed)); cut_count = cut_count.saturating_add(usize::from(cut)); self.elements.push(e); diff --git a/crates/map/src/layout/elements.rs b/crates/map/src/layout/elements.rs index e873b950b4..076ca1c042 100644 --- a/crates/map/src/layout/elements.rs +++ b/crates/map/src/layout/elements.rs @@ -361,6 +361,8 @@ pub enum ElementKind { #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::symbology::de_dash")] dash: Option, }, + /// A raster's profile along a section line of a map frame, beside the frame (#2863 part 2). + Profile(Profile), } pub(super) fn rows() -> usize { @@ -491,6 +493,7 @@ impl ElementKind { ElementKind::Rectangle { .. } => "rectangle", ElementKind::Ellipse { .. } => "ellipse", ElementKind::Line { .. } => "line", + ElementKind::Profile(_) => "profile", } } pub fn label(&self) -> &'static str { @@ -507,6 +510,7 @@ impl ElementKind { ElementKind::Rectangle { .. } => "Rectangle", ElementKind::Ellipse { .. } => "Ellipse", ElementKind::Line { .. } => "Line", + ElementKind::Profile(_) => "Profile", } } /// Whether an element of this kind takes a background (#2257): all but a map frame, which @@ -515,21 +519,31 @@ impl ElementKind { !matches!(self, ElementKind::MapFrame { .. }) } - /// Whether an element of this kind takes an ink (#2257): a legend, colorbar, table or chart, - /// whose text and lines are otherwise dark grey. The other kinds' colours are their own options. + /// Whether an element of this kind takes an ink (#2257): a legend, colorbar, table, chart or + /// profile, whose text and lines are otherwise dark grey. The other kinds' colours are their own + /// options. pub fn takes_ink(&self) -> bool { - matches!(self, ElementKind::Legend { .. } | ElementKind::Colorbar { .. } | ElementKind::Table { .. } | ElementKind::Chart { .. }) + matches!( + self, + ElementKind::Legend { .. } + | ElementKind::Colorbar { .. } + | ElementKind::Table { .. } + | ElementKind::Chart { .. } + | ElementKind::Profile(_) + ) } /// Whether `key` given as null changes an element of this kind, giving it back its default: /// an ink's `color`, a chart's `title` (the title it is given), `barColor`, `max` (its bars' /// own scale) and `barOutline` (none), a legend's or scale bar's `textSize` (#2581), and a - /// scale bar's `unitLabel` (its unit's abbreviation). + /// scale bar's `unitLabel` (its unit's abbreviation), and a profile's `fill` (none), `min` and + /// `max` (its samples' own). pub fn null_resets(&self, key: &str) -> bool { (self.takes_ink() && key == "color") || (matches!(self, ElementKind::Chart { .. }) && matches!(key, "title" | "barColor" | "max" | "barOutline")) || (matches!(self, ElementKind::Legend { .. } | ElementKind::ScaleBar { .. }) && key == "textSize") || (matches!(self, ElementKind::ScaleBar { .. }) && key == "unitLabel") + || (self.is_profile() && matches!(key, "fill" | "min" | "max")) } /// Its ink, when it [takes one](ElementKind::takes_ink) and has one; `None` draws in [`INK`]. @@ -538,7 +552,8 @@ impl ElementKind { ElementKind::Legend { color, .. } | ElementKind::Colorbar { color, .. } | ElementKind::Table { color, .. } - | ElementKind::Chart { color, .. } => *color, + | ElementKind::Chart { color, .. } + | ElementKind::Profile(Profile { color, .. }) => *color, _ => None, } } @@ -549,7 +564,8 @@ impl ElementKind { ElementKind::Legend { color, .. } | ElementKind::Colorbar { color, .. } | ElementKind::Table { color, .. } - | ElementKind::Chart { color, .. } => Some(color), + | ElementKind::Chart { color, .. } + | ElementKind::Profile(Profile { color, .. }) => Some(color), _ => None, } } @@ -576,6 +592,11 @@ impl ElementKind { matches!(self, ElementKind::MapFrame { sections, .. } if !sections.is_empty()) } + /// Whether it is a profile (#2863 part 2). + pub fn is_profile(&self) -> bool { + matches!(self, ElementKind::Profile(_)) + } + /// The map frame this element belongs to. pub fn frame(&self) -> Option { match self { @@ -584,7 +605,8 @@ impl ElementKind { | ElementKind::Legend { frame, .. } | ElementKind::Colorbar { frame, .. } | ElementKind::Table { frame, .. } - | ElementKind::Chart { frame, .. } => Some(*frame), + | ElementKind::Chart { frame, .. } + | ElementKind::Profile(Profile { frame, .. }) => Some(*frame), _ => None, } } diff --git a/crates/map/src/layout/profile.rs b/crates/map/src/layout/profile.rs new file mode 100644 index 0000000000..2938601c64 --- /dev/null +++ b/crates/map/src/layout/profile.rs @@ -0,0 +1,228 @@ +//! A raster's profile beside its map frame (#2863 part 2): along one of the frame's section lines, +//! on the side the line runs along, lined up with the map so that each point of the curve is +//! straight across from the place it comes from. + +use super::*; + +/// The side of its map frame a profile lies along: under or over it for a horizontal section line, +/// left or right of it for a vertical one. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ProfileSide { + #[default] + Bottom, + Top, + Left, + Right, +} + +impl ProfileSide { + pub const ALL: [ProfileSide; 4] = [ProfileSide::Bottom, ProfileSide::Top, ProfileSide::Left, ProfileSide::Right]; + + pub fn code(self) -> &'static str { + match self { + ProfileSide::Bottom => "bottom", + ProfileSide::Top => "top", + ProfileSide::Left => "left", + ProfileSide::Right => "right", + } + } + + pub fn from_name(s: &str) -> Option { + ProfileSide::ALL.into_iter().find(|v| v.code().eq_ignore_ascii_case(s.trim())) + } + + /// Whether it runs across the page: under or over the frame. + pub fn is_horizontal(self) -> bool { + matches!(self, ProfileSide::Bottom | ProfileSide::Top) + } + + /// Whether a profile of `line` can lie on this side: one that runs the same way as the line. + pub fn suits(self, line: SectionLine) -> bool { + self.is_horizontal() == matches!(line, SectionLine::Horizontal(_)) + } + + /// The side a profile of `line` takes unless given one: under a horizontal line's frame, right + /// of a vertical one's. + pub fn default_for(line: SectionLine) -> ProfileSide { + match line { + SectionLine::Horizontal(_) => ProfileSide::Bottom, + SectionLine::Vertical(_) => ProfileSide::Right, + } + } +} + +/// A profile element: the values of a raster's band along a section line of its map frame, drawn +/// beside the frame as a line, filled under it or not, with a value axis, a distance axis and the +/// section's names at its ends. Its box isn't its own: it takes the frame's side along its length +/// ([`Profile::rect`]), so it follows the frame when the frame is moved or resized. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Profile { + /// The map frame, and its section line (by name, any case). + pub frame: u32, + pub section: String, + /// The raster layer of the frame's map (by name, any case), and its band from 1. + pub layer: String, + #[serde(default = "first_band", skip_serializing_if = "is_first_band")] + pub band: u32, + #[serde(default)] + pub side: ProfileSide, + /// Millimetres between the frame and the profile, and across the profile. + #[serde(default = "profile_gap")] + pub gap: f64, + #[serde(default = "profile_thickness")] + pub thickness: f64, + /// Written over the curve ("Elevation"), and after the value axis' numbers ("m"). Left out + /// when empty. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub title: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub unit: String, + /// The curve's colour and width (points), and the colour under it; none, no fill. + #[serde(default = "profile_line")] + pub line_color: Rgba, + #[serde(default = "profile_line_width")] + pub line_width: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fill: Option, + /// The value axis' ends; none, the samples' own, out to round numbers. Two profiles given the + /// same share a scale. Read only when below the other end. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub min: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max: Option, + /// What the distance axis counts in, as a scale bar does. + #[serde(default, skip_serializing_if = "is_default")] + pub units: ScaleUnits, + /// Lines across the curve at the value axis' numbers. + #[serde(default = "yes", skip_serializing_if = "is_true")] + pub guides: bool, + /// The colour of its text and axes (#2257); none, the dark grey of [`INK`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, +} + +/// A new profile's gap and thickness (mm), and the least and most each may be. +pub const PROFILE_GAP: f64 = 3.0; +pub const PROFILE_GAPS: (f64, f64) = (0.0, 100.0); +pub const PROFILE_THICKNESS: f64 = 30.0; +pub const PROFILE_THICKNESSES: (f64, f64) = (10.0, 300.0); +/// A new profile's curve: its colour, width (points) and fill; and the least and most the width may be. +pub const PROFILE_LINE: Rgba = Rgba::rgb(0x3C, 0x32, 0x28); +pub const PROFILE_LINE_WIDTH: f64 = 1.0; +pub const PROFILE_LINE_WIDTHS: (f64, f64) = (0.1, 10.0); +pub const PROFILE_FILL: Rgba = Rgba::rgb(0xD8, 0xC8, 0xA8); +/// The longest title and unit (characters), and the highest band a profile names. +pub const MAX_PROFILE_TEXT: usize = 100; +pub const MAX_PROFILE_BAND: u32 = 65_535; +/// The most samples a profile reads along its section, as the `profile.*` commands. +pub const MAX_PROFILE_SAMPLES: usize = 10_000; + +fn first_band() -> u32 { + 1 +} + +fn is_first_band(b: &u32) -> bool { + *b == 1 +} + +fn is_true(v: &bool) -> bool { + *v +} + +fn profile_gap() -> f64 { + PROFILE_GAP +} + +fn profile_thickness() -> f64 { + PROFILE_THICKNESS +} + +fn profile_line() -> Rgba { + PROFILE_LINE +} + +fn profile_line_width() -> f64 { + PROFILE_LINE_WIDTH +} + +impl Profile { + /// A profile of `layer`'s first band along `section` of `frame`, on `side`, in the default look. + pub fn new(frame: u32, section: String, layer: String, side: ProfileSide) -> Profile { + Profile { + frame, + section, + layer, + band: 1, + side, + gap: PROFILE_GAP, + thickness: PROFILE_THICKNESS, + title: String::new(), + unit: String::new(), + line_color: PROFILE_LINE, + line_width: PROFILE_LINE_WIDTH, + fill: Some(PROFILE_FILL), + min: None, + max: None, + units: ScaleUnits::default(), + guides: true, + color: None, + } + } + + /// Its box (x, y, w, h in mm) beside a frame whose box is `frame`: the frame's length along its + /// side, `gap` from it and `thickness` across. + pub fn rect(&self, (fx, fy, fw, fh): (f64, f64, f64, f64)) -> (f64, f64, f64, f64) { + let (g, t) = (self.gap, self.thickness); + match self.side { + ProfileSide::Bottom => (fx, fy + fh + g, fw, t), + ProfileSide::Top => (fx, fy - g - t, fw, t), + ProfileSide::Right => (fx + fw + g, fy, t, fh), + ProfileSide::Left => (fx - g - t, fy, t, fh), + } + } + + /// The gap and thickness that put it at `rect` (x, y, w, h in mm), beside a frame whose box is + /// `frame`, as far as they can: what is along the frame stays the frame's ([`Profile::rect`]). + /// Whether either was held to its limits. + pub fn take_rect(&mut self, (fx, fy, fw, fh): (f64, f64, f64, f64), (x, y, w, h): (f64, f64, f64, f64)) -> bool { + let (gap, thickness) = match self.side { + ProfileSide::Bottom => (y - (fy + fh), h), + ProfileSide::Top => (fy - (y + h), h), + ProfileSide::Right => (x - (fx + fw), w), + ProfileSide::Left => (fx - (x + w), w), + }; + self.gap = finite_or(gap, self.gap); + self.thickness = finite_or(thickness, self.thickness); + let (g, t) = (self.gap, self.thickness); + self.clamp(); + (g, t) != (self.gap, self.thickness) + } + + /// Its numbers and texts brought into range (a layout file is hostile input). Whether a text was + /// cut. + pub(super) fn clamp(&mut self) -> bool { + self.gap = finite_or(self.gap, PROFILE_GAP).clamp(PROFILE_GAPS.0, PROFILE_GAPS.1); + self.thickness = finite_or(self.thickness, PROFILE_THICKNESS).clamp(PROFILE_THICKNESSES.0, PROFILE_THICKNESSES.1); + self.line_width = finite_or(self.line_width, PROFILE_LINE_WIDTH).clamp(PROFILE_LINE_WIDTHS.0, PROFILE_LINE_WIDTHS.1); + self.band = self.band.clamp(1, MAX_PROFILE_BAND); + self.min = self.min.filter(|v| v.is_finite()); + self.max = self.max.filter(|v| v.is_finite()); + let mut cut = false; + for (text, most) in [(&mut self.title, MAX_PROFILE_TEXT), (&mut self.unit, MAX_PROFILE_TEXT), (&mut self.section, MAX_SECTION_NAME)] + { + // One line: a break in a hand-edited file is a space. + let one = text.replace("\r\n", " ").replace(['\n', '\r'], " "); + cut |= one.trim().chars().nth(most).is_some(); + *text = one.trim().chars().take(most).collect::().trim_end().to_string(); + } + cut + } + + /// The value axis' ends given, when they make one (the least below the most). + pub fn given_range(&self) -> (Option, Option) { + match (self.min, self.max) { + (Some(lo), Some(hi)) if lo >= hi => (None, None), + given => given, + } + } +} diff --git a/crates/map/src/layout/tests.rs b/crates/map/src/layout/tests.rs index 0e9e307513..e4efbbc377 100644 --- a/crates/map/src/layout/tests.rs +++ b/crates/map/src/layout/tests.rs @@ -2012,3 +2012,94 @@ fn legend_class_labels_save_only_when_set_and_load_into_range() { let (saved, _, cut) = load(&json!({"a": many})); assert_eq!((saved["a"].as_object().unwrap().len(), cut), (MAX_LEGEND_LABELS, 1)); } + +/// A profile beside its frame (#2863 part 2): its box is the frame's side, which it takes back after +/// the frame moves or is resized, a box asked of it read as its gap and thickness; saved with only +/// what isn't its default, read back as saved; a hostile file's brought into range and counted, +/// and one saved elsewhere than its frame's side put back there. +#[test] +fn a_profile_keeps_to_its_frames_side() { + let frame = (30.0, 34.0, 186.0, 112.0); + for (side, rect) in [ + (ProfileSide::Bottom, (30.0, 149.0, 186.0, 30.0)), + (ProfileSide::Top, (30.0, 1.0, 186.0, 30.0)), + (ProfileSide::Right, (219.0, 34.0, 30.0, 112.0)), + (ProfileSide::Left, (-3.0, 34.0, 30.0, 112.0)), + ] { + let mut p = Profile::new(1, "A".into(), "DEM".into(), side); + assert_eq!(p.rect(frame), rect, "{side:?}"); + // Dragged off along the frame, 5 mm further from it and 4 mm thicker: only the gap and + // thickness follow. + let (x, y, w, h) = rect; + let moved = match side { + ProfileSide::Bottom => (x + 40.0, y + 5.0, w, h + 4.0), + ProfileSide::Top => (x + 40.0, y - 9.0, w, h + 4.0), + ProfileSide::Right => (x + 5.0, y + 40.0, w + 4.0, h), + ProfileSide::Left => (x - 9.0, y + 40.0, w + 4.0, h), + }; + assert!(!p.take_rect(frame, moved)); + assert_eq!((p.gap, p.thickness), (8.0, 34.0), "{side:?}"); + // Into the frame, or too thin: held. + assert!(p.take_rect(frame, if side.is_horizontal() { (x, 60.0, w, 2.0) } else { (100.0, y, 2.0, h) })); + assert_eq!((p.gap, p.thickness), (PROFILE_GAPS.0, PROFILE_THICKNESSES.0), "{side:?}"); + } + assert!(ProfileSide::Bottom.suits(SectionLine::Horizontal(Coord::new(0.0, 0.0)))); + assert!(!ProfileSide::Left.suits(SectionLine::Horizontal(Coord::new(0.0, 0.0)))); + assert_eq!(ProfileSide::default_for(SectionLine::Vertical(Coord::new(0.0, 0.0))), ProfileSide::Right); + // On the page, it follows its frame. + let mut l = Layout::new("L", 297.0, 210.0); + let f = l.add( + "Map", + frame, + ElementKind::MapFrame { + map: "M".into(), + center: Coord::new(0.0, 0.0), + scale: 1e6, + shape: FrameShape::Rectangle, + grid: None, + sections: vec![Section::new("A".into(), SectionLine::Horizontal(Coord::new(0.0, 0.0)))], + extent_of: None, + extent_color: INDICATOR_COLOR, + extent_width: INDICATOR_WIDTH, + border_color: FRAME_BORDER_COLOR, + border_width: FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }, + ); + let p = Profile::new(f, "A".into(), "DEM".into(), ProfileSide::Bottom); + let id = l.add("Profile", p.rect(frame), ElementKind::Profile(p)); + if let Some(e) = l.element_mut(f) { + (e.x, e.y, e.w) = (10.0, 20.0, 150.0); + } + assert_eq!(l.fit_profiles(), 1); + let e = l.element(id).unwrap(); + assert_eq!((e.x, e.y, e.w, e.h), (10.0, 135.0, 150.0, 30.0)); + assert_eq!(l.fit_profiles(), 0, "already beside it"); + // Saved with only what isn't its default; read back as saved; a repaired one needs nothing more. + let text = serde_json::to_string(&l).unwrap(); + let saved = text.split("\"Profile\":").nth(1).unwrap(); + for left_out in ["\"band\"", "\"min\"", "\"max\"", "\"units\"", "\"guides\"", "\"color\"", "\"title\"", "\"unit\""] { + assert!(!saved.contains(left_out), "{left_out} in {saved}"); + } + let back: Layout = serde_json::from_str(&text).unwrap(); + assert_eq!(back, l); + assert!(l.clamp().is_empty()); + // A hostile file: out of range, a text too long, saved away from its frame. + let hostile = text + .replace("\"gap\":3.0", "\"gap\":-1e9") + .replace("\"line_width\":1.0", "\"line_width\":1e9,\"band\":0,\"title\":\"x\\ny\",\"unit\":\"%UNIT%\"") + .replace("\"y\":135.0", "\"y\":0.0") + .replace("%UNIT%", &"m".repeat(MAX_PROFILE_TEXT + 5)); + let mut l: Layout = serde_json::from_str(&hostile).unwrap_or_else(|e| panic!("{e}: {hostile}")); + let repairs = l.clamp(); + assert_eq!((repairs.elements_adjusted, repairs.elements_cut), (1, 1), "{repairs:?}"); + let e = l.element(id).unwrap(); + let ElementKind::Profile(p) = &e.kind else { panic!("a profile") }; + assert_eq!((p.gap, p.line_width, p.band), (PROFILE_GAPS.0, PROFILE_LINE_WIDTHS.1, 1)); + assert_eq!((p.title.as_str(), p.unit.chars().count()), ("x y", MAX_PROFILE_TEXT)); + assert_eq!((e.x, e.y), (10.0, 132.0), "beside its frame again"); + assert!(l.clamp().is_empty(), "a repaired profile needs nothing more"); + // Its frame removed, it goes with it. + assert!(l.remove(f) && l.element(id).is_none()); +} diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 2a77925213..f0d879d265 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -28,6 +28,7 @@ mod grid; mod legend; mod losses; mod north; +mod profile; mod scale_bar; mod section; mod swatch; @@ -43,6 +44,7 @@ pub use grid::*; pub use legend::*; pub use losses::*; use north::*; +pub use profile::*; pub use scale_bar::*; pub use section::*; use swatch::*; @@ -672,6 +674,10 @@ fn draw_page( None => placeholder(&mut pm, r, "Chart", ppp), } } + ElementKind::Profile(p) => match profile_samples(layout, maps, p) { + Ok((samples, section)) => draw_profile(&mut pm, r, p, (&samples, §ion), layout.decimal_comma, ppp), + Err(_) => placeholder(&mut pm, r, "Profile", ppp), + }, ElementKind::Rectangle { fill, outline, width, radius, dash } => { // Square corners filled as before, so an existing layout draws to the same pixels. let rounded = rounded_rect(r, (*radius * PT_PER_MM * ppp) as f32); diff --git a/crates/render/src/layout/profile.rs b/crates/render/src/layout/profile.rs new file mode 100644 index 0000000000..a4b3a50429 --- /dev/null +++ b/crates/render/src/layout/profile.rs @@ -0,0 +1,423 @@ +//! A raster's profile beside its map frame (#2863 part 2): its samples along a section line, read +//! at each one's point of the page line through the frame's projection, what keeps one from being +//! drawn, and the curve with its axes, lined up with the frame. + +use rustgis_map::layout::{MAX_PROFILE_SAMPLES, Profile, ProfileSide}; + +use super::*; + +/// What a profile reads along its section line ([`profile_samples`]). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ProfileSamples { + /// Each sample's place along the frame's side, in the frame's points from its left (or top). + pub along: Vec, + /// Each sample's metres along the ground from the section line's start (its A end), on the + /// WGS 84 ellipsoid, between one sample and the next. + pub metres: Vec, + /// The band's value at each sample; `None` where it has no data. + pub values: Vec>, + /// The raster's cells along the section line, when there are more than the samples read + /// ([`MAX_PROFILE_SAMPLES`]). + pub cells: Option, +} + +impl ProfileSamples { + /// The least and most of the values read, if any. + pub fn range(&self) -> Option<(f64, f64)> { + let mut it = self.values.iter().flatten().copied(); + let first = it.next()?; + Some(it.fold((first, first), |(lo, hi), v| (lo.min(v), hi.max(v)))) + } +} + +/// How many points of the line a profile probes to count the raster's cells it crosses. +const CELL_PROBES: usize = 64; + +/// A profile's frame, section line and raster in `layout` over `maps`, and what it reads along +/// the line: a sample per cell of the raster it crosses (at most [`MAX_PROFILE_SAMPLES`]), each at +/// its point of the line on the page, taken back through the frame's projection to the ground and +/// read bilinearly there ([`rustgis_data::raster::Raster::bilinear`]), with no smoothing. +/// `Err` says why it draws nothing. +pub fn profile_samples(layout: &Layout, maps: &[Map], p: &Profile) -> Result<(ProfileSamples, Section), String> { + let frame = layout.element(p.frame).ok_or("its map frame is missing")?; + let ElementKind::MapFrame { map, center, scale, bearing, pitch, shape, sections, .. } = &frame.kind else { + return Err("its map frame is missing".into()); + }; + let map = map_index(maps, map).and_then(|i| maps.get(i)).ok_or("its frame's map is missing")?; + let section = Section::find(sections, &p.section) + .and_then(|i| sections.get(i)) + .ok_or_else(|| format!("its frame has no section line '{}'", p.section))?; + if !p.side.suits(section.line) { + return Err(format!( + "a {} section line's profile goes {}, not {}", + section.line.code(), + if p.side.is_horizontal() { "left or right of its frame" } else { "under or over its frame" }, + p.side.code() + )); + } + let cam = frame_camera(map, *center, *scale, *bearing, *pitch); + if map.projection.is_globe() || cam.pitch.abs() > 1e-9 { + return Err("its frame is tilted or on the globe, where a line straight on the page isn't a section of the ground".into()); + } + let layer = map + .layer_by_name(&p.layer) + .filter(|l| l.is_raster()) + .ok_or_else(|| format!("the frame's map has no raster layer '{}'", p.layer))?; + let rl = layer.raster.as_ref().ok_or_else(|| format!("the frame's map has no raster layer '{}'", p.layer))?; + if rl.in_place || rl.tiled { + return Err(format!("its layer '{}' is read in place, a part at a time, not held whole", layer.name)); + } + let r = rl.data.as_ref().ok_or_else(|| format!("its layer '{}' has no pixels read", layer.name))?; + if r.overview.is_some() { + return Err(format!("its layer '{}' holds only an overview of its file", layer.name)); + } + if !r.georeferenced { + return Err(format!("its layer '{}' isn't placed on the ground", layer.name)); + } + let band = usize::try_from(p.band).unwrap_or(usize::MAX).saturating_sub(1); + if band >= r.bands.len() { + return Err(format!("its layer '{}' has no band {} (it has {})", layer.name, p.band, r.bands.len())); + } + let (fw, fh) = (frame.w * PT_PER_MM, frame.h * PT_PER_MM); + let ends = section_ends(map, &cam, (fw, fh), shape, section.line) + .map_err(|why| format!("its section line '{}' isn't drawn: {why}", section.name))?; + // Along the line and across it: a vertical line is worked out with the axes swapped. + let vertical = matches!(section.line, SectionLine::Vertical(_)); + let swap = |(x, y): (f64, f64)| if vertical { (y, x) } else { (x, y) }; + let ((a, across), (b, _)) = (swap(ends[0]), swap(ends[1])); + let lonlat = |along: f64| { + let (x, y) = swap((along, across)); + cam.try_to_map(x, y, fw, fh).and_then(|m| map.to_lonlat(m)).filter(|c| c.x.is_finite() && c.y.is_finite()) + }; + // The cells the line crosses, counted along it in the raster's own grid. + let cell = |c: Coord| r.transformer().from_lonlat(c).map(|w| r.transform.to_pixel(w)); + let probes: Vec<(f64, f64)> = + (0..=CELL_PROBES).filter_map(|i| lonlat(a + (b - a) * i as f64 / CELL_PROBES as f64).and_then(cell)).collect(); + let crossed: f64 = probes.windows(2).map(|w| if let [p, q] = w { (q.0 - p.0).hypot(q.1 - p.1) } else { 0.0 }).sum(); + let cells = if crossed.is_finite() { crossed.ceil() as usize } else { 0 }; + let n = cells.saturating_add(1).clamp(2, MAX_PROFILE_SAMPLES); + let mut out = ProfileSamples { cells: (cells.saturating_add(1) > MAX_PROFILE_SAMPLES).then_some(cells), ..ProfileSamples::default() }; + let (mut metres, mut last) = (0.0, None); + for i in 0..n { + let along = a + (b - a) * i as f64 / (n - 1) as f64; + let at = lonlat(along); + if let (Some(p), Some(q)) = (last, at) { + metres += rustgis_geom::wgs84_distance_m(p, q); + } + last = at.or(last); + out.along.push(along); + out.metres.push(metres); + out.values.push(at.and_then(|c| r.bilinear(band, c))); + } + if out.values.iter().all(Option::is_none) { + return Err(format!("its layer '{}' has no data along section line '{}'", layer.name, section.name)); + } + Ok((out, section.clone())) +} + +/// A profile its layout doesn't draw, or draws from fewer samples than its raster's cells along +/// its section line ([`profile_samples`]). +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct ProfileNote { + /// The layout it is in, named where several are said together (a report's); empty otherwise. + pub layout: String, + pub element: u32, + pub name: String, + /// Why it isn't drawn; `None` for one drawn from fewer samples than cells. + pub why: Option, + /// With no `why`, the cells along its section line. + pub cells: usize, +} + +/// What `layout`'s visible profiles say as the page is now: those not drawn, and why, and those +/// read at fewer samples than their raster's cells along the line. +pub fn profiles_not_drawn(layout: &Layout, maps: &[Map]) -> Vec { + let profiles = layout.elements.iter().filter(|e| e.visible).filter_map(|e| match &e.kind { + ElementKind::Profile(p) => Some((e, p)), + _ => None, + }); + profiles + .filter_map(|(e, p)| { + let (why, cells) = match profile_samples(layout, maps, p) { + Err(why) => (Some(why), 0), + Ok((s, _)) => (None, s.cells?), + }; + Some(ProfileNote { layout: String::new(), element: e.id, name: e.name.clone(), why, cells }) + }) + .collect() +} + +/// What an export of `pages` pages says of its profiles ([`profiles_not_drawn`]), each with the +/// pages it is on: one notice for those not drawn, by reason, and one for those read at fewer +/// samples than cells; the profiles counted, the first ten named. +pub fn profiles_notice(notes: &BTreeMap, pages: usize) -> Vec { + let on = |n: usize| if pages > 1 { format!(" on {n} of {pages} pages") } else { String::new() }; + let list = |items: Vec| { + let more = items.len().saturating_sub(10); + let mut named = items.into_iter().take(10).collect::>().join("; "); + if more > 0 { + named.push_str(&format!("; and {more} more")); + } + named + }; + // A profile can be missing for one reason on some pages and another on others: one profile still. + let mut missing: BTreeMap<(&str, u32, &str), Vec> = BTreeMap::new(); + let mut thinned: BTreeMap<(&str, u32, &str), usize> = BTreeMap::new(); + for (n, count) in notes { + let key = (n.layout.as_str(), n.element, n.name.as_str()); + match &n.why { + Some(why) => missing.entry(key).or_default().push(format!("{}: {why}", on(*count))), + None => { + let most = thinned.entry(key).or_default(); + *most = (*most).max(n.cells); + } + } + } + let named = |(layout, id, name): (&str, u32, &str)| { + if layout.is_empty() { format!("'{name}' ({id})") } else { format!("'{name}' ({id}) in layout '{layout}'") } + }; + let mut out = Vec::new(); + if !missing.is_empty() { + let count = missing.len(); + let items = missing.into_iter().map(|(key, why)| format!("{}{}", named(key), why.join(","))).collect(); + out.push(format!("{count} profile(s) not drawn: {}", list(items))); + } + if !thinned.is_empty() { + let count = thinned.len(); + let items = thinned.into_iter().map(|(key, cells)| format!("{}, across {cells} cells", named(key))).collect(); + out.push(format!( + "{count} profile(s) read at {MAX_PROFILE_SAMPLES} samples, fewer than their raster's cells along the line: {}", + list(items) + )); + } + out +} + +/// The size of a profile's numbers, its title and its section's names, in points. +const PROFILE_LABEL_PT: f32 = 7.0; +const PROFILE_TITLE_PT: f32 = 7.5; +const PROFILE_NAME_PT: f32 = 8.0; + +/// A round step that splits `span` into about `parts`: 1, 2 or 5 times a power of ten. +fn round_step(span: f64, parts: f64) -> f64 { + let rough = (span / parts).abs(); + if !(rough.is_finite() && rough > 0.0) { + return 1.0; + } + let p = 10f64.powf(rough.log10().floor()); + [1.0, 2.0, 5.0, 10.0].iter().map(|k| k * p).find(|s| *s >= rough * 0.999).unwrap_or(10.0 * p) +} + +/// `v` written with the decimals a step of `step` needs, with a decimal comma when `comma`. +fn number(v: f64, step: f64, comma: bool) -> String { + let decimals = if step >= 1.0 || step <= 0.0 { 0 } else { (-step.log10().floor()).clamp(0.0, 6.0) as usize }; + let k = 10f64.powi(decimals as i32); + decimal(format!("{:.*}", decimals, (v * k).round() / k + 0.0), comma) +} + +/// The value axis' ends and step for a profile whose samples run from `lo` to `hi`, the ends it is +/// given taking their place: each end not given out to a round number past the samples. +pub(super) fn value_axis(p: &Profile, (lo, hi): (f64, f64)) -> (f64, f64, f64) { + let (min, max) = p.given_range(); + let (lo, hi) = (min.unwrap_or(lo), max.unwrap_or(hi)); + let (lo, hi) = if hi > lo { (lo, hi) } else { (lo - (lo.abs() * 0.1).max(1.0), hi + (hi.abs() * 0.1).max(1.0)) }; + let step = round_step(hi - lo, 4.0); + let lo = min.unwrap_or_else(|| (lo / step).floor() * step); + let hi = max.unwrap_or_else(|| (hi / step).ceil() * step); + (lo, hi.max(lo + step * 1e-6), step) +} + +/// A profile in `r` (pixels, at `ppp` pixels a point): the frame's side along its length, so a +/// sample `along` points from the frame's start is drawn at `along` × `ppp` pixels from the +/// element's. Along a horizontal side the values rise up the page; along a vertical one, away from +/// the frame. The distance axis runs under the curve (beside it, on the frame's side, for a +/// vertical one), the section's names at its ends over it, and the value axis' numbers on its +/// guide lines at the start (at the end for a vertical one). +pub(super) fn draw_profile(pm: &mut Canvas, r: Rect, p: &Profile, (samples, section): (&ProfileSamples, &Section), comma: bool, ppp: f64) { + let k = ppp as f32; + let ink = p.color.unwrap_or(INK); + let label_px = PROFILE_LABEL_PT * 1.33 * k; + let name_px = PROFILE_NAME_PT * 1.33 * k; + let title_px = PROFILE_TITLE_PT * 1.33 * k; + let width = |s: &str, px: f32, bold: bool| text::measure(s, px / 1.33, bold); + let horizontal = p.side.is_horizontal(); + let (start, length, thick) = if horizontal { (r.x(), r.width(), r.height()) } else { (r.y(), r.height(), r.width()) }; + // The distance axis' numbers, in the unit that reads best over the whole line. + let total = samples.metres.last().copied().unwrap_or(0.0); + let (unit_m, abbr) = p.units.resolve(total); + let step_d = round_step(total / unit_m, 5.0); + let ticks: Vec<(f32, String)> = (0..=200) + .map(|i| f64::from(i) * step_d) + .take_while(|d| *d * unit_m <= total * (1.0 + 1e-9)) + .filter_map(|d| along_at(samples, d * unit_m).map(|a| (a as f32 * k, number(d, step_d, comma)))) + .collect(); + let tick = 3.0 * k; + let widest = ticks.iter().map(|(_, s)| width(&format!("{s} {abbr}"), label_px, false)).fold(0.0, f32::max); + // The strips the distance axis and the names take, across the profile. + let axis = if horizontal { tick + label_px * 1.3 } else { tick + widest + 2.0 * k }; + let names = [section.name.clone(), format!("{}'", section.name)]; + let head = if horizontal { name_px * 1.5 } else { names.iter().map(|n| width(n, name_px, true)).fold(0.0, f32::max) + 3.0 * k }; + let plot = thick - axis - head; + if plot < 2.0 * k { + placeholder(pm, r, "Profile", ppp); + return; + } + // A point `u` pixels along the profile and `v` above its base, on the page. + let page = |u: f32, v: f32| match p.side { + ProfileSide::Bottom | ProfileSide::Top => (r.x() + u, r.y() + r.height() - axis - v), + ProfileSide::Right => (r.x() + axis + v, r.y() + u), + ProfileSide::Left => (r.x() + r.width() - axis - v, r.y() + u), + }; + let Some((lo_v, hi_v)) = samples.range() else { return }; + let (lo, hi, step) = value_axis(p, (lo_v, hi_v)); + let v_of = |val: f64| (((val - lo) / (hi - lo)) as f32 * plot).clamp(0.0, plot); + let line = |pts: &[(f32, f32)]| { + let mut pb = PathBuilder::new(); + for (i, &(u, v)) in pts.iter().enumerate() { + let (x, y) = page(u, v); + if i == 0 { pb.move_to(x, y) } else { pb.line_to(x, y) } + } + pb.finish() + }; + let thin = |pm: &mut Canvas, pts: &[(f32, f32)], colour: Rgba, w: f32| { + if let Some(path) = line(pts) { + pm.stroke_path(&path, &paint(colour, 1.0), &Stroke { width: w, ..Stroke::default() }, Transform::identity(), None); + } + }; + // Guide lines at the round values, under the curve. + let guides: Vec = (0..=40).map(|i| ((lo / step).ceil() + f64::from(i)) * step).take_while(|g| *g <= hi + step * 1e-9).collect(); + if p.guides { + for g in guides.iter().filter(|g| **g > lo + step * 1e-9) { + thin(pm, &[(0.0, v_of(*g)), (length, v_of(*g))], ink.with_alpha(70), 0.35 * k); + } + } + // The curve, a run between gaps in the data at a time, filled down to the base or not. + let runs = samples.along.iter().zip(&samples.values).map(|(a, v)| v.map(|v| (*a as f32 * k, v_of(v)))); + let mut pieces: Vec> = vec![Vec::new()]; + for pt in runs { + match (pt, pieces.last_mut()) { + (Some(pt), Some(run)) => run.push(pt), + (None, Some(run)) if !run.is_empty() => pieces.push(Vec::new()), + _ => {} + } + } + for run in pieces.iter().filter(|r| !r.is_empty()) { + if let (Some(fill), Some(first), Some(last)) = (p.fill, run.first(), run.last()) { + let mut pb = PathBuilder::new(); + let (x, y) = page(first.0, 0.0); + pb.move_to(x, y); + for (x, y) in run.iter().chain([&(last.0, 0.0)]).map(|&(u, v)| page(u, v)) { + pb.line_to(x, y); + } + pb.close(); + if let Some(area) = pb.finish() { + pm.fill_path(&area, &paint(fill, 1.0), FillRule::Winding, Transform::identity(), None); + } + } + if run.len() > 1 + && let Some(path) = line(run) + { + let stroke = Stroke { + width: p.line_width as f32 * k, + line_join: tiny_skia::LineJoin::Round, + line_cap: tiny_skia::LineCap::Round, + ..Stroke::default() + }; + pm.stroke_path(&path, &paint(p.line_color, 1.0), &stroke, Transform::identity(), None); + } + } + // The base and the distance axis: a tick and a number at each round distance, the unit after + // the last, each number clear of the one before and inside the element. + thin(pm, &[(0.0, 0.0), (length, 0.0)], ink, 0.6 * k); + let mut before = f32::NEG_INFINITY; + let last = ticks.len().saturating_sub(1); + for (i, (u, s)) in ticks.iter().enumerate() { + thin(pm, &[(*u, 0.0), (*u, -tick)], ink, 0.5 * k); + let s = if i == last { format!("{s} {abbr}") } else { s.clone() }; + let (x, y) = page(*u, -tick); + if horizontal { + let half = width(&s, label_px, false) / 2.0 + k; + let cx = (x).clamp(r.x() + half, (r.x() + r.width() - half).max(r.x() + half)); + if cx - half < before { + continue; + } + before = cx + half; + text::text_at(pm, &s, cx, y + label_px * 0.65, label_px, ink, false, text::Align::Center, false); + } else { + let half = label_px * 0.6; + let cy = y.clamp(r.y() + half, (r.y() + r.height() - half).max(r.y() + half)); + if cy - half < before { + continue; + } + before = cy + half; + let (tx, align) = if p.side == ProfileSide::Right { (x - k, text::Align::Right) } else { (x + k, text::Align::Left) }; + text::text_at(pm, &s, tx, cy, label_px, ink, false, align, false); + } + } + // The value axis' numbers, on their guides (the base's on it): at the start along a + // horizontal side, at the end along a vertical one, each clear of the one before. + let unit = if p.unit.trim().is_empty() { String::new() } else { format!(" {}", p.unit.trim()) }; + let mut before = f32::NEG_INFINITY; + for g in &guides { + let s = format!("{}{unit}", number(*g, step, comma)); + let v = v_of(*g); + if horizontal { + let (_, y) = page(0.0, v); + let cy = y - label_px * 0.55; + // Stacked up the page: each over the one before. + if before.is_finite() && cy + label_px * 0.5 > before { + continue; + } + before = cy - label_px * 0.5; + text::text_at(pm, &s, start + 2.0 * k, cy, label_px, ink, false, text::Align::Left, true); + } else { + let (x, _) = page(length, v); + let half = width(&s, label_px, false) / 2.0 + k; + // Side by side away from the frame: each past the one before. + let (lo_x, hi_x) = if p.side == ProfileSide::Right { (x - half, x + half) } else { (-(x + half), -(x - half)) }; + if lo_x < before || x - half < r.x() || x + half > r.x() + r.width() { + continue; + } + before = hi_x; + text::text_at(pm, &s, x, r.y() + r.height() - label_px * 0.6, label_px, ink, false, text::Align::Center, true); + } + } + // The section's names at the ends, in its colour, and the title after the first. + let [first, second] = names; + let colour = section.color.with_alpha(255); + if horizontal { + let cy = r.y() + head / 2.0; + text::text_at(pm, &first, start + 2.0 * k, cy, name_px, colour, true, text::Align::Left, false); + text::text_at(pm, &second, start + length - 2.0 * k, cy, name_px, colour, true, text::Align::Right, false); + if !p.title.trim().is_empty() { + let x = start + 2.0 * k + width(&first, name_px, true) + 4.0 * k; + text::text_at(pm, p.title.trim(), x, cy, title_px, ink, true, text::Align::Left, false); + } + } else { + let (cx, align) = + if p.side == ProfileSide::Right { (r.x() + r.width() - k, text::Align::Right) } else { (r.x() + k, text::Align::Left) }; + text::text_at(pm, &first, cx, start + name_px * 0.7, name_px, colour, true, align, false); + text::text_at(pm, &second, cx, start + length - name_px * 0.7, name_px, colour, true, align, false); + if !p.title.trim().is_empty() { + let (x, _) = page(0.0, plot); + let align = if p.side == ProfileSide::Right { text::Align::Right } else { text::Align::Left }; + text::text_at(pm, p.title.trim(), x, start + name_px * 2.0, title_px, ink, true, align, true); + } + } +} + +/// The place along the frame's side (points) where the ground distance from the section's start is +/// `metres`, between the samples around it; `None` past the last. +fn along_at(s: &ProfileSamples, metres: f64) -> Option { + let i = s.metres.partition_point(|m| *m < metres); + match (i.checked_sub(1).and_then(|j| s.metres.get(j).zip(s.along.get(j))), s.metres.get(i).zip(s.along.get(i))) { + (_, Some((m, a))) if (*m - metres).abs() < 1e-9 => Some(*a), + (Some((m0, a0)), Some((m1, a1))) if m1 > m0 => Some(a0 + (a1 - a0) * (metres - m0) / (m1 - m0)), + (None, Some((_, a))) => Some(*a), + _ => None, + } +} + +#[cfg(test)] +#[path = "profile_tests.rs"] +mod tests; diff --git a/crates/render/src/layout/profile_tests.rs b/crates/render/src/layout/profile_tests.rs new file mode 100644 index 0000000000..6c92250d77 --- /dev/null +++ b/crates/render/src/layout/profile_tests.rs @@ -0,0 +1,254 @@ +use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; +use rustgis_map::Projection; +use rustgis_map::layout::{FRAME_BORDER_COLOR, FRAME_BORDER_WIDTH, INDICATOR_COLOR, INDICATOR_WIDTH}; + +use super::*; + +/// The Mantiqueira frame of #2863: 186 × 112 mm at 1:200,000 round the Agulhas Negras, in UTM 23S. +const CENTER: Coord = Coord::new(-44.715, -22.412); +const AGULHAS_NEGRAS: Coord = Coord::new(-44.6615, -22.3802); +const PEDRA_DA_MINA: Coord = Coord::new(-44.8429, -22.4282); +const UTM: &str = "EPSG:31983"; +const FRAME_MM: (f64, f64, f64, f64) = (30.0, 34.0, 186.0, 112.0); + +/// A 30 m grid in UTM 23S over the frame and round it, each cell `z` of its centre's easting and +/// northing. +fn dem(z: impl Fn(f64, f64) -> f64) -> Raster { + let crs = Crs::from_epsg(31983).unwrap(); + let mid = crs.transformer().unwrap().from_lonlat(CENTER).unwrap(); + let (cols, rows, cell) = (1600usize, 1000usize, 30.0); + let (x0, y0) = (((mid.x - 24_000.0) / cell).round() * cell, ((mid.y + 15_000.0) / cell).round() * cell); + let data = (0..rows * cols).map(|i| z(x0 + ((i % cols) as f64 + 0.5) * cell, y0 - ((i / cols) as f64 + 0.5) * cell) as f32).collect(); + let gt = GeoTransform { origin_x: x0, origin_y: y0, pixel_width: cell, pixel_height: -cell }; + Raster::new("dem", cols as u32, rows as u32, vec![data], gt, crs, None, ColorHint::Gray, "Float32").unwrap() +} + +/// A map in UTM 23S with `dem` as its layer "DEM". +fn utm_map(dem: Raster) -> Map { + let mut map = Map::new("m"); + map.projection = Projection::Custom(UTM.into()); + map.add_raster("DEM", rustgis_map::RasterLayer::from_path(dem, "dem.tif")); + map +} + +fn frame_kind(sections: Vec
, bearing: f64, pitch: f64) -> ElementKind { + ElementKind::MapFrame { + map: "m".into(), + center: CENTER, + scale: 200_000.0, + shape: FrameShape::Rectangle, + grid: None, + sections, + extent_of: None, + extent_color: INDICATOR_COLOR, + extent_width: INDICATOR_WIDTH, + border_color: FRAME_BORDER_COLOR, + border_width: FRAME_BORDER_WIDTH, + bearing, + pitch, + } +} + +/// A page with the Mantiqueira frame, its section line `line` named A, and a profile of "DEM" along +/// it on `side`; the profile's id. +fn page(line: SectionLine, side: ProfileSide, (bearing, pitch): (f64, f64)) -> (Layout, u32) { + let mut l = Layout::new("L", 297.0, 210.0); + let frame = l.add("Map", FRAME_MM, frame_kind(vec![Section::new("A".into(), line)], bearing, pitch)); + let p = Profile { title: String::new(), ..Profile::new(frame, "A".into(), "DEM".into(), side) }; + let id = l.add("Profile", p.rect(FRAME_MM), ElementKind::Profile(p)); + (l, id) +} + +fn profile_of(l: &Layout, id: u32) -> &Profile { + match l.element(id).map(|e| &e.kind) { + Some(ElementKind::Profile(p)) => p, + _ => panic!("a profile"), + } +} + +/// A profile is read along the page's line through the frame's projection, not along a straight line +/// of longitude and latitude: on a grid whose value is its northing, a horizontal section line of a +/// UTM frame reads one value end to end, and a vertical one on a grid of eastings too. Its samples +/// run from the frame's one edge to the other, a cell of 30 m apart, their distances adding up to +/// the frame's width on the ground. +#[test] +fn a_profile_is_read_along_the_line_on_the_page() { + let fw = FRAME_MM.2 * PT_PER_MM; + for (line, z, side) in [ + (SectionLine::Horizontal(AGULHAS_NEGRAS), (|_, n| n - 7_500_000.0) as fn(f64, f64) -> f64, ProfileSide::Bottom), + (SectionLine::Vertical(PEDRA_DA_MINA), |e, _| e - 500_000.0, ProfileSide::Right), + ] { + let maps = vec![utm_map(dem(z))]; + let (l, id) = page(line, side, (0.0, 0.0)); + let (s, section) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); + assert_eq!(section.name, "A"); + let (lo, hi) = s.range().unwrap(); + assert!(hi - lo < 0.05, "{line:?}: {lo} to {hi}"); + let length = if side.is_horizontal() { fw } else { FRAME_MM.3 * PT_PER_MM }; + let (first, last) = (s.along.first().copied().unwrap(), s.along.last().copied().unwrap()); + assert!(first.abs() < 1e-6 && (last - length).abs() < 1e-6, "{first} {last}"); + let ground = length / PT_PER_MM * 200.0; + let total = s.metres.last().copied().unwrap(); + assert!((total / ground - 1.0).abs() < 0.005, "{total} m for {ground} m"); + let n = s.values.len() as f64; + assert!((n - ground / 30.0).abs() < 0.02 * n, "{n} samples"); + assert!(s.cells.is_none() && s.values.iter().all(Option::is_some)); + } + // A turned frame reads the line the page shows: turned a quarter, its horizontal runs north to + // south, its northings falling a metre a metre of ground where the grid (30 km from north to + // south) has them. + let maps = vec![utm_map(dem(|_, n| n))]; + let (l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (90.0, 0.0)); + let (s, _) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); + let read: Vec<(f64, f64)> = s.metres.iter().zip(&s.values).filter_map(|(m, v)| Some((*m, (*v)?))).collect(); + assert!(read.len() > 900, "{} read", read.len()); + for w in read.windows(2) { + let [(m0, v0), (m1, v1)] = w else { continue }; + assert!(((v0 - v1) / (m1 - m0) - 1.0).abs() < 0.01, "{m0}: {v0}, {m1}: {v1}"); + } +} + +/// The page's line, not a straight line between its ends' longitudes and latitudes: between the +/// ends of the horizontal section line of the Mantiqueira, a straight line of longitude and +/// latitude strays metres off the line on the page, which a profile doesn't (#2863). +#[test] +fn the_page_line_is_not_a_straight_line_of_longitude_and_latitude() { + let maps = vec![utm_map(dem(|_, n| n))]; + let (l, id) = page(SectionLine::Horizontal(AGULHAS_NEGRAS), ProfileSide::Bottom, (0.0, 0.0)); + let (s, _) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); + let map = maps.first().unwrap(); + let cam = frame_camera(map, CENTER, 200_000.0, 0.0, 0.0); + let (fw, fh) = (FRAME_MM.2 * PT_PER_MM, FRAME_MM.3 * PT_PER_MM); + let (_, y) = cam.try_to_screen(map.to_map(AGULHAS_NEGRAS).unwrap(), fw, fh).unwrap(); + let ll = |x: f64| map.to_lonlat(cam.try_to_map(x, y, fw, fh).unwrap()).unwrap(); + let (a, b) = (ll(0.0), ll(fw)); + let r = &map.layers.first().unwrap().raster.as_ref().unwrap().data.clone().unwrap(); + let chord = (0..=100).map(|i| { + let t = f64::from(i) / 100.0; + r.bilinear(0, Coord::new(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t)).unwrap() + }); + let along = s.values.first().copied().flatten().unwrap(); + let off = chord.map(|v| (v - along).abs()).fold(0.0, f64::max); + assert!(off > 1.0, "the chord strays {off} m"); + assert!(s.values.iter().flatten().all(|v| (v - along).abs() < 0.05)); +} + +/// The middle of the pixels `at` (a run along the profile, its curve flat at its top), at their +/// centres. +fn middle(at: impl Iterator) -> f64 { + let at: Vec = at.collect(); + at.iter().map(|v| f64::from(*v) + 0.5).sum::() / at.len().max(1) as f64 +} + +/// A profile's highest point is drawn straight under the place it comes from, and straight beside it +/// for a vertical section line, whichever way the frame is turned. +#[test] +fn a_profiles_peak_is_drawn_straight_across_from_its_place() { + let crs = Crs::from_epsg(31983).unwrap(); + let peak_at = crs.transformer().unwrap().from_lonlat(AGULHAS_NEGRAS).unwrap(); + let peak = + move |e: f64, n: f64| 1000.0 + 1500.0 * (-((e - peak_at.x).powi(2) + (n - peak_at.y).powi(2)) / (2.0 * 900.0f64.powi(2))).exp(); + for (line, side, bearing) in [ + (SectionLine::Horizontal(AGULHAS_NEGRAS), ProfileSide::Bottom, 0.0), + (SectionLine::Horizontal(AGULHAS_NEGRAS), ProfileSide::Top, 25.0), + (SectionLine::Vertical(AGULHAS_NEGRAS), ProfileSide::Right, 0.0), + (SectionLine::Vertical(AGULHAS_NEGRAS), ProfileSide::Left, -15.0), + ] { + let mut maps = vec![utm_map(dem(peak))]; + let (mut l, id) = page(line, side, (bearing, 0.0)); + if let Some(ElementKind::Profile(p)) = l.element_mut(id).map(|e| &mut e.kind) { + (p.guides, p.fill) = (false, None); + } + // Where the frame shows the peak, in the page's pixels at 2 a point. + let map = maps.first().unwrap(); + let (fw, fh) = (FRAME_MM.2 * PT_PER_MM, FRAME_MM.3 * PT_PER_MM); + let cam = frame_camera(map, CENTER, 200_000.0, bearing, 0.0); + let (px, py) = cam.try_to_screen(map.to_map(AGULHAS_NEGRAS).unwrap(), fw, fh).unwrap(); + let dpi = 192.0; + let pm = render(&l, &mut maps, dpi, &PageInfo::default()).unwrap(); + let (_, _, k) = page_geometry(&l, dpi); + let ppp = k / PT_PER_MM; + let e = l.element(id).unwrap(); + let (x0, y0, x1, y1) = ((e.x * k) as u32, (e.y * k) as u32, ((e.x + e.w) * k) as u32, ((e.y + e.h) * k) as u32); + let dark = |x: u32, y: u32| pm.pixel(x, y).is_some_and(|p| p.red() < 90 && p.green() < 90 && p.blue() < 90 && p.alpha() > 200); + // The curve's point farthest from its base, in the middle of the profile (its numbers and + // names are at its ends). + let found = if side.is_horizontal() { + let (lo, hi) = (x0 + (x1 - x0) / 5, x1 - (x1 - x0) / 5); + let top = |x: u32| (y0..y1).find(|y| dark(x, *y)).unwrap_or(y1); + let highest = (lo..hi).map(top).min().unwrap(); + middle((lo..hi).filter(|x| top(*x) == highest)) - FRAME_MM.0 * k - px * ppp + } else { + let (lo, hi) = (y0 + (y1 - y0) / 5, y1 - (y1 - y0) / 5); + let reach = |y: u32| match side { + ProfileSide::Right => (x0..x1).rev().find(|x| dark(*x, y)).map_or(0, |x| x - x0), + _ => (x0..x1).find(|x| dark(*x, y)).map_or(0, |x| x1 - x), + }; + let farthest = (lo..hi).map(reach).max().unwrap(); + middle((lo..hi).filter(|y| reach(*y) == farthest)) - FRAME_MM.1 * k - py * ppp + }; + assert!(found.abs() <= 3.0, "{side:?} turned {bearing}: {found} pixels off"); + } +} + +/// What keeps a profile from being drawn is said, one notice with each profile and why: a tilted +/// frame, a section line running the other way, a band the raster hasn't, a raster read in place, a +/// section line that isn't there, and no data along the line. A drawable one says nothing. +#[test] +fn a_profile_not_drawn_says_why() { + let notes = |l: &Layout, maps: &[Map]| { + let n = profiles_not_drawn(l, maps); + profiles_notice(&n.into_iter().map(|n| (n, 1)).collect(), 1) + }; + let maps = vec![utm_map(dem(|_, n| n))]; + let (l, _) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); + assert!(notes(&l, &maps).is_empty(), "{:?}", notes(&l, &maps)); + let (tilted, _) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 40.0)); + let said = notes(&tilted, &maps); + assert!(said.len() == 1 && said[0].starts_with("1 profile(s) not drawn: 'Profile' (2): its frame is tilted"), "{said:?}"); + let (across, _) = page(SectionLine::Horizontal(CENTER), ProfileSide::Right, (0.0, 0.0)); + assert!(notes(&across, &maps)[0].contains("a horizontal section line's profile goes under or over its frame, not right")); + let change = |f: &dyn Fn(&mut Profile)| { + let (mut l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); + if let Some(ElementKind::Profile(p)) = l.element_mut(id).map(|e| &mut e.kind) { + f(p); + } + notes(&l, &maps).join(" | ") + }; + assert!(change(&|p| p.band = 2).contains("its layer 'DEM' has no band 2 (it has 1)")); + assert!(change(&|p| p.section = "B".into()).contains("its frame has no section line 'B'")); + assert!(change(&|p| p.layer = "Other".into()).contains("the frame's map has no raster layer 'Other'")); + let mut in_place = utm_map(dem(|_, n| n)); + if let Some(r) = in_place.layers.first_mut().and_then(|l| l.raster.as_mut()) { + r.in_place = true; + } + assert!(notes(&l, &[in_place]).join("").contains("is read in place, a part at a time, not held whole")); + let empty = vec![utm_map(dem(|_, _| f64::NAN))]; + assert!(notes(&l, &empty).join("").contains("has no data along section line 'A'")); + // Drawn, it draws its placeholder otherwise. + let mut maps = maps; + assert!(render(&tilted, &mut maps, 96.0, &PageInfo::default()).is_ok()); +} + +/// A gap in the data breaks the curve, and a value axis given keeps to it: the samples' own ends +/// otherwise, out to round numbers. +#[test] +fn a_profiles_value_axis_is_round_or_given() { + let base = Profile::new(1, "A".into(), "DEM".into(), ProfileSide::Bottom); + assert_eq!(value_axis(&base, (412.0, 2_791.0)), (0.0, 3_000.0, 1_000.0)); + let (lo, hi, step) = value_axis(&base, (12.3, 12.9)); + assert!((lo - 12.2).abs() < 1e-9 && (hi - 13.0).abs() < 1e-9 && (step - 0.2).abs() < 1e-12, "{lo} {hi} {step}"); + let given = Profile { min: Some(400.0), max: Some(2_900.0), ..base.clone() }; + assert_eq!(value_axis(&given, (412.0, 2_791.0)).0, 400.0); + assert_eq!(value_axis(&given, (412.0, 2_791.0)).1, 2_900.0); + // Flat, it still has a span. + let (lo, hi, _) = value_axis(&base, (5.0, 5.0)); + assert!(lo < 5.0 && hi > 5.0); + // A gap of no data along the line: two runs, each drawn. + let mid = Crs::from_epsg(31983).unwrap().transformer().unwrap().from_lonlat(CENTER).unwrap().x; + let maps = vec![utm_map(dem(move |e, _| if (e - mid).abs() < 2_000.0 { f64::NAN } else { 100.0 }))]; + let (l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); + let (s, _) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); + let runs = s.values.windows(2).filter(|w| w[0].is_some() != w[1].is_some()).count(); + assert_eq!(runs, 2, "a gap in the middle"); +} diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index fa590268e9..c42d870ef7 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -1241,6 +1241,23 @@ pub fn paint(painter: &Painter, r: Rect, name: &str, ink: Color32, accent: Color p.line(&[(12.0, y), (18.0, y)], 1.1, ink); } } + // A ridge's profile over its base and distance ticks, a dashed section line above it. + "layout_profile" => { + let ridge = [(3.0, 15.0), (6.0, 12.0), (9.0, 13.0), (12.5, 7.0), (15.5, 10.0), (18.0, 9.0), (21.0, 14.0)]; + for w in ridge.windows(2) { + if let [a, b] = w { + p.fill(&[(a.0, 17.0), *a, *b, (b.0, 17.0)], p.tint(60)); + } + } + p.line(&ridge, 1.4, ink); + p.line(&[(3.0, 17.0), (21.0, 17.0)], 1.2, ink); + for x in [3.0, 9.0, 15.0, 21.0] { + p.line(&[(x, 17.0), (x, 19.5)], 1.0, ink); + } + for x in [3.0, 8.0, 13.0, 18.0] { + p.line(&[(x, 4.0), (x + 3.0, 4.0)], 1.3, accent); + } + } // A gradient bar over its tick marks. "colorbar" => { for i in 0..9 { @@ -1363,6 +1380,7 @@ pub const ALL: &[&str] = &[ "stats", "chart", "colorbar", + "layout_profile", "count", "calc_geom", "table", diff --git a/crates/ui-egui/src/layoutview.rs b/crates/ui-egui/src/layoutview.rs index fa0c974c9c..ae69a7c938 100644 --- a/crates/ui-egui/src/layoutview.rs +++ b/crates/ui-egui/src/layoutview.rs @@ -119,6 +119,9 @@ pub struct LayoutView { text_warning: Option, /// The last notice of the section lines the page's frames don't draw. section_warning: Option, + /// The last notices of the profiles the page doesn't draw, or draws from fewer samples than + /// cells (#2863). + profile_warning: Vec, /// The texts of the layout drawn (by its index) cut off on its page, with their lines left /// out of their box, as the Format pane tells them (#2346). text_losses: Option<(usize, Vec)>, @@ -212,6 +215,7 @@ pub(crate) fn follow_project(app: &mut RustGisApp) { app.layout.viewed = None; app.layout.text_warning = None; app.layout.section_warning = None; + app.layout.profile_warning.clear(); app.layout.text_losses = None; app.layout.views.clear(); } @@ -289,6 +293,7 @@ impl LayoutView { } self.text_warning = None; self.section_warning = None; + self.profile_warning.clear(); self.text_losses = None; if let Some(old) = self.viewed.replace(name.to_string()) { self.views.insert(old, (self.zoom, self.pan)); @@ -430,6 +435,17 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { } app.layout.section_warning = note; } + let notes = rustgis_engine::render::layout::profiles_not_drawn(&layout, &app.session.project.maps); + let said = rustgis_engine::render::layout::profiles_notice(¬es.into_iter().map(|n| (n, 1)).collect(), 1); + if said != app.layout.profile_warning { + // (The command that added or changed one has just said so.) + for note in said.iter().filter(|n| !app.layout.profile_warning.contains(n)) { + if app.session.notices.last().is_none_or(|last| last.text != *note) { + app.session.warn(note.clone()); + } + } + app.layout.profile_warning = said; + } // The Format pane is drawn before the page: a count that changed shows on the next // frame, without waiting for an input event. let losses = Some((li, losses)); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 22c0ee6529..6ebe00a593 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -3608,6 +3608,12 @@ fn layout_groups(app: &mut RustGisApp, ui: &mut Ui) { } }); }); + col(ui, |ui| { + let desc = "Add a raster's profile beside the map frame, along one of its section lines."; + if small(ui, app, "layout_profile", "Profile", desc, "ui.menu", Value::Null, false).clicked() { + add(app, json!({"kind": "profile"})); + } + }); }); group(ui, "Shapes", |ui| { // In the middle of the page, ready to be moved and sized. diff --git a/docs/maintaining.md b/docs/maintaining.md index f8e490dde3..9865eacbe5 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -288,6 +288,13 @@ saved `layout.addElement` of a section requires it too, and so does a `layout.up `section` object, which an older reader warns that it ignores. A saved `layout.import` whose `text` has such a frame requires it as well. +Projects with a profile beside a map frame (an element of kind `Profile`) require `layout-profile`, +so an older reader refuses them instead of dropping the element (#2863 part 2). A saved +`layout.addElement` of a profile requires it too, and so does a `layout.update` with a key only a +profile reads (`band`, `side`, `gap`, `thickness`, `unit`, `lineColor`, `lineWidth`, `guides`, +`min`, or a `section` given as a name). A saved `layout.import` whose `text` has one requires it as +well. + Projects with a legend, a scale bar or a grid whose text isn't its default size (`text_size` on a legend, 9 points by default, or on a scale bar, 8; `label_size` on a frame's grid, 8) require `layout-text-size`, so an older reader refuses them instead of drawing that text at the default diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index e833e1a08e..c388a29ca5 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -323,6 +323,31 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu (the name defaults to the first free letter, the place to the frame's centre), then `layout.update={"element":1,"section":{"name":"A","at":[-44.7,-22.4],"color":"#1F5C84"}}` (`"newName"` renames it, and `"remove": true` removes it). +- **Profiles**: **Profile** in *Publish › Map Surrounds* draws, beside a frame, the profile of a + raster along one of its section lines (#2863): under or over the frame for a horizontal line, + right or left of it for a vertical one. It is lined up with the map: each sample is read at its + point of the line on the page, taken back through the frame's projection to the ground, so each + point of the curve is straight across from the place it comes from, whatever the projection or + the frame's bearing. That line is neither a parallel nor a straight line between the longitudes + and latitudes of its ends, which `profile.create` follows: on a map in UTM 37 km wide the two + part by metres. The profile takes the frame's side along its length, and keeps to it when the + frame is moved or resized; dragged, it moves away from the frame or nearer, and resized, it grows + thicker or thinner. It reads one band of any raster held whole (not one read in place, such as a + web address's cloud-optimised GeoTIFF, which gives only the overview the view draws), bilinearly, + a sample a cell up to 10,000, nothing smoothed; where the raster has no data the curve breaks. + The curve can be filled under it in one colour; its value axis has round numbers on guide lines + (or the **min** and **max** given, so that two profiles share a scale), with a unit after them; + its distance axis counts along the ground from the line's A end in the units a scale bar takes; + and the section's names stand at its ends. A tilted frame or one on the globe takes no profile + (a line straight on the page there isn't a section of the ground), nor does a section line + running the other way: the profile draws its placeholder, and the layout view, its command and + exports say why. It follows its section line and layer when they are renamed, and goes with its + frame. From a command: + `layout.addElement={"kind":"profile","frame":1,"section":"A","layer":"DEM","side":"bottom","unit":"m"}` + (the section defaults to the frame's first, the layer to the top raster shown, the title to the + layer's name; `"band"`, `"gap"`, `"thickness"`, `"lineColor"`, `"lineWidth"`, `"fill"` (null for + none), `"min"`, `"max"`, `"units"`, `"guides"` and `"color"`, its ink, are its options), then + `layout.update` with the same keys. - **Measured grids**: a grid's **Type** is a **Graticule** (latitudes and longitudes, as above) or a **Measured grid**, as ArcGIS Pro has them: eastings and northings in a projected coordinate system, for maps read with UTM or national grid coordinates (a hiking map at 1:25,000 with a diff --git a/schema/fixtures/layout_profile.rgis b/schema/fixtures/layout_profile.rgis new file mode 100644 index 0000000000..6defac7e10 --- /dev/null +++ b/schema/fixtures/layout_profile.rgis @@ -0,0 +1,27 @@ +{ + "format": 2, + "name": "Profile", + "requires": ["layout-section", "layout-profile"], + "active_map": 0, + "maps": [ + { + "name": "Map", + "layers": [], + "basemap": "Paper", + "camera": {"center": {"x": 0, "y": 0}, "res": 30000} + } + ], + "layouts": [ + { + "name": "Profiles", + "width": 200, + "height": 150, + "elements": [ + {"id": 1, "name": "Map", "x": 10, "y": 10, "w": 120, "h": 90, "kind": {"MapFrame": {"map": "Map", "center": {"x": 0, "y": 0}, "scale": 1000000, "sections": [ + {"name": "A", "line": {"Horizontal": {"x": 0.05, "y": 0.1}}, "color": [168, 67, 31, 255], "width": 1.5} + ]}}}, + {"id": 2, "name": "Profile", "x": 10, "y": 103, "w": 120, "h": 30, "kind": {"Profile": {"frame": 1, "section": "A", "layer": "DEM", "side": "Bottom", "gap": 3, "thickness": 30, "title": "Elevation", "unit": "m", "line_color": [60, 50, 40, 255], "line_width": 1, "fill": [216, 200, 168, 255]}}} + ] + } + ] +} diff --git a/schema/project.schema.json b/schema/project.schema.json index 480dd51cb4..b4a7fe8dc9 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1276,6 +1276,7 @@ "blank-paper", "layout-frame-border", "layout-section", + "layout-profile", "native-coordinates", "layout-text-size", "layout-legend-fit", @@ -1398,6 +1399,7 @@ "blank-paper", "layout-frame-border", "layout-section", + "layout-profile", "native-coordinates", "layout-text-size", "layout-legend-fit",