Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / library / map / src / main / rust / src / tile / placement.rs

placement.rs442 lines · 18.2 KiBRaw
1//! Screen-space label placement: greedy, rank-ordered, per-frame.
2//!
3//! M1 places _point_ labels only (country/region/locality/subplace). Each tile
4//! shapes its candidates once ([`crate::tile::symbol`]); this module decides, per
5//! frame, which candidates draw: sort by rank (country first), greedily accept
6//! while the screen box collides with nothing accepted yet.
7//!
8//! # Coordinates
9//!
10//! Collision runs in _screen px_: the caller passes each candidate's screen box
11//! (computed from the anchor's clip position + the frame's text size). This keeps
12//! the module free of camera math and testable with literal boxes.
13//!
14//! Projection is pitch-aware ([`project_to_screen`]): at pitch 0 it is the linear
15//! map, and under tilt it carries the perspective divide the billboard shader
16//! applies — so a box sits where its label draws, and distant POIs compress onto
17//! overlapping boxes the rank-ordered placer thins by importance.
18//!
19//! # Rank
20//!
21//! Lower is more important: country (0) > region (1) > locality (2) > subplace
22//! (3) > POI (4), 255 for an id the renderer did not recognise (sinks last). Ties break
23//! by population weight (higher first — a big city beats a town), then by
24//! larger box (more informative), then by id order — deterministic, so frames
25//! don't shimmer.
26//!
27//! # Variable anchors
28//!
29//! A POI label may be drawn to the left or the right of its icon
30//! (`text-variable-anchor: ["left", "right"]`), so a candidate carries two boxes and
31//! [`place`] reports which one it accepted. The renderer then emits at that anchor, which
32//! is what makes a label near the edge of a crowd flip to its other side instead of
33//! disappearing.
34
35use crate::style::Anchor;
36
37/// A label candidate's screen box plus its rank.
38pub struct Candidate {
39 /// Stable id for the accept-set.
40 pub id: u64,
41 /// Rank: 0 country … 4 POI, 255 unknown (sorts last).
42 pub rank: u8,
43 /// Population weight within the rank, higher first.
44 pub pop: u16,
45 /// Screen box in device px, with collision padding baked in.
46 pub rect: (f32, f32, f32, f32),
47 /// The box to try when [`rect`](Self::rect) collides — the label drawn at its second
48 /// variable anchor. `None` for a label that cannot move, which is every place label.
49 pub alternate: Option<(f32, f32, f32, f32)>,
50}
51
52/// An accepted candidate: its id, and whether it took its
53/// [`alternate`](Candidate::alternate) box.
54pub type Placed = (u64, bool);
55
56/// Minimum population rank for a locality to draw at a camera zoom.
57///
58/// Country/region always draw (few, important); subplace is layer-gated. Rank gating
59/// happens before collision because collision alone cannot thin hundreds of towns down
60/// to the major-city set - the small ones simply arrive first in some tiles.
61///
62/// The ranks are the reference basemap's `population_rank` (see the tiler's
63/// `schema::places::rank_of`): 12 is 500k, 1 is any counted population at all. So z6 and
64/// below hold the half-million-plus cities, z7..z9 add anywhere with a population, and
65/// z10 draws everything the tile shaped.
66pub fn locality_min_pop(zoom: f64) -> u16 {
67 if zoom < 7.0 {
68 12
69 } else if zoom < 10.0 {
70 1
71 } else {
72 0
73 }
74}
75
76/// Greedily place candidates: rank order, first-come keeps its box.
77/// Rank 0 (country) always draws: it never collides, so capitals and country
78/// names survive any crowd. All other ranks collide normally.
79///
80/// A candidate whose primary box collides gets one more try at its
81/// [`alternate`](Candidate::alternate), and is reported as having taken it. That is
82/// MapLibre's variable-anchor behaviour reduced to the two anchors the reference
83/// declares.
84///
85/// Returns the accepted candidates in acceptance order.
86pub fn place(candidates: &[Candidate]) -> Vec<Placed> {
87 let mut ordered: Vec<&Candidate> = candidates.iter().collect();
88 ordered.sort_by(|a, b| {
89 a.rank
90 .cmp(&b.rank)
91 .then_with(|| b.pop.cmp(&a.pop))
92 .then_with(|| {
93 let (aw, ah) = (a.rect.2 - a.rect.0, a.rect.3 - a.rect.1);
94 let (bw, bh) = (b.rect.2 - b.rect.0, b.rect.3 - b.rect.1);
95 (bw * bh).partial_cmp(&(aw * ah)).unwrap_or(std::cmp::Ordering::Equal)
96 })
97 .then_with(|| a.id.cmp(&b.id))
98 });
99 let mut accepted: Vec<(f32, f32, f32, f32)> = Vec::new();
100 let mut out = Vec::new();
101 for c in ordered {
102 // Rank 0 never collides: country labels are few and must always draw.
103 let free = |rect: (f32, f32, f32, f32), accepted: &[(f32, f32, f32, f32)]| {
104 c.rank == 0 || !accepted.iter().any(|a| overlaps(*a, rect))
105 };
106 let taken = if free(c.rect, &accepted) {
107 (c.rect, false)
108 } else if let Some(alternate) = c.alternate.filter(|a| free(*a, &accepted)) {
109 (alternate, true)
110 } else {
111 continue;
112 };
113 accepted.push(taken.0);
114 out.push((c.id, taken.1));
115 }
116 out
117}
118
119fn overlaps(a: (f32, f32, f32, f32), b: (f32, f32, f32, f32)) -> bool {
120 a.0 < b.2 && b.0 < a.2 && a.1 < b.3 && b.1 < a.3
121}
122
123/// Hasher for maps keyed by [`candidate_id`]: the id passes straight through.
124///
125/// A candidate id is already a splitmix64-avalanched hash of its tile, layer and label, so
126/// running it through std's SipHash again buys nothing and costs a SipHash per lookup — and the
127/// frame path looks up every symbol-layer label of every resident tile in the accept-set on
128/// every frame (thousands of lookups a frame at city zooms).
129#[derive(Default, Clone, Copy)]
130pub struct CandidateIdHasher(u64);
131
132impl std::hash::Hasher for CandidateIdHasher {
133 fn finish(&self) -> u64 {
134 self.0
135 }
136
137 fn write_u64(&mut self, id: u64) {
138 self.0 = id;
139 }
140
141 /// Only `u64` keys are expected; anything else still hashes (FNV-1a), just not for free.
142 fn write(&mut self, bytes: &[u8]) {
143 for &b in bytes {
144 self.0 = (self.0 ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);
145 }
146 }
147}
148
149/// A map keyed by [`candidate_id`], hashed with [`CandidateIdHasher`].
150pub type CandidateMap<V> =
151 std::collections::HashMap<u64, V, std::hash::BuildHasherDefault<CandidateIdHasher>>;
152
153/// Stable id for one label of one tile in one frame, so the accept-set the
154/// renderer computes in its pre-pass names the same labels `record_symbol`
155/// later filters by.
156///
157/// A cheap deterministic integer mix over (tile z/x/y, layer index, position in
158/// the tile's shaped label list) — the label list is shaped once in feature
159/// order, so the inputs are frame-stable and collisions across tiles are
160/// impossible in practice. Pure integer arithmetic, so ids are stable across
161/// frames and runs (no hasher keys, no per-process randomness).
162pub fn candidate_id(z: u8, x: u32, y: u32, layer_index: usize, label_idx: usize) -> u64 {
163 // FxHash-style multiply mix + splitmix64 final avalanche.
164 const K: u64 = 0xbf58476d1ce4e5b9;
165 let mut h: u64 = 0x9e3779b97f4a7c15;
166 h ^= z as u64;
167 h = h.wrapping_mul(K);
168 h ^= x as u64;
169 h = h.wrapping_mul(K);
170 h ^= y as u64;
171 h = h.wrapping_mul(K);
172 h ^= layer_index as u64;
173 h = h.wrapping_mul(K);
174 h ^= label_idx as u64;
175 h = h.wrapping_mul(K);
176 // Final avalanche so neighbouring inputs land far apart.
177 h ^= h >> 30;
178 h = h.wrapping_mul(K);
179 h ^= h >> 27;
180 h = h.wrapping_mul(0x94d049bb133111eb);
181 h ^= h >> 31;
182 h
183}
184
185/// One label's screen collision box in device px, from the same inputs the
186/// tessellator uses — so the box the placer sees is the box the GPU draws,
187/// plus MapLibre-style padding.
188///
189/// `anchor` is tile-local 0..1, `tile_clip` the camera's column-major matrix
190/// for the tile, `extent_wh` the viewport in device px. Width is the label's
191/// advance at the frame's `text_px` (`total_advance` is in font units over
192/// [`UP_EM`](crate::tile::glyph::UP_EM)); height is one `text_px`, centred on
193/// the anchor like the emitted em box. `pad_px` inflates the box on every
194/// side, standing in for the icon + text padding MapLibre applies around
195/// every label: without it tight advance boxes let hundreds of villages
196/// survive at z6 where MapLibre shows ~10 cities.
197pub fn screen_rect(
198 anchor: (f32, f32),
199 tile_clip: [f32; 16],
200 extent_wh: (u32, u32),
201 text_px: f32,
202 total_advance: f32,
203 pad_px: f32,
204) -> Option<(f32, f32, f32, f32)> {
205 anchored_rect(
206 anchor,
207 tile_clip,
208 extent_wh,
209 &BoxInputs {
210 text_px,
211 advance: total_advance,
212 line_count: 1,
213 offset_em: (0.0, 0.0),
214 icon_px: None,
215 pad_px,
216 },
217 Anchor::Center,
218 )
219}
220
221/// Everything a label's collision box depends on besides where it is anchored.
222///
223/// A struct rather than eight parameters because the renderer builds one of these per
224/// label and then asks for a box at each candidate anchor — the inputs are shared and only
225/// the anchor varies.
226pub struct BoxInputs {
227 /// The frame's text size in device px.
228 pub text_px: f32,
229 /// The widest line's advance, in font units.
230 pub advance: f32,
231 /// How many lines the label wrapped to, at least 1.
232 pub line_count: usize,
233 /// `text-offset` in ems.
234 pub offset_em: (f32, f32),
235 /// The icon's drawn size in device px, when the label has one.
236 pub icon_px: Option<(f32, f32)>,
237 /// Collision padding added on every side.
238 pub pad_px: f32,
239}
240
241/// Project a tile-local 0..1 point to screen px through the tile's clip matrix, **with**
242/// the perspective divide — the one derivation collision shares with the GPU billboard path.
243///
244/// [`anchored_rect`] and [`curved_boxes`] used to apply only the matrix's linear part, which
245/// is the whole transform at pitch 0 (`w == 1`) but drops the foreshortening under tilt: boxes
246/// were built around a pre-divide position while `symbol_billboard.vert` draws each anchor
247/// post-divide, so collision tested boxes that sat nowhere near the drawn labels. A tilted view
248/// additionally compresses distant ground toward the horizon, which is exactly the declutter
249/// case — with the divide, far POIs land close together on screen, their screen-constant boxes
250/// overlap, and the rank-ordered placer culls them, so declutter follows the projected density
251/// rather than the zoom alone.
252///
253/// Returns `None` when the point is on or behind the eye (`w <= 0`): there is no screen position
254/// to collide at, so the label cannot be a candidate. Callers skip the label (point path) or the
255/// glyph (curved path) — a box for an unprojectable label is unrepresentable rather than garbage.
256/// The `partial_cmp` form also catches NaN, which would otherwise build a box that collides with
257/// nothing and always draws.
258pub fn project_to_screen(
259 tile_clip: [f32; 16],
260 point: (f32, f32),
261 extent_wh: (u32, u32),
262) -> Option<(f32, f32)> {
263 let cx = tile_clip[0] * point.0 + tile_clip[4] * point.1 + tile_clip[12];
264 let cy = tile_clip[1] * point.0 + tile_clip[5] * point.1 + tile_clip[13];
265 let w = tile_clip[3] * point.0 + tile_clip[7] * point.1 + tile_clip[15];
266 if !matches!(w.partial_cmp(&0.0), Some(std::cmp::Ordering::Greater)) {
267 return None;
268 }
269 Some(((cx / w * 0.5 + 0.5) * extent_wh.0 as f32, (cy / w * 0.5 + 0.5) * extent_wh.1 as f32))
270}
271
272/// The screen box a label would occupy if drawn at `anchor`.
273///
274/// The union of the text block and the icon, which is where this departs from MapLibre:
275/// it keeps two linked boxes and tests both. The two are equivalent while `icon-optional`
276/// and `text-optional` are both false — as they are here, since neither is set — because
277/// then a collision on either box rejects the pair anyway. A union is looser only in the
278/// gap the `text-offset` opens between icon and text, which is 1.1 em of empty space that
279/// nothing would have been placed in.
280///
281/// The box is centred on [`project_to_screen`]'s pitch-aware projection of `point`, so under
282/// tilt it sits where the billboarded label draws; its width and height are screen-constant
283/// (text advance at `text_px`, icon size in device px), matching the screen-constant size the
284/// billboard path draws at. Returns `None` when the anchor is on or behind the eye — such a
285/// label cannot be a candidate, so no box exists for it.
286pub fn anchored_rect(
287 point: (f32, f32),
288 tile_clip: [f32; 16],
289 extent_wh: (u32, u32),
290 inputs: &BoxInputs,
291 anchor: Anchor,
292) -> Option<(f32, f32, f32, f32)> {
293 let (sx, sy) = project_to_screen(tile_clip, point, extent_wh)?;
294
295 let w = inputs.text_px * inputs.advance / crate::tile::glyph::UP_EM as f32;
296 // Lines stack at 1.2 em, so a two-line block is 2.2 em tall, not 2.4: the first line
297 // contributes its own height and each further one a line's worth of leading.
298 let lines = inputs.line_count.max(1) as f32;
299 let h = inputs.text_px * (1.0 + (lines - 1.0) * crate::tess::text::LINE_HEIGHT_EM);
300 // The same placement `tess::text::emit` uses: the offset's magnitude, its direction
301 // taken from the anchor, and no vertical component on a horizontal anchor.
302 let offset = inputs.offset_em.0.abs() * inputs.text_px;
303 let (mut x0, mut x1) = match anchor {
304 Anchor::Center => (sx - w * 0.5, sx + w * 0.5),
305 Anchor::Left => (sx + offset, sx + offset + w),
306 Anchor::Right => (sx - offset - w, sx - offset),
307 };
308 let (mut y0, mut y1) = (sy - h * 0.5, sy + h * 0.5);
309 if let Some((icon_w, icon_h)) = inputs.icon_px {
310 x0 = x0.min(sx - icon_w * 0.5);
311 x1 = x1.max(sx + icon_w * 0.5);
312 y0 = y0.min(sy - icon_h * 0.5);
313 y1 = y1.max(sy + icon_h * 0.5);
314 }
315 Some((x0 - inputs.pad_px, y0 - inputs.pad_px, x1 + inputs.pad_px, y1 + inputs.pad_px))
316}
317
318// --- oriented / segmented collision (curved labels) -------------------------
319
320/// An oriented bounding box in screen px: a centre, half-extents along its own axes, and the
321/// unit orientation `(cos, sin)` of its local x-axis.
322///
323/// A point label's box is one of these with `sin == 0` (axis-aligned), so a single collision
324/// primitive serves both the straight point labels and the per-glyph boxes of a curved one — a
325/// curved street name is a *row* of these, each rotated to its glyph's tangent, which is what
326/// lets it collide tightly instead of as one loose AABB across the whole bend.
327#[derive(Clone, Copy, Debug)]
328pub struct Obb {
329 pub cx: f32,
330 pub cy: f32,
331 pub hx: f32,
332 pub hy: f32,
333 pub cos: f32,
334 pub sin: f32,
335}
336
337impl Obb {
338 /// An axis-aligned box from a screen rect — how a point label enters the segmented placer.
339 pub fn from_rect(rect: (f32, f32, f32, f32)) -> Obb {
340 Obb {
341 cx: (rect.0 + rect.2) * 0.5,
342 cy: (rect.1 + rect.3) * 0.5,
343 hx: (rect.2 - rect.0).abs() * 0.5,
344 hy: (rect.3 - rect.1).abs() * 0.5,
345 cos: 1.0,
346 sin: 0.0,
347 }
348 }
349
350 /// The box's two unit axes.
351 fn axes(&self) -> [(f32, f32); 2] {
352 [(self.cos, self.sin), (-self.sin, self.cos)]
353 }
354}
355
356/// Whether two oriented boxes overlap, by the separating-axis theorem.
357///
358/// Four candidate axes (each box's two), which is all a 2D OBB pair needs: if the boxes' shadows
359/// are disjoint on any one axis they cannot intersect. Touching exactly (a gap of zero) counts as
360/// separated, matching the half-open [`overlaps`] the axis-aligned path uses so a label may sit
361/// flush against its neighbour.
362///
363/// Fast path: when both boxes are axis-aligned (`sin == 0`, which is how every point label enters
364/// via [`Obb::from_rect`]), this is exactly the 4-float AABB test — same half-open rule, no SAT.
365pub fn obb_overlap(a: &Obb, b: &Obb) -> bool {
366 if a.sin == 0.0 && b.sin == 0.0 {
367 // |dx| < hx sum AND |dy| < hy sum; touching exactly (>=) is separated.
368 return (a.cx - b.cx).abs() < a.hx + b.hx && (a.cy - b.cy).abs() < a.hy + b.hy;
369 }
370 let dx = b.cx - a.cx;
371 let dy = b.cy - a.cy;
372 for axis in a.axes().iter().chain(b.axes().iter()) {
373 let (ax, ay) = *axis;
374 let centre_gap = (dx * ax + dy * ay).abs();
375 let ra = project_radius(a, ax, ay);
376 let rb = project_radius(b, ax, ay);
377 if centre_gap >= ra + rb {
378 return false;
379 }
380 }
381 true
382}
383
384/// The half-width of `box`'s shadow on unit axis `(ax, ay)`.
385fn project_radius(b: &Obb, ax: f32, ay: f32) -> f32 {
386 let [u, v] = b.axes();
387 b.hx * (u.0 * ax + u.1 * ay).abs() + b.hy * (v.0 * ax + v.1 * ay).abs()
388}
389
390/// A label candidate whose collision footprint is one or more oriented boxes.
391///
392/// The superset of [`Candidate`]: a point label is a single [`Obb`], a curved label is the row of
393/// per-glyph boxes [`curved_boxes`] builds. [`alternate`](Self::alternate) is the second
394/// variable-anchor footprint (POI only), tried when the primary collides — the same fallback
395/// [`Candidate`] carries, generalised to a set of boxes.
396pub struct SegmentedCandidate {
397 pub id: u64,
398 pub rank: u8,
399 pub pop: u16,
400 pub boxes: Vec<Obb>,
401 pub alternate: Option<Vec<Obb>>,
402 /// Stable feature identity for cross-tile dedup (`ID_NONE` when the label
403 /// carries no identity — such candidates are never deduped).
404 pub feature_id: u64,
405 /// Style layer index, the second half of the dedup identity.
406 pub layer_index: usize,
407}
408
409impl SegmentedCandidate {
410 /// The bounding half-area of the primary footprint, for the size tie-break — a curved label's
411 /// summed glyph areas, a point label's box area.
412 fn area(&self) -> f32 {
413 self.boxes.iter().map(|b| b.hx * b.hy).sum::<f32>() * 4.0
414 }
415}
416
417include!("placement_grid.rs");
418include!("placement_part1.rs");
419include!("placement_part2.rs");
420include!("placement_part3.rs");
421include!("placement_globe.rs");
422
423#[cfg(test)]
424mod candidate_map_tests {
425 use super::{candidate_id, CandidateMap};
426
427 #[test]
428 fn an_id_keyed_map_finds_exactly_the_ids_put_in() {
429 let mut map: CandidateMap<u32> = CandidateMap::default();
430 for label in 0..5_000usize {
431 map.insert(candidate_id(14, 2620, 6332, label % 14, label), label as u32);
432 }
433 assert_eq!(map.len(), 5_000, "candidate ids must stay distinct under the identity hash");
434 for label in 0..5_000usize {
435 assert_eq!(
436 map.get(&candidate_id(14, 2620, 6332, label % 14, label)),
437 Some(&(label as u32))
438 );
439 }
440 assert!(!map.contains_key(&candidate_id(14, 2620, 6333, 0, 0)));
441 }
442}