Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 52 additions & 16 deletions crates/render/src/area_labels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,9 +294,9 @@ pub(super) fn centre_line(rings: &[Vec<(f32, f32)>], w: f32, h: f32, half_width:
/// of the polygon `polys` as drawn: the label's centre and its characters. Tried at the line's
/// middle, then at places either side of it ([`line_labels::positions`]); the text must fit on the
/// line, with the polygon at least half its height either side of it. `None` when it fits nowhere,
/// or a part of the polygon near the view doesn't project (behind the globe): the label is then
/// placed as `Auto`. With a `stretch`, the letters are first spaced to cover its share of the centre
/// line, then (where that text can't follow it) `gap` apart.
/// or no part of the polygon is on the near side of the globe: the label is then placed as `Auto`.
/// With a `stretch`, the letters are first spaced to cover its share of the centre line, then
/// (where that text can't follow it) `gap` apart.
///
/// It works per frame, for each polygon labelled this way with its label point in view, and looks at
/// no Cancel: a step bounded by the outline's points near the view (each read once or a few times
Expand All @@ -318,23 +318,45 @@ pub(super) fn glyphs(
}

/// The rings of the polygon `polys` near the view on the screen, thinned before they are projected
/// (about [`MAX_VERTICES`] in all); `None` when a place of one doesn't project (behind the globe).
/// (about [`MAX_VERTICES`] in all). On the globe they are cut at the horizon as its fill is
/// ([`super::Ctx::globe_ring_vectors`], which draws them whole, so this never costs more): a
/// polygon with its outer ring wholly behind is left out, holes and all, as is a hole wholly
/// behind. `None` when none is left.
pub(super) fn screen_rings(ctx: &super::Ctx<'_>, polys: &[Vec<Vec<Coord>>]) -> Option<Vec<Vec<(f32, f32)>>> {
let near = |ring: &Vec<Coord>| {
let mut e = Extent::EMPTY;
ring.iter().for_each(|c| e.expand(*c));
ctx.globe.is_some() || ctx.cull.intersects(&e)
};
let near: Vec<&Vec<Coord>> = polys.iter().filter(|poly| poly.first().is_some_and(near)).flatten().collect();
let how = Thinning::new(near.iter().map(|r| r.len()));
near.into_iter()
.map(|ring| {
thin(ring, how, |c| (c.x, c.y))
.into_iter()
.map(|c| ctx.screen(c).map(|(x, y)| (x as f32, y as f32)))
.collect::<Option<Vec<_>>>()
})
.collect()
let candidates: Vec<&Vec<Vec<Coord>>> = polys.iter().filter(|poly| poly.first().is_some_and(near)).collect();
let how = Thinning::new(candidates.iter().copied().flatten().map(Vec::len));
let thinned = |ring: &Vec<Coord>| thin(ring, how, |c| (c.x, c.y));
let Some(globe) = &ctx.globe else {
let project = |c| ctx.screen(c).map(|(x, y)| (x as f32, y as f32));
return candidates.into_iter().flatten().map(|ring| thinned(ring).into_iter().map(project).collect()).collect();
};
let cut = |ring: &Vec<Coord>| globe_outline(globe, thinned(ring));
let mut rings = Vec::new();
for poly in candidates {
let mut cuts = poly.iter().map(cut);
if let Some(outer) = cuts.next().filter(|outer| !outer.is_empty()) {
rings.push(outer);
rings.extend(cuts.filter(|hole| !hole.is_empty()));
}
}
(!rings.is_empty()).then_some(rings)
}

/// A thinned ring's outline on the globe, in points, cut at the horizon. Closed first (thinning
/// may drop the closing place), so its last edge is bent and cut as the others are.
fn globe_outline(globe: &rustgis_map::Globe, mut ring: Vec<Coord>) -> Vec<(f32, f32)> {
if let Some(&first) = ring.first()
&& ring.last() != Some(&first)
{
ring.push(first);
}
let seen = super::Ctx::globe_ring_vectors(globe, &ring);
seen.into_iter().map(|v| globe.project(v)).map(|(x, y)| (x as f32, y as f32)).collect()
}

/// Where in `g`'s label part a label `aspect` times as wide as it is tall fits best on the screen
Expand All @@ -348,8 +370,9 @@ pub(super) fn screen_rings(ctx: &super::Ctx<'_>, polys: &[Vec<Vec<Coord>>]) -> O
///
/// The text stays upright in the view the frame is `shown` in (a turned or tilted one; none: the
/// frame's own), so the search is made there. The place is given in the frame's points, then in
/// that view's. `None` for no polygon, one with no area near the view or one with a place behind
/// the globe or the camera.
/// that view's. On the globe it is searched in the part this side of the horizon (#3356). `None`
/// for no polygon, one with no area near the view (or this side of the horizon) or one with a
/// place behind the camera.
///
/// With `clip` (#3276), the rings are first cut to that view, so the place is in the polygon's
/// part in view and the view's edges count as its own: a name that fits in that part is whole on
Expand Down Expand Up @@ -651,6 +674,19 @@ mod tests {
assert!(line.iter().all(|p| (p.1 - 5.0).abs() < 2.0), "{line:?}");
}

/// Thinning may drop a ring's closing place: the edge back to its first one is still bent
/// along its great circle and cut at the horizon.
#[test]
fn a_ring_without_its_closing_place_has_the_same_outline_on_the_globe() {
let camera = rustgis_map::Camera { center: Coord::new(0.0, 0.0), res: 25_000.0, bearing: 0.0, pitch: 0.0 };
let globe = rustgis_map::Globe::new(&camera, 800.0, 600.0);
// The edge from the last corner back to the first crosses the horizon.
let open: Vec<Coord> = [(60.0, 40.0), (60.0, -40.0), (140.0, -40.0), (140.0, 40.0)].map(|(x, y)| Coord::new(x, y)).into();
let mut closed = open.clone();
closed.push(Coord::new(60.0, 40.0));
assert_eq!(globe_outline(&globe, open), globe_outline(&globe, closed));
}

#[test]
fn nothing_inside_or_too_narrow_gives_no_line() {
assert!(centre_line(&[], 100.0, 100.0, 1.0).is_none());
Expand Down
32 changes: 21 additions & 11 deletions crates/render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1024,14 +1024,15 @@ impl Ctx<'_> {
out
}

/// A polygon ring on the globe. Hidden vertices are moved radially onto the horizon circle at
/// their own bearing, so the hidden part of the ring runs along the limb in its true order and
/// encloses no area; a ring that is wholly hidden is skipped.
fn globe_ring(&self, g: &Globe, pb: &mut PathBuilder, ring: &[Coord]) {
/// A polygon ring on the globe, as it is filled and as its labels read it. Hidden vertices
/// are moved radially onto the horizon circle at their own bearing, so the hidden part of the
/// ring runs along the limb in its true order and encloses no area; empty for a ring that is
/// wholly hidden or has fewer than three places.
fn globe_ring_vectors(g: &Globe, ring: &[Coord]) -> Vec<V3> {
let vs = Self::globe_vectors(g, ring);
let h = g.horizon();
if vs.len() < 3 || vs.iter().all(|v| v[2] <= h) {
return;
return Vec::new();
}
let r = (1.0 - h * h).sqrt();
let limb = |v: V3| {
Expand Down Expand Up @@ -1070,6 +1071,12 @@ impl Ctx<'_> {
{
out.extend(g.horizon_arc(last, first));
}
out
}

/// A polygon ring's path on the globe ([`Self::globe_ring_vectors`]).
fn globe_ring(&self, g: &Globe, pb: &mut PathBuilder, ring: &[Coord]) {
let out = Self::globe_ring_vectors(g, ring);
for (i, v) in out.iter().enumerate() {
let (x, y) = self.vpx(g, *v);
if i == 0 { pb.move_to(x, y) } else { pb.line_to(x, y) }
Expand Down Expand Up @@ -6217,7 +6224,7 @@ fn render_frame(
let Some(c) = g.label_point() else { continue };
// Where the label point is on the screen, `None` when it is out of view (or
// behind the globe): then only a line labelled along it can be, on its
// stretch in view.
// stretch in view, or a polygon placed inside, in its part in view.
let point = if globe.is_some() || ctx.cull.contains(c) {
ctx.screen(c)
} else if offset_reach > 0.0 {
Expand All @@ -6226,19 +6233,22 @@ fn render_frame(
} else {
None
};
let extent_in_view =
|| globe.is_some() || ctx.cull.intersects(&extents.get(row).copied().unwrap_or_else(|| g.extent()));
let extent_in_view = || {
let e = extents.get(row).copied().unwrap_or_else(|| g.extent());
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
match &globe {
Some(globe) => globe.may_see(&e),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
None => ctx.cull.intersects(&e),
}
};
let fid = layer.dataset.features.get(row).map(|f| f.id);
// (Its class's clause read only for a feature with a label moved.)
let moved_here = || {
any_moved
&& fid.is_some_and(|id| labels.in_order().any(|c| c.moved_to(id).is_some()))
&& classes.classes_of(ds_ptr, row).any(|(_, c)| moved_to(c, fid).is_some())
};
// (A polygon with its label point behind the globe is behind it too.)
let reaches_view = || {
((any_along && matches!(g, Geometry::Line(_)))
|| (any_inside && globe.is_none() && matches!(g, Geometry::Polygon(_))))
((any_along && matches!(g, Geometry::Line(_))) || (any_inside && matches!(g, Geometry::Polygon(_))))
&& extent_in_view()
};
if point.is_none() && !reaches_view() && !moved_here() {
Expand Down
161 changes: 156 additions & 5 deletions crates/render/src/polygon_labels_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,8 +275,7 @@ fn turned_and_tilted_views_place_the_pole() {
}
}

/// A lock that took the label point (place 1) still finds it in a frame with no pole, as with a
/// vertex behind the globe.
/// A lock that took the label point (place 1) still finds it in a frame with no pole.
#[test]
fn a_lock_on_the_label_point_holds_without_a_pole() {
let g = Geometry::Polygon(vec![vec![ring(&[(-0.2, 0.0), (0.0, 0.0), (0.2, 0.0)])]]);
Expand All @@ -290,9 +289,8 @@ fn a_lock_on_the_label_point_holds_without_a_pole() {
assert!(near(one(&mut m, &v), at_lock));
}

/// A lock taken where no place inside can be found (here a polygon with no area; on the globe,
/// one reaching behind it) keeps the label point's map place as the first, so the label doesn't
/// move when a place inside appears.
/// A lock taken where no place inside can be found (here a polygon with no area) keeps the label
/// point's map place as the first, so the label doesn't move when a place inside appears.
#[test]
fn a_lock_taken_without_a_pole_keeps_the_label_point() {
let g = Geometry::Polygon(vec![vec![ring(&[(-0.2, 0.0), (0.0, 0.0), (0.2, 0.0)])]]);
Expand Down Expand Up @@ -583,3 +581,156 @@ fn a_tilted_view_labels_a_polygon_reaching_behind_the_camera() {
box_in_view_and_polygon(&mut m, &v, &huge);
}
}

/// 60 to 140 degrees east and 40 south to 40 north (#3356): on a globe centred on the prime
/// meridian its label point is behind the horizon and a sliver of it is in view.
fn eastward() -> Vec<Coord> {
ring(&[(60.0, -40.0), (140.0, -40.0), (140.0, 40.0), (60.0, 40.0)])
}

/// A globe showing the polygon `rings`, labelled "Lake", trying other places when `on`.
fn globe(rings: &[Vec<Coord>], on: bool) -> (Map, u32) {
let (mut m, id) = map(Geometry::Polygon(vec![rings.to_vec()]), on);
m.projection = rustgis_map::Projection::Globe;
(m, id)
}

/// The whole globe, centred on the equator at `lon`.
fn globe_at(lon: f64) -> View {
let mut v = view_at(lon, 0.0);
v.camera.res = 25_000.0;
v
}

/// The longitude and latitude under a place on the globe.
fn globe_under(v: &View, (x, y): (f32, f32)) -> Coord {
let g = rustgis_map::Globe::new(&v.camera, v.width, v.height);
g.inverse(f64::from(x), f64::from(y)).expect("on the globe")
}

/// The one "Lake" label's place, in view and inside `rings`.
fn on_globe_inside(m: &mut Map, v: &View, rings: &[Vec<Coord>]) -> Coord {
let (x, y) = one(m, v);
assert!((0.0..=800.0).contains(&x) && (0.0..=600.0).contains(&y), "out of view: {:?}", (x, y));
let there = globe_under(v, (x, y));
assert!(depth(rings, there) > 0.0, "out of the polygon: {there:?}, tilted {}", v.camera.pitch);
there
}

/// Whether the whole box of the "Lake" label is in view and inside `rings` on the globe.
fn globe_box_inside(m: &mut Map, v: &View, rings: &[Vec<Coord>]) {
let placed = render(m, v).unwrap().labels;
let p = placed.iter().find(|l| l.text == "Lake").expect("labelled");
let face = text::Face { bold: false, italic: false, serif: false, family: None };
let (hw, hh) = (text::spaced_block_width("Lake", p.size, face, 0.0) / 2.0, text::block_height("Lake", p.size) / 2.0);
for (x, y) in [(p.x - hw, p.y - hh), (p.x + hw, p.y - hh), (p.x - hw, p.y + hh), (p.x + hw, p.y + hh)] {
assert!((0.0..=800.0).contains(&x) && (0.0..=600.0).contains(&y), "out of view: {:?}", (p.x, p.y));
assert!(depth(rings, globe_under(v, (x, y))) > 0.0, "out of the polygon: {:?}", (p.x, p.y));
}
}

#[test]
fn on_the_globe_a_polygon_crossing_the_horizon_is_labelled_in_its_visible_part() {
let rings = [eastward()];
on_globe_inside(&mut globe(&rings, true).0, &globe_at(0.0), &rings);
// Off, as on the flat map: its label point is behind the globe, so no label.
assert!(places(&mut globe(&rings, false).0, &globe_at(0.0)).is_empty());
}

#[test]
fn on_the_globe_a_visible_label_point_gives_way_to_a_place_in_the_visible_part() {
// Centred on 30 degrees east the label point (100, 0) is in view, near the horizon.
let rings = [eastward()];
let (mut m, _) = globe(&rings, true);
let v = globe_at(30.0);
let there = on_globe_inside(&mut m, &v, &rings);
assert!(there.x < 90.0, "still at the label point: {there:?}");
globe_box_inside(&mut m, &v, &rings);
}

#[test]
fn a_turned_and_tilted_globe_labels_the_visible_part() {
let rings = [eastward()];
// East is up, and tilted the camera sees less of that way: only about 55 degrees.
let mut v = globe_at(20.0);
(v.camera.bearing, v.camera.pitch) = (90.0, 30.0);
let g = rustgis_map::Globe::new(&v.camera, v.width, v.height);
assert!(g.forward(c(100.0, 0.0)).is_none(), "the label point is behind");
on_globe_inside(&mut globe(&rings, true).0, &v, &rings);
}

#[test]
fn a_zoomed_globe_labels_a_polygon_far_larger_than_the_view() {
// Its label point (70, 0) is on the near side but off the screen; its east side is behind.
let rings = [ring(&[(-10.0, -30.0), (150.0, -30.0), (150.0, 30.0), (-10.0, 30.0)])];
let mut v = view();
v.camera.res = 5_000.0;
globe_box_inside(&mut globe(&rings, true).0, &v, &rings);
}

#[test]
fn on_the_globe_a_hole_behind_the_horizon_leaves_the_visible_part_labelled() {
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
let rings = [eastward(), square(125.0, 0.0, 5.0)];
globe_box_inside(&mut globe(&rings, true).0, &globe_at(30.0), &rings);
}

#[test]
fn on_the_globe_a_curved_label_follows_the_visible_part() {
let rings = [eastward()];
let (mut m, id) = globe(&rings, true);
m.layer_mut(id).unwrap().labels.default.placement = LabelPlacement::Curved;
let v = globe_at(30.0);
let placed = render(&mut m, &v).unwrap().labels;
let p = placed.iter().find(|l| l.text == "Lake").expect("labelled");
assert_eq!(p.glyphs.len(), 4, "along its centre line");
for g in &p.glyphs {
let there = globe_under(&v, (p.x + g.dx, p.y + g.dy));
assert!(depth(&rings, there) > 0.0, "{} out of the polygon: {there:?}", g.text);
}
}

#[test]
fn a_lock_holds_a_visible_parts_label_on_a_turning_globe() {
let rings = [eastward()];
let (mut m, _) = globe(&rings, true);
m.label_display.locked = true;
let before = on_globe_inside(&mut m, &globe_at(0.0), &rings);
let after = on_globe_inside(&mut m, &globe_at(2.0), &rings);
assert!((after.x - before.x).abs() < 0.05 && (after.y - before.y).abs() < 0.05, "{before:?} {after:?}");
}

#[test]
fn on_the_globe_a_guided_label_follows_its_line_in_the_visible_part() {
let rings = [eastward()];
let (mut m, id) = globe(&rings, false);
let mut d = Dataset::new("ridges", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]);
let ridge = (0..=40).map(|i| c(75.0, f64::from(i) - 20.0)).collect();
d.push(Some(Geometry::Line(vec![ridge])), vec![Value::Text("Ridge".into())]);
m.add_dataset(d);
m.layer_mut(id).unwrap().labels.default.guide = Some(rustgis_map::symbology::LabelGuide { layer: "ridges".into(), field: None });
let v = globe_at(30.0);
let placed = render(&mut m, &v).unwrap().labels;
let p = placed.iter().find(|l| l.text == "Lake").expect("labelled");
assert_eq!(p.glyphs.len(), 4, "along its guide");
for g in &p.glyphs {
let there = globe_under(&v, (p.x + g.dx, p.y + g.dy));
assert!((there.x - 75.0).abs() < 1.0, "{} off the guide: {there:?}", g.text);
}
}

#[test]
fn on_the_globe_a_line_is_labelled_along_its_visible_stretch_only() {
let along = |lons: std::ops::RangeInclusive<i32>| {
let line = lons.step_by(5).map(|x| c(f64::from(x), 0.0)).collect();
let (mut m, id) = map(Geometry::Line(vec![line]), false);
m.projection = rustgis_map::Projection::Globe;
m.layer_mut(id).unwrap().labels.default.placement = LabelPlacement::Parallel;
m
};
// Wholly behind the globe: no label.
assert!(places(&mut along(150..=170), &globe_at(0.0)).is_empty());
// Its middle (110, 0) behind, its west end in view.
let v = globe_at(20.0);
let there = globe_under(&v, one(&mut along(50..=170), &v));
assert!((50.0..101.0).contains(&there.x), "{there:?}");
}
9 changes: 5 additions & 4 deletions docs/user-guide/cartography.md
Original file line number Diff line number Diff line change
Expand Up @@ -788,10 +788,11 @@ Turn labels on per layer (Labeling › Labels › **Label**), then:
view, the label goes where its shape fits best inside the part of the polygon in view, the view's
edges counting as the polygon's own: it follows that part as the map moves (Lock holds it), and is
left out if another label takes its place. On a multipolygon this is the part its label is for;
other parts in view don't take it. On a polygon more than 64 times longer than wide on screen,
once narrowed to the text's shape, only its first 64 widths are searched. Curved labels and
labels along a guide don't use it: the box is hidden for them, the command refuses to turn it
on, and a setting already on has no effect. Off by default,
other parts in view don't take it. On the globe only the part on this side of the horizon counts:
the shape is fitted to it, and what is behind the horizon is out of view. On a polygon more than
64 times longer than wide on screen, once narrowed to the text's shape, only its first 64 widths
are searched. Curved labels and labels along a guide don't use it: the box is hidden for them,
the command refuses to turn it on, and a setting already on has no effect. Off by default,
as round points; the class's position and offset apply from each of the two places (Above sets the
name above that point), and Lock keeps the place each label took
(`labels.placement={"layer": "Lakes", "otherPositions": true}`).
Expand Down
Loading