diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 139954cb86..32ccfe8ee9 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -208,7 +208,7 @@ labels.fonts search? labels.lock on? labels.move layer? class? feature? row? to labels.pause on? -labels.placement layer? class? position? to? side? offset? repeat? lineOffset? otherPositions? fit? abbreviations? showAll? weight? clearance? removeDuplicates? callout? guide? +labels.placement layer? class? position? to? side? offset? repeat? lineOffset? otherPositions? fit? abbreviations? showAll? weight? obstacleWeight? clearance? removeDuplicates? callout? guide? labels.resetMoved layer? class? all? labels.scaleRange layer? class? min? max? clear? labels.style layer? class? size? color? halo? haloColor? haloWidth? spacing? stretch? bold? italic? font? background? wrapChar? wrapLength? lineAlign? diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index ddededfbd1..c720444719 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -143,14 +143,14 @@ pub fn commands() -> Vec { // A position that isn't a placement name is refused, not dropped for the others (null: // none, as for the other keys). None if p.get("position").is_some_and(|v| !v.is_null()) => return Err("position must be a placement name".into()), - None if ["offset", "repeat", "lineOffset", "otherPositions", "showAll", "weight", "clearance", "removeDuplicates", "callout", "to", "side", "fit", "abbreviations", "guide"] + None if ["offset", "repeat", "lineOffset", "otherPositions", "showAll", "weight", "obstacleWeight", "clearance", "removeDuplicates", "callout", "to", "side", "fit", "abbreviations", "guide"] .iter() .any(|k| p.get(k).is_some()) => { None } None => { - return Err("position is required (or an offset, a repeat, a lineOffset, otherPositions, showAll, a weight, a clearance, removeDuplicates, a callout, to, side, fit, abbreviations or a guide)".into()); + return Err("position is required (or an offset, a repeat, a lineOffset, otherPositions, showAll, a weight, an obstacleWeight, a clearance, removeDuplicates, a callout, to, side, fit, abbreviations or a guide)".into()); } }; // Along a line placed curved, the label fitted to the room the line gives (#2265). @@ -213,6 +213,15 @@ 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 + // number out of range or a fraction is held to a whole one, and says so. + let obstacle = match p.get("obstacleWeight") { + None => None, + Some(Value::Null) => Some(0.0), + Some(v) => Some(number(v).ok_or("obstacleWeight must be a number from 0 to 10 (0 or null: none)")?), + }; + let obstacle_asked = obstacle.filter(|w| w.fract() != 0.0 || !rustgis_map::symbology::LABEL_WEIGHT.contains(w)); + let obstacle = obstacle.map(rustgis_map::symbology::label_weight); // The room its labels keep free of other labels (#2828): 0 to 100 points, null back to // 2. A number out of range is held to it, and says so. let clearance = match p.get("clearance") { @@ -276,12 +285,20 @@ pub fn commands() -> Vec { let clears = matches!(to, Some(None)); let id = s.layer_id(p)?; let held = held_geometries(s.map().layer(id).ok_or("no such layer")?); - let (_, lines, _) = held; + let (points, lines, _) = held; + // On a layer with no points it would do nothing; off is taken anywhere. + if obstacle.is_some_and(|w| w > 0) && !points { + return Err("obstacleWeight is for layers with points: lines and polygons aren't obstacles yet".into()); + } 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). let mut unused: Vec<&str> = Vec::new(); let done = with_labels(s, p, |labels| { + // The layer's, whatever class is named. + if let Some(w) = obstacle { + labels.obstacle_weight = w; + } let c = class_in(labels, p)?; if let Some(pos) = pos { c.placement = pos; @@ -401,6 +418,18 @@ pub fn commands() -> Vec { false, ); } + if let Some(asked) = obstacle_asked { + let name = s.map().layer(id).map(|l| l.name.clone()).unwrap_or_default(); + let kept = rustgis_map::symbology::label_weight(asked); + let asked = if asked.abs() < 1e6 { asked.to_string() } else { format!("{asked:e}") }; + s.notify_text( + NoticeText::format( + "{name}: obstacleWeight {asked} adjusted to {kept} (an obstacle weight is a whole number from 0 to 10)", + [("name", name.into()), ("asked", asked.into()), ("kept", kept.to_string().into())], + ), + false, + ); + } if let Some(asked) = clearance_asked { let name = s.map().layer(id).map(|l| l.name.clone()).unwrap_or_default(); let kept = rustgis_map::symbology::label_clearance(asked); @@ -430,7 +459,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 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)}"#, + 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)}"#, ), // 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/engine/src/project.rs b/crates/engine/src/project.rs index e479348a81..671d422801 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -160,6 +160,7 @@ pub const CAPABILITIES: &[&str] = &[ "layout-publication-crs", "shaded-relief-generalize", PROJECT_OPEN_LAYOUT, + "label-obstacles", ]; /// An offline area keeping the versions that lost a sync or a Bring Back /// (`OfflineArea::conflicts`, #2468): an older reader would save it again without them. diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 73bc820c98..97b0758220 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -72,6 +72,10 @@ impl Project { if !required.contains(&UNIQUE_KEEP_ORDER) && self.styles.iter().any(|s| keeps_class_order(&s.renderer)) { required.push(UNIQUE_KEEP_ORDER); } + // And its obstacle weight (#3526): an older reader would apply the style without it. + if !required.contains(&"label-obstacles") && self.styles.iter().any(|s| s.labels.obstacle_weight > 0) { + required.push("label-obstacles"); + } // And its labels' weights (#2803): an older reader would apply the style without them. if !required.contains(&"label-weight") && self.styles.iter().any(|s| s.labels.in_order().any(|c| c.weight != rustgis_map::symbology::DEFAULT_LABEL_WEIGHT)) @@ -199,6 +203,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("layout-scale-bar-details", command_uses_scale_bar_details), ("dggs-system", command_uses_dggs_system), ("label-weight", command_weighs_labels), + ("label-obstacles", command_sets_obstacles), ("label-clearance", command_clears_labels), ("label-duplicates", command_removes_duplicate_labels), ("layer-raster-mask", command_masks_by_raster), @@ -411,6 +416,37 @@ fn text_keeps_class_order(text: &str) -> bool { && serde_json::from_str::(text).is_ok_and(|v| holds_kept_class_order(&v)) } +/// Whether saved JSON text holds a layer that is an obstacle for labels (#3526). Read only when +/// the text names `obstacle`, or could hide it ([`may_hide_a_key`], a step's base64 `data` or a +/// notebook). A project is read as one ([`inline_project_requires`]), its steps' and notebooks' +/// included. +fn text_sets_obstacles(text: &str) -> bool { + let hidden = text.contains("obstacle") || may_hide_a_key(text) || names_data(text) || text.contains("\"notebooks\""); + let Some(v) = hidden.then(|| serde_json::from_str::(text).ok()).flatten() else { return false }; + if v.get("maps").is_some() + && let Some(requires) = inline_project_requires(text, "label-obstacles") + { + return requires; + } + holds_obstacles(&v) +} + +/// Whether saved JSON holds an obstacle weight other than none, wherever it is, in JSON text a +/// string carries too; a saved step in it is read as the command reads it. +fn holds_obstacles(v: &Value) -> bool { + match v { + Value::Object(o) => { + let step = ["command", "tool", "id"].iter().find_map(|k| o.get(*k).and_then(Value::as_str)).zip(o.get("params")); + o.get("obstacle_weight").and_then(Value::as_f64).is_some_and(|w| rustgis_map::symbology::label_weight(w) > 0) + || step.is_some_and(|(id, params)| command_sets_obstacles(id, params)) + || o.values().any(holds_obstacles) + } + Value::Array(a) => a.iter().any(holds_obstacles), + Value::String(s) => text_sets_obstacles(s), + _ => false, + } +} + /// Whether JSON text holds a `data` key, written plain (`"data"`) or inside a string's JSON at any /// depth (`\"data\"`, `\\\"data\\\"`, …): `data` and then a quote after any run of backslashes. fn names_data(text: &str) -> bool { @@ -525,6 +561,25 @@ fn command_clears_labels(id: &str, params: &Value) -> bool { } } +/// A saved `labels.placement` that makes a layer an obstacle (#3526), read as the command reads +/// it: an older reader runs it without the key, saying nothing. 0 or null is what it keeps. +fn command_sets_obstacles(id: &str, params: &Value) -> bool { + match id { + "labels.placement" => { + params.get("obstacleWeight").and_then(crate::cmd::labels::number).is_some_and(|w| rustgis_map::symbology::label_weight(w) > 0) + } + // A style, layer, map or project given inline (`text` or `data`) that holds one; one read + // from a `"path"` is a file, whose header requires what it uses. + "style.add" | "style.import" | "layer.addLayerFile" | "map.import" => { + crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_sets_obstacles(&t)) + } + // It opens its `text` only, whatever else the step holds. + "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_sets_obstacles), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_sets_obstacles)), + _ => false, + } +} + /// A saved `labels.placement` that gives a class a weight other than 5, read as the command reads /// it (#2803): an older reader runs it without the key, saying nothing, so the labels would compete /// as before. 5 or null is what an older reader keeps. @@ -1623,6 +1678,12 @@ 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 +/// weight, and place and save the labels as without it. +fn label_obstacle(layer: &Layer) -> bool { + layer.labels.obstacle_weight > 0 +} + /// Whether a layer's label classes weigh other than the default (#2803): an older reader would /// drop the weights, and place and save the labels as without them. fn label_weight(layer: &Layer) -> bool { @@ -1687,6 +1748,7 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { (keeps_class_order(&layer.renderer), UNIQUE_KEEP_ORDER), (label_guide(layer), "label-guide"), (label_weight(layer), "label-weight"), + (label_obstacle(layer), "label-obstacles"), (label_clearance(layer), "label-clearance"), (removes_duplicate_labels(layer), "label-duplicates"), (held_natively(&layer.dataset), super::NATIVE_COORDINATES), @@ -1717,6 +1779,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static let (mut polygon, mut svg, mut raster_mask, mut class_order) = (false, false, false, false); let (mut offline_area_id, mut paper, mut native, mut guided, mut weighed, mut cleared, mut deduped) = (false, false, false, false, false, false, false); + let mut obstructing = false; let (mut crisp, mut bed, mut walls_top, mut soft, mut aerial, mut terrain_type, mut flats, mut generalize) = (false, false, false, false, false, false, false, false); for map in maps { @@ -1725,6 +1788,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static paper |= map.paper.is_some(); guided |= map.layers.iter().any(label_guide); weighed |= map.layers.iter().any(label_weight); + obstructing |= map.layers.iter().any(label_obstacle); cleared |= map.layers.iter().any(label_clearance); deduped |= map.layers.iter().any(removes_duplicate_labels); // A tile layer drawn nearest (#2804), which an older reader would draw and save blended. @@ -1797,6 +1861,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (class_order, UNIQUE_KEEP_ORDER), (guided, "label-guide"), (weighed, "label-weight"), + (obstructing, "label-obstacles"), (cleared, "label-clearance"), (deduped, "label-duplicates"), (crisp, "tile-resampling"), @@ -2059,7 +2124,7 @@ mod tests { Project::default() }; let mut s = crate::Session::new(base); - s.project.name = r"font generalize extent_numbers one_row \u0041".to_string(); + s.project.name = r"font generalize extent_numbers one_row obstacle_weight \u0041".to_string(); s.map_mut().add_raster("Scene".to_string(), rustgis_map::raster::RasterLayer::unread_in_place(scene.to_string())); s.run("layout.new", &json!({"template": "map"})).unwrap(); let element = |s: &crate::Session, code: &str| s.project.layouts[0].elements.iter().find(|e| e.kind.code() == code).unwrap().id; @@ -2074,6 +2139,11 @@ mod tests { "layout-scale-bar-font" if wanted => { s.run("layout.addElement", &json!({"kind": "scaleBar", "font": "serif"})).unwrap(); } + "label-obstacles" if wanted => { + let points = rustgis_data::Dataset::new("pts", rustgis_data::GeometryType::Point, Vec::new()); + let id = s.map_mut().add_dataset(points); + s.run("labels.placement", &json!({"layer": id, "obstacleWeight": 6})).unwrap(); + } _ => {} } s.project @@ -2083,7 +2153,8 @@ mod tests { /// as saved, without its header, from a script and from a step of a step (#3530). #[test] fn the_checks_of_an_inline_project_read_nothing_it_names() { - let checks: [(&str, CommandCheck); 4] = [ + let checks: [(&str, CommandCheck); 5] = [ + ("label-obstacles", command_sets_obstacles), ("shaded-relief-generalize", command_sets_generalize), ("layout-extent-numbers", command_numbers_extents), ("layout-north-arrow-font", command_uses_north_arrow_font), @@ -2477,6 +2548,7 @@ mod tests { (&["dggs-system"], "a5Grid", json!({"system": "H3"})), (&["dggs-system"], "a5Aggregate", json!({"system": "S2"})), (&["label-weight"], "labels.placement", json!({"weight": 9})), + (&["label-obstacles"], "labels.placement", json!({"obstacleWeight": 9})), (&["unique-keep-order"], "style.add", json!({"text": kept_order_style()})), (&["label-clearance"], "labels.placement", json!({"clearance": 9})), (&["label-duplicates"], "labels.placement", json!({"removeDuplicates": 20})), diff --git a/crates/engine/src/project_label_losses.rs b/crates/engine/src/project_label_losses.rs index 90d35c4919..84dd3e6a6f 100644 --- a/crates/engine/src/project_label_losses.rs +++ b/crates/engine/src/project_label_losses.rs @@ -114,6 +114,8 @@ struct Labels { #[serde(default)] stretch: Option, #[serde(default)] + obstacle_weight: Option, + #[serde(default)] classes: Vec, } @@ -280,6 +282,7 @@ fn count<'a>( let mut classes = ClassLosses::default(); let (mut moves, mut callouts, mut offsets, mut flags, mut squares, mut stretches) = (0usize, 0usize, 0usize, 0usize, 0usize, 0usize); let (mut guides, mut weights, mut clearances, mut duplicates) = (0usize, 0usize, 0usize, 0usize); + let mut obstacles = 0usize; let mut diagrams = rustgis_map::diagram::DiagramAudit::default(); for layer in raw { diagrams = diagrams.plus(layer.diagram); @@ -290,6 +293,8 @@ fn count<'a>( offsets = offsets.saturating_add(usize::from(adjusted_line_offset(labels.line_offset.as_ref()))); flags = flags.saturating_add(usize::from(damaged_flag(labels.show_all.as_ref()))); weights = weights.saturating_add(usize::from(adjusted_weight(labels.weight.as_ref()))); + // An obstacle weight (#3526) is held to the same whole numbers. + obstacles = obstacles.saturating_add(usize::from(adjusted_weight(labels.obstacle_weight.as_ref()))); clearances = clearances.saturating_add(usize::from(adjusted_clearance(labels.clearance.as_ref()))); duplicates = duplicates.saturating_add(usize::from(adjusted_duplicates(labels.remove_duplicates.as_ref()))); squares = squares.saturating_add(usize::from(adjusted_square_to(labels.square_to.as_ref()))); @@ -328,6 +333,10 @@ fn count<'a>( if weights > 0 { messages.push(format!("{name}: {weights} label weight(s) not a whole number from 0 to 10 adjusted while opening {what}")); } + if obstacles > 0 { + messages + .push(format!("{name}: {obstacles} label obstacle weight(s) not a whole number from 0 to 10 adjusted while opening {what}")); + } if clearances > 0 { messages.push(format!("{name}: {clearances} label clearance(s) not a number from 0 to 100 points adjusted while opening {what}")); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2b65676ea9..aea749e9b2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -58,6 +58,9 @@ mod cube_strips; #[path = "tests/plugin_summaries.rs"] mod plugin_summaries; +#[path = "tests/label_obstacles.rs"] +mod label_obstacles; + #[path = "tests/permission_policy.rs"] mod permission_policy; diff --git a/crates/engine/src/tests/label_obstacles.rs b/crates/engine/src/tests/label_obstacles.rs new file mode 100644 index 0000000000..7438577137 --- /dev/null +++ b/crates/engine/src/tests/label_obstacles.rs @@ -0,0 +1,137 @@ +//! A point layer's points as obstacles for labels (#3526): `labels.placement`'s `obstacleWeight`, +//! how it is saved, and what requires `label-obstacles`. + +use super::*; + +fn weight(s: &Session, id: u32) -> u8 { + s.map().layer(id).unwrap().labels.obstacle_weight +} + +fn said(s: &Session, mark: u64) -> Vec { + s.notices_since(mark).iter().map(|n| n.text.clone()).collect() +} + +#[test] +fn a_point_layer_takes_an_obstacle_weight() { + let mut s = world(); + let id = s.map().layer_by_name("Cities").unwrap().id; + assert_eq!(weight(&s, id), 0); + assert!(serde_json::to_value(&s.project).unwrap().get("requires").is_none()); + let (mark, labelled) = (s.notice_mark(), s.map().layer(id).unwrap().labels.enabled); + s.run("labels.placement", &json!({"layer": "Cities", "obstacleWeight": 8})).unwrap(); + assert_eq!(weight(&s, id), 8); + assert_eq!(s.map().layer(id).unwrap().labels.enabled, labelled, "labels stay as they were"); + assert!(said(&s, mark).is_empty(), "{:?}", said(&s, mark)); + s.run("edit.undo", &json!({})).unwrap(); + assert_eq!(weight(&s, id), 0, "undoes"); + for (given, kept, note) in [ + (json!(11), 10, "obstacleWeight 11 adjusted to 10"), + (json!(-1), 0, "obstacleWeight -1 adjusted to 0"), + (json!(5.5), 6, "obstacleWeight 5.5 adjusted to 6"), + ] { + let mark = s.notice_mark(); + s.run("labels.placement", &json!({"layer": "Cities", "obstacleWeight": given})).unwrap(); + assert_eq!(weight(&s, id), kept, "{given}"); + let notes = said(&s, mark); + assert!(notes.iter().any(|n| n.contains(note)), "{given}: {notes:?}"); + } + for bad in [json!("high"), json!(true), json!([1])] { + assert!(s.run("labels.placement", &json!({"layer": "Cities", "obstacleWeight": bad})).is_err(), "{bad}"); + } + // It is the layer's, whatever class is named; a lock holds. + s.run("labels.class.add", &json!({"layer": "Cities", "name": "Big"})).unwrap(); + s.map_mut().label_lock = Some(vec![((id, 0, 0, 0), rustgis_map::LockedPlace { place: 0, callout: None })]); + s.run("labels.placement", &json!({"layer": "Cities", "class": "Big", "obstacleWeight": 3})).unwrap(); + assert_eq!(weight(&s, id), 3); + assert!(s.map().label_lock.is_some(), "an obstacle weight keeps the lock"); + // Saved, it requires `label-obstacles`, and reads back. + let saved = serde_json::to_value(&s.project).unwrap(); + assert_eq!(saved["requires"], json!(["label-obstacles"])); + let read = Project::from_json(&saved.to_string()).unwrap(); + assert_eq!(read.maps[0].layers.iter().find(|l| l.id == id).unwrap().labels.obstacle_weight, 3); + s.run("labels.placement", &json!({"layer": "Cities", "obstacleWeight": null})).unwrap(); + assert_eq!(weight(&s, id), 0, "null: no obstacle"); + assert!(serde_json::to_value(&s.project).unwrap().get("requires").is_none()); +} + +#[test] +fn only_a_layer_with_points_is_an_obstacle() { + let mut s = world(); + 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); + // Off is taken anywhere. + s.run("labels.placement", &json!({"layer": "Rivers", "obstacleWeight": 0})).unwrap(); +} + +#[test] +fn a_files_obstacle_weight_is_held_and_said() { + // The fixture (`label_obstacles.rgis`) reads back as saved, saying nothing. + let mut fixture = Project::from_json(include_str!("../../../../schema/fixtures/label_obstacles.rgis")).unwrap(); + assert_eq!(fixture.maps[0].layers[0].labels.obstacle_weight, 8); + assert!(fixture.take_read_notices(&crate::project::ALL_PARTS).is_empty()); + assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["label-obstacles"])); + let mut damaged = serde_json::to_value(&world().project).unwrap(); + damaged["maps"][0]["layers"][0]["labels"]["obstacle_weight"] = json!(99); + damaged["maps"][0]["layers"][1]["labels"]["obstacle_weight"] = json!("x"); + let read = Session::new(Project::from_json(&damaged.to_string()).unwrap()); + assert_eq!(read.map().layers[0].labels.obstacle_weight, 10); + assert_eq!(read.map().layers[1].labels.obstacle_weight, 0); + let notes: Vec<_> = read.notices.iter().filter(|n| n.text.contains("obstacle weight")).map(|n| n.text.clone()).collect(); + assert!(notes.len() == 1 && notes[0].contains("2 label obstacle weight(s)"), "{notes:?}"); +} + +#[test] +fn saved_obstacle_weights_are_required_by_name() { + let s = world(); + let required = |command: &str, params: serde_json::Value| { + let mut project = s.project.clone(); + project.tasks = + vec![serde_json::from_value(json!({"name": "T", "steps": [{"title": "T", "command": command, "params": params}]})).unwrap()]; + serde_json::to_value(&project).unwrap().get("requires").cloned() + }; + for on in [json!(8), json!(1), json!("8")] { + let params = json!({"layer": "Cities", "obstacleWeight": on}); + assert_eq!(required("labels.placement", params), Some(json!(["label-obstacles"])), "{on}"); + } + for off in [json!(0), json!(null)] { + assert_eq!(required("labels.placement", json!({"layer": "Cities", "obstacleWeight": off})), None, "{off}"); + } + let script = json!({"script": "labels.placement {\"layer\": \"Cities\", \"obstacleWeight\": 9}"}); + assert_eq!(required("script.run", script), Some(json!(["label-obstacles"]))); + // A saved style keeps the weight its layer had. + let mut s = world(); + s.run("labels.placement", &json!({"layer": "Cities", "obstacleWeight": 7})).unwrap(); + s.run("style.new", &json!({"layer": "Cities", "name": "In the way"})).unwrap(); + s.run("labels.placement", &json!({"layer": "Cities", "obstacleWeight": 0})).unwrap(); + assert_eq!(serde_json::to_value(&s.project).unwrap()["requires"], json!(["label-obstacles"])); +} + +/// A style, layer, map or project given inline in a saved step requires it too: an older reader +/// would read the text without the weight. +#[test] +fn inline_obstacle_weights_are_required_by_name() { + let mut weighted = world(); + weighted.run("labels.placement", &json!({"layer": "Cities", "obstacleWeight": 7})).unwrap(); + let text = serde_json::to_string(&weighted.project).unwrap(); + let plain = serde_json::to_string(&world().project).unwrap(); + // A project written without its header, whose notebook cell sets one. + let mut noted: serde_json::Value = serde_json::from_str(&plain).unwrap(); + noted["notebooks"] = json!([{"name": "N", "cells": [{"kind": "code", + "source": "labels.placement {\"layer\": \"Cities\", \"obstacleWeight\": 7}"}]}]); + let noted = noted.to_string(); + for (command, text, needs) in [ + ("project.openText", &text, true), + ("map.import", &text, true), + ("project.openText", &plain, false), + ("project.openText", ¬ed, true), + ] { + let mut project = world().project.clone(); + project.tasks = vec![ + serde_json::from_value(json!({"name": "T", "steps": [{"title": "T", "command": command, "params": {"text": text}}]})).unwrap(), + ]; + let required = serde_json::to_value(&project).unwrap().get("requires").cloned(); + assert_eq!(required, needs.then(|| json!(["label-obstacles"])), "{command} {needs}"); + } +} diff --git a/crates/map/src/qgis/labels.rs b/crates/map/src/qgis/labels.rs index 7132b95ded..c3fad29043 100644 --- a/crates/map/src/qgis/labels.rs +++ b/crates/map/src/qgis/labels.rs @@ -114,7 +114,7 @@ pub(super) fn read(l: Node, geometry: Option<&str>, layer: &str, report: &mut Re LabelClass { name: DEFAULT_LABEL_CLASS.into(), visible: false, where_: None, ..first } }; let classes = if l.attribute("type") == Some("simple") { Vec::new() } else { classes }; - Some(Labeling { enabled: true, default, classes }) + Some(Labeling { enabled: true, default, classes, obstacle_weight: 0 }) } fn is_else(f: &str) -> bool { diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 1bdf1b9420..adbd25e413 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -2940,6 +2940,11 @@ 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 + /// 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")] + pub obstacle_weight: u8, } /// A layer's labels as a file holds them, read into what the commands would leave (see `From`). @@ -2950,6 +2955,8 @@ struct LabelingFile { default: LabelClass, #[serde(default)] classes: Vec, + #[serde(default, deserialize_with = "de_obstacle_weight")] + obstacle_weight: u8, } impl From for Labeling { @@ -2974,7 +2981,7 @@ impl From for Labeling { classes.push(c); } } - Labeling { enabled: f.enabled, default: f.default, classes } + Labeling { enabled: f.enabled, default: f.default, classes, obstacle_weight: f.obstacle_weight } } } @@ -3424,6 +3431,16 @@ pub fn label_weight(v: f64) -> u8 { if v.is_finite() { v.round().clamp(*LABEL_WEIGHT.start(), *LABEL_WEIGHT.end()) as u8 } else { DEFAULT_LABEL_WEIGHT } } +/// An obstacle weight (#3526) from a file: held within [`LABEL_WEIGHT`] and rounded; one that +/// isn't a number is 0, no obstacle. +fn de_obstacle_weight<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + Ok(lenient::(d)?.filter(|v| v.is_finite()).map_or(0, label_weight)) +} + +fn is_no_obstacle(w: &u8) -> bool { + *w == 0 +} + fn de_label_weight<'de, D: serde::Deserializer<'de>>(d: D) -> Result { Ok(lenient::(d)?.map_or(DEFAULT_LABEL_WEIGHT, label_weight)) } @@ -4051,7 +4068,7 @@ impl Labeling { /// Off, on the first text field that looks like a name, with only its Default class. pub fn default_for(ds: &Dataset) -> Labeling { - Labeling { enabled: false, default: LabelClass::default_for(ds), classes: Vec::new() } + Labeling { enabled: false, default: LabelClass::default_for(ds), classes: Vec::new(), obstacle_weight: 0 } } } diff --git a/crates/render/src/approximations.rs b/crates/render/src/approximations.rs index 293a307898..e260eedf2b 100644 --- a/crates/render/src/approximations.rs +++ b/crates/render/src/approximations.rs @@ -30,6 +30,9 @@ thread_local! { static SOLID_DASHES: Cell = const { Cell::new(0) }; /// Distinct glyphs actually omitted while drawing, not characters merely measured. static MISSING_GLYPHS: RefCell> = const { RefCell::new(std::collections::BTreeSet::new()) }; + /// How many points of each layer (by name) a frame left out of the obstacles for labels, since + /// they were last said ([`obstacles_left_out`]). + static OBSTACLES_LEFT: RefCell> = const { RefCell::new(std::collections::BTreeMap::new()) }; static MORE_GLYPHS: Cell = const { Cell::new(false) }; static MISSING_LABEL_TEXT: Cell = const { Cell::new(false) }; /// Whether a selected feature's highlight is being drawn ([`Highlighting`]): its redraws of a @@ -116,6 +119,7 @@ pub(crate) fn take() -> Vec { pub(crate) fn keep() -> (Vec, usize) { flush_missing_glyphs(); flush_stray_dashes(); + flush_obstacles_left(); (SAID.with(|s| std::mem::take(&mut *s.borrow_mut())), TURNED_AWAY.with(|c| c.replace(0))) } @@ -325,6 +329,29 @@ 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 +/// 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) { + OBSTACLES_LEFT.with(|m| { + let mut m = m.borrow_mut(); + let c = m.entry(name.to_string()).or_insert(0); + *c = c.saturating_add(n); + }); +} + +/// Notes what [`obstacles_left_out`] counted, a notice for each layer, and forgets it. +fn flush_obstacles_left() { + for (name, n) in OBSTACLES_LEFT.with(|m| std::mem::take(&mut *m.borrow_mut())) { + 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" + ), + ); + } +} + /// What a block diagram's top band (#2607) drew of layer `name`: `n` of the polygons along it /// fill with hatches, markers, gradients or shapebursts, which the band leaves off. pub(crate) fn band_left_plain(name: &str, n: usize) { diff --git a/crates/render/src/budget_tests.rs b/crates/render/src/budget_tests.rs index bd38a98625..07d0d07859 100644 --- a/crates/render/src/budget_tests.rs +++ b/crates/render/src/budget_tests.rs @@ -25,6 +25,8 @@ fn export_after_budgeted_interaction_matches_the_original_full_source() { let layer = map.layer_mut(id).unwrap(); layer.labels.enabled = true; layer.labels.default.field = "label".into(); + // Its points keep the labels off too (#3526), streamed or not. + layer.labels.obstacle_weight = 5; layer.transparency = 0.25; layer.definition_query = Some("label <> 'p3'".into()); } diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs index eb91a2db54..e753b63d4b 100644 --- a/crates/render/src/frame_cache.rs +++ b/crates/render/src/frame_cache.rs @@ -44,7 +44,7 @@ use tiny_skia::Pixmap; use crate::gpu_scene::DrawCmd; use crate::tiles::TileOutput; -use crate::{Backend, Candidate, PlacedLabel, Sprites, View}; +use crate::{Backend, Candidate, Gathered, Obstacle, PlacedLabel, Sprites, View}; /// The most pixels the kept pictures hold together, checkpoints and layers alone, about 66 MB: /// two views of 3840 × 2160, or one with its layer alone; two views with their layers alone at @@ -151,6 +151,7 @@ pub(crate) struct Checkpoint { /// asked for again ([`rustgis_tiles::cache::RETRY`]), as the next frame drawn whole would. pub taken: web_time::Instant, pub candidates: Vec, + pub obstacles: Vec, pub fixed: Vec, pub tiles: TileOutput, } @@ -190,6 +191,7 @@ pub(crate) struct Alone { pub sprites: Sprites, pub bursts: f32, pub candidates: Vec, + pub obstacles: Vec, pub fixed: Vec, pub tiles: TileOutput, } @@ -200,7 +202,7 @@ pub(crate) type Looks = Vec<((u32, usize), Option)>; /// The label candidates each layer gave a frame, by the layer's id and place in the map's list, /// before any were placed. -pub(crate) type LayerLabels = Vec<((u32, usize), Vec)>; +pub(crate) type LayerLabels = Vec<((u32, usize), Gathered)>; /// A kept picture and what it was drawn from. struct Kept { @@ -324,7 +326,7 @@ pub(crate) struct Plan { impl Plan { /// The label candidates the layer at place `place` in the map's list gave the frame kept, when /// they still stand. [`keep`] keeps them again for the frames after this one. - pub(crate) fn take_labels(&mut self, id: u32, place: usize) -> Option> { + pub(crate) fn take_labels(&mut self, id: u32, place: usize) -> Option { let i = self.labels.iter().position(|(k, _)| *k == (id, place))?; #[cfg(test)] REUSED.with_borrow_mut(|r| r.push(id)); @@ -464,7 +466,8 @@ pub(crate) fn keep(plan: Plan, captured: Option<(usize, Checkpoint)>, alone: Opt let mut bytes = 0; for (key, _) in &looks { if let Some((i, b)) = given.iter().position(|(k, _)| k == key).and_then(|i| { - let b = Candidate::bytes(&given.get(i)?.1); + let g = &given.get(i)?.1; + let b = Gathered::bytes(&g.candidates, &g.obstacles); (bytes + b <= MAX_LABEL_BYTES).then_some((i, b)) }) { bytes += b; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index edc8d646ec..20ed03b2f7 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2719,6 +2719,8 @@ fn covers_most(b: &Extent, layer: &Extent) -> bool { /// ([`FeatureSource::streams_chunks`](rustgis_data::source::FeatureSource::streams_chunks), /// Shapefiles) hold one kind of shape. fn draws_in_view_only(layer: &rustgis_map::Layer, labels_drawn: bool, shore: bool) -> bool { + // (A layer with only an obstacle weight reads its view alone: its plain markers, the ones this + // reads by, count as obstacles where the drawing's cull has their point.) let plain = !(labels_drawn && layer.labels.enabled) && !shore && layer.aggregation.is_none() @@ -2771,6 +2773,9 @@ struct Candidate { /// Its class removes duplicates (#2847): left out within this many points of a label placed /// before it for another feature of its layer and class with the same text. None keeps it. remove_duplicates: Option, + /// Its feature is a point: it goes over an obstacle where that point is, whichever layer + /// holds it (#3526: an annotation on its source's point). + marks_point: bool, } impl Candidate { @@ -2793,6 +2798,47 @@ 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. +#[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. + owner: (u32, u64), + x: f32, + y: f32, + /// How far its marker reaches from it, in points. + r: f32, + /// Its layer's obstacle weight: labels of a class weighing no more keep off it. + weight: u8, +} + +/// What layers give a frame to place its labels by. +#[derive(Clone, Debug, Default)] +struct Gathered { + candidates: Vec, + obstacles: Vec, + /// A tilted view's standing-up markers, where they stand in that view already: not moved by + /// it again, nor lifted onto its ground, as `obstacles` are. + raised: Vec, + /// Where each layer's `obstacles` are in the view, as its bands add to them (a tilted view's + /// bands overlap, and share what the frame may hold). + merges: std::collections::HashMap, +} + +impl From> for Gathered { + /// Labels with nothing to keep off but each other. + fn from(candidates: Vec) -> Gathered { + Gathered { candidates, ..Default::default() } + } +} + +impl Gathered { + /// About how many bytes it takes, for a budget (`frame_cache::MAX_LABEL_BYTES`). + fn bytes(candidates: &[Candidate], obstacles: &[Obstacle]) -> usize { + Candidate::bytes(candidates) + size_of_val(obstacles) + } +} + /// Alternatives from one line stretch; band siblings retain one top-level candidate slot. #[derive(Clone, Debug, Default)] struct LinePlaces { @@ -2875,6 +2921,7 @@ impl From<(PlacedLabel, f64, rustgis_map::LabelKey)> for Candidate { line: None, row: usize::MAX, remove_duplicates: None, + marks_point: false, } } } @@ -2917,7 +2964,7 @@ enum Labels<'a> { Turned(&'a View), /// Handed back unplaced, at their places in a tilted view ([`render_tilted`]), whose /// bands share one read of the streamed layers. - Tilted(&'a View, &'a mut Vec), + Tilted(&'a View, &'a mut Gathered), /// Placed in the frame, a band of a tilted view's drape ([`render_tilt_drape`]), which /// shares the view's read of the streamed layers. Shared, @@ -2942,7 +2989,7 @@ fn render_tilted( let bands_of = view.camera.tilt_bands(view.width, view.height); let data_pending = !sources_ready && sync_tilted(map, view, &bands_of, full_res_rasters, env); // Labels are placed in the tilted view: a lock on a flat view's labels doesn't apply. - let mut candidates = Vec::new(); + let mut gathered = Gathered::default(); let (w, h) = view.pixel_size(); let mut pm = Canvas::new(w, h)?; let lock = map.label_lock.take(); @@ -2969,7 +3016,7 @@ fn render_tilted( } let v = band_view(view, &b); let Some(RenderOutput::Cpu(r)) = - render_frame(map, &v, full_res_rasters, Backend::Cpu, Labels::Tilted(view, &mut candidates), false, failed_source, env) + render_frame(map, &v, full_res_rasters, Backend::Cpu, Labels::Tilted(view, &mut gathered), false, failed_source, env) else { let scale = map.ground_res_at(&v.camera) / rustgis_geom::PIXEL_M; let complete = sources_ready @@ -3040,8 +3087,10 @@ fn render_tilted( } drop(kept); extrusions_tilted(map, view, pm.pixels(), env)?; - markers_tilted(map, view, &mut pm, env); - let placed = place_tilted_labels(map, view, candidates, ground.as_ref()); + let markers = upright_markers_with(map, view, 0.0, env); + markers_tilted(map, &markers, view, &mut pm); + gathered.raised = upright_obstacles(map, view, &markers, gathered.obstacles.len()); + let placed = place_tilted_labels(map, view, gathered, ground.as_ref()); for l in &placed.labels { if let Some(icon) = &l.icon { draw_icon(&mut pm, icon, view.pixels_per_point as f32); @@ -3500,6 +3549,22 @@ fn lift_labels(view: &View, ground: &terrain::Ground, candidates: &mut [Candidat } } +/// Obstacles raised onto the terrain, as [`lift_labels`] raises the labels. +fn lift_obstacles(view: &View, ground: &terrain::Ground, obstacles: &mut [Obstacle]) { + let cam = view.camera; + let (w, h) = (view.width, view.height); + for o in obstacles { + let Some(m) = cam.try_to_map(f64::from(o.x), f64::from(o.y), w, h) else { continue }; + let (u, v) = cam.ground_px(m); + if let Some((x, y)) = cam.project_raised(u, v, ground.up_px(m, &cam), w, h) + && x.is_finite() + && y.is_finite() + { + (o.x, o.y) = (x as f32, y as f32); + } + } +} + /// A turned or tilted view as a GPU scene, drawn by the vertex shader's full perspective: a /// turned view's north-up frame, or a tilted view's bands, each clipped to its own ground (as /// [`render_tilted`] warps them), with point markers upright over them and labels placed in @@ -3536,7 +3601,7 @@ fn gpu_turned( let bands = view.camera.tilt_bands(view.width, view.height); let data_pending = !sources_ready && sync_tilted(map, view, &bands, full_res_rasters, env); let lock = map.label_lock.take(); - let mut candidates = Vec::new(); + let mut gathered = Gathered::default(); let (mut cmds, mut clips) = (Vec::new(), Vec::new()); let (mut attribution, mut tiles_pending, mut tile_errors, mut clear) = (Vec::::new(), false, Vec::::new(), [0.0; 4]); let (mut partial, mut pending_in_place) = (Vec::<(u32, String)>::new(), Vec::::new()); @@ -3566,7 +3631,7 @@ fn gpu_turned( let spread = scale * b.depth_per_unit; let (grow, spread) = if grow.is_finite() && spread.is_finite() { (grow, spread) } else { (f64::MAX, f64::MAX) }; GPU_BAND.with(|g| g.set(Some(GpuBand { band: *b, slot: i, grow, spread, margin, meshed }))); - let frame = render_frame(map, &v, full_res_rasters, Backend::Gpu, Labels::Tilted(view, &mut candidates), false, failed_source, env); + let frame = render_frame(map, &v, full_res_rasters, Backend::Gpu, Labels::Tilted(view, &mut gathered), false, failed_source, env); meshed = GPU_BAND.with(|g| g.take()).map_or(meshed, |g| g.meshed); let Some(RenderOutput::Gpu(scene)) = frame else { if cancel::requested() { @@ -3624,7 +3689,13 @@ fn gpu_turned( if !plain { return None; } - let placed = place_tilted_labels(map, view, candidates, None); + // An icon label is drawn on the CPU: its view isn't made twice (markers and obstacles) to find out. + if gathered.candidates.iter().any(|c| c.label.icon.is_some()) { + return None; + } + let markers = upright_markers_with(map, view, 0.0, env); + gathered.raised = upright_obstacles(map, view, &markers, gathered.obstacles.len()); + let placed = place_tilted_labels(map, view, gathered, None); if placed.labels.iter().any(|l| l.icon.is_some()) { return None; } @@ -3636,10 +3707,8 @@ fn gpu_turned( clips.push(CmdClip::ALL); } let ppp = view.pixels_per_point as f32; - let instances: Vec = upright_markers_with(map, view, 0.0, env) - .iter() - .flat_map(|m| mesh::marker_instances(m.at, origin, &m.symbol, ppp, m.selected.then_some(SELECTION))) - .collect(); + let instances: Vec = + markers.iter().flat_map(|m| mesh::marker_instances(m.at, origin, &m.symbol, ppp, m.selected.then_some(SELECTION))).collect(); if !instances.is_empty() { cmds.push(DrawCmd::Points { origin, instances: std::sync::Arc::new(instances) }); clips.push(CmdClip { upright: true, ..CmdClip::ALL }); @@ -3667,7 +3736,8 @@ fn gpu_turned( /// band's offer. Tile labels (keyed by their place in a band's list) are told apart by their /// text and where they land, to a few points. Extruded /// features' labels go up onto their roofs, and on terrain every label onto the ground's relief. -fn place_tilted_labels(map: &Map, view: &View, mut candidates: Vec, ground: Option<&terrain::Ground>) -> Placement { +fn place_tilted_labels(map: &Map, view: &View, gathered: impl Into, ground: Option<&terrain::Ground>) -> Placement { + let Gathered { mut candidates, mut obstacles, raised, merges: _ } = gathered.into(); let mut seen = std::collections::HashSet::new(); let mut seen_tile = std::collections::HashSet::new(); let mut seen_repeat = std::collections::HashSet::new(); @@ -3684,7 +3754,9 @@ fn place_tilted_labels(map: &Map, view: &View, mut candidates: Vec, g raise_labels(map, view, &mut candidates); if let Some(g) = ground { lift_labels(view, g, &mut candidates); + lift_obstacles(view, g, &mut obstacles); } + obstacles.extend(raised); // Group bands under one candidate slot, retaining their near-first order. A nearer // band's failed places must not suppress a later band's usable ones. let mut groups: Vec = Vec::new(); @@ -3704,7 +3776,8 @@ fn place_tilted_labels(map: &Map, view: &View, mut candidates: Vec, g } groups.push(candidate); } - place_labels_with_previews(groups, Vec::new(), view.width as f32, view.height as f32, false, map.label_display.show_unplaced) + let (w, h) = (view.width as f32, view.height as f32); + place_labels_with_previews(groups, Vec::new(), obstacles, w, h, false, map.label_display.show_unplaced) } /// Whether a turned or tilted `view` of `map` may be drawn on the GPU ([`gpu_turned`]): only @@ -4071,6 +4144,8 @@ fn stands_up(map: &Map, layer: &rustgis_map::Layer) -> bool { pub struct UprightMarker { /// The owning layer, shared by its markers for loss notices during the tilted pass. layer: std::sync::Arc, + /// Its layer's id and its feature's, as a label's key names them (#3526). + owner: (u32, u64), /// Where it stands (the camera's coordinates). pub at: Coord, /// The ground's height under it (map units), on terrain; 0 without. @@ -4138,6 +4213,40 @@ pub fn marker_outline(marker: Marker, x: f32, y: f32, r: f32) -> Vec<(f32, f32)> } } +/// The obstacles the markers a tilted `view` of `map` stands upright make for labels (#3526): each +/// where and as large as it is drawn there, those of layers with an obstacle weight, merged as +/// obstacles are where they are gathered, within what the frame may hold beside the `held` ground +/// obstacles it has (none while labels are paused, as on a flat map). +fn upright_obstacles(map: &Map, view: &View, markers: &[UprightMarker], held: usize) -> Vec { + let mut out = Vec::new(); + if map.label_display.paused { + return out; + } + let limit = if held.saturating_add(markers.len()) < obstacle_check_from() { usize::MAX } else { obstacle_limit().saturating_sub(held) }; + let mut left_out = std::collections::BTreeMap::::new(); + let mut merges: std::collections::HashMap = Default::default(); + for m in markers { + let Some(weight) = map.layer(m.owner.0).map(|l| l.labels.obstacle_weight).filter(|w| *w > 0) else { continue }; + // An image takes its layer's opacity in drawing (a shape has it in its colours). + if m.opacity <= 0.0 { + continue; + } + let Some((x, y, k, _)) = m.place(&view.camera, view.width, view.height) else { continue }; + // (A marker standing up has no marks: `stands_up` leaves out a layer with strokes.) + let Some(reach) = marker_obstacle_reach(&m.symbol, &[], k as f32 * view.pixels_per_point as f32) else { continue }; + let o = Obstacle { owner: m.owner, x: x as f32, y: y as f32, r: reach * k as f32, weight }; + if !merges.entry(m.owner.0).or_default().add(&mut out, o, limit) { + *left_out.entry(m.owner.0).or_insert(0) += 1; + } + } + for layer in map.layers.iter() { + if let Some(n) = left_out.get(&layer.id) { + approximations::obstacles_left_out(&layer.name, *n); + } + } + out +} + /// The point markers a tilted `view` of `map` stands upright ([`stands_up`]), bottom layer /// first and each layer's far to near, so nearer markers draw over farther ones. Those with /// their point on the ground it shows, grown by `margin` of its size on every side (for a view @@ -4243,7 +4352,8 @@ fn upright_markers_with(map: &mut Map, view: &View, margin: f64, env: &Env) -> V } // On terrain, standing on the ground (its height in map units there). let height = ground.as_ref().and_then(|g| g.height(*c).map(|m| (m / g.per_unit(*c)).clamp(-1e9, 1e9))).unwrap_or(0.0); - here.push((k, UprightMarker { layer: name.clone(), at: *c, height, symbol, opacity, selected })); + let owner = (layer.id, layer.dataset.features.row(row).map_or(row as u64, |r| r.id())); + here.push((k, UprightMarker { layer: name.clone(), owner, at: *c, height, symbol, opacity, selected })); } } here.sort_by(|a, b| a.0.total_cmp(&b.0)); @@ -4308,13 +4418,13 @@ fn foggy_picture_marker( } /// The point markers of a tilted view, stood up over its ground and extrusions. -fn markers_tilted(map: &mut Map, view: &View, pm: &mut Canvas, env: &Env) { +fn markers_tilted(map: &Map, markers: &[UprightMarker], view: &View, pm: &mut Canvas) { let (_, fog) = tilt_sky(map); let ppp = (f64::from(pm.width()) / view.width.max(1e-9)) as f32; let (pw, ph) = (pm.width() as f32, pm.height() as f32); let mut active_layer = None; let mut active_name: Option> = None; - for m in upright_markers_with(map, view, 0.0, env) { + for m in markers { let Some((x, y, k, t)) = m.place(&view.camera, view.width, view.height) else { continue }; let s = m.look(k, fog, t); let (x, y) = (x as f32 * ppp, y as f32 * ppp); @@ -5229,6 +5339,9 @@ fn render_frame( // Layers, bottom first. let mut label_candidates: Vec = Vec::new(); + let mut label_obstacles: Vec = Vec::new(); + // How many obstacles a frame may hold, asked of the system once a frame, when a layer needs it. + let mut obstacle_room: Option = None; let display = map.label_display; if !display.locked { map.label_lock = None; @@ -5266,6 +5379,7 @@ fn render_frame( ctx.sprites.borrow_mut().clone_from(&c.sprites); ctx.bursts.set(c.bursts); label_candidates.clone_from(&c.candidates); + label_obstacles.clone_from(&c.obstacles); fixed_labels.clone_from(&c.fixed); tile_out = c.tiles.clone(); } @@ -5323,7 +5437,8 @@ fn render_frame( if let Some((a, pixels)) = drawn_alone.take().filter(|_| complete(&tile_out)) { let (candidates, fixed, tiles) = (label_candidates.clone(), fixed_labels.clone(), tile_out.clone()); let (sprites, bursts) = (ctx.sprites.borrow().clone(), ctx.bursts.get()); - captured_alone = Some((a, frame_cache::Alone { pixels, sprites, bursts, candidates, fixed, tiles })); + let obstacles = label_obstacles.clone(); + captured_alone = Some((a, frame_cache::Alone { pixels, sprites, bursts, candidates, obstacles, fixed, tiles })); } // What is drawn so far already leaves a picture, waiting or in the scene (see // `pictureless`). @@ -5362,6 +5477,7 @@ fn render_frame( // Over a restored picture, its tiles are as old as that picture. taken: cached.as_ref().and_then(|p| p.restored.as_ref()).map_or_else(web_time::Instant::now, |c| c.taken), candidates: label_candidates.clone(), + obstacles: label_obstacles.clone(), fixed: fixed_labels.clone(), tiles: tile_out.clone(), }, @@ -5428,6 +5544,7 @@ fn render_frame( ctx.sprites.borrow_mut().clone_from(&a.sprites); ctx.bursts.set(a.bursts); label_candidates.clone_from(&a.candidates); + label_obstacles.clone_from(&a.obstacles); fixed_labels.clone_from(&a.fixed); tile_out = a.tiles.clone(); continue; @@ -5655,7 +5772,9 @@ fn render_frame( let mut taken = cached.as_mut().filter(|_| keeps_labels).and_then(|p| p.take_labels(lid, li)); // Copied only while the frame's copies stay within what a view keeps. let room = frame_cache::MAX_LABEL_BYTES.saturating_sub(layer_label_bytes); - let mut gave_labels: Option> = None; + let mut gave_labels: Option = None; + // Where its obstacles are, for all of a streamed layer's chunks. + let mut obstacle_cells = ObstacleMerge::default(); // Whether the picture being drawn held anything before this layer: a layer drawn as a // picture of its own (`gpu_own`) leaves it so. let dirty_before = cpu_dirty; @@ -5680,7 +5799,7 @@ fn render_frame( // Exact positions are needed by labels, selection and effects. Plain flat layers can // project only their retained display vertices, leaving interaction geometry lazy. let display_only = globe.is_none() - && (!layer.labels.enabled || display.paused) + && ((!layer.labels.enabled && layer.labels.obstacle_weight == 0) || display.paused) && layer.selection.is_empty() && !layer.graphics && layer.aggregation.is_none() @@ -6202,11 +6321,68 @@ fn render_frame( // as working them out again. (Not compacted: only a layer read from its source is, and // that keeps none.) if let Some(c) = taken.take() { - gave_labels = (Candidate::bytes(&c) <= room).then(|| c.clone()); - label_candidates.extend(c); + gave_labels = (Gathered::bytes(&c.candidates, &c.obstacles) <= room).then(|| c.clone()); + label_candidates.extend(c.candidates); + label_obstacles.extend(c.obstacles); return Ok(()); } - let first_label = label_candidates.len(); + 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.) + if labels.obstacle_weight > 0 && !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); + // The same, on the map, by each feature's extent as the drawing skips them, so a + // layer's rows far from the view cost a look at their extent, not a projection. + let reach_cull = ctx.cull.padded(0.0, near * map_per_px); + // 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; + for (row, g) in geoms.iter().enumerate() { + let Some(g) = g else { continue }; + let points = match g { + Geometry::Point(c) => std::slice::from_ref(c), + Geometry::MultiPoint(v) => v.as_slice(), + _ => continue, + }; + if rows.get(row) != Some(&true) || (globe.is_none() && extents.get(row).is_some_and(|e| !e.intersects(&reach_cull))) { + continue; + } + #[cfg(test)] + OBSTACLE_ROWS.with(|c| c.set(c.get() + 1)); + 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. + if here.peek().is_none() { + continue; + } + let (sym, strokes) = styler.style(row); + let marks = styler.marks(row, strokes); + let Some(reach) = marker_obstacle_reach(&sym, &marks, ctx.ppp) else { continue }; + // A plain marker is drawn only where its point is in the cull, as the drawing has + // it (images and marks reach in from further out, which the margin above holds). + let plain = globe.is_none() + && marks.is_empty() + && !matches!(sym.marker, Marker::Picture(p) if picture::marker_aspect(p).is_some()); + // A layer the GPU drew is culled with its meshes' margin; one it handed to the CPU, with the CPU's. + 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 label_obstacles.len() < ask_from { usize::MAX } else { *obstacle_room.get_or_insert_with(obstacle_limit) }; + if !obstacle_cells.add(&mut label_obstacles, o, limit) { + left_out += 1; + } + } + } + if left_out > 0 { + approximations::obstacles_left_out(&layer.name, left_out); + } + } // Each label class labels every feature its clause takes, as in ArcGIS Pro (#732), when // shown, in range and on a field the layer has (#618) or by a text expression. Its // expressions are compiled once for the drawing. @@ -7067,13 +7243,17 @@ fn render_frame( line: line_places.take(), row, remove_duplicates: class.remove_duplicates, + marks_point: is_point, }); } } } } - if keeps_labels && let Some(gave) = label_candidates.get(first_label..).filter(|c| Candidate::bytes(c) <= room) { - gave_labels = Some(gave.to_vec()); + if keeps_labels + && let (Some(candidates), Some(obstacles)) = (label_candidates.get(first_label..), label_obstacles.get(first_obstacle..)) + && Gathered::bytes(candidates, obstacles) <= room + { + gave_labels = Some(Gathered { candidates: candidates.to_vec(), obstacles: obstacles.to_vec(), ..Default::default() }); } if complete_source && matches!(labels_to, Labels::Own | Labels::Turned(_)) { compact_label_candidates(&mut label_candidates); @@ -7367,7 +7547,7 @@ fn render_frame( return None; } if let Some(c) = gave_labels { - layer_label_bytes += Candidate::bytes(&c); + layer_label_bytes += Gathered::bytes(&c.candidates, &c.obstacles); layer_labels.push(((lid, li), c)); } if let (Some(spool), Some(x)) = (&mut extrusions, &layer.extrusion) @@ -7424,7 +7604,8 @@ fn render_frame( if let Some((a, pixels)) = drawn_alone.take().filter(|_| complete(&tile_out)) { let (candidates, fixed, tiles) = (label_candidates.clone(), fixed_labels.clone(), tile_out.clone()); let (sprites, bursts) = (ctx.sprites.borrow().clone(), ctx.bursts.get()); - captured_alone = Some((a, frame_cache::Alone { pixels, sprites, bursts, candidates, fixed, tiles })); + let obstacles = label_obstacles.clone(); + captured_alone = Some((a, frame_cache::Alone { pixels, sprites, bursts, candidates, obstacles, fixed, tiles })); } if let Some(id) = below { draw_tiles!(Some(id)); @@ -7454,6 +7635,13 @@ fn render_frame( label_candidates.push(tile_candidate(l, pri, i)); } } + // A layer wholly transparent shows no points to keep off. (Here, not as they are gathered: + // kept ones take no transparency.) + if !label_obstacles.is_empty() { + let unseen: std::collections::HashSet = + map.layers.iter().filter(|l| l.opacity() * group_opacity.get(&l.id).copied().unwrap_or(1.0) <= 0.0).map(|l| l.id).collect(); + label_obstacles.retain(|o| !unseen.contains(&o.owner.0)); + } if let Labels::Tilted(to, out) = &mut labels_to { // At their places in the tilted view; those behind the camera, under the sky or too far // to read are left out. @@ -7468,9 +7656,29 @@ fn render_frame( }; let fixed = fixed_labels.into_iter().map(fixed_candidate); for c in fixed.chain(label_candidates) { - out.extend(tilt_candidate(c, &at)); + out.candidates.extend(tilt_candidate(c, &at)); + } + // Markers on the ground, as large as their band is shown (those standing up are the view's), + // merged with the other bands' by the point of the view, within what the frame may hold. + let held = out.obstacles.len() + label_obstacles.len(); + let limit = if held < obstacle_check_from() { usize::MAX } else { *obstacle_room.get_or_insert_with(obstacle_limit) }; + let mut left_out = std::collections::BTreeMap::::new(); + for o in std::mem::take(&mut label_obstacles) { + let Some((x, y)) = at(o.x, o.y) else { continue }; + let o = Obstacle { x, y, r: shown_reach(&at, (o.x, o.y), o.r), ..o }; + let layer = o.owner.0; + if !out.merges.entry(layer).or_default().add(&mut out.obstacles, o, limit) { + *left_out.entry(layer).or_insert(0) += 1; + } + } + // Said as a flat frame says it: this merge crosses the bands, which each only see their own. + for layer in map.layers.iter() { + if let Some(n) = left_out.get(&layer.id) { + approximations::obstacles_left_out(&layer.name, *n); + } } label_candidates = Vec::new(); + label_obstacles = Vec::new(); fixed_labels = Vec::new(); } let turned = match &labels_to { @@ -7488,6 +7696,11 @@ fn render_frame( for c in &mut label_candidates { turn_candidate(c, at); } + for o in &mut label_obstacles { + if let Some((x, y)) = at(o.x, o.y) { + (o.x, o.y) = (x, y); + } + } for l in &mut fixed_labels { turn_with(l, &at); if let Some((x, y)) = at(l.x, l.y) { @@ -7503,7 +7716,15 @@ fn render_frame( } None => (view.width, view.height), }; - let placed = place_labels_with_previews(label_candidates, fixed_labels, lw as f32, lh as f32, lock.is_some(), display.show_unplaced); + let placed = place_labels_with_previews( + label_candidates, + fixed_labels, + label_obstacles, + lw as f32, + lh as f32, + lock.is_some(), + display.show_unplaced, + ); // Each placed label's map layer, for a recording to keep each layer's labels together: the // fixed labels (graphics text) come first, then one for each key. let label_layers: Vec<(u32, String)> = if pm.is_recording() { @@ -8850,13 +9071,14 @@ fn callout_spot( /// the first where all of it shows; where none does, its own place shows what fits there. #[cfg(test)] fn place_labels(cands: impl IntoIterator>, fixed: Vec, w: f32, h: f32, locked: bool) -> Placement { - place_labels_with_previews(cands, fixed, w, h, locked, true) + place_labels_with_previews(cands, fixed, Vec::new(), w, h, locked, true) } /// Places labels while retaining failed previews only when View Unplaced needs them. fn place_labels_with_previews( cands: impl IntoIterator>, fixed: Vec, + obstacles: Vec, w: f32, h: f32, locked: bool, @@ -8865,6 +9087,8 @@ fn place_labels_with_previews( let mut cands: Vec = cands.into_iter().map(Into::into).collect(); cands.sort_by(placed_first); let mut grid = LabelGrid::new(w, h); + // A lock replays its labels over whatever is under them. + let obstacles = Obstacles::new(if locked { Vec::new() } else { obstacles }, w, h); for l in &fixed { let (text, icon) = label_boxes(l); text.iter().chain(&icon).for_each(|b| grid.insert(*b)); @@ -8881,7 +9105,9 @@ fn place_labels_with_previews( let fallbacks = head.line.as_mut().map(|line| std::mem::take(&mut line.fallbacks)).unwrap_or_default(); // Siblings are contiguous: hold just one temporary preview until the group finishes. let mut pending = None; - for Candidate { label: mut l, key, alternatives, curves, line, remove_duplicates, .. } in std::iter::once(head).chain(fallbacks) { + for Candidate { label: mut l, key, weight, alternatives, curves, line, remove_duplicates, marks_point, .. } in + std::iter::once(head).chain(fallbacks) + { let c = l.collide; let feature = c.callout_anchor.map(|[ax, ay]| [l.x + ax, l.y + ay]); let grouped = line.as_ref().is_some_and(|line| line.deduplicate); @@ -8889,6 +9115,10 @@ fn place_labels_with_previews( continue; } let collide = l.collide; + // Whether a box is taken for this label: by a label placed before it, or by a point + // it keeps off. + let marked = feature.filter(|_| marks_point); + let taken = |b: &[f32; 4]| grid.hits(b) || obstacles.hits(b, weight, (key.0, key.1), marked); let (has_text, has_icon) = (!l.text.is_empty(), l.icon.is_some()); // Its own place, else the first alternative where all of it shows (the text moves there; // an icon stays). @@ -8940,7 +9170,7 @@ fn place_labels_with_previews( if text.iter().chain(&icon).all(outside) { continue; } - let (show_text, show_icon) = shows(&l, &text, &icon, &grid, locked); + let (show_text, show_icon) = shows(&l, &text, &icon, taken, locked); let whole = show_text == has_text && show_icon == has_icon; if i == 0 || whole { at = Some((i, LabelPlace::take(&mut l), text, icon, show_text, show_icon)); @@ -8983,7 +9213,8 @@ fn place_labels_with_previews( && !locked && !has_icon && has_text - && text.iter().any(|b| grid.hits(b)) + // Crowded by labels (and by obstacles, unless it is drawn over them whatever is there). + && text.iter().any(|b| grid.hits(b) || (!collide.text_allow_overlap && obstacles.hits(b, weight, (key.0, key.1), marked))) && searches > 0 // A duplicate where it is goes rather than moving away from its twin: no search spent. && !duplicate(&l) @@ -8993,7 +9224,7 @@ fn place_labels_with_previews( // spot it stays, and is left out, or shown over the others when its class shows all. searches -= 1; if let Some((dx, dy, line)) = - callout_spot(&text, &text_edges(&l), f, collide.callout_reach, |b| !grid.hits(b), w, h, &mut spots) + callout_spot(&text, &text_edges(&l), f, collide.callout_reach, |b| !taken(b), w, h, &mut spots) { moved_by = Some([dx, dy]); l.x += dx; @@ -9099,11 +9330,11 @@ impl PlacedTexts { /// Which of a label's text and icon show with their boxes `text` and `icon` where they are, as /// MapLibre has it: each where it fits, or may overlap, and a part that isn't optional only with /// the other. -fn shows(l: &PlacedLabel, text: &[[f32; 4]], icon: &[[f32; 4]], grid: &LabelGrid, locked: bool) -> (bool, bool) { +fn shows(l: &PlacedLabel, text: &[[f32; 4]], icon: &[[f32; 4]], taken: impl Fn(&[f32; 4]) -> bool, locked: bool) -> (bool, bool) { let c = l.collide; let (has_text, has_icon) = (!text.is_empty(), !icon.is_empty()); // A label moved by hand shows where it was put, whatever is under it. - let fits = |boxes: &[[f32; 4]], overlap: bool| locked || overlap || c.pinned || !boxes.iter().any(|b| grid.hits(b)); + let fits = |boxes: &[[f32; 4]], overlap: bool| locked || overlap || c.pinned || !boxes.iter().any(&taken); let mut show_text = has_text && fits(text, c.text_allow_overlap); let mut show_icon = has_icon && fits(icon, c.icon_allow_overlap); // Which part may show without the other (MapLibre's rules). @@ -9227,17 +9458,204 @@ impl LabelGrid { /// Whether a box overlaps one already placed. fn hits(&self, b: &[f32; 4]) -> bool { + self.hits_where(b, |_| true) + } + + /// Whether a box overlaps one placed that `counts`, by its place in the order they came. + fn hits_where(&self, b: &[f32; 4], counts: impl Fn(usize) -> bool) -> bool { let Some((xs, ys)) = self.span(b) else { return true }; ys.into_iter().any(|y| { xs.clone().any(|x| { self.cells.get(y * self.cols + x).is_some_and(|c| { - c.iter().any(|&i| self.boxes.get(i as usize).is_some_and(|o| b[0] < o[2] && o[0] < b[2] && b[1] < o[3] && o[1] < b[3])) + c.iter().any(|&i| { + self.boxes.get(i as usize).is_some_and(|o| b[0] < o[2] && o[0] < b[2] && b[1] < o[3] && o[1] < b[3]) + && counts(i as usize) + }) }) }) }) } } +/// How far a marker on the ground, `r` points from its centre in its band, reaches in the view the +/// band is shown in (`at`: a place of the band there, if it shows): the larger of its reach across +/// the screen and up and down it, each from its first point that shows (east or west, south or +/// north), else as large as in its band, so a point that doesn't show doesn't drop the obstacle. +fn shown_reach(at: &impl Fn(f32, f32) -> Option<(f32, f32)>, (x, y): (f32, f32), r: f32) -> f32 { + let Some((sx, sy)) = at(x, y) else { return r }; + let along = + |dx: f32, dy: f32| [1.0, -1.0].into_iter().find_map(|d| at(x + d * dx, y + d * dy)).map(|(ex, ey)| (ex - sx).hypot(ey - sy)); + match (along(r, 0.0), along(0.0, r)) { + (Some(a), Some(b)) => a.max(b), + (a, b) => a.or(b).unwrap_or(r), + } +} + +/// The feature an obstacle merged from points of more than one feature of its layer belongs to: +/// none's, so no label of the layer is exempt from it. +const NO_OWNER: u64 = u64::MAX; + +/// How near a label's own point an obstacle is for it to be that point, in points. +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; + +/// 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 +/// no label's way. +fn marker_obstacle_reach(sym: &Symbol, marks: &[LineStroke], px_per_point: f32) -> Option { + 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()) { + return None; + } + // An image wider than `picture_marker` draws (100,000 pixels) is the circle, too. + let image = matches!(sym.marker, Marker::Picture(p) if picture::marker_aspect(p).is_some()) + && sym.size.max(1.0) * px_per_point < PICTURE_MARKER_MAX_PX; + let outline = if !image && sym.stroke.a() > 0 { sym.stroke_width.max(0.0) } else { 0.0 }; + (image || sym.fill.a() > 0 || outline > 0.0).then(|| sym.size.max(1.0) * marker_reach(sym.marker) + outline / 2.0) +} + +/// 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). +const OBSTACLE_BYTES: u64 = 256; + +/// The fewest obstacles a frame may hold, whatever memory is free: about 60 MB, more than any view +/// of a few thousand points makes. +const OBSTACLES_FLOOR: usize = 250_000; + +/// How many obstacles a frame holds before it asks the system what memory is left: the fewest it +/// may hold. (A test sets it with its limit.) +fn obstacle_check_from() -> usize { + #[cfg(test)] + if let Some(n) = OBSTACLE_LIMIT.with(std::cell::Cell::get) { + return n; + } + OBSTACLES_FLOOR +} + +/// How many obstacles a frame may hold, as the memory left allows ([`rustgis_data::memory::planned`]): +/// past it a layer's points aren't kept off by labels, and the layer says so. +fn obstacle_limit() -> usize { + #[cfg(test)] + OBSTACLE_ASKED.with(|c| c.set(c.get() + 1)); + #[cfg(test)] + if let Some(n) = OBSTACLE_LIMIT.with(std::cell::Cell::get) { + return n; + } + rustgis_data::memory::planned(OBSTACLES_FLOOR, usize::MAX, OBSTACLE_BYTES) +} + +#[cfg(test)] +thread_local! { + /// A limit set for a test, in place of the memory's. + static OBSTACLE_LIMIT: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// The rows of an obstacle layer that reached their projection, for a test. + static OBSTACLE_ROWS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many times a frame asked the system for the obstacles memory allows, for a test. + static OBSTACLE_ASKED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The most a marker counts as reaching from its point, in points, as an obstacle: a bigger one +/// (a size by field can be hundreds of points) spans no more of the placement grid than this. +const MAX_OBSTACLE_REACH: f32 = 32.0; + +/// Obstacles of one layer, merged as they are gathered so what a frame holds follows its size, not +/// the layer's rows: points in one point of the screen are one obstacle, at that point's centre and +/// grown to cover them. Where they are of more than one feature, no feature's label is exempt from +/// it by its owner; a label over its own point is exempt where it is within [`SAME_PLACE`] of it, +/// which the centre of the point of the screen is for each of its points. +#[derive(Clone, Debug, Default)] +struct ObstacleMerge(std::collections::HashMap<(i32, i32), (usize, bool)>); + +impl ObstacleMerge { + /// Adds `o`, its reach held to [`MAX_OBSTACLE_REACH`], to `list`, or merges it into the obstacle + /// already in its point of the screen. A point in a point of the screen with no obstacle yet is + /// left out, and this says so, once `list` holds `limit`. + fn add(&mut self, list: &mut Vec, o: Obstacle, limit: usize) -> bool { + let o = Obstacle { r: o.r.min(MAX_OBSTACLE_REACH), ..o }; + let key = (o.x.round() as i32, o.y.round() as i32); + match self.0.entry(key) { + std::collections::hash_map::Entry::Vacant(cell) => { + if list.len() >= limit { + return false; + } + cell.insert((list.len(), false)); + list.push(o); + } + std::collections::hash_map::Entry::Occupied(mut cell) => { + let (at, merged) = *cell.get(); + if let Some(held) = list.get_mut(at) { + // Each point is within half a diagonal of the point's centre: the first merge + // grows the obstacle by that, the next ones hold what it covers. + let half = std::f32::consts::FRAC_1_SQRT_2; + held.r = if merged { held.r.max(o.r + half) } else { held.r.max(o.r) + half }; + cell.get_mut().1 = true; + (held.x, held.y) = (key.0 as f32, key.1 as f32); + if held.owner != o.owner { + held.owner = (o.owner.0, NO_OWNER); + } + } + } + } + true + } +} + +/// The points 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, + /// Each point's owner, weight and place, in the grid's order. + who: Vec<((u32, u64), u8, [f32; 2])>, + /// The heaviest: a label above it has nothing to look for. + heaviest: u8, +} + +impl Obstacles { + fn new(obstacles: Vec, w: f32, h: f32) -> Obstacles { + let mut out = Obstacles { grid: None, who: Vec::new(), heaviest: 0 }; + let reach = LabelGrid::MARGIN; + for o in obstacles { + let b = [o.x - o.r, o.y - o.r, o.x + o.r, o.y + o.r]; + // Those far off the view are left out, which would crowd the cells along its edge. + if !b.iter().all(|v| v.is_finite()) || b[2] < -reach || b[3] < -reach || b[0] > w + reach || b[1] > h + reach { + continue; + } + out.grid.get_or_insert_with(|| LabelGrid::new(w, h)).insert(b); + out.who.push((o.owner, o.weight, [o.x, o.y])); + out.heaviest = out.heaviest.max(o.weight); + } + out + } + + /// How many cell entries the grid holds, for a test of how much a frame's obstacles take. + #[cfg(test)] + fn references(&self) -> usize { + self.grid.as_ref().map_or(0, |g| g.cells.iter().map(Vec::len).sum()) + } + + /// Whether a label of `weight` of the feature `owner`, marking the point at `marked` if its + /// feature is one, keeps off a point in the box: one weighing at least as much, of another + /// feature, and not where the label's own point is (within the point of the screen obstacles + /// are merged by). + fn hits(&self, b: &[f32; 4], weight: u8, owner: (u32, u64), marked: Option<[f32; 2]>) -> bool { + weight <= self.heaviest + && self.grid.as_ref().is_some_and(|grid| { + grid.hits_where(b, |i| { + self.who.get(i).is_some_and(|&(o, w, [x, y])| { + w >= weight && o != owner && marked.is_none_or(|[mx, my]| (x - mx).hypot(y - my) >= SAME_PLACE) + }) + }) + }) + } +} + thread_local! { /// Set on the interface's thread ([`on_the_interface_thread`]), and while the Layout view's /// page is drawn: frames don't wait for cast shadows (see [`without_shadow_wait`]). @@ -10156,6 +10574,7 @@ mod tests { line: None, row: 0, remove_duplicates: None, + marks_point: false, }; let at = |p: &Placement| p.labels.iter().map(|l| (l.text.clone(), l.x, l.y)).collect::>(); // None: left out, as before. @@ -10199,6 +10618,7 @@ mod tests { line: None, row: 0, remove_duplicates: None, + marks_point: false, alternatives: vec![other.clone()], }; let blocker = label("Blocker", 100.0, None, 0.0); @@ -10238,6 +10658,7 @@ mod tests { line: None, row: 0, remove_duplicates: None, + marks_point: false, alternatives: vec![alternative.clone()], }; let projected = tilt_candidate(c, &|x, y| (y > 50.0).then_some((2.0 * x + 10.0, 2.0 * y))).unwrap(); @@ -10266,6 +10687,7 @@ mod tests { line: None, row: 0, remove_duplicates: None, + marks_point: false, }; let c = tilt_candidate(offer((10.0, 50.0), vec![(10.0, 60.0), (10.0, 150.0), (20.0, 160.0)]), &at).unwrap(); assert_eq!((c.label.x, c.label.y), (1010.0, 150.0)); @@ -10287,7 +10709,7 @@ mod tests { let view = View { width: 400.0, height: 300.0, pixels_per_point: 1.0, camera, sky: false }; let (a, b) = (label("Capitals", 100.0, None, 0.0), label("Default", 300.0, None, 0.0)); let texts = |c: Vec<(PlacedLabel, f64, rustgis_map::LabelKey)>| -> Vec { - place_tilted_labels(&map, &view, c.into_iter().map(Candidate::from).collect(), None) + place_tilted_labels(&map, &view, c.into_iter().map(Candidate::from).collect::>(), None) .labels .into_iter() .map(|l| l.text) @@ -10323,6 +10745,7 @@ mod tests { line: None, row: usize::MAX, remove_duplicates: None, + marks_point: false, } }) .collect() @@ -11217,7 +11640,7 @@ mod tests { let c: Candidate = (label(text, x, None, 0.0), 0.0, (lid, fid, ci, 0)).into(); Candidate { remove_duplicates: (within > 0.0).then_some(within), ..c } }; - let place = |c: Vec| place_labels_with_previews(c, Vec::new(), 2000.0, 40.0, false, true); + let place = |c: Vec| place_labels_with_previews(c, Vec::new(), Vec::new(), 2000.0, 40.0, false, true); let shown = |p: &Placement| p.labels.iter().map(|l| (l.text.clone(), l.center_x().round() as i32)).collect::>(); let main = |x: f32, fid: u64, within: f32| dup("Main", x, (1, fid, 0), within); // Off (0): both, as before. @@ -11278,7 +11701,7 @@ mod tests { .map(|(x, fid)| Candidate { remove_duplicates: Some(200.0), ..(label("Main", x, None, 0.0), 0.0, (1, fid, 0, 0)).into() }) }; let count = |locked| { - let placed = place_labels_with_previews(twins(), Vec::new(), 2000.0, 200.0, locked, true); + let placed = place_labels_with_previews(twins(), Vec::new(), Vec::new(), 2000.0, 200.0, locked, true); placed.labels.iter().filter(|l| l.text == "Main").count() }; assert_eq!(count(false), 1, "taking the lock: one"); @@ -11299,7 +11722,7 @@ mod tests { // callout and then removed; "Oak" comes last, crowded too. let mut cands: Vec = (1..=MAX_CALLOUT_SEARCHES as u64 + 1).map(|fid| crowded("Main", fid, 0.0)).collect(); cands.push(crowded("Oak", 10_000, -1.0)); - let placed = place_labels_with_previews(cands, Vec::new(), 2000.0, 200.0, false, true); + let placed = place_labels_with_previews(cands, Vec::new(), Vec::new(), 2000.0, 200.0, false, true); let oak = placed.labels.iter().find(|l| l.text == "Oak"); assert!(oak.is_some_and(|l| l.collide.callout.is_some()), "Oak moved to a free spot with its line"); assert_eq!(placed.labels.iter().filter(|l| l.text == "Main").count(), 1); @@ -12718,7 +13141,10 @@ mod tests { assert_eq!(upright_markers(&mut map, &view, 0.0).len(), 2); approximations::layer(Some("Outer")); let mut image = Pixmap::new(120, 80).unwrap(); - crate::canvas::with_canvas(&mut image, |canvas| markers_tilted(&mut map, &view, canvas, &Env::default())); + crate::canvas::with_canvas(&mut image, |canvas| { + let markers = upright_markers_with(&mut map, &view, 0.0, &Env::default()); + markers_tilted(&map, &markers, &view, canvas) + }); approximations::missing_glyphs(['\u{10fffe}']); approximations::layer(None); let notices = approximations::take(); @@ -12742,7 +13168,10 @@ mod tests { m.layer_mut(id).unwrap().transparency = transparency; m.layer_mut(id).unwrap().selection = if selected { vec![0] } else { vec![] }; let mut image = Pixmap::new(view.width as u32, view.height as u32).unwrap(); - crate::canvas::with_canvas(&mut image, |canvas| markers_tilted(&mut m, view, canvas, &Env::default())); + crate::canvas::with_canvas(&mut image, |canvas| { + let markers = upright_markers_with(&mut m, view, 0.0, &Env::default()); + markers_tilted(&m, &markers, view, canvas) + }); (image, m) } @@ -17737,3 +18166,6 @@ mod line_positions_tests; #[cfg(test)] mod polygon_labels_tests; + +#[cfg(test)] +mod obstacle_labels_tests; diff --git a/crates/render/src/line_positions_tests.rs b/crates/render/src/line_positions_tests.rs index a9df044b9b..50baf0b83d 100644 --- a/crates/render/src/line_positions_tests.rs +++ b/crates/render/src/line_positions_tests.rs @@ -14,6 +14,7 @@ fn curved(line: &[(f32, f32)]) -> Candidate { priority: 1.0, row: 0, remove_duplicates: None, + marks_point: false, key: (1, 0, 0, 0), alternatives: Vec::new(), line: Some(LinePlaces::default()), @@ -352,11 +353,11 @@ fn a_nearer_bands_unlayoutable_curve_does_not_claim_the_feature_key() { assert!(p.unplaced.is_empty(), "a successful later band replaces the failed preview"); // Every physical camera band remains available, with a hard bound on excess siblings. let max = rustgis_map::camera::MAX_TILT_BANDS; - let candidates = std::iter::repeat_n(bad.clone(), max - 1).chain(std::iter::once(good.clone())).collect(); + let candidates: Vec<_> = std::iter::repeat_n(bad.clone(), max - 1).chain(std::iter::once(good.clone())).collect(); let p = place_tilted_labels(&map, &view, candidates, None); assert_eq!(p.labels.len(), 1); label_places::LAYOUTS.with(|n| n.set(0)); - let candidates = std::iter::repeat_n(bad, 20_000).chain(std::iter::once(good)).collect(); + let candidates: Vec<_> = std::iter::repeat_n(bad, 20_000).chain(std::iter::once(good)).collect(); let p = place_tilted_labels(&map, &view, candidates, None); assert!(p.labels.is_empty()); assert_eq!(p.unplaced.len(), 1); @@ -541,8 +542,8 @@ fn hidden_unplaced_previews_do_not_change_placement() { let candidates: Vec<_> = (0..3000).map(|i| Candidate::from((PlacedLabel { y: 100.0, ..label("road", 100.0, None, 0.0) }, 1.0, (1, i, 0, 0)))).collect(); let blocker = PlacedLabel { y: 100.0, ..label("BLOCKER", 100.0, None, 0.0) }; - let shown = place_labels_with_previews(candidates.clone(), vec![blocker.clone()], 400.0, 200.0, false, true); - let hidden = place_labels_with_previews(candidates, vec![blocker], 400.0, 200.0, false, false); + let shown = place_labels_with_previews(candidates.clone(), vec![blocker.clone()], Vec::new(), 400.0, 200.0, false, true); + let hidden = place_labels_with_previews(candidates, vec![blocker], Vec::new(), 400.0, 200.0, false, false); assert_eq!(shown.unplaced.len(), 2000); assert!(hidden.unplaced.is_empty()); assert_eq!(shown.labels, hidden.labels); diff --git a/crates/render/src/obstacle_labels_tests.rs b/crates/render/src/obstacle_labels_tests.rs new file mode 100644 index 0000000000..2816baa1a4 --- /dev/null +++ b/crates/render/src/obstacle_labels_tests.rs @@ -0,0 +1,897 @@ +//! 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. + +use super::*; +use rustgis_data::{Dataset, Field, FieldType, Value}; +use rustgis_map::{Camera, LabelPlacement}; + +fn view() -> View { + let camera = Camera { center: lonlat_to_merc(Coord::new(0.0, 0.0)), res: 100.0, bearing: 0.0, pitch: 0.0 }; + View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera, sky: false } +} + +/// 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)) +} + +/// A point layer of the places `points`, each named or left without a name. +fn points(m: &mut Map, layer: &str, points: &[(Coord, Option<&str>)]) -> u32 { + let mut d = Dataset::new(layer, GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + for &(p, name) in points { + d.push(Some(Geometry::Point(p)), vec![name.map_or(Value::Null, |n| Value::Text(n.into()))]); + } + m.add_dataset(d) +} + +/// A map with one town, "Town", at the view's centre. +fn town() -> (Map, u32) { + let mut m = Map::new("Map"); + let id = points(&mut m, "towns", &[(Coord::new(0.0, 0.0), Some("Town"))]); + let l = m.layer_mut(id).unwrap(); + l.labels.enabled = true; + l.labels.default.field = "name".into(); + (m, id) +} + +/// A layer, its labels off, with one 16 point marker without an outline at `p` and the obstacle +/// weight `weight`. +fn obstacle(m: &mut Map, p: Coord, weight: u8) -> u32 { + let id = points(m, "hospitals", &[(p, None)]); + let l = m.layer_mut(id).unwrap(); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { size: 16.0, stroke_width: 0.0, ..l.symbol(0) }); + l.labels.enabled = false; + l.labels.obstacle_weight = weight; + id +} + +fn label_of(r: &Rendered) -> Option { + r.labels.iter().find(|l| l.text == "Town").cloned() +} + +fn placed(m: &mut Map, v: &View) -> Option<(f32, f32)> { + label_of(&render(m, v).unwrap()).map(|l| (l.x, l.y)) +} + +/// Where the town's label goes with nothing in its way. +fn free(m: &Map, v: &View) -> (f32, f32) { + placed(&mut m.clone(), v).unwrap() +} + +fn near(a: (f32, f32), b: (f32, f32)) -> bool { + (a.0 - b.0).hypot(a.1 - b.1) < 1.0 +} + +/// Whether the town's label, as `r` placed it, reaches the screen place `p`. +fn covers(r: &Rendered, p: (f32, f32)) -> bool { + label_of(r).is_some_and(|l| { + let face = text::Face { bold: false, italic: false, serif: false, family: None }; + let (hw, hh) = (text::spaced_block_width("Town", l.size, face, 0.0) / 2.0, text::block_height("Town", l.size) / 2.0); + (l.center_x() - p.0).abs() < hw && (l.y - p.1).abs() < hh + }) +} + +#[test] +fn a_layer_with_no_obstacle_weight_moves_nothing() { + let (mut m, _) = town(); + let v = view(); + let here = free(&m, &v); + obstacle(&mut m, at(&v, here), 0); + assert!(near(placed(&mut m, &v).unwrap(), here)); +} + +#[test] +fn a_label_no_heavier_than_the_obstacle_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); + obstacle(&mut m, at(&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_it_is_unplaced() { + let (mut m, _) = town(); + let v = view(); + let here = free(&m, &v); + obstacle(&mut m, at(&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_obstacle() { + let (mut m, id) = town(); + m.layer_mut(id).unwrap().labels.default.weight = 6; + let v = view(); + let here = free(&m, &v); + obstacle(&mut m, at(&v, here), 5); + assert!(near(placed(&mut m, &v).unwrap(), here)); +} + +#[test] +fn weight_ten_keeps_the_heaviest_label_off_but_not_one_moved_by_hand() { + let (mut m, id) = town(); + m.layer_mut(id).unwrap().labels.default.weight = 10; + let v = view(); + let here = free(&m, &v); + obstacle(&mut m, at(&v, here), 10); + assert_eq!(placed(&mut m, &v), None); + let to = at(&v, here); + let layer = m.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 m, &v).unwrap(), here), "moved by hand, where it was put"); +} + +#[test] +fn a_class_showing_all_labels_goes_over_the_obstacle() { + let (mut m, id) = town(); + m.layer_mut(id).unwrap().labels.default.show_all = true; + let v = view(); + let here = free(&m, &v); + obstacle(&mut m, at(&v, here), 10); + assert!(near(placed(&mut m, &v).unwrap(), here)); +} + +#[test] +fn a_label_never_keeps_off_its_own_point() { + let (mut m, id) = town(); + let l = m.layer_mut(id).unwrap(); + l.labels.default.placement = LabelPlacement::Center; + l.labels.obstacle_weight = 10; + assert!(placed(&mut m, &view()).is_some()); +} + +#[test] +fn another_point_of_its_own_layer_is_an_obstacle() { + let v = view(); + let (m, _) = town(); + let here = free(&m, &v); + // The town, and a point with no name where its name would go. + let mut m = Map::new("Map"); + let id = points(&mut m, "towns", &[(Coord::new(0.0, 0.0), Some("Town")), (at(&v, here), None)]); + 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 points_not_drawn_are_no_obstacle() { + let v = view(); + let (base, _) = town(); + let here = free(&base, &v); + let hide: [(&str, fn(&mut rustgis_map::Layer)); 3] = [ + ("hidden", |l| l.visible = false), + ("out of its scale range", |l| l.min_scale = Some(1.0)), + ("left out by its query", |l| l.definition_query = Some("name = 'none'".into())), + ]; + for (case, set) in hide { + let mut m = base.clone(); + let id = obstacle(&mut m, at(&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_locked_label_stays_where_it_was_locked() { + let (mut m, _) = town(); + let v = view(); + let here = free(&m, &v); + let id = obstacle(&mut m, at(&v, here), 0); + m.label_display.locked = true; + assert!(near(placed(&mut m, &v).unwrap(), here)); + m.layer_mut(id).unwrap().labels.obstacle_weight = 10; + assert!(near(placed(&mut m, &v).unwrap(), here)); +} + +#[test] +fn a_callouts_free_spot_is_off_the_obstacles() { + let (mut m, id) = town(); + m.layer_mut(id).unwrap().labels.default.callout = Some(60.0); + let v = view(); + let here = free(&m, &v); + obstacle(&mut m, at(&v, here), 5); + let r = render(&mut m, &v).unwrap(); + assert!(label_of(&r).is_some_and(|l| l.collide.callout.is_some()), "{:?}", label_of(&r)); + assert!(!covers(&r, here)); +} + +#[test] +fn turned_tilted_and_globe_views_keep_off_too() { + for (bearing, pitch, globe) in [(90.0, 0.0, false), (0.0, 30.0, false), (30.0, 30.0, false), (0.0, 0.0, true)] { + let (mut m, _) = town(); + if globe { + m.projection = rustgis_map::Projection::Globe; + } + let mut v = view(); + (v.camera.bearing, v.camera.pitch) = (bearing, pitch); + let here = free(&m, &v); + obstacle(&mut m, at(&v, here), 5); + let r = render(&mut m, &v).unwrap(); + assert!(label_of(&r).is_none(), "turned {bearing}, tilted {pitch}, globe {globe}: {:?}", label_of(&r)); + } +} + +/// A frame drawn from a kept picture, or with a layer's kept labels, keeps off as one drawn +/// whole does. +#[test] +fn a_frame_drawn_from_a_kept_one_keeps_off_too() { + let v = view(); + let (mut m, towns) = town(); + let here = free(&m, &v); + let hospitals = obstacle(&mut m, at(&v, here), 5); + m.layers.swap(0, 1); + for (i, id) in [towns, towns, towns, towns, hospitals, 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_tile_label_keeps_off_the_obstacle() { + let text = PlacedLabel { x: 100.0, y: 100.0, text: "Road".into(), ..tests::label("Road", 100.0, None, 0.0) }; + let point = Obstacle { owner: (1, 1), x: 100.0, y: 100.0, r: 8.0, weight: 1 }; + let place = |obstacles: Vec| { + place_labels_with_previews([tile_candidate(text.clone(), 0.0, 0)], Vec::new(), obstacles, 400.0, 300.0, false, true).labels.len() + }; + assert_eq!(place(Vec::new()), 1); + assert_eq!(place(vec![point]), 0); +} + +#[test] +fn many_obstacles_are_placed_quickly() { + let cands: Vec = (0..20_000) + .map(|i| { + let (x, y) = ((i % 200) as f32 * 10.0, (i / 200) as f32 * 10.0); + let l = PlacedLabel { x, y, ..tests::label("ab", x, None, 0.0) }; + let alternatives = [(-6.0, -6.0), (6.0, -6.0), (-6.0, 6.0), (6.0, 6.0), (-8.0, 0.0), (8.0, 0.0), (0.0, 8.0)] + .map(|(dx, dy)| LabelPlace::from((x + dx, y + dy))) + .to_vec(); + Candidate { alternatives, ..(l, -f64::from(i), (1, i as u64, 0, 0)).into() } + }) + .collect(); + let obstacles: Vec = (0..200_000) + .map(|i| Obstacle { owner: (2, i), x: (i % 500) as f32 * 4.0, y: (i / 500) as f32 * 2.5, r: 2.0, weight: (i % 10) as u8 + 1 }) + .collect(); + let start = web_time::Instant::now(); + place_labels_with_previews(cands, Vec::new(), obstacles, 2000.0, 1000.0, false, true); + assert!(start.elapsed() < web_time::Duration::from_secs(5), "{:?}", start.elapsed()); +} + +/// What a band `band` of the tilted view `shown` hands back to place its labels by. +fn gathered(m: &mut Map, band: &View, shown: View) -> Gathered { + let mut out = Gathered::default(); + render_frame(m, band, false, Backend::Cpu, Labels::Tilted(&shown, &mut out), false, &mut None, &Env::default()).unwrap(); + // The markers standing up are the view's own, as a tilted view hands them over. + let markers = upright_markers_with(m, &shown, 0.0, &Env::default()); + out.raised = upright_obstacles(m, &shown, &markers, out.obstacles.len()); + out +} + +/// The view tilted 30 degrees. +fn tilted() -> View { + let mut v = view(); + v.camera.pitch = 30.0; + v +} + +/// Every obstacle of a tilted view: those of its bands and those of its markers standing up. +fn held(g: &Gathered) -> Vec { + g.obstacles.iter().chain(&g.raised).copied().collect() +} + +/// In a tilted view an obstacle reaches as far as its marker does on the screen: one standing up +/// is drawn at the view's size, smaller further away; one on the ground as large as its band is +/// shown. Held to a reference scale or not. +#[test] +fn a_tilted_views_obstacles_reach_as_far_as_their_markers() { + let mut shown = view(); + shown.camera.pitch = 45.0; + // A flat band at half the sharpness: each of its points is two of the view's at the centre. + let mut band = view(); + band.camera.res = 200.0; + let scale = Map::new("Map").ground_res_at(&shown.camera) / rustgis_geom::PIXEL_M; + // Far from the centre, where upright markers shrink; and at it. + let far = shown.camera.to_map(400.0, 100.0, shown.width, shown.height); + let k = shown.camera.depth_scale(far, shown.height).unwrap(); + assert!(k < 0.9, "{k}"); + for reference in [None, Some(scale)] { + let mut m = Map::new("Map"); + let id = obstacle(&mut m, rustgis_geom::merc_to_lonlat(far), 5); + m.layer_mut(id).unwrap().reference_scale = reference; + let r = held(&gathered(&mut m, &band, shown))[0].r; + assert!((r - 9.6 * k as f32).abs() < 0.5, "upright, {reference:?}: {r}, k {k}"); + // Blended, its markers lie on the ground, drawn on the band. + let mut m = Map::new("Map"); + let id = obstacle(&mut m, Coord::new(0.0, 0.0), 5); + let l = m.layer_mut(id).unwrap(); + (l.reference_scale, l.blend) = (reference, rustgis_map::effects::Blend::Multiply); + let r = held(&gathered(&mut m, &band, shown))[0].r; + // Its band's marker, held to the reference scale, is half the size. + let on_band = if reference.is_some() { 4.8 } else { 9.6 }; + let o = shown.camera.to_screen(Coord::new(0.0, 0.0), shown.width, shown.height); + let e = shown.camera.to_screen(band.camera.to_map(400.0 + on_band, 300.0, band.width, band.height), shown.width, shown.height); + let expected = (e.0 - o.0).hypot(e.1 - o.1) as f32; + assert!((r - expected).abs() < 0.5, "ground, {reference:?}: {r}, expected {expected}"); + } +} + +/// Only the points near enough the frame to reach a label are gathered, so a layer costs what is +/// in view. +#[test] +fn points_far_off_the_view_are_not_gathered() { + let mut m = Map::new("Map"); + let id = points(&mut m, "hospitals", &[(Coord::new(0.0, 0.0), None), (Coord::new(20.0, 0.0), None)]); + m.layer_mut(id).unwrap().labels.obstacle_weight = 5; + let mut shown = view(); + shown.camera.pitch = 30.0; + assert_eq!(held(&gathered(&mut m, &view(), shown)).len(), 1); +} + +/// A marker sized under a point is drawn at one point, and takes that room. +#[test] +fn a_marker_of_no_size_reaches_as_far_as_it_is_drawn() { + let mut m = Map::new("Map"); + let id = obstacle(&mut m, Coord::new(0.0, 0.0), 5); + let l = m.layer_mut(id).unwrap(); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { size: 0.0, ..l.symbol(0) }); + let r = held(&gathered(&mut m, &view(), tilted()))[0].r; + assert!((r - 0.6).abs() < 0.01, "{r}"); +} + +/// Points in one point of the screen are one obstacle, so what a frame holds follows its size, +/// not the layer's rows. With more than one feature there, none goes over it; the points of one +/// feature stay its own. +#[test] +fn points_in_one_point_of_the_screen_are_one_obstacle() { + let v = view(); + let at_screen = |x: f32, y: f32| at(&v, (x, y)); + let crowd: Vec<_> = (0..1000).map(|i| (at_screen(400.0 + (i % 10) as f32 * 0.02, 300.0), None)).collect(); + let mut m = Map::new("Map"); + let id = points(&mut m, "hospitals", &[crowd, vec![(at_screen(410.0, 300.0), None)]].concat()); + m.layer_mut(id).unwrap().labels.obstacle_weight = 5; + let held = held(&gathered(&mut m, &v, v)); + assert_eq!(held.len(), 2, "{held:?}"); + + // Two features in one place, labelled on their points: it is the point each marks. + let mut m = Map::new("Map"); + let here = Coord::new(0.0, 0.0); + let id = points(&mut m, "towns", &[(here, Some("Town")), (here, None)]); + let l = m.layer_mut(id).unwrap(); + l.labels.enabled = true; + l.labels.default.field = "name".into(); + l.labels.default.placement = LabelPlacement::Center; + l.labels.obstacle_weight = 5; + assert!(placed(&mut m, &v).is_some()); + + // One feature of two points in one place: still its own. + let mut m = Map::new("Map"); + let mut d = Dataset::new("towns", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + d.push(Some(Geometry::MultiPoint(vec![here, here])), vec![Value::Text("Town".into())]); + let id = m.add_dataset(d); + let l = m.layer_mut(id).unwrap(); + l.labels.enabled = true; + l.labels.default.field = "name".into(); + l.labels.default.placement = LabelPlacement::Center; + l.labels.obstacle_weight = 5; + assert!(placed(&mut m, &v).is_some()); +} + +/// A point that draws nothing is in no label's way: a symbol with nothing visible, or a layer +/// wholly transparent, in a frame drawn whole or from a kept one. +#[test] +fn points_that_draw_nothing_are_no_obstacle() { + let v = view(); + let (base, towns) = town(); + let here = free(&base, &v); + let mut m = base.clone(); + let id = obstacle(&mut m, at(&v, here), 10); + let l = m.layer_mut(id).unwrap(); + let none = Rgba::new(0, 0, 0, 0); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { fill: none, stroke: none, ..l.symbol(0) }); + assert!(placed(&mut m, &v).is_some_and(|p| near(p, here)), "nothing visible"); + let mut m = base; + let hospitals = obstacle(&mut m, at(&v, here), 10); + m.layers.swap(0, 1); + for (i, t) in [0.0, 0.0, 100.0, 100.0, 0.0].into_iter().enumerate() { + m.layer_mut(hospitals).unwrap().transparency = t; + let l = m.layer_mut(towns).unwrap(); + let size = 8.0 + (i % 2) as f32; + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { size, ..l.symbol(0) }); + assert_eq!(placed(&mut m, &v).is_some(), t == 100.0, "frame {i}, transparency {t}"); + } +} + +/// A marker's outline is part of how far it reaches. +#[test] +fn a_markers_outline_reaches_as_far_as_it_is_drawn() { + let mut m = Map::new("Map"); + let id = obstacle(&mut m, Coord::new(0.0, 0.0), 5); + let l = m.layer_mut(id).unwrap(); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { size: 2.0, stroke_width: 20.0, ..l.symbol(0) }); + let r = held(&gathered(&mut m, &view(), tilted()))[0].r; + assert!((r - 11.2).abs() < 0.01, "{r}"); +} + +/// A label never keeps off an obstacle where the point it marks is, whichever layer holds it: +/// an annotation on its source's point, a layer added twice. A polygon's label marks no point, +/// so one at its label point is in its way. +#[test] +fn a_label_goes_over_the_point_it_marks_in_any_layer() { + let v = view(); + let (mut m, id) = town(); + m.layer_mut(id).unwrap().labels.default.placement = LabelPlacement::Center; + let mut off = m.clone(); + obstacle(&mut m, Coord::new(0.0, 0.0), 10); + assert!(placed(&mut m, &v).is_some()); + // Off its point, it is in the way. + obstacle(&mut off, at(&v, (404.0, 300.0)), 10); + assert!(placed(&mut off, &v).is_none()); + let mut m = Map::new("Map"); + let h = 0.1; + let ring = [(-h, -h), (h, -h), (h, h), (-h, h), (-h, -h)].map(|(x, y)| Coord::new(x, y)).to_vec(); + let mut d = Dataset::new("areas", GeometryType::Polygon, vec![Field::new("name", FieldType::Text)]); + d.push(Some(Geometry::Polygon(vec![vec![ring]])), vec![Value::Text("Town".into())]); + let id = m.add_dataset(d); + let l = m.layer_mut(id).unwrap(); + l.labels.enabled = true; + l.labels.default.field = "name".into(); + assert!(placed(&mut m, &v).is_some()); + obstacle(&mut m, Coord::new(0.0, 0.0), 10); + assert!(placed(&mut m, &v).is_none()); +} + +/// An obstacle on the ground reaches as far as its band's marker does there: from its east point, +/// else its west, else as large as its band, never dropped for one point that doesn't project. +#[test] +fn a_ground_obstacles_reach_does_not_depend_on_one_point_showing() { + let near_the_edge = |x: f32, y: f32| (x < 100.0).then_some((2.0 * x, 2.0 * y)); + assert_eq!(shown_reach(&near_the_edge, (50.0, 50.0), 5.0), 10.0, "east shows"); + // The east point past the edge: the west one measures it. + assert_eq!(shown_reach(&near_the_edge, (98.0, 50.0), 5.0), 10.0); + let nowhere_else = |x: f32, y: f32| ((x - 98.0).abs() < 1e-3).then_some((x, y)); + assert_eq!(shown_reach(&nowhere_else, (98.0, 50.0), 5.0), 5.0, "else its band's size"); +} + +/// With no obstacle the placement makes no grid for them. +#[test] +fn no_obstacles_make_no_grid() { + assert!(Obstacles::new(Vec::new(), 400.0, 300.0).grid.is_none()); + let far = Obstacle { owner: (1, 1), x: 1e9, y: 0.0, r: 2.0, weight: 5 }; + assert!(Obstacles::new(vec![far], 400.0, 300.0).grid.is_none(), "none kept"); +} + +/// A tilted view's standing-up obstacles are the markers it draws: a layer out of scale range at +/// the view's centre draws none there, however far bands with another scale gather it. +#[test] +fn a_tilted_views_upright_obstacles_follow_the_markers_drawn() { + let mut shown = view(); + shown.camera.pitch = 60.0; + let far = shown.camera.to_map(400.0, 150.0, shown.width, shown.height); + let mut m = Map::new("Map"); + let id = points(&mut m, "towns", &[(rustgis_geom::merc_to_lonlat(far), Some("Town"))]); + let l = m.layer_mut(id).unwrap(); + l.labels.enabled = true; + l.labels.default.field = "name".into(); + let here = placed(&mut m, &shown).expect("a town in the far part of the view"); + let centre = m.ground_res_at(&shown.camera) / rustgis_geom::PIXEL_M; + let hospitals = obstacle( + &mut m, + rustgis_geom::merc_to_lonlat(shown.camera.to_map(f64::from(here.0), f64::from(here.1), shown.width, shown.height)), + 10, + ); + assert!(placed(&mut m, &shown).is_none(), "in range everywhere, its marker is in the way"); + // Out of range at the centre, in range at the far bands: no marker is drawn, none is in the way. + m.layer_mut(hospitals).unwrap().max_scale = Some(centre * 1.2); + assert!(placed(&mut m, &shown).is_some_and(|p| near(p, here))); +} + +/// A picture marker that doesn't draw falls back to a circle, and is an obstacle as that circle: +/// as far as it reaches with its outline, and none with nothing visible. +#[test] +fn a_picture_marker_drawn_as_a_circle_is_an_obstacle_as_the_circle() { + let reach_of = |fill: Rgba, stroke: Rgba, size: f32, stroke_width: f32| { + let mut m = Map::new("Map"); + let id = obstacle(&mut m, Coord::new(0.0, 0.0), 5); + let l = m.layer_mut(id).unwrap(); + let marker = Marker::Picture(rustgis_map::Picture::default()); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { fill, stroke, size, stroke_width, marker }); + held(&gathered(&mut m, &view(), tilted())).first().map(|o| o.r) + }; + let (none, red) = (Rgba::new(0, 0, 0, 0), Rgba::new(200, 0, 0, 255)); + assert_eq!(reach_of(none, none, 8.0, 1.0), None, "nothing visible"); + let r = reach_of(red, red, 2.0, 20.0).unwrap(); + assert!((r - 11.2).abs() < 0.01, "{r}"); +} + +/// A Show All label stays over an obstacle: no callout search starts for a crowd of obstacles +/// alone, though it still does for one of labels. +#[test] +fn a_show_all_label_with_callouts_stays_over_an_obstacle() { + let v = view(); + let (mut m, id) = town(); + let l = m.layer_mut(id).unwrap(); + (l.labels.default.show_all, l.labels.default.callout) = (true, Some(60.0)); + let here = free(&m, &v); + obstacle(&mut m, at(&v, here), 10); + let r = render(&mut m, &v).unwrap(); + let label = label_of(&r).expect("shown"); + assert!(near((label.x, label.y), here) && label.collide.callout.is_none(), "{label:?}"); +} + +/// On the ground of a tilted view a marker reaches farther up and down the screen than across +/// it: the larger reach is the obstacle's. +#[test] +fn a_ground_obstacles_reach_takes_the_larger_way() { + let taller = |x: f32, y: f32| Some((2.0 * x, 3.0 * y)); + assert_eq!(shown_reach(&taller, (50.0, 50.0), 5.0), 15.0); + let wider = |x: f32, y: f32| Some((3.0 * x, 2.0 * y)); + assert_eq!(shown_reach(&wider, (50.0, 50.0), 5.0), 15.0); +} + +/// What a frame holds of an obstacle layer follows the frame, whatever its markers' size: points +/// in one point of the screen are one obstacle, and a marker counts as no more than +/// [`MAX_OBSTACLE_REACH`] from its centre, so it spans few cells of the placement grid. +#[test] +fn big_markers_keep_the_obstacles_and_their_grid_small() { + let mut merged = Vec::new(); + let mut cells = ObstacleMerge::default(); + // 200,000 points over a 2000 × 1500 frame, each of a marker 2,000 points across. + for i in 0..200_000u64 { + let (x, y) = ((i * 7919 % 2000) as f32, (i * 104_729 % 1500) as f32); + cells.add(&mut merged, Obstacle { owner: (1, i), x, y, r: 1000.0, weight: 5 }, usize::MAX); + } + assert!(merged.iter().all(|o| o.r <= MAX_OBSTACLE_REACH + 1.0), "no marker counts beyond its limit, merged ones apart"); + let obstacles = Obstacles::new(merged, 2000.0, 1500.0); + // A box 64 points across spans at most 3 × 3 of the grid's cells of 32 points or more. + assert!(obstacles.references() <= 200_000 * 9, "{}", obstacles.references()); +} + +/// Two points in one point of the screen merge into one obstacle covering both, and each +/// feature's label still goes over its own point; a point 3 points off is another obstacle, so +/// one label's point is never what lets it over another's. +#[test] +fn merged_points_keep_each_features_exemption() { + let v = view(); + // Two towns in one point of the screen, both labelled on their points, with an obstacle + // weight that would keep them off each other: they are one obstacle at the point's centre. + let (a, b) = (at(&v, (400.0, 300.0)), at(&v, (400.3, 300.2))); + let mut m = Map::new("Map"); + let id = points(&mut m, "towns", &[(a, Some("Town")), (b, Some("Other"))]); + let l = m.layer_mut(id).unwrap(); + l.labels.enabled = true; + l.labels.default.field = "name".into(); + l.labels.default.placement = LabelPlacement::Center; + l.labels.obstacle_weight = 5; + let labels = render(&mut m, &v).unwrap().labels; + assert!(labels.iter().any(|l| l.text == "Town") || labels.iter().any(|l| l.text == "Other"), "{labels:?}"); + // A neighbour 3 points away is in the way of the label over the point beside it. + let mut m = Map::new("Map"); + let id = points(&mut m, "towns", &[(a, Some("Town")), (at(&v, (403.0, 300.0)), None)]); + let l = m.layer_mut(id).unwrap(); + l.labels.enabled = true; + l.labels.default.field = "name".into(); + l.labels.default.placement = LabelPlacement::Center; + l.labels.obstacle_weight = 5; + assert_eq!(placed(&mut m, &v), None); +} + +/// The merged obstacle covers each point it took. +#[test] +fn a_merged_obstacle_still_covers_each_of_its_points() { + let mut merged = Vec::new(); + let mut cells = ObstacleMerge::default(); + let points = [(100.0, 100.0), (100.4, 100.4)]; + for (i, (x, y)) in points.into_iter().enumerate() { + cells.add(&mut merged, Obstacle { owner: (1, i as u64), x, y, r: 6.0, weight: 5 }, usize::MAX); + } + assert_eq!(merged.len(), 1); + let o = merged[0]; + assert_eq!(o.owner, (1, NO_OWNER), "of more than one feature, none's own"); + for (x, y) in points { + assert!((o.x - x).hypot(o.y - y) + 6.0 <= o.r + 1e-3, "{o:?} covers ({x}, {y})"); + } +} + +/// A plain marker the drawing doesn't reach, centred past its cull, is no obstacle. +#[test] +fn a_plain_marker_the_drawing_culls_is_no_obstacle() { + let v = view(); + let mut m = Map::new("Map"); + let id = points(&mut m, "towns", &[(at(&v, (0.0, 300.0)), Some("Town"))]); + let l = m.layer_mut(id).unwrap(); + l.labels.enabled = true; + l.labels.default.field = "name".into(); + l.labels.default.placement = LabelPlacement::Center; + // A marker 60 points across centred 42 past the left edge: its disc reaches x = -10, but the + // map draws nothing centred past 5% of the view's width. + let id = obstacle(&mut m, at(&v, (-42.0, 300.0)), 10); + let l = m.layer_mut(id).unwrap(); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { size: 60.0, ..l.symbol(0) }); + assert!(placed(&mut m, &v).is_some()); +} + +/// A marker that draws nothing, a space, is no obstacle. +#[test] +fn a_blank_character_marker_is_no_obstacle() { + let mut m = Map::new("Map"); + let id = obstacle(&mut m, Coord::new(0.0, 0.0), 5); + let l = m.layer_mut(id).unwrap(); + let marker = Marker::Char(rustgis_map::symbology::Glyph::new(' ', "")); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { marker, ..l.symbol(0) }); + assert!(held(&gathered(&mut m, &view(), tilted())).is_empty()); +} + +/// An image marker of a wholly transparent layer standing up in a tilted view is no obstacle, +/// where one with some opacity is. +#[test] +fn a_transparent_images_upright_obstacle_is_none() { + use base64::Engine; + let mut red = tiny_skia::Pixmap::new(4, 4).unwrap(); + red.fill(tiny_skia::Color::from_rgba8(255, 0, 0, 255)); + let png = base64::engine::general_purpose::STANDARD.encode(red.encode_png().unwrap()); + let on = |transparency: f32| { + let mut m = Map::new("Map"); + let id = obstacle(&mut m, Coord::new(0.0, 0.0), 5); + let l = m.layer_mut(id).unwrap(); + let marker = Marker::Picture(rustgis_map::Picture::new(&png)); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { marker, size: 12.0, ..l.symbol(0) }); + l.transparency = transparency; + held(&gathered(&mut m, &view(), tilted())).len() + }; + assert_eq!((on(0.0), on(100.0)), (1, 0)); +} + +/// An image too wide to draw (100,000 pixels across or more) is the circle `draw_marker` falls +/// back to, an obstacle as that circle is. +#[test] +fn an_image_too_wide_to_draw_is_the_circle_it_falls_back_to() { + use base64::Engine; + let mut red = tiny_skia::Pixmap::new(4, 4).unwrap(); + red.fill(tiny_skia::Color::from_rgba8(255, 0, 0, 255)); + let png = base64::engine::general_purpose::STANDARD.encode(red.encode_png().unwrap()); + let reach_of = |size: f32| { + let mut m = Map::new("Map"); + let id = obstacle(&mut m, Coord::new(0.0, 0.0), 5); + let l = m.layer_mut(id).unwrap(); + let none = Rgba::new(0, 0, 0, 0); + let marker = Marker::Picture(rustgis_map::Picture::new(&png)); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { fill: none, stroke: none, size, stroke_width: 0.0, marker }); + held(&gathered(&mut m, &view(), tilted())).first().map(|o| o.r) + }; + assert!(reach_of(12.0).is_some(), "an image that draws is in the way"); + assert_eq!(reach_of(150_000.0), None, "too wide to draw, a circle with nothing visible"); +} + +/// A frame holds only the obstacles memory allows: the points of a layer past the limit are left +/// out of it, said once, and a point in a cell it holds still merges into it. +#[test] +fn obstacles_past_the_limit_are_left_out_and_said() { + let mut merge = ObstacleMerge::default(); + let mut list = Vec::new(); + let o = |x: f32| Obstacle { owner: (1, x as u64), x, y: 0.0, r: 3.0, weight: 5 }; + assert!(merge.add(&mut list, o(10.0), 2)); + assert!(merge.add(&mut list, o(20.0), 2)); + assert!(!merge.add(&mut list, o(30.0), 2), "a third cell is past the limit"); + assert!(merge.add(&mut list, o(10.2), 2), "a point of a cell it holds merges"); + assert_eq!(list.len(), 2); + + let v = view(); + let mut m = Map::new("Map"); + let places: Vec<_> = (0..10).map(|i| (at(&v, (100.0 + 40.0 * i as f32, 300.0)), None)).collect(); + let id = points(&mut m, "hospitals", &places); + let l = m.layer_mut(id).unwrap(); + // Blended, its markers lie on the ground: its obstacles are gathered by the bands. + (l.labels.obstacle_weight, l.blend) = (5, rustgis_map::effects::Blend::Multiply); + OBSTACLE_LIMIT.with(|l| l.set(Some(3))); + approximations::take(); + let made = held(&gathered(&mut m, &v, tilted())).len(); + 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:?}"); +} + +/// A layer's points far from the view aren't projected: its rows are skipped by their extent, +/// as the drawing skips them. +#[test] +fn rows_far_from_the_view_are_skipped_before_they_are_projected() { + let v = view(); + let mut m = Map::new("Map"); + let mut places = vec![(at(&v, (400.0, 300.0)), None)]; + places.extend((0..500).map(|i| (Coord::new(40.0 + f64::from(i) * 0.01, 40.0), None))); + let id = points(&mut m, "hospitals", &places); + m.layer_mut(id).unwrap().labels.obstacle_weight = 5; + OBSTACLE_ROWS.with(|c| c.set(0)); + render(&mut m, &v).unwrap(); + assert_eq!(OBSTACLE_ROWS.with(std::cell::Cell::get), 1); +} + +/// In a GPU frame, a layer the GPU doesn't draw (a blended one) is drawn on the CPU, so its plain +/// markers count where the CPU's cull has their point, not the wider one of the GPU's meshes. +#[test] +fn a_gpu_frames_cpu_layer_is_culled_as_the_cpu_does() { + let v = view(); + let mut m = Map::new("Map"); + let id = points(&mut m, "towns", &[(at(&v, (0.0, 300.0)), Some("Town"))]); + let l = m.layer_mut(id).unwrap(); + l.labels.enabled = true; + l.labels.default.field = "name".into(); + l.labels.default.placement = LabelPlacement::Center; + let id = obstacle(&mut m, at(&v, (-42.0, 300.0)), 10); + let l = m.layer_mut(id).unwrap(); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { size: 60.0, ..l.symbol(0) }); + l.blend = rustgis_map::effects::Blend::Multiply; + let Some(RenderOutput::Gpu(scene)) = render_backend(&mut m, &v, Backend::Gpu) else { panic!("a gpu scene") }; + assert!(scene.labels.iter().any(|l| l.text == "Town"), "{:?}", scene.labels); +} + +/// The points of a graphics layer (its text and images) are no obstacle, as the guide says. +#[test] +fn a_graphics_layers_points_are_no_obstacle() { + let v = view(); + let (mut m, _) = town(); + let here = free(&m, &v); + let id = obstacle(&mut m, at(&v, here), 10); + assert_eq!(placed(&mut m.clone(), &v), None, "an ordinary layer's point is in the way"); + m.layer_mut(id).unwrap().graphics = true; + assert!(placed(&mut m, &v).is_some_and(|p| near(p, here))); +} + +/// A frame with few obstacles doesn't ask the system for the memory left: a tilted view makes a +/// frame for each of its bands. +#[test] +fn a_frame_with_few_obstacles_asks_nothing_of_the_system() { + let v = view(); + let (mut m, _) = town(); + let here = free(&m, &v); + obstacle(&mut m, at(&v, here), 5); + OBSTACLE_ASKED.with(|c| c.set(0)); + render(&mut m, &v).unwrap(); + assert_eq!(OBSTACLE_ASKED.with(std::cell::Cell::get), 0); +} + +/// The bands of a tilted view share one list of obstacles: bands that overlap, a point within the +/// margin of two of them, make it once, and what the frame may hold is for all of them. +#[test] +fn a_tilted_views_bands_share_their_obstacles_and_their_limit() { + let v = view(); + let mut shown = view(); + shown.camera.pitch = 30.0; + let mut m = Map::new("Map"); + let places: Vec<_> = (0..10).map(|i| (at(&v, (100.0 + 40.0 * i as f32, 300.0)), None)).collect(); + let id = points(&mut m, "hospitals", &places); + let l = m.layer_mut(id).unwrap(); + // Blended, its markers lie on the ground: its obstacles come from the bands. + (l.labels.obstacle_weight, l.blend) = (5, rustgis_map::effects::Blend::Multiply); + let two_bands = |m: &mut Map| { + let mut out = Gathered::default(); + for _ in 0..2 { + render_frame(m, &v, false, Backend::Cpu, Labels::Tilted(&shown, &mut out), false, &mut None, &Env::default()).unwrap(); + } + out.obstacles.len() + }; + let one = { + let mut out = Gathered::default(); + render_frame(&mut m, &v, false, Backend::Cpu, Labels::Tilted(&shown, &mut out), false, &mut None, &Env::default()).unwrap(); + out.obstacles.len() + }; + assert!(one >= 5, "{one}"); + assert_eq!(two_bands(&mut m), one, "the same points in two bands are made once"); + OBSTACLE_LIMIT.with(|l| l.set(Some(4))); + let limited = two_bands(&mut m); + OBSTACLE_LIMIT.with(|l| l.set(None)); + assert!(limited <= 4, "{limited}"); +} + +/// A ground marker shown near the camera counts as no more than the limit, as on the flat map. +#[test] +fn a_ground_obstacle_shown_larger_counts_no_more_than_the_limit() { + let mut shown = view(); + shown.camera.pitch = 45.0; + let low = shown.camera.to_map(400.0, 500.0, shown.width, shown.height); + let mut m = Map::new("Map"); + let id = obstacle(&mut m, rustgis_geom::merc_to_lonlat(low), 5); + let l = m.layer_mut(id).unwrap(); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { size: 50.0, ..l.symbol(0) }); + l.blend = rustgis_map::effects::Blend::Multiply; + let all = held(&gathered(&mut m, &view(), shown)); + assert_eq!(all.len(), 1, "{all:?}"); + assert!(all[0].r <= MAX_OBSTACLE_REACH + 0.01, "{}", all[0].r); +} + +/// A streamed point layer with an obstacle weight and its labels off still reads only the features +/// near the view: its markers count only where the drawing's cull has their point, which the read +/// holds. +#[test] +fn an_obstacle_only_point_layer_still_reads_its_view_only() { + let mut m = Map::new("Map"); + let id = obstacle(&mut m, Coord::new(0.0, 0.0), 5); + let layer = m.layer(id).unwrap(); + assert!(draws_in_view_only(layer, true, false)); + // With its labels on, labels reach in from beyond the view: all of it. + let mut labelled = layer.clone(); + labelled.labels.enabled = true; + assert!(!draws_in_view_only(&labelled, true, false)); +} + +/// Bands that each fit the limit but not together leave points out at the sink they share, and +/// say so, as a flat frame does. +#[test] +fn bands_that_pass_the_limit_together_say_what_they_left_out() { + let v = view(); + let mut shown = view(); + shown.camera.pitch = 30.0; + let layer = |name: &str, y: f32| { + let mut m = Map::new("Map"); + let places: Vec<_> = (0..10).map(|i| (at(&v, (100.0 + 40.0 * i as f32, y)), None)).collect(); + let id = points(&mut m, name, &places); + let l = m.layer_mut(id).unwrap(); + (l.labels.obstacle_weight, l.blend) = (5, rustgis_map::effects::Blend::Multiply); + m + }; + let (mut a, mut b) = (layer("hospitals", 300.0), layer("clinics", 400.0)); + let mut out = Gathered::default(); + let band = |m: &mut Map, out: &mut Gathered| { + render_frame(m, &v, false, Backend::Cpu, Labels::Tilted(&shown, out), false, &mut None, &Env::default()).unwrap(); + out.obstacles.len() + }; + let one = band(&mut a, &mut out); + assert!(one >= 5, "{one}"); + OBSTACLE_LIMIT.with(|l| l.set(Some(one + 2))); + approximations::take(); + band(&mut b, &mut 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); + assert!(said.iter().any(|t| t.starts_with(&lost)), "{lost}: {said:?}"); +} + +/// What a layer's chunks, or a tilted view's bands, each leave out is said as one total. +#[test] +fn what_is_left_out_is_said_as_one_total() { + approximations::take(); + approximations::obstacles_left_out("hospitals", 3); + 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!(approximations::take().is_empty(), "said once, then forgotten"); +} + +/// The markers standing up in a tilted view are held to the frame's limit as the ground ones are, +/// and say what they leave out; none while labels are paused. +#[test] +fn standing_markers_share_the_frames_limit_and_are_none_when_paused() { + let shown = tilted(); + let v = view(); + let mut m = Map::new("Map"); + let places: Vec<_> = (0..10).map(|i| (at(&v, (100.0 + 40.0 * i as f32, 300.0)), None)).collect(); + let id = points(&mut m, "hospitals", &places); + m.layer_mut(id).unwrap().labels.obstacle_weight = 5; + let markers = upright_markers_with(&mut m, &shown, 0.0, &Env::default()); + let all = upright_obstacles(&m, &shown, &markers, 0); + assert!(all.len() >= 5, "{}", all.len()); + OBSTACLE_LIMIT.with(|l| l.set(Some(all.len() + 2))); + approximations::take(); + let rest = upright_obstacles(&m, &shown, &markers, all.len()); + 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:?}"); + m.label_display.paused = true; + assert!(upright_obstacles(&m, &shown, &markers, 0).is_empty()); +} diff --git a/docs/maintaining.md b/docs/maintaining.md index 2690209f5d..b6e7d0f88b 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -211,6 +211,11 @@ 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 +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, +or run the step without it. + A label class removing duplicates (`labels.placement` with a `removeDuplicates` distance) requires `label-duplicates`, in a layer, a saved style or a saved `labels.placement` step: an older reader would place and save every label, or run the step without it. diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index efe41b9680..b240982a83 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -693,6 +693,23 @@ 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**: 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 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 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 + 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 + 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, set by command + (`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). - **Clearance** (Labeling pane › Position): the room, in points, a class's labels keep free of other labels (0 to 100, 2 to start with, the room every label kept before). Two labels keep both their clearances apart: a river's name with 10 keeps a town's with 2 at least 12 points @@ -734,12 +751,11 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: moves and old label locks because replacement data can reuse feature ids, with a counted notice and undo restoration. Opening a project, importing a map or styles, or adding a layer file reports invalid, duplicate or excess moved-label entries that were ignored, callout lengths that - were adjusted, label weights that were not a whole number from 0 to 10, label clearances that - were not a number from 0 to 100 points, label duplicate distances that were not a number from 1 - to 2000 points, and Show all labels settings that were not true or - false. A callout length given - to `labels.placement` outside 5 to 500 points is brought within range with a notice. Clean - settings give no such notice. + were adjusted, label weights and obstacle weights that were not a whole number from 0 to 10, + label clearances that were not a number from 0 to 100 points, label duplicate distances that + were not a number from 1 to 2000 points, and Show all labels settings that were not true or + false. A callout length given to `labels.placement` outside 5 to 500 points is brought within + range with a notice. Clean settings give no such notice. - **Font**: the labels' font family, any installed on the computer (Labeling pane › Symbol › **Font**; type part of a name to find it), or the label font the interface uses. Bold and italic take the family's own bold and italic faces where it has them. The family is saved by diff --git a/schema/fixtures/label_obstacles.rgis b/schema/fixtures/label_obstacles.rgis new file mode 100644 index 0000000000..f750ce6a5d --- /dev/null +++ b/schema/fixtures/label_obstacles.rgis @@ -0,0 +1 @@ +{"requires":["label-obstacles"],"format":2,"name":"Label obstacles","maps":[{"name":"Map","layers":[{"id":2,"name":"picos","visible":true,"dataset":{"name":"picos","geometry_type":"Point","fields":[{"name":"nome","ty":"Text","alias":null}],"features":[{"id":1,"geometry":{"Point":{"x":-41.0,"y":-20.37}},"attrs":[{"Text":"Ribeirão Santo Antônio"}]}],"source":null},"renderer":{"Single":{"fill":[224,123,57,255],"stroke":[224,123,57,255],"stroke_width":1.6,"size":0.0,"marker":"Circle"}},"labels":{"enabled":true,"field":"nome","size":8.0,"color":[43,43,43,255],"halo":true,"bold":false,"min_scale":null,"max_scale":null,"closest":null,"farthest":null,"placement":"Auto","italic":true,"obstacle_weight":8},"transparency":0.0,"min_scale":null,"max_scale":null,"definition_query":null,"selection":[],"expanded":true,"selectable":true,"graphics":false,"blend":"Normal","mask":null,"display_filters":[],"aggregation":null,"extrusion":null,"priority":0,"geometry_rev":0},{"id":1,"name":"rios","visible":true,"dataset":{"name":"rios","geometry_type":"Polyline","fields":[{"name":"nome","ty":"Text","alias":null}],"features":[{"id":1,"geometry":{"Line":[[{"x":-41.1,"y":-20.4},{"x":-41.0,"y":-20.38},{"x":-40.9,"y":-20.35}]]},"attrs":[{"Text":"Ribeirão Santo Antônio"}]}],"source":null},"renderer":{"Single":{"fill":[224,123,57,255],"stroke":[224,123,57,255],"stroke_width":1.6,"size":0.0,"marker":"Circle"}},"labels":{"enabled":false,"field":"nome","size":8.0,"color":[43,43,43,255],"halo":true,"bold":false,"min_scale":null,"max_scale":null,"closest":null,"farthest":null,"placement":"Auto","italic":true},"transparency":0.0,"min_scale":null,"max_scale":null,"definition_query":null,"selection":[],"expanded":true,"selectable":true,"graphics":false,"blend":"Normal","mask":null,"display_filters":[],"aggregation":null,"extrusion":null,"priority":0,"geometry_rev":0}],"basemap":"Paper","camera":{"center":{"x":-4564099.122524217,"y":-2317508.4417822156},"res":20.779638281411025,"bearing":0.0,"pitch":0.0},"bookmarks":[],"graticule":true,"projection":"WebMercator","popup_mode":"Topmost","label_display":{"paused":false,"locked":false,"show_unplaced":false},"editing":{"relationships":[],"snapping":{"enabled":false,"tolerance_px":10.0,"vertex":true,"edge":true,"end":true},"topology":[],"settings":{"enabled":true,"show_vertices":true,"elevation":"None","ground_to_grid":null}},"swipe":null,"view":{"effects":{"stars":true,"sun_time":null,"weather":"None","vignette":false,"edges":false,"tilt_shift":false,"grain":false,"brightness":0.0,"contrast":0.0,"saturation":0.0,"sepia":0.0},"wireframe":false,"clip_distance":null,"terrain":null},"animation":[],"next_layer_id":3}],"active_map":0,"tables":[],"next_table_id":1,"gp_history":[],"layouts":[],"folders":[],"styles":[],"ramps":[],"tasks":[],"gp_env":{"extent":null,"cell_size":null},"models":[],"workspaces":[],"link_views":false,"jobs":[],"offline_areas":[],"reports":[],"presentations":[],"notebooks":[],"dl_models":[],"shared":[],"data_stores":[]} diff --git a/schema/project.schema.json b/schema/project.schema.json index cac9792a1d..3a29b50a0b 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1328,7 +1328,8 @@ "shaded-relief-flats", "layout-publication-crs", "shaded-relief-generalize", - "project-open-layout" + "project-open-layout", + "label-obstacles" ], "type": "string" }, @@ -1475,7 +1476,8 @@ "shaded-relief-flats", "layout-publication-crs", "shaded-relief-generalize", - "project-open-layout" + "project-open-layout", + "label-obstacles" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2