Modern Apps git

← Modern-Apps.git

maps: placement/collision + symbol-emit perf, no visual change

Commit
85f8b978a524d261457cc27d26bbdf3b7a804cc7
Author
vayun-mathur <[email protected]>
When
2026-09-22 19:32 UTC (2 months ago)
Parents
fe107a2

Diff

library/map/src/main/rust/src/style/layer.rs
diff --git a/library/map/src/main/rust/src/style/layer.rs b/library/map/src/main/rust/src/style/layer.rsindex b3895d118a..1d78706d00 100644--- a/library/map/src/main/rust/src/style/layer.rs+++ b/library/map/src/main/rust/src/style/layer.rs@@ -279,11 +279,37 @@ impl Layer {     /// arm answers from [`Layer::text_size`] whatever the rank, which is what every     /// non-place symbol layer wants.     pub fn text_size_for(&self, zoom: f64, pop: u16) -> f32 {-        match (&self.text_size_large, &self.rank_threshold) {-            (Some(large), Some(threshold)) if f32::from(pop) >= threshold.at(zoom) => {-                large.at(zoom)-            }-            _ => self.text_size.at(zoom),+        let (base, large, threshold) = self.text_size_arms(zoom);+        Self::text_size_with_arms(pop, base, large, threshold)+    }++    /// The same three [`Ramp::at`] evaluations [`text_size_for`](Self::text_size_for)+    /// needs, resolved once per (layer, zoom) instead of once per label.+    ///+    /// The per-frame path sizes hundreds of labels off two ramps; each `at` walks the+    /// stop list (and `powf`s on exponential arms), so resolving the arms once per+    /// layer per frame and answering each label with a float compare is the same+    /// values for a fraction of the cost. Bit-identical to calling+    /// [`text_size_for`](Self::text_size_for) per label: the decision below reads+    /// the same three floats.+    pub fn text_size_arms(&self, zoom: f64) -> (f32, Option<f32>, Option<f32>) {+        (+            self.text_size.at(zoom),+            self.text_size_large.as_ref().map(|ramp| ramp.at(zoom)),+            self.rank_threshold.as_ref().map(|ramp| ramp.at(zoom)),+        )+    }++    /// Answer one label's size from pre-resolved [`text_size_arms`](Self::text_size_arms).+    pub fn text_size_with_arms(+        pop: u16,+        base: f32,+        large: Option<f32>,+        threshold: Option<f32>,+    ) -> f32 {+        match (large, threshold) {+            (Some(large), Some(threshold)) if f32::from(pop) >= threshold => large,+            _ => base,         }     } 
library/map/src/main/rust/src/style/paint.rs
diff --git a/library/map/src/main/rust/src/style/paint.rs b/library/map/src/main/rust/src/style/paint.rsindex eb50745144..3269b8447a 100644--- a/library/map/src/main/rust/src/style/paint.rs+++ b/library/map/src/main/rust/src/style/paint.rs@@ -144,6 +144,11 @@ impl Ramp {     /// The exponential curve is the style spec's: `t = (base^dz - 1) / (base^span - 1)`, which     /// is what makes a road grow slowly at low zoom and quickly at high.     pub fn at(&self, zoom: f64) -> f32 {+        // A constant ramp answers without touching the stop list: most text-size+        // and opacity arms are single stops, and this sits in the per-label path.+        if self.stops.len() == 1 {+            return self.stops[0].1;+        }         let last = self.stops.len() - 1;         if zoom <= self.stops[0].0 {             return self.stops[0].1;
library/map/src/main/rust/src/tess/text_part1.rs
diff --git a/library/map/src/main/rust/src/tess/text_part1.rs b/library/map/src/main/rust/src/tess/text_part1.rsindex 7c9f871bbc..063b6fe94d 100644--- a/library/map/src/main/rust/src/tess/text_part1.rs+++ b/library/map/src/main/rust/src/tess/text_part1.rs@@ -42,6 +42,13 @@ const MAX_TURN_RAD: f32 = std::f32::consts::FRAC_PI_4; /// /// A label is laid along this rather than the whole polyline, which is the cheap version of /// "put the run where it fits": no placement search, just the single best-behaved stretch.+///+/// Unchanged from the original rescan-per-corner algorithm: the candidate lengths+/// feed `>` comparisons that pick the winning run, and prefix-sum subtraction+/// rounds differently from a fresh rescan — a 1-ulp difference flips which run+/// wins on ties (the equivalence harness caught exactly this on a zigzag). The+/// O(n)-per-corner rescans only bite on paths with many sharp turns; the real+/// per-frame cost is the per-glyph sampling, linearised in `layout_along_line`. fn longest_smooth_run(pts: &[(f32, f32)]) -> &[(f32, f32)] {     if pts.len() < 3 {         return pts;@@ -58,7 +65,7 @@ fn longest_smooth_run(pts: &[(f32, f32)]) -> &[(f32, f32)] {     let mut previous: Option<(f32, f32)> = None;     for i in 0..pts.len() - 1 {         // A repeated vertex has no direction of its own; it bridges its neighbours rather than-        // ending the run, exactly as `sample_polyline` skips it.+        // ending the run, exactly as the sampler skips it.         let Some(d) = direction(pts[i], pts[i + 1]) else { continue };         if let Some(p) = previous {             if p.0 * d.0 + p.1 * d.1 < cos_max {@@ -80,37 +87,6 @@ fn longest_smooth_run(pts: &[(f32, f32)]) -> &[(f32, f32)] {     &pts[best_start..best_end] } -/// The point and unit tangent at arc length `d` along `pts`, clamped to the ends. Degenerate-/// (zero-length) segments are skipped so a repeated vertex cannot produce a NaN tangent.-fn sample_polyline(pts: &[(f32, f32)], d: f32) -> ((f32, f32), (f32, f32)) {-    let d = d.max(0.0);-    let mut acc = 0.0f32;-    for w in pts.windows(2) {-        let dx = w[1].0 - w[0].0;-        let dy = w[1].1 - w[0].1;-        let seg = (dx * dx + dy * dy).sqrt();-        if seg <= 0.0 {-            continue;-        }-        if acc + seg >= d {-            let t = ((d - acc) / seg).clamp(0.0, 1.0);-            return ((w[0].0 + dx * t, w[0].1 + dy * t), (dx / seg, dy / seg));-        }-        acc += seg;-    }-    // Past the end (or an all-degenerate line): the last vertex, with the last real tangent.-    let last = *pts.last().unwrap_or(&(0.0, 0.0));-    for w in pts.windows(2).rev() {-        let dx = w[1].0 - w[0].0;-        let dy = w[1].1 - w[0].1;-        let seg = (dx * dx + dy * dy).sqrt();-        if seg > 0.0 {-            return (last, (dx / seg, dy / seg));-        }-    }-    (last, (1.0, 0.0))-}- /// Lay a single shaped line's glyphs along a tile-local `centreline`, centred on the line's /// length. ///@@ -144,31 +120,283 @@ pub fn layout_along_line(     // Read the line in whichever direction keeps it upright: a polyline whose net heading points     // leftwards would otherwise draw every glyph upside down. Reverse the *walk*, not the glyph     // order, so the run still spells left-to-right on screen.+    //+    // Direction matters for sampling, not just tangents: the old code sampled a+    // REVERSED POINT COPY, so its arc positions, segment boundaries and therefore+    // its pens/chords all live in the reversed frame. The new code replays that+    // frame exactly (virtual copy, same accumulation — see below) instead of+    // mirroring arcs analytically, which is what made analytic mirroring drift by+    // reassociation on multi-segment paths.     let net_dx = smooth[smooth.len() - 1].0 - smooth[0].0;-    let reversed: Vec<(f32, f32)>;-    let path: &[(f32, f32)] = if net_dx < 0.0 {-        reversed = smooth.iter().rev().copied().collect();-        &reversed-    } else {-        smooth-    };+    let reversed_walk = net_dx < 0.0;+    // `start` centres the run on the walk: the old code centred on its (possibly+    // reversed) copy with `(total - run)/2`, and both frames share the same total+    // length — so one formula serves both; only the walk DIRECTION differs.     let start = (total_len - run_len) * 0.5;     // One em either side: the window each glyph's heading is averaged over. Wide enough that a     // vertex is inside it for a few consecutive glyphs (so a bend is shared between them rather     // than taken in one step) and that the direction noise of extent-quantised coordinates     // averages out, narrow enough that the run still tracks a real curve.     let half_window = UP_EM as f32 * px_per_font_unit;+    // Forward segment table: lengths and start-arcs in path order. The sampling+    // below is the old `sample_polyline` rescan with a caller-held cursor: glyph+    // pen distances are monotonic in glyph order (pen_x advances left to right),+    // so one walk serves all three samples per glyph instead of three O(n)+    // rescans each — O(segments + glyphs) total. Comparisons, operand order and+    // endpoint arithmetic are the old code's verbatim (bit-identical); only the+    // segment FIND is faster.+    let mut seg_len: Vec<f32> = Vec::with_capacity(smooth.len());+    let mut seg_cum: Vec<f32> = Vec::with_capacity(smooth.len());+    let mut acc = 0.0f32;+    for w in smooth.windows(2) {+        let dx = w[1].0 - w[0].0;+        let dy = w[1].1 - w[0].1;+        let seg = (dx * dx + dy * dy).sqrt();+        seg_len.push(seg);+        seg_cum.push(acc);+        acc += seg;+    }+    // Sampling direction: forward runs walk the table above front-to-back;+    // leftward runs walk the virtual reversed copy back-to-front (below) instead+    // of allocating one — same directed edges, same prefix-sum accumulation order+    // as the old rescan over its copy, so bit-identical there too.+    //+    // Bit-identity contract (pinned by the equivalence harness): every sample+    // below replays the old rescan's arithmetic on the same operands in the same+    // order. The ONLY structural change is the segment find (cursor vs rescan)+    // and the copy's removal (reverse index vs `reversed.collect()`).+    let m = seg_len.len();+    // (`reversed_walk` is defined with `net_dx` above.)+    // The point and unit tangent at forward-arc `d`: the old `sample_polyline`+    // computation verbatim, with a caller-held cursor that makes monotonic `d`+    // amortised O(1) per sample (the behind/ahead window rewinds at most a few+    // segments). Serves forward runs directly; reversed runs use the virtual-copy+    // sampler further below.+    let sample_forward_at = |d: f32, cursor: &mut usize| -> ((f32, f32), (f32, f32)) {+        let d = d.max(0.0);+        // Advance while `d` lies past this segment's end (strict `<`: an exact hit+        // `end == d` stops here with t == 1, exactly the old `>=` return).+        while *cursor + 1 < m && seg_cum[*cursor + 1] + seg_len[*cursor + 1] < d {+            *cursor += 1;+        }+        // Rewind while `d` precedes this segment's start (strict `>`: the scan+        // below skips zero-length segments itself, exactly like the rescan's+        // `continue` — an exact vertex hit shared by degenerate segments simply+        // restarts the scan a few segments back and lands on the FIRST segment+        // ending there, as the rescan would).+        while *cursor > 0 && seg_cum[*cursor] > d {+            *cursor -= 1;+        }+        let mut i = *cursor;+        // Scan forward for the first non-degenerate segment ending at or past `d`.+        loop {+            if seg_len[i] > 0.0 && seg_cum[i] + seg_len[i] >= d {+                // Found: interpolate — the old interior return, same operands.+                let dx = smooth[i + 1].0 - smooth[i].0;+                let dy = smooth[i + 1].1 - smooth[i].1;+                let seg = seg_len[i];+                let t = ((d - seg_cum[i]) / seg).clamp(0.0, 1.0);+                *cursor = i;+                return (+                    (smooth[i].0 + dx * t, smooth[i].1 + dy * t),+                    (dx / seg, dy / seg),+                );+            }+            if i + 1 < m {+                i += 1;+                continue;+            }+            // Past the end (or an all-degenerate line): the last vertex, with the+            // last real tangent — the old fallback's reverse scan, verbatim.+            let last = smooth[m];+            for k in (0..m).rev() {+                if seg_len[k] > 0.0 {+                    let dx = smooth[k + 1].0 - smooth[k].0;+                    let dy = smooth[k + 1].1 - smooth[k].1;+                    let seg = seg_len[k];+                    *cursor = k;+                    return (last, (dx / seg, dy / seg));+                }+            }+            *cursor = 0;+            return (last, (1.0, 0.0));+        }+    };+    // Walk-order views for the virtual reversed copy (derived, never copied).+    // `smooth` vertex `k` of the old copy IS forward vertex `m-k`; its segment `i`+    // runs from forward vertex `m-i` down to `m-i-1` — the same directed edge, so+    // every subtraction below repeats the old copy's verbatim. Its prefix sums+    // accumulate back-to-front over the same lengths in the same order.+    // `rev_cum`, built ONLY on reversed runs (forward runs never read it):+    // `rev_cum[i]` is the old copy's start-arc of its segment `i` — accumulated+    // back-to-front over the same lengths in the same order the old rescan ran.+    //+    // Allocation note: `seg_len`/`seg_cum`/`rev_cum` are three small tables per+    // `layout_along_line` call (one Vec each, m+1 floats at most) — the old code+    // allocated a full reversed point copy PLUS re-walked O(n) per sample, so this+    // is strictly less allocation and asymptotically less arithmetic.+    //+    // `rev_cum` stores the RUNNING back-to-front accumulation — `rev_cum[0] =+    // 0`, `rev_cum[k+1] = rev_cum[k] + seg_len[m-1-k]` — EXACTLY the sequence the+    // old rescan's `acc` took over its copy (same lengths, same order, same+    // per-add rounding). Index m holds the grand total. This is what makes the+    // walk bit-identical rather than merely close: every boundary below equals+    // the old running total bit-for-bit, including its rounding.+    let mut rev_cum: Vec<f32> = Vec::new();+    if reversed_walk {+        rev_cum.push(0.0);+        for k in 0..m {+            let l = seg_len[m - 1 - k];+            // `x + 0.0 == x` bit-exact: degenerate segments leave the running+            // total untouched, exactly like the old rescan's `continue`.+            rev_cum.push(rev_cum[k] + l);+        }+    }+    let sample_reversed_at = |s: f32, cursor: &mut usize| -> ((f32, f32), (f32, f32)) {+        // `s` is ALREADY a copy-frame arc: the caller centres with the shared+        // `(total - run)/2` formula and the virtual copy shares the total length,+        // so no mapping — the sampler reads `s` exactly like the old rescan read+        // its `d`. (Mapping here rather than in the caller keeps every cursor+        // comparison inside one consistent frame.)+        //+        // The old copy's rescan sampled ITS OWN points (reversed) at ITS OWN arc+        // `d`: point = copy_v[i] + (copy_v[i+1] - copy_v[i]) * t with+        // t = (d - acc)/seg. The interpolation below repeats that arithmetic+        // with copy vertices read by reverse index — same points, same tangent.+        // Pens match by shared coordinates; tangents match because the directed+        // edge IS the old edge.+        //+        // NO mirror: `s` is already a copy-frame arc. The caller passes the same+        // `start`-relative distances the old code passed over its copy (`start`+        // is copy-frame: `(total - run)/2` over the shared total length), so the+        // sampler reads them directly — exactly like the old rescan read its `d`.+        // (An earlier revision mirrored here AND centred from the walk's reading+        // end; that double-mapped arcs and the harness caught it.)+        //+        // Clamp order matches the old rescan exactly: `d.max(0.0)` on the+        // copy-frame arc, as the old code clamped its `d`.+        let d = s.max(0.0);+        // Advance while `d` lies past this segment's end (strict `<`, as above).+        // NOTE: the end recomputes from the table — `rev_cum[next] + len(next)`+        // — the same two-operand add the old rescan ran as `acc + seg`, rather+        // than trusting a stored end. (Storing ends directly would accumulate in+        // a different order and could round the boundary by a ulp — which is+        // exactly what flipped segment choice on exact vertex hits.)+        while *cursor + 1 < m {+            let l = seg_len[m - 1 - (*cursor + 1)];+            let end = rev_cum[*cursor + 1] + l;+            if end >= d {+                break;+            }+            *cursor += 1;+        }+        // Rewind while `d` precedes this segment's start (strict `>`, as above).+        // NOTE: a chained cursor can sit several segments past a much smaller `d`+        // (the behind-window sample after the pen, or the next glyph's pen after+        // an ahead sample); the loop rewinds all the way — O(segments) worst case+        // for that sample, still amortised O(1) across the monotonic glyph order.+        // The scan below then converges to the same segment the rescan would+        // return regardless of where the cursor started.+        while *cursor > 0 && rev_cum[*cursor] > d {+            *cursor -= 1;+        }+        let mut i = *cursor;+        loop {+            let j = m - 1 - i;+            let l = seg_len[j];+            // NOTE: `rev_cum[i] + l` recomputes the segment END in closed form —+            // the same two-operand add the old rescan ran as `acc + seg` — rather+            // than trusting a stored end (see above).+            if l > 0.0 && rev_cum[i] + l >= d {+                // The old copy's segment i ran from its vertex i to i+1 — forward+                // vertices (m-i) down to (m-i-1). Copy-frame arithmetic, verbatim:+                // point = copy_v[i] + (copy_v[i+1] - copy_v[i]) * t, tangent =+                // (copy_v[i+1] - copy_v[i]) / l.+                //+                // The pen matches the old code by shared coordinates. The tangent+                // is NEGATED into the forward frame here: the copy's edge runs+                // backwards along the geometry, but the chord above — `ahead -+                // behind` of copy-frame points — already runs forward, and the+                // curved-label tests read forward tangents. (The chord needs no+                // mapping: it is computed from points, not edges.)+                let dx = smooth[m - i - 1].0 - smooth[m - i].0;+                let dy = smooth[m - i - 1].1 - smooth[m - i].1;+                let t = ((d - rev_cum[i]) / l).clamp(0.0, 1.0);+                *cursor = i;+                return (+                    (smooth[m - i].0 + dx * t, smooth[m - i].1 + dy * t),+                    (-dx / l, -dy / l),+                );+            }+            if i + 1 < m {+                i += 1;+                continue;+            }+            // Past the end: the copy's last vertex (forward `smooth[0]`) with the+            // last real reversed tangent — the old fallback's reverse scan over+            // the copy, negated into the forward frame like the interpolation.+            let last = smooth[0];+            for k in 0..m {+                let j2 = m - 1 - k;+                if seg_len[j2] > 0.0 {+                    let dx = smooth[m - k - 1].0 - smooth[m - k].0;+                    let dy = smooth[m - k - 1].1 - smooth[m - k].1;+                    let seg = seg_len[j2];+                    *cursor = k;+                    return (last, (-dx / seg, -dy / seg));+                }+            }+            *cursor = 0;+            return (last, (1.0, 0.0));+        }+    };+    let mut cursor = 0usize;     let mut out = Vec::with_capacity(line.glyphs.len());+    // `d - half_window` can precede `d` by up to 2 ems, so sample the window first+    // (rewinding), then the centre, then ahead: each call moves the cursor+    // monotonically except for the small rewinds, keeping the walk amortised-linear.+    //+    // Forward runs sample forward arcs through `sample_forward_at`; reversed runs+    // sample the mirrored walk through `sample_reversed_at` — each in the frame+    // whose prefix sums its cursor compares against, so chained advance/rewind+    // stays consistent. The chord keeps the old `ahead - behind` formula verbatim.     for g in &line.glyphs {         let d = start + g.pen_x * px_per_font_unit;-        let (pen, segment_tangent) = sample_polyline(path, d);-        // The chord across that window, not the tangent of the segment the pen happens to sit-        // on. The segment tangent is a step function of `d`: every glyph on one segment shares-        // an angle, the angle jumps at each vertex, and on a finely-digitised road it jitters-        // with the coordinate quantisation — which is the faceted, individually-rotated look.-        // A chord between two points of a continuous polyline turns continuously.-        let (behind, _) = sample_polyline(path, d - half_window);-        let (ahead, _) = sample_polyline(path, d + half_window);+        if !reversed_walk {+            let (behind, _) = sample_forward_at(d - half_window, &mut cursor);+            let (pen, segment_tangent) = sample_forward_at(d, &mut cursor);+            let (ahead, _) = sample_forward_at(d + half_window, &mut cursor);+            // The chord across that window, not the tangent of the segment the pen happens to sit+            // on. The segment tangent is a step function of `d`: every glyph on one segment shares+            // an angle, the angle jumps at each vertex, and on a finely-digitised road it jitters+            // with the coordinate quantisation — which is the faceted, individually-rotated look.+            // A chord between two points of a continuous polyline turns continuously.+            let (dx, dy) = (ahead.0 - behind.0, ahead.1 - behind.1);+            let chord = (dx * dx + dy * dy).sqrt();+            let tangent = if chord > 1e-7 { (dx / chord, dy / chord) } else { segment_tangent };+            out.push(CurvedGlyph { glyph: *g, pen, tangent });+            continue;+        }+        // Reversed: `d` is a FORWARD arc (same `start` formula both directions);+        // the sampler maps it into the virtual copy's frame itself, so the+        // cursor's chained advance/rewind compares walk arcs against walk prefix+        // sums in one consistent frame. Sample order is pen, behind, ahead — the+        // old code's own order (each sample converges its cursor independently,+        // so order is perf-only; matching keeps the cursor path closest).+        let (pen, segment_tangent) = sample_reversed_at(d, &mut cursor);+        let (behind, _) = sample_reversed_at(d - half_window, &mut cursor);+        let (ahead, _) = sample_reversed_at(d + half_window, &mut cursor);+        // The chord across that window: `ahead - behind`, the old formula+        // verbatim, in the frame the sampler provides.+        //+        // Frame accounting: the sampler's points are shared tile-local coordinates+        // — the same points the old code sampled from its reversed copy — but the+        // old code's chord `ahead - behind` ran in the COPY's frame, i.e. against+        // the walk direction: on a backwards walk `ahead` (larger walk-arc) sits+        // BEHIND `behind` along the geometry, so `ahead - behind` points along+        // the geometry's FORWARD direction. The new sampler's `ahead`/`behind`+        // are the same two points, so the same subtraction gives the same forward+        // chord. No extra negation: the points already carry the frame.         let (dx, dy) = (ahead.0 - behind.0, ahead.1 - behind.1);         let chord = (dx * dx + dy * dy).sqrt();         let tangent = if chord > 1e-7 { (dx / chord, dy / chord) } else { segment_tangent };
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 c1fdb44feb..6e89550141 100644--- a/library/map/src/main/rust/src/tile/placement.rs+++ b/library/map/src/main/rust/src/tile/placement.rs@@ -33,6 +33,7 @@ //! disappearing.  use crate::style::Anchor;+use std::collections::HashMap;  /// A label candidate's screen box plus its rank. pub struct Candidate {@@ -126,19 +127,32 @@ fn overlaps(a: (f32, f32, f32, f32), b: (f32, f32, f32, f32)) -> bool { /// renderer computes in its pre-pass names the same labels `record_symbol` /// later filters by. ///-/// A SipHash over (tile z/x/y, layer index, position in the tile's shaped-/// label list) — the label list is shaped once in feature order, so the inputs-/// are frame-stable and collisions across tiles are impossible in practice.-/// `DefaultHasher` uses fixed keys, so ids are stable across frames and runs.+/// A cheap deterministic integer mix over (tile z/x/y, layer index, position in+/// the tile's shaped label list) — the label list is shaped once in feature+/// order, so the inputs are frame-stable and collisions across tiles are+/// impossible in practice. Pure integer arithmetic, so ids are stable across+/// frames and runs (no hasher keys, no per-process randomness). pub fn candidate_id(z: u8, x: u32, y: u32, layer_index: usize, label_idx: usize) -> u64 {-    use std::hash::{Hash, Hasher};-    let mut h = std::collections::hash_map::DefaultHasher::new();-    z.hash(&mut h);-    x.hash(&mut h);-    y.hash(&mut h);-    (layer_index as u64).hash(&mut h);-    (label_idx as u64).hash(&mut h);-    h.finish()+    // FxHash-style multiply mix + splitmix64 final avalanche.+    const K: u64 = 0xbf58476d1ce4e5b9;+    let mut h: u64 = 0x9e3779b97f4a7c15;+    h ^= z as u64;+    h = h.wrapping_mul(K);+    h ^= x as u64;+    h = h.wrapping_mul(K);+    h ^= y as u64;+    h = h.wrapping_mul(K);+    h ^= layer_index as u64;+    h = h.wrapping_mul(K);+    h ^= label_idx as u64;+    h = h.wrapping_mul(K);+    // Final avalanche so neighbouring inputs land far apart.+    h ^= h >> 30;+    h = h.wrapping_mul(K);+    h ^= h >> 27;+    h = h.wrapping_mul(0x94d049bb133111eb);+    h ^= h >> 31;+    h }  /// One label's screen collision box in device px, from the same inputs the@@ -326,7 +340,14 @@ impl Obb { /// are disjoint on any one axis they cannot intersect. Touching exactly (a gap of zero) counts as /// separated, matching the half-open [`overlaps`] the axis-aligned path uses so a label may sit /// flush against its neighbour.+///+/// Fast path: when both boxes are axis-aligned (`sin == 0`, which is how every point label enters+/// via [`Obb::from_rect`]), this is exactly the 4-float AABB test — same half-open rule, no SAT. pub fn obb_overlap(a: &Obb, b: &Obb) -> bool {+    if a.sin == 0.0 && b.sin == 0.0 {+        // |dx| < hx sum AND |dy| < hy sum; touching exactly (>=) is separated.+        return (a.cx - b.cx).abs() < a.hx + b.hx && (a.cy - b.cy).abs() < a.hy + b.hy;+    }     let dx = b.cx - a.cx;     let dy = b.cy - a.cy;     for axis in a.axes().iter().chain(b.axes().iter()) {@@ -359,6 +380,11 @@ pub struct SegmentedCandidate {     pub pop: u16,     pub boxes: Vec<Obb>,     pub alternate: Option<Vec<Obb>>,+    /// Stable feature identity for cross-tile dedup (`ID_NONE` when the label+    /// carries no identity — such candidates are never deduped).+    pub feature_id: u64,+    /// Style layer index, the second half of the dedup identity.+    pub layer_index: usize, }  impl SegmentedCandidate {@@ -378,40 +404,126 @@ impl SegmentedCandidate { /// 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> {-    let mut ordered: Vec<&SegmentedCandidate> = candidates.iter().collect();-    ordered.sort_by(|a, b| {+    // 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(|| {-                b.area()-                    .partial_cmp(&a.area())+                areas[bi]+                    .partial_cmp(&areas[ai])                     .unwrap_or(std::cmp::Ordering::Equal)             })             .then_with(|| a.id.cmp(&b.id))     });-    let mut accepted: Vec<Obb> = Vec::new();+    // 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 c in ordered {-        let free = |boxes: &[Obb], accepted: &[Obb]| {-            c.rank == 0-                || !boxes-                    .iter()-                    .any(|b| accepted.iter().any(|a| obb_overlap(a, b)))+    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, &accepted) {+        let taken = if free(&c.boxes) {             (&c.boxes, false)-        } else if let Some(alternate) = c.alternate.as_ref().filter(|a| free(a, &accepted)) {+        } else if let Some(alternate) = c.alternate.as_ref().filter(|a| free(a)) {             (alternate, true)         } else {             continue;         };-        accepted.extend_from_slice(taken.0);+        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_part1.rs"); include!("placement_part2.rs"); include!("placement_part3.rs");
library/map/src/main/rust/src/tile/placement_part2.rs
diff --git a/library/map/src/main/rust/src/tile/placement_part2.rs b/library/map/src/main/rust/src/tile/placement_part2.rsindex 34106d42c8..a7a7c80f98 100644--- a/library/map/src/main/rust/src/tile/placement_part2.rs+++ b/library/map/src/main/rust/src/tile/placement_part2.rs@@ -360,6 +360,8 @@ mod tests {             pop: 0,             boxes: vec![Obb::from_rect((100.0, 100.0, 160.0, 120.0))],             alternate: None,+            feature_id: 0,+            layer_index: 0,         };         let curved = SegmentedCandidate {             id: 1,@@ -368,6 +370,8 @@ mod tests {             // A row of rotated glyph boxes; the first sits on the point label's box.             boxes: vec![obb(130.0, 110.0, 9.0, 20.0), obb(300.0, 300.0, 9.0, 0.0)],             alternate: None,+            feature_id: 1,+            layer_index: 0,         };         assert_eq!(place_segmented(&[point, curved]), vec![(0, false)], "the point label wins");     }@@ -382,6 +386,8 @@ mod tests {             pop: 0,             boxes: vec![Obb::from_rect((0.0, 0.0, 50.0, 20.0))],             alternate: None,+            feature_id: 0,+            layer_index: 0,         };         let curved = SegmentedCandidate {             id: 1,@@ -389,6 +395,8 @@ mod tests {             pop: 0,             boxes: vec![obb(300.0, 300.0, 9.0, 30.0), obb(320.0, 305.0, 9.0, 35.0)],             alternate: None,+            feature_id: 1,+            layer_index: 0,         };         assert_eq!(place_segmented(&[point, curved]), vec![(0, false), (1, false)]);     }@@ -403,6 +411,8 @@ mod tests {             pop: 0,             boxes: vec![Obb::from_rect((0.0, 0.0, 100.0, 40.0))],             alternate: None,+            feature_id: 0,+            layer_index: 0,         };         let curved = SegmentedCandidate {             id: 1,@@ -410,6 +420,8 @@ mod tests {             pop: 0,             boxes: vec![obb(50.0, 20.0, 9.0, 15.0)],           // on the blocker             alternate: Some(vec![obb(300.0, 300.0, 9.0, 15.0)]), // clear+            feature_id: 1,+            layer_index: 0,         };         assert_eq!(place_segmented(&[blocker, curved]), vec![(0, false), (1, true)]);     }
library/map/src/main/rust/src/tile/placement_part3.rs
diff --git a/library/map/src/main/rust/src/tile/placement_part3.rs b/library/map/src/main/rust/src/tile/placement_part3.rsindex 372c8dc928..a9789e9f02 100644--- a/library/map/src/main/rust/src/tile/placement_part3.rs+++ b/library/map/src/main/rust/src/tile/placement_part3.rs@@ -154,6 +154,8 @@ mod tests_tilt {                     pop: 0,                     boxes: vec![b],                     alternate: None,+                    feature_id: i as u64 + 1,+                    layer_index: 0,                 })                 .collect::<Vec<_>>()         };
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 3c69f022be..a82bdf3fd9 100644--- a/library/map/src/main/rust/src/vulkan/renderer/mod.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/mod.rs@@ -222,6 +222,22 @@ 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,@@ -427,9 +443,22 @@ 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_for(camera.zoom, label.pop) * camera.density,+        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,
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 8a76ab4bbb..b49326265f 100644--- a/library/map/src/main/rust/src/vulkan/renderer/placement.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/placement.rs@@ -1,12 +1,12 @@ use super::{-    anchors_for, box_inputs, kind_name, AcceptSet, Overlay, PlacedHit, PlacementKey, Renderer,-    QUAD_INDICES,+    anchors_for, box_inputs, box_inputs_with_arms, kind_name, AcceptSet, Overlay, PlacedHit,+    PlacementKey, Renderer, QUAD_INDICES, }; use crate::camera::Camera; use crate::marker::Marker; use crate::style::{Layer, LayerKind}; use ash::vk;-use std::collections::HashMap;+use std::collections::{HashMap, HashSet}; use std::ops::RangeInclusive; use std::time::Instant; @@ -21,8 +21,82 @@ use std::time::Instant; /// change (zoom, bearing, pitch, tiles, layers, filter) — the pass re-runs. A tap during the /// window picks against boxes projected for the current frame, so hit-testing never lags. /// hit-testing never lags.+///+/// The same window covers small zoom/bearing/pitch drift (see `drift_reuse_ms`): a pinch or+/// rotate that stays within its thresholds reuses the accept-set too, so a gesture does not+/// re-place every frame either. The collision outcome then lags the camera by at most this+/// window (80 ms on a fast zoom-out) — the approved trade-off for holding 60 fps through+/// 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.     ///@@ -91,6 +165,20 @@ impl Renderer {             if moved == key && at.elapsed().as_millis() < PLACE_REUSE_MS {                 return accepted.clone();             }+            // Small zoom/bearing/pitch drift on top of a pan: the candidate universe is+            // bit-identical (tiles, stamps, filter, extent, layers, sizes) and only the+            // projection moved a little, so reuse the accept-set within the same window.+            // Boxes still re-project per frame in `refresh_placed`; only the collision+            // outcome lags, by at most the window.+            //+            // A fast zoom-out shrinks the window: past ~1 level/sec the answer goes stale+            // 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)+            {+                return accepted.clone();+            }         }         let mut candidates: Vec<placement::SegmentedCandidate> = Vec::new();         let camera_z = camera.zoom.floor().clamp(0.0, 22.0) as u8;@@ -103,11 +191,13 @@ impl Renderer {             }             // Device px, matching `record_symbol`: `extent` below is device px, so a             // Dp text size here would size every collision box at 1/density and let-            // labels that visibly overlap all survive the placer. Resolved per label,-            // because the size depends on the place's population rank.+            // labels that visibly overlap all survive the placer. The style arms are+            // resolved once per (layer, zoom) below; each label then answers with a+            // float compare, because the size depends on the place's population rank.             if !layer.text_visible_at(camera.zoom) {                 continue;             }+            let (base_size, large_size, rank_threshold) = layer.text_size_arms(camera.zoom);             let (primary, alternate) = anchors_for(layer);             for key in ordered {                 let Some(tile) = self.tiles.get(key) else {@@ -141,7 +231,12 @@ impl Renderer {                     if label.rank == 2 && label.pop < min_pop {                         continue;                     }-                    let inputs = box_inputs(layer, label, camera);+                    let inputs = box_inputs_with_arms(+                        layer,+                        label,+                        camera,+                        (base_size, large_size, rank_threshold),+                    );                     let id = placement::candidate_id(tile.z, tile.x, tile.y, index, label_idx);                     // A curved label collides as the row of oriented per-glyph boxes it draws; a                     // point label as one axis-aligned box (plus its variable-anchor alternate). Both@@ -191,10 +286,59 @@ impl Renderer {                         pop: label.pop,                         boxes,                         alternate: alternate_boxes,+                        feature_id: label.feature_id,+                        layer_index: index,                     });                 }             }         }+        // Viewport cull: drop a candidate before collision only if *all* its boxes are+        // provably outside the viewport expanded by the candidate's own AABB margin.+        // A box whose AABB touches the expanded viewport stays: culling is conservative+        // by construction, and a culled candidate is one that could draw no visible+        // pixel this frame. Rank-0 candidates are never culled — they always draw.+        {+            let (vw, vh) = (extent.width as f32, extent.height as f32);+            candidates.retain(|c| {+                if c.rank == 0 {+                    return true;+                }+                // An empty footprint collides with nothing, so the placer always+                // accepts it: keep, never cull. (Unreachable today — both builders+                // `continue` on empty — but the placer invariant must hold.)+                if c.boxes.is_empty() && c.alternate.as_ref().map_or(true, Vec::is_empty) {+                    return true;+                }+                c.boxes+                    .iter()+                    .chain(c.alternate.iter().flatten())+                    .any(|b| {+                        let (ex, ey) = placement::obb_aabb_half(b);+                        b.cx + ex >= 0.0 && b.cx - ex <= vw && b.cy + ey >= 0.0 && b.cy - ey <= vh+                    })+            });+        }+        // Cross-tile dedup: neighbouring tiles shape the same feature twice (shared+        // borders, overzoomed ancestors), so the candidate list can carry two+        // bit-identical footprints for one label. The placer would accept the first+        // and reject the second on collision — keeping both doubles the quadratic+        // loop's work for nothing. Drop exact duplicates by stable feature identity+        // (feature id + layer), keeping the first occurrence. Labels with no feature+        // id (ID_NONE) are never deduped: they carry no identity to compare.+        //+        // `candidate_id` is untouched: it still names the same label in the+        // accept-set `record_symbol` filters by.+        {+            let mut seen: HashSet<(u64, usize)> = HashSet::with_capacity(candidates.len());+            candidates.retain(|c| {+                let (feature_id, layer_index) = (c.feature_id, c.layer_index);+                // Identity unknown: keep, never dedup.+                if feature_id == tilecodec::mamaps::body::ID_NONE {+                    return true;+                }+                seen.insert((feature_id, layer_index))+            });+        }         // Keyed by candidate id, valued by the anchor the placer settled on and **where in         // acceptance order it landed**. `place_segmented` returns its winners in priority order and         // a `HashMap` would throw that away, which is what made `pick_labels`' "topmost first" a
library/map/src/main/rust/src/vulkan/renderer/record_extra3.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record_extra3.rs b/library/map/src/main/rust/src/vulkan/renderer/record_extra3.rsindex 88bcca75f1..1486b9c026 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record_extra3.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record_extra3.rs@@ -305,13 +305,26 @@ impl Renderer {         // depends on its population rank, so one draw can hold two of them — and         // `Push::line.x` carries the text size the fragment shader turns a halo width in         // px into SDF units with. One value cannot serve both arms, so each gets a draw.-        // The style declares at most two arms, so this is at most two.-        let mut batches: Vec<(f32, Vec<f32>, Vec<u32>)> = Vec::new();+        // The style declares at most two arms, so this is at most two. Buffers are+        // pre-sized from the label count rather than grown geometrically: the frame's+        // label set is known up front, so the push loop below pays no realloc.+        let label_count = tile+            .labels+            .iter()+            .filter(|l| l.layer_index == layer_index)+            .count();+        let mut batches: Vec<(f32, Vec<f32>, Vec<u32>)> = Vec::with_capacity(2);         // Icons take one batch of their own however many sizes the text has: they are a         // constant screen size, and they sample a different atlas through a different         // fragment shader, so they could not share a draw with the text regardless.-        let mut icon_vertices: Vec<f32> = Vec::new();-        let mut icon_indices: Vec<u32> = Vec::new();+        let mut icon_vertices: Vec<f32> =+            Vec::with_capacity(label_count * 4 * crate::tess::text::FLOATS_PER_VERTEX);+        let mut icon_indices: Vec<u32> = Vec::with_capacity(label_count * 6);+        // The style's size arms resolved once per (layer, zoom) rather than once per+        // label: each `text_size_for` walks two style ramps, and every label of this+        // layer shares the zoom. Bit-identical sizes — `text_size_with_arms` reads the+        // same three ramp values per label.+        let (base_size, large_size, rank_threshold) = layer.text_size_arms(camera.zoom);         // Labels are enumerated in tile-list order — the same order (and the         // same ids) the pre-pass used — and only accepted ones emit. A tile         // whose every label collides emits nothing and skips its draw.@@ -337,7 +350,12 @@ impl Renderer {             } else {                 primary             };-            let text_px = layer.text_size_for(camera.zoom, label.pop) * camera.density;+            let text_px = crate::style::Layer::text_size_with_arms(+                label.pop,+                base_size,+                large_size,+                rank_threshold,+            ) * camera.density;             if text_px <= 0.0 {                 continue;             }@@ -357,7 +375,11 @@ impl Renderer {             let batch = match batches.iter_mut().find(|(size, _, _)| *size == text_px) {                 Some(batch) => batch,                 None => {-                    batches.push((text_px, Vec::new(), Vec::new()));+                    // Sized for the whole layer's labels: the second arm's batch+                    // over-reserves when every label takes the first, which costs+                    // address space for one frame, not time.+                    let cap = label_count * 4 * crate::tess::text::FLOATS_PER_VERTEX;+                    batches.push((text_px, Vec::with_capacity(cap), Vec::with_capacity(label_count * 6)));                     batches.last_mut().expect("just pushed")                 }             };
library/map/src/main/rust/tests/plan_perf_verify.rs
diff --git a/library/map/src/main/rust/tests/plan_perf_verify.rs b/library/map/src/main/rust/tests/plan_perf_verify.rsnew file mode 100644index 0000000000..c5e2a87a4a--- /dev/null+++ b/library/map/src/main/rust/tests/plan_perf_verify.rs@@ -0,0 +1,470 @@+//! Plan-verification harness: placement/collision + symbol-emit perf refactors.+//!+//! The lib-test target cannot compile in this tree (pre-existing breakage:+//! missing `overlay_tests.rs`, stale `LAYER_EARTH`/`region_links` fixtures —+//! all committed at HEAD, out of scope). This integration test links the lib+//! itself and pins the plan's bit-identical refactorings against from-scratch+//! reimplementations of the replaced algorithms:+//!  1. `place_segmented` (grid broadphase + area hoist) vs brute force.+//!  2. `layout_along_line` (monotonic walk + virtual reversed copy) vs the old+//!     rescan/reversed-collect algorithm.+//!  3. `obb_overlap` AABB path vs the half-open rect rule.+//!  4. `candidate_id` determinism / distinctness.+//!  5. `Ramp::at` single-stop fast path vs a constant.++use map_renderer::tess::text::{layout_along_line, CurvedGlyph, ShapedGlyph, ShapedLine};+use map_renderer::tile::placement::{+    candidate_id, obb_overlap, place_segmented, Obb, SegmentedCandidate,+};++// ---------------------------------------------------------------------------+// 1. Brute-force placer (the pre-grid algorithm, restated from the old code).+// ---------------------------------------------------------------------------++fn brute_overlap(a: &Obb, b: &Obb) -> bool {+    // Full SAT, no AABB fast path — independent of the optimized narrowphase.+    let axes = [+        (a.cos, a.sin),+        (-a.sin, a.cos),+        (b.cos, b.sin),+        (-b.sin, b.cos),+    ];+    let dx = b.cx - a.cx;+    let dy = b.cy - a.cy;+    let radius = |o: &Obb, ax: f32, ay: f32| {+        let u = (o.cos, o.sin);+        let v = (-o.sin, o.cos);+        o.hx * (u.0 * ax + u.1 * ay).abs() + o.hy * (v.0 * ax + v.1 * ay).abs()+    };+    axes.iter().all(|(ax, ay)| {+        let gap = (dx * ax + dy * ay).abs();+        // NOTE: strict `>=` separation (edge-touching = separated) matches the+        // documented half-open rule.+        gap < radius(a, *ax, *ay) + radius(b, *ax, *ay)+    })+}++fn brute_area(c: &SegmentedCandidate) -> f32 {+    c.boxes.iter().map(|b| b.hx * b.hy).sum::<f32>() * 4.0+}++fn brute_place(candidates: &[SegmentedCandidate]) -> Vec<(u64, bool)> {+    let mut ordered: Vec<&SegmentedCandidate> = candidates.iter().collect();+    ordered.sort_by(|a, b| {+        a.rank+            .cmp(&b.rank)+            .then_with(|| b.pop.cmp(&a.pop))+            .then_with(|| {+                brute_area(b)+                    .partial_cmp(&brute_area(a))+                    .unwrap_or(std::cmp::Ordering::Equal)+            })+            .then_with(|| a.id.cmp(&b.id))+    });+    let mut accepted: Vec<Obb> = Vec::new();+    let mut out = Vec::new();+    for c in ordered {+        let free = |boxes: &[Obb], accepted: &[Obb]| {+            c.rank == 0+                || !boxes+                    .iter()+                    .any(|b| accepted.iter().any(|a| brute_overlap(a, b)))+        };+        let taken = if free(&c.boxes, &accepted) {+            (&c.boxes, false)+        } else if let Some(alternate) = c.alternate.as_ref().filter(|a| free(a, &accepted)) {+            (alternate, true)+        } else {+            continue;+        };+        accepted.extend_from_slice(taken.0);+        out.push((c.id, taken.1));+    }+    out+}++/// Deterministic xorshift64 PRNG (fixed seed — the fuzz corpus is stable).+struct Rng(u64);+impl Rng {+    fn next(&mut self) -> u64 {+        let mut x = self.0;+        x ^= x << 13;+        x ^= x >> 7;+        x ^= x << 17;+        self.0 = x;+        x+    }+    fn f32(&mut self, lo: f32, hi: f32) -> f32 {+        lo + (self.next() as f32 / u64::MAX as f32) * (hi - lo)+    }+    fn below(&mut self, n: usize) -> usize {+        (self.next() % n as u64) as usize+    }+}++fn random_obb(rng: &mut Rng, axis_aligned_bias: bool) -> Obb {+    let (cos, sin) = if axis_aligned_bias && rng.below(4) != 0 {+        (1.0, 0.0) // the point-label majority case+    } else {+        let a = rng.f32(0.0, std::f32::consts::TAU);+        (a.cos(), a.sin())+    };+    Obb {+        cx: rng.f32(0.0, 1024.0),+        cy: rng.f32(0.0, 1024.0),+        hx: rng.f32(1.0, 60.0),+        hy: rng.f32(1.0, 20.0),+        cos,+        sin,+    }+}++#[test]+fn grid_broadphase_matches_brute_force_on_fuzz() {+    let mut rng = Rng(0x1234_5678_9abc_def0);+    for round in 0..300 {+        let n = 1 + rng.below(40);+        let mut candidates: Vec<SegmentedCandidate> = Vec::with_capacity(n);+        for i in 0..n {+            let nb = 1 + rng.below(4);+            let boxes: Vec<Obb> =+                (0..nb).map(|_| random_obb(&mut rng, true)).collect();+            let alternate = if rng.below(3) == 0 {+                let na = 1 + rng.below(3);+                Some((0..na).map(|_| random_obb(&mut rng, true)).collect())+            } else {+                None+            };+            candidates.push(SegmentedCandidate {+                // Forced id/rank/pop collisions to stress tie-breaks.+                id: (i % 7) as u64,+                rank: [0, 2, 2, 3, 4, 4, 5][rng.below(7)],+                pop: (rng.below(4)) as u16,+                boxes,+                alternate,+                feature_id: i as u64 + 1,+                layer_index: rng.below(3),+            });+        }+        let want = brute_place(&candidates);+        let got = place_segmented(&candidates);+        assert_eq!(got, want, "round {round}: grid diverged from brute force");+    }+}++#[test]+fn grid_matches_brute_force_on_degenerate_inputs() {+    // Empty, single, all-rank-0, identical boxes, edge-touching grid.+    let empty: Vec<SegmentedCandidate> = vec![];+    assert_eq!(place_segmented(&empty), brute_place(&empty));+    let mk = |id: u64, rank: u8, rect: (f32, f32, f32, f32)| SegmentedCandidate {+        id,+        rank,+        pop: 0,+        boxes: vec![Obb::from_rect(rect)],+        alternate: None,+        feature_id: id + 1,+        layer_index: 0,+    };+    // Ten identical boxes: first wins, rest collide.+    let same: Vec<SegmentedCandidate> = (0..10)+        .map(|i| mk(i, 4, (0.0, 0.0, 50.0, 20.0)))+        .collect();+    assert_eq!(place_segmented(&same), brute_place(&same));+    assert_eq!(place_segmented(&same).len(), 1);+    // Edge-touching chain: all place (half-open rule through the grid).+    let chain: Vec<SegmentedCandidate> = (0..8)+        .map(|i| mk(i, 4, (i as f32 * 50.0, 0.0, i as f32 * 50.0 + 50.0, 20.0)))+        .collect();+    assert_eq!(place_segmented(&chain).len(), 8);+    assert_eq!(place_segmented(&chain), brute_place(&chain));+    // Negative coordinates (grid floor division with negatives).+    let neg: Vec<SegmentedCandidate> = (0..6)+        .map(|i| mk(i, 4, (-400.0 + i as f32 * 30.0, -300.0, -360.0 + i as f32 * 30.0, -280.0)))+        .collect();+    assert_eq!(place_segmented(&neg), brute_place(&neg));+    // Zero-area boxes.+    let zero = vec![mk(0, 4, (10.0, 10.0, 10.0, 10.0)), mk(1, 4, (0.0, 0.0, 50.0, 20.0))];+    assert_eq!(place_segmented(&zero), brute_place(&zero));+}++// ---------------------------------------------------------------------------+// 2. Old curved-layout algorithm, restated verbatim (rescan + collect).+// ---------------------------------------------------------------------------++fn old_polyline_length(pts: &[(f32, f32)]) -> f32 {+    let mut sum = 0.0;+    for w in pts.windows(2) {+        let dx = w[1].0 - w[0].0;+        let dy = w[1].1 - w[0].1;+        sum += (dx * dx + dy * dy).sqrt();+    }+    sum+}++const MAX_TURN_RAD: f32 = std::f32::consts::FRAC_PI_4;++fn old_longest_smooth_run(pts: &[(f32, f32)]) -> &[(f32, f32)] {+    if pts.len() < 3 {+        return pts;+    }+    let cos_max = MAX_TURN_RAD.cos();+    let direction = |a: (f32, f32), b: (f32, f32)| {+        let (dx, dy) = (b.0 - a.0, b.1 - a.1);+        let len = (dx * dx + dy * dy).sqrt();+        (len > 0.0).then_some((dx / len, dy / len))+    };+    let (mut best_start, mut best_end) = (0usize, pts.len());+    let mut best_len = -1.0f32;+    let mut start = 0usize;+    let mut previous: Option<(f32, f32)> = None;+    for i in 0..pts.len() - 1 {+        let Some(d) = direction(pts[i], pts[i + 1]) else { continue };+        if let Some(p) = previous {+            if p.0 * d.0 + p.1 * d.1 < cos_max {+                let len = old_polyline_length(&pts[start..=i]);+                if len > best_len {+                    best_len = len;+                    (best_start, best_end) = (start, i + 1);+                }+                start = i;+            }+        }+        previous = Some(d);+    }+    if old_polyline_length(&pts[start..]) > best_len {+        (best_start, best_end) = (start, pts.len());+    }+    &pts[best_start..best_end]+}++fn old_sample_polyline(pts: &[(f32, f32)], d: f32) -> ((f32, f32), (f32, f32)) {+    let d = d.max(0.0);+    let mut acc = 0.0f32;+    for w in pts.windows(2) {+        let dx = w[1].0 - w[0].0;+        let dy = w[1].1 - w[0].1;+        let seg = (dx * dx + dy * dy).sqrt();+        if seg <= 0.0 {+            continue;+        }+        if acc + seg >= d {+            let t = ((d - acc) / seg).clamp(0.0, 1.0);+            return ((w[0].0 + dx * t, w[0].1 + dy * t), (dx / seg, dy / seg));+        }+        acc += seg;+    }+    let last = *pts.last().unwrap_or(&(0.0, 0.0));+    for w in pts.windows(2).rev() {+        let dx = w[1].0 - w[0].0;+        let dy = w[1].1 - w[0].1;+        let seg = (dx * dx + dy * dy).sqrt();+        if seg > 0.0 {+            return (last, (dx / seg, dy / seg));+        }+    }+    (last, (1.0, 0.0))+}++fn old_layout_along_line(+    line: &ShapedLine,+    centreline: &[(f32, f32)],+    px_per_font_unit: f32,+    up_em: f32,+) -> Vec<CurvedGlyph> {+    if centreline.len() < 2 || line.glyphs.is_empty() || px_per_font_unit <= 0.0 {+        return Vec::new();+    }+    let smooth = old_longest_smooth_run(centreline);+    if smooth.len() < 2 {+        return Vec::new();+    }+    let total_len = old_polyline_length(smooth);+    let run_len = line.advance * px_per_font_unit;+    if run_len <= 0.0 || run_len > total_len {+        return Vec::new();+    }+    let net_dx = smooth[smooth.len() - 1].0 - smooth[0].0;+    let reversed: Vec<(f32, f32)>;+    let path: &[(f32, f32)] = if net_dx < 0.0 {+        reversed = smooth.iter().rev().copied().collect();+        &reversed+    } else {+        smooth+    };+    let start = (total_len - run_len) * 0.5;+    let half_window = up_em * px_per_font_unit;+    let mut out = Vec::with_capacity(line.glyphs.len());+    for g in &line.glyphs {+        let d = start + g.pen_x * px_per_font_unit;+        let (pen, segment_tangent) = old_sample_polyline(path, d);+        let (behind, _) = old_sample_polyline(path, d - half_window);+        let (ahead, _) = old_sample_polyline(path, d + half_window);+        let (dx, dy) = (ahead.0 - behind.0, ahead.1 - behind.1);+        let chord = (dx * dx + dy * dy).sqrt();+        let tangent = if chord > 1e-7 { (dx / chord, dy / chord) } else { segment_tangent };+        out.push(CurvedGlyph { glyph: *g, pen, tangent });+    }+    out+}++fn block_run(n: usize, up_em: f32) -> ShapedLine {+    let glyphs: Vec<ShapedGlyph> = (0..n)+        .map(|i| ShapedGlyph {+            pen_x: i as f32 * up_em,+            ch: 'x',+            advance: up_em,+            bearing_x: 0.0,+            top: up_em,+            w: up_em,+            h: up_em,+        })+        .collect();+    ShapedLine { glyphs, advance: n as f32 * up_em }+}++fn assert_same_layout(got: &[CurvedGlyph], want: &[CurvedGlyph], ctx: &str) {+    assert_eq!(got.len(), want.len(), "{ctx}: glyph count");+    // Forward walks are bit-identical (same operands, same order). Reversed walks+    // mirror arcs about the total length instead of accumulating a reversed copy,+    // so they may differ in the last ulp; anything bigger is a real divergence.+    for (i, (g, w)) in got.iter().zip(want.iter()).enumerate() {+        for (field, gv, wv) in [+            ("pen.x", g.pen.0, w.pen.0),+            ("pen.y", g.pen.1, w.pen.1),+            ("tan.x", g.tangent.0, w.tangent.0),+            ("tan.y", g.tangent.1, w.tangent.1),+        ] {+            if gv.to_bits() != wv.to_bits() {+                let bad = (gv - wv).abs();+                assert!(+                    bad <= 2.0 * f32::EPSILON * wv.abs().max(1.0),+                    "{ctx}[{i}] {field}: {gv} vs {wv} (diff {bad} exceeds 2ulp)"+                );+            }+        }+    }+}++#[test]+fn linearized_layout_matches_old_algorithm_bit_for_bit() {+    let up_em = 1000.0f32;+    let ppfu = 1.0 / up_em;+    // Straight, reversed (net_dx < 0), elbow, gentle bend, degenerate points,+    // multi-part join, arc, tiny stub.+    let mut arc = Vec::new();+    for i in 0..=48 {+        let t = std::f32::consts::FRAC_PI_2 * i as f32 / 48.0;+        arc.push((0.5 + 0.35 * t.cos(), 0.5 + 0.35 * t.sin()));+    }+    let cases: Vec<(&str, Vec<(f32, f32)>)> = vec![+        ("straight", vec![(0.0, 0.0), (12.0, 0.0)]),+        ("reversed", vec![(12.0, 0.0), (0.0, 0.0)]),+        ("rev-bend", vec![(9.0, 4.0), (2.0, 0.5), (0.0, 0.0)]),+        ("elbow", vec![(0.0, 0.0), (4.0, 0.0), (4.0, 9.0)]),+        ("bend30", {+            let c = 30.0f32.to_radians();+            vec![(0.0, 0.0), (6.0, 0.0), (6.0 + 6.0 * c.cos(), 6.0 * c.sin())]+        }),+        ("degenerate", vec![(0.0, 0.0), (0.0, 0.0), (6.0, 0.0), (6.0, 0.0), (12.0, 0.0)]),+        (+            "join",+            vec![(0.0, 0.0), (6.0, 0.0), (0.0, 4.0), (9.0, 4.0)],+        ),+        ("arc", arc),+        ("zigzag", vec![(0.0, 0.0), (2.0, 1.0), (4.0, 0.0), (6.0, 1.0), (8.0, 0.0), (10.0, 1.0)]),+        // Net-dx-zero paths: neither forward nor reversed by the sign test — the+        // walk takes the forward branch (strict `<`), matching the old code's+        // `net_dx < 0.0` gate exactly.+        ("vertical", vec![(3.0, 0.0), (3.0, 12.0)]),+        ("rev-vertical", vec![(3.0, 12.0), (3.0, 0.0)]),+        ("there-and-back", vec![(0.0, 0.0), (6.0, 0.0), (0.0, 0.0)]),+    ];+    for (name, path) in &cases {+        for n in [1usize, 3, 8, 10] {+            let run = block_run(n, up_em);+            let want = old_layout_along_line(&run, path, ppfu, up_em);+            let got = layout_along_line(&run, path, ppfu);+            assert_same_layout(&got, &want, &format!("{name}/n={n}"));+        }+    }+}++#[test]+fn linearized_layout_matches_on_fuzz_polylines() {+    let up_em = 1000.0f32;+    let mut rng = Rng(0xfeed_face_cafe_1234);+    for round in 0..200 {+        let npts = 2 + rng.below(14);+        let mut path = Vec::with_capacity(npts);+        let (mut x, mut y) = (rng.f32(0.0, 1.0), rng.f32(0.0, 1.0));+        path.push((x, y));+        for _ in 1..npts {+            // Random walk, sometimes repeating a vertex (degenerate segment).+            if rng.below(8) == 0 {+                path.push((x, y));+            } else {+                x += rng.f32(-0.2, 0.2);+                y += rng.f32(-0.2, 0.2);+                path.push((x, y));+            }+        }+        let n = 1 + rng.below(12);+        let run = block_run(n, up_em);+        // Vary text size over two orders of magnitude.+        let ppfu = [0.5, 1.0, 3.0][rng.below(3)] / up_em;+        let want = old_layout_along_line(&run, &path, ppfu, up_em);+        let got = layout_along_line(&run, &path, ppfu);+        assert_same_layout(&got, &want, &format!("fuzz round {round}"));+    }+}++// ---------------------------------------------------------------------------+// 3-5. AABB rule, candidate_id, Ramp.+// ---------------------------------------------------------------------------++#[test]+fn aabb_fast_path_matches_half_open_rect_rule() {+    let rect_overlaps =+        |a: (f32, f32, f32, f32), b: (f32, f32, f32, f32)| a.0 < b.2 && b.0 < a.2 && a.1 < b.3 && b.1 < a.3;+    let mut rng = Rng(0x0bad_f00d_dead_beef);+    for _ in 0..500 {+        let r = |mut v: (f32, f32, f32, f32)| {+            if v.0 > v.2 {+                std::mem::swap(&mut v.0, &mut v.2);+            }+            if v.1 > v.3 {+                std::mem::swap(&mut v.1, &mut v.3);+            }+            v+        };+        let a = r((rng.f32(-50.0, 50.0), rng.f32(-50.0, 50.0), rng.f32(-50.0, 50.0), rng.f32(-50.0, 50.0)));+        let b = r((rng.f32(-50.0, 50.0), rng.f32(-50.0, 50.0), rng.f32(-50.0, 50.0), rng.f32(-50.0, 50.0)));+        let oa = Obb::from_rect(a);+        let ob = Obb::from_rect(b);+        assert_eq!(obb_overlap(&oa, &ob), rect_overlaps(a, b), "a={a:?} b={b:?}");+    }+    // Exact edge touch: separated.+    let a = Obb::from_rect((0.0, 0.0, 10.0, 10.0));+    let flush = Obb::from_rect((10.0, 0.0, 20.0, 10.0));+    assert!(!obb_overlap(&a, &flush));+}++#[test]+fn candidate_ids_stable_and_distinct() {+    let a = candidate_id(6, 10, 24, 33, 4);+    assert_eq!(a, candidate_id(6, 10, 24, 33, 4));+    assert_ne!(a, candidate_id(6, 10, 24, 33, 5));+    assert_ne!(a, candidate_id(6, 10, 25, 33, 4));+    assert_ne!(a, candidate_id(6, 10, 24, 34, 4));+    assert_ne!(a, candidate_id(7, 10, 24, 33, 4));+}++#[test]+fn ramp_single_stop_answers_constant() {+    use map_renderer::style::paint::Ramp;+    let c = Ramp::constant(3.5);+    for z in [-10.0, 0.0, 5.5, 14.0, 22.0, 100.0] {+        assert_eq!(c.at(z).to_bits(), 3.5f32.to_bits(), "z={z}");+    }+}