diff --git a/crates/data/src/geometry.rs b/crates/data/src/geometry.rs index faa7df5a06..ec1961e065 100644 --- a/crates/data/src/geometry.rs +++ b/crates/data/src/geometry.rs @@ -310,6 +310,15 @@ impl Geometry { false } + /// The part of a polygon [`label_point`](Self::label_point) places its point in: the largest + /// valid one. `None` for other geometries. + pub fn label_part(&self) -> Option<&Vec>> { + match self { + Geometry::Polygon(polys) => largest_part(polys), + _ => None, + } + } + /// A point for a label or a pop-up: the point itself, the middle vertex of the longest line /// part, or the centroid of the largest valid polygon (moved inside it if the centroid falls out). /// diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 3442a0bbd2..9423ae2684 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -275,7 +275,8 @@ pub fn commands() -> Vec { // `to: null`: this call takes the line away. let clears = matches!(to, Some(None)); let id = s.layer_id(p)?; - let (points, lines) = points_and_lines(s.map().layer(id).ok_or("no such layer")?); + let held = held_geometries(s.map().layer(id).ok_or("no such layer")?); + let (_, lines, _) = held; let guide = label_guide(s, p, s.map().layer(id).ok_or("no such layer")?)?; // A repeat or line offset given where it does nothing (not along a line), kept for // when the class is placed along one, and said (#2639). @@ -344,8 +345,8 @@ pub fn commands() -> Vec { } // Asked of the class as this call leaves it, so a position or a repeat given with // it counts. On where it would do nothing is refused; off is taken anywhere. - if others == Some(true) && !tries_other_places(points, lines, c) { - return Err("otherPositions is for points, and for lines placed parallel or curved without a repeat".into()); + if others == Some(true) && !tries_other_places(held, c) { + return Err("otherPositions is for points, for polygons whose labels aren't curved or along a guide, and for lines placed parallel or curved without a repeat".into()); } if !(lines && c.placement.along_line()) { if repeat.is_some_and(|r| r.is_some()) { @@ -429,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; true is refused for any other line label and on polygons), "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; 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| { @@ -598,10 +599,10 @@ pub fn commands() -> Vec { ] } -/// Whether the layer holds points and lines: declared so, or among its features, as the renderer +/// Whether the layer holds points, lines and polygons: declared so, or among its features, as the renderer /// goes by each feature's geometry. -fn points_and_lines(l: &Layer) -> (bool, bool) { - (l.has_geometry(GeometryType::Point), l.has_geometry(GeometryType::Polyline)) +fn held_geometries(l: &Layer) -> (bool, bool, bool) { + (l.has_geometry(GeometryType::Point), l.has_geometry(GeometryType::Polyline), l.has_geometry(GeometryType::Polygon)) } /// `labels.placement`'s `to`: the line or polygon layer a perpendicular label is square to, by @@ -665,11 +666,12 @@ fn label_guide(s: &Session, p: &Value, labelled: &Layer) -> Result bool { - points || (lines && c.placement.along_line() && c.repeat.is_none()) +fn tries_other_places((points, lines, polygons): (bool, bool, bool), c: &LabelClass) -> bool { + points || (lines && c.placement.along_line() && c.repeat.is_none()) || (polygons && c.places_inside_polygons()) } /// `labels.by`: sets a label class's expressions, each checked against the layer's fields. @@ -776,21 +778,24 @@ pub(crate) fn lock_holds(l: &Layer, b: &Labeling) -> bool { /// Whether the layer's classes and those of `b` (listed alike) put their labels in the same places. /// A lock names the place round its point or along its line a label took by its number among its -/// class's (#1011, #1187), so another position, or trying the others turned on or off, locks the +/// class's (#1011, #1187, #3268), so another position, or trying the others turned on or off, locks the /// labels again; with no class trying them a new position keeps the lock, as before. The flag only /// counts where it has an effect: kept on a line's class at a position off the line, or with a /// repeat, it does nothing ([`tries_other_places`]). Along a line, off it, each place is tried on /// both sides, the label's own first: its number says which, so the other side, or a distance /// where there was none, locks the labels again too; another distance on the same side doesn't. fn same_places(l: &Layer, b: &Labeling) -> bool { - let (points, lines) = points_and_lines(l); + let held = held_geometries(l); + let (_, lines, _) = held; let classes = |labels: &Labeling| { - let tries = |c: &LabelClass| c.other_positions && tries_other_places(points, lines, c); + let tries = |c: &LabelClass| c.other_positions && tries_other_places(held, c); // -1 below, 1 above, 0 on the line (-0.0 too). let side = |c: &LabelClass| { if lines && c.placement.along_line() { i8::from(c.line_offset > 0.0) - i8::from(c.line_offset < 0.0) } else { 0 } }; - labels.classes.iter().chain([&labels.default]).map(|c| (c.placement, tries(c), c.repeat.is_some(), side(c))).collect::>() + // A repeat counts only along a line, where it places labels. + let repeats = |c: &LabelClass| lines && c.placement.along_line() && c.repeat.is_some(); + labels.classes.iter().chain([&labels.default]).map(|c| (c.placement, tries(c), repeats(c), side(c))).collect::>() }; classes(&l.labels).into_iter().zip(classes(b)).all(|(x, y)| x == y || !(x.1 || y.1)) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 49fd20805d..e5b169c8dc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9564,8 +9564,8 @@ fn converting_labels_along_lines_says_what_they_lose() { /// A point label class tries the other places round its point when told to (#1011): alone it keeps /// the position, junk is refused (in it or in the position) and so is turning it on for lines at a -/// position off them and for polygons, it undoes, the project keeps it, and turning it on or off -/// while the labels are locked locks them again (the places they took no longer stand). +/// position off them, it undoes, the project keeps it, and turning it on or off while the labels +/// are locked locks them again (the places they took no longer stand). #[test] fn labels_take_other_positions_round_points() { use crate::render::View; @@ -9591,12 +9591,11 @@ fn labels_take_other_positions_round_points() { assert!(!class(&s).0); s.run("labels.placement", &json!({"layer": "Cities", "position": null, "otherPositions": false})).unwrap(); assert_eq!(class(&s), (false, placement), "null is no position"); - // Only a point's label goes round it: on is refused for a line off its line (along it, see - // labels_take_other_positions_along_lines) and for polygons, off taken anywhere. - for layer in ["Rivers", "Countries"] { - assert!(s.run("labels.placement", &json!({"layer": layer, "otherPositions": true})).is_err(), "{layer}"); - s.run("labels.placement", &json!({"layer": layer, "otherPositions": false})).unwrap(); - } + // On is refused for a line off its line (along it, see + // labels_take_other_positions_along_lines; polygons, labels_take_other_positions_in_polygons), + // off taken anywhere. + assert!(s.run("labels.placement", &json!({"layer": "Rivers", "otherPositions": true})).is_err()); + s.run("labels.placement", &json!({"layer": "Rivers", "otherPositions": false})).unwrap(); s.run("labels.placement", &json!({"layer": "Cities", "otherPositions": true})).unwrap(); let text = serde_json::to_string(&s.project).unwrap(); assert!(Session::new(serde_json::from_str(&text).unwrap()).map().layer_by_name("Cities").unwrap().labels.default.other_positions); @@ -9614,6 +9613,52 @@ fn labels_take_other_positions_round_points() { assert!(s.map().label_lock.is_none(), "turned on: locked again"); } +/// A polygon label class tries its pole of inaccessibility when told to (#3268): at any position +/// but curved, and without a guide. A refusal changes nothing, it undoes, the project keeps it, and +/// turning it on or off locks the labels again. +#[test] +fn labels_take_other_positions_in_polygons() { + use crate::render::View; + let mut s = world(); + let id = s.map().layer_by_name("Countries").unwrap().id; + let on = |s: &Session| s.map().layer(id).unwrap().labels.default.other_positions; + assert!(!on(&s)); + s.run("labels.placement", &json!({"layer": id, "otherPositions": true})).unwrap(); + assert!(on(&s)); + s.run("edit.undo", &json!({})).unwrap(); + assert!(!on(&s), "undoes"); + for position in ["center", "above", "parallel"] { + s.run("labels.placement", &json!({"layer": id, "position": position, "otherPositions": true})).unwrap(); + s.run("labels.placement", &json!({"layer": id, "otherPositions": false})).unwrap(); + } + s.run("labels.placement", &json!({"layer": id, "position": "auto"})).unwrap(); + assert!(s.run("labels.placement", &json!({"layer": id, "position": "curved", "otherPositions": true})).is_err()); + let guide = json!({"layer": "Rivers"}); + assert!(s.run("labels.placement", &json!({"layer": id, "guide": guide, "otherPositions": true})).is_err()); + let class = &s.map().layer(id).unwrap().labels.default; + assert!(!class.other_positions && class.guide.is_none() && class.placement == rustgis_map::LabelPlacement::Auto, "nothing changes"); + for position in ["curved", "auto"] { + s.run("labels.placement", &json!({"layer": id, "position": position, "otherPositions": false})).unwrap(); + } + s.run("labels.placement", &json!({"layer": id, "otherPositions": true})).unwrap(); + let text = serde_json::to_string(&s.project).unwrap(); + assert!(on(&Session::new(serde_json::from_str(&text).unwrap()))); + s.run("labels.enable", &json!({"layer": id, "on": true})).unwrap(); + let v = View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera: s.map().camera, sky: false }; + // A repeat does nothing on a polygon, so it keeps the lock. + s.run("labels.lock", &json!({"on": true})).unwrap(); + crate::render::render(s.map_mut(), &v).unwrap(); + s.run("labels.placement", &json!({"layer": id, "repeat": 144})).unwrap(); + assert!(s.map().label_lock.is_some(), "a repeat moves no polygon label"); + for turn in [false, true] { + s.run("labels.lock", &json!({"on": true})).unwrap(); + crate::render::render(s.map_mut(), &v).unwrap(); + assert!(s.map().label_lock.is_some()); + s.run("labels.placement", &json!({"layer": id, "otherPositions": turn})).unwrap(); + assert!(s.map().label_lock.is_none(), "turned {turn}: locked again"); + } +} + /// A line label class tries other places along its line when told to (#1187): only placed parallel /// or curved and without a repeat, judged on what the call leaves, in the class it names. A refusal /// changes nothing, a later position or repeat keeps the flag, it undoes, the project keeps it, and @@ -9654,9 +9699,6 @@ fn labels_take_other_positions_along_lines() { for bad in [json!("yes"), json!(1), Value::Null] { assert!(s.run("labels.placement", &json!({"layer": "Rivers", "otherPositions": bad})).is_err(), "{bad}"); } - // Polygons have no such places, even placed parallel. - assert!(s.run("labels.placement", &json!({"layer": "Countries", "position": "parallel", "otherPositions": true})).is_err()); - s.run("labels.placement", &json!({"layer": "Countries", "otherPositions": false})).unwrap(); // Judged in the class named, not in Default; a class that isn't there is refused. s.run("labels.placement", &json!({"layer": "Rivers", "position": "above", "otherPositions": false})).unwrap(); s.run("labels.class.add", &json!({"layer": "Rivers", "name": "Big"})).unwrap(); diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 868991549a..9625b918b8 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -2232,7 +2232,8 @@ pub struct Map { /// drawn while the lock holds, there, wherever the map moves. Filled by the renderer. #[serde(skip)] pub label_lock: Option>, - /// Geographic anchors of locked non-repeated line labels. Render cache only, never saved. + /// Geographic anchors of locked non-repeated line labels, and of polygon labels trying places + /// inside. Render cache only, never saved. #[serde(skip)] pub label_lock_line_anchors: std::collections::HashMap, /// Relationships, snapping, topology rules and edit settings. diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 3c6bfe4e75..a4e859022d 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -2728,7 +2728,8 @@ pub struct LabelClass { #[serde(default)] pub placement: LabelPlacement, /// A label taken by another tries nearby positions before it is left out (#1011): - /// round a point ([`LabelPlacement::alternatives`]), or along a non-repeated line. + /// round a point ([`LabelPlacement::alternatives`]), or along a non-repeated line. A polygon's + /// goes first where its shape fits best inside it (#3268). /// Off by default: placed /// elsewhere, a label may take the place another has today. #[serde(default, deserialize_with = "de_flag", skip_serializing_if = "std::ops::Not::not")] @@ -3572,6 +3573,12 @@ impl LabelPlacement { } impl LabelClass { + /// Whether this class's polygon labels have a place inside to try before their own (#3268): + /// not those curved or along a guide, whose course is their place. + pub fn places_inside_polygons(&self) -> bool { + self.placement != LabelPlacement::Curved && self.guide.is_none() + } + /// The Default class: on the first text field that looks like a name. pub fn default_for(ds: &Dataset) -> LabelClass { let field = ds diff --git a/crates/render/src/area_labels.rs b/crates/render/src/area_labels.rs index 300abd3bf4..5439a6e892 100644 --- a/crates/render/src/area_labels.rs +++ b/crates/render/src/area_labels.rs @@ -337,6 +337,53 @@ pub(super) fn screen_rings(ctx: &super::Ctx<'_>, polys: &[Vec>]) -> O .collect() } +/// Where in `g`'s label part a label `aspect` times as wide as it is tall fits best on the screen +/// (#3268), from its rings thinned as [`screen_rings`] thins them: the pole of inaccessibility with +/// the rings narrowed `aspect` times, so the centre of the largest ellipse of that shape inside +/// them. The largest circle's would put a wide name in a corner of a U or an L, out over its side. +/// Searched in the narrowed rings, to about a point up and down and `aspect` points across (a +/// two-hundredth of a large polygon where that is coarser). It starts with at most 64 cells along +/// a side and takes at most about 1,000 steps: on a shape more than 64 times longer than wide, as +/// narrowed, only its first 64 widths are searched. +/// +/// The text stays upright in the view the frame is `shown` in (a turned or tilted one; none: the +/// frame's own), so the search is made there. The place is given in the frame's points, then in +/// that view's. `None` for no polygon, one with no area near the view or one with a place behind +/// the globe or the camera. +pub(super) fn pole( + ctx: &super::Ctx<'_>, + g: &rustgis_data::Geometry, + aspect: f32, + shown: Option<&super::View>, +) -> Option<((f32, f32), (f32, f32))> { + #[cfg(test)] + SEARCHES.with(|n| n.set(n.get() + 1)); + let mut rings = screen_rings(ctx, std::slice::from_ref(g.label_part()?))?; + let here = ctx.view; + if let Some(to) = shown { + for p in rings.iter_mut().flatten() { + let m = here.camera.to_map(f64::from(p.0), f64::from(p.1), here.width, here.height); + let (x, y) = to.camera.try_to_screen(m, to.width, to.height)?; + *p = (x as f32, y as f32); + } + } + // 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 (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)) }; + let m = to.camera.try_to_map(f64::from(there.0), f64::from(there.1), to.width, to.height)?; + let (x, y) = here.to_screen(m); + Some(((x as f32, y as f32), there)) +} + +#[cfg(test)] +thread_local! { + /// The [`pole`] searches made on this thread. + pub(super) static SEARCHES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// [`glyphs`]' characters `advances` wide and `height` tall, as [`Line::curved`] takes them. fn curved( ctx: &super::Ctx<'_>, diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index d882334ae9..8283f08553 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6173,15 +6173,17 @@ fn render_frame( let (bw, bh) = (text::spaced_block_width(&text, csize, face, class.spacing), text::block_height(&text, csize)); // Where a placement puts it, moved as its class says (points, as the // text's size), unless along a line. - let place = |p: LabelPlacement| { + let place_at = |(x, y): (f32, f32), p: LabelPlacement| { let (dx, dy) = p.offset(bw, bh, marker, is_point); let (dx, dy) = ((dx + class.offset[0] * 1.33) * label_factor, (dy + class.offset[1] * 1.33) * label_factor); - (x as f32 + dx, y as f32 + dy) + (x + dx, y + dy) }; + let place = |p: LabelPlacement| place_at((x as f32, y as f32), p); // Where it goes, each with its repeat's index: by its feature (0), or along // a line at its middle and, repeated, every so far either side. let mut places: Vec<(usize, f32, f32, Option, Vec)> = Vec::new(); let mut curves = None; + // (A polygon's too: its label point, after its pole.) let mut line_alternatives = Vec::new(); let mut line_places = None; // Turned square to a line: no other places round its point. @@ -6521,7 +6523,60 @@ fn render_frame( .filter(|a| *a != 0.0) .map(|a| rustgis_tiles::symbols::upright(a.to_radians())) .filter(|a| *a != 0.0); - places.push((0, lx, ly, turned, Vec::new())); + // A polygon's label trying other places (#3268) goes first where its + // shape fits best inside (a pole of inaccessibility), then here. A curved + // or guided one has its own course, which this is only what's left of. + let tries = class.other_positions + && moved.is_none() + && class.places_inside_polygons() + && matches!(g, Geometry::Polygon(_)); + // The view the frame is shown in, where that isn't its own. + let shown = match &labels_to { + Labels::Turned(to) | Labels::Tilted(to, _) => Some(*to), + Labels::Own | Labels::Shared => None, + }; + let key = (lid, label_id(row), ci, 0); + let locked_at = lock.as_ref().and_then(|k| k.get(&key)).map(|won| won.place); + // 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 + // search finds one in view. Locked at the place after, neither. + let first = match locked_at { + _ if !tries => None, + Some(0) => { + let target = map.label_lock_line_anchors.get(&key).copied().and_then(|anchor| match &globe { + Some(globe) => globe.forward(anchor), + None => flat.forward(anchor).map(|p| view.to_screen(p)), + }); + let Some((x, y)) = target else { continue }; + Some((x as f32, y as f32)) + } + Some(_) => None, + None => area_labels::pole(ctx, g, bw / bh, shown) + .filter(|&(_, (px, py))| { + let (w, h) = shown.map_or((vw, vh), |to| (to.width, to.height)); + (0.0..=w).contains(&f64::from(px)) && (0.0..=h).contains(&f64::from(py)) + }) + .map(|(here, _)| here), + }; + // The first place and the label point on the map, while the lock is + // taken (never from a tilted view), for it to keep. + if tries && display.locked && lock.is_none() && !matches!(labels_to, Labels::Tilted(..)) { + let on_map = |(x, y): (f32, f32)| match &globe { + 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)), + }; + let own = (x as f32, y as f32); + let anchors = vec![on_map(first.unwrap_or(own)), on_map(own)]; + 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. + if tries { + line_alternatives.push(LabelPlace { x: lx, y: ly, angle: turned, glyphs: Vec::new() }); + } + let (px, py) = first.map_or((lx, ly), |first| place_at(first, class.placement)); + places.push((0, px, py, turned, Vec::new())); } // Heavier classes first (#2803; labels moved by hand before all of them, // so the others keep off them), then, among equals, layers above, the @@ -16756,3 +16811,6 @@ mod lod_tests; #[cfg(test)] mod line_positions_tests; + +#[cfg(test)] +mod polygon_labels_tests; diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs new file mode 100644 index 0000000000..150a77fb2d --- /dev/null +++ b/crates/render/src/polygon_labels_tests.rs @@ -0,0 +1,380 @@ +//! A polygon's label trying other places (#3268): its pole of inaccessibility first, then where +//! it goes without the setting. + +use super::*; +use rustgis_data::{Dataset, Field, FieldType, Value}; +use rustgis_map::{Camera, LabelPlacement}; + +fn c(x: f64, y: f64) -> Coord { + Coord::new(x, y) +} + +fn ring(points: &[(f64, f64)]) -> Vec { + points.iter().chain(points.first()).map(|&(x, y)| c(x, y)).collect() +} + +/// A U open to the north, in degrees: arms and base 0.1 wide. Its label point is in the widest +/// span, the base's, against its south edge; a name fits best half way up the base. +fn u() -> Vec> { + vec![ring(&[(-0.25, -0.2), (0.25, -0.2), (0.25, 0.2), (0.15, 0.2), (0.15, -0.1), (-0.15, -0.1), (-0.15, 0.2), (-0.25, 0.2)])] +} + +fn square(x: f64, y: f64, half: f64) -> Vec { + ring(&[(x - half, y - half), (x + half, y - half), (x + half, y + half), (x - half, y + half)]) +} + +/// A map with one polygon layer labelled "Lake", trying other places when `on`. +fn map(geometry: Geometry, on: bool) -> (Map, u32) { + named(geometry, on, "Lake") +} + +fn named(geometry: Geometry, on: bool, name: &str) -> (Map, u32) { + let mut m = Map::new("Map"); + let mut d = Dataset::new("areas", GeometryType::Polygon, vec![Field::new("name", FieldType::Text)]); + d.push(Some(geometry), vec![Value::Text(name.into())]); + let id = m.add_dataset(d); + if let Some(l) = m.layer_mut(id) { + l.labels.enabled = true; + l.labels.default.other_positions = on; + } + (m, id) +} + +fn view_at(lon: f64, lat: f64) -> View { + let camera = Camera { center: lonlat_to_merc(c(lon, lat)), res: 100.0, bearing: 0.0, pitch: 0.0 }; + View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera, sky: false } +} + +fn view() -> View { + view_at(0.0, 0.0) +} + +fn places(m: &mut Map, v: &View) -> Vec<(f32, f32)> { + render(m, v).unwrap().labels.into_iter().filter(|l| l.text == "Lake").map(|l| (l.x, l.y)).collect() +} + +fn one(m: &mut Map, v: &View) -> (f32, f32) { + let p = places(m, v); + assert_eq!(p.len(), 1, "{p:?}"); + p[0] +} + +/// The longitude and latitude under a place on the screen. +fn at(v: &View, (x, y): (f32, f32)) -> Coord { + rustgis_geom::merc_to_lonlat(v.camera.to_map(f64::from(x), f64::from(y), v.width, v.height)) +} + +/// How far, in degrees, the place is from the nearest edge, negative outside the polygon. +fn depth(rings: &[Vec], p: Coord) -> f64 { + let mut inside = false; + let mut best = f64::INFINITY; + for r in rings { + for w in r.windows(2) { + let (a, b) = (w[0], w[1]); + if (a.y > p.y) != (b.y > p.y) && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x { + inside = !inside; + } + let (dx, dy) = (b.x - a.x, b.y - a.y); + let t = (((p.x - a.x) * dx + (p.y - a.y) * dy) / (dx * dx + dy * dy)).clamp(0.0, 1.0); + best = best.min((p.x - a.x - t * dx).hypot(p.y - a.y - t * dy)); + } + } + if inside { best } else { -best } +} + +/// A point layer above the polygon with a heavier label centred at `places`, which take them. +fn block(m: &mut Map, v: &View, places: &[(f32, f32)]) { + let mut d = Dataset::new("blockers", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + for &p in places { + d.push(Some(Geometry::Point(at(v, p))), vec![Value::Text("XX".into())]); + } + let id = m.add_dataset(d); + if let Some(l) = m.layer_mut(id) { + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { size: 1.0, ..l.symbol(0) }); + l.labels.enabled = true; + l.labels.default.placement = LabelPlacement::Center; + l.labels.default.weight = 10; + } +} + +/// The polygon's label point on the screen. +fn today(v: &View, g: &Geometry) -> (f32, f32) { + let (x, y) = v.to_screen(lonlat_to_merc(g.label_point().unwrap())); + (x as f32, y as f32) +} + +fn near(a: (f32, f32), b: (f32, f32)) -> bool { + (a.0 - b.0).hypot(a.1 - b.1) < 1.0 +} + +#[test] +fn off_a_polygons_label_stays_at_its_label_point() { + let g = Geometry::Polygon(vec![u()]); + let (mut m, _) = map(g.clone(), false); + let v = view(); + assert!(near(one(&mut m, &v), today(&v, &g))); +} + +#[test] +fn on_it_goes_to_the_point_farthest_from_the_edges() { + let g = Geometry::Polygon(vec![u()]); + let (mut m, _) = map(g.clone(), true); + let v = view(); + let placed = one(&mut m, &v); + assert!(!near(placed, today(&v, &g)), "{placed:?}"); + // Half way across the base, which is 0.1 tall. + let d = depth(&u(), at(&v, placed)); + assert!(d > 0.045, "{d}"); +} + +/// The place is the one the label's shape fits best, not the largest circle's: a wide name stays +/// whole inside a U or an L, whose largest circles sit in a corner. +#[test] +fn a_wide_name_stays_inside_its_polygon() { + let l = vec![ring(&[(-0.25, -0.2), (0.25, -0.2), (0.25, -0.1), (-0.1, -0.1), (-0.1, 0.2), (-0.25, 0.2)])]; + let name = "Horseshoe Lake"; + // Zoomed out: the arms and base are about as wide as half the name. Turned and tilted too: + // the shape is fitted where the text is read, upright on the screen. + for (rings, bearing, pitch) in [u(), l].into_iter().flat_map(|r| [(0.0, 0.0), (90.0, 0.0), (0.0, 30.0)].map(|(b, p)| (r.clone(), b, p))) + { + let mut v = view(); + (v.camera.res, v.camera.bearing, v.camera.pitch) = (200.0, bearing, pitch); + let (mut m, _) = named(Geometry::Polygon(vec![rings.clone()]), true, name); + let placed = render(&mut m, &v).unwrap().labels; + let p = placed.iter().find(|l| l.text == name).unwrap(); + let face = text::Face { bold: false, italic: false, serif: false, family: None }; + let (hw, hh) = (text::spaced_block_width(name, p.size, face, 0.0) / 2.0, text::block_height(name, p.size) / 2.0); + for (dx, dy) in [(-hw, -hh), (hw, -hh), (-hw, hh), (hw, hh)] { + let corner = at(&v, (p.x + dx, p.y + dy)); + assert!(depth(&rings, corner) > 0.0, "turned {bearing}, tilted {pitch}: {corner:?} of the box at {:?}", (p.x, p.y)); + } + } +} + +#[test] +fn with_its_pole_taken_it_goes_to_its_label_point() { + let g = Geometry::Polygon(vec![u()]); + let (mut m, _) = map(g.clone(), true); + let v = view(); + let pole = one(&mut m, &v); + block(&mut m, &v, &[pole]); + assert!(near(one(&mut m, &v), today(&v, &g))); +} + +#[test] +fn with_both_taken_it_is_unplaced_once_at_its_pole() { + let g = Geometry::Polygon(vec![u()]); + let (mut m, _) = map(g.clone(), true); + let v = view(); + let pole = one(&mut m, &v); + block(&mut m, &v, &[pole, today(&v, &g)]); + m.label_display.show_unplaced = true; + let r = render(&mut m, &v).unwrap(); + assert!(r.labels.iter().all(|l| l.text != "Lake")); + let unplaced: Vec<_> = r.unplaced.iter().filter(|l| l.text == "Lake").map(|l| (l.x, l.y)).collect(); + assert_eq!(unplaced.len(), 1); + assert!(near(unplaced[0], pole), "{unplaced:?} {pole:?}"); +} + +#[test] +fn a_polygons_pole_keeps_out_of_its_hole() { + // A ring with its hole off centre. + let rings = vec![square(0.0, 0.0, 0.2), square(0.05, 0.0, 0.1)]; + let (mut m, _) = map(Geometry::Polygon(vec![rings.clone()]), true); + let v = view(); + let d = depth(&rings, at(&v, one(&mut m, &v))); + // The widest bands round the hole are those north and south of it, 0.1 tall. + assert!(d > 0.045, "in a band, away from the hole: {d}"); +} + +#[test] +fn a_multipolygons_pole_is_in_the_part_its_label_point_picks() { + let g = Geometry::Polygon(vec![vec![square(0.33, 0.2, 0.03)], u()]); + let (mut m, _) = map(g, true); + let v = view(); + let d = depth(&u(), at(&v, one(&mut m, &v))); + assert!(d > 0.045, "{d}"); +} + +#[test] +fn a_polygon_without_area_keeps_its_label_point() { + let g = Geometry::Polygon(vec![vec![ring(&[(-0.2, 0.0), (0.0, 0.0), (0.2, 0.0)])]]); + let v = view(); + let off = places(&mut map(g.clone(), false).0, &v); + assert_eq!(places(&mut map(g, true).0, &v), off); +} + +#[test] +fn a_label_moved_by_hand_stays_where_it_was_put() { + let (mut m, id) = map(Geometry::Polygon(vec![u()]), true); + let fid = m.layer(id).unwrap().dataset.features.first().unwrap().id; + m.layer_mut(id).unwrap().labels.default.moved = vec![rustgis_map::symbology::MovedLabel { id: fid, at: [0.0, 0.1] }]; + let v = view(); + let placed = at(&v, one(&mut m, &v)); + assert!((placed.x - 0.0).abs() < 2e-3 && (placed.y - 0.1).abs() < 2e-3, "{placed:?}"); +} + +#[test] +fn a_curved_label_has_no_pole() { + let g = Geometry::Polygon(vec![u()]); + let v = view(); + let render_curved = |on: bool| { + let (mut m, id) = map(g.clone(), on); + // Along the centre line, or straight where it does not fit: the same either way. + let l = m.layer_mut(id).unwrap(); + l.labels.default.placement = LabelPlacement::Curved; + render(&mut m, &v).unwrap().labels.into_iter().map(|l| (l.x, l.y)).collect::>() + }; + assert_eq!(render_curved(true), render_curved(false)); +} + +#[test] +fn a_lock_keeps_the_place_each_polygon_label_took() { + let g = Geometry::Polygon(vec![u()]); + for taken in [false, true] { + let (mut m, _) = map(g.clone(), true); + let v = view(); + let pole = one(&mut m, &v); + if taken { + block(&mut m, &v, &[pole]); + } + m.label_display.locked = true; + let before = at(&v, one(&mut m, &v)); + let kept = m.label_lock.as_ref().unwrap().iter().find(|(_, place)| place.place == u8::from(taken)); + assert!(kept.is_some(), "{:?}", 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:?}"); + } +} + +/// With its pole out of view a label is at its label point, as without the setting, and a lock +/// taken then keeps it there when the pole comes into view. +#[test] +fn a_pole_out_of_view_leaves_the_label_at_its_label_point() { + let g = Geometry::Polygon(vec![u()]); + // The pole is above this view; the label point is inside it. + let low = view_at(0.0, -0.435); + let (mut m, _) = map(g.clone(), true); + assert!(near(one(&mut m, &low), today(&low, &g))); + m.label_display.locked = true; + assert!(near(one(&mut m, &low), today(&low, &g))); + let v = view(); + assert!(near(one(&mut m, &v), today(&v, &g)), "locked, it stays"); +} + +#[test] +fn turned_and_tilted_views_place_the_pole() { + let g = Geometry::Polygon(vec![u()]); + for (bearing, pitch) in [(30.0, 0.0), (0.0, 30.0)] { + let mut v = view(); + (v.camera.bearing, v.camera.pitch) = (bearing, pitch); + let off = one(&mut map(g.clone(), false).0, &v); + let on = one(&mut map(g.clone(), true).0, &v); + assert!(!near(on, off), "turned {bearing}, tilted {pitch}: {on:?}"); + } +} + +/// A lock that took the label point (place 1) still finds it in a frame with no pole, as with a +/// vertex behind the globe. +#[test] +fn a_lock_on_the_label_point_holds_without_a_pole() { + let g = Geometry::Polygon(vec![vec![ring(&[(-0.2, 0.0), (0.0, 0.0), (0.2, 0.0)])]]); + let (mut m, _) = map(g, true); + let v = view(); + m.label_display.locked = true; + let at_lock = one(&mut m, &v); + for (_, place) in m.label_lock.as_mut().unwrap() { + place.place = 1; + } + assert!(near(one(&mut m, &v), at_lock)); +} + +/// A lock taken where no place inside can be found (here a polygon with no area; on the globe, +/// one reaching behind it) keeps the label point's map place as the first, so the label doesn't +/// move when a place inside appears. +#[test] +fn a_lock_taken_without_a_pole_keeps_the_label_point() { + let g = Geometry::Polygon(vec![vec![ring(&[(-0.2, 0.0), (0.0, 0.0), (0.2, 0.0)])]]); + let (mut m, _) = map(g.clone(), true); + let v = view(); + m.label_display.locked = true; + assert!(near(one(&mut m, &v), today(&v, &g))); + assert!(m.label_lock.as_ref().unwrap().iter().all(|(_, p)| p.place == 0), "{:?}", m.label_lock); + assert_eq!(m.label_lock_line_anchors.len(), 1); + assert!(near(one(&mut m, &v), today(&v, &g))); +} + +/// Locked with no place inside, a crowded label still shows as unplaced. +#[test] +fn a_crowded_label_locked_without_a_pole_is_unplaced() { + let g = Geometry::Polygon(vec![vec![ring(&[(-0.2, 0.0), (0.0, 0.0), (0.2, 0.0)])]]); + let v = view(); + for bearing in [0.0, 90.0] { + let mut v = v; + v.camera.bearing = bearing; + let (mut m, _) = map(g.clone(), true); + let at_label = one(&mut m, &v); + block(&mut m, &v, &[at_label]); + m.label_display.show_unplaced = true; + m.label_display.locked = true; + let r = render(&mut m, &v).unwrap(); + assert!(r.labels.iter().all(|l| l.text != "Lake"), "turned {bearing}"); + assert_eq!(r.unplaced.iter().filter(|l| l.text == "Lake").count(), 1, "turned {bearing}"); + } +} + +/// A lock keeps the map place a polygon label's pole was at, not the search: along a flat stretch +/// many places are as good, and which one a search finds changes with the view. +#[test] +fn a_locked_polygon_label_stays_at_the_place_it_was_locked() { + for bearing in [0.0, 90.0] { + let (mut m, _) = map(Geometry::Polygon(vec![u()]), true); + let mut v = view(); + v.camera.bearing = bearing; + m.label_display.locked = true; + let placed = at(&v, one(&mut m, &v)); + let kept: Vec = m.label_lock_line_anchors.values().copied().collect(); + assert_eq!(kept.len(), 1, "turned {bearing}"); + assert!((kept[0].x - placed.x).abs() < 2e-3 && (kept[0].y - placed.y).abs() < 2e-3, "{kept:?} {placed:?}"); + // Another place along the base, as another search might find. + let other = c(placed.x + 0.05, placed.y); + m.label_lock_line_anchors.values_mut().for_each(|a| *a = other); + let mut moved = view_at(0.03, 0.02); + moved.camera.bearing = bearing; + let after = at(&moved, one(&mut m, &moved)); + assert!((after.x - other.x).abs() < 2e-3 && (after.y - other.y).abs() < 2e-3, "turned {bearing}: {after:?} {other:?}"); + } +} + +/// Locked at its label point, a label's pole isn't searched for again. +#[test] +fn a_lock_at_the_label_point_searches_for_no_pole() { + let g = Geometry::Polygon(vec![u()]); + let (mut m, _) = map(g.clone(), true); + let v = view(); + let pole = one(&mut m, &v); + block(&mut m, &v, &[pole]); + m.label_display.locked = true; + assert!(near(one(&mut m, &v), today(&v, &g))); + area_labels::SEARCHES.with(|n| n.set(0)); + let moved = view_at(0.03, 0.02); + assert!(near(one(&mut m, &moved), today(&moved, &g))); + area_labels::SEARCHES.with(|n| assert_eq!(n.get(), 0)); +} + +/// Lock doesn't bring in a pole just out of view, whose name would show in part: the label stays +/// where it was. +#[test] +fn locking_leaves_a_label_whose_pole_is_just_out_of_view() { + let g = Geometry::Polygon(vec![u()]); + let pole = at(&view(), one(&mut map(g.clone(), true).0, &view())); + // The pole 3 points above the top of the view. + let mut v = view(); + v.camera.center.y = lonlat_to_merc(pole).y - 303.0 * v.camera.res; + let (mut m, _) = map(g.clone(), true); + assert!(near(one(&mut m, &v), today(&v, &g))); + m.label_display.locked = true; + assert!(near(one(&mut m, &v), today(&v, &g)), "as before the lock"); + assert!(near(one(&mut m, &v), today(&v, &g)), "and locked"); +} diff --git a/crates/tiles/src/symbols.rs b/crates/tiles/src/symbols.rs index 84c244d322..aa530f0a63 100644 --- a/crates/tiles/src/symbols.rs +++ b/crates/tiles/src/symbols.rs @@ -554,7 +554,7 @@ fn signed_area(r: &[(f32, f32)]) -> f32 { /// The point inside a polygon (outer ring, then holes) farthest from its edges, to within /// `precision` (after Mapbox's polylabel, ISC; see `INCLUDED` in `xtask/src/notices.rs`): where a /// label sits best in an area. `None` for a polygon with no area. -pub(crate) fn pole_of_inaccessibility(poly: &[Vec<(f32, f32)>], precision: f32) -> Option<(f32, f32)> { +pub fn pole_of_inaccessibility(poly: &[Vec<(f32, f32)>], precision: f32) -> Option<(f32, f32)> { let outer = poly.first()?; let (mut x0, mut y0, mut x1, mut y1) = (f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY); for p in outer.iter().filter(|p| p.0.is_finite() && p.1.is_finite()) { diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index 00f999eebc..28b1b87356 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -881,6 +881,16 @@ 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). 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."); + if ui.checkbox(&mut on, tl!("Try other places inside the polygon")).on_hover_text(help).changed() { + run(app, "labels.placement", c.params(json!({"otherPositions": on}))); + } + } // Lines: the text along them, straight or bending with them. if l.geometry_type() == rustgis_engine::data::GeometryType::Polyline { ui.add_space(4.0); @@ -1620,6 +1630,50 @@ mod tests { assert!(h.query_by_role_and_label(Role::CheckBox, BOX).is_none(), "not for polygons"); } + /// A polygon layer's labels can try other places inside their polygons (#3268): the box is + /// there but for a curved label or one along a guide, it undoes, and hiding it keeps what it was + /// set to. + #[test] + fn other_positions_are_set_in_the_pane_for_polygons() { + use egui::accesskit::Role; + const BOX: &str = "Try other places inside the polygon"; + let mut h = harness(with_cities()); + h.run(); + let countries = layer_id(h.state(), "Countries"); + h.state_mut().session.run("layer.select", &json!({"layer": countries})).unwrap(); + h.run(); + open_tab(&mut h, "Position"); + let on = |h: &egui_kittest::Harness<'_, RustGisApp>| { + h.state().session.map().layer_by_name("Countries").unwrap().labels.default.other_positions + }; + assert!(!on(&h)); + h.get_by_role_and_label(Role::CheckBox, BOX).click(); + h.run(); + assert!(on(&h)); + h.state_mut().session.run("edit.undo", &json!({})).unwrap(); + h.run(); + assert!(!on(&h)); + h.get_by_role_and_label(Role::CheckBox, BOX).click(); + h.run(); + for change in [json!({"position": "curved"}), json!({"position": "auto", "guide": {"layer": "Rivers"}})] { + let mut p = change.clone(); + p["layer"] = json!(countries); + h.state_mut().session.run("labels.placement", &p).unwrap(); + h.run(); + assert!(h.query_by_role_and_label(Role::CheckBox, BOX).is_none(), "{change}"); + assert!(on(&h), "hidden, it's kept"); + } + h.state_mut().session.run("labels.placement", &json!({"layer": countries, "guide": null})).unwrap(); + h.run(); + h.get_by_role_and_label(Role::CheckBox, BOX).click(); + h.run(); + assert!(!on(&h)); + let cities = layer_id(h.state(), "Cities"); + h.state_mut().session.run("layer.select", &json!({"layer": cities})).unwrap(); + h.run(); + assert!(h.query_by_role_and_label(Role::CheckBox, BOX).is_none(), "not for points"); + } + /// A point's label placed square to a line (#2263) is chosen in the pane, starting on a line /// layer of the map, and shows as chosen however it was set. #[test] diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 1478f3f7bc..da9f0cc5cf 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -764,6 +764,18 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: take the place a less important one had. The class's offset applies to every place, and Lock keeps the place each label took (`labels.placement={"layer": "Cities", "otherPositions": true}`). +- **Other places inside polygons**: a polygon's label goes where its shape fits best inside the + polygon, as seen on the screen (the point with the most room round it for something as wide and + tall as the text), so a name sits in the body of a lake or bay rather than against a shore. Where + another label takes that place, it goes where it goes without this setting, and is left out if + that is taken too (Labeling pane › Position › **Try other places inside the polygon**, for polygon + layers). With that point out of view, the label stays where it goes without this. 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 (Above sets the + name above that point), 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, nearest the middle first, and goes to the first that will do (Labeling pane › Position › Along