From ac799953764b55ae672af5300a0e50ca52c3bafa Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 28 Nov 2026 15:50:38 -0300 Subject: [PATCH 1/5] feat(layout): a profile's curve and axes (#2863 part 2d) A profile draws its samples beside its frame: along a horizontal side the values rise up the page, along a vertical one away from the frame, each sample straight across from its place. A line, filled under it in one colour or not, broken where there is no data; a value axis out to round numbers, or the min and max given, so profiles can share a scale, with guide lines and the unit after its numbers; a distance axis along the ground from the line's A end, in the units a scale bar takes; the title, and the section's names at the ends in its colour. Drawn on the page's canvas, it is kept as vectors in PDF and SVG exports. Co-Authored-By: Claude Opus 5.5 --- crates/map/src/layout/profile.rs | 8 + crates/render/src/layout.rs | 6 +- crates/render/src/layout/profile.rs | 231 +++++++++++++++++++++- crates/render/src/layout/profile_tests.rs | 73 +++++++ 4 files changed, 313 insertions(+), 5 deletions(-) diff --git a/crates/map/src/layout/profile.rs b/crates/map/src/layout/profile.rs index ae7310adcd..8b060f95db 100644 --- a/crates/map/src/layout/profile.rs +++ b/crates/map/src/layout/profile.rs @@ -204,4 +204,12 @@ impl Profile { } 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/render/src/layout.rs b/crates/render/src/layout.rs index d601456bc1..7274bdf029 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -696,8 +696,10 @@ fn draw_page( None => placeholder(&mut pm, r, "Chart", ppp), } } - // Its curve comes in its own step (#2863 part 2d); what it reads is said meanwhile. - ElementKind::Profile(_) => placeholder(&mut pm, r, "Profile", 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 index 77bd203953..2db682c43b 100644 --- a/crates/render/src/layout/profile.rs +++ b/crates/render/src/layout/profile.rs @@ -1,8 +1,8 @@ //! 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, and what keeps one from -//! being drawn. +//! 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}; +use rustgis_map::layout::{MAX_PROFILE_SAMPLES, Profile, ProfileSide}; use super::*; @@ -221,6 +221,231 @@ pub fn profiles_notice(notes: &BTreeMap, pages: usize) -> Ve 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 index 4cec885aaa..e0cb903768 100644 --- a/crates/render/src/layout/profile_tests.rs +++ b/crates/render/src/layout/profile_tests.rs @@ -133,6 +133,64 @@ fn the_page_line_is_not_a_straight_line_of_longitude_and_latitude() { 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. @@ -172,6 +230,21 @@ fn a_profile_not_drawn_says_why() { assert!(render(&tilted, &mut maps, 96.0, &PageInfo::default()).is_ok()); } +/// 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 leaves a gap in the samples, which breaks the curve: two runs, /// each drawn. #[test] From a20653abebe76da83aa1e5f54737f10889a140b6 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 29 Nov 2026 04:13:08 -0300 Subject: [PATCH 2/5] feat(layout): the layout view says a profile's notice from what it drew (#2863 part 2d) The page's drawing returns what its profiles said of what they read (PagePending::profiles), and the layout view says the notice from that instead of reading each profile again on every redraw. The gaps notice says where the line runs off its raster too, and profile_samples says it reads about the line's length in cells. A value axis given the wrong way round is tested to fall back to the samples' ends. The value axis' top number keeps inside the plot, clear of the section's name and the title; across a vertical side the title goes in the names' strip instead of over the curve. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/layout.rs | 17 +++++--- crates/render/src/layout/profile.rs | 51 ++++++++++++----------- crates/render/src/layout/profile_tests.rs | 30 +++++++++++-- crates/ui-egui/src/layoutview.rs | 5 ++- 4 files changed, 69 insertions(+), 34 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 7274bdf029..bdc06e76c4 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -170,12 +170,15 @@ pub fn meets(e: &rustgis_map::layout::Element, [x, y, w, h]: [f64; 4], margin: f } /// What a page actually drew without, kept separately so legend-only waits redraw only on completion. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct PagePending { /// A frame drew without tiles, streamed data or cast shadows still on their way. pub frames: bool, /// A legend drew while one of its own pictures was still on its way. pub legends: bool, + /// What its profiles said of what they read as they were drawn ([`profiles_not_drawn`]), so + /// the Layout view needn't read them again to say it. + pub profiles: Vec, } /// [`render`], and whether a frame or legend was drawn while content was still on its way. @@ -696,10 +699,14 @@ 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::Profile(p) => { + let read = profile_samples(layout, maps, p); + pending.profiles.extend(profile_note(e, &read)); + match read { + 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 index 2db682c43b..456069c77b 100644 --- a/crates/render/src/layout/profile.rs +++ b/crates/render/src/layout/profile.rs @@ -16,7 +16,7 @@ pub struct ProfileSamples { 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 + /// The section line's length in the raster's cells, when it is more than the samples read /// ([`MAX_PROFILE_SAMPLES`]). pub cells: Option, } @@ -34,7 +34,8 @@ impl ProfileSamples { 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 +/// the line: about as many samples as its length in the raster's cells (at most +/// [`MAX_PROFILE_SAMPLES`]; a diagonal reads fewer than the cells it touches), 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. @@ -122,7 +123,7 @@ pub fn profile_samples(layout: &Layout, maps: &[Map], p: &Profile) -> Result<(Pr } /// A profile its layout doesn't draw, or draws from fewer samples than its raster's cells along -/// its section line, or with gaps where the line has no data ([`profile_samples`]). +/// its section line, or with gaps where the line has no data or runs off its raster ([`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. @@ -144,21 +145,22 @@ pub fn profiles_not_drawn(layout: &Layout, maps: &[Map]) -> Vec { ElementKind::Profile(p) => Some((e, p)), _ => None, }); - profiles - .filter_map(|(e, p)| { - let (why, cells, blank) = match profile_samples(layout, maps, p) { - Err(why) => (Some(why), 0, (0, 0)), - Ok((s, _)) => { - let blank = (s.values.iter().filter(|v| v.is_none()).count(), s.values.len()); - if s.cells.is_none() && blank.0 == 0 { - return None; - } - (None, s.cells.unwrap_or(0), blank) - } - }; - Some(ProfileNote { layout: String::new(), element: e.id, name: e.name.clone(), why, cells, blank }) - }) - .collect() + profiles.filter_map(|(e, p)| profile_note(e, &profile_samples(layout, maps, p))).collect() +} + +/// What profile `e` says of what it read ([`profiles_not_drawn`]), if anything. +pub(super) fn profile_note(e: &rustgis_map::layout::Element, read: &Result<(ProfileSamples, Section), String>) -> Option { + let (why, cells, blank) = match read { + Err(why) => (Some(why.clone()), 0, (0, 0)), + Ok((s, _)) => { + let blank = (s.values.iter().filter(|v| v.is_none()).count(), s.values.len()); + if s.cells.is_none() && blank.0 == 0 { + return None; + } + (None, s.cells.unwrap_or(0), blank) + } + }; + Some(ProfileNote { layout: String::new(), element: e.id, name: e.name.clone(), why, cells, blank }) } /// What an export of `pages` pages says of its profiles ([`profiles_not_drawn`]), each with the @@ -216,7 +218,7 @@ pub fn profiles_notice(notes: &BTreeMap, pages: usize) -> Ve if !gaps.is_empty() { let count = gaps.len(); let items = gaps.into_iter().map(|(key, ((blank, all), n))| format!("{}, {blank} of {all} samples{}", named(key), on(n))).collect(); - out.push(format!("{count} profile(s) drawn with gaps, where the line has no data: {}", list(items))); + out.push(format!("{count} profile(s) drawn with gaps, where the line has no data or runs off its raster: {}", list(items))); } out } @@ -284,7 +286,9 @@ pub(super) fn draw_profile(pm: &mut Canvas, r: Rect, p: &Profile, (samples, sect // 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 }; + // Across a vertical one the names and the title share a strip, the title taking at most half. + let title = if p.title.trim().is_empty() { 0.0 } else { width(p.title.trim(), title_px, true).min((thick - axis) / 2.0) }; + let head = if horizontal { name_px * 1.5 } else { names.iter().map(|n| width(n, name_px, true)).fold(title, f32::max) + 3.0 * k }; let plot = thick - axis - head; if plot < 2.0 * k { placeholder(pm, r, "Profile", ppp); @@ -391,7 +395,8 @@ pub(super) fn draw_profile(pm: &mut Canvas, r: Rect, p: &Profile, (samples, sect let v = v_of(*g); if horizontal { let (_, y) = page(0.0, v); - let cy = y - label_px * 0.55; + // Over its guide, inside the plot: the top one under it, clear of the names. + let cy = (y - label_px * 0.55).max(page(0.0, plot).1 + label_px * 0.55); // Stacked up the page: each over the one before. if before.is_finite() && cy + label_px * 0.5 > before { continue; @@ -427,9 +432,7 @@ pub(super) fn draw_profile(pm: &mut Canvas, r: Rect, p: &Profile, (samples, sect 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); + text::text_at(pm, p.title.trim(), cx, start + name_px * 2.0, title_px, ink, true, align, false); } } } diff --git a/crates/render/src/layout/profile_tests.rs b/crates/render/src/layout/profile_tests.rs index e0cb903768..0aee89dbb8 100644 --- a/crates/render/src/layout/profile_tests.rs +++ b/crates/render/src/layout/profile_tests.rs @@ -240,6 +240,9 @@ fn a_profiles_value_axis_is_round_or_given() { 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); + // Given the wrong way round, they make no axis: the samples' own ends again. + let wrong = Profile { min: Some(2_900.0), max: Some(400.0), ..base.clone() }; + assert_eq!(value_axis(&wrong, (412.0, 2_791.0)), (0.0, 3_000.0, 1_000.0)); // Flat, it still has a span. let (lo, hi, _) = value_axis(&base, (5.0, 5.0)); assert!(lo < 5.0 && hi > 5.0); @@ -320,7 +323,10 @@ fn a_profile_with_gaps_says_how_many_samples_have_no_value() { let (s, _) = profile_samples(&l, &gap, profile_of(&l, id)).unwrap(); let blank = s.values.iter().filter(|v| v.is_none()).count(); assert!(blank > 100, "{blank} of {}", s.values.len()); - let want = format!("1 profile(s) drawn with gaps, where the line has no data: 'Profile' ({id}), {blank} of {} samples", s.values.len()); + let want = format!( + "1 profile(s) drawn with gaps, where the line has no data or runs off its raster: 'Profile' ({id}), {blank} of {} samples", + s.values.len() + ); assert_eq!(said(&gap), vec![want]); // A line read whole says nothing. assert!(said(&[utm_map(dem(|_, _| 100.0))]).is_empty()); @@ -338,9 +344,27 @@ fn a_thinned_or_gapped_profile_says_on_how_many_pages() { format!( "1 profile(s) read at {MAX_PROFILE_SAMPLES} samples, fewer than their raster's cells along the line: 'Profile' (2), across 12000 cells on 2 of 3 pages" ), - "1 profile(s) drawn with gaps, where the line has no data: 'Profile' (2), 133 of 1242 samples on 1 of 3 pages".to_string(), + "1 profile(s) drawn with gaps, where the line has no data or runs off its raster: 'Profile' (2), 133 of 1242 samples on 1 of 3 pages".to_string(), ] ); let one: BTreeMap = [(note(0, (133, 1242)), 1)].into_iter().collect(); - assert_eq!(profiles_notice(&one, 1), ["1 profile(s) drawn with gaps, where the line has no data: 'Profile' (2), 133 of 1242 samples"]); + assert_eq!( + profiles_notice(&one, 1), + ["1 profile(s) drawn with gaps, where the line has no data or runs off its raster: 'Profile' (2), 133 of 1242 samples"] + ); +} + +/// The page the Layout view draws says what its profiles read as they were drawn, as +/// [`profiles_not_drawn`] would, so the view doesn't read each one again to say it (#2863). +#[test] +fn a_drawn_page_says_what_its_profiles_read() { + let mid = Crs::from_epsg(31983).unwrap().transformer().unwrap().from_lonlat(CENTER).unwrap().x; + // Drawn with a gap, and not drawn on a tilted frame. + let mut maps = vec![utm_map(dem(move |e, n| if (e - mid).abs() < 2_000.0 { f64::NAN } else { n }))]; + for (bearing, pitch) in [(0.0, 0.0), (0.0, 40.0)] { + let (l, _) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (bearing, pitch)); + let (_, pending) = render_pending(&l, &mut maps, 30.0, &PageInfo::default()).unwrap(); + let read = profiles_not_drawn(&l, &maps); + assert!(read.len() == 1 && pending.profiles == read, "{:?} drawn, {read:?} read", pending.profiles); + } } diff --git a/crates/ui-egui/src/layoutview.rs b/crates/ui-egui/src/layoutview.rs index 10d197daaa..ec4cc6f4d0 100644 --- a/crates/ui-egui/src/layoutview.rs +++ b/crates/ui-egui/src/layoutview.rs @@ -435,8 +435,9 @@ 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); + // From what the drawing read, not read again. + let notes = pending.profiles.into_iter().map(|n| (n, 1)).collect(); + let said = rustgis_engine::render::layout::profiles_notice(¬es, 1); if said != app.layout.profile_warning { // (An export of this page may have just said the same; it isn't said twice.) for note in said.iter().filter(|n| !app.layout.profile_warning.contains(n)) { From 744033882e9c5c9623956a0c26c090c595f273fd Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 29 Nov 2026 04:50:03 -0300 Subject: [PATCH 3/5] fix(layout): a profile cut at its axis' given ends says so; given ends keep their place (#2863 part 2d) Review round 1 of #3316, each fix after a test that failed: - samples past the value axis' given ends, drawn flat at its edge, are said with how many of all ("drawn cut at their axis' given ends"); - one end given past the samples' other end keeps its place, the other a span away on its own side, instead of the axis taken over by the end worked out; - a tiny step's numbers keep the decimals that tell them apart (up to 15, not 6). Co-Authored-By: Claude Opus 5.5 --- crates/render/src/layout/profile.rs | 47 ++++++++++++++++++----- crates/render/src/layout/profile_tests.rs | 43 ++++++++++++++++++++- 2 files changed, 79 insertions(+), 11 deletions(-) diff --git a/crates/render/src/layout/profile.rs b/crates/render/src/layout/profile.rs index 456069c77b..0eed518d14 100644 --- a/crates/render/src/layout/profile.rs +++ b/crates/render/src/layout/profile.rs @@ -123,7 +123,8 @@ pub fn profile_samples(layout: &Layout, maps: &[Map], p: &Profile) -> Result<(Pr } /// A profile its layout doesn't draw, or draws from fewer samples than its raster's cells along -/// its section line, or with gaps where the line has no data or runs off its raster ([`profile_samples`]). +/// its section line, with gaps where the line has no data or runs off its raster, or cut at its +/// axis' given ends ([`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. @@ -136,10 +137,13 @@ pub struct ProfileNote { pub cells: usize, /// Drawn, its samples without a value (off its raster or over no data), and all of them. pub blank: (usize, usize), + /// Drawn, its samples past the ends given to its value axis, drawn flat at its edge. + pub cut: usize, } /// What `layout`'s visible profiles say as the page is now: those not drawn, and why, those read -/// at fewer samples than their raster's cells along the line, and those drawn with gaps. +/// at fewer samples than their raster's cells along the line, those drawn with gaps, and those cut +/// at their axis' given ends. 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)), @@ -150,22 +154,28 @@ pub fn profiles_not_drawn(layout: &Layout, maps: &[Map]) -> Vec { /// What profile `e` says of what it read ([`profiles_not_drawn`]), if anything. pub(super) fn profile_note(e: &rustgis_map::layout::Element, read: &Result<(ProfileSamples, Section), String>) -> Option { - let (why, cells, blank) = match read { - Err(why) => (Some(why.clone()), 0, (0, 0)), + let (min, max) = match &e.kind { + ElementKind::Profile(p) => p.given_range(), + _ => (None, None), + }; + let (why, cells, blank, cut) = match read { + Err(why) => (Some(why.clone()), 0, (0, 0), 0), Ok((s, _)) => { let blank = (s.values.iter().filter(|v| v.is_none()).count(), s.values.len()); - if s.cells.is_none() && blank.0 == 0 { + let cut = s.values.iter().flatten().filter(|v| min.is_some_and(|m| **v < m) || max.is_some_and(|m| **v > m)).count(); + if s.cells.is_none() && blank.0 == 0 && cut == 0 { return None; } - (None, s.cells.unwrap_or(0), blank) + (None, s.cells.unwrap_or(0), blank, cut) } }; - Some(ProfileNote { layout: String::new(), element: e.id, name: e.name.clone(), why, cells, blank }) + Some(ProfileNote { layout: String::new(), element: e.id, name: e.name.clone(), why, cells, blank, cut }) } /// 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, each named with its reason, one for those read -/// at fewer samples than cells, and one for those drawn with gaps, each with the pages it is on +/// at fewer samples than cells, one for those drawn with gaps, and one for those cut at their +/// axis' given ends, each with the pages it is on /// over several; 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() }; @@ -182,6 +192,7 @@ pub fn profiles_notice(notes: &BTreeMap, pages: usize) -> Ve // The most a page says of each, and the pages saying it. let mut thinned: BTreeMap<(&str, u32, &str), (usize, usize)> = BTreeMap::new(); let mut gaps: BTreeMap<(&str, u32, &str), ((usize, usize), usize)> = BTreeMap::new(); + let mut cut: BTreeMap<(&str, u32, &str), ((usize, usize), usize)> = BTreeMap::new(); for (n, count) in notes { let key = (n.layout.as_str(), n.element, n.name.as_str()); match &n.why { @@ -195,6 +206,10 @@ pub fn profiles_notice(notes: &BTreeMap, pages: usize) -> Ve let (most, on) = gaps.entry(key).or_default(); (*most, *on) = ((*most).max(n.blank), *on + count); } + if n.cut > 0 { + let (most, on) = cut.entry(key).or_default(); + (*most, *on) = ((*most).max((n.cut, n.blank.1)), *on + count); + } } } } @@ -220,6 +235,12 @@ pub fn profiles_notice(notes: &BTreeMap, pages: usize) -> Ve let items = gaps.into_iter().map(|(key, ((blank, all), n))| format!("{}, {blank} of {all} samples{}", named(key), on(n))).collect(); out.push(format!("{count} profile(s) drawn with gaps, where the line has no data or runs off its raster: {}", list(items))); } + if !cut.is_empty() { + let count = cut.len(); + let items = + cut.into_iter().map(|(key, ((past, all), n))| format!("{}, {past} of {all} samples past them{}", named(key), on(n))).collect(); + out.push(format!("{count} profile(s) drawn cut at their axis' given ends: {}", list(items))); + } out } @@ -240,7 +261,7 @@ fn round_step(span: f64, parts: f64) -> f64 { /// `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 decimals = if step >= 1.0 || step <= 0.0 { 0 } else { (-step.log10().floor()).clamp(0.0, 15.0) as usize }; let k = 10f64.powi(decimals as i32); decimal(format!("{:.*}", decimals, (v * k).round() / k + 0.0), comma) } @@ -249,7 +270,13 @@ fn number(v: f64, step: f64, comma: bool) -> String { /// 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)); + // One end given past the samples' other end: that end a span away from it, on its own side. + let span = if hi > lo { hi - lo } else { (hi.abs() * 0.1).max(1.0) }; + let (lo, hi) = match (min, max) { + (Some(m), None) if hi <= m => (m, m + span), + (None, Some(m)) if lo >= m => (m - span, m), + _ => (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); diff --git a/crates/render/src/layout/profile_tests.rs b/crates/render/src/layout/profile_tests.rs index 0aee89dbb8..4a9fa44b28 100644 --- a/crates/render/src/layout/profile_tests.rs +++ b/crates/render/src/layout/profile_tests.rs @@ -336,7 +336,7 @@ fn a_profile_with_gaps_says_how_many_samples_have_no_value() { /// drawn does; on one page it says nothing of pages (#2863). #[test] fn a_thinned_or_gapped_profile_says_on_how_many_pages() { - let note = |cells, blank| ProfileNote { layout: String::new(), element: 2, name: "Profile".into(), why: None, cells, blank }; + let note = |cells, blank| ProfileNote { layout: String::new(), element: 2, name: "Profile".into(), why: None, cells, blank, cut: 0 }; let notes: BTreeMap = [(note(12_000, (0, 10_000)), 2), (note(0, (133, 1242)), 1)].into_iter().collect(); assert_eq!( profiles_notice(¬es, 3), @@ -368,3 +368,44 @@ fn a_drawn_page_says_what_its_profiles_read() { assert!(read.len() == 1 && pending.profiles == read, "{:?} drawn, {read:?} read", pending.profiles); } } + +/// A profile whose given value ends cut its samples says how many fall past them, drawn flat at the +/// axis' edge: a clipped curve is not left unexplained (#2863). +#[test] +fn a_profile_cut_by_its_given_ends_says_how_many_samples_are_past_them() { + let mid = Crs::from_epsg(31983).unwrap().transformer().unwrap().from_lonlat(CENTER).unwrap().x; + let maps = vec![utm_map(dem(move |e, _| e - mid))]; + let (mut l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); + let said = |l: &Layout| profiles_notice(&profiles_not_drawn(l, &maps).into_iter().map(|n| (n, 1)).collect(), 1); + assert!(said(&l).is_empty(), "{:?}", said(&l)); + if let Some(ElementKind::Profile(p)) = l.element_mut(id).map(|e| &mut e.kind) { + p.max = Some(0.0); + } + let (s, _) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); + let past = s.values.iter().flatten().filter(|v| **v > 0.0).count(); + assert!(past > 0 && past < s.values.len(), "{past} of {}", s.values.len()); + let want = + format!("1 profile(s) drawn cut at their axis' given ends: 'Profile' ({id}), {past} of {} samples past them", s.values.len()); + assert_eq!(said(&l), [want]); +} + +/// One end given past the samples' other end keeps its place, the other a span away on its own side: +/// no axis taken over by the end worked out (#2863). +#[test] +fn an_end_given_past_the_samples_keeps_its_place() { + let base = Profile::new(1, "A".into(), "DEM".into(), ProfileSide::Bottom); + let (lo, hi, _) = value_axis(&Profile { max: Some(0.0), ..base.clone() }, (100.0, 200.0)); + assert!(hi == 0.0 && lo < 0.0, "{lo} to {hi}"); + let (lo, hi, _) = value_axis(&Profile { min: Some(300.0), ..base }, (100.0, 200.0)); + assert!(lo == 300.0 && hi > 300.0 + 1e-3, "{lo} to {hi}"); +} + +/// A tiny step's numbers keep their decimals: the ticks of an axis from 0 to 0.0000004 read apart. +#[test] +fn a_tiny_steps_numbers_read_apart() { + let given = Profile { min: Some(0.0), max: Some(4e-7), ..Profile::new(1, "A".into(), "DEM".into(), ProfileSide::Bottom) }; + let (lo, hi, step) = value_axis(&given, (0.0, 4e-7)); + let ticks: Vec = + (0..).map(|i| lo + f64::from(i) * step).take_while(|v| *v <= hi + step * 1e-9).map(|v| number(v, step, false)).collect(); + assert!(ticks.len() > 2 && ticks.windows(2).all(|w| w[0] != w[1]), "{ticks:?}"); +} From 99a602cab99a478fdd7ec000fe84c149525c8faa Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 29 Nov 2026 04:59:58 -0300 Subject: [PATCH 4/5] fix(layout): a profile's sample alone between gaps is drawn as a dot (#2863 part 2d) Review round 2 of #3316: a run of one point had no line to stroke and a fill of no area, so a sample with a value between two gaps left no mark. It is drawn as a dot as wide as the line. The test, written first, failed with no mark where the sample is. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/layout/profile.rs | 7 ++++ crates/render/src/layout/profile_tests.rs | 41 +++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/crates/render/src/layout/profile.rs b/crates/render/src/layout/profile.rs index 0eed518d14..10cb43f08f 100644 --- a/crates/render/src/layout/profile.rs +++ b/crates/render/src/layout/profile.rs @@ -373,6 +373,13 @@ pub(super) fn draw_profile(pm: &mut Canvas, r: Rect, p: &Profile, (samples, sect pm.fill_path(&area, &paint(fill, 1.0), FillRule::Winding, Transform::identity(), None); } } + // A sample alone between gaps has no line to draw: a dot, as wide as the line. + if let [(u, v)] = run.as_slice() { + let (x, y) = page(*u, *v); + if let Some(dot) = PathBuilder::from_circle(x, y, (p.line_width as f32 * k).max(k)) { + pm.fill_path(&dot, &paint(p.line_color, 1.0), FillRule::Winding, Transform::identity(), None); + } + } if run.len() > 1 && let Some(path) = line(run) { diff --git a/crates/render/src/layout/profile_tests.rs b/crates/render/src/layout/profile_tests.rs index 4a9fa44b28..32c40c6c8d 100644 --- a/crates/render/src/layout/profile_tests.rs +++ b/crates/render/src/layout/profile_tests.rs @@ -409,3 +409,44 @@ fn a_tiny_steps_numbers_read_apart() { (0..).map(|i| lo + f64::from(i) * step).take_while(|v| *v <= hi + step * 1e-9).map(|v| number(v, step, false)).collect(); assert!(ticks.len() > 2 && ticks.windows(2).all(|w| w[0] != w[1]), "{ticks:?}"); } + +/// A sample with a value between two gaps leaves its mark: a dot where a run of one point has no +/// line to draw (#2863). +#[test] +fn a_lone_sample_between_gaps_is_drawn() { + let red = Rgba::rgb(0xFF, 0, 0); + let p = Profile { + guides: false, + fill: None, + line_color: red, + line_width: 1.0, + ..Profile::new(1, "A".into(), "DEM".into(), ProfileSide::Bottom) + }; + let n = 41; + // Values at both ends make the axis; the one in the middle stands alone between gaps. + let values = (0..n).map(|i| match i { + 0 | 1 => Some(0.0), + 20 => Some(50.0), + 39 | 40 => Some(100.0), + _ => None, + }); + let samples = ProfileSamples { + along: (0..n).map(|i| f64::from(i) * 10.0).collect(), + metres: (0..n).map(|i| f64::from(i) * 100.0).collect(), + values: values.collect(), + cells: None, + }; + let section = Section::new("A".into(), SectionLine::Horizontal(CENTER)); + let ppp = 2.0; + let (w, h) = ((400.0 * ppp) as u32, (120.0 * ppp) as u32); + let mut pm = Canvas::new(w, h).unwrap(); + draw_profile(&mut pm, Rect::from_xywh(0.0, 0.0, w as f32, h as f32).unwrap(), &p, (&samples, §ion), false, ppp); + let pm = pm.into_pixmap(); + // Around the lone sample's place, 200 points along. + let x = (200.0 * ppp) as u32; + let reddish = (x - 6..x + 6) + .flat_map(|x| (0..h).map(move |y| (x, y))) + .filter(|(x, y)| pm.pixel(*x, *y).is_some_and(|c| c.red() > 150 && c.green() < 80)) + .count(); + assert!(reddish > 0, "no mark where the lone sample is"); +} From 9f7475f2de3e7744994129b09c23b71f2355da51 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 29 Nov 2026 05:18:22 -0300 Subject: [PATCH 5/5] fix(layout): a profile too thin for its axes says so; tiny steps and a lone sample's dot (#2863 part 2d) Review round 3 of #3316, each fix after a test that failed: - a profile whose box can't hold its axes and names, drawn as the placeholder, was silent: it is now said as not drawn, "its box is too thin to hold its axes and names" (the strips are worked out in one place, profile_strips, for the drawing and the notice); - a step under a millionth writes its numbers in powers of ten, so ticks read apart below 1e-15 too; - a lone sample's dot is as wide as the line: from_circle takes a radius. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/layout/profile.rs | 78 +++++++++++++++++------ crates/render/src/layout/profile_tests.rs | 24 +++++++ 2 files changed, 83 insertions(+), 19 deletions(-) diff --git a/crates/render/src/layout/profile.rs b/crates/render/src/layout/profile.rs index 10cb43f08f..ba3a3a0d98 100644 --- a/crates/render/src/layout/profile.rs +++ b/crates/render/src/layout/profile.rs @@ -160,7 +160,23 @@ pub(super) fn profile_note(e: &rustgis_map::layout::Element, read: &Result<(Prof }; let (why, cells, blank, cut) = match read { Err(why) => (Some(why.clone()), 0, (0, 0), 0), - Ok((s, _)) => { + Ok((s, section)) => { + // Drawn as the placeholder when its box can't hold its axes and names. + if let ElementKind::Profile(p) = &e.kind { + let thick = if p.side.is_horizontal() { e.h } else { e.w } * PT_PER_MM; + if profile_strips(p, (s, section), thick as f32, 1.0, false).2.2 < 2.0 { + let why = "its box is too thin to hold its axes and names".to_string(); + return Some(ProfileNote { + layout: String::new(), + element: e.id, + name: e.name.clone(), + why: Some(why), + cells: 0, + blank: (0, 0), + cut: 0, + }); + } + } let blank = (s.values.iter().filter(|v| v.is_none()).count(), s.values.len()); let cut = s.values.iter().flatten().filter(|v| min.is_some_and(|m| **v < m) || max.is_some_and(|m| **v > m)).count(); if s.cells.is_none() && blank.0 == 0 && cut == 0 { @@ -261,7 +277,15 @@ fn round_step(span: f64, parts: f64) -> f64 { /// `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, 15.0) as usize }; + // A step under a millionth in powers of ten, with the digits that tell its numbers apart. + if step > 0.0 && step < 1e-6 { + if v == 0.0 { + return "0".into(); + } + let digits = (v.abs().log10().floor() - step.log10().floor()).clamp(0.0, 15.0) as usize; + return decimal(format!("{v:.digits$e}"), comma); + } + 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) } @@ -284,6 +308,37 @@ pub(super) fn value_axis(p: &Profile, (lo, hi): (f64, f64)) -> (f64, f64, f64) { (lo, hi.max(lo + step * 1e-6), step) } +/// Across a profile `thick` pixels deep at `k` pixels a point: its distance axis' ticks (pixels +/// along, number) and unit, and the depths of the strips its distance axis, its names and its +/// curve take; the curve's, under 2 points, too thin to draw ([`draw_profile`]). +fn profile_strips( + p: &Profile, + (samples, section): (&ProfileSamples, &Section), + thick: f32, + k: f32, + comma: bool, +) -> (Vec<(f32, String)>, &'static str, (f32, f32, f32)) { + let (label_px, name_px, title_px) = (PROFILE_LABEL_PT * 1.33 * k, PROFILE_NAME_PT * 1.33 * k, PROFILE_TITLE_PT * 1.33 * k); + let width = |s: &str, px: f32, bold: bool| text::measure(s, px / 1.33, bold); + // 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 widest = ticks.iter().map(|(_, s)| width(&format!("{s} {abbr}"), label_px, false)).fold(0.0, f32::max); + let axis = if p.side.is_horizontal() { 3.0 * k + label_px * 1.3 } else { 3.0 * k + widest + 2.0 * k }; + // Across a vertical one the names and the title share a strip, the title taking at most half. + let title = if p.title.trim().is_empty() { 0.0 } else { width(p.title.trim(), title_px, true).min((thick - axis) / 2.0) }; + let names = [section.name.clone(), format!("{}'", section.name)]; + let head = + if p.side.is_horizontal() { name_px * 1.5 } else { names.iter().map(|n| width(n, name_px, true)).fold(title, f32::max) + 3.0 * k }; + (ticks, abbr, (axis, head, thick - axis - head)) +} + /// 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 @@ -299,24 +354,9 @@ pub(super) fn draw_profile(pm: &mut Canvas, r: Rect, p: &Profile, (samples, sect 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 (ticks, abbr, (axis, head, plot)) = profile_strips(p, (samples, section), thick, k, comma); 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)]; - // Across a vertical one the names and the title share a strip, the title taking at most half. - let title = if p.title.trim().is_empty() { 0.0 } else { width(p.title.trim(), title_px, true).min((thick - axis) / 2.0) }; - let head = if horizontal { name_px * 1.5 } else { names.iter().map(|n| width(n, name_px, true)).fold(title, f32::max) + 3.0 * k }; - let plot = thick - axis - head; if plot < 2.0 * k { placeholder(pm, r, "Profile", ppp); return; @@ -376,7 +416,7 @@ pub(super) fn draw_profile(pm: &mut Canvas, r: Rect, p: &Profile, (samples, sect // A sample alone between gaps has no line to draw: a dot, as wide as the line. if let [(u, v)] = run.as_slice() { let (x, y) = page(*u, *v); - if let Some(dot) = PathBuilder::from_circle(x, y, (p.line_width as f32 * k).max(k)) { + if let Some(dot) = PathBuilder::from_circle(x, y, (p.line_width as f32 * k / 2.0).max(0.5)) { pm.fill_path(&dot, &paint(p.line_color, 1.0), FillRule::Winding, Transform::identity(), None); } } diff --git a/crates/render/src/layout/profile_tests.rs b/crates/render/src/layout/profile_tests.rs index 32c40c6c8d..4c03df8803 100644 --- a/crates/render/src/layout/profile_tests.rs +++ b/crates/render/src/layout/profile_tests.rs @@ -408,6 +408,12 @@ fn a_tiny_steps_numbers_read_apart() { let ticks: Vec = (0..).map(|i| lo + f64::from(i) * step).take_while(|v| *v <= hi + step * 1e-9).map(|v| number(v, step, false)).collect(); assert!(ticks.len() > 2 && ticks.windows(2).all(|w| w[0] != w[1]), "{ticks:?}"); + // Past the decimals a number can carry, too. + let given = Profile { min: Some(0.0), max: Some(4e-17), ..given }; + let (lo, hi, step) = value_axis(&given, (0.0, 4e-17)); + let ticks: Vec = + (0..).map(|i| lo + f64::from(i) * step).take_while(|v| *v <= hi + step * 1e-9).map(|v| number(v, step, false)).collect(); + assert!(ticks.len() > 2 && ticks.windows(2).all(|w| w[0] != w[1]), "{ticks:?}"); } /// A sample with a value between two gaps leaves its mark: a dot where a run of one point has no @@ -449,4 +455,22 @@ fn a_lone_sample_between_gaps_is_drawn() { .filter(|(x, y)| pm.pixel(*x, *y).is_some_and(|c| c.red() > 150 && c.green() < 80)) .count(); assert!(reddish > 0, "no mark where the lone sample is"); + // As wide as the line (1 point, 2 pixels), give or take a pixel of antialiasing. + let columns = (x - 6..x + 6).filter(|x| (0..h).any(|y| pm.pixel(*x, y).is_some_and(|c| c.red() > 150 && c.green() < 80))).count(); + assert!(columns <= 3, "a dot {columns} pixels wide for a line of 2"); +} + +/// A profile whose box is too thin to hold its axes and names, drawn as the placeholder, says so; +/// one that fits says nothing (#2863). +#[test] +fn a_profile_too_thin_for_its_axes_says_so() { + let maps = vec![utm_map(dem(|_, n| n))]; + let (mut l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); + let said = |l: &Layout| profiles_notice(&profiles_not_drawn(l, &maps).into_iter().map(|n| (n, 1)).collect(), 1); + assert!(said(&l).is_empty(), "{:?}", said(&l)); + if let Some(e) = l.element_mut(id) { + e.h = 6.0; + } + let said = said(&l); + assert!(said.len() == 1 && said[0].contains("not drawn") && said[0].contains("too thin"), "{said:?}"); }