From 8d2a62a004a034e93468ab662f0254e510c64144 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 19:04:02 -0500 Subject: [PATCH 1/4] feat(labels): try more places inside a polygon whose name fits --- crates/engine/src/cmd/labels.rs | 2 +- crates/render/src/area_labels.rs | 22 ++- crates/render/src/lib.rs | 123 ++++++++++----- crates/render/src/polygon_labels_tests.rs | 183 +++++++++++++++++++++- crates/tiles/src/symbols.rs | 2 +- crates/ui-egui/src/labelpane.rs | 4 +- docs/user-guide/cartography.md | 16 +- 7 files changed, 293 insertions(+), 59 deletions(-) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index d432b9be0c..ddededfbd1 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -430,7 +430,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, 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 is wider or taller than the box of the polygon on the screen, 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), "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, 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), "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/area_labels.rs b/crates/render/src/area_labels.rs index 8bdb6d6457..2777a9a625 100644 --- a/crates/render/src/area_labels.rs +++ b/crates/render/src/area_labels.rs @@ -386,9 +386,7 @@ pub(super) fn pole( #[cfg(test)] SEARCHES.with(|n| n.set(n.get() + 1)); let here = ctx.view; - // A text of no measurable shape counts as square; a very long or tall one as 20 to 1. - let aspect = if aspect.is_finite() && aspect > 0.0 { aspect.clamp(0.05, 20.0) } else { 1.0 }; - rings.iter_mut().flatten().for_each(|p| p.0 /= aspect); + let aspect = narrow(&mut rings, aspect); let (x, y) = rustgis_tiles::symbols::pole_of_inaccessibility(&rings, 1.0)?; let there = (x * aspect, y); let Some(to) = shown else { return Some((there, there)) }; @@ -397,6 +395,24 @@ pub(super) fn pole( Some(((x as f32, y as f32), there)) } +/// Narrows `rings` by a text `aspect` times as wide as it is tall, which makes its box a square +/// there, and returns the aspect used: a text of no measurable shape counts as square, a very long +/// or tall one as 20 to 1. +fn narrow(rings: &mut [Vec<(f32, f32)>], aspect: f32) -> f32 { + let aspect = if aspect.is_finite() && aspect > 0.0 { aspect.clamp(0.05, 20.0) } else { 1.0 }; + rings.iter_mut().flatten().for_each(|p| p.0 /= aspect); + aspect +} + +/// Whether a box `w` by `h` centred on a point lies whole inside `rings`, holes kept out (#3500): +/// the circle round the box, narrowed as [`pole`] narrows them, is inside. So a box that only just +/// fits may be refused, never one sticking out taken. +pub(super) fn holds(mut rings: Vec>, (w, h): (f32, f32)) -> impl Fn((f32, f32)) -> bool { + let aspect = narrow(&mut rings, w / h); + let reach = (w / aspect).hypot(h) / 2.0; + move |(x, y)| rustgis_tiles::symbols::signed_distance((x / aspect, y), &rings) >= reach +} + /// The rings of `g`'s label part as [`pole`] searches them, in the points of the view the frame is /// `shown` in (none: the frame's own), cut to the frame and that view with `clip`. pub(super) fn shown_rings( diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 63d11020fc..081727d16c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6798,6 +6798,9 @@ fn render_frame( rings[usize::from(clip)].get_or_init(|| area_labels::shown_rings(ctx, g, shown, clip)).as_ref() }; let pole = |clip: bool| area_labels::pole(ctx, ringed(clip)?.clone(), bw / bh, shown); + // The place a search found, in the view shown, and whether it searched + // the part in view: what the places further inside are counted from. + let mut from = None; // Where it goes first, when that isn't its label point: locked there, // the map place it was locked at (not what a search finds now, as along // a flat stretch many places are as good); not locked, the pole, when a @@ -6814,17 +6817,23 @@ fn render_frame( Some((x as f32, y as f32)).filter(|&at| point.is_some() || in_view(at)) } Some(_) => None, - None => pole(false) - .filter(|&(_, (px, py))| on_shown((f64::from(px), f64::from(py)))) - .or_else(|| if own_seen { None } else { pole(true) }) - .map(|(here, _)| here), + None => { + let whole = pole(false); + let inside = whole + .filter(|&(_, (px, py))| on_shown((f64::from(px), f64::from(py)))) + .map(|found| (found, false)) + .or_else(|| if own_seen { None } else { pole(true).map(|found| (found, true)) }); + // (With none in view, the whole one's: places near it may be.) + from = inside.or(whole.map(|found| (found, false))).map(|((_, there), clip)| (there, clip)); + inside.map(|((here, _), _)| here) + } }; // Its label point, where that is a place for it: not one out of view // when it has a place in view. let own = point.is_some() && (first.is_none() || locked_at.is_some() || own_seen); - // Locked at a place round the polygon, it needs neither place inside. - let locked_round = locked_at.is_some_and(|place| place >= 2); - if tries && !own && first.is_none() && !locked_round { + // Locked at a later place, it needs neither of the first two. + let locked_later = locked_at.is_some_and(|place| place >= 2); + if tries && !own && first.is_none() && !locked_later { continue; } // A callout's line goes back to the place inside when the label point @@ -6839,16 +6848,18 @@ fn render_frame( Some(globe) => globe.inverse(f64::from(x), f64::from(y)), None => flat.inverse(view.camera.to_map(f64::from(x), f64::from(y), view.width, view.height)), }; - // After both places inside, a name wider or taller than the box of its - // part goes round that box, upright in the view shown (#3484): the - // places a point's label tries, each as far off the box's side or corner. - // A name that fits stays on its own polygon: off the box of a large one it - // would read as another's. Not a label turned by its expression, whose box - // this isn't. A place off the view, or with none on the map for a lock to - // keep (past the globe's edge), isn't one, but keeps its slot. - let mut round = Vec::new(); - if let Some(place) = locked_at.filter(|_| tries && locked_round) { - // Locked there: the map place it was locked at, as the first inside is, + // After the first two places, those a point's label tries, in that order. + // A name wider or taller than the box of its part goes round that box + // (#3484), each as far off the box's side or corner. One that fits stays + // on its own polygon, off whose box it would read as another's: it goes + // a text box away from the first place, then two, where the whole of it + // is inside the polygon and in view (#3500). All upright in the view + // shown, and none for a label turned by its expression, whose box this + // isn't. A place not tried, or with none on the map for a lock to keep + // (past the globe's edge), keeps its slot. + let mut later = Vec::new(); + if let Some(place) = locked_at.filter(|_| tries && locked_later) { + // Locked there: the map place it was locked at, as the first is, // and like it no label where that has no place in this view. let target = map.label_lock_line_anchors.get(&key).copied().and_then(|anchor| match &globe { Some(globe) => globe.forward(anchor), @@ -6856,55 +6867,85 @@ fn render_frame( }); let Some((x, y)) = target else { continue }; // The slots before it (the label point's is the first), then its own. - round.resize(usize::from(place) - 2, LabelPlace::from((f32::NAN, f32::NAN))); - round.push(LabelPlace::from((x as f32, y as f32))); + later.resize(usize::from(place) - 2, LabelPlace::from((f32::NAN, f32::NAN))); + later.push(LabelPlace::from((x as f32, y as f32))); } else if tries && turned.is_none() && locked_at.is_none() && let Some((left, top, right, bottom)) = ringed(false).and_then(|r| area_labels::around(r)) - && (bw * label_factor > right - left || bh * label_factor > bottom - top) { - let along = |d: f32, lo: f32, hi: f32| { - if d < 0.0 { - lo - } else if d > 0.0 { - hi - } else { - (lo + hi) / 2.0 - } - }; - round.extend(LabelPlacement::Center.alternatives().map(|p| { - let (dx, dy) = p.offset(0.0, 0.0, 0.0, false); - let (px, py) = place_at((along(dx, left, right), along(dy, top, bottom)), p); - let there = (f64::from(px), f64::from(py)); - let here = Some(there).filter(|&at| on_shown(at)).and_then(|(x, y)| match shown { + // A place in the view shown as one in the frame's points. + let slot = |there: Option<(f32, f32)>| { + let here = there.and_then(|(px, py)| match shown { Some(to) => to .camera - .try_to_map(x, y, to.width, to.height) + .try_to_map(f64::from(px), f64::from(py), to.width, to.height) .map(|m| ctx.view.to_screen(m)) .map(|(x, y)| (x as f32, y as f32)), None => Some((px, py)), }); LabelPlace::from(here.filter(|&at| on_map(at).is_some()).unwrap_or((f32::NAN, f32::NAN))) - })); + }; + // Which way each goes, across and down. + let ways: Vec<_> = LabelPlacement::Center + .alternatives() + .map(|p| { + let sign = |d: f32| { + if d < 0.0 { + -1.0 + } else if d > 0.0 { + 1.0 + } else { + 0.0 + } + }; + let (dx, dy) = p.offset(0.0, 0.0, 0.0, false); + (p, sign(dx), sign(dy)) + }) + .collect(); + let (w, h) = (bw * label_factor, bh * label_factor); + if w > right - left || h > bottom - top { + let along = |way: f32, lo: f32, hi: f32| (lo + hi) / 2.0 + way * (hi - lo) / 2.0; + later.extend(ways.iter().map(|&(p, x, y)| { + let there = place_at((along(x, left, right), along(y, top, bottom)), p); + slot(Some(there).filter(|&(x, y)| on_shown((f64::from(x), f64::from(y))))) + })); + } else if let Some(((x0, y0), clip)) = from + && let Some(rings) = ringed(clip) + { + let holds = area_labels::holds(rings.clone(), (w, h)); + // Clear of a label of its size at the place before. + let (across, down) = (w + 2.0 * class.clearance, h + 2.0 * class.clearance); + let seen = |(x, y): (f32, f32)| { + [(x - w / 2.0, y - h / 2.0), (x + w / 2.0, y + h / 2.0)] + .into_iter() + .all(|(x, y)| on_shown((f64::from(x), f64::from(y)))) + }; + for boxes in [1.0, 2.0] { + later.extend(ways.iter().map(|&(_, x, y)| { + let there = place_at((x0 + x * boxes * across, y0 + y * boxes * down), class.placement); + slot(Some(there).filter(|&at| seen(at) && holds(at))) + })); + } + } } // Each place on the map, while the lock is taken (never from a tilted // view): it keeps the one it took. if tries && display.locked && lock.is_none() && !matches!(labels_to, Labels::Tilted(..)) { let label_point = (x as f32, y as f32); let mut anchors = vec![on_map(first.unwrap_or(label_point))]; - if own || !round.is_empty() { + if own || !later.is_empty() { anchors.push(own.then(|| on_map(label_point)).flatten()); } - anchors.extend(round.iter().map(|p: &LabelPlace| on_map((p.x, p.y)))); + anchors.extend(later.iter().map(|p: &LabelPlace| on_map((p.x, p.y)))); line_places = Some(LinePlaces { anchors, ..Default::default() }); } // The label point is the place after the first, so a lock that took it - // there finds it; without it, its slot stays before those round. - if tries && (own || !round.is_empty()) { + // there finds it; without it, its slot stays before the later ones. + if tries && (own || !later.is_empty()) { let (x, y) = if own { (lx, ly) } else { (f32::NAN, f32::NAN) }; line_alternatives.push(LabelPlace { x, y, angle: turned, glyphs: Vec::new() }); - line_alternatives.append(&mut round); + line_alternatives.append(&mut later); } let (px, py) = first.map_or((lx, ly), |first| place_at(first, class.placement)); places.push((0, px, py, turned, Vec::new())); diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index 2e08090ed3..3fb56c3a29 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -1,5 +1,5 @@ //! A polygon's label trying other places (#3268): its pole of inaccessibility first, then where -//! it goes without the setting, then round the polygon (#3484). +//! it goes without the setting, then more places inside (#3500) or round the polygon (#3484). use super::*; use rustgis_data::{Dataset, Field, FieldType, Value}; @@ -122,7 +122,7 @@ fn islet(rings: Vec, on: bool) -> (Map, u32) { fn every_place(m: &mut Map, v: &View) -> Vec<(f32, f32)> { let mut taken = Vec::new(); while let Some(&here) = places(m, v).first() { - assert!(taken.len() < 12, "{taken:?}"); + assert!(taken.len() < 24, "{taken:?}"); taken.push(here); block(m, v, &[here]); } @@ -924,8 +924,11 @@ fn a_place_past_the_globes_edge_is_not_tried_round_a_polygon() { #[test] fn a_name_that_fits_its_polygons_box_does_not_go_round_it() { let (mut m, _) = map(Geometry::Polygon(vec![u()]), true); - // Its two places inside, and no more. - assert_eq!(every_place(&mut m, &view()).len(), 2); + let v = view(); + let outline = &u()[0]; + for p in every_place(&mut m, &v) { + assert_eq!(side(screen_box(&v, outline), p), INSIDE, "{p:?}"); + } } #[test] @@ -994,7 +997,13 @@ fn a_polygon_labels_rings_are_thinned_once_whole_and_once_cut_to_the_view() { let low = view_at(0.0, 0.1); let u = u()[0].clone(); assert!(today(&low, &Geometry::Polygon(vec![vec![u.clone()]])).1 > 600.0); - for (rings, v, most) in [(small(), view(), 1), (u, low, 1), (small(), view_at(0.3643, 0.0), 2), (big()[0].clone(), east(), 2)] { + for (rings, v, most) in [ + (small(), view(), 1), + (square(0.0, 0.0, 0.4), view(), 1), + (u, low, 1), + (small(), view_at(0.3643, 0.0), 2), + (big()[0].clone(), east(), 2), + ] { let (mut m, _) = islet(rings, true); area_labels::THINNED.with(|n| n.set(0)); render(&mut m, &v).unwrap(); @@ -1002,3 +1011,167 @@ fn a_polygon_labels_rings_are_thinned_once_whole_and_once_cut_to_the_view() { assert!((1..=most).contains(&thinned), "{thinned} of at most {most}, at {:?}", v.camera.center); } } + +/// A square about 440 points across in [`view`]: room for every place inside. +fn wide() -> Vec> { + vec![square(0.0, 0.0, 0.2)] +} + +/// Room kept round "Lake", so its places inside stand well clear of one another's blockers. +const CLEAR: f32 = 20.0; + +/// [`map`] of the polygon `rings` with [`CLEAR`] round its name. +fn roomy(rings: Vec>, on: bool) -> (Map, u32) { + let (mut m, id) = map(Geometry::Polygon(vec![rings]), on); + m.layer_mut(id).unwrap().labels.default.clearance = CLEAR; + (m, id) +} + +/// Half the width and height of the "Lake" label's text. +fn half(m: &mut Map, v: &View) -> (f32, f32) { + let size = render(m, v).unwrap().labels.iter().find(|l| l.text == "Lake").expect("labelled").size; + let face = text::Face { bold: false, italic: false, serif: false, family: None }; + (text::spaced_block_width("Lake", size, face, 0.0) / 2.0, text::block_height("Lake", size) / 2.0) +} + +/// Whether the box `half` round `(x, y)` is in view and inside what `under` says the polygon is. +fn whole(rings: &[Vec], (hw, hh): (f32, f32), (x, y): (f32, f32), under: impl Fn((f32, f32)) -> Coord) -> bool { + [(x - hw, y - hh), (x + hw, y - hh), (x - hw, y + hh), (x + hw, y + hh)] + .into_iter() + .all(|(x, y)| (0.0..=800.0).contains(&x) && (0.0..=600.0).contains(&y) && depth(rings, under((x, y))) > 0.0) +} + +/// With both places inside taken, a name that fits goes to places a box away from the first, in +/// the order a point's label tries them, then two boxes away (#3500). +#[test] +fn with_both_places_inside_taken_a_name_that_fits_goes_to_more_places_inside() { + for (bearing, pitch) in [(0.0, 0.0), (90.0, 0.0), (30.0, 0.0), (0.0, 30.0)] { + let mut v = view(); + (v.camera.bearing, v.camera.pitch) = (bearing, pitch); + let (mut m, _) = roomy(wide(), true); + let (hw, hh) = half(&mut m, &v); + let taken = every_place(&mut m, &v); + let (x0, y0) = taken[0]; + let step = (2.0 * (hw + CLEAR), 2.0 * (hh + CLEAR)); + let wanted: Vec<(f32, f32)> = [1.0, 2.0] + .into_iter() + .flat_map(|boxes| ROUND.map(|(x, y)| (x0 + f32::from(x) * boxes * step.0, y0 + f32::from(y) * boxes * step.1))) + .collect(); + // Seen from above, the square's label point is its pole, one blocker takes both and every + // place has room. Tilted it is wider below: the pole is lower, the label point is a place + // of its own and some places further out don't fit. + let label_point = today(&v, &Geometry::Polygon(vec![wide()])); + let mut next = wanted.iter(); + let mut further = 0; + for &p in taken[1..].iter().filter(|&&p| !near(p, label_point)) { + assert!(next.any(|&w| near(p, w)), "turned {bearing}, tilted {pitch}: {p:?} out of order in {wanted:?}"); + assert!(whole(&wide(), (hw, hh), p, |p| at(&v, p)), "turned {bearing}, tilted {pitch}: {p:?}"); + further += 1; + } + let least = if pitch == 0.0 { 16 } else { 10 }; + assert!(further >= least, "turned {bearing}, tilted {pitch}: {taken:?}"); + assert_eq!(every_place(&mut roomy(wide(), true).0, &v), taken, "the same again"); + } +} + +#[test] +fn off_a_name_that_fits_has_one_place() { + assert_eq!(every_place(&mut roomy(wide(), false).0, &view()).len(), 1); +} + +#[test] +fn a_label_turned_by_an_expression_tries_no_more_places_inside() { + let (mut m, id) = roomy(wide(), true); + m.layer_mut(id).unwrap().labels.default.by.angle = Some("20".into()); + assert_eq!(every_place(&mut m, &view()).len(), 1); +} + +/// A polygon its name fits with no room for it a box away: no more places than before. +#[test] +fn a_place_inside_is_tried_only_where_the_whole_name_fits() { + // About 70 points by 30. + let rings = vec![ring(&[(-0.0315, -0.0135), (0.0315, -0.0135), (0.0315, 0.0135), (-0.0315, 0.0135)])]; + let (mut m, _) = map(Geometry::Polygon(vec![rings]), true); + assert_eq!(every_place(&mut m, &view()).len(), 1); +} + +#[test] +fn places_inside_keep_out_of_holes_and_in_the_labelled_part() { + let holed = vec![square(0.0, 0.0, 0.2), square(0.07, 0.05, 0.04)]; + let parts = Geometry::Polygon(vec![vec![square(0.3, 0.2, 0.03)], wide()]); + for (g, rings) in [(Geometry::Polygon(vec![holed.clone()]), holed), (parts, wide())] { + let (mut m, id) = map(g, true); + m.layer_mut(id).unwrap().labels.default.clearance = CLEAR; + let v = view(); + let size = half(&mut m, &v); + let taken = every_place(&mut m, &v); + assert!(taken.len() > 4, "{taken:?}"); + for &p in &taken[2..] { + assert!(whole(&rings, size, p, |p| at(&v, p)), "{p:?}"); + } + } +} + +/// With the first place against the view's right edge, the places right of it aren't tried. +#[test] +fn places_off_the_view_are_not_tried_inside() { + let (mut m, _) = roomy(wide(), true); + // The square's middle 20 points from the right edge. + let v = view_at(-0.3415, 0.0); + let size = half(&mut m, &v); + let taken = every_place(&mut m, &v); + assert!(taken.len() > 2 && taken.len() < 17, "{taken:?}"); + for &p in &taken[1..] { + assert!(whole(&wide(), size, p, |p| at(&v, p)), "{p:?}"); + } +} + +#[test] +fn with_its_label_point_out_of_view_the_places_inside_are_in_the_visible_part() { + let (mut m, _) = map(Geometry::Polygon(vec![big()]), true); + let v = east(); + let size = half(&mut m, &v); + let taken = every_place(&mut m, &v); + assert!(taken.len() > 4, "{taken:?}"); + for &p in &taken { + assert!(whole(&big(), size, p, |p| at(&v, p)), "{p:?}"); + } +} + +#[test] +fn on_the_globe_the_places_inside_stay_in_the_visible_part() { + let rings = [eastward()]; + let (mut m, _) = globe(&rings, true); + let v = globe_at(30.0); + let size = half(&mut m, &v); + let mut taken = Vec::new(); + while let Some(&here) = places(&mut m, &v).first() { + assert!(taken.len() < 24, "{taken:?}"); + taken.push(here); + block_at(&mut m, &[globe_under(&v, here)]); + } + assert!(taken.len() > 2, "{taken:?}"); + for &p in &taken[2..] { + assert!(whole(&rings, size, p, |p| globe_under(&v, p)), "{p:?}"); + } +} + +/// A lock keeps the place a label took inside, as the map moves under it. +#[test] +fn a_lock_keeps_a_place_inside() { + for taken in [2, 11] { + let (mut m, _) = roomy(wide(), true); + let v = view(); + // The first blocker takes the pole and the label point; each later one, one place. + for _ in 1..taken { + let here = one(&mut m, &v); + block(&mut m, &v, &[here]); + } + m.label_display.locked = true; + let before = at(&v, one(&mut m, &v)); + assert!(m.label_lock.as_ref().unwrap().iter().any(|(_, p)| usize::from(p.place) == taken), "{:?}", m.label_lock); + let moved = view_at(0.03, 0.02); + let after = at(&moved, one(&mut m, &moved)); + assert!((after.x - before.x).abs() < 2e-3 && (after.y - before.y).abs() < 2e-3, "{taken}: {before:?} {after:?}"); + } +} diff --git a/crates/tiles/src/symbols.rs b/crates/tiles/src/symbols.rs index aa530f0a63..7bc6800a9f 100644 --- a/crates/tiles/src/symbols.rs +++ b/crates/tiles/src/symbols.rs @@ -647,7 +647,7 @@ fn centroid(r: &[(f32, f32)]) -> Option<(f32, f32)> { } /// The distance from `p` to a polygon's edges: positive inside, negative outside. -fn signed_distance(p: (f32, f32), poly: &[Vec<(f32, f32)>]) -> f32 { +pub fn signed_distance(p: (f32, f32), poly: &[Vec<(f32, f32)>]) -> f32 { let mut inside = false; let mut best = f32::INFINITY; for ring in poly { diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index 5505ba5d1c..8bb6b42209 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -882,13 +882,13 @@ fn position(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { square_to(app, ui, l, c); } // Polygons: where the text fits best inside, tried before the label's own place (#3268), then - // round a polygon its name doesn't fit (#3484). Not for a label curved or along a guide, whose + // further inside (#3500) or round a polygon its name doesn't fit (#3484). Not for a label curved or along a guide, whose // course is its place. if l.geometry_type() == rustgis_engine::data::GeometryType::Polygon && c.it.places_inside_polygons() { ui.add_space(4.0); let mut on = c.it.other_positions; let help = tl!( - "The label goes where it fits best inside the polygon; if that is taken, where it goes without this, then round a polygon its text doesn't fit." + "The label goes where it fits best inside the polygon; if that is taken, where it goes without this, then elsewhere inside, or round a polygon its text doesn't fit." ); if ui.checkbox(&mut on, tl!("Try other places inside and around the polygon")).on_hover_text(help).changed() { run(app, "labels.placement", c.params(json!({"otherPositions": on}))); diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 20af3425fc..9f551b8dfc 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -806,21 +806,25 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: a name wider or taller than the polygon on the screen (a small country, an island) goes round it: just off the box round it, in the order round points (above right, above left, below right, below left, right, left, above, below), at the places in view (on the globe, those on it). A name - that fits that box stays on its polygon, so it never reads as a neighbour's. It is left out if - every place is taken (Labeling pane › Position › **Try other places inside and around the - polygon**, for polygon layers). A label turned by an angle expression doesn't go round it. With + that fits that box stays on its polygon, so it never reads as a neighbour's: it tries up to 16 + more places inside, in the same order, a text box (and the class's clearance) away from the + first place and then two, only where the whole name is inside the polygon, holes kept out, and + in view. It is left out if every place is taken (Labeling pane › Position › **Try other places + inside and around the polygon**, for polygon layers). A label turned by an angle expression + tries neither the places further inside nor those round the polygon. With the first place inside out of view, the label starts where it goes without this. With both places inside out of view, it goes where its shape fits best inside the part of the polygon in view, the view's edges counting as the polygon's own: it follows that part as the map moves (Lock - holds it), and if another label takes its place it goes round the polygon as above. On a multipolygon this is the part its label is for; + holds it), and if another label takes its place it goes further inside that part, or round the + polygon, as above. On a multipolygon this is the part its label is for; other parts in view don't take it. On the globe only the part on this side of the horizon counts: the shape is fitted to it, and what is behind the horizon is out of view. On a polygon more than 64 times longer than wide on screen, once narrowed to the text's shape, only its first 64 widths are searched. Curved labels and labels along a guide don't use it: the box is hidden for them, the command refuses to turn it on, and a setting already on has no effect. Off by default, as round points; the class's position and offset apply from each of the two places inside (Above - sets the name above that point), the offset alone to those round it, and Lock keeps the place - each label took + sets the name above that point, and the same from each place further inside), the offset alone + to those round it, and Lock keeps the place each label took (`labels.placement={"layer": "Lakes", "otherPositions": true}`). - **Other places along lines**: a Parallel or Curved label whose place at the middle is taken, or (curved) where the line bends too sharply, tries up to seven others along the same stretch, From c08788e4d37df61ff1c5fd48c81d734a253f7996 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 19:14:43 -0500 Subject: [PATCH 2/4] refactor(labels): name the search origin and size the test's view from the view --- crates/render/src/lib.rs | 6 +++--- crates/render/src/polygon_labels_tests.rs | 14 +++++++------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 081727d16c..10b54d674a 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6800,7 +6800,7 @@ fn render_frame( let pole = |clip: bool| area_labels::pole(ctx, ringed(clip)?.clone(), bw / bh, shown); // The place a search found, in the view shown, and whether it searched // the part in view: what the places further inside are counted from. - let mut from = None; + let mut search_origin = None; // Where it goes first, when that isn't its label point: locked there, // the map place it was locked at (not what a search finds now, as along // a flat stretch many places are as good); not locked, the pole, when a @@ -6824,7 +6824,7 @@ fn render_frame( .map(|found| (found, false)) .or_else(|| if own_seen { None } else { pole(true).map(|found| (found, true)) }); // (With none in view, the whole one's: places near it may be.) - from = inside.or(whole.map(|found| (found, false))).map(|((_, there), clip)| (there, clip)); + search_origin = inside.or(whole.map(|found| (found, false))).map(|((_, there), clip)| (there, clip)); inside.map(|((here, _), _)| here) } }; @@ -6910,7 +6910,7 @@ fn render_frame( let there = place_at((along(x, left, right), along(y, top, bottom)), p); slot(Some(there).filter(|&(x, y)| on_shown((f64::from(x), f64::from(y))))) })); - } else if let Some(((x0, y0), clip)) = from + } else if let Some(((x0, y0), clip)) = search_origin && let Some(rings) = ringed(clip) { let holds = area_labels::holds(rings.clone(), (w, h)); diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index 3fb56c3a29..dbead01e68 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -1035,10 +1035,10 @@ fn half(m: &mut Map, v: &View) -> (f32, f32) { } /// Whether the box `half` round `(x, y)` is in view and inside what `under` says the polygon is. -fn whole(rings: &[Vec], (hw, hh): (f32, f32), (x, y): (f32, f32), under: impl Fn((f32, f32)) -> Coord) -> bool { +fn whole(v: &View, rings: &[Vec], (hw, hh): (f32, f32), (x, y): (f32, f32), under: impl Fn((f32, f32)) -> Coord) -> bool { [(x - hw, y - hh), (x + hw, y - hh), (x - hw, y + hh), (x + hw, y + hh)] .into_iter() - .all(|(x, y)| (0.0..=800.0).contains(&x) && (0.0..=600.0).contains(&y) && depth(rings, under((x, y))) > 0.0) + .all(|(x, y)| (0.0..=v.width as f32).contains(&x) && (0.0..=v.height as f32).contains(&y) && depth(rings, under((x, y))) > 0.0) } /// With both places inside taken, a name that fits goes to places a box away from the first, in @@ -1065,7 +1065,7 @@ fn with_both_places_inside_taken_a_name_that_fits_goes_to_more_places_inside() { let mut further = 0; for &p in taken[1..].iter().filter(|&&p| !near(p, label_point)) { assert!(next.any(|&w| near(p, w)), "turned {bearing}, tilted {pitch}: {p:?} out of order in {wanted:?}"); - assert!(whole(&wide(), (hw, hh), p, |p| at(&v, p)), "turned {bearing}, tilted {pitch}: {p:?}"); + assert!(whole(&v, &wide(), (hw, hh), p, |p| at(&v, p)), "turned {bearing}, tilted {pitch}: {p:?}"); further += 1; } let least = if pitch == 0.0 { 16 } else { 10 }; @@ -1107,7 +1107,7 @@ fn places_inside_keep_out_of_holes_and_in_the_labelled_part() { let taken = every_place(&mut m, &v); assert!(taken.len() > 4, "{taken:?}"); for &p in &taken[2..] { - assert!(whole(&rings, size, p, |p| at(&v, p)), "{p:?}"); + assert!(whole(&v, &rings, size, p, |p| at(&v, p)), "{p:?}"); } } } @@ -1122,7 +1122,7 @@ fn places_off_the_view_are_not_tried_inside() { let taken = every_place(&mut m, &v); assert!(taken.len() > 2 && taken.len() < 17, "{taken:?}"); for &p in &taken[1..] { - assert!(whole(&wide(), size, p, |p| at(&v, p)), "{p:?}"); + assert!(whole(&v, &wide(), size, p, |p| at(&v, p)), "{p:?}"); } } @@ -1134,7 +1134,7 @@ fn with_its_label_point_out_of_view_the_places_inside_are_in_the_visible_part() let taken = every_place(&mut m, &v); assert!(taken.len() > 4, "{taken:?}"); for &p in &taken { - assert!(whole(&big(), size, p, |p| at(&v, p)), "{p:?}"); + assert!(whole(&v, &big(), size, p, |p| at(&v, p)), "{p:?}"); } } @@ -1152,7 +1152,7 @@ fn on_the_globe_the_places_inside_stay_in_the_visible_part() { } assert!(taken.len() > 2, "{taken:?}"); for &p in &taken[2..] { - assert!(whole(&rings, size, p, |p| globe_under(&v, p)), "{p:?}"); + assert!(whole(&v, &rings, size, p, |p| globe_under(&v, p)), "{p:?}"); } } From 2c543601c1528c45c18a6db3fd1b74f538646b0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 19:20:21 -0500 Subject: [PATCH 3/4] test(labels): the places further inside follow the class's position and offset --- crates/render/src/polygon_labels_tests.rs | 19 +++++++++++++++++++ crates/ui-egui/src/labelpane.rs | 4 ++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index dbead01e68..2df5de9162 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -1074,6 +1074,25 @@ fn with_both_places_inside_taken_a_name_that_fits_goes_to_more_places_inside() { } } +/// The class's position and offset move each place further inside as they move the first. +#[test] +fn the_places_further_inside_move_with_the_classs_position_and_offset() { + let v = view(); + let plain = every_place(&mut roomy(wide(), true).0, &v); + for (placement, offset) in [(LabelPlacement::Auto, [9.0, -6.0]), (LabelPlacement::Above, [0.0, 0.0])] { + let (mut m, id) = roomy(wide(), true); + let class = &mut m.layer_mut(id).unwrap().labels.default; + (class.placement, class.offset) = (placement, offset); + let moved = every_place(&mut m, &v); + assert_eq!(moved.len(), plain.len(), "{placement:?}: {moved:?}"); + let by = (moved[0].0 - plain[0].0, moved[0].1 - plain[0].1); + assert!(by.1 < -5.0, "{placement:?}: {by:?}"); + for (&a, &b) in plain.iter().zip(&moved) { + assert!(near((a.0 + by.0, a.1 + by.1), b), "{placement:?}: {a:?} {b:?} {by:?}"); + } + } +} + #[test] fn off_a_name_that_fits_has_one_place() { assert_eq!(every_place(&mut roomy(wide(), false).0, &view()).len(), 1); diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index 8bb6b42209..9aec98d4ae 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -882,8 +882,8 @@ fn position(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { square_to(app, ui, l, c); } // Polygons: where the text fits best inside, tried before the label's own place (#3268), then - // further inside (#3500) or round a polygon its name doesn't fit (#3484). Not for a label curved or along a guide, whose - // course is its place. + // further inside (#3500) or round a polygon its name doesn't fit (#3484). Not for a label curved + // or along a guide, whose course is its place. if l.geometry_type() == rustgis_engine::data::GeometryType::Polygon && c.it.places_inside_polygons() { ui.add_space(4.0); let mut on = c.it.other_positions; From 03d57a0da1455895b4e0efcec66e986a11047c9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 19:23:19 -0500 Subject: [PATCH 4/4] docs(labels): say the places inside are tested on the thinned outline --- crates/render/src/area_labels.rs | 5 +++-- crates/render/src/lib.rs | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/render/src/area_labels.rs b/crates/render/src/area_labels.rs index 2777a9a625..9d16bc93b3 100644 --- a/crates/render/src/area_labels.rs +++ b/crates/render/src/area_labels.rs @@ -405,8 +405,9 @@ fn narrow(rings: &mut [Vec<(f32, f32)>], aspect: f32) -> f32 { } /// Whether a box `w` by `h` centred on a point lies whole inside `rings`, holes kept out (#3500): -/// the circle round the box, narrowed as [`pole`] narrows them, is inside. So a box that only just -/// fits may be refused, never one sticking out taken. +/// the circle round the box, narrowed as [`pole`] narrows them, is inside, so a box that only just +/// fits may be refused. Inside the rings as given: of an outline of more than about +/// [`MAX_VERTICES`], the thinned one [`pole`] searches too, whose chords may pass over a notch. pub(super) fn holds(mut rings: Vec>, (w, h): (f32, f32)) -> impl Fn((f32, f32)) -> bool { let aspect = narrow(&mut rings, w / h); let reach = (w / aspect).hypot(h) / 2.0; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 10b54d674a..67be1665f8 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6916,6 +6916,7 @@ fn render_frame( let holds = area_labels::holds(rings.clone(), (w, h)); // Clear of a label of its size at the place before. let (across, down) = (w + 2.0 * class.clearance, h + 2.0 * class.clearance); + // (Two opposite corners stand for the box: the view is a rectangle.) let seen = |(x, y): (f32, f32)| { [(x - w / 2.0, y - h / 2.0), (x + w / 2.0, y + h / 2.0)] .into_iter()