Modern Apps git

← Modern-Apps.git

maps: split overlong Rust files under 500-line limit

Commit
bd3eca223915ec9dda40091ab580ef3a9959c325
Author
vayun-mathur <[email protected]>
When
2026-09-23 01:25 UTC (2 months ago)
Parents
ef33321

Diff

library/map/src/main/rust/src/tile/placement.rs
diff --git a/library/map/src/main/rust/src/tile/placement.rs b/library/map/src/main/rust/src/tile/placement.rsindex 6e89550141..78783cd7ef 100644--- a/library/map/src/main/rust/src/tile/placement.rs+++ b/library/map/src/main/rust/src/tile/placement.rs@@ -33,7 +33,6 @@ //! disappearing.  use crate::style::Anchor;-use std::collections::HashMap;  /// A label candidate's screen box plus its rank. pub struct Candidate {@@ -395,135 +394,7 @@ impl SegmentedCandidate {     } } -/// Greedily place candidates whose footprints are oriented-box sets: the segmented counterpart of-/// [`place`], and the one the curved labels use so a street name collides with a point label-/// box-for-box rather than as one loose rectangle.-///-/// Ordering, rank-0-never-collides and the variable-anchor fallback are identical to [`place`];-/// only the geometry test changes (any box against any accepted box, by [`obb_overlap`]). A point-/// label enters as a one-box candidate, so point and curved labels place in the **same** pass and-/// therefore collide with each other, which is the whole point of the exercise.-pub fn place_segmented(candidates: &[SegmentedCandidate]) -> Vec<Placed> {-    // Hoisted footprint areas: `SegmentedCandidate::area` computed once per-    // candidate into a side table. The comparator below reads this table, so-    // sorting never recomputes the sum.-    let mut areas: Vec<f32> = Vec::with_capacity(candidates.len());-    for c in candidates.iter() {-        areas.push(c.area());-    }-    // Sort indices (stable) by the same key as before: rank, pop desc, area-    // desc, id. Starting from 0..n with a stable sort and identical keys yields-    // the identical order as sorting `Vec<&Candidate>` from iteration order.-    let mut ordered: Vec<usize> = (0..candidates.len()).collect();-    ordered.sort_by(|&ai, &bi| {-        let (a, b) = (&candidates[ai], &candidates[bi]);-        a.rank-            .cmp(&b.rank)-            .then_with(|| b.pop.cmp(&a.pop))-            .then_with(|| {-                areas[bi]-                    .partial_cmp(&areas[ai])-                    .unwrap_or(std::cmp::Ordering::Equal)-            })-            .then_with(|| a.id.cmp(&b.id))-    });-    // Reserve the accepted-box buffer from the candidate count (primary boxes;-    // alternates substitute 1:1 so this bounds the accepted set size).-    let total_primary: usize = candidates.iter().map(|c| c.boxes.len()).sum();-    let mut accepted: Vec<Obb> = Vec::with_capacity(total_primary);-    // Uniform-grid broadphase over accepted boxes. Cell size derives from the-    // max AABB half-extent over all candidate boxes (padding is already baked-    // into the boxes); any cell size keeps results exact, this one keeps each-    // box in few cells.-    let mut max_e: f32 = 0.0;-    for c in candidates.iter() {-        for b in c.boxes.iter().chain(c.alternate.iter().flatten()) {-            let (ex, ey) = obb_aabb_half(b);-            max_e = max_e.max(ex).max(ey);-        }-    }-    let mut cell: f32 = max_e * 2.0;-    if !(cell >= 1.0) {-        cell = 1.0;-    }-    let mut grid: HashMap<(i32, i32), Vec<usize>> = HashMap::new();-    let mut out = Vec::new();-    for &ci in ordered.iter() {-        let c = &candidates[ci];-        // Rank 0 short-circuits before any geometry, as before.-        let free = |boxes: &[Obb]| {-            if c.rank == 0 {-                return true;-            }-            for b in boxes.iter() {-                let (x0, y0, x1, y1) = obb_aabb(b);-                let (cx0, cy0, cx1, cy1) = cell_range(x0, y0, x1, y1, cell);-                for cy in cy0..=cy1 {-                    for cx in cx0..=cx1 {-                        if let Some(bucket) = grid.get(&(cx, cy)) {-                            for &ai in bucket.iter() {-                                // Narrowphase stays exact `obb_overlap`, same-                                // argument order as the brute-force loop.-                                if obb_overlap(&accepted[ai], b) {-                                    return false;-                                }-                            }-                        }-                    }-                }-            }-            true-        };-        let taken = if free(&c.boxes) {-            (&c.boxes, false)-        } else if let Some(alternate) = c.alternate.as_ref().filter(|a| free(a)) {-            (alternate, true)-        } else {-            continue;-        };-        for b in taken.0.iter() {-            let idx = accepted.len();-            accepted.push(*b);-            let (x0, y0, x1, y1) = obb_aabb(b);-            let (cx0, cy0, cx1, cy1) = cell_range(x0, y0, x1, y1, cell);-            for cy in cy0..=cy1 {-                for cx in cx0..=cx1 {-                    grid.entry((cx, cy)).or_default().push(idx);-                }-            }-        }-        out.push((c.id, taken.1));-    }-    out-}--/// Half-extents of an OBB's axis-aligned bounding box.-///-/// `pub(crate)` for the renderer's viewport cull: the AABB conservatively bounds the OBB,-/// so a candidate whose every box AABB misses the viewport can draw no visible pixel.-pub(crate) fn obb_aabb_half(b: &Obb) -> (f32, f32) {-    let (c, s) = (b.cos.abs(), b.sin.abs());-    (b.hx * c + b.hy * s, b.hx * s + b.hy * c)-}--/// Full AABB of an OBB in screen px.-fn obb_aabb(b: &Obb) -> (f32, f32, f32, f32) {-    let (ex, ey) = obb_aabb_half(b);-    (b.cx - ex, b.cy - ey, b.cx + ex, b.cy + ey)-}--/// Grid cells overlapped by an AABB (inclusive range via floor).-fn cell_range(x0: f32, y0: f32, x1: f32, y1: f32, cell: f32) -> (i32, i32, i32, i32) {-    let (lo_x, hi_x) = if x0 <= x1 { (x0, x1) } else { (x1, x0) };-    let (lo_y, hi_y) = if y0 <= y1 { (y0, y1) } else { (y1, y0) };-    (-        (lo_x / cell).floor() as i32,-        (lo_y / cell).floor() as i32,-        (hi_x / cell).floor() as i32,-        (hi_y / cell).floor() as i32,-    )-}-+include!("placement_grid.rs"); include!("placement_part1.rs"); include!("placement_part2.rs"); include!("placement_part3.rs");
library/map/src/main/rust/src/tile/placement_grid.rs
diff --git a/library/map/src/main/rust/src/tile/placement_grid.rs b/library/map/src/main/rust/src/tile/placement_grid.rsnew file mode 100644index 0000000000..9981d37d1c--- /dev/null+++ b/library/map/src/main/rust/src/tile/placement_grid.rs@@ -0,0 +1,143 @@+// The segmented placer's broadphase: a uniform-grid index over accepted boxes.+//+// File-length split from `tile::placement` (see `placement.rs`): the greedy+// `place_segmented` pass plus the grid helpers it reads. Included textually via+// `include!`, so everything here shares `placement.rs`'s scope — `Obb`,+// `obb_overlap`, `SegmentedCandidate` and `Placed` resolve as if this were one+// file.+use std::collections::HashMap;++/// Greedily place candidates whose footprints are oriented-box sets: the segmented counterpart of+/// the `place` function in `placement.rs`, and the one the curved labels use so a street name+/// collides with a point label box-for-box rather than as one loose rectangle.+///+/// Ordering, rank-0-never-collides and the variable-anchor fallback are identical to `place`;+/// only the geometry test changes (any box against any accepted box, by `obb_overlap`). A point+/// label enters as a one-box candidate, so point and curved labels place in the **same** pass and+/// therefore collide with each other, which is the whole point of the exercise.+///+/// Performance shape: footprint areas are hoisted into a side table (the sort+/// comparator never recomputes the sum), the accepted-box buffer is reserved up+/// front, and collision runs through a uniform-grid broadphase — cell size from+/// the max AABB half-extent — with the exact narrowphase. Bit-identical accept+/// order, accept set and `flipped` flags versus the brute-force loop.+pub fn place_segmented(candidates: &[SegmentedCandidate]) -> Vec<Placed> {+    // Hoisted footprint areas: `SegmentedCandidate::area` computed once per+    // candidate into a side table. The comparator below reads this table, so+    // sorting never recomputes the sum.+    let mut areas: Vec<f32> = Vec::with_capacity(candidates.len());+    for c in candidates.iter() {+        areas.push(c.area());+    }+    // Sort indices (stable) by the same key as before: rank, pop desc, area+    // desc, id. Starting from 0..n with a stable sort and identical keys yields+    // the identical order as sorting `Vec<&Candidate>` from iteration order.+    let mut ordered: Vec<usize> = (0..candidates.len()).collect();+    ordered.sort_by(|&ai, &bi| {+        let (a, b) = (&candidates[ai], &candidates[bi]);+        a.rank+            .cmp(&b.rank)+            .then_with(|| b.pop.cmp(&a.pop))+            .then_with(|| {+                areas[bi]+                    .partial_cmp(&areas[ai])+                    .unwrap_or(std::cmp::Ordering::Equal)+            })+            .then_with(|| a.id.cmp(&b.id))+    });+    // Reserve the accepted-box buffer from the candidate count (primary boxes;+    // alternates substitute 1:1 so this bounds the accepted set size).+    let total_primary: usize = candidates.iter().map(|c| c.boxes.len()).sum();+    let mut accepted: Vec<Obb> = Vec::with_capacity(total_primary);+    // Uniform-grid broadphase over accepted boxes. Cell size derives from the+    // max AABB half-extent over all candidate boxes (padding is already baked+    // into the boxes); any cell size keeps results exact, this one keeps each+    // box in few cells.+    let mut max_e: f32 = 0.0;+    for c in candidates.iter() {+        for b in c.boxes.iter().chain(c.alternate.iter().flatten()) {+            let (ex, ey) = obb_aabb_half(b);+            max_e = max_e.max(ex).max(ey);+        }+    }+    let mut cell: f32 = max_e * 2.0;+    if !(cell >= 1.0) {+        cell = 1.0;+    }+    let mut grid: HashMap<(i32, i32), Vec<usize>> = HashMap::new();+    let mut out = Vec::new();+    for &ci in ordered.iter() {+        let c = &candidates[ci];+        // Rank 0 short-circuits before any geometry, as before.+        let free = |boxes: &[Obb]| {+            if c.rank == 0 {+                return true;+            }+            for b in boxes.iter() {+                let (x0, y0, x1, y1) = obb_aabb(b);+                let (cx0, cy0, cx1, cy1) = cell_range(x0, y0, x1, y1, cell);+                for cy in cy0..=cy1 {+                    for cx in cx0..=cx1 {+                        if let Some(bucket) = grid.get(&(cx, cy)) {+                            for &ai in bucket.iter() {+                                // Narrowphase stays exact `obb_overlap`, same+                                // argument order as the brute-force loop.+                                if obb_overlap(&accepted[ai], b) {+                                    return false;+                                }+                            }+                        }+                    }+                }+            }+            true+        };+        let taken = if free(&c.boxes) {+            (&c.boxes, false)+        } else if let Some(alternate) = c.alternate.as_ref().filter(|a| free(a)) {+            (alternate, true)+        } else {+            continue;+        };+        for b in taken.0.iter() {+            let idx = accepted.len();+            accepted.push(*b);+            let (x0, y0, x1, y1) = obb_aabb(b);+            let (cx0, cy0, cx1, cy1) = cell_range(x0, y0, x1, y1, cell);+            for cy in cy0..=cy1 {+                for cx in cx0..=cx1 {+                    grid.entry((cx, cy)).or_default().push(idx);+                }+            }+        }+        out.push((c.id, taken.1));+    }+    out+}++/// Half-extents of an OBB's axis-aligned bounding box.+///+/// `pub(crate)` for the renderer's viewport cull: the AABB conservatively bounds the OBB,+/// so a candidate whose every box AABB misses the viewport can draw no visible pixel.+pub(crate) fn obb_aabb_half(b: &Obb) -> (f32, f32) {+    let (c, s) = (b.cos.abs(), b.sin.abs());+    (b.hx * c + b.hy * s, b.hx * s + b.hy * c)+}++/// Full AABB of an OBB in screen px.+fn obb_aabb(b: &Obb) -> (f32, f32, f32, f32) {+    let (ex, ey) = obb_aabb_half(b);+    (b.cx - ex, b.cy - ey, b.cx + ex, b.cy + ey)+}++/// Grid cells overlapped by an AABB (inclusive range via floor).+fn cell_range(x0: f32, y0: f32, x1: f32, y1: f32, cell: f32) -> (i32, i32, i32, i32) {+    let (lo_x, hi_x) = if x0 <= x1 { (x0, x1) } else { (x1, x0) };+    let (lo_y, hi_y) = if y0 <= y1 { (y0, y1) } else { (y1, y0) };+    (+        (lo_x / cell).floor() as i32,+        (lo_y / cell).floor() as i32,+        (hi_x / cell).floor() as i32,+        (hi_y / cell).floor() as i32,+    )+}
library/map/src/main/rust/src/vulkan/renderer/mod.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/mod.rs b/library/map/src/main/rust/src/vulkan/renderer/mod.rsindex a82bdf3fd9..ae3a71a43e 100644--- a/library/map/src/main/rust/src/vulkan/renderer/mod.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/mod.rs@@ -13,6 +13,7 @@ mod fog; mod frame; mod mod_extra; mod placement;+mod placement_reuse; mod rebuild; mod record; mod record_extra;@@ -222,22 +223,6 @@ struct PlacementKey {     layers: usize, } -impl PlacementKey {-    /// Bit-identity of everything but the camera pose: tiles and their stamps, filter, extent,-    /// sizes, and layer count. A drift-reuse candidate must match all of these; only-    /// centre/zoom/bearing/pitch may differ (within their thresholds — see `within_drift` in-    /// `placement.rs`). Any universe change is a hard re-place.-    fn same_universe(&self, other: &PlacementKey) -> bool {-        self.width_dp == other.width_dp-            && self.height_dp == other.height_dp-            && self.density == other.density-            && self.extent == other.extent-            && self.filter == other.filter-            && self.tiles == other.tiles-            && self.layers == other.layers-    }-}- /// Per-frame synchronisation and its command buffer. struct Frame {     command_buffer: vk::CommandBuffer,@@ -439,53 +424,10 @@ fn anchors_for(layer: &Layer) -> (Anchor, Option<Anchor>) { /// /// Built once per label and reused for each candidate anchor, so the two boxes a POI is /// tried at can only differ in where they sit — not in how big they are.-fn box_inputs(-    layer: &Layer,-    label: &geometry::ShapedLabel,-    camera: &Camera,-) -> crate::tile::placement::BoxInputs {-    box_inputs_with_arms(layer, label, camera, layer.text_size_arms(camera.zoom))-}--/// [`box_inputs`], but with the style's text-size arms already resolved for this-/// (layer, zoom) — see [`Layer::text_size_arms`]. The per-label call resolves two-/// style ramps per label; the per-layer caller resolves them once and answers each-/// label with a float compare. Bit-identical values either way.-fn box_inputs_with_arms(-    layer: &Layer,-    label: &geometry::ShapedLabel,-    camera: &Camera,-    arms: (f32, Option<f32>, Option<f32>),-) -> crate::tile::placement::BoxInputs {-    crate::tile::placement::BoxInputs {-        text_px: Layer::text_size_with_arms(label.pop, arms.0, arms.1, arms.2) * camera.density,-        advance: label.total_advance,-        line_count: label.lines.len(),-        offset_em: layer.text_offset,-        // Dp from the sheet, device px here — the same conversion `emit_icon` makes.-        icon_px: label-            .sprite-            .map(|s| (s.width_dp * camera.density, s.height_dp * camera.density)),-        pad_px: collision_padding_px(camera.zoom),-    }-}--/// Collision padding in device px around every label box, by camera zoom. ///-/// MapLibre pads every label (icon + text padding, growing at low zoom via-/// the icon-padding ramp), which is what holds z6 to ~10 cities while z14-/// stays dense. Without it tight advance boxes let hundreds of villages-/// survive at z6. 24px at z6 and below culls hamlets against towns; 4px at-/// z14+ keeps street labels tight. Linear between.-fn collision_padding_px(zoom: f64) -> f32 {-    if zoom <= 6.0 {-        24.0-    } else if zoom >= 14.0 {-        4.0-    } else {-        (24.0 - (zoom - 6.0) * (20.0 / 8.0)) as f32-    }-}+/// Lives in [`placement_reuse`] (file-length split) alongside the candidate loop+/// that reads it; re-exported here so existing `super::box_inputs` paths keep working.+pub(super) use placement_reuse::{box_inputs, box_inputs_with_arms};  /// Multiply a colour's alpha by `opacity`, for the style's fill-opacity ramps. ///
library/map/src/main/rust/src/vulkan/renderer/placement.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/placement.rs b/library/map/src/main/rust/src/vulkan/renderer/placement.rsindex b49326265f..83f7d14221 100644--- a/library/map/src/main/rust/src/vulkan/renderer/placement.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/placement.rs@@ -1,6 +1,7 @@ use super::{-    anchors_for, box_inputs, box_inputs_with_arms, kind_name, AcceptSet, Overlay, PlacedHit,-    PlacementKey, Renderer, QUAD_INDICES,+    anchors_for, box_inputs, box_inputs_with_arms, kind_name,+    placement_reuse::{drift_reuse_ms, within_drift},+    AcceptSet, Overlay, PlacedHit, PlacementKey, Renderer, QUAD_INDICES, }; use crate::camera::Camera; use crate::marker::Marker;@@ -29,74 +30,6 @@ use std::time::Instant; /// gestures. pub(super) const PLACE_REUSE_MS: u128 = 300; -/// The reuse window once the camera is zooming fast (see [`place_symbols`]).-///-/// Past ~1 zoom level per second the collision answer goes stale faster than the pan window-/// allows: re-place promptly instead so labels do not visibly lag the zoom.-const PLACE_REUSE_FAST_ZOOM_MS: u128 = 80;--/// The zoom speed past which the reuse window shrinks to [`PLACE_REUSE_FAST_ZOOM_MS`],-/// in zoom levels per second.-const FAST_ZOOM_PER_SEC: f64 = 1.0;--/// Drift thresholds for reusing the accept-set without an exact key match.-///-/// A camera that differs from the cached one only in centre/zoom/bearing/pitch, each within-/// these, reuses the cached accept-set within [`PLACE_REUSE_MS`]: the projection moved a-/// little but the candidate universe (tiles, layers, filter, extent, sizes) is bit-identical,-/// so the collision answer is overwhelmingly likely unchanged and boxes still re-project per-/// frame in `refresh_placed`. Any drift past these re-places.-const DRIFT_MAX_DZOOM: f64 = 0.05;-/// Degrees.-const DRIFT_MAX_DBEARING: f64 = 2.0;-/// Degrees.-const DRIFT_MAX_DPITCH: f64 = 2.0;--/// Whether `key` differs from `cached` only by camera drift within the reuse thresholds.-///-/// Centre may move arbitrarily (pan); zoom/bearing/pitch each have a small budget. The-/// universe (tiles, stamps, filter, extent, sizes, layers) must be bit-identical — checked-/// by the caller via [`PlacementKey::same_universe`](super::PlacementKey::same_universe).-fn within_drift(cached: &PlacementKey, key: &PlacementKey) -> bool {-    let zoom = f64::from_bits(key.zoom);-    let cached_zoom = f64::from_bits(cached.zoom);-    if (zoom - cached_zoom).abs() >= DRIFT_MAX_DZOOM {-        return false;-    }-    let bearing = f64::from_bits(key.bearing);-    let cached_bearing = f64::from_bits(cached.bearing);-    if (bearing - cached_bearing).abs() >= DRIFT_MAX_DBEARING {-        return false;-    }-    let pitch = f64::from_bits(key.pitch);-    let cached_pitch = f64::from_bits(cached.pitch);-    if (pitch - cached_pitch).abs() >= DRIFT_MAX_DPITCH {-        return false;-    }-    true-}--/// The reuse window for a drift-reuse hit: the full [`PLACE_REUSE_MS`], shrunk to-/// [`PLACE_REUSE_FAST_ZOOM_MS`] while zooming fast.-///-/// Zoom velocity comes from the cached key's zoom versus this frame's over the cache age —-/// both already in hand, no extra state. A zero/negative age (same-instant re-entry) takes-/// the fast path only if the zoom actually jumped; otherwise the full window.-fn drift_reuse_ms(cached: &PlacementKey, key: &PlacementKey, at: &Instant) -> u128 {-    let zoom = f64::from_bits(key.zoom);-    let cached_zoom = f64::from_bits(cached.zoom);-    let dz = (zoom - cached_zoom).abs();-    if dz <= 0.0 {-        return PLACE_REUSE_MS;-    }-    let age_secs = at.elapsed().as_secs_f64();-    if age_secs > 0.0 && dz / age_secs > FAST_ZOOM_PER_SEC {-        PLACE_REUSE_FAST_ZOOM_MS-    } else {-        PLACE_REUSE_MS-    }-}- impl Renderer {     /// Whether any resident tile carries a region-mask piece with this id.     ///@@ -175,7 +108,7 @@ impl Renderer {             // faster than the pan window allows, so re-place promptly.             if cached.same_universe(&key)                 && within_drift(cached, &key)-                && at.elapsed().as_millis() < drift_reuse_ms(cached, &key, at)+                && at.elapsed().as_millis() < drift_reuse_ms(cached, &key, at, PLACE_REUSE_MS)             {                 return accepted.clone();             }
library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rs b/library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rsnew file mode 100644index 0000000000..475809e818--- /dev/null+++ b/library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rs@@ -0,0 +1,154 @@+//! Placement reuse across camera motion, plus the collision-box inputs.+//!+//! File-length split from the renderer root (see `mod.rs`) and from+//! [`placement`](super::placement) (see `placement.rs`): the drift-reuse+//! machinery that lets small zoom/bearing/pitch changes reuse the cached+//! accept-set, the [`PlacementKey`] universe comparison behind it, and the+//! per-label collision-box inputs the candidate loop reads. A real submodule+//! (not `include!`), so imports are explicit below.+use super::PlacementKey;+use crate::camera::Camera;+use crate::style::Layer;+use crate::tile::geometry;+use std::time::Instant;++/// The reuse window once the camera is zooming fast (see [`Renderer::place_symbols`](super::Renderer::place_symbols)).+///+/// Past ~1 zoom level per second the collision answer goes stale faster than the pan window+/// allows: re-place promptly instead so labels do not visibly lag the zoom.+const PLACE_REUSE_FAST_ZOOM_MS: u128 = 80;++/// The zoom speed past which the reuse window shrinks to [`PLACE_REUSE_FAST_ZOOM_MS`],+/// in zoom levels per second.+const FAST_ZOOM_PER_SEC: f64 = 1.0;++/// Drift thresholds for reusing the accept-set without an exact key match.+///+/// A camera that differs from the cached one only in centre/zoom/bearing/pitch, each within+/// these, reuses the cached accept-set within the reuse window: the projection moved a+/// little but the candidate universe (tiles, layers, filter, extent, sizes) is bit-identical,+/// so the collision answer is overwhelmingly likely unchanged and boxes still re-project per+/// frame in `refresh_placed`. Any drift past these re-places.+const DRIFT_MAX_DZOOM: f64 = 0.05;+/// Degrees.+const DRIFT_MAX_DBEARING: f64 = 2.0;+/// Degrees.+const DRIFT_MAX_DPITCH: f64 = 2.0;++/// Whether `key` differs from `cached` only by camera drift within the reuse thresholds.+///+/// Centre may move arbitrarily (pan); zoom/bearing/pitch each have a small budget. The+/// universe (tiles, stamps, filter, extent, sizes, layers) must be bit-identical — checked+/// by the caller via [`PlacementKey::same_universe`].+pub(super) fn within_drift(cached: &PlacementKey, key: &PlacementKey) -> bool {+    let zoom = f64::from_bits(key.zoom);+    let cached_zoom = f64::from_bits(cached.zoom);+    if (zoom - cached_zoom).abs() >= DRIFT_MAX_DZOOM {+        return false;+    }+    let bearing = f64::from_bits(key.bearing);+    let cached_bearing = f64::from_bits(cached.bearing);+    if (bearing - cached_bearing).abs() >= DRIFT_MAX_DBEARING {+        return false;+    }+    let pitch = f64::from_bits(key.pitch);+    let cached_pitch = f64::from_bits(cached.pitch);+    if (pitch - cached_pitch).abs() >= DRIFT_MAX_DPITCH {+        return false;+    }+    true+}++/// The reuse window for a drift-reuse hit: the full reuse window, shrunk to+/// [`PLACE_REUSE_FAST_ZOOM_MS`] while zooming fast.+///+/// Zoom velocity comes from the cached key's zoom versus this frame's over the cache age —+/// both already in hand, no extra state. A zero/negative age (same-instant re-entry) takes+/// the fast path only if the zoom actually jumped; otherwise the full window.+pub(super) fn drift_reuse_ms(+    cached: &PlacementKey,+    key: &PlacementKey,+    at: &Instant,+    full_window_ms: u128,+) -> u128 {+    let zoom = f64::from_bits(key.zoom);+    let cached_zoom = f64::from_bits(cached.zoom);+    let dz = (zoom - cached_zoom).abs();+    if dz <= 0.0 {+        return full_window_ms;+    }+    let age_secs = at.elapsed().as_secs_f64();+    if age_secs > 0.0 && dz / age_secs > FAST_ZOOM_PER_SEC {+        PLACE_REUSE_FAST_ZOOM_MS+    } else {+        full_window_ms+    }+}++impl PlacementKey {+    /// Bit-identity of everything but the camera pose: tiles and their stamps, filter, extent,+    /// sizes, and layer count. A drift-reuse candidate must match all of these; only+    /// centre/zoom/bearing/pitch may differ (within their thresholds — see `within_drift`).+    /// Any universe change is a hard re-place.+    pub(super) fn same_universe(&self, other: &PlacementKey) -> bool {+        self.width_dp == other.width_dp+            && self.height_dp == other.height_dp+            && self.density == other.density+            && self.extent == other.extent+            && self.filter == other.filter+            && self.tiles == other.tiles+            && self.layers == other.layers+    }+}++/// Everything one label's collision box depends on besides its anchor.+///+/// Built once per label and reused for each candidate anchor, so the two boxes a POI is+/// tried at can only differ in where they sit — not in how big they are.+pub(super) fn box_inputs(+    layer: &Layer,+    label: &geometry::ShapedLabel,+    camera: &Camera,+) -> crate::tile::placement::BoxInputs {+    box_inputs_with_arms(layer, label, camera, layer.text_size_arms(camera.zoom))+}++/// [`box_inputs`], but with the style's text-size arms already resolved for this+/// (layer, zoom) — see [`Layer::text_size_arms`]. The per-label call resolves two+/// style ramps per label; the per-layer caller resolves them once and answers each+/// label with a float compare. Bit-identical values either way.+pub(super) fn box_inputs_with_arms(+    layer: &Layer,+    label: &geometry::ShapedLabel,+    camera: &Camera,+    arms: (f32, Option<f32>, Option<f32>),+) -> crate::tile::placement::BoxInputs {+    crate::tile::placement::BoxInputs {+        text_px: Layer::text_size_with_arms(label.pop, arms.0, arms.1, arms.2) * camera.density,+        advance: label.total_advance,+        line_count: label.lines.len(),+        offset_em: layer.text_offset,+        // Dp from the sheet, device px here — the same conversion `emit_icon` makes.+        icon_px: label+            .sprite+            .map(|s| (s.width_dp * camera.density, s.height_dp * camera.density)),+        pad_px: collision_padding_px(camera.zoom),+    }+}++/// Collision padding in device px around every label box, by camera zoom.+///+/// MapLibre pads every label (icon + text padding, growing at low zoom via+/// the icon-padding ramp), which is what holds z6 to ~10 cities while z14+/// stays dense. Without it tight advance boxes let hundreds of villages+/// survive at z6. 24px at z6 and below culls hamlets against towns; 4px at+/// z14+ keeps street labels tight. Linear between.+fn collision_padding_px(zoom: f64) -> f32 {+    if zoom <= 6.0 {+        24.0+    } else if zoom >= 14.0 {+        4.0+    } else {+        (24.0 - (zoom - 6.0) * (20.0 / 8.0)) as f32+    }+}