From f1e45fdceb5f0c04bee10db906a80ac42aa434f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 10:48:43 -0500 Subject: [PATCH 01/10] feat(labels): labels keep off a line layer's lines, with the layer's obstacle weight (#3613) Step 5b of #995. A line layer takes the obstacle weight points already have: its lines count as a chain of obstacles along the stroke, within the same frame limit, merge and notice as points. A label never keeps off its own feature's line. --- crates/engine/src/cmd/labels.rs | 10 +- crates/engine/src/project_capabilities.rs | 2 +- crates/engine/src/tests/label_obstacles.rs | 16 +- crates/map/src/lib.rs | 9 +- crates/map/src/symbology.rs | 2 +- crates/render/src/approximations.rs | 4 +- crates/render/src/lib.rs | 178 ++++++++++- crates/render/src/obstacle_labels_tests.rs | 348 ++++++++++++++++++++- crates/ui-egui/src/labelpane.rs | 18 +- docs/maintaining.md | 4 +- docs/user-guide/cartography.md | 24 +- 11 files changed, 553 insertions(+), 62 deletions(-) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index dab715795b..0287b8bce9 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -213,7 +213,7 @@ pub fn commands() -> Vec { }; let weight_asked = weight.filter(|w| w.fract() != 0.0 || !rustgis_map::symbology::LABEL_WEIGHT.contains(w)); let weight = weight.map(rustgis_map::symbology::label_weight); - // How much labels keep off the layer's points (#3526): 0 to 10, null back to 0. A + // How much labels keep off the layer's points or lines (#3526, #3613): 0 to 10, null back to 0. A // number out of range or a fraction is held to a whole one, and says so. let obstacle = match p.get("obstacleWeight") { None => None, @@ -287,15 +287,15 @@ pub fn commands() -> Vec { let layer = s.map().layer(id).ok_or("no such layer")?; let held = held_geometries(layer); let (points, lines, _) = held; - // On a layer whose points aren't obstacles it would do nothing; off is taken anywhere. + // On a layer whose points or lines aren't obstacles it would do nothing; off is taken anywhere. // The rule is the layer's, shared with the Labeling pane's row. if obstacle.is_some_and(|w| w > 0) && !layer.takes_obstacle_weight() { - return Err(if !points { - "obstacleWeight is for layers with points: lines and polygons aren't obstacles yet" + return Err(if !points && !lines { + "obstacleWeight is for layers with points or lines: polygons aren't obstacles yet" } else if layer.graphics { "obstacleWeight isn't for a graphics layer: its points are text and images, which draw no obstacle" } else { - "obstacleWeight isn't for a cluster or heat map layer: it draws no points" + "obstacleWeight isn't for a cluster or heat map layer: it draws no points or lines" } .into()); } diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index e817be5fff..bb88931363 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -1724,7 +1724,7 @@ fn label_guide(layer: &Layer) -> bool { layer.labels.in_order().any(|c| c.guide.is_some()) } -/// Whether a layer's points are obstacles for labels (#3526): an older reader would drop the +/// Whether a layer's points or lines are obstacles for labels (#3526, #3613): an older reader would drop the /// weight, and place and save the labels as without it. fn label_obstacle(layer: &Layer) -> bool { layer.labels.obstacle_weight > 0 diff --git a/crates/engine/src/tests/label_obstacles.rs b/crates/engine/src/tests/label_obstacles.rs index a9506febea..6980dc3be6 100644 --- a/crates/engine/src/tests/label_obstacles.rs +++ b/crates/engine/src/tests/label_obstacles.rs @@ -1,4 +1,4 @@ -//! A point layer's points as obstacles for labels (#3526): `labels.placement`'s `obstacleWeight`, +//! A point or line layer's points or lines as obstacles for labels (#3526, #3613): `labels.placement`'s `obstacleWeight`, //! how it is saved, and what requires `label-obstacles`. use super::*; @@ -55,14 +55,18 @@ fn a_point_layer_takes_an_obstacle_weight() { } #[test] -fn only_a_layer_with_points_is_an_obstacle() { +fn only_a_layer_with_points_or_lines_is_an_obstacle() { let mut s = world(); + // A line layer takes it (#3613); a polygon layer doesn't yet. let rivers = s.map().layer_by_name("Rivers").unwrap().id; - let err = s.run("labels.placement", &json!({"layer": "Rivers", "obstacleWeight": 5})).unwrap_err(); - assert!(err.to_string().contains("point"), "{err}"); - assert_eq!(weight(&s, rivers), 0); + s.run("labels.placement", &json!({"layer": "Rivers", "obstacleWeight": 5})).unwrap(); + assert_eq!(weight(&s, rivers), 5); + let countries = s.map().layer_by_name("Countries").unwrap().id; + let err = s.run("labels.placement", &json!({"layer": "Countries", "obstacleWeight": 5})).unwrap_err(); + assert!(err.to_string().contains("polygons"), "{err}"); + assert_eq!(weight(&s, countries), 0); // Off is taken anywhere. - s.run("labels.placement", &json!({"layer": "Rivers", "obstacleWeight": 0})).unwrap(); + s.run("labels.placement", &json!({"layer": "Countries", "obstacleWeight": 0})).unwrap(); // A graphics layer's points are its text and images, a cluster's or heat map's aren't drawn: // no obstacle either, so it isn't taken only to do nothing. let cities = s.map().layer_by_name("Cities").unwrap().id; diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index da663228d6..f6b3b98807 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -1414,11 +1414,14 @@ impl Layer { kind != GeometryType::None && (self.geometry_type() == kind || self.geometry_kinds.contains(&self.dataset.features, kind)) } - /// Whether the layer's points can be obstacles for labels (#3526): it has points, draws them - /// (not a graphics, cluster or heat map layer), so an obstacle weight above 0 means something. + /// Whether the layer's points or lines can be obstacles for labels (#3526, #3613): it has + /// some, draws them (not a graphics, cluster or heat map layer), so an obstacle weight above 0 + /// means something. /// The one rule for `labels.placement`'s `obstacleWeight` and the Labeling pane's row. pub fn takes_obstacle_weight(&self) -> bool { - !self.graphics && self.aggregation.is_none() && self.has_geometry(GeometryType::Point) + !self.graphics + && self.aggregation.is_none() + && (self.has_geometry(GeometryType::Point) || self.has_geometry(GeometryType::Polyline)) } /// Copies of every geometry in a map projection's coordinates (`key` names the projection), diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 9d938dddc8..d2b48550ad 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -2958,7 +2958,7 @@ pub struct Labeling { pub default: LabelClass, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub classes: Vec, - /// How much labels keep off this layer's points (#3526): a label whose class's weight isn't + /// How much labels keep off this layer's points or lines (#3526, #3613): a label whose class's weight isn't /// above it isn't placed over one. 0 to 10; 0: the layer is no obstacle. The layer's, not a /// class's, and in force with its labels off too. #[serde(default, skip_serializing_if = "is_no_obstacle")] diff --git a/crates/render/src/approximations.rs b/crates/render/src/approximations.rs index caa14df40f..89805fd82c 100644 --- a/crates/render/src/approximations.rs +++ b/crates/render/src/approximations.rs @@ -329,7 +329,7 @@ pub(crate) fn walls_left_plain(name: &str, n: usize) { ); } -/// Counts `n` of layer `name`'s points in view left out of the obstacles for labels (#3526), as a +/// Counts `n` of layer `name`'s points (or lines) in view left out of the obstacles for labels (#3526), as a /// frame holds only as many as memory allows. The count is of the layer's chunks and of a tilted /// view's bands together: said when what frames approximated is taken ([`flush_obstacles_left`]). pub(crate) fn obstacles_left_out(name: &str, n: usize) { @@ -358,7 +358,7 @@ fn flush_obstacles_left() { note( format!("{name}\0obstacles"), format!( - "{name}: {n} points in view aren't kept off by labels, as a frame holds only as many obstacles as memory allows; zoom in or filter the layer" + "{name}: {n} points or lines in view aren't kept off by labels, as a frame holds only as many obstacles as memory allows; zoom in or filter the layer" ), ); } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index c405463070..d38cd4e6b8 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -407,7 +407,7 @@ use rustgis_data::{Dataset, Geometry, GeometryType}; use rustgis_geom::{Coord, Extent, extent_to_merc, lonlat_to_merc}; use rustgis_map::globe::{V3, densify}; use rustgis_map::layout::TextAlign; -use rustgis_map::{Camera, Globe, LabelPlacement, LineStroke, Map, Marker, Rgba, Symbol}; +use rustgis_map::{Camera, Globe, LabelPlacement, LineMark, LineStroke, Map, Marker, Rgba, Symbol}; pub use text::{covers_quietly, halo_reach}; /// The image type pages and maps are drawn into. pub use tiny_skia::Pixmap; @@ -1267,7 +1267,8 @@ impl Ctx<'_> { self.ring_path(&mut pb, part, false); } let Some(path) = pb.finish() else { return }; - let st = Stroke { width: (w * self.ppp).max(0.5), line_cap: LineCap::Round, line_join: LineJoin::Round, ..Stroke::default() }; + let st = + Stroke { width: (w * self.ppp).max(MIN_STROKE_PX), line_cap: LineCap::Round, line_join: LineJoin::Round, ..Stroke::default() }; pm.stroke_path(&path, p, &st, Transform::identity(), None); } @@ -2805,7 +2806,7 @@ impl Candidate { } /// A point labels keep off (#3526): a feature of a layer with an obstacle weight, where its -/// marker is drawn. Whatever moves the labels on their way to the screen moves it too. +/// marker is drawn, or a sample along its line (#3613). Whatever moves the labels on their way to the screen moves it too. #[derive(Clone, Copy, Debug, PartialEq)] struct Obstacle { /// Its layer and feature, as a label's key names them: its own label may go over it. @@ -6364,15 +6365,27 @@ fn render_frame( // The system is asked for the memory left only by a frame with that many obstacles. let ask_from = obstacle_check_from(); let mut left_out = 0usize; + // Whether the frame took all it may hold: the lines left aren't walked. + let mut full = false; + // Adds an obstacle within what a frame may hold. + let mut add = |o: Obstacle| { + let limit = if obstacles_before + label_obstacles.len() < ask_from { + usize::MAX + } else { + obstacle_room.get_or_insert_with(obstacle_limit).saturating_sub(obstacles_before) + }; + obstacle_cells.add(&mut label_obstacles, o, limit) + }; for (row, g) in geoms.iter().enumerate() { // A stopped frame goes no further, as the drawing loop below does (see `cancel`). if row % cancel::EVERY == 0 && row > 0 && cancel::requested() { break; } let Some(g) = g else { continue }; - let points = match g { - Geometry::Point(c) => std::slice::from_ref(c), - Geometry::MultiPoint(v) => v.as_slice(), + let (points, line) = match g { + Geometry::Point(c) => (std::slice::from_ref(c), None), + Geometry::MultiPoint(v) => (v.as_slice(), None), + Geometry::Line(parts) => (&[][..], Some(parts)), _ => continue, }; if rows.get(row) != Some(&true) || (globe.is_none() && extents.get(row).is_some_and(|e| !e.intersects(&reach_cull))) { @@ -6390,6 +6403,41 @@ fn render_frame( } }); } + if let Some(parts) = line { + // A line's stretches near the view, as far as its stroke reaches. Once the frame is + // full, a line is only checked for a stretch near the view, to count it. + // (On a globe, along the arcs it is drawn in, already on the screen.) + let arcs: Option>> = ctx.globe.as_ref().map(|g| { + let runs = parts.iter().flat_map(|p| globe_runs(g, p)); + runs.map(|r| r.into_iter().map(|(x, y)| Coord::new(f64::from(x), f64::from(y))).collect()).collect() + }); + let (sym, strokes) = styler.style(row); + let Some(reach) = line_obstacle_reach(&sym, strokes, ctx.ppp) else { continue }; + let parts = arcs.as_ref().unwrap_or(parts); + let screen = |c: Coord| if arcs.is_some() { Some((c.x, c.y)) } else { ctx.screen(c) }; + let rect = [-near, -near, right, bottom]; + if full { + // Walked no further than its first stretch near the frame, to count it. + let mut shows = false; + sample_line(parts, &screen, f64::from(MAX_OBSTACLE_REACH), rect, &mut |_, _| { + shows = true; + false + }); + left_out += usize::from(shows); + continue; + } + let (owner, weight, r) = ((lid, label_id(row)), labels.obstacle_weight, reach * size_factor); + // As close as the obstacles are wide: they count as reaching no more than the cap. + sample_line(parts, &screen, f64::from(r.clamp(1.0, MAX_OBSTACLE_REACH)), rect, &mut |x, y| { + let kept = add(Obstacle { owner, x, y, r, weight }); + if !kept { + left_out += 1; + full = true; + } + kept + }); + continue; + } let near_frame = |&(_, (x, y)): &(Coord, (f64, f64))| x >= -near && y >= -near && x <= right && y <= bottom; let mut here = points.iter().filter_map(|&c| ctx.screen(c).map(|xy| (c, xy))).filter(near_frame).peekable(); // Styled only with a point in reach, as the drawing styles only what is in view. @@ -6408,14 +6456,9 @@ fn render_frame( let drawn_cull = if gpu_done { &mesh_cull } else { &ctx.cull }; let (owner, weight, r) = ((lid, label_id(row)), labels.obstacle_weight, reach * size_factor); for (_, (x, y)) in here.filter(|(c, _)| !plain || drawn_cull.contains(*c)) { - let o = Obstacle { owner, x: x as f32, y: y as f32, r, weight }; - let limit = if obstacles_before + label_obstacles.len() < ask_from { - usize::MAX - } else { - obstacle_room.get_or_insert_with(obstacle_limit).saturating_sub(obstacles_before) - }; - if !obstacle_cells.add(&mut label_obstacles, o, limit) { + if !add(Obstacle { owner, x: x as f32, y: y as f32, r, weight }) { left_out += 1; + full = true; } } } @@ -9561,6 +9604,112 @@ fn marker_obstacle_reach(sym: &Symbol, marks: &[LineStroke], px_per_point: f32) (image || sym.fill.a() > 0 || outline > 0.0).then(|| sym.size.max(1.0) * marker_reach(sym.marker) + outline / 2.0) } +/// The least a line is drawn wide, in pixels (`Ctx::line`). +const MIN_STROKE_PX: f32 = 0.5; + +/// How far a line's stroke reaches from its centre line, in points, as it is drawn: half the +/// widest of its stacked strokes' width, shifted by their offsets (a mark as far as its corners). None +/// where it shows nothing (a clear colour), so is in no label's way. Like a marker's, it counts as +/// no more than [`MAX_OBSTACLE_REACH`] from the line. +fn line_obstacle_reach(sym: &Symbol, strokes: &[LineStroke], px_per_point: f32) -> Option { + // (A stroke is drawn at least half a pixel wide, as `Ctx::line` has it.) + let half = |w: f32| w.max(MIN_STROKE_PX / px_per_point) / 2.0; + let reach = if strokes.is_empty() { + (sym.stroke.a() > 0).then(|| half(sym.stroke_width)) + } else { + strokes + .iter() + .filter_map(|s| match s.markers { + // A mark as far as its corners however it's turned (as `line_markers::reach`). + Some(m) => Some( + s.offset.abs() + + match m.mark { + LineMark::Marker(shape) => m.size.max(1.0) * marker_reach(shape).max(point_marks::turned_reach(shape)), + LineMark::Hash => m.size.max(0.0) / 2.0, + }, + ), + None => { + let drawn = s.color.map_or(sym.stroke.a() > 0, |c| c.a() > 0); + drawn.then(|| s.offset.abs() + half(s.width.unwrap_or(sym.stroke_width))) + } + }) + .reduce(f32::max) + }; + reach.filter(|r| *r > 0.0 && r.is_finite()) +} + +/// Calls `emit` with points along `parts` (lines in map coordinates, put on the screen by +/// `screen`), `step` points apart, those within `rect` (left, top, right, bottom) only: a segment +/// is cut to it first, so a line crossing the view from far off costs what shows. `emit` says +/// whether to go on. A stopped frame (see `cancel`) stops it, checked every few thousand vertices: +/// a line may have millions. +fn sample_line( + parts: &[Vec], + screen: &impl Fn(Coord) -> Option<(f64, f64)>, + step: f64, + rect: [f64; 4], + emit: &mut impl FnMut(f32, f32) -> bool, +) { + let inside = |(x, y): (f64, f64)| x >= rect[0] && y >= rect[1] && x <= rect[2] && y <= rect[3]; + let mut walked = 0usize; + for part in parts { + // A part of one vertex is a point where it shows. + if let [only] = part.as_slice() { + walked += 1; + if walked.is_multiple_of(cancel::EVERY) && cancel::requested() { + return; + } + if let Some(b) = screen(*only).filter(|&b| b.0.is_finite() && b.1.is_finite() && inside(b)) + && !emit(b.0 as f32, b.1 as f32) + { + return; + } + continue; + } + let mut before: Option<(f64, f64)> = None; + // Whether the segment before sampled its end, the vertex the next one starts at. + let mut sampled = false; + for &c in part { + walked += 1; + if walked.is_multiple_of(cancel::EVERY) && cancel::requested() { + return; + } + let here = screen(c).filter(|(x, y)| x.is_finite() && y.is_finite()); + if let (Some(a), Some(b)) = (before, here) { + // Liang-Barsky: the part of a to b inside `rect`, as fractions of it. + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let (mut t0, mut t1) = (0.0f64, 1.0f64); + let clipped = + [(-dx, a.0 - rect[0]), (dx, rect[2] - a.0), (-dy, a.1 - rect[1]), (dy, rect[3] - a.1)].into_iter().all(|(p, q)| { + if p == 0.0 { + return q >= 0.0; + } + let t = q / p; + if p < 0.0 { + t0 = t0.max(t); + } else { + t1 = t1.min(t); + } + t0 <= t1 + }); + if clipped { + let n = (dx.hypot(dy) * (t1 - t0) / step).ceil().max(1.0); + for i in u64::from(sampled && t0 == 0.0)..=(n as u64) { + let t = t0 + (t1 - t0) * i as f64 / n; + if !emit((a.0 + dx * t) as f32, (a.1 + dy * t) as f32) { + return; + } + } + } + sampled = clipped && t1 == 1.0; + } else { + sampled = false; + } + before = here; + } + } +} + /// What a frame's obstacles take, in bytes each, with the copies kept beside them (a checkpoint, a /// layer kept alone), the merge map, the placement's index and its grid: the list's 32 and about /// 220 more, measured at the worst case of one in every point of a frame (#3526). @@ -9650,7 +9799,8 @@ impl ObstacleMerge { } } -/// The points labels keep off ([`Obstacle`]), their boxes in a grid of their own. +/// The points, and samples of lines, labels keep off ([`Obstacle`]), their boxes in a grid of +/// their own. struct Obstacles { /// Made with the first point kept: a frame with none makes none. grid: Option, diff --git a/crates/render/src/obstacle_labels_tests.rs b/crates/render/src/obstacle_labels_tests.rs index 91e9696f87..2ebc8ea0d5 100644 --- a/crates/render/src/obstacle_labels_tests.rs +++ b/crates/render/src/obstacle_labels_tests.rs @@ -1,5 +1,5 @@ -//! A point layer's points as obstacles for labels (#3526): a label whose class's weight isn't -//! above the layer's obstacle weight isn't placed over one of them. +//! A point or line layer's points or lines as obstacles for labels (#3526, #3613): a label whose +//! class's weight isn't above the layer's obstacle weight isn't placed over one of them. use super::*; use rustgis_data::{Dataset, Field, FieldType, Value}; @@ -700,7 +700,7 @@ fn obstacles_past_the_limit_are_left_out_and_said() { let said = approximations::take(); OBSTACLE_LIMIT.with(|l| l.set(None)); assert_eq!(made, 3); - assert!(said.iter().any(|t| t.starts_with("hospitals: 7 points in view aren't kept off by labels")), "{said:?}"); + assert!(said.iter().any(|t| t.starts_with("hospitals: 7 points or lines in view aren't kept off by labels")), "{said:?}"); } /// A layer's points far from the view aren't projected: its rows are skipped by their extent, @@ -855,7 +855,7 @@ fn bands_that_pass_the_limit_together_say_what_they_left_out() { let said = approximations::take(); OBSTACLE_LIMIT.with(|l| l.set(None)); assert!(out.obstacles.len() <= one + 2, "{}", out.obstacles.len()); - let lost = format!("clinics: {} points in view aren't kept off by labels", one - 2); + let lost = format!("clinics: {} points or lines in view aren't kept off by labels", one - 2); assert!(said.iter().any(|t| t.starts_with(&lost)), "{lost}: {said:?}"); } @@ -867,8 +867,8 @@ fn what_is_left_out_is_said_as_one_total() { approximations::obstacles_left_out("hospitals", 4); approximations::obstacles_left_out("clinics", 1); let said = approximations::take(); - assert!(said.iter().any(|t| t.starts_with("hospitals: 7 points in view")), "{said:?}"); - assert!(said.iter().any(|t| t.starts_with("clinics: 1 points in view")), "{said:?}"); + assert!(said.iter().any(|t| t.starts_with("hospitals: 7 points or lines in view")), "{said:?}"); + assert!(said.iter().any(|t| t.starts_with("clinics: 1 points or lines in view")), "{said:?}"); assert!(approximations::take().is_empty(), "said once, then forgotten"); } @@ -891,7 +891,7 @@ fn standing_markers_share_the_frames_limit_and_are_none_when_paused() { let said = approximations::take(); OBSTACLE_LIMIT.with(|l| l.set(None)); assert!(rest.len() <= 2, "{}", rest.len()); - assert!(said.iter().any(|t| t.starts_with("hospitals: ") && t.contains("points in view")), "{said:?}"); + assert!(said.iter().any(|t| t.starts_with("hospitals: ") && t.contains("points or lines in view")), "{said:?}"); m.label_display.paused = true; assert!(upright_obstacles(&m, &shown, &markers, 0).is_empty()); } @@ -908,7 +908,7 @@ fn a_fallback_does_not_count_what_it_left_out_twice() { approximations::obstacles_uncount(before); approximations::obstacles_left_out("hospitals", 4); let said = approximations::take(); - assert!(said.iter().any(|t| t.starts_with("hospitals: 8 points in view")), "{said:?}"); + assert!(said.iter().any(|t| t.starts_with("hospitals: 8 points or lines in view")), "{said:?}"); assert!(!said.iter().any(|t| t.starts_with("clinics")), "{said:?}"); } @@ -968,3 +968,335 @@ fn a_stopped_frame_stops_gathering_obstacles() { let stopped = rows(true); assert!(stopped <= crate::cancel::EVERY, "{stopped} rows gathered after a stop"); } + +// Lines as obstacles (#3613). + +/// A layer, its labels off, with one 6 point line from `a` to `b` and the obstacle weight `weight`. +fn road(m: &mut Map, a: Coord, b: Coord, weight: u8) -> u32 { + let mut d = Dataset::new("roads", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + d.push(Some(Geometry::Line(vec![vec![a, b]])), vec![Value::Null]); + let id = m.add_dataset(d); + let l = m.layer_mut(id).unwrap(); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { stroke_width: 6.0, ..l.symbol(0) }); + l.labels.enabled = false; + l.labels.obstacle_weight = weight; + id +} + +/// A road of the weight `weight` straight across the view through the screen place `p`. +fn road_through(m: &mut Map, v: &View, p: (f32, f32), weight: u8) -> u32 { + road(m, at(v, (p.0 - 300.0, p.1)), at(v, (p.0 + 300.0, p.1)), weight) +} + +#[test] +fn a_line_layer_with_no_obstacle_weight_moves_nothing() { + let (mut m, _) = town(); + let v = view(); + let here = free(&m, &v); + road_through(&mut m, &v, here, 0); + assert!(near(placed(&mut m, &v).unwrap(), here)); +} + +#[test] +fn a_label_no_heavier_than_the_line_tries_another_place() { + let (mut m, id) = town(); + m.layer_mut(id).unwrap().labels.default.other_positions = true; + let v = view(); + let here = free(&m, &v); + road_through(&mut m, &v, here, 5); + let r = render(&mut m, &v).unwrap(); + assert!(label_of(&r).is_some() && !covers(&r, here), "{:?}", label_of(&r)); +} + +#[test] +fn with_no_other_place_a_label_over_a_line_is_unplaced() { + let (mut m, _) = town(); + let v = view(); + let here = free(&m, &v); + road_through(&mut m, &v, here, 5); + m.label_display.show_unplaced = true; + let r = render(&mut m, &v).unwrap(); + assert!(label_of(&r).is_none(), "{:?}", label_of(&r)); + assert_eq!(r.unplaced.iter().filter(|l| l.text == "Town").count(), 1); +} + +#[test] +fn a_heavier_label_goes_over_the_line() { + let (mut m, id) = town(); + m.layer_mut(id).unwrap().labels.default.weight = 6; + let v = view(); + let here = free(&m, &v); + road_through(&mut m, &v, here, 5); + assert!(near(placed(&mut m, &v).unwrap(), here)); +} + +#[test] +fn a_label_moved_by_hand_or_showing_all_goes_over_the_line() { + let v = view(); + let (base, id) = town(); + let here = free(&base, &v); + let mut shown = base.clone(); + shown.layer_mut(id).unwrap().labels.default.show_all = true; + road_through(&mut shown, &v, here, 10); + assert!(near(placed(&mut shown, &v).unwrap(), here)); + let mut moved = base; + road_through(&mut moved, &v, here, 10); + let to = at(&v, here); + let layer = moved.layer_mut(id).unwrap(); + let feature = layer.dataset.features.first().unwrap().id; + layer.labels.default.moved = vec![rustgis_map::symbology::MovedLabel { id: feature, at: [to.x, to.y] }]; + assert!(near(placed(&mut moved, &v).unwrap(), here)); +} + +#[test] +fn a_line_nobody_sees_is_no_obstacle() { + let v = view(); + let (base, _) = town(); + let here = free(&base, &v); + let hide: [(&str, fn(&mut rustgis_map::Layer)); 4] = [ + ("a clear stroke", |l| { + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { stroke: Rgba::new(0, 0, 0, 0), ..l.symbol(0) }); + }), + ("hidden", |l| l.visible = false), + ("out of its scale range", |l| l.min_scale = Some(1.0)), + ("a transparent layer", |l| l.transparency = 100.0), + ]; + for (case, set) in hide { + let mut m = base.clone(); + let id = road_through(&mut m, &v, here, 10); + set(m.layer_mut(id).unwrap()); + assert!(placed(&mut m, &v).is_some_and(|p| near(p, here)), "{case}"); + } +} + +#[test] +fn a_line_longer_than_the_view_is_still_an_obstacle_where_it_crosses_it() { + let (mut m, _) = town(); + let v = view(); + let here = free(&m, &v); + road(&mut m, at(&v, (here.0 - 5.0e6, here.1)), at(&v, (here.0 + 5.0e6, here.1)), 5); + assert!(placed(&mut m, &v).is_none_or(|p| !near(p, here))); +} + +#[test] +fn a_label_of_the_line_is_not_kept_off_its_own_line() { + let (mut m, id) = town(); + let v = view(); + // The town layer's own point at the centre, labelled at its centre, on a line layer. + let l = m.layer_mut(id).unwrap(); + l.labels.obstacle_weight = 10; + let mut d = Dataset::new("roads", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + d.push(Some(Geometry::Line(vec![vec![at(&v, (100.0, 300.0)), at(&v, (700.0, 300.0))]])), vec![Value::Text("Road".into())]); + let road_id = m.add_dataset(d); + let l = m.layer_mut(road_id).unwrap(); + l.labels.enabled = true; + l.labels.default.field = "name".into(); + l.labels.obstacle_weight = 10; + let r = render(&mut m, &v).unwrap(); + assert!(r.labels.iter().any(|l| l.text == "Road"), "{:?}", r.labels.iter().map(|l| &l.text).collect::>()); +} + +#[test] +fn a_line_layer_takes_an_obstacle_weight() { + let (mut m, _) = town(); + let v = view(); + let id = road_through(&mut m, &v, (400.0, 300.0), 5); + assert!(m.layer(id).unwrap().takes_obstacle_weight()); +} + +/// A layer of many lines costs what a layer of as many points does, not its vertices: its frame +/// holds no more obstacles than the limit and says what it left out. +#[test] +fn a_layer_of_many_long_lines_is_gathered_within_the_limit() { + let (mut m, _) = town(); + let v = view(); + let mut d = Dataset::new("roads", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + for i in 0..20_000 { + let (x0, y0) = ((i % 200) as f32 * 4.0 - 50.0, (i / 200) as f32 * 6.0 - 50.0); + let part: Vec = (0..50).map(|k| at(&v, (x0 + k as f32 * 20.0, y0 + (k % 3) as f32 * 5.0))).collect(); + d.push(Some(Geometry::Line(vec![part])), vec![Value::Null]); + } + let id = m.add_dataset(d); + let l = m.layer_mut(id).unwrap(); + l.labels.enabled = false; + l.labels.obstacle_weight = 5; + OBSTACLE_LIMIT.with(|l| l.set(Some(50_000))); + approximations::take(); + render(&mut m, &v).unwrap(); + let said = approximations::take(); + OBSTACLE_LIMIT.with(|l| l.set(None)); + assert!(said.iter().any(|t| t.starts_with("roads: ") && t.contains("points or lines")), "{said:?}"); +} + +/// A line of no width is drawn half a point wide, so it is an obstacle as that line. +#[test] +fn a_line_of_no_width_is_drawn_as_a_hairline_and_is_an_obstacle() { + let (mut m, _) = town(); + let v = view(); + let here = free(&m, &v); + let id = road_through(&mut m, &v, here, 5); + let l = m.layer_mut(id).unwrap(); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { stroke_width: 0.0, ..l.symbol(0) }); + assert!(placed(&mut m, &v).is_none_or(|p| !near(p, here))); +} + +#[test] +fn another_line_of_its_own_layer_is_an_obstacle() { + let v = view(); + let (m, _) = town(); + let here = free(&m, &v); + // The town's layer has a line through where its name would go. + let mut m = Map::new("Map"); + let mut d = Dataset::new("towns", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + d.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Text("Town".into())]); + d.push(Some(Geometry::Line(vec![vec![at(&v, (here.0 - 300.0, here.1)), at(&v, (here.0 + 300.0, here.1))]])), vec![Value::Null]); + let id = m.add_dataset(d); + let l = m.layer_mut(id).unwrap(); + l.labels.enabled = true; + l.labels.default.field = "name".into(); + assert!(near(placed(&mut m, &v).unwrap(), here), "weight 0"); + m.layer_mut(id).unwrap().labels.obstacle_weight = 5; + assert_eq!(placed(&mut m, &v), None); +} + +#[test] +fn turned_and_tilted_views_keep_off_a_line_too() { + for (bearing, pitch) in [(90.0, 0.0), (0.0, 30.0), (30.0, 30.0)] { + let (mut m, _) = town(); + let mut v = view(); + (v.camera.bearing, v.camera.pitch) = (bearing, pitch); + let here = free(&m, &v); + road_through(&mut m, &v, here, 5); + let r = render(&mut m, &v).unwrap(); + assert!(label_of(&r).is_none(), "turned {bearing}, tilted {pitch}: {:?}", label_of(&r)); + } +} + +/// A frame drawn from a kept picture keeps off a line as one drawn whole does. +#[test] +fn a_frame_drawn_from_a_kept_one_keeps_off_a_line_too() { + let v = view(); + let (mut m, towns) = town(); + let here = free(&m, &v); + let roads = road_through(&mut m, &v, here, 5); + m.layers.swap(0, 1); + for (i, id) in [towns, towns, towns, towns, roads, towns].into_iter().enumerate() { + let l = m.layer_mut(id).unwrap(); + let size = 16.0 + (i % 2) as f32; + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { size, ..l.symbol(0) }); + assert_eq!(placed(&mut m, &v), None, "frame {i}"); + } +} + +#[test] +fn a_layer_of_lines_in_the_limit_says_nothing() { + let (mut m, _) = town(); + let v = view(); + let here = free(&m, &v); + road_through(&mut m, &v, here, 5); + approximations::take(); + render(&mut m, &v).unwrap(); + let said = approximations::take(); + assert!(!said.iter().any(|t| t.contains("aren't kept off")), "{said:?}"); +} + +#[test] +fn a_layer_with_points_and_lines_keeps_both_off() { + let v = view(); + let (base, _) = town(); + let here = free(&base, &v); + for (case, line) in [("a point", false), ("a line", true)] { + let mut m = base.clone(); + let mut d = Dataset::new("mixed", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + if line { + d.push(Some(Geometry::Line(vec![vec![at(&v, (here.0 - 300.0, here.1)), at(&v, (here.0 + 300.0, here.1))]])), vec![Value::Null]); + d.push(Some(Geometry::Point(at(&v, (10.0, 10.0)))), vec![Value::Null]); + } else { + d.push(Some(Geometry::Point(at(&v, here))), vec![Value::Null]); + d.push(Some(Geometry::Line(vec![vec![at(&v, (10.0, 10.0)), at(&v, (20.0, 10.0))]])), vec![Value::Null]); + } + let id = m.add_dataset(d); + let l = m.layer_mut(id).unwrap(); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { size: 16.0, stroke_width: 6.0, ..l.symbol(0) }); + l.labels.enabled = false; + l.labels.obstacle_weight = 5; + assert_eq!(placed(&mut m, &v), None, "{case}"); + } +} + +/// A stroke wider than an obstacle counts as reaching leaves no gap along it: its samples are as +/// close as the obstacles they make are wide. +#[test] +fn a_very_wide_line_leaves_no_gap_along_it() { + let (mut m, _) = town(); + let v = view(); + let here = free(&m, &v); + let id = road(&mut m, at(&v, (here.0 - 100.0, here.1)), at(&v, (here.0 + 100.0, here.1)), 5); + let l = m.layer_mut(id).unwrap(); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { stroke_width: 400.0, ..l.symbol(0) }); + assert!(placed(&mut m, &v).is_none_or(|p| !near(p, here))); +} + +#[test] +fn a_lines_reach_covers_its_markers_and_its_hairline() { + let (mut m, _) = town(); + let id = road(&mut m, Coord::new(0.0, 0.0), Coord::new(0.1, 0.0), 5); + let sym = rustgis_map::Symbol { stroke_width: 0.0, ..m.layer(id).unwrap().symbol(0) }; + // Half a pixel, whatever the points in it. + assert_eq!(line_obstacle_reach(&sym, &[], 2.0), Some(0.125)); + let marked: rustgis_map::LineStroke = serde_json::from_value(serde_json::json!({"markers": {"size": 20.0}})).unwrap(); + assert!(line_obstacle_reach(&sym, &[marked], 1.0).unwrap() >= 12.0, "a 20 point circle reaches past half its size"); +} + +/// Once a frame is full, a line that doesn't come near it isn't counted as left out. +#[test] +fn a_line_that_misses_the_frame_is_not_counted_as_left_out() { + let (mut m, _) = town(); + let v = view(); + let mut d = Dataset::new("roads", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + for (a, b) in [((100.0, 100.0), (700.0, 100.0)), ((-2000.0, 300.0), (400.0, -2000.0))] { + d.push(Some(Geometry::Line(vec![vec![at(&v, a), at(&v, b)]])), vec![Value::Null]); + } + let id = m.add_dataset(d); + let l = m.layer_mut(id).unwrap(); + l.labels.enabled = false; + l.labels.obstacle_weight = 5; + OBSTACLE_LIMIT.with(|l| l.set(Some(3))); + approximations::take(); + render(&mut m, &v).unwrap(); + let said = approximations::take(); + OBSTACLE_LIMIT.with(|l| l.set(None)); + assert!(said.iter().any(|t| t.starts_with("roads: 1 points or lines")), "{said:?}"); +} + +#[test] +fn a_vertex_two_stretches_share_is_sampled_once() { + let mut at = Vec::new(); + let part = [(0.0, 0.0), (10.0, 0.0), (20.0, 0.0)].map(|(x, y)| Coord::new(x, y)).to_vec(); + sample_line(&[part], &|c| Some((c.x, c.y)), 5.0, [-100.0, -100.0, 100.0, 100.0], &mut |x, _| { + at.push(x); + true + }); + assert_eq!(at, [0.0, 5.0, 10.0, 15.0, 20.0]); +} + +/// On a globe a long edge is drawn along its great circle, and its obstacles lie on that arc, not +/// on the straight line between its ends on the screen. +#[test] +fn a_long_line_on_a_globe_is_kept_off_along_the_arc_it_draws() { + let mut m = Map::new("Map"); + // The middle of the great circle from 60° west to 60° east at 40° north. + let middle = Coord::new(0.0, (40.0_f64.to_radians().tan() / 60.0_f64.to_radians().cos()).atan().to_degrees()); + let id = points(&mut m, "towns", &[(middle, Some("Town"))]); + let l = m.layer_mut(id).unwrap(); + l.labels.enabled = true; + l.labels.default.field = "name".into(); + m.projection = rustgis_map::Projection::Globe; + let mut v = view(); + (v.camera.center, v.camera.res) = (lonlat_to_merc(Coord::new(0.0, 45.0)), 20_000.0); + assert!(placed(&mut m, &v).is_some(), "the label shows without the line"); + let roads = road(&mut m, Coord::new(-60.0, 40.0), Coord::new(60.0, 40.0), 5); + let l = m.layer_mut(roads).unwrap(); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { stroke_width: 60.0, ..l.symbol(0) }); + assert_eq!(placed(&mut m, &v), None); +} diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index b286347652..7ea82bc99d 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -1024,10 +1024,10 @@ fn crowding(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { } }); ui.end_row(); - // The layer's points as obstacles (#3526), for the layers the engine takes it for, whatever + // The layer's points or lines as obstacles (#3526, #3613), for the layers the engine takes it for, whatever // the class shown; 0 is none. if l.takes_obstacle_weight() { - let input_label = ui.label(tl!("Labels keep off these points: weight")); + let input_label = ui.label(tl!("Labels keep off these points or lines: weight")); // As the weight: scoped to its layer, written when let go. ui.push_id(("label_obstacle_weight", l.instance_id()), |ui| { let mut v = f64::from(l.labels.obstacle_weight); @@ -1036,7 +1036,7 @@ fn crowding(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { .add(egui::DragValue::new(&mut v).update_while_editing(false).range(LABEL_WEIGHT).speed(0.05).max_decimals(0)) .labelled_by(input_label.id) .on_hover_text(tl!( - "A label whose class's weight isn't above this isn't placed over one of this layer's points, except its own feature's. 0: the points are no obstacle." + "A label whose class's weight isn't above this isn't placed over one of this layer's points or lines, except its own feature's. 0: they are no obstacle." )); if drag.settled(ui, &r, &mut v) && label_weight(v) != l.labels.obstacle_weight { run(app, "labels.placement", c.params(json!({"obstacleWeight": label_weight(v)}))); @@ -1847,12 +1847,12 @@ mod tests { assert_eq!(h.state().session.undo_depth(), steps, "nothing to undo"); } - /// A point layer's obstacle weight (#3526) is shown and set in Position, under Weight: typed, - /// a fraction rounded; a layer of lines has no such row. + /// A point or line layer's obstacle weight (#3526, #3613) is shown and set in Position, under + /// Weight: typed, a fraction rounded; a layer of polygons has no such row. #[test] fn an_obstacle_weight_is_set_in_the_pane() { use egui::accesskit::Role; - const LABEL: &str = "Labels keep off these points: weight"; + const LABEL: &str = "Labels keep off these points or lines: weight"; let mut h = harness(with_cities()); h.run(); let cities = layer_id(h.state(), "Cities"); @@ -1874,12 +1874,12 @@ mod tests { // The class's own weight is left alone. let class_weight = h.state().session.map().layer_by_name("Cities").unwrap().labels.default.weight; assert_eq!(class_weight, rustgis_engine::map::symbology::DEFAULT_LABEL_WEIGHT); - // A layer of lines takes no obstacle weight, so the row isn't shown. + // A layer of lines takes it too. let rivers = layer_id(h.state(), "Rivers"); h.state_mut().session.run("layer.select", &json!({"layer": rivers})).unwrap(); h.run(); - assert!(h.query_by_role_and_label(Role::SpinButton, LABEL).is_none(), "no row for lines"); - // Nor for polygons, a graphics layer, or a cluster or heat map layer: the engine takes the + assert!(h.query_by_role_and_label(Role::SpinButton, LABEL).is_some(), "a row for lines"); + // Not for polygons, a graphics layer, or a cluster or heat map layer: the engine takes the // weight of none of them. let countries = layer_id(h.state(), "Countries"); h.state_mut().session.run("layer.select", &json!({"layer": countries})).unwrap(); diff --git a/docs/maintaining.md b/docs/maintaining.md index 3a84cef946..0b05976e80 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -211,9 +211,9 @@ Likewise a label class keeping other than 2 points free round its labels (`label step: an older reader would place the labels 2 points apart and save them again without the clearances, or run the step without it. -A layer whose points are obstacles for labels (`labels.placement` with an `obstacleWeight` other +A layer whose points or lines are obstacles for labels (`labels.placement` with an `obstacleWeight` other than 0) requires `label-obstacles`, in a layer, a saved style or a saved `labels.placement` step: -an older reader would place the labels over the points and save the layer again without the weight, +an older reader would place the labels over the points or lines and save the layer again without the weight, or run the step without it. A label class removing duplicates (`labels.placement` with a `removeDuplicates` distance) requires diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index f4c2ab56ce..1c36e6d319 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -695,22 +695,24 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: win over the towns' without moving the river layer above them, which would change what draws on top (`labels.placement={"layer": "Rivers", "weight": 8}`; a fraction is rounded and a number past 0 or 10 brought to it, with a notice; `null` is 5). -- **Obstacle weight** (Labeling pane › Position, under Weight, for a layer with points): how - much labels keep off a layer's points (0 to 10, 0 to start with: no obstacle). A label whose - class's **Weight** isn't above it isn't placed over one of those points: it tries its other +- **Obstacle weight** (Labeling pane › Position, under Weight, for a layer with points or lines): how + much labels keep off a layer's points and lines (0 to 10, 0 to start with: no obstacle). A label whose + class's **Weight** isn't above it isn't placed over one of those points or lines: it tries its other places where its class has them or its callout, else it is left out and shows in View Unplaced. - A heavier label goes over them. A label never keeps off its own feature's point, nor, for a + A heavier label goes over them. A line counts as wide as its stroke, along its drawn length + and as far as 512 points from the view; a line with no visible stroke is none. A label never keeps off + its own feature's point or line, nor, for a point's label, one in the same place on the screen in any layer (an annotation goes over the point it came from); it keeps off the other points, of its layer too. - Only the points drawn count (a clustered or heat map layer draws none), whether or not their - layer's labels are on; vector tile labels keep off them too. Points that show nothing (a wholly - transparent layer or symbol) are none. Points in one point of the screen count as one, so a - dense layer takes room as the view does, not as its rows do, and a marker counts as no more + Only the points and lines drawn count (a clustered or heat map layer draws none), whether or not their + layer's labels are on; vector tile labels keep off them too. Points and lines that show nothing (a wholly + transparent layer, symbol or stroke) are none. Points in one point of the screen count as one, so a + dense layer takes room as the view does, not as its rows do, and a marker or a line's stroke counts as no more than 32 points from its centre. A frame holds only as many obstacles as memory allows (never - fewer than 250,000): past that, the layer's remaining points aren't kept off, and a notice says - how many. Points a layer mask hides still count. The points of a graphics layer (its text and + fewer than 250,000): past that, the layer's remaining points and lines aren't kept off, and a notice says + how many. Points and lines a layer mask hides still count. The points of a graphics layer (its text and images) are no obstacle. A label moved by hand, one with Show all labels and locked labels are - drawn where they go, over them or not. Layers with points only for now; the row is the same for + drawn where they go, over them or not. Layers with points or lines for now (polygons come later); the row is the same for every class of the layer, and a command sets it too (`labels.placement={"layer": "Hospitals", "obstacleWeight": 5}`; a fraction is rounded and a number past 0 or 10 brought to it, with a notice; `0` or `null` turns it off). From 18ce8e029820be3389bbad6d425b687ea4c86f02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 13:24:52 -0500 Subject: [PATCH 02/10] fix(render): bound a line's obstacle samples and gather a globe's lines a part at a time (#3613) --- crates/render/src/lib.rs | 79 +++++++++++++--------- crates/render/src/obstacle_labels_tests.rs | 26 +++++-- 2 files changed, 65 insertions(+), 40 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index d38cd4e6b8..28992d1733 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6365,7 +6365,8 @@ fn render_frame( // The system is asked for the memory left only by a frame with that many obstacles. let ask_from = obstacle_check_from(); let mut left_out = 0usize; - // Whether the frame took all it may hold: the lines left aren't walked. + // Whether the frame took all it may hold: a line left is only checked for a stretch near + // the view, to count it. let mut full = false; // Adds an obstacle within what a frame may hold. let mut add = |o: Obstacle| { @@ -6406,36 +6407,44 @@ fn render_frame( if let Some(parts) = line { // A line's stretches near the view, as far as its stroke reaches. Once the frame is // full, a line is only checked for a stretch near the view, to count it. - // (On a globe, along the arcs it is drawn in, already on the screen.) - let arcs: Option>> = ctx.globe.as_ref().map(|g| { - let runs = parts.iter().flat_map(|p| globe_runs(g, p)); - runs.map(|r| r.into_iter().map(|(x, y)| Coord::new(f64::from(x), f64::from(y))).collect()).collect() - }); let (sym, strokes) = styler.style(row); let Some(reach) = line_obstacle_reach(&sym, strokes, ctx.ppp) else { continue }; - let parts = arcs.as_ref().unwrap_or(parts); - let screen = |c: Coord| if arcs.is_some() { Some((c.x, c.y)) } else { ctx.screen(c) }; - let rect = [-near, -near, right, bottom]; - if full { - // Walked no further than its first stretch near the frame, to count it. - let mut shows = false; - sample_line(parts, &screen, f64::from(MAX_OBSTACLE_REACH), rect, &mut |_, _| { - shows = true; - false - }); - left_out += usize::from(shows); - continue; - } let (owner, weight, r) = ((lid, label_id(row)), labels.obstacle_weight, reach * size_factor); + let rect = [-near, -near, right, bottom]; // As close as the obstacles are wide: they count as reaching no more than the cap. - sample_line(parts, &screen, f64::from(r.clamp(1.0, MAX_OBSTACLE_REACH)), rect, &mut |x, y| { - let kept = add(Obstacle { owner, x, y, r, weight }); - if !kept { - left_out += 1; - full = true; + let step = if full { MAX_OBSTACLE_REACH } else { r.clamp(1.0, MAX_OBSTACLE_REACH) }; + let (mut kept_all, mut shows) = (true, false); + let mut take = |x: f32, y: f32| { + shows = true; + // A full frame's line is walked no further than its first stretch near the view. + kept_all = !full && add(Obstacle { owner, x, y, r, weight }); + kept_all + }; + match &ctx.globe { + // On a globe, along the arcs it is drawn in, a part at a time: a stopped + // frame goes no further, and one part's arcs are held at once. + Some(g) => { + for part in parts { + if cancel::requested() { + break; + } + let arcs: Vec> = globe_runs(g, part) + .into_iter() + .map(|r| r.into_iter().map(|(x, y)| Coord::new(f64::from(x), f64::from(y))).collect()) + .collect(); + if !sample_line(&arcs, &|c| Some((c.x, c.y)), f64::from(step), rect, &mut take) { + break; + } + } } - kept - }); + None => { + sample_line(parts, &|c| ctx.screen(c), f64::from(step), rect, &mut take); + } + } + if shows && !kept_all { + left_out += 1; + full = true; + } continue; } let near_frame = |&(_, (x, y)): &(Coord, (f64, f64))| x >= -near && y >= -near && x <= right && y <= bottom; @@ -9641,7 +9650,7 @@ fn line_obstacle_reach(sym: &Symbol, strokes: &[LineStroke], px_per_point: f32) /// Calls `emit` with points along `parts` (lines in map coordinates, put on the screen by /// `screen`), `step` points apart, those within `rect` (left, top, right, bottom) only: a segment /// is cut to it first, so a line crossing the view from far off costs what shows. `emit` says -/// whether to go on. A stopped frame (see `cancel`) stops it, checked every few thousand vertices: +/// whether to go on, and this answers whether it did to the end. A stopped frame (see `cancel`) stops it, checked every few thousand vertices: /// a line may have millions. fn sample_line( parts: &[Vec], @@ -9649,7 +9658,7 @@ fn sample_line( step: f64, rect: [f64; 4], emit: &mut impl FnMut(f32, f32) -> bool, -) { +) -> bool { let inside = |(x, y): (f64, f64)| x >= rect[0] && y >= rect[1] && x <= rect[2] && y <= rect[3]; let mut walked = 0usize; for part in parts { @@ -9657,12 +9666,12 @@ fn sample_line( if let [only] = part.as_slice() { walked += 1; if walked.is_multiple_of(cancel::EVERY) && cancel::requested() { - return; + return false; } if let Some(b) = screen(*only).filter(|&b| b.0.is_finite() && b.1.is_finite() && inside(b)) && !emit(b.0 as f32, b.1 as f32) { - return; + return false; } continue; } @@ -9672,7 +9681,7 @@ fn sample_line( for &c in part { walked += 1; if walked.is_multiple_of(cancel::EVERY) && cancel::requested() { - return; + return false; } let here = screen(c).filter(|(x, y)| x.is_finite() && y.is_finite()); if let (Some(a), Some(b)) = (before, here) { @@ -9693,11 +9702,14 @@ fn sample_line( t0 <= t1 }); if clipped { - let n = (dx.hypot(dy) * (t1 - t0) / step).ceil().max(1.0); + // What shows is no longer than the rectangle's diagonal, whatever the rounding of + // where a segment with far ends was cut says. + let longest = ((rect[2] - rect[0]).hypot(rect[3] - rect[1]) / step).ceil(); + let n = (dx.hypot(dy) * (t1 - t0) / step).ceil().min(longest).max(1.0); for i in u64::from(sampled && t0 == 0.0)..=(n as u64) { let t = t0 + (t1 - t0) * i as f64 / n; if !emit((a.0 + dx * t) as f32, (a.1 + dy * t) as f32) { - return; + return false; } } } @@ -9708,6 +9720,7 @@ fn sample_line( before = here; } } + true } /// What a frame's obstacles take, in bytes each, with the copies kept beside them (a checkpoint, a diff --git a/crates/render/src/obstacle_labels_tests.rs b/crates/render/src/obstacle_labels_tests.rs index 2ebc8ea0d5..ec9abad706 100644 --- a/crates/render/src/obstacle_labels_tests.rs +++ b/crates/render/src/obstacle_labels_tests.rs @@ -1080,11 +1080,8 @@ fn a_line_longer_than_the_view_is_still_an_obstacle_where_it_crosses_it() { #[test] fn a_label_of_the_line_is_not_kept_off_its_own_line() { - let (mut m, id) = town(); + let mut m = Map::new("Map"); let v = view(); - // The town layer's own point at the centre, labelled at its centre, on a line layer. - let l = m.layer_mut(id).unwrap(); - l.labels.obstacle_weight = 10; let mut d = Dataset::new("roads", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); d.push(Some(Geometry::Line(vec![vec![at(&v, (100.0, 300.0)), at(&v, (700.0, 300.0))]])), vec![Value::Text("Road".into())]); let road_id = m.add_dataset(d); @@ -1093,6 +1090,7 @@ fn a_label_of_the_line_is_not_kept_off_its_own_line() { l.labels.default.field = "name".into(); l.labels.obstacle_weight = 10; let r = render(&mut m, &v).unwrap(); + // The name lies on the line, which is as heavy as it: placed by the exemption alone. assert!(r.labels.iter().any(|l| l.text == "Road"), "{:?}", r.labels.iter().map(|l| &l.text).collect::>()); } @@ -1271,13 +1269,13 @@ fn a_line_that_misses_the_frame_is_not_counted_as_left_out() { #[test] fn a_vertex_two_stretches_share_is_sampled_once() { - let mut at = Vec::new(); + let mut xs = Vec::new(); let part = [(0.0, 0.0), (10.0, 0.0), (20.0, 0.0)].map(|(x, y)| Coord::new(x, y)).to_vec(); sample_line(&[part], &|c| Some((c.x, c.y)), 5.0, [-100.0, -100.0, 100.0, 100.0], &mut |x, _| { - at.push(x); + xs.push(x); true }); - assert_eq!(at, [0.0, 5.0, 10.0, 15.0, 20.0]); + assert_eq!(xs, [0.0, 5.0, 10.0, 15.0, 20.0]); } /// On a globe a long edge is drawn along its great circle, and its obstacles lie on that arc, not @@ -1300,3 +1298,17 @@ fn a_long_line_on_a_globe_is_kept_off_along_the_arc_it_draws() { l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { stroke_width: 60.0, ..l.symbol(0) }); assert_eq!(placed(&mut m, &v), None); } + +/// A segment with ends far past any view is sampled no more than the view's diagonal holds: the +/// rounding of where it is cut grows with its length (this one was cut to 5,394 samples). +#[test] +fn a_stretch_with_ends_far_off_is_sampled_no_more_than_the_view_holds() { + let part = vec![Coord::new(1.82138025360104e19, 1.6849219897048633e19), Coord::new(-1.2442822639079865e20, -1.1510603256586877e20)]; + let mut count = 0usize; + sample_line(&[part], &|c| Some((c.x, c.y)), 1.0, [-512.0, -512.0, 1312.0, 1112.0], &mut |_, _| { + count += 1; + true + }); + // The diagonal of the rectangle, a sample a point. + assert!(count <= 2_582, "{count}"); +} From cd6f39fc5bf9e2aa1e4acdbcb12c6e62a63f7151 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 13:39:29 -0500 Subject: [PATCH 03/10] fix(render): no sample from a line stretch too long to measure (#3613) --- crates/render/src/lib.rs | 8 +++++--- crates/render/src/obstacle_labels_tests.rs | 18 +++++++++++++++--- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 28992d1733..e9c8ffde9c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6422,7 +6422,8 @@ fn render_frame( }; match &ctx.globe { // On a globe, along the arcs it is drawn in, a part at a time: a stopped - // frame goes no further, and one part's arcs are held at once. + // frame goes no further, and one part's arcs are held at once. (A part + // is bent whole, with no Cancel check, as the drawing bends it.) Some(g) => { for part in parts { if cancel::requested() { @@ -9688,8 +9689,9 @@ fn sample_line( // Liang-Barsky: the part of a to b inside `rect`, as fractions of it. let (dx, dy) = (b.0 - a.0, b.1 - a.1); let (mut t0, mut t1) = (0.0f64, 1.0f64); - let clipped = - [(-dx, a.0 - rect[0]), (dx, rect[2] - a.0), (-dy, a.1 - rect[1]), (dy, rect[3] - a.1)].into_iter().all(|(p, q)| { + // (Ends too far apart to measure between show no stretch.) + let clipped = (dx.is_finite() && dy.is_finite()) + && [(-dx, a.0 - rect[0]), (dx, rect[2] - a.0), (-dy, a.1 - rect[1]), (dy, rect[3] - a.1)].into_iter().all(|(p, q)| { if p == 0.0 { return q >= 0.0; } diff --git a/crates/render/src/obstacle_labels_tests.rs b/crates/render/src/obstacle_labels_tests.rs index ec9abad706..79024acef2 100644 --- a/crates/render/src/obstacle_labels_tests.rs +++ b/crates/render/src/obstacle_labels_tests.rs @@ -1126,7 +1126,7 @@ fn a_layer_of_many_long_lines_is_gathered_within_the_limit() { assert!(said.iter().any(|t| t.starts_with("roads: ") && t.contains("points or lines")), "{said:?}"); } -/// A line of no width is drawn half a point wide, so it is an obstacle as that line. +/// A line of no width is drawn half a pixel wide, so it is an obstacle as that line. #[test] fn a_line_of_no_width_is_drawn_as_a_hairline_and_is_an_obstacle() { let (mut m, _) = town(); @@ -1141,8 +1141,8 @@ fn a_line_of_no_width_is_drawn_as_a_hairline_and_is_an_obstacle() { #[test] fn another_line_of_its_own_layer_is_an_obstacle() { let v = view(); - let (m, _) = town(); - let here = free(&m, &v); + let (alone, _) = town(); + let here = free(&alone, &v); // The town's layer has a line through where its name would go. let mut m = Map::new("Map"); let mut d = Dataset::new("towns", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); @@ -1312,3 +1312,15 @@ fn a_stretch_with_ends_far_off_is_sampled_no_more_than_the_view_holds() { // The diagonal of the rectangle, a sample a point. assert!(count <= 2_582, "{count}"); } + +/// Ends so far apart that the stretch between them overflows give no sample that isn't a place. +#[test] +fn a_stretch_too_long_to_measure_gives_no_place_that_is_not_a_number() { + let part = vec![Coord::new(-f64::MAX, 100.0), Coord::new(f64::MAX, 100.0)]; + let mut bad = 0usize; + sample_line(&[part], &|c| Some((c.x, c.y)), 1.0, [-512.0, -512.0, 1312.0, 1112.0], &mut |x, y| { + bad += usize::from(!x.is_finite() || !y.is_finite()); + true + }); + assert_eq!(bad, 0); +} From 3315023a1b246af9554f7b722bea664312a9bba5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 13:49:31 -0500 Subject: [PATCH 04/10] fix(labels): a line's marks count as they show, and the command's help says lines (#3613) --- crates/engine/src/cmd/labels.rs | 2 +- crates/render/src/lib.rs | 33 ++++++++++++++-------- crates/render/src/obstacle_labels_tests.rs | 19 ++++++++++++- 3 files changed, 40 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 0287b8bce9..41df46a114 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -468,7 +468,7 @@ pub fn commands() -> Vec { .inputs(super::Inputs::single_layer) .when(need_feature_layer) .params( - r#"{"layer"?, "class"?: name (none: the Default class, by whatever name it has), "position"?: "auto"|"center"|"above"|"below"|"left"|"right"|"aboveRight"|"aboveLeft"|"belowRight"|"belowLeft"|"parallel" (along a line, straight)|"curved" (along a line, following its bends)|"perpendicular" (a point's, square to the nearest line of `to`, starting at the point; none that near: as auto) (required without offset, repeat, lineOffset, otherPositions, showAll, weight, obstacleWeight, clearance, removeDuplicates, callout, to, side, fit, abbreviations or guide), "to"?: {"layer": a line or polygon layer's name, "within"?: points (1 to 500; 20)} | null, "side"?: "away" (the side of the line the point isn't on; the default)|"left"|"right" (as the line runs), "offset"?: [right, down] points (-200 to 200 each) the label moves from where its position puts it ([0, 0]: none; perpendicular: [out along the normal, down as the text reads]; a label along a line isn't moved), "repeat"?: points (10 to 10000) between a line's labels, spaced out from the one at its middle, at most 32 a line (0 or null: the one at its middle; parallel and curved only), "lineOffset"?: points (-200 to 200) between a line and its label's nearest edge, above the line as the text reads, negative below it (0 or null: on the line; parallel and curved only), "otherPositions"?: bool (a label whose place is taken tries others: a point's round the point, corners first; a line's along the line, nearest its middle first, placed parallel or curved without a repeat; a polygon's goes first where its shape fits best inside it, then where it goes without this; then, if its text fits the box of the polygon on the screen, up to 16 places further inside, a text box from the first and then two, corners first, where all of it is inside and in view, or else round that box, corners first; true is refused for any other line label, and on polygons for a curved label or one along a guide), "fit"?: "auto"|"off" (curved along a line: "auto" abbreviates a name that can't follow the line, sets one longer than a third of it on its straightest stretch, and spreads one over labels.style's stretch of a line more than three times its length; "off" or null: as placed), "abbreviations"?: {word: abbreviation} (whole words a fitted label puts short, ignoring case, over the built-in English, Portuguese and Spanish list, as {"Creek": "Cr.", "Córrego": "Cór."}; null or {}: the built-in list alone), "showAll"?: bool (every label drawn, over the others where they crowd), "weight"?: 0 to 10 (where labels compete for a place, the heavier class's wins, whatever its layer's place; equal weights: the layer above, then the class listed first; a fraction rounded; null: 5), "obstacleWeight"?: 0 to 10 (the layer's, for layers with points, whatever class is named: a label whose class's weight isn't above it isn't placed over one of the layer's points, its own feature's aside; labels moved by hand go where they were put; a fraction rounded; 0 or null: no obstacle), "clearance"?: points (0 to 100: the room the class's labels keep free of other labels, two labels keeping both their clearances apart; null: 2), "removeDuplicates"?: points (1 to 2000: a label is left out within this distance of one placed before it for another feature of its layer and class with the same text; a label moved by hand always shows; false or null: off), "callout"?: true|false|points (5 to 500: a label crowded off its spot moves to a free one nearby, a line drawn back to its feature at most this long; true keeps its length, or 40; false, 0 or null: none; not labels along a line or with an icon), "guide"?: {"layer": a line layer's name (as ridge or valley lines; not drawn by this), "field"?: a field both layers have} | null (points and polygons, not perpendicular ones: each label curved along its guide line, the one with the feature's value in field, else the longest in view under the label inside its polygon, or the nearest to its point within the text's width; a feature with none its text fits along is labelled as without a guide; null: none)}"#, + r#"{"layer"?, "class"?: name (none: the Default class, by whatever name it has), "position"?: "auto"|"center"|"above"|"below"|"left"|"right"|"aboveRight"|"aboveLeft"|"belowRight"|"belowLeft"|"parallel" (along a line, straight)|"curved" (along a line, following its bends)|"perpendicular" (a point's, square to the nearest line of `to`, starting at the point; none that near: as auto) (required without offset, repeat, lineOffset, otherPositions, showAll, weight, obstacleWeight, clearance, removeDuplicates, callout, to, side, fit, abbreviations or guide), "to"?: {"layer": a line or polygon layer's name, "within"?: points (1 to 500; 20)} | null, "side"?: "away" (the side of the line the point isn't on; the default)|"left"|"right" (as the line runs), "offset"?: [right, down] points (-200 to 200 each) the label moves from where its position puts it ([0, 0]: none; perpendicular: [out along the normal, down as the text reads]; a label along a line isn't moved), "repeat"?: points (10 to 10000) between a line's labels, spaced out from the one at its middle, at most 32 a line (0 or null: the one at its middle; parallel and curved only), "lineOffset"?: points (-200 to 200) between a line and its label's nearest edge, above the line as the text reads, negative below it (0 or null: on the line; parallel and curved only), "otherPositions"?: bool (a label whose place is taken tries others: a point's round the point, corners first; a line's along the line, nearest its middle first, placed parallel or curved without a repeat; a polygon's goes first where its shape fits best inside it, then where it goes without this; then, if its text fits the box of the polygon on the screen, up to 16 places further inside, a text box from the first and then two, corners first, where all of it is inside and in view, or else round that box, corners first; true is refused for any other line label, and on polygons for a curved label or one along a guide), "fit"?: "auto"|"off" (curved along a line: "auto" abbreviates a name that can't follow the line, sets one longer than a third of it on its straightest stretch, and spreads one over labels.style's stretch of a line more than three times its length; "off" or null: as placed), "abbreviations"?: {word: abbreviation} (whole words a fitted label puts short, ignoring case, over the built-in English, Portuguese and Spanish list, as {"Creek": "Cr.", "Córrego": "Cór."}; null or {}: the built-in list alone), "showAll"?: bool (every label drawn, over the others where they crowd), "weight"?: 0 to 10 (where labels compete for a place, the heavier class's wins, whatever its layer's place; equal weights: the layer above, then the class listed first; a fraction rounded; null: 5), "obstacleWeight"?: 0 to 10 (the layer's, for layers with points or lines, whatever class is named: a label whose class's weight isn't above it isn't placed over one of the layer's points or lines, its own feature's aside; labels moved by hand go where they were put; a fraction rounded; 0 or null: no obstacle), "clearance"?: points (0 to 100: the room the class's labels keep free of other labels, two labels keeping both their clearances apart; null: 2), "removeDuplicates"?: points (1 to 2000: a label is left out within this distance of one placed before it for another feature of its layer and class with the same text; a label moved by hand always shows; false or null: off), "callout"?: true|false|points (5 to 500: a label crowded off its spot moves to a free one nearby, a line drawn back to its feature at most this long; true keeps its length, or 40; false, 0 or null: none; not labels along a line or with an icon), "guide"?: {"layer": a line layer's name (as ridge or valley lines; not drawn by this), "field"?: a field both layers have} | null (points and polygons, not perpendicular ones: each label curved along its guide line, the one with the feature's value in field, else the longest in view under the label inside its polygon, or the nearest to its point within the text's width; a feature with none its text fits along is labelled as without a guide; null: none)}"#, ), // Labels moved by hand (the Move Label tool, as QGIS's): kept by their feature's id. C::new("labels.move", "Move Label", "Labeling › Label Placement", |s, p| { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index e9c8ffde9c..f0f2eeea47 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6411,7 +6411,8 @@ fn render_frame( let Some(reach) = line_obstacle_reach(&sym, strokes, ctx.ppp) else { continue }; let (owner, weight, r) = ((lid, label_id(row)), labels.obstacle_weight, reach * size_factor); let rect = [-near, -near, right, bottom]; - // As close as the obstacles are wide: they count as reaching no more than the cap. + // As far apart as an obstacle reaches, which is no more than the cap, and at least + // a point: obstacles in one point of the screen are one. let step = if full { MAX_OBSTACLE_REACH } else { r.clamp(1.0, MAX_OBSTACLE_REACH) }; let (mut kept_all, mut shows) = (true, false); let mut take = |x: f32, y: f32| { @@ -6424,14 +6425,14 @@ fn render_frame( // On a globe, along the arcs it is drawn in, a part at a time: a stopped // frame goes no further, and one part's arcs are held at once. (A part // is bent whole, with no Cancel check, as the drawing bends it.) - Some(g) => { + Some(onto) => { for part in parts { if cancel::requested() { break; } - let arcs: Vec> = globe_runs(g, part) + let arcs: Vec> = globe_runs(onto, part) .into_iter() - .map(|r| r.into_iter().map(|(x, y)| Coord::new(f64::from(x), f64::from(y))).collect()) + .map(|run| run.into_iter().map(|(x, y)| Coord::new(f64::from(x), f64::from(y))).collect()) .collect(); if !sample_line(&arcs, &|c| Some((c.x, c.y)), f64::from(step), rect, &mut take) { break; @@ -9630,14 +9631,22 @@ fn line_obstacle_reach(sym: &Symbol, strokes: &[LineStroke], px_per_point: f32) strokes .iter() .filter_map(|s| match s.markers { - // A mark as far as its corners however it's turned (as `line_markers::reach`). - Some(m) => Some( - s.offset.abs() - + match m.mark { - LineMark::Marker(shape) => m.size.max(1.0) * marker_reach(shape).max(point_marks::turned_reach(shape)), - LineMark::Hash => m.size.max(0.0) / 2.0, - }, - ), + // A mark as far as its corners however it's turned (as `line_markers::reach`), and + // its outline half the stroke past them; one that shows nothing (as + // `line_markers::draw` has it) is none. + Some(m) => { + let width = s.width.unwrap_or(sym.stroke_width).max(0.0); + let color = s.color.unwrap_or(sym.stroke).a() > 0; + let outline = m.outline.is_some_and(|c| c.a() > 0) && width > 0.0; + let (shows, past) = match m.mark { + LineMark::Marker(shape) => { + let past = m.size.max(1.0) * marker_reach(shape).max(point_marks::turned_reach(shape)); + (color || outline, past + if outline { width / 2.0 } else { 0.0 }) + } + LineMark::Hash => (color && width > 0.0, m.size.max(0.0) / 2.0 + width / 2.0), + }; + (shows || line_markers::drawn_picture(&m).is_some()).then(|| s.offset.abs() + past) + } None => { let drawn = s.color.map_or(sym.stroke.a() > 0, |c| c.a() > 0); drawn.then(|| s.offset.abs() + half(s.width.unwrap_or(sym.stroke_width))) diff --git a/crates/render/src/obstacle_labels_tests.rs b/crates/render/src/obstacle_labels_tests.rs index 79024acef2..2d6c7a035e 100644 --- a/crates/render/src/obstacle_labels_tests.rs +++ b/crates/render/src/obstacle_labels_tests.rs @@ -1105,7 +1105,7 @@ fn a_line_layer_takes_an_obstacle_weight() { /// A layer of many lines costs what a layer of as many points does, not its vertices: its frame /// holds no more obstacles than the limit and says what it left out. #[test] -fn a_layer_of_many_long_lines_is_gathered_within_the_limit() { +fn a_layer_of_many_long_lines_says_what_the_limit_left_out() { let (mut m, _) = town(); let v = view(); let mut d = Dataset::new("roads", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); @@ -1324,3 +1324,20 @@ fn a_stretch_too_long_to_measure_gives_no_place_that_is_not_a_number() { }); assert_eq!(bad, 0); } + +/// Marks drawn in a clear colour without an outline show nothing, so keep nothing off; an outline +/// shows, and reaches past the mark by half the stroke. +#[test] +fn a_marked_stroke_reaches_only_as_it_shows() { + let (mut m, _) = town(); + let id = road(&mut m, Coord::new(0.0, 0.0), Coord::new(0.1, 0.0), 5); + let sym = rustgis_map::Symbol { stroke: Rgba::new(0, 0, 0, 0), stroke_width: 4.0, ..m.layer(id).unwrap().symbol(0) }; + let mut marked: rustgis_map::LineStroke = serde_json::from_value(serde_json::json!({"markers": {"size": 20.0}})).unwrap(); + assert_eq!(line_obstacle_reach(&sym, std::slice::from_ref(&marked), 1.0), None); + let bare = { + let sym = rustgis_map::Symbol { stroke: Rgba::new(0, 0, 0, 255), ..sym }; + line_obstacle_reach(&sym, std::slice::from_ref(&marked), 1.0).unwrap() + }; + marked.markers.as_mut().unwrap().outline = Some(Rgba::new(0, 0, 0, 255)); + assert_eq!(line_obstacle_reach(&sym, &[marked], 1.0), Some(bare + 2.0)); +} From 4ec04ba9e4a3628f1f9814af42a247c9af4ff9c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 14:25:16 -0500 Subject: [PATCH 05/10] fix(labels): a shorter obstacle weight row label, and a full globe frame counts lines unbent (#3613) --- crates/render/src/lib.rs | 9 +++++---- crates/render/src/mesh.rs | 2 +- crates/render/src/obstacle_labels_tests.rs | 6 +++--- crates/ui-egui/src/labelpane.rs | 4 ++-- 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index f0f2eeea47..3a39929a32 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -1503,7 +1503,7 @@ impl Ctx<'_> { } let (stroke, width, fill) = match g { Geometry::Point(_) | Geometry::MultiPoint(_) => return false, - Geometry::Line(_) => (s.stroke, (s.stroke_width * self.ppp).max(0.5), None), + Geometry::Line(_) => (s.stroke, (s.stroke_width * self.ppp).max(MIN_STROKE_PX), None), Geometry::Polygon(_) if self.wireframe => (s.stroke.with_alpha(255), s.stroke_width.max(1.0) * self.ppp, None), Geometry::Polygon(_) => (s.stroke, if s.stroke.a() > 0 { s.stroke_width.max(0.0) * self.ppp } else { 0.0 }, Some(s.fill)), }; @@ -6425,7 +6425,8 @@ fn render_frame( // On a globe, along the arcs it is drawn in, a part at a time: a stopped // frame goes no further, and one part's arcs are held at once. (A part // is bent whole, with no Cancel check, as the drawing bends it.) - Some(onto) => { + // (A full frame's line is only counted: not worth bending for that.) + Some(onto) if !full => { for part in parts { if cancel::requested() { break; @@ -6439,7 +6440,7 @@ fn render_frame( } } } - None => { + _ => { sample_line(parts, &|c| ctx.screen(c), f64::from(step), rect, &mut take); } } @@ -9616,7 +9617,7 @@ fn marker_obstacle_reach(sym: &Symbol, marks: &[LineStroke], px_per_point: f32) } /// The least a line is drawn wide, in pixels (`Ctx::line`). -const MIN_STROKE_PX: f32 = 0.5; +pub(crate) const MIN_STROKE_PX: f32 = 0.5; /// How far a line's stroke reaches from its centre line, in points, as it is drawn: half the /// widest of its stacked strokes' width, shifted by their offsets (a mark as far as its corners). None diff --git a/crates/render/src/mesh.rs b/crates/render/src/mesh.rs index 1bd5919607..469fba78c8 100644 --- a/crates/render/src/mesh.rs +++ b/crates/render/src/mesh.rs @@ -482,7 +482,7 @@ pub(crate) fn estimate_vertices(g: &Geometry, s: &Symbol, wireframe: bool) -> us pub(crate) fn stroke_reach(g: &Geometry, s: &Symbol, wireframe: bool, ppp: f32, map_per_px: f64) -> f64 { let width_px = match g { Geometry::Point(_) | Geometry::MultiPoint(_) => return 0.0, - Geometry::Line(_) if s.stroke.a() > 0 => (s.stroke_width * ppp).max(0.5), + Geometry::Line(_) if s.stroke.a() > 0 => (s.stroke_width * ppp).max(crate::MIN_STROKE_PX), Geometry::Line(_) => return 0.0, Geometry::Polygon(_) if wireframe => s.stroke_width.max(1.0) * ppp, Geometry::Polygon(_) if s.stroke_width > 0.0 && s.stroke.a() > 0 => s.stroke_width * ppp, diff --git a/crates/render/src/obstacle_labels_tests.rs b/crates/render/src/obstacle_labels_tests.rs index 2d6c7a035e..fc0cd1581a 100644 --- a/crates/render/src/obstacle_labels_tests.rs +++ b/crates/render/src/obstacle_labels_tests.rs @@ -1300,7 +1300,7 @@ fn a_long_line_on_a_globe_is_kept_off_along_the_arc_it_draws() { } /// A segment with ends far past any view is sampled no more than the view's diagonal holds: the -/// rounding of where it is cut grows with its length (this one was cut to 5,394 samples). +/// rounding of where it is cut grows with its length (this one was cut to 5,395 samples). #[test] fn a_stretch_with_ends_far_off_is_sampled_no_more_than_the_view_holds() { let part = vec![Coord::new(1.82138025360104e19, 1.6849219897048633e19), Coord::new(-1.2442822639079865e20, -1.1510603256586877e20)]; @@ -1309,8 +1309,8 @@ fn a_stretch_with_ends_far_off_is_sampled_no_more_than_the_view_holds() { count += 1; true }); - // The diagonal of the rectangle, a sample a point. - assert!(count <= 2_582, "{count}"); + // The diagonal of the rectangle (1,824 by 1,624 points) at a sample a point, and its end. + assert!(count <= 2_444, "{count}"); } /// Ends so far apart that the stretch between them overflows give no sample that isn't a place. diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index 7ea82bc99d..77911612b2 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -1027,7 +1027,7 @@ fn crowding(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { // The layer's points or lines as obstacles (#3526, #3613), for the layers the engine takes it for, whatever // the class shown; 0 is none. if l.takes_obstacle_weight() { - let input_label = ui.label(tl!("Labels keep off these points or lines: weight")); + let input_label = ui.label(tl!("Labels keep off this layer: weight")); // As the weight: scoped to its layer, written when let go. ui.push_id(("label_obstacle_weight", l.instance_id()), |ui| { let mut v = f64::from(l.labels.obstacle_weight); @@ -1852,7 +1852,7 @@ mod tests { #[test] fn an_obstacle_weight_is_set_in_the_pane() { use egui::accesskit::Role; - const LABEL: &str = "Labels keep off these points or lines: weight"; + const LABEL: &str = "Labels keep off this layer: weight"; let mut h = harness(with_cities()); h.run(); let cities = layer_id(h.state(), "Cities"); From f3ad53110438c80586e16371c3ad5ae34ddb96a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 14:37:33 -0500 Subject: [PATCH 06/10] fix(render): the lines of a point layer standing up in a tilted view are obstacles (#3613) --- crates/render/src/lib.rs | 18 +++++++----------- crates/render/src/obstacle_labels_tests.rs | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 3a39929a32..2306839fb6 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6344,18 +6344,13 @@ fn render_frame( let (first_label, first_obstacle) = (label_candidates.len(), label_obstacles.len()); // Its points as obstacles for labels (#3526), whether or not it labels them: those // drawn, as far as their markers reach. (Clusters and heat maps draw no points.) - // (A layer standing up over a tilted view has them from the markers drawn there.) // (A graphics layer's points are its text and images, no obstacle: its symbols draw none.) // A layer wholly transparent shows no points to keep off, and takes none of the room of those that do: // not gathered, nor kept, so that a kept frame gathers them when it shows again. let unseen = opacity <= 0.0; - if labels.obstacle_weight > 0 - && !unseen - && !display.paused - && layer.aggregation.is_none() - && !layer.graphics - && !upright.contains(&lid) - { + if labels.obstacle_weight > 0 && !unseen && !display.paused && layer.aggregation.is_none() && !layer.graphics { + // (A layer standing up over a tilted view has its points from the markers drawn there.) + let stands = upright.contains(&lid); // Only those near enough the frame to reach a label, so they cost what is in view. let near = f64::from(LabelGrid::MARGIN); let (right, bottom) = (ctx.view.width + near, ctx.view.height + near); @@ -6384,8 +6379,8 @@ fn render_frame( } let Some(g) = g else { continue }; let (points, line) = match g { - Geometry::Point(c) => (std::slice::from_ref(c), None), - Geometry::MultiPoint(v) => (v.as_slice(), None), + Geometry::Point(c) if !stands => (std::slice::from_ref(c), None), + Geometry::MultiPoint(v) if !stands => (v.as_slice(), None), Geometry::Line(parts) => (&[][..], Some(parts)), _ => continue, }; @@ -9662,7 +9657,8 @@ fn line_obstacle_reach(sym: &Symbol, strokes: &[LineStroke], px_per_point: f32) /// `screen`), `step` points apart, those within `rect` (left, top, right, bottom) only: a segment /// is cut to it first, so a line crossing the view from far off costs what shows. `emit` says /// whether to go on, and this answers whether it did to the end. A stopped frame (see `cancel`) stops it, checked every few thousand vertices: -/// a line may have millions. +/// a line may have millions. (On a globe a part is bent into its arcs before this, whole and with +/// no check, as the drawing bends it.) fn sample_line( parts: &[Vec], screen: &impl Fn(Coord) -> Option<(f64, f64)>, diff --git a/crates/render/src/obstacle_labels_tests.rs b/crates/render/src/obstacle_labels_tests.rs index fc0cd1581a..711a1a5f5a 100644 --- a/crates/render/src/obstacle_labels_tests.rs +++ b/crates/render/src/obstacle_labels_tests.rs @@ -1341,3 +1341,22 @@ fn a_marked_stroke_reaches_only_as_it_shows() { marked.markers.as_mut().unwrap().outline = Some(Rgba::new(0, 0, 0, 255)); assert_eq!(line_obstacle_reach(&sym, &[marked], 1.0), Some(bare + 2.0)); } + +/// A layer of points that stands up over a tilted view has lines too: its markers are gathered +/// where they stand, and its lines on the ground, as another layer's are. +#[test] +fn the_lines_of_a_layer_standing_up_in_a_tilted_view_are_obstacles() { + let (mut m, _) = town(); + let mut v = view(); + v.camera.pitch = 30.0; + let here = free(&m, &v); + let mut d = Dataset::new("mixed", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + d.push(Some(Geometry::Point(at(&v, (20.0, 580.0)))), vec![Value::Null]); + d.push(Some(Geometry::Line(vec![vec![at(&v, (here.0 - 300.0, here.1)), at(&v, (here.0 + 300.0, here.1))]])), vec![Value::Null]); + let id = m.add_dataset(d); + let l = m.layer_mut(id).unwrap(); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { stroke_width: 8.0, ..l.symbol(0) }); + l.labels.enabled = false; + l.labels.obstacle_weight = 5; + assert_eq!(placed(&mut m, &v), None); +} From be331c0405b3a69a39fa8b831052ce97386789b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 14:39:44 -0500 Subject: [PATCH 07/10] fix(render): only lines the drawing takes are obstacles, and no stacked stroke of no width (#3613) --- crates/render/src/lib.rs | 16 ++++++++++++-- crates/render/src/obstacle_labels_tests.rs | 25 ++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 2306839fb6..3d68db2444 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6404,6 +6404,17 @@ fn render_frame( // full, a line is only checked for a stretch near the view, to count it. let (sym, strokes) = styler.style(row); let Some(reach) = line_obstacle_reach(&sym, strokes, ctx.ppp) else { continue }; + // Only a line the drawing takes: by its extent, grown by how far its stacked + // strokes reach, in the cull of whoever drew the layer. + let drawn_cull = if gpu_done { &mesh_cull } else { &ctx.cull }; + let stacked = if strokes.is_empty() { 0.0 } else { line_markers::reach(strokes, sym.stroke_width) }; + let grown = f64::from(stacked * ctx.ppp) * map_per_px; + let culled = |e: &Extent| { + !Extent::new(e.min_x - grown, e.min_y - grown, e.max_x + grown, e.max_y + grown).intersects(drawn_cull) + }; + if globe.is_none() && extents.get(row).is_some_and(culled) { + continue; + } let (owner, weight, r) = ((lid, label_id(row)), labels.obstacle_weight, reach * size_factor); let rect = [-near, -near, right, bottom]; // As far apart as an obstacle reaches, which is no more than the cap, and at least @@ -9644,8 +9655,9 @@ fn line_obstacle_reach(sym: &Symbol, strokes: &[LineStroke], px_per_point: f32) (shows || line_markers::drawn_picture(&m).is_some()).then(|| s.offset.abs() + past) } None => { - let drawn = s.color.map_or(sym.stroke.a() > 0, |c| c.a() > 0); - drawn.then(|| s.offset.abs() + half(s.width.unwrap_or(sym.stroke_width))) + // As `stacked_path` has it: none of no width or a clear colour. + let (color, width) = s.resolve(sym); + (color.a() > 0 && width > 0.0).then(|| s.offset.abs() + half(width)) } }) .reduce(f32::max) diff --git a/crates/render/src/obstacle_labels_tests.rs b/crates/render/src/obstacle_labels_tests.rs index 711a1a5f5a..c5e19c9b27 100644 --- a/crates/render/src/obstacle_labels_tests.rs +++ b/crates/render/src/obstacle_labels_tests.rs @@ -1360,3 +1360,28 @@ fn the_lines_of_a_layer_standing_up_in_a_tilted_view_are_obstacles() { l.labels.obstacle_weight = 5; assert_eq!(placed(&mut m, &v), None); } + +/// A plain line the drawing culls, off the view but near enough a label's reach, is no obstacle. +#[test] +fn a_plain_line_the_drawing_culls_is_no_obstacle() { + let (mut m, _) = town(); + let v = view(); + road(&mut m, at(&v, (100.0, -400.0)), at(&v, (700.0, -400.0)), 5); + // A frame that may hold none says so of anything it gathers. + OBSTACLE_LIMIT.with(|l| l.set(Some(0))); + approximations::take(); + render(&mut m, &v).unwrap(); + let said = approximations::take(); + OBSTACLE_LIMIT.with(|l| l.set(None)); + assert!(!said.iter().any(|t| t.starts_with("roads: ")), "{said:?}"); +} + +/// A stacked stroke of no width isn't drawn, unlike a plain line of none: no obstacle. +#[test] +fn a_stacked_stroke_of_no_width_is_no_obstacle() { + let (mut m, _) = town(); + let id = road(&mut m, Coord::new(0.0, 0.0), Coord::new(0.1, 0.0), 5); + let sym = rustgis_map::Symbol { stroke: Rgba::new(0, 0, 0, 255), ..m.layer(id).unwrap().symbol(0) }; + let flat: rustgis_map::LineStroke = serde_json::from_value(serde_json::json!({"width": 0.0})).unwrap(); + assert_eq!(line_obstacle_reach(&sym, &[flat], 1.0), None); +} From 49469e40aa6340ac8ba60783e701371f7a2167db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 19:26:02 -0500 Subject: [PATCH 08/10] fix(render): lines a standing layer doesn't draw and blank marks are no obstacle (#3613) --- crates/render/src/lib.rs | 26 +++++++++---- crates/render/src/obstacle_labels_tests.rs | 44 +++++++++++++++++----- 2 files changed, 53 insertions(+), 17 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 3d68db2444..68a6678ffe 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6348,9 +6348,15 @@ fn render_frame( // A layer wholly transparent shows no points to keep off, and takes none of the room of those that do: // not gathered, nor kept, so that a kept frame gathers them when it shows again. let unseen = opacity <= 0.0; - if labels.obstacle_weight > 0 && !unseen && !display.paused && layer.aggregation.is_none() && !layer.graphics { - // (A layer standing up over a tilted view has its points from the markers drawn there.) - let stands = upright.contains(&lid); + // (A layer standing up over a tilted view has its points from the markers drawn there, and + // draws no lines in it, so none of those is an obstacle.) + if labels.obstacle_weight > 0 + && !unseen + && !display.paused + && layer.aggregation.is_none() + && !layer.graphics + && !upright.contains(&lid) + { // Only those near enough the frame to reach a label, so they cost what is in view. let near = f64::from(LabelGrid::MARGIN); let (right, bottom) = (ctx.view.width + near, ctx.view.height + near); @@ -6379,8 +6385,8 @@ fn render_frame( } let Some(g) = g else { continue }; let (points, line) = match g { - Geometry::Point(c) if !stands => (std::slice::from_ref(c), None), - Geometry::MultiPoint(v) if !stands => (v.as_slice(), None), + Geometry::Point(c) => (std::slice::from_ref(c), None), + Geometry::MultiPoint(v) => (v.as_slice(), None), Geometry::Line(parts) => (&[][..], Some(parts)), _ => continue, }; @@ -9603,6 +9609,11 @@ const SAME_PLACE: f32 = 1.0; /// The widest an image marker is drawn, in pixels (`picture_marker`): past it, the circle. const PICTURE_MARKER_MAX_PX: f32 = 1e5; +/// Whether a marker has no shape to draw: a space no font here shapes (`marker_path`). +fn blank_marker(marker: Marker) -> bool { + matches!(marker, Marker::Char(g) if g.ch.is_whitespace() && glyphs::shape(g).is_none()) +} + /// How far a marker reaches from its point, in points at its own size, as it is drawn: to its /// outline for a plain marker (an image that draws has none, and one that doesn't falls back to /// the circle, which does), by its marks when it has some. None where it shows nothing, so is in @@ -9611,8 +9622,7 @@ fn marker_obstacle_reach(sym: &Symbol, marks: &[LineStroke], px_per_point: f32) if !marks.is_empty() { return Some(point_marks::reach(sym, marks)); } - // A space has no shape: the drawing makes it nothing. - if matches!(sym.marker, Marker::Char(g) if g.ch.is_whitespace() && glyphs::shape(g).is_none()) { + if blank_marker(sym.marker) { return None; } // An image wider than `picture_marker` draws (100,000 pixels) is the circle, too. @@ -9648,7 +9658,7 @@ fn line_obstacle_reach(sym: &Symbol, strokes: &[LineStroke], px_per_point: f32) let (shows, past) = match m.mark { LineMark::Marker(shape) => { let past = m.size.max(1.0) * marker_reach(shape).max(point_marks::turned_reach(shape)); - (color || outline, past + if outline { width / 2.0 } else { 0.0 }) + ((color || outline) && !blank_marker(shape), past + if outline { width / 2.0 } else { 0.0 }) } LineMark::Hash => (color && width > 0.0, m.size.max(0.0) / 2.0 + width / 2.0), }; diff --git a/crates/render/src/obstacle_labels_tests.rs b/crates/render/src/obstacle_labels_tests.rs index c5e19c9b27..a22870a82e 100644 --- a/crates/render/src/obstacle_labels_tests.rs +++ b/crates/render/src/obstacle_labels_tests.rs @@ -1309,8 +1309,9 @@ fn a_stretch_with_ends_far_off_is_sampled_no_more_than_the_view_holds() { count += 1; true }); - // The diagonal of the rectangle (1,824 by 1,624 points) at a sample a point, and its end. - assert!(count <= 2_444, "{count}"); + // The diagonal of the rectangle (1,824 by 1,624 points), rounded up to 2,443 steps of a point: + // a sample more than steps, and no more than that. + assert!(count <= 2_445, "{count}"); } /// Ends so far apart that the stretch between them overflows give no sample that isn't a place. @@ -1342,23 +1343,34 @@ fn a_marked_stroke_reaches_only_as_it_shows() { assert_eq!(line_obstacle_reach(&sym, &[marked], 1.0), Some(bare + 2.0)); } -/// A layer of points that stands up over a tilted view has lines too: its markers are gathered -/// where they stand, and its lines on the ground, as another layer's are. +/// The lines of a layer of points standing up over a tilted view aren't drawn there, so they are +/// no obstacle: a label is never kept off what doesn't show. #[test] -fn the_lines_of_a_layer_standing_up_in_a_tilted_view_are_obstacles() { +fn the_undrawn_lines_of_a_layer_standing_up_in_a_tilted_view_are_no_obstacle() { let (mut m, _) = town(); let mut v = view(); v.camera.pitch = 30.0; let here = free(&m, &v); let mut d = Dataset::new("mixed", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); - d.push(Some(Geometry::Point(at(&v, (20.0, 580.0)))), vec![Value::Null]); + d.push(Some(Geometry::Point(at(&v, (-3000.0, 580.0)))), vec![Value::Null]); d.push(Some(Geometry::Line(vec![vec![at(&v, (here.0 - 300.0, here.1)), at(&v, (here.0 + 300.0, here.1))]])), vec![Value::Null]); let id = m.add_dataset(d); let l = m.layer_mut(id).unwrap(); - l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { stroke_width: 8.0, ..l.symbol(0) }); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { stroke: Rgba::new(255, 0, 0, 255), stroke_width: 8.0, ..l.symbol(0) }); l.labels.enabled = false; - l.labels.obstacle_weight = 5; - assert_eq!(placed(&mut m, &v), None); + let red = |m: &mut Map| { + let r = render(m, &v).unwrap(); + r.pixmap.pixels().iter().filter(|p| p.red() > 200 && p.green() < 60 && p.blue() < 60).count() + }; + // Flat, the line shows; tilted, nothing of it does. + let mut flat = v; + flat.camera.pitch = 0.0; + let shown = + render(&mut m.clone(), &flat).unwrap().pixmap.pixels().iter().filter(|p| p.red() > 200 && p.green() < 60 && p.blue() < 60).count(); + assert!(shown > 500, "{shown}"); + assert_eq!(red(&mut m), 0, "drawn in the tilted view"); + m.layer_mut(id).unwrap().labels.obstacle_weight = 5; + assert!(placed(&mut m, &v).is_some_and(|p| near(p, here))); } /// A plain line the drawing culls, off the view but near enough a label's reach, is no obstacle. @@ -1385,3 +1397,17 @@ fn a_stacked_stroke_of_no_width_is_no_obstacle() { let flat: rustgis_map::LineStroke = serde_json::from_value(serde_json::json!({"width": 0.0})).unwrap(); assert_eq!(line_obstacle_reach(&sym, &[flat], 1.0), None); } + +/// Marks that are a blank character draw nothing along a line, so keep nothing off. +#[test] +fn blank_character_marks_along_a_line_are_no_obstacle() { + let (mut m, _) = town(); + let id = road(&mut m, Coord::new(0.0, 0.0), Coord::new(0.1, 0.0), 5); + let sym = rustgis_map::Symbol { stroke: Rgba::new(0, 0, 0, 255), ..m.layer(id).unwrap().symbol(0) }; + let mut marked: rustgis_map::LineStroke = serde_json::from_value(serde_json::json!({"markers": {"size": 20.0}})).unwrap(); + let letter = |ch| rustgis_map::LineMark::Marker(Marker::Char(rustgis_map::symbology::Glyph::new(ch, ""))); + marked.markers.as_mut().unwrap().mark = letter(' '); + assert_eq!(line_obstacle_reach(&sym, std::slice::from_ref(&marked), 1.0), None); + marked.markers.as_mut().unwrap().mark = letter('A'); + assert!(line_obstacle_reach(&sym, &[marked], 1.0).is_some()); +} From 9e5189617908451ce7b712e15e4347b294e5bae1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 19:30:00 -0500 Subject: [PATCH 09/10] fix(render): a line of many vertices is sampled by its length on the screen (#3613) --- crates/render/src/lib.rs | 10 +++++++++- crates/render/src/obstacle_labels_tests.rs | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 68a6678ffe..e4a3f94619 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -9691,6 +9691,9 @@ fn sample_line( let inside = |(x, y): (f64, f64)| x >= rect[0] && y >= rect[1] && x <= rect[2] && y <= rect[3]; let mut walked = 0usize; for part in parts { + // The last sample of this part: the next is taken half a step or more from it, so a line of + // many vertices costs by its length on the screen. + let mut last: Option<(f64, f64)> = None; // A part of one vertex is a point where it shows. if let [only] = part.as_slice() { walked += 1; @@ -9738,7 +9741,12 @@ fn sample_line( let n = (dx.hypot(dy) * (t1 - t0) / step).ceil().min(longest).max(1.0); for i in u64::from(sampled && t0 == 0.0)..=(n as u64) { let t = t0 + (t1 - t0) * i as f64 / n; - if !emit((a.0 + dx * t) as f32, (a.1 + dy * t) as f32) { + let at = (a.0 + dx * t, a.1 + dy * t); + if last.is_some_and(|(x, y)| (at.0 - x).hypot(at.1 - y) < step / 2.0) { + continue; + } + last = Some(at); + if !emit(at.0 as f32, at.1 as f32) { return false; } } diff --git a/crates/render/src/obstacle_labels_tests.rs b/crates/render/src/obstacle_labels_tests.rs index a22870a82e..60456ecaaf 100644 --- a/crates/render/src/obstacle_labels_tests.rs +++ b/crates/render/src/obstacle_labels_tests.rs @@ -1411,3 +1411,19 @@ fn blank_character_marks_along_a_line_are_no_obstacle() { marked.markers.as_mut().unwrap().mark = letter('A'); assert!(line_obstacle_reach(&sym, &[marked], 1.0).is_some()); } + +/// A line of many vertices close together on the screen is sampled by its length there, not once +/// a vertex: each sample is at least half a step from the one before. +#[test] +fn a_line_of_many_vertices_is_sampled_by_its_length_on_the_screen() { + let part: Vec = (0..=10_000).map(|i| Coord::new(f64::from(i) * 0.01, 0.0)).collect(); + let mut xs: Vec = Vec::new(); + sample_line(&[part], &|c| Some((c.x, c.y)), 5.0, [-512.0, -512.0, 1312.0, 1112.0], &mut |x, _| { + xs.push(x); + true + }); + assert!(xs.len() <= 41, "{}", xs.len()); + // And leaves no gap of more than a step and a half along it. + assert!(xs.windows(2).all(|w| w[1] - w[0] <= 7.5), "{xs:?}"); + assert!(xs.first().is_some_and(|x| *x == 0.0) && xs.last().is_some_and(|x| *x >= 97.5), "{xs:?}"); +} From bbf66d7955d1534ed04ce73856516e71be84daf0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 2 Dec 2026 19:48:17 -0500 Subject: [PATCH 10/10] fix(render): sample the lines as drawn, count marks only along a line, skip the far side of a globe (#3613) --- crates/engine/src/cmd/labels.rs | 2 +- crates/render/src/lib.rs | 27 +++++++---------- crates/render/src/obstacle_labels_tests.rs | 34 ++++++++++++++++++++-- crates/ui-egui/src/labelpane.rs | 2 +- docs/user-guide/cartography.md | 3 +- 5 files changed, 46 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 41df46a114..0b1ecb66c4 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -293,7 +293,7 @@ pub fn commands() -> Vec { return Err(if !points && !lines { "obstacleWeight is for layers with points or lines: polygons aren't obstacles yet" } else if layer.graphics { - "obstacleWeight isn't for a graphics layer: its points are text and images, which draw no obstacle" + "obstacleWeight isn't for a graphics layer: its elements are no obstacle" } else { "obstacleWeight isn't for a cluster or heat map layer: it draws no points or lines" } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index e4a3f94619..c6f899282f 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -407,7 +407,7 @@ use rustgis_data::{Dataset, Geometry, GeometryType}; use rustgis_geom::{Coord, Extent, extent_to_merc, lonlat_to_merc}; use rustgis_map::globe::{V3, densify}; use rustgis_map::layout::TextAlign; -use rustgis_map::{Camera, Globe, LabelPlacement, LineMark, LineStroke, Map, Marker, Rgba, Symbol}; +use rustgis_map::{Camera, Globe, LabelPlacement, LineMark, LineStroke, Map, Marker, Placements, Rgba, Symbol}; pub use text::{covers_quietly, halo_reach}; /// The image type pages and maps are drawn into. pub use tiny_skia::Pixmap; @@ -6405,7 +6405,10 @@ fn render_frame( } }); } - if let Some(parts) = line { + if line.is_some() { + // The parts the drawing strokes: the view's thinned copy where it uses one, so a + // line costs here what it costs there, and an obstacle follows what shows. + let Some(Some(Geometry::Line(parts))) = drawn.get(row) else { continue }; // A line's stretches near the view, as far as its stroke reaches. Once the frame is // full, a line is only checked for a stretch near the view, to count it. let (sym, strokes) = styler.style(row); @@ -6421,6 +6424,10 @@ fn render_frame( if globe.is_none() && extents.get(row).is_some_and(culled) { continue; } + // On a globe, only lines it may show, as the drawing has it. + if globe.is_some() && !visible(&g.extent()) { + continue; + } let (owner, weight, r) = ((lid, label_id(row)), labels.obstacle_weight, reach * size_factor); let rect = [-near, -near, right, bottom]; // As far apart as an obstacle reaches, which is no more than the cap, and at least @@ -9651,6 +9658,8 @@ fn line_obstacle_reach(sym: &Symbol, strokes: &[LineStroke], px_per_point: f32) // A mark as far as its corners however it's turned (as `line_markers::reach`), and // its outline half the stroke past them; one that shows nothing (as // `line_markers::draw` has it) is none. + // (Marks only at places of it, its ends or its vertices, leave the rest bare.) + Some(m) if !m.at.has(Placements::INTERVAL) => None, Some(m) => { let width = s.width.unwrap_or(sym.stroke_width).max(0.0); let color = s.color.unwrap_or(sym.stroke).a() > 0; @@ -9688,25 +9697,11 @@ fn sample_line( rect: [f64; 4], emit: &mut impl FnMut(f32, f32) -> bool, ) -> bool { - let inside = |(x, y): (f64, f64)| x >= rect[0] && y >= rect[1] && x <= rect[2] && y <= rect[3]; let mut walked = 0usize; for part in parts { // The last sample of this part: the next is taken half a step or more from it, so a line of // many vertices costs by its length on the screen. let mut last: Option<(f64, f64)> = None; - // A part of one vertex is a point where it shows. - if let [only] = part.as_slice() { - walked += 1; - if walked.is_multiple_of(cancel::EVERY) && cancel::requested() { - return false; - } - if let Some(b) = screen(*only).filter(|&b| b.0.is_finite() && b.1.is_finite() && inside(b)) - && !emit(b.0 as f32, b.1 as f32) - { - return false; - } - continue; - } let mut before: Option<(f64, f64)> = None; // Whether the segment before sampled its end, the vertex the next one starts at. let mut sampled = false; diff --git a/crates/render/src/obstacle_labels_tests.rs b/crates/render/src/obstacle_labels_tests.rs index 60456ecaaf..cf7fcb3fac 100644 --- a/crates/render/src/obstacle_labels_tests.rs +++ b/crates/render/src/obstacle_labels_tests.rs @@ -1309,9 +1309,9 @@ fn a_stretch_with_ends_far_off_is_sampled_no_more_than_the_view_holds() { count += 1; true }); - // The diagonal of the rectangle (1,824 by 1,624 points), rounded up to 2,443 steps of a point: - // a sample more than steps, and no more than that. - assert!(count <= 2_445, "{count}"); + // The diagonal of the rectangle (1,824 by 1,624 points) is 2,442.2: at most 2,443 steps of a + // point, and a sample more than steps. + assert!(count <= 2_444, "{count}"); } /// Ends so far apart that the stretch between them overflows give no sample that isn't a place. @@ -1427,3 +1427,31 @@ fn a_line_of_many_vertices_is_sampled_by_its_length_on_the_screen() { assert!(xs.windows(2).all(|w| w[1] - w[0] <= 7.5), "{xs:?}"); assert!(xs.first().is_some_and(|x| *x == 0.0) && xs.last().is_some_and(|x| *x >= 97.5), "{xs:?}"); } + +/// Marks placed at a line's ends or middle alone leave the rest of it bare: only marks at every +/// interval keep labels off along the line. +#[test] +fn marks_only_at_places_of_a_line_are_no_obstacle_along_it() { + let (mut m, _) = town(); + let id = road(&mut m, Coord::new(0.0, 0.0), Coord::new(0.1, 0.0), 5); + let sym = rustgis_map::Symbol { stroke: Rgba::new(0, 0, 0, 255), ..m.layer(id).unwrap().symbol(0) }; + let marked: rustgis_map::LineStroke = serde_json::from_value(serde_json::json!({"markers": {"size": 20.0}})).unwrap(); + for (at, along) in + [(rustgis_map::Placements::LAST, false), (rustgis_map::Placements::INTERVAL.with(rustgis_map::Placements::LAST), true)] + { + let mut marked = marked; + marked.markers.as_mut().unwrap().at = at; + assert_eq!(line_obstacle_reach(&sym, &[marked], 1.0).is_some(), along, "{:?}", at.codes()); + } +} + +/// A part of one vertex isn't drawn as a line, so is no obstacle. +#[test] +fn a_part_of_one_vertex_is_no_obstacle() { + let mut count = 0usize; + sample_line(&[vec![Coord::new(10.0, 10.0)]], &|c| Some((c.x, c.y)), 1.0, [-512.0, -512.0, 1312.0, 1112.0], &mut |_, _| { + count += 1; + true + }); + assert_eq!(count, 0); +} diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index 77911612b2..06c159192e 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -989,7 +989,7 @@ fn square_to(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { /// weight, the heavier winning where labels compete; its clearance, the room its labels keep free /// of others; whether it removes duplicates, one label of a text where its features lie closer than /// so far (#2847); callouts, which move a crowded label to a free spot nearby with a line back -/// to its feature, no longer than so far; and, for a layer with points, the weight of its points as +/// to its feature, no longer than so far; and, for a layer with points or lines, the weight of those as /// obstacles for labels: the layer's, whichever class is shown (#3526). fn crowding(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { use rustgis_engine::map::symbology::{ diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 1c36e6d319..e88d2edfc2 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -700,7 +700,8 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: class's **Weight** isn't above it isn't placed over one of those points or lines: it tries its other places where its class has them or its callout, else it is left out and shows in View Unplaced. A heavier label goes over them. A line counts as wide as its stroke, along its drawn length - and as far as 512 points from the view; a line with no visible stroke is none. A label never keeps off + and as far as 512 points from the view; a line with no visible stroke is none. A stroke shifted sideways counts as far as its shift on + both sides, a dashed one across its gaps, and marks only where they repeat at every interval. A label never keeps off its own feature's point or line, nor, for a point's label, one in the same place on the screen in any layer (an annotation goes over the point it came from); it keeps off the other points, of its layer too.