library: build the glyph atlas 80x faster, bit-identical (#maprender)
- Commit
5c0a460fd731b5bc38758ffecb91293721004082- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-13 20:21 UTC (22 days ago)
- Parents
ca8dfe2
Part of the "Maps isn't responding" / slow-start report. Root cause: the SDF glyph atlas (both Noto Sans weights, ~640 glyphs) is built at first use, and its distance transform was a brute-force square scan: for each of the 64x64 texels of a cell, every offset in a 17x17 square, each paying a float divide and four bounds checks through the `sample` closure. Measured with tests/frame_cpu_bench.rs (create_time_cpu_work): 1350 ms on one Genoa core, so roughly 3-5 s on a phone core. Renderer creation uploads the atlas and every worker blocks on it before it can shape its first label, so this was paid on every cold map open before anything could draw - and, until the previous commit, on the main thread. What changed (output unchanged): - `sdf_from_coverage` samples inside/outside once per texel into a mask, walks only offsets inside the search circle, nearest first, and stops at the first opposite texel (by construction the minimum the old scan converged to; equal distances give equal values). - A summed-area table answers "no opposite texel in the search square" in O(1), skipping the walk for the empty margin and stem interiors, which are most of each cell. - `GlyphAtlas::build` renders glyphs on up to 8 scoped threads (`available_parallelism`), then blits and inserts metrics in one sequential pass. `sdf_per_em` keeps the last weight's value as the old loop did. Measured (host, release, `taskset` to pin the core count): before 1350.5 ms after, 1 core 115.0 ms (11.7x) after, 4 cores 31.1 ms (43x) after, 8 cores 16.7 ms (81x) Verified: new test pins the fast transform bit-for-bit against the original square scan (kept as `sdf_from_coverage_reference`) over the whole charset in both weights; all 24 glyph tests pass.
Diff
library/map/src/main/rust/src/tile/glyph/atlas.rs
diff --git a/library/map/src/main/rust/src/tile/glyph/atlas.rs b/library/map/src/main/rust/src/tile/glyph/atlas.rsindex 31e171047f..81cabcd88c 100644--- a/library/map/src/main/rust/src/tile/glyph/atlas.rs+++ b/library/map/src/main/rust/src/tile/glyph/atlas.rs@@ -23,100 +23,67 @@ pub struct GlyphAtlas { impl GlyphAtlas { /// Rasterise both weights and build the SDF atlas. Called once per process.+ ///+ /// Glyphs are independent (each fills its own cell), so they are rendered across up to+ /// [`MAX_BUILD_THREADS`] scoped threads and blitted afterwards in one pass. The atlas is+ /// built on the first tile a worker shapes or by renderer creation, whichever comes first,+ /// and every other caller blocks on it — so a faster build is a sooner first frame. pub fn build() -> GlyphAtlas { let regular = FontRef::try_from_slice(REGULAR_TTF).expect("bundled NotoSans-Regular.ttf parses"); let medium = FontRef::try_from_slice(MEDIUM_TTF).expect("bundled NotoSans-Medium.ttf parses"); let chars = charset();- let mut pixels = vec![0u8; (ATLAS_PX * ATLAS_PX) as usize];- let mut metrics = HashMap::new();- let mut sdf_per_em = 0.0f32;- for (weight, font) in [(Weight::Regular, regular), (Weight::Medium, medium)] {- // Font units per rasterised pixel. Derived from the font rather than from- // `UP_EM / px`, because ab_glyph's `PxScale` is a HEIGHT (ascent + descent)- // and not pixels-per-em: at scale 48 this face puts an em at 35.2px, so the- // naive ratio is out by `height_unscaled / units_per_em`.- let px = 48.0f32;- let per_raster_px = font.height_unscaled() / font.as_scaled(px).height();- sdf_per_em = UP_EM as f32 / per_raster_px / (2.0 * SDF_SPREAD_PX as f32);+ // Font units per rasterised pixel. Derived from the font rather than from+ // `UP_EM / px`, because ab_glyph's `PxScale` is a HEIGHT (ascent + descent)+ // and not pixels-per-em: at scale 48 this face puts an em at 35.2px, so the+ // naive ratio is out by `height_unscaled / units_per_em`.+ let px = 48.0f32;+ let per_raster = |font: &FontRef| font.height_unscaled() / font.as_scaled(px).height();+ // The last weight's value, as the sequential loop this replaced left it.+ let sdf_per_em =+ UP_EM as f32 / per_raster(&medium) / (2.0 * SDF_SPREAD_PX as f32);+ let mut jobs: Vec<(Weight, &FontRef, char, u32)> = Vec::with_capacity(chars.len() * 2);+ for (weight, font) in [(Weight::Regular, ®ular), (Weight::Medium, &medium)] { for (i, &ch) in chars.iter().enumerate() { let cell = match weight { Weight::Regular => i as u32, Weight::Medium => (chars.len() + i) as u32, };- let id = font.glyph_id(ch);- // Skip .notdef: an unknown glyph rasterises as tofu; shaping skips- // these codepoints instead (see `tess::text::shape`).- if id.0 == 0 {- continue;- }- let advance = font.h_advance_unscaled(id);- let bearing = font.h_side_bearing_unscaled(id);- // A glyph with an advance but no ink. It still has to reach the metrics- // table: shaping looks every codepoint up there and skips the ones it- // cannot find, so a space that is missing here closes the gap between two- // words instead of widening it — "Telegraph Hill" shapes as "TelegraphHill".- let blank = GlyphMetrics {- advance,- bearing_x: bearing,- top: 0.0,- w: 0.0,- h: 0.0,- cell,- uv: UvRect {- u0: 0.0,- v0: 0.0,- u1: 0.0,- v1: 0.0,- },- };- // 4x raster of the outline at 48px, then downsample-by-distance to- // the SDF cell: coverage at 4x is a 2-bit alpha proxy.- let Some(outlined) = font.outline_glyph(id.with_scale(px)) else {- // Space and friends: `outline_glyph` gives nothing at all for these,- // so the zero-size check below is never reached for them.- metrics.insert((weight, ch), blank);- continue;- };- let bounds = outlined.px_bounds();- let w_px = bounds.width().ceil() as u32;- let h_px = bounds.height().ceil() as u32;- if w_px == 0 || h_px == 0 {- // A zero-size quad emits two degenerate triangles, which rasterise to- // nothing.- metrics.insert((weight, ch), blank);- continue;- }- let mut coverage = vec![0u8; (w_px * h_px) as usize];- outlined.draw(|x, y, v| {- if x < w_px && y < h_px {- coverage[(y * w_px + x) as usize] = (v * 255.0) as u8;- }- });- let placement = place_in_cell(w_px, h_px);- let sdf = sdf_from_coverage(&coverage, w_px, h_px, placement);- blit_cell(&mut pixels, cell, &sdf);- // The spread margin measured in rasterised pixels. The cell margin is a- // constant number of CELL px, so a glyph scaled down to fit spans- // proportionally more of its own pixels — hence the divide by `scale`.- let pad = SDF_SPREAD_PX as f32 / placement.scale;- metrics.insert(- (weight, ch),- GlyphMetrics {- advance,- bearing_x: bearing - pad * per_raster_px,- // `px_bounds` is y-down from the baseline, so the ink's top- // above the baseline is `-min.y`.- top: (-bounds.min.y + pad) * per_raster_px,- w: (w_px as f32 + 2.0 * pad) * per_raster_px,- h: (h_px as f32 + 2.0 * pad) * per_raster_px,- cell,- uv: ink_uv(cell, placement),- },- );+ jobs.push((weight, font, ch, cell)); } }+ let threads = std::thread::available_parallelism()+ .map(|n| n.get())+ .unwrap_or(1)+ .clamp(1, MAX_BUILD_THREADS);+ let chunk = jobs.len().div_ceil(threads).max(1);+ let rendered: Vec<RenderedGlyph> = std::thread::scope(|scope| {+ let handles: Vec<_> = jobs+ .chunks(chunk)+ .map(|part| {+ scope.spawn(move || {+ part.iter()+ .filter_map(|&(weight, font, ch, cell)| {+ render_glyph(font, weight, ch, cell, px, per_raster(font))+ })+ .collect::<Vec<_>>()+ })+ })+ .collect();+ handles+ .into_iter()+ .flat_map(|h| h.join().expect("glyph raster thread panicked"))+ .collect()+ });+ let mut pixels = vec![0u8; (ATLAS_PX * ATLAS_PX) as usize];+ let mut metrics = HashMap::with_capacity(rendered.len());+ for glyph in rendered {+ if let Some(sdf) = &glyph.sdf {+ blit_cell(&mut pixels, glyph.metrics.cell, sdf);+ }+ metrics.insert((glyph.weight, glyph.ch), glyph.metrics);+ } GlyphAtlas { pixels, sdf_per_em,@@ -141,6 +108,95 @@ impl GlyphAtlas { } } +/// Upper bound on [`GlyphAtlas::build`]'s raster threads: past eight the per-thread share of+/// ~640 glyphs is too small to pay for the spawn, and a phone has no more big cores than that.+const MAX_BUILD_THREADS: usize = 8;++/// One rasterised glyph: its metrics and, when it has ink, its SDF cell.+struct RenderedGlyph {+ weight: Weight,+ ch: char,+ metrics: GlyphMetrics,+ sdf: Option<Vec<u8>>,+}++/// Rasterise one glyph into its SDF cell and metrics, or `None` for a codepoint the font does+/// not cover (shaping skips those instead of drawing tofu; see `tess::text::shape`).+fn render_glyph(+ font: &FontRef,+ weight: Weight,+ ch: char,+ cell: u32,+ px: f32,+ per_raster_px: f32,+) -> Option<RenderedGlyph> {+ let id = font.glyph_id(ch);+ if id.0 == 0 {+ return None;+ }+ let advance = font.h_advance_unscaled(id);+ let bearing = font.h_side_bearing_unscaled(id);+ // A glyph with an advance but no ink. It still has to reach the metrics table: shaping+ // looks every codepoint up there and skips the ones it cannot find, so a space that is+ // missing here closes the gap between two words instead of widening it — "Telegraph Hill"+ // shapes as "TelegraphHill".+ let blank = GlyphMetrics {+ advance,+ bearing_x: bearing,+ top: 0.0,+ w: 0.0,+ h: 0.0,+ cell,+ uv: UvRect {+ u0: 0.0,+ v0: 0.0,+ u1: 0.0,+ v1: 0.0,+ },+ };+ let blank_glyph = RenderedGlyph { weight, ch, metrics: blank, sdf: None };+ // 4x raster of the outline at 48px, then downsample-by-distance to the SDF cell: coverage+ // at 4x is a 2-bit alpha proxy. Space and friends: `outline_glyph` gives nothing at all.+ let Some(outlined) = font.outline_glyph(id.with_scale(px)) else {+ return Some(blank_glyph);+ };+ let bounds = outlined.px_bounds();+ let w_px = bounds.width().ceil() as u32;+ let h_px = bounds.height().ceil() as u32;+ if w_px == 0 || h_px == 0 {+ // A zero-size quad emits two degenerate triangles, which rasterise to nothing.+ return Some(blank_glyph);+ }+ let mut coverage = vec![0u8; (w_px * h_px) as usize];+ outlined.draw(|x, y, v| {+ if x < w_px && y < h_px {+ coverage[(y * w_px + x) as usize] = (v * 255.0) as u8;+ }+ });+ let placement = place_in_cell(w_px, h_px);+ let sdf = sdf_from_coverage(&coverage, w_px, h_px, placement);+ // The spread margin measured in rasterised pixels. The cell margin is a constant number of+ // CELL px, so a glyph scaled down to fit spans proportionally more of its own pixels —+ // hence the divide by `scale`.+ let pad = SDF_SPREAD_PX as f32 / placement.scale;+ Some(RenderedGlyph {+ weight,+ ch,+ metrics: GlyphMetrics {+ advance,+ bearing_x: bearing - pad * per_raster_px,+ // `px_bounds` is y-down from the baseline, so the ink's top above the baseline+ // is `-min.y`.+ top: (-bounds.min.y + pad) * per_raster_px,+ w: (w_px as f32 + 2.0 * pad) * per_raster_px,+ h: (h_px as f32 + 2.0 * pad) * per_raster_px,+ cell,+ uv: ink_uv(cell, placement),+ },+ sdf: Some(sdf),+ })+}+ /// The process-wide atlas, built once. pub fn atlas() -> &'static GlyphAtlas { static ATLAS: std::sync::OnceLock<GlyphAtlas> = std::sync::OnceLock::new();
library/map/src/main/rust/src/tile/glyph/mod.rs
diff --git a/library/map/src/main/rust/src/tile/glyph/mod.rs b/library/map/src/main/rust/src/tile/glyph/mod.rsindex 07562224e8..5ed8294f5e 100644--- a/library/map/src/main/rust/src/tile/glyph/mod.rs+++ b/library/map/src/main/rust/src/tile/glyph/mod.rs@@ -15,9 +15,11 @@ //! `src/main/assets/`: anything in the latter is packaged into every consumer's //! APK, which shipped these 1.5 MB a second time for bytes no code path reads. //!-//! Rasterising at first use costs milliseconds once:-//! ~319 Latin codepoints × 2 weights, each a 4x `ab_glyph` rasterise followed by an-//! 8SSEDT distance transform over a ≤128px cell. The atlas is a single R8 image+//! Rasterising at first use is paid once per process, and every caller (renderer creation,+//! the first tile a worker shapes) blocks on it: ~319 Latin codepoints × 2 weights, each a+//! 4x `ab_glyph` rasterise followed by an exact distance transform over a 64px cell. The+//! transform's search is mask- and summed-area-table-accelerated and glyphs are rendered on+//! several threads (`atlas.rs`, `sdf.rs`): 1350 ms → 17 ms on an 8-core host, bit-identical. The atlas is a single R8 image //! (32×32 cells of 64px = 2048px) uploaded to Vulkan once. //! //! # Metrics live here, shaping in `tess::text`
library/map/src/main/rust/src/tile/glyph/sdf.rs
diff --git a/library/map/src/main/rust/src/tile/glyph/sdf.rs b/library/map/src/main/rust/src/tile/glyph/sdf.rsindex 3ef076be0b..34b9fa895c 100644--- a/library/map/src/main/rust/src/tile/glyph/sdf.rs+++ b/library/map/src/main/rust/src/tile/glyph/sdf.rs@@ -3,12 +3,24 @@ use super::placement::Placement; /// 8SSEDT-lite: exact brute-force distance transform over a small cell. ///-/// Cells are ≤128px; brute force is ~16k×256 ops per glyph worst case, once per-/// process — simpler than Felzenszwalb and exact. Inside/outside comes from the-/// 50% coverage threshold; distance is normalised by `SDF_SPREAD_PX`.+/// Inside/outside comes from the 50% coverage threshold; distance is normalised by+/// `SDF_SPREAD_PX`. `placement` is where the caller has decided the bitmap sits in the+/// cell, so the same rect `ink_uv` addresses is the rect sampled here. ///-/// `placement` is where the caller has decided the bitmap sits in the cell, so the-/// same rect `ink_uv` addresses is the rect sampled here.+/// Still an exact nearest-opposite-texel search, but organised so it is cheap enough to run+/// at renderer start (the atlas used to cost 1.35 s on a desktop core, all of it on the thread+/// that created the map):+/// - the inside/outside test is sampled once per cell texel into a mask instead of once per+/// (texel, offset) pair, each of which paid a float divide and four bounds checks;+/// - the search walks offsets nearest-first and stops at the first opposite texel, which is+/// by construction the nearest one, and never visits offsets at or past the search limit;+/// - a summed-area table skips the walk outright for texels whose whole search square is one+/// colour (no opposite texel can be in range), which is most of every cell.+///+/// The result is bit-identical to the original square scan+/// ([`sdf_from_coverage_reference`] in the tests pins it over every glyph of both weights):+/// the original kept the minimum `d_cell` among opposite texels with `d_cell < spread*scale`,+/// which is exactly the first opposite texel in ascending-distance order. pub(super) fn sdf_from_coverage(coverage: &[u8], w: u32, h: u32, placement: Placement) -> Vec<u8> { let inside = |x: i32, y: i32| -> bool { x >= 0@@ -18,7 +30,6 @@ pub(super) fn sdf_from_coverage(coverage: &[u8], w: u32, h: u32, placement: Plac && coverage[(y as u32 * w + x as u32) as usize] >= 128 }; let spread = SDF_SPREAD_PX as f32;- let mut out = vec![0u8; (CELL_PX * CELL_PX) as usize]; let Placement { scale, ox,@@ -37,14 +48,120 @@ pub(super) fn sdf_from_coverage(coverage: &[u8], w: u32, h: u32, placement: Plac // Search radius in *cell* px: the spread in glyph px scaled up. Distances are // divided back down by the same scale so the SDF is in glyph px everywhere. let r_cell = ((SDF_SPREAD_PX as f32 * scale).ceil() as u32).max(2);- for cy in 0..CELL_PX {- for cx in 0..CELL_PX {- let me = sample(cx, cy);+ // The mask covers every coordinate a neighbour lookup can reach: 0..CELL_PX + r_cell.+ // Negative neighbours saturate to 0 (the original used `saturating_add_signed`).+ let ext = (CELL_PX + r_cell + 1) as usize;+ let mut mask = vec![false; ext * ext];+ for y in 0..ext {+ for x in 0..ext {+ mask[y * ext + x] = sample(x as u32, y as u32);+ }+ }+ // Every offset the original could accept (`d_cell < best * scale` with `best` starting at+ // `spread`), nearest first. Ties keep any order: equal distances give equal answers.+ let limit = spread * scale;+ let r = r_cell as i32;+ let mut offsets: Vec<(f32, i32, i32)> = Vec::with_capacity(((2 * r + 1) * (2 * r + 1)) as usize);+ for dy in -r..=r {+ for dx in -r..=r {+ let d_cell = ((dx * dx + dy * dy) as f32).sqrt();+ if d_cell < limit {+ offsets.push((d_cell, dx, dy));+ }+ }+ }+ offsets.sort_by(|a, b| a.0.total_cmp(&b.0));+ // Summed-area table of the mask, so a texel whose whole search square is one colour —+ // most of the cell: the empty margin around the ink and the middle of thick stems — can+ // be answered "no opposite texel in range" in O(1) instead of walking every offset.+ let mut sat = vec![0u32; (ext + 1) * (ext + 1)];+ for y in 0..ext {+ let mut row = 0u32;+ for x in 0..ext {+ row += u32::from(mask[y * ext + x]);+ sat[(y + 1) * (ext + 1) + x + 1] = sat[y * (ext + 1) + x + 1] + row;+ }+ }+ let inside_in = |x0: usize, y0: usize, x1: usize, y1: usize| -> u32 {+ // Inclusive rect; `+ - -` order keeps the u32 arithmetic from underflowing.+ sat[(y1 + 1) * (ext + 1) + x1 + 1] + sat[y0 * (ext + 1) + x0]+ - sat[y0 * (ext + 1) + x1 + 1]+ - sat[(y1 + 1) * (ext + 1) + x0]+ };+ let mut out = vec![0u8; (CELL_PX * CELL_PX) as usize];+ for cy in 0..CELL_PX as i32 {+ for cx in 0..CELL_PX as i32 {+ let me = mask[cy as usize * ext + cx as usize]; // Inside the stroke the distance is capped by the search radius, so a // thick stem never reaches full bright — but the shader only needs the // 0.5 crossing plus a smoothing band either side. Scale the inside // distance so the stem centre hits 1.0: full dynamic range at the edge. let mut best = spread;+ // The reachable square, clamped at 0 exactly as the neighbour lookup clamps.+ let (x0, y0) = ((cx - r).max(0) as usize, (cy - r).max(0) as usize);+ let (x1, y1) = ((cx + r) as usize, (cy + r) as usize);+ let inside = inside_in(x0, y0, x1, y1);+ let uniform = if me {+ inside as usize == (x1 - x0 + 1) * (y1 - y0 + 1)+ } else {+ inside == 0+ };+ if !uniform {+ for &(d_cell, dx, dy) in &offsets {+ let nx = (cx + dx).max(0) as usize;+ let ny = (cy + dy).max(0) as usize;+ if mask[ny * ext + nx] != me {+ best = d_cell / scale;+ break;+ }+ }+ }+ let value = if me {+ // Inside: 0.5 at the edge → 1.0 one px in. Stems thicker than 2px+ // saturate, which is correct for an SDF edge function.+ (0.5 + (best / 2.0).min(0.5)).clamp(0.0, 1.0)+ } else {+ (0.5 - best / (2.0 * spread)).clamp(0.0, 1.0)+ };+ out[(cy as u32 * CELL_PX + cx as u32) as usize] = (value * 255.0) as u8;+ }+ }+ out+}++/// The original square-scan distance transform, kept verbatim as the reference the+/// optimised [`sdf_from_coverage`] is pinned against.+#[cfg(test)]+pub(super) fn sdf_from_coverage_reference(coverage: &[u8], w: u32, h: u32, placement: Placement) -> Vec<u8> {+ let inside = |x: i32, y: i32| -> bool {+ x >= 0+ && y >= 0+ && (x as u32) < w+ && (y as u32) < h+ && coverage[(y as u32 * w + x as u32) as usize] >= 128+ };+ let spread = SDF_SPREAD_PX as f32;+ let mut out = vec![0u8; (CELL_PX * CELL_PX) as usize];+ let Placement {+ scale,+ ox,+ oy,+ dw,+ dh,+ } = placement;+ let sample = |cx: u32, cy: u32| -> bool {+ if cx < ox || cy < oy || cx >= ox + dw || cy >= oy + dh {+ return false;+ }+ let gx = ((cx - ox) as f32 / scale) as i32;+ let gy = ((cy - oy) as f32 / scale) as i32;+ inside(gx, gy)+ };+ let r_cell = ((SDF_SPREAD_PX as f32 * scale).ceil() as u32).max(2);+ for cy in 0..CELL_PX {+ for cx in 0..CELL_PX {+ let me = sample(cx, cy);+ let mut best = spread; for dy in -(r_cell as i32)..=(r_cell as i32) { for dx in -(r_cell as i32)..=(r_cell as i32) { let d_cell = ((dx * dx + dy * dy) as f32).sqrt();@@ -56,8 +173,6 @@ pub(super) fn sdf_from_coverage(coverage: &[u8], w: u32, h: u32, placement: Plac } } let value = if me {- // Inside: 0.5 at the edge → 1.0 one px in. Stems thicker than 2px- // saturate, which is correct for an SDF edge function. (0.5 + (best / 2.0).min(0.5)).clamp(0.0, 1.0) } else { (0.5 - best / (2.0 * spread)).clamp(0.0, 1.0)
library/map/src/main/rust/src/tile/glyph/tests.rs
diff --git a/library/map/src/main/rust/src/tile/glyph/tests.rs b/library/map/src/main/rust/src/tile/glyph/tests.rsindex dd3a306add..c8c083874d 100644--- a/library/map/src/main/rust/src/tile/glyph/tests.rs+++ b/library/map/src/main/rust/src/tile/glyph/tests.rs@@ -275,3 +275,43 @@ fn budapest_street_names_shape_every_character() { } } }++#[test]+fn the_fast_distance_transform_matches_the_square_scan_on_every_glyph() {+ // The nearest-first search with a precomputed mask must be bit-identical to the original+ // square scan, or every label on the map changes weight. Checked over the real charset in+ // both weights, which covers both placement branches (scale 1.0 and scaled-to-fit).+ if !real_fonts_staged() {+ eprintln!("SKIP: staged TTFs are 404 pages, not fonts");+ return;+ }+ use super::sdf::{sdf_from_coverage, sdf_from_coverage_reference};+ use ab_glyph::FontRef;+ let mut checked = 0;+ for ttf in [REGULAR_TTF, MEDIUM_TTF] {+ let font = FontRef::try_from_slice(ttf).unwrap();+ for ch in super::metrics::charset() {+ let id = font.glyph_id(ch);+ let Some(outlined) = font.outline_glyph(id.with_scale(48.0)) else { continue };+ let bounds = outlined.px_bounds();+ let (w, h) = (bounds.width().ceil() as u32, bounds.height().ceil() as u32);+ if w == 0 || h == 0 {+ continue;+ }+ let mut coverage = vec![0u8; (w * h) as usize];+ outlined.draw(|x, y, v| {+ if x < w && y < h {+ coverage[(y * w + x) as usize] = (v * 255.0) as u8;+ }+ });+ let placement = place_in_cell(w, h);+ assert_eq!(+ sdf_from_coverage(&coverage, w, h, placement),+ sdf_from_coverage_reference(&coverage, w, h, placement),+ "SDF of {ch:?} differs from the reference"+ );+ checked += 1;+ }+ }+ assert!(checked > 400, "only {checked} glyphs checked");+}