Skip to main content

basemapper_core/vector/
symbol.rs

1//! Point text labels: a port of MapLibre GL JS's symbol pipeline.
2//!
3//! - Glyph PBFs (`style/parse_glyph_pbf.ts`): SDF bitmaps with a 3 px border.
4//! - Shaping (`symbol/shaping.ts`, `symbol/tagged_string.ts`): line breaking
5//!   by least badness, justification, anchor alignment, letter spacing.
6//! - Quads (`symbol/quads.ts`) with corner offsets stored at 1/32 precision
7//!   (`symbol_bucket.ts addVertex`).
8//! - Anchors (`symbol/symbol_layout.ts addFeature`): points, the first vertex
9//!   of lines, and the pole of inaccessibility of polygons; anchors outside
10//!   the tile are dropped.
11//! - Placement (`symbol/placement.ts`, `symbol/collision_index.ts`): layers
12//!   top-down, tiles by (x, y), features by sort key; boxes in a viewport grid
13//!   padded by 100 px.
14//! - Drawing (`webgl/draw/draw_symbol.ts`, `symbol_sdf.*.glsl`): bilinear SDF
15//!   sampling, EDGE_GAMMA, one- or two-pass halos.
16//!
17//! - Icons (`render/image_atlas.ts`, `getIconQuads`, `symbol_icon.*.glsl`):
18//!   premultiplied sprite images with 1 px padding, NEAREST/LINEAR per
19//!   draw_symbol.ts, SDF icons through the text shader; text/icon placement
20//!   combined through text-optional / icon-optional.
21//!
22//! - Line placement (`symbol_line.rs`): merged, clipped lines; anchors by
23//!   spacing and max angle; collision circles; glyphs placed along the
24//!   projected line with keep-upright flipping.
25//!
26//! - Vertical text (`vertical.rs`): point labels with `text-writing-mode`
27//!   vertical (upright glyphs, the label turned 90°, tried in the layer's
28//!   writing-mode order) and line labels whose line runs vertically
29//!   (updateLineLabels switches to the vertical shaping).
30
31use super::expr::{eval_filter, eval_property, is_data_driven, Color, Ctx, Kind, Val};
32use super::gl::{raster_triangle, smoothstep, Clip, Framebuffer, Vert, EXTENT};
33use super::mvt::{Feature, Geometry, Value};
34use super::symbol_line::{self as line, ProjectedLine};
35use prost::Message;
36use serde_json::Value as Json;
37use std::collections::{HashMap, HashSet};
38
39const ONE_EM: f64 = 24.0;
40const GLYPH_PBF_BORDER: f64 = 3.0;
41const ATLAS_PADDING: i64 = 1;
42const SHAPING_DEFAULT_OFFSET: f64 = -17.0;
43const VIEWPORT_PADDING: f64 = 100.0;
44const SDF_PX: f64 = 8.0;
45const EDGE_GAMMA: f64 = 0.105;
46
47// ── Glyph PBFs ───────────────────────────────────────────────────────────────
48
49#[derive(Clone, PartialEq, Message)]
50struct PbGlyphs {
51    #[prost(message, repeated, tag = "1")]
52    stacks: Vec<PbFontstack>,
53}
54
55#[derive(Clone, PartialEq, Message)]
56struct PbFontstack {
57    #[prost(string, optional, tag = "1")]
58    name: Option<String>,
59    #[prost(string, optional, tag = "2")]
60    range: Option<String>,
61    #[prost(message, repeated, tag = "3")]
62    glyphs: Vec<PbGlyph>,
63}
64
65#[derive(Clone, PartialEq, Message)]
66struct PbGlyph {
67    #[prost(uint32, optional, tag = "1")]
68    id: Option<u32>,
69    #[prost(bytes = "vec", optional, tag = "2")]
70    bitmap: Option<Vec<u8>>,
71    #[prost(uint32, optional, tag = "3")]
72    width: Option<u32>,
73    #[prost(uint32, optional, tag = "4")]
74    height: Option<u32>,
75    #[prost(sint32, optional, tag = "5")]
76    left: Option<i32>,
77    #[prost(sint32, optional, tag = "6")]
78    top: Option<i32>,
79    #[prost(uint32, optional, tag = "7")]
80    advance: Option<u32>,
81}
82
83/// A glyph as laid out in MapLibre's atlas: the SDF bitmap (glyph + 3 px
84/// border) surrounded by 1 px of zero padding.
85#[derive(Clone, Debug)]
86pub struct Glyph {
87    pub width: f64,
88    pub height: f64,
89    pub left: f64,
90    pub top: f64,
91    pub advance: f64,
92    /// Atlas cell size (bitmap + 2 * padding).
93    pub rect_w: usize,
94    pub rect_h: usize,
95    /// Padded cell pixels, `rect_w * rect_h`.
96    pub cell: Vec<u8>,
97}
98
99impl Glyph {
100    /// Bilinear sample (GL_LINEAR) at atlas-cell coordinates; zero outside,
101    /// as the neighbouring atlas texels are padding.
102    fn sample(&self, tx: f64, ty: f64) -> f64 {
103        let x = tx - 0.5;
104        let y = ty - 0.5;
105        let (x0, y0) = (x.floor(), y.floor());
106        let (fx, fy) = (x - x0, y - y0);
107        let px = |ix: i64, iy: i64| -> f64 {
108            if ix < 0 || iy < 0 || ix >= self.rect_w as i64 || iy >= self.rect_h as i64 {
109                0.0
110            } else {
111                self.cell[iy as usize * self.rect_w + ix as usize] as f64
112            }
113        };
114        let (ix, iy) = (x0 as i64, y0 as i64);
115        let top = px(ix, iy) * (1.0 - fx) + px(ix + 1, iy) * fx;
116        let bot = px(ix, iy + 1) * (1.0 - fx) + px(ix + 1, iy + 1) * fx;
117        (top * (1.0 - fy) + bot * fy) / 255.0
118    }
119}
120
121/// Glyphs by font stack (comma-joined, as in the glyph URL) and code point.
122#[derive(Default)]
123pub struct GlyphMap {
124    pub stacks: HashMap<String, HashMap<u32, Glyph>>,
125}
126
127impl GlyphMap {
128    pub fn add_pbf(&mut self, fontstack: &str, bytes: &[u8]) -> Result<(), String> {
129        let pb = PbGlyphs::decode(bytes).map_err(|e| format!("glyph pbf: {e}"))?;
130        let stack = self.stacks.entry(fontstack.to_owned()).or_default();
131        for fs in pb.stacks {
132            for g in fs.glyphs {
133                let (w, h) = (g.width.unwrap_or(0) as usize, g.height.unwrap_or(0) as usize);
134                let bw = w + 2 * GLYPH_PBF_BORDER as usize;
135                let bh = h + 2 * GLYPH_PBF_BORDER as usize;
136                let bitmap = g.bitmap.unwrap_or_default();
137                let pad = ATLAS_PADDING as usize;
138                let (rw, rh) = (bw + 2 * pad, bh + 2 * pad);
139                let mut cell = vec![0u8; rw * rh];
140                if bitmap.len() >= bw * bh {
141                    for y in 0..bh {
142                        cell[(y + pad) * rw + pad..(y + pad) * rw + pad + bw]
143                            .copy_from_slice(&bitmap[y * bw..y * bw + bw]);
144                    }
145                }
146                stack.insert(
147                    g.id.unwrap_or(0),
148                    Glyph {
149                        width: w as f64,
150                        height: h as f64,
151                        left: g.left.unwrap_or(0) as f64,
152                        top: g.top.unwrap_or(0) as f64,
153                        advance: g.advance.unwrap_or(0) as f64,
154                        rect_w: rw,
155                        rect_h: rh,
156                        cell,
157                    },
158                );
159            }
160        }
161        Ok(())
162    }
163}
164
165// ── Text evaluation ──────────────────────────────────────────────────────────
166
167fn prop_string(f: &Feature, key: &str) -> String {
168    match f.properties.get(key) {
169        Some(Value::String(s)) => s.clone(),
170        Some(Value::Number(n)) => {
171            if n.fract() == 0.0 && n.abs() < 1e15 {
172                format!("{}", *n as i64)
173            } else {
174                n.to_string()
175            }
176        }
177        Some(Value::Bool(b)) => b.to_string(),
178        None => String::new(),
179    }
180}
181
182fn val_text(v: Val) -> Option<String> {
183    match v {
184        Val::Str(s) => Some(s),
185        Val::Num(n) => Some(if n.fract() == 0.0 && n.abs() < 1e15 { format!("{}", n as i64) } else { n.to_string() }),
186        Val::Bool(b) => Some(b.to_string()),
187        _ => None,
188    }
189}
190
191/// The label text a symbol layer shows for a feature (text-field + tokens +
192/// format + text-transform), or None.
193pub fn feature_text(layer: &Json, f: &Feature, zoom: f64) -> Option<String> {
194    let layout = &layer["layout"];
195    let tf = layout.get("text-field")?;
196    let ctx = Ctx { zoom, feature: Some(f) };
197    // Legacy "{token}" interpolation (getValueAndResolveTokens / the
198    // style-spec's convertTokenString): plain strings and the stop values of
199    // legacy functions; not expressions.
200    let resolve_tokens = |s: &str| -> String {
201        let mut out = String::new();
202        let mut rest = s;
203        while let Some(i) = rest.find('{') {
204            out.push_str(&rest[..i]);
205            let Some(j) = rest[i..].find('}') else {
206                out.push_str(&rest[i..]);
207                rest = "";
208                break;
209            };
210            out.push_str(&prop_string(f, &rest[i + 1..i + j]));
211            rest = &rest[i + j + 1..];
212        }
213        out.push_str(rest);
214        out
215    };
216    let text = match tf {
217        Json::String(s) => resolve_tokens(s),
218        Json::Object(_) => resolve_tokens(&val_text(eval_property(tf, Kind::Enum, &ctx))?),
219        Json::Array(a) if a.first().and_then(|v| v.as_str()) == Some("format") => {
220            let mut out = String::new();
221            let mut i = 1;
222            while i < a.len() {
223                if !a[i].is_object() {
224                    if let Some(t) = val_text(eval_property(&a[i], Kind::Enum, &ctx)) {
225                        out.push_str(&t);
226                    }
227                }
228                i += 1;
229            }
230            out
231        }
232        other => val_text(eval_property(other, Kind::Enum, &ctx))?,
233    };
234    let transform = layout
235        .get("text-transform")
236        .map(|j| eval_property(j, Kind::Enum, &ctx))
237        .and_then(|v| v.as_str().map(str::to_owned));
238    let text = match transform.as_deref() {
239        Some("uppercase") => text.to_uppercase(),
240        Some("lowercase") => text.to_lowercase(),
241        _ => text,
242    };
243    // transformText: Arabic shaping (the RTL text plugin's applyArabicShaping).
244    Some(super::rtl::apply_arabic_shaping(&text))
245}
246
247/// The comma-joined font stack of a symbol layer for a feature.
248pub fn feature_fontstack(layer: &Json, f: Option<&Feature>, zoom: f64) -> String {
249    let ctx = Ctx { zoom, feature: f };
250    match layer["layout"].get("text-font") {
251        // A plain list of font names (the common case) is a literal, not an
252        // expression, even though its first element is a string.
253        Some(Json::Array(a)) if !a.is_empty() && a.iter().all(|v| v.is_string()) => {
254            a.iter().filter_map(|v| v.as_str()).collect::<Vec<_>>().join(",")
255        }
256        Some(j) => match eval_property(j, Kind::Array, &ctx) {
257            Val::Array(a) => a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect::<Vec<_>>().join(","),
258            _ => "Open Sans Regular,Arial Unicode MS Regular".into(),
259        },
260        None => "Open Sans Regular,Arial Unicode MS Regular".into(),
261    }
262}
263
264/// Glyph ranges (font stack, range start) the visible symbol layers need.
265pub fn required_glyph_ranges<'a>(
266    style: &Json,
267    tiles: impl Iterator<Item = &'a super::mvt::Tile> + Clone,
268    zoom: f64,
269) -> HashSet<(String, u32)> {
270    let mut out = HashSet::new();
271    for layer in style["layers"].as_array().map(|v| v.as_slice()).unwrap_or(&[]) {
272        if layer["type"] != "symbol" || layer["layout"].get("text-field").is_none() || !layer_visible(layer, zoom) {
273            continue;
274        }
275        let sl = super::mvt::source_layer(layer);
276        // calculateGlyphDependencies: text that can be written vertically
277        // also needs its punctuation's vertical forms (along lines, or with
278        // vertical point placement).
279        let layout = &layer["layout"];
280        let placement = super::expr::layout_enum(layout, "symbol-placement", zoom).unwrap_or_else(|| "point".into());
281        let along = placement != "point" && super::expr::layout_enum(layout, "text-rotation-alignment", zoom).as_deref() != Some("viewport");
282        let vertical_possible = along || (placement == "point" && writing_modes(layout).contains(&true));
283        for t in tiles.clone() {
284            let Some(l) = t.layers.get(sl) else { continue };
285            for f in &l.features {
286                let ctx = Ctx { zoom, feature: Some(f) };
287                if layer.get("filter").map_or(false, |flt| !eval_filter(flt, &ctx)) {
288                    continue;
289                }
290                if let Some(text) = feature_text(layer, f, zoom) {
291                    let stack = feature_fontstack(layer, Some(f), zoom);
292                    let vertical = vertical_possible && super::vertical::allows_vertical_writing_mode(&text);
293                    for ch in text.chars() {
294                        out.insert((stack.clone(), (ch as u32 / 256) * 256));
295                        if let Some(v) = super::vertical::verticalized(ch).filter(|_| vertical) {
296                            out.insert((stack.clone(), (v as u32 / 256) * 256));
297                        }
298                    }
299                }
300            }
301        }
302    }
303    out
304}
305
306/// text-writing-mode of a point-placed layer, duplicates removed (true =
307/// vertical); `["horizontal"]` when unset.
308fn writing_modes(layout: &Json) -> Vec<bool> {
309    let mut out: Vec<bool> = Vec::new();
310    for m in layout["text-writing-mode"].as_array().map(|v| v.as_slice()).unwrap_or(&[]) {
311        let v = match m.as_str() {
312            Some("vertical") => true,
313            Some("horizontal") => false,
314            _ => continue,
315        };
316        if !out.contains(&v) {
317            out.push(v);
318        }
319    }
320    if out.is_empty() {
321        out.push(false);
322    }
323    out
324}
325
326pub fn layer_visible(layer: &Json, zoom: f64) -> bool {
327    layer["layout"]["visibility"] != "none"
328        && !layer["minzoom"].as_f64().map_or(false, |mz| zoom < mz)
329        && !layer["maxzoom"].as_f64().map_or(false, |mz| zoom >= mz)
330}
331
332// ── Shaping ──────────────────────────────────────────────────────────────────
333
334#[derive(Clone, Debug)]
335struct PositionedGlyph {
336    codepoint: u32,
337    x: f64,
338    y: f64,
339    /// Upright in a vertical shaping (isLineVertical).
340    vertical: bool,
341}
342
343#[derive(Clone, Debug)]
344pub struct Shaping {
345    lines: Vec<Vec<PositionedGlyph>>,
346    top: f64,
347    bottom: f64,
348    left: f64,
349    right: f64,
350}
351
352fn is_whitespace(c: char) -> bool {
353    c.is_whitespace()
354}
355
356fn breakable(cp: u32) -> bool {
357    matches!(cp, 0x0a | 0x20 | 0x26 | 0x29 | 0x2b | 0x2d | 0x2f | 0xad | 0xb7 | 0x200b | 0x2010 | 0x2013 | 0x2027)
358}
359
360/// codePointAllowsIdeographicBreaking.
361fn allows_ideographic_breaking(cp: u32) -> bool {
362    super::vertical::ideographic_breaking(cp)
363}
364
365struct Break {
366    index: usize,
367    x: f64,
368    prior: Option<usize>,
369    badness: f64,
370}
371
372fn badness(line_width: f64, target: f64, penalty: f64, is_last: bool) -> f64 {
373    let raggedness = (line_width - target).powi(2);
374    if is_last {
375        if line_width < target { raggedness / 2.0 } else { raggedness * 2.0 }
376    } else {
377        raggedness + penalty.abs() * penalty
378    }
379}
380
381fn penalty(cp: u32, next: u32, ideographic: bool) -> f64 {
382    let mut p = 0.0;
383    if cp == 0x0a {
384        p -= 10000.0;
385    }
386    if ideographic {
387        p += 150.0;
388    }
389    if cp == 0x28 || cp == 0xff08 {
390        p += 50.0;
391    }
392    if next == 0x29 || next == 0xff09 {
393        p += 50.0;
394    }
395    p
396}
397
398fn evaluate_break(index: usize, x: f64, target: f64, breaks: &[Break], pen: f64, is_last: bool) -> Break {
399    let mut best: Option<usize> = None;
400    let mut best_badness = badness(x, target, pen, is_last);
401    for (i, b) in breaks.iter().enumerate() {
402        let bb = badness(x - b.x, target, pen, is_last) + b.badness;
403        if bb <= best_badness {
404            best = Some(i);
405            best_badness = bb;
406        }
407    }
408    Break { index, x, prior: best, badness: best_badness }
409}
410
411fn determine_line_breaks(chars: &[char], spacing: f64, max_width: f64, glyphs: &HashMap<u32, Glyph>) -> Vec<usize> {
412    let advance = |c: char| glyphs.get(&(c as u32)).map_or(0.0, |g| g.advance + spacing);
413    let total: f64 = chars.iter().map(|&c| advance(c)).sum();
414    let line_count = (total / max_width).ceil().max(1.0);
415    let target = total / line_count;
416    let has_zwsp = chars.contains(&'\u{200b}');
417
418    let mut breaks: Vec<Break> = Vec::new();
419    let mut x = 0.0;
420    for i in 0..chars.len() {
421        let cp = chars[i] as u32;
422        if !is_whitespace(chars[i]) {
423            x += advance(chars[i]);
424        }
425        if i + 1 < chars.len() {
426            let ideographic = allows_ideographic_breaking(cp);
427            let next = chars[i + 1] as u32;
428            let next_next_exists = i + 2 < chars.len();
429            if breakable(cp) || ideographic || (next_next_exists && next == 0x28) {
430                let b = evaluate_break(i + 1, x, target, &breaks, penalty(cp, next, ideographic && has_zwsp), false);
431                breaks.push(b);
432            }
433        }
434    }
435    let last = evaluate_break(chars.len(), x, target, &breaks, 0.0, true);
436    let mut out = vec![last.index];
437    let mut prior = last.prior;
438    while let Some(p) = prior {
439        out.push(breaks[p].index);
440        prior = breaks[p].prior;
441    }
442    out.reverse();
443    out
444}
445
446fn anchor_alignment(anchor: &str) -> (f64, f64) {
447    let h = match anchor {
448        "right" | "top-right" | "bottom-right" => 1.0,
449        "left" | "top-left" | "bottom-left" => 0.0,
450        _ => 0.5,
451    };
452    let v = match anchor {
453        "bottom" | "bottom-right" | "bottom-left" => 1.0,
454        "top" | "top-right" | "top-left" => 0.0,
455        _ => 0.5,
456    };
457    (h, v)
458}
459
460fn trim_line(line: &[char]) -> &[char] {
461    let start = line.iter().position(|c| !is_whitespace(*c)).unwrap_or(line.len());
462    let end = line.iter().rposition(|c| !is_whitespace(*c)).map_or(start, |e| e + 1);
463    &line[start..end.max(start)]
464}
465
466#[allow(clippy::too_many_arguments)]
467fn shape_text(
468    text: &str,
469    glyphs: &HashMap<u32, Glyph>,
470    max_width: f64,
471    line_height: f64,
472    anchor: &str,
473    justify: &str,
474    spacing: f64,
475    translate: (f64, f64),
476    vertical_mode: bool,
477    allow_vertical_placement: bool,
478) -> Option<Shaping> {
479    let mut chars: Vec<char> = text.chars().collect();
480    if vertical_mode {
481        chars = super::vertical::verticalize_punctuation(&chars);
482    }
483    let breaks = determine_line_breaks(&chars, spacing, max_width, glyphs);
484    // Lines broken on the logical text, each reordered for display
485    // (the RTL text plugin's processBidirectionalText).
486    let lines: Vec<Vec<char>> = super::rtl::process_bidi(&chars, &breaks);
487
488    let justify_f = match justify {
489        "right" => 1.0,
490        "left" => 0.0,
491        _ => 0.5,
492    };
493    let mut positioned: Vec<Vec<PositionedGlyph>> = Vec::new();
494    let (mut y, mut max_line_length, mut max_line_height) = (0.0, 0.0f64, 0.0f64);
495    for line in &lines {
496        let line = trim_line(line);
497        let mut pg: Vec<PositionedGlyph> = Vec::new();
498        if line.is_empty() {
499            y += line_height;
500            positioned.push(pg);
501            continue;
502        }
503        let mut x = 0.0;
504        for &c in line {
505            let cp = c as u32;
506            let Some(g) = glyphs.get(&cp) else { continue };
507            // Upright glyphs of a vertical shaping advance one em.
508            let vertical = vertical_mode && super::vertical::glyph_is_vertical(cp, allow_vertical_placement);
509            pg.push(PositionedGlyph { codepoint: cp, x, y: y + SHAPING_DEFAULT_OFFSET, vertical });
510            x += if vertical { ONE_EM } else { g.advance } + spacing;
511        }
512        if !pg.is_empty() {
513            let line_length = x - spacing;
514            max_line_length = max_line_length.max(line_length);
515            // justifyLine
516            if justify_f != 0.0 {
517                let last = pg.last().unwrap();
518                let indent = (last.x + glyphs[&last.codepoint].advance) * justify_f;
519                for p in &mut pg {
520                    p.x -= indent;
521                }
522            }
523        }
524        let current_line_height = line_height;
525        y += current_line_height;
526        max_line_height = max_line_height.max(current_line_height);
527        positioned.push(pg);
528    }
529    if positioned.iter().all(|l| l.is_empty()) {
530        return None;
531    }
532    let (ha, va) = anchor_alignment(anchor);
533    // align()
534    let shift_x = (justify_f - ha) * max_line_length;
535    let shift_y = if max_line_height != line_height {
536        -y * va - SHAPING_DEFAULT_OFFSET
537    } else {
538        -va * lines.len() as f64 * line_height + 0.5 * line_height
539    };
540    for l in &mut positioned {
541        for p in l {
542            p.x += shift_x;
543            p.y += shift_y;
544        }
545    }
546    let top = translate.1 - va * y;
547    let left = translate.0 - ha * max_line_length;
548    Some(Shaping { lines: positioned, top, bottom: top + y, left, right: left + max_line_length })
549}
550
551// ── Quads ────────────────────────────────────────────────────────────────────
552
553#[derive(Clone, Debug)]
554struct GlyphQuad {
555    /// Corner offsets tl, tr, bl, br in glyph-em units, quantised to 1/32.
556    corners: [(f64, f64); 4],
557    codepoint: u32,
558}
559
560/// JavaScript Math.round.
561fn js_round(x: f64) -> f64 {
562    (x + 0.5).floor()
563}
564
565/// getGlyphQuads' rotation of an upright glyph in a vertical shaping: 90°
566/// counter-clockwise about the left-edge centre of its em box, then the
567/// half-width correction and `then` (the label offset it was laid out at).
568fn rotate_vertical_glyph(corners: &mut [(f64, f64); 4], half_advance: f64, then: (f64, f64)) {
569    let center = (-half_advance, half_advance - SHAPING_DEFAULT_OFFSET);
570    let (cos, sin) = ((-std::f64::consts::FRAC_PI_2).cos(), (-std::f64::consts::FRAC_PI_2).sin());
571    let x_half_width_correction = ONE_EM / 2.0 - half_advance;
572    let correction = (5.0 - SHAPING_DEFAULT_OFFSET - x_half_width_correction, 0.0);
573    for p in corners.iter_mut() {
574        let (dx, dy) = (p.0 - center.0, p.1 - center.1);
575        let r = (center.0 + cos * dx - sin * dy, center.1 + sin * dx + cos * dy);
576        *p = (r.0 + correction.0 + then.0, r.1 + correction.1 + then.1);
577    }
578}
579
580/// Point-label glyph quads; `allow_vertical` (vertical point placement)
581/// rotates the upright glyphs of a vertical shaping.
582fn glyph_quads(shaping: &Shaping, glyphs: &HashMap<u32, Glyph>, offset: (f64, f64), rotate_deg: f64, allow_vertical: bool) -> Vec<GlyphQuad> {
583    let rect_buffer = GLYPH_PBF_BORDER + ATLAS_PADDING as f64;
584    let (s, c) = (rotate_deg.to_radians().sin(), rotate_deg.to_radians().cos());
585    let mut quads = Vec::new();
586    for line in &shaping.lines {
587        for pg in line {
588            let g = &glyphs[&pg.codepoint];
589            let half_advance = g.advance / 2.0;
590            let mut built_in = (pg.x + half_advance + offset.0, pg.y + offset.1);
591            let rotate_vertical = allow_vertical && pg.vertical;
592            let mut verticalized_offset = (0.0, 0.0);
593            if rotate_vertical {
594                verticalized_offset = built_in;
595                built_in = (0.0, 0.0);
596            }
597            let x1 = (g.left - rect_buffer) - half_advance + built_in.0;
598            let y1 = (-g.top - rect_buffer) + built_in.1;
599            let x2 = x1 + g.rect_w as f64;
600            let y2 = y1 + g.rect_h as f64;
601            let mut corners = [(x1, y1), (x2, y1), (x1, y2), (x2, y2)];
602            if rotate_vertical {
603                rotate_vertical_glyph(&mut corners, half_advance, verticalized_offset);
604            }
605            if rotate_deg != 0.0 {
606                for p in &mut corners {
607                    *p = (c * p.0 - s * p.1, s * p.0 + c * p.1);
608                }
609            }
610            // a_offset = Math.round(o * 32), decoded as a_offset / 32.
611            for p in &mut corners {
612                *p = (js_round(p.0 * 32.0) / 32.0, js_round(p.1 * 32.0) / 32.0);
613            }
614            quads.push(GlyphQuad { corners, codepoint: pg.codepoint });
615        }
616    }
617    quads
618}
619
620// ── Pole of inaccessibility (util/find_pole_of_inaccessibility.ts) ──────────
621
622#[derive(Clone, Copy)]
623struct Cell {
624    x: f64,
625    y: f64,
626    h: f64,
627    d: f64,
628    max: f64,
629}
630
631fn dist_to_segment_sq(px: f64, py: f64, v: (f64, f64), w: (f64, f64)) -> f64 {
632    let l2 = (v.0 - w.0).powi(2) + (v.1 - w.1).powi(2);
633    if l2 == 0.0 {
634        return (px - v.0).powi(2) + (py - v.1).powi(2);
635    }
636    let t = ((px - v.0) * (w.0 - v.0) + (py - v.1) * (w.1 - v.1)) / l2;
637    if t < 0.0 {
638        return (px - v.0).powi(2) + (py - v.1).powi(2);
639    }
640    if t > 1.0 {
641        return (px - w.0).powi(2) + (py - w.1).powi(2);
642    }
643    let (qx, qy) = (v.0 + (w.0 - v.0) * t, v.1 + (w.1 - v.1) * t);
644    (px - qx).powi(2) + (py - qy).powi(2)
645}
646
647fn point_to_polygon_dist(px: f64, py: f64, poly: &[Vec<(f64, f64)>]) -> f64 {
648    let mut inside = false;
649    let mut min_sq = f64::INFINITY;
650    for ring in poly {
651        let len = ring.len();
652        let mut j = len.wrapping_sub(1);
653        for i in 0..len {
654            let a = ring[i];
655            let b = ring[j];
656            if (a.1 > py) != (b.1 > py) && px < (b.0 - a.0) * (py - a.1) / (b.1 - a.1) + a.0 {
657                inside = !inside;
658            }
659            min_sq = min_sq.min(dist_to_segment_sq(px, py, a, b));
660            j = i;
661        }
662    }
663    (if inside { 1.0 } else { -1.0 }) * min_sq.sqrt()
664}
665
666fn cell(x: f64, y: f64, h: f64, poly: &[Vec<(f64, f64)>]) -> Cell {
667    let d = point_to_polygon_dist(x, y, poly);
668    Cell { x, y, h, d, max: d + h * std::f64::consts::SQRT_2 }
669}
670
671/// tinyqueue with compareMax (b.max - a.max): a max-heap on `max`.
672struct Queue {
673    data: Vec<Cell>,
674}
675
676impl Queue {
677    fn cmp(a: &Cell, b: &Cell) -> f64 {
678        b.max - a.max
679    }
680    fn push(&mut self, item: Cell) {
681        self.data.push(item);
682        let mut pos = self.data.len() - 1;
683        while pos > 0 {
684            let parent = (pos - 1) >> 1;
685            if Self::cmp(&item, &self.data[parent]) >= 0.0 {
686                break;
687            }
688            self.data[pos] = self.data[parent];
689            pos = parent;
690        }
691        self.data[pos] = item;
692    }
693    fn pop(&mut self) -> Option<Cell> {
694        if self.data.is_empty() {
695            return None;
696        }
697        let top = self.data[0];
698        let bottom = self.data.pop().unwrap();
699        if !self.data.is_empty() {
700            let len = self.data.len();
701            let half = len >> 1;
702            let item = bottom;
703            let mut pos = 0;
704            while pos < half {
705                let mut left = (pos << 1) + 1;
706                let mut best = self.data[left];
707                let right = left + 1;
708                if right < len && Self::cmp(&self.data[right], &best) < 0.0 {
709                    left = right;
710                    best = self.data[right];
711                }
712                if Self::cmp(&best, &item) >= 0.0 {
713                    break;
714                }
715                self.data[pos] = best;
716                pos = left;
717            }
718            self.data[pos] = item;
719        }
720        Some(top)
721    }
722}
723
724fn pole_of_inaccessibility(poly: &[Vec<(f64, f64)>], precision: f64) -> (f64, f64) {
725    let outer = &poly[0];
726    let (mut minx, mut miny, mut maxx, mut maxy) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
727    for p in outer {
728        minx = minx.min(p.0);
729        miny = miny.min(p.1);
730        maxx = maxx.max(p.0);
731        maxy = maxy.max(p.1);
732    }
733    let cell_size = (maxx - minx).min(maxy - miny);
734    let h = cell_size / 2.0;
735    if cell_size == 0.0 {
736        return (minx, miny);
737    }
738    let mut q = Queue { data: Vec::new() };
739    let mut x = minx;
740    while x < maxx {
741        let mut y = miny;
742        while y < maxy {
743            q.push(cell(x + h, y + h, h, poly));
744            y += cell_size;
745        }
746        x += cell_size;
747    }
748    // Centroid of the outer ring.
749    let (mut area, mut cx, mut cy) = (0.0, 0.0, 0.0);
750    let len = outer.len();
751    let mut j = len - 1;
752    for i in 0..len {
753        let (a, b) = (outer[i], outer[j]);
754        let f = a.0 * b.1 - b.0 * a.1;
755        cx += (a.0 + b.0) * f;
756        cy += (a.1 + b.1) * f;
757        area += f * 3.0;
758        j = i;
759    }
760    let centroid = cell(cx / area, cy / area, 0.0, poly);
761    let mut best = centroid;
762    while let Some(c) = q.pop() {
763        if c.d > best.d || best.d == 0.0 {
764            best = c;
765        }
766        if c.max - best.d <= precision {
767            continue;
768        }
769        let h = c.h / 2.0;
770        q.push(cell(c.x - h, c.y - h, h, poly));
771        q.push(cell(c.x + h, c.y - h, h, poly));
772        q.push(cell(c.x - h, c.y + h, h, poly));
773        q.push(cell(c.x + h, c.y + h, h, poly));
774    }
775    if centroid.d > 0.0 && best.d - centroid.d <= precision {
776        return (centroid.x, centroid.y);
777    }
778    (best.x, best.y)
779}
780
781// ── Sprites ──────────────────────────────────────────────────────────────────
782
783/// A sprite image as MapLibre stores it in its icon atlas: premultiplied RGBA
784/// (`premultiplyAlpha`, Math.round(c * a / 255)) with 1 px of zero padding.
785#[derive(Clone, Debug)]
786pub struct SpriteImage {
787    pub w: usize,
788    pub h: usize,
789    pub pixel_ratio: f64,
790    pub sdf: bool,
791    /// Stretchable image metadata (image px): content box [x1, y1, x2, y2]
792    /// and stretch ranges, used with icon-text-fit.
793    pub content: Option<[f64; 4]>,
794    pub stretch_x: Option<Vec<(f64, f64)>>,
795    pub stretch_y: Option<Vec<(f64, f64)>>,
796    /// (w + 2) * (h + 2) * 4 bytes.
797    pub cell: Vec<u8>,
798}
799
800impl SpriteImage {
801    /// The image as a straight-alpha PNG data URI (unpadded).
802    pub fn png_data_uri(&self) -> String {
803        let cw = self.w + 2;
804        let mut rgba = Vec::with_capacity(self.w * self.h * 4);
805        for row in 0..self.h {
806            for col in 0..self.w {
807                let o = ((row + 1) * cw + col + 1) * 4;
808                let a = self.cell[o + 3] as u32;
809                for k in 0..3 {
810                    let c = self.cell[o + k] as u32;
811                    rgba.push(if a == 0 { 0 } else { ((c * 255 + a / 2) / a).min(255) as u8 });
812                }
813                rgba.push(a as u8);
814            }
815        }
816        super::svg::png_data_uri(self.w as u32, self.h as u32, &rgba)
817    }
818
819    /// GL_LINEAR sample at image-pixel coordinates (u, v), wrapping around the
820    /// edges: pattern images are stored in MapLibre's atlas with their
821    /// opposite edges copied into the padding. Premultiplied 0..=255.
822    pub fn sample_wrapped(&self, u: f64, v: f64) -> [f64; 4] {
823        let (w, h) = (self.w as i64, self.h as i64);
824        let (x, y) = (u - 0.5, v - 0.5);
825        let (x0, y0) = (x.floor(), y.floor());
826        let (fx, fy) = (x - x0, y - y0);
827        let t = |ix: i64, iy: i64| self.texel(ix.rem_euclid(w) + 1, iy.rem_euclid(h) + 1);
828        let (ix, iy) = (x0 as i64, y0 as i64);
829        let (a, b, c, d) = (t(ix, iy), t(ix + 1, iy), t(ix, iy + 1), t(ix + 1, iy + 1));
830        let mut out = [0.0; 4];
831        for i in 0..4 {
832            out[i] = (a[i] * (1.0 - fx) + b[i] * fx) * (1.0 - fy) + (c[i] * (1.0 - fx) + d[i] * fx) * fy;
833        }
834        out
835    }
836
837    /// GL_LINEAR sample of a pattern image as it sits in MapLibre's atlas, at
838    /// padded-cell coordinates: the 1 px padding holds the opposite edges
839    /// (wrapped), anything beyond it is transparent. Premultiplied 0..=255.
840    pub fn sample_atlas_pattern(&self, tx: f64, ty: f64) -> [f64; 4] {
841        let (w, h) = (self.w as i64, self.h as i64);
842        let wrap = |i: i64, n: i64| -> Option<i64> {
843            match i {
844                0 => Some(n),
845                i if i == n + 1 => Some(1),
846                i if i >= 1 && i <= n => Some(i),
847                _ => None,
848            }
849        };
850        let t = |ix: i64, iy: i64| match (wrap(ix, w), wrap(iy, h)) {
851            (Some(x), Some(y)) => self.texel(x, y),
852            _ => [0.0; 4],
853        };
854        let (x, y) = (tx - 0.5, ty - 0.5);
855        let (x0, y0) = (x.floor(), y.floor());
856        let (fx, fy) = (x - x0, y - y0);
857        let (ix, iy) = (x0 as i64, y0 as i64);
858        let (a, b, c, d) = (t(ix, iy), t(ix + 1, iy), t(ix, iy + 1), t(ix + 1, iy + 1));
859        let mut out = [0.0; 4];
860        for i in 0..4 {
861            out[i] = (a[i] * (1.0 - fx) + b[i] * fx) * (1.0 - fy) + (c[i] * (1.0 - fx) + d[i] * fx) * fy;
862        }
863        out
864    }
865
866    fn texel(&self, ix: i64, iy: i64) -> [f64; 4] {
867        let (cw, ch) = (self.w as i64 + 2, self.h as i64 + 2);
868        if ix < 0 || iy < 0 || ix >= cw || iy >= ch {
869            return [0.0; 4];
870        }
871        let o = ((iy * cw + ix) * 4) as usize;
872        [self.cell[o] as f64, self.cell[o + 1] as f64, self.cell[o + 2] as f64, self.cell[o + 3] as f64]
873    }
874
875    /// Sample at padded-cell coordinates; GL_LINEAR or GL_NEAREST. 0..=255.
876    fn sample(&self, tx: f64, ty: f64, linear: bool) -> [f64; 4] {
877        if !linear {
878            return self.texel(tx.floor() as i64, ty.floor() as i64);
879        }
880        let (x, y) = (tx - 0.5, ty - 0.5);
881        let (x0, y0) = (x.floor(), y.floor());
882        let (fx, fy) = (x - x0, y - y0);
883        let (ix, iy) = (x0 as i64, y0 as i64);
884        let (a, b, c, d) = (self.texel(ix, iy), self.texel(ix + 1, iy), self.texel(ix, iy + 1), self.texel(ix + 1, iy + 1));
885        let mut out = [0.0; 4];
886        for i in 0..4 {
887            out[i] = (a[i] * (1.0 - fx) + b[i] * fx) * (1.0 - fy) + (c[i] * (1.0 - fx) + d[i] * fx) * fy;
888        }
889        out
890    }
891}
892
893fn stretch_ranges(j: &Json) -> Option<Vec<(f64, f64)>> {
894    let a = j.as_array()?;
895    let v: Vec<(f64, f64)> = a
896        .iter()
897        .filter_map(|r| {
898            let r = r.as_array()?;
899            Some((r.first()?.as_f64()?, r.get(1)?.as_f64()?))
900        })
901        .collect();
902    (!v.is_empty()).then_some(v)
903}
904
905#[derive(Default)]
906pub struct Sprite {
907    pub images: HashMap<String, SpriteImage>,
908    /// The device pixel ratio the sprite is drawn at (0 means 1). Icons whose
909    /// image pixelRatio differs are sampled linearly (iconsNeedLinear).
910    pub device_pixel_ratio: f64,
911}
912
913impl Sprite {
914    pub fn dpr(&self) -> f64 {
915        if self.device_pixel_ratio > 0.0 { self.device_pixel_ratio } else { 1.0 }
916    }
917
918    /// Build from a sprite's `.json` index and `.png` sheet.
919    pub fn from_json_png(json: &[u8], png: &[u8]) -> Result<Sprite, String> {
920        let index: Json = serde_json::from_slice(json).map_err(|e| format!("sprite json: {e}"))?;
921        let sheet = image::load_from_memory(png).map_err(|e| format!("sprite png: {e}"))?.to_rgba8();
922        let mut images = HashMap::new();
923        for (name, e) in index.as_object().ok_or("sprite json is not an object")? {
924            let g = |k: &str| e[k].as_u64().unwrap_or(0) as usize;
925            let (x, y, w, h) = (g("x"), g("y"), g("width"), g("height"));
926            if w == 0 || h == 0 || x + w > sheet.width() as usize || y + h > sheet.height() as usize {
927                continue;
928            }
929            let cw = w + 2;
930            let mut cell = vec![0u8; cw * (h + 2) * 4];
931            for row in 0..h {
932                for col in 0..w {
933                    let p = sheet.get_pixel((x + col) as u32, (y + row) as u32).0;
934                    let a = p[3] as f64;
935                    let o = ((row + 1) * cw + col + 1) * 4;
936                    for i in 0..3 {
937                        cell[o + i] = (p[i] as f64 * a / 255.0 + 0.5).floor() as u8;
938                    }
939                    cell[o + 3] = p[3];
940                }
941            }
942            images.insert(
943                name.clone(),
944                SpriteImage {
945                    w,
946                    h,
947                    pixel_ratio: e["pixelRatio"].as_f64().unwrap_or(1.0),
948                    sdf: e["sdf"].as_bool().unwrap_or(false),
949                    content: e["content"].as_array().filter(|a| a.len() == 4).map(|a| {
950                        let v: Vec<f64> = a.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect();
951                        [v[0], v[1], v[2], v[3]]
952                    }),
953                    stretch_x: stretch_ranges(&e["stretchX"]),
954                    stretch_y: stretch_ranges(&e["stretchY"]),
955                    cell,
956                },
957            );
958        }
959        Ok(Sprite { images, device_pixel_ratio: 1.0 })
960    }
961}
962
963/// Everything symbol layers need besides the tiles.
964#[derive(Default)]
965pub struct SymbolAssets {
966    pub glyphs: GlyphMap,
967    pub sprite: Sprite,
968}
969
970/// The icon image name a symbol layer shows for a feature, or None.
971pub fn feature_icon(layer: &Json, f: &Feature, zoom: f64) -> Option<String> {
972    let ii = layer["layout"].get("icon-image")?;
973    let ctx = Ctx { zoom, feature: Some(f) };
974    let name = match ii {
975        Json::String(s) if s.contains('{') => {
976            let mut out = String::new();
977            let mut rest = s.as_str();
978            while let Some(i) = rest.find('{') {
979                out.push_str(&rest[..i]);
980                let Some(j) = rest[i..].find('}') else { break };
981                out.push_str(&prop_string(f, &rest[i + 1..i + j]));
982                rest = &rest[i + j + 1..];
983            }
984            out.push_str(rest);
985            out
986        }
987        other => val_text(eval_property(other, Kind::Enum, &ctx))?,
988    };
989    (!name.is_empty()).then_some(name)
990}
991
992// ── Placement + drawing ──────────────────────────────────────────────────────
993
994/// A tile placed on the canvas, as the renderer sees it.
995pub struct SymbolTile<'a> {
996    /// Style source id the tile belongs to; layers place features only from
997    /// their own source's tiles.
998    pub source: &'a str,
999    pub coord: (u8, u32, u32),
1000    /// World copy (OverscaledTileID.wrap); placement orders by it first.
1001    pub wrap: i32,
1002    pub tile: &'a super::mvt::Tile,
1003    pub ox: f64,
1004    pub oy: f64,
1005    /// Canvas px per 8192-extent tile unit.
1006    pub unit_px: f64,
1007    /// 2^(floor(zoom) - tile z): MapLibre's overscaling.
1008    pub overscaling: f64,
1009}
1010
1011#[derive(Clone)]
1012struct SdfStyle {
1013    fill: Color,
1014    halo: Color,
1015    halo_width: f64,
1016    halo_blur: f64,
1017    opacity: f64,
1018}
1019
1020#[derive(Clone)]
1021struct TextPart {
1022    quads: Vec<GlyphQuad>,
1023    fontstack: String,
1024    size: f64,
1025    style: SdfStyle,
1026    along: Option<AlongLine>,
1027    /// Render shift (px) of a variable-anchor label (calculateVariableRenderShift).
1028    shift: (f64, f64),
1029}
1030
1031/// Geometry for a symbol drawn along a line (updateLineLabels).
1032#[derive(Clone)]
1033struct AlongLine {
1034    /// The symbol's line in screen px (label plane).
1035    line_px: Vec<(f64, f64)>,
1036    segment: usize,
1037    /// Per-quad glyph offsets along the line, in glyph units.
1038    glyph_offsets: Vec<f64>,
1039    line_offset: (f64, f64),
1040    keep_upright: bool,
1041    rotate_to_line: bool,
1042    /// Font scale used for placement along the line (size / 24).
1043    placement_scale: f64,
1044    /// The label's vertical shaping (text with upright characters).
1045    vertical: Option<Box<VerticalAlong>>,
1046}
1047
1048#[derive(Clone)]
1049/// One icon quad (getIconQuads): corner offsets tl, tr, bl, br in icon px,
1050/// scaled by max(min_scale, icon-size) and then shifted by fixed pixel
1051/// offsets (stretchable images keep their fixed parts at pixel size); the
1052/// texture rectangle in padded atlas-cell coordinates.
1053#[derive(Debug)]
1054struct IconQuad {
1055    em: [(f64, f64); 4],
1056    px_tl: (f64, f64),
1057    px_br: (f64, f64),
1058    min_scale: (f64, f64),
1059    tex: (f64, f64, f64, f64),
1060}
1061
1062impl IconQuad {
1063    /// Corner offsets (tl, tr, bl, br) at icon size `size`.
1064    fn corners(&self, size: f64) -> [(f64, f64); 4] {
1065        let (sx, sy) = (self.min_scale.0.max(size), self.min_scale.1.max(size));
1066        let px = [self.px_tl, (self.px_br.0, self.px_tl.1), (self.px_tl.0, self.px_br.1), self.px_br];
1067        let mut out = [(0.0, 0.0); 4];
1068        for i in 0..4 {
1069            out[i] = (self.em[i].0 * sx + px[i].0, self.em[i].1 * sy + px[i].1);
1070        }
1071        out
1072    }
1073}
1074
1075#[derive(Clone)]
1076struct IconPart {
1077    image: String,
1078    quads: Vec<IconQuad>,
1079    /// Render shift (px): text-fit icons follow a variable-anchor label.
1080    shift: (f64, f64),
1081    size: f64,
1082    sdf: bool,
1083    linear: bool,
1084    style: SdfStyle,
1085    along: Option<AlongLine>,
1086}
1087
1088/// A symbol that survived placement, ready to draw.
1089struct Label {
1090    anchor_px: (f64, f64),
1091    text: Option<TextPart>,
1092    icon: Option<IconPart>,
1093    tile: usize,
1094}
1095
1096/// Placed symbols per style layer index.
1097pub struct Placement {
1098    labels: HashMap<usize, Vec<Label>>,
1099}
1100
1101struct Instance {
1102    tile_idx: usize,
1103    sort_key: f64,
1104    /// Variable-anchor attempts: (screen collision box, text part shifted
1105    /// for that anchor, icon box / render shift for text-fit icons).
1106    variants: Vec<([f64; 4], TextPart, Option<([f64; 4], (f64, f64))>)>,
1107    text_box: Option<[f64; 4]>,
1108    /// Line labels collide with runtime circles along their projected path.
1109    text_line: Option<TextCircles>,
1110    icon_box: Option<[f64; 4]>,
1111    /// Vertical point text (screen box, text part), tried in the layer's
1112    /// text-writing-mode order.
1113    vertical: Option<([f64; 4], TextPart)>,
1114    label: Label,
1115}
1116
1117struct TextCircles {
1118    radius: f64,
1119    /// Projected path from the first to the last glyph; None if they don't fit.
1120    path: Option<Vec<(f64, f64)>>,
1121}
1122
1123/// An entry in the collision index.
1124enum Item {
1125    Box([f64; 4]),
1126    Circle(f64, f64, f64),
1127}
1128
1129fn circle_rect(cx: f64, cy: f64, r: f64, b: &[f64; 4]) -> bool {
1130    let hw = (b[2] - b[0]) / 2.0;
1131    let dx = (cx - (b[0] + hw)).abs();
1132    if dx > hw + r {
1133        return false;
1134    }
1135    let hh = (b[3] - b[1]) / 2.0;
1136    let dy = (cy - (b[1] + hh)).abs();
1137    if dy > hh + r {
1138        return false;
1139    }
1140    if dx <= hw || dy <= hh {
1141        return true;
1142    }
1143    let (ex, ey) = (dx - hw, dy - hh);
1144    ex * ex + ey * ey <= r * r
1145}
1146
1147/// GridIndex.hitTest for a box (with its whole-grid shortcut).
1148fn hit_box(items: &[Item], b: &[f64; 4], gw: f64, gh: f64) -> bool {
1149    if b[2] < 0.0 || b[0] > gw || b[3] < 0.0 || b[1] > gh {
1150        return false;
1151    }
1152    if b[0] <= 0.0 && b[1] <= 0.0 && gw <= b[2] && gh <= b[3] {
1153        return !items.is_empty();
1154    }
1155    items.iter().any(|it| match it {
1156        Item::Box(o) => b[0] <= o[2] && b[1] <= o[3] && b[2] >= o[0] && b[3] >= o[1],
1157        Item::Circle(x, y, r) => circle_rect(*x, *y, *r, b),
1158    })
1159}
1160
1161/// GridIndex.hitTestCircle.
1162fn hit_circle(items: &[Item], x: f64, y: f64, r: f64, gw: f64, gh: f64) -> bool {
1163    if x + r < 0.0 || x - r > gw || y + r < 0.0 || y - r > gh {
1164        return false;
1165    }
1166    items.iter().any(|it| match it {
1167        Item::Box(o) => circle_rect(x, y, r, o),
1168        Item::Circle(x2, y2, r2) => {
1169            let (dx, dy) = (x2 - x, y2 - y);
1170            (r + r2) * (r + r2) > dx * dx + dy * dy
1171        }
1172    })
1173}
1174
1175/// placeCollisionCircles: returns (circles, collision detected).
1176fn place_circles(
1177    items: &[Item],
1178    path: &[(f64, f64)],
1179    radius: f64,
1180    width: f64,
1181    height: f64,
1182    always: bool,
1183) -> (Vec<(f64, f64, f64)>, bool) {
1184    let (gw, gh) = (width + 2.0 * VIEWPORT_PADDING, height + 2.0 * VIEWPORT_PADDING);
1185    let (minx, miny, maxx, maxy) = (-VIEWPORT_PADDING, -VIEWPORT_PADDING, width + VIEWPORT_PADDING, height + VIEWPORT_PADDING);
1186    let mut circles = Vec::new();
1187    let mut in_grid = false;
1188    if path.is_empty() {
1189        return (circles, false);
1190    }
1191    let (mut lo_x, mut lo_y, mut hi_x, mut hi_y) = (path[0].0, path[0].1, path[0].0, path[0].1);
1192    for p in path {
1193        lo_x = lo_x.min(p.0);
1194        lo_y = lo_y.min(p.1);
1195        hi_x = hi_x.max(p.0);
1196        hi_y = hi_y.max(p.1);
1197    }
1198    let segments: Vec<Vec<(f64, f64)>> = if lo_x >= minx && hi_x <= maxx && lo_y >= miny && hi_y <= maxy {
1199        vec![path.to_vec()]
1200    } else if hi_x < minx || lo_x > maxx || hi_y < miny || lo_y > maxy {
1201        Vec::new()
1202    } else {
1203        line::clip_line(&[path.to_vec()], minx, miny, maxx, maxy)
1204    };
1205    let circle_dist = radius * 2.5;
1206    for seg in segments {
1207        let interp = line::PathInterpolator::new(seg, radius * 0.25);
1208        let n = if interp.length <= 0.5 * radius { 1 } else { (interp.padded_length / circle_dist).ceil() as usize + 1 };
1209        for i in 0..n {
1210            let t = i as f64 / (n.max(2) - 1) as f64;
1211            let p = interp.lerp(t);
1212            let (cx, cy) = (p.0 + VIEWPORT_PADDING, p.1 + VIEWPORT_PADDING);
1213            circles.push((cx, cy, radius));
1214            let (x1, y1, x2, y2) = (cx - radius, cy - radius, cx + radius, cy + radius);
1215            in_grid |= x2 >= 0.0 && x1 < gw && y2 >= 0.0 && y1 < gh;
1216            if !always && hit_circle(items, cx, cy, radius, gw, gh) {
1217                return (Vec::new(), true);
1218            }
1219        }
1220    }
1221    if !in_grid {
1222        circles.clear();
1223    }
1224    (circles, false)
1225}
1226
1227fn num(layout: &Json, key: &str, ctx: &Ctx, default: f64) -> f64 {
1228    layout.get(key).map(|j| eval_property(j, Kind::Number, ctx)).and_then(|v| v.as_num()).unwrap_or(default)
1229}
1230
1231fn string(layout: &Json, key: &str, ctx: &Ctx, default: &str) -> String {
1232    layout
1233        .get(key)
1234        .map(|j| eval_property(j, Kind::Enum, ctx))
1235        .and_then(|v| v.as_str().map(str::to_owned))
1236        .unwrap_or_else(|| default.to_owned())
1237}
1238
1239fn num_pair(layout: &Json, key: &str, ctx: &Ctx) -> (f64, f64) {
1240    match layout.get(key).map(|j| eval_property(j, Kind::Array, ctx)).and_then(|v| v.as_num_array()) {
1241        Some(v) if v.len() == 2 => (v[0], v[1]),
1242        _ => (0.0, 0.0),
1243    }
1244}
1245
1246fn color(paint: &Json, key: &str, ctx: &Ctx, default: Color) -> Color {
1247    let c = paint
1248        .get(key)
1249        .map(|j| eval_property(j, Kind::Color, ctx))
1250        .and_then(|v| v.as_color())
1251        .unwrap_or(default);
1252    // Data-driven colors are packed to 8 bits (packColor floors).
1253    if paint.get(key).map_or(false, is_data_driven) {
1254        let q = |v: f32| (v * 255.0).floor().clamp(0.0, 255.0) / 255.0;
1255        Color::new(q(c.r), q(c.g), q(c.b), q(c.a))
1256    } else {
1257        c
1258    }
1259}
1260
1261fn sdf_style(paint: &Json, prefix: &str, ctx: &Ctx) -> SdfStyle {
1262    SdfStyle {
1263        fill: color(paint, &format!("{prefix}-color"), ctx, Color::BLACK),
1264        halo: color(paint, &format!("{prefix}-halo-color"), ctx, Color::TRANSPARENT),
1265        halo_width: num(paint, &format!("{prefix}-halo-width"), ctx, 0.0),
1266        halo_blur: num(paint, &format!("{prefix}-halo-blur"), ctx, 0.0),
1267        opacity: num(paint, &format!("{prefix}-opacity"), ctx, 1.0),
1268    }
1269}
1270
1271fn to_extent(p: (f32, f32), scale: f64) -> (f64, f64) {
1272    ((p.0 as f64 * scale + 0.5).floor(), (p.1 as f64 * scale + 0.5).floor())
1273}
1274
1275/// A point collision box as CollisionFeature stores it: the envelope of the
1276/// box rotated by `deg` (text-rotate / icon-rotate), in tile units about the
1277/// anchor, kept in CollisionBoxArray's Int16 fields (truncated toward zero).
1278fn rotated_envelope(b: [f64; 4], deg: f64) -> [f64; 4] {
1279    let b = if deg == 0.0 {
1280        b
1281    } else {
1282        let (s, c) = (deg.to_radians().sin(), deg.to_radians().cos());
1283        let pts = [(b[0], b[1]), (b[2], b[1]), (b[0], b[3]), (b[2], b[3])].map(|(x, y)| (c * x - s * y, s * x + c * y));
1284        [
1285            pts.iter().map(|p| p.0).fold(f64::INFINITY, f64::min),
1286            pts.iter().map(|p| p.1).fold(f64::INFINITY, f64::min),
1287            pts.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max),
1288            pts.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max),
1289        ]
1290    };
1291    b.map(f64::trunc)
1292}
1293
1294fn padding4(layout: &Json, key: &str, ctx: &Ctx, default: f64) -> [f64; 4] {
1295    // [top, right, bottom, left] (CSS order); a single number applies to all.
1296    match layout.get(key).map(|j| eval_property(j, Kind::Array, ctx)) {
1297        Some(Val::Num(n)) => [n; 4],
1298        Some(Val::Array(a)) => {
1299            let v: Vec<f64> = a.iter().filter_map(|x| x.as_num()).collect();
1300            match v.len() {
1301                1 => [v[0]; 4],
1302                2 => [v[0], v[1], v[0], v[1]],
1303                3 => [v[0], v[1], v[2], v[1]],
1304                4 => [v[0], v[1], v[2], v[3]],
1305                _ => [default; 4],
1306            }
1307        }
1308        _ => [default; 4],
1309    }
1310}
1311
1312/// Text shaping parameters and output for one feature.
1313fn build_text(
1314    layer: &Json,
1315    f: &Feature,
1316    assets: &SymbolAssets,
1317    zoom: f64,
1318    tile_zoom: f64,
1319    tile_pixel_ratio: f64,
1320    variable_justify: Option<&str>,
1321    vertical: bool,
1322) -> Option<(TextPart, [f64; 4], (TextExtents, f64))> {
1323    let layout = &layer["layout"];
1324    let paint = &layer["paint"];
1325    let ctx = Ctx { zoom, feature: Some(f) };
1326    let lctx = Ctx { zoom: tile_zoom, feature: Some(f) };
1327    let next_ctx = Ctx { zoom: tile_zoom + 1.0, feature: Some(f) };
1328    let t = feature_text(layer, f, tile_zoom)?;
1329    // A vertical point label only for text with upright characters.
1330    if vertical && !super::vertical::allows_vertical_writing_mode(&t) {
1331        return None;
1332    }
1333    let stack = feature_fontstack(layer, Some(f), tile_zoom);
1334    let gmap = assets.glyphs.stacks.get(&stack)?;
1335    let spacing = num(layout, "text-letter-spacing", &lctx, 0.0) * ONE_EM;
1336    // Variable anchors: shaped about the centre with the anchor's
1337    // justification; the offset is applied when placing.
1338    let anchor = if variable_justify.is_some() { "center".to_owned() } else { string(layout, "text-anchor", &lctx, "center") };
1339    let mut justify = variable_justify.map(str::to_owned).unwrap_or_else(|| string(layout, "text-justify", &lctx, "center"));
1340    if justify == "auto" {
1341        justify = match anchor.as_str() {
1342            "right" | "top-right" | "bottom-right" => "right",
1343            "left" | "top-left" | "bottom-left" => "left",
1344            _ => "center",
1345        }
1346        .to_owned();
1347    }
1348    let max_width = num(layout, "text-max-width", &lctx, 10.0) * ONE_EM;
1349    let line_height = num(layout, "text-line-height", &lctx, 1.2) * ONE_EM;
1350    let radial = num(layout, "text-radial-offset", &lctx, 0.0);
1351    let text_offset = if variable_justify.is_some() {
1352        (0.0, 0.0)
1353    } else if radial != 0.0 {
1354        variable_offset(&anchor, VarOffset::Radial(radial * ONE_EM))
1355    } else {
1356        let o = num_pair(layout, "text-offset", &lctx);
1357        (o.0 * ONE_EM, o.1 * ONE_EM)
1358    };
1359    // Vertical point labels: left-justified (addVerticalShapingForPointLabelIfNeeded).
1360    if vertical {
1361        justify = "left".to_owned();
1362    }
1363    let shaping = shape_text(&t, gmap, max_width, line_height, &anchor, &justify, spacing, text_offset, vertical, vertical)?;
1364    let rotate = num(layout, "text-rotate", &lctx, 0.0);
1365    let mut quads = glyph_quads(&shaping, gmap, text_offset, rotate, vertical);
1366    if quads.is_empty() {
1367        return None;
1368    }
1369    if vertical {
1370        // The vertical symbol is drawn turned 90° clockwise about its anchor
1371        // (addSymbols' dynamic angle of π/2); exact on the 1/32 grid.
1372        for q in &mut quads {
1373            for p in &mut q.corners {
1374                *p = (-p.1, p.0);
1375            }
1376        }
1377    }
1378    let layout_size = num(layout, "text-size", &next_ctx, 16.0);
1379    let box_scale = tile_pixel_ratio * layout_size / 24.0;
1380    let pad = num(layout, "text-padding", &lctx, 2.0) * tile_pixel_ratio;
1381    let b = rotated_envelope(
1382        [shaping.left * box_scale - pad, shaping.top * box_scale - pad, shaping.right * box_scale + pad, shaping.bottom * box_scale + pad],
1383        rotate + if vertical { 90.0 } else { 0.0 },
1384    );
1385    Some((
1386        TextPart {
1387            quads,
1388            fontstack: stack,
1389            size: num(layout, "text-size", &ctx, 16.0),
1390            style: sdf_style(paint, "text", &ctx),
1391            along: None,
1392            shift: (0.0, 0.0),
1393        },
1394        b,
1395        ((shaping.left, shaping.right, shaping.top, shaping.bottom), layout_size / ONE_EM),
1396    ))
1397}
1398
1399/// Icon shaping (shapeIcon + getIconQuads without icon-text-fit). Returns
1400/// the part, its collision box (tile units) and whether it needs LINEAR.
1401/// Shaped text extents (left, right, top, bottom, in em units before the
1402/// font scale), for icon-text-fit.
1403type TextExtents = (f64, f64, f64, f64);
1404
1405/// getIconQuads: one quad for plain icons; with icon-text-fit and stretch
1406/// metadata, a grid of quads whose stretchable parts scale and fixed parts
1407/// keep their pixel size. `shaped` is the icon box (left, top, right, bottom).
1408fn icon_quads(img: &SpriteImage, shaped: (f64, f64, f64, f64), rotate: f64, has_fit: bool) -> Vec<IconQuad> {
1409    let (l, u) = (img.w as f64, img.h as f64);
1410    let pr = img.pixel_ratio;
1411    let hx = img.stretch_x.clone().unwrap_or_else(|| vec![(0.0, l)]);
1412    let hy = img.stretch_y.clone().unwrap_or_else(|| vec![(0.0, u)]);
1413    let sum = |r: &[(f64, f64)]| r.iter().map(|x| x.1 - x.0).sum::<f64>();
1414    let within = |r: &[(f64, f64)], a: f64, b: f64| r.iter().map(|x| a.max(b.min(x.1)) - a.max(b.min(x.0))).sum::<f64>();
1415    let (d, y) = (sum(&hx), sum(&hy));
1416    let (m, g) = (l - d, u - y);
1417    let (mut x0, mut v, mut b0, mut wv, mut fx0, mut sw, mut fy0, mut sh) = (0.0, d, 0.0, y, 0.0, m, 0.0, g);
1418    if let (Some(c), true) = (img.content, has_fit) {
1419        x0 = within(&hx, 0.0, c[0]);
1420        b0 = within(&hy, 0.0, c[1]);
1421        v = within(&hx, c[0], c[2]);
1422        wv = within(&hy, c[1], c[3]);
1423        fx0 = c[0] - x0;
1424        fy0 = c[1] - b0;
1425        sw = c[2] - c[0] - v;
1426        sh = c[3] - c[1] - wv;
1427    }
1428    let (k, i0, e, t) = (shaped.0, shaped.1, shaped.2 - shaped.0, shaped.3 - shaped.1);
1429    let em = |stretch: f64, off: f64, size: f64, total: f64, origin: f64| if size == 0.0 { origin } else { (stretch - off) / size * total + origin };
1430    let pxo = |fixed: f64, off: f64, fixed_size: f64, stretch: f64, stretch_total: f64| {
1431        if stretch_total == 0.0 { fixed - off } else { fixed - off - fixed_size * stretch / stretch_total }
1432    };
1433    #[derive(Clone, Copy)]
1434    struct P {
1435        fixed: f64,
1436        stretch: f64,
1437    }
1438    let make = |a: P, bq: P, c: P, dq: P| -> IconQuad {
1439        let lx = em(a.stretch, x0, v, e, k);
1440        let lpx = pxo(a.fixed, fx0, sw, a.stretch, d);
1441        let ty = em(bq.stretch, b0, wv, t, i0);
1442        let tpx = pxo(bq.fixed, fy0, sh, bq.stretch, y);
1443        let rx = em(c.stretch, x0, v, e, k);
1444        let rpx = pxo(c.fixed, fx0, sw, c.stretch, d);
1445        let by = em(dq.stretch, b0, wv, t, i0);
1446        let bpx = pxo(dq.fixed, fy0, sh, dq.stretch, y);
1447        let mut corners = [(lx, ty), (rx, ty), (lx, by), (rx, by)];
1448        if rotate != 0.0 {
1449            let (sn, cs) = (rotate.to_radians().sin(), rotate.to_radians().cos());
1450            for p in &mut corners {
1451                *p = (cs * p.0 - sn * p.1, sn * p.0 + cs * p.1);
1452            }
1453        }
1454        // Vertex attributes: a_offset * 32, a_pixeloffset * 16, min font scale * 256.
1455        for p in &mut corners {
1456            *p = (js_round(p.0 * 32.0) / 32.0, js_round(p.1 * 32.0) / 32.0);
1457        }
1458        let q16 = |x: f64| js_round(x / pr * 16.0) / 16.0;
1459        let q256 = |x: f64| js_round(x * 256.0) / 256.0;
1460        let x1 = a.stretch + a.fixed;
1461        let y1 = bq.stretch + bq.fixed;
1462        IconQuad {
1463            em: corners,
1464            px_tl: (q16(lpx), q16(tpx)),
1465            px_br: (q16(rpx), q16(bpx)),
1466            min_scale: (if e == 0.0 { 0.0 } else { q256(sw / pr / e) }, if t == 0.0 { 0.0 } else { q256(sh / pr / t) }),
1467            tex: (1.0 + x1, 1.0 + y1, c.stretch + c.fixed - x1, dq.stretch + dq.fixed - y1),
1468        }
1469    };
1470    if has_fit && (img.stretch_x.is_some() || img.stretch_y.is_some()) {
1471        let parts = |r: &[(f64, f64)], fixed: f64, stretch: f64| {
1472            let mut out = vec![P { fixed: -1.0, stretch: 0.0 }];
1473            for &(a, b) in r {
1474                let last = *out.last().unwrap();
1475                out.push(P { fixed: a - last.stretch, stretch: last.stretch });
1476                out.push(P { fixed: a - last.stretch, stretch: last.stretch + (b - a) });
1477            }
1478            out.push(P { fixed: fixed + 1.0, stretch });
1479            out
1480        };
1481        let (xs, ys) = (parts(&hx, m, d), parts(&hy, g, y));
1482        let mut quads = Vec::new();
1483        for xi in 0..xs.len() - 1 {
1484            for yi in 0..ys.len() - 1 {
1485                quads.push(make(xs[xi], ys[yi], xs[xi + 1], ys[yi + 1]));
1486            }
1487        }
1488        quads
1489    } else {
1490        vec![make(P { fixed: 0.0, stretch: -1.0 }, P { fixed: 0.0, stretch: -1.0 }, P { fixed: 0.0, stretch: l + 1.0 }, P { fixed: 0.0, stretch: u + 1.0 })]
1491    }
1492}
1493
1494/// An icon's part, collision box and whether it needs linear sampling.
1495/// `text` is the shaped text's extents and its layout font scale, for
1496/// icon-text-fit (fitIconToText).
1497#[allow(clippy::too_many_arguments)]
1498fn build_icon(
1499    layer: &Json,
1500    f: &Feature,
1501    assets: &SymbolAssets,
1502    zoom: f64,
1503    tile_zoom: f64,
1504    tile_pixel_ratio: f64,
1505    text: Option<(TextExtents, f64)>,
1506) -> Option<(IconPart, [f64; 4], bool)> {
1507    let layout = &layer["layout"];
1508    let paint = &layer["paint"];
1509    let ctx = Ctx { zoom, feature: Some(f) };
1510    let lctx = Ctx { zoom: tile_zoom, feature: Some(f) };
1511    let next_ctx = Ctx { zoom: tile_zoom + 1.0, feature: Some(f) };
1512    let name = feature_icon(layer, f, tile_zoom)?;
1513    let img = assets.sprite.images.get(&name)?;
1514    let rotate = num(layout, "icon-rotate", &lctx, 0.0);
1515    let needs_linear = img.pixel_ratio != assets.sprite.dpr() || rotate != 0.0 || layout.get("icon-rotate").map_or(false, is_data_driven);
1516    let (dw, dh) = (img.w as f64 / img.pixel_ratio, img.h as f64 / img.pixel_ratio);
1517    let off = num_pair(layout, "icon-offset", &lctx);
1518    let fit = super::expr::layout_enum(layout, "icon-text-fit", tile_zoom).unwrap_or_else(|| "none".into());
1519    let mut collision_pad: Option<[f64; 4]> = None;
1520    let (left, top, right, bottom) = match (fit.as_str(), text) {
1521        (mode, Some(((tl, tr, tt, tb), font_scale))) if mode != "none" => {
1522            // fitIconToText: centred on the text, stretched in the fitted
1523            // dimensions (icon-anchor is ignored).
1524            if let Some(c) = img.content {
1525                let pr = img.pixel_ratio;
1526                collision_pad = Some([c[0] / pr, c[1] / pr, dw - c[2] / pr, dh - c[3] / pr]);
1527            }
1528            let pad = padding4(layout, "icon-text-fit-padding", &lctx, 0.0);
1529            let (l, r) = (tl * font_scale, tr * font_scale);
1530            let (lx, rx) = if mode == "width" || mode == "both" {
1531                (off.0 + l - pad[3], off.0 + r + pad[1])
1532            } else {
1533                let lx = off.0 + (l + r - dw) / 2.0;
1534                (lx, lx + dw)
1535            };
1536            let (t, b) = (tt * font_scale, tb * font_scale);
1537            let (ty, by) = if mode == "height" || mode == "both" {
1538                (off.1 + t - pad[0], off.1 + b + pad[2])
1539            } else {
1540                let ty = off.1 + (t + b - dh) / 2.0;
1541                (ty, ty + dh)
1542            };
1543            (lx, ty, rx, by)
1544        }
1545        _ => {
1546            let (ha, va) = anchor_alignment(&string(layout, "icon-anchor", &lctx, "center"));
1547            let (l, t) = (off.0 - dw * ha, off.1 - dh * va);
1548            (l, t, l + dw, t + dh)
1549        }
1550    };
1551    let has_fit = fit != "none" && text.is_some();
1552    let quads = icon_quads(img, (left, top, right, bottom), rotate, has_fit);
1553    let box_scale = tile_pixel_ratio * num(layout, "icon-size", &next_ctx, 1.0);
1554    let pad = padding4(layout, "icon-padding", &lctx, 2.0).map(|v| v * tile_pixel_ratio);
1555    let mut bx = [left * box_scale - pad[3], top * box_scale - pad[0], right * box_scale + pad[1], bottom * box_scale + pad[2]];
1556    if let Some(cp) = collision_pad {
1557        bx = [bx[0] - cp[0] * box_scale, bx[1] - cp[1] * box_scale, bx[2] + cp[2] * box_scale, bx[3] + cp[3] * box_scale];
1558    }
1559    let b = rotated_envelope(bx, rotate);
1560    Some((
1561        IconPart {
1562            image: name,
1563            quads,
1564            shift: (0.0, 0.0),
1565            size: num(layout, "icon-size", &ctx, 1.0),
1566            sdf: img.sdf,
1567            linear: false,
1568            style: sdf_style(paint, "icon", &ctx),
1569            along: None,
1570        },
1571        b,
1572        needs_linear,
1573    ))
1574}
1575
1576/// A line-placed label's text: (part, glyph offsets along the line, shaped
1577/// width, collision diameter, text offset, point box).
1578type LineText = (TextPart, Vec<f64>, f64, f64, (f64, f64), Option<[f64; 4]>, (TextExtents, f64), Option<VerticalAlong>);
1579
1580/// The vertical shaping of a line label (glyph quads and along-line glyph
1581/// offsets), drawn when its line runs vertically.
1582#[derive(Clone)]
1583struct VerticalAlong {
1584    quads: Vec<GlyphQuad>,
1585    glyph_offsets: Vec<f64>,
1586}
1587
1588/// Along-line glyph quads (getGlyphQuads with alongLine): corners about the
1589/// glyph centre, upright glyphs of a vertical shaping rotated, the glyph's
1590/// line y added (addSymbols) before the 1/32 rounding; and the glyph offsets.
1591fn along_line_quads(shaping: &Shaping, gmap: &HashMap<u32, Glyph>) -> (Vec<GlyphQuad>, Vec<f64>) {
1592    let rect_buffer = GLYPH_PBF_BORDER + ATLAS_PADDING as f64;
1593    let mut quads = Vec::new();
1594    let mut offsets = Vec::new();
1595    for l in &shaping.lines {
1596        for pg in l {
1597            let g = &gmap[&pg.codepoint];
1598            let half = g.advance / 2.0;
1599            let x1 = (g.left - rect_buffer) - half;
1600            let y1 = -g.top - rect_buffer;
1601            let (x2, y2) = (x1 + g.rect_w as f64, y1 + g.rect_h as f64);
1602            let mut corners = [(x1, y1), (x2, y1), (x1, y2), (x2, y2)];
1603            if pg.vertical {
1604                rotate_vertical_glyph(&mut corners, half, (0.0, 0.0));
1605            }
1606            for c in &mut corners {
1607                *c = (js_round(c.0 * 32.0) / 32.0, js_round((pg.y + c.1) * 32.0) / 32.0);
1608            }
1609            quads.push(GlyphQuad { corners, codepoint: pg.codepoint });
1610            offsets.push(pg.x + half);
1611        }
1612    }
1613    (quads, offsets)
1614}
1615
1616/// Shaping for a line label: centred, no line breaks. With `along` (text
1617/// rotation alignment `map`), quads carry along-line glyph offsets
1618/// (getGlyphQuads with alongLine = true); otherwise the label is drawn like
1619/// a point label at its anchor (textAlongLine is false for `viewport`), with
1620/// point quads and a collision box.
1621#[allow(clippy::too_many_arguments)]
1622fn build_line_text(
1623    layer: &Json,
1624    f: &Feature,
1625    text: &str,
1626    assets: &SymbolAssets,
1627    zoom: f64,
1628    tile_zoom: f64,
1629    along: bool,
1630    tile_pixel_ratio: f64,
1631) -> Option<LineText> {
1632    let layout = &layer["layout"];
1633    let paint = &layer["paint"];
1634    let ctx = Ctx { zoom, feature: Some(f) };
1635    let lctx = Ctx { zoom: tile_zoom, feature: Some(f) };
1636    let next_ctx = Ctx { zoom: tile_zoom + 1.0, feature: Some(f) };
1637    let stack = feature_fontstack(layer, Some(f), tile_zoom);
1638    let gmap = assets.glyphs.stacks.get(&stack)?;
1639    let spacing = num(layout, "text-letter-spacing", &lctx, 0.0) * ONE_EM;
1640    let anchor = string(layout, "text-anchor", &lctx, "center");
1641    let line_height = num(layout, "text-line-height", &lctx, 1.2) * ONE_EM;
1642    let o = num_pair(layout, "text-offset", &lctx);
1643    let text_offset = (o.0 * ONE_EM, o.1 * ONE_EM);
1644    let shaping = shape_text(text, gmap, f64::INFINITY, line_height, &anchor, "center", spacing, text_offset, false, false)?;
1645    let (mut quads, offsets) = along_line_quads(&shaping, gmap);
1646    if quads.is_empty() {
1647        return None;
1648    }
1649    // Verticalized line label: text with upright characters, drawn along
1650    // the line, kept upright.
1651    let vertical = if along && layout["text-keep-upright"] != false && super::vertical::allows_vertical_writing_mode(text) {
1652        shape_text(text, gmap, f64::INFINITY, line_height, &anchor, "center", spacing, text_offset, true, false)
1653            .map(|vs| along_line_quads(&vs, gmap))
1654            .filter(|(q, _)| !q.is_empty())
1655            .map(|(quads, glyph_offsets)| VerticalAlong { quads, glyph_offsets })
1656    } else {
1657        None
1658    };
1659    let height = shaping.bottom - shaping.top;
1660    let layout_size = num(layout, "text-size", &next_ctx, 16.0);
1661    // SymbolInstance.collisionCircleDiameter is a Float32.
1662    let diameter = if height > 0.0 { (height.max(10.0) * layout_size / ONE_EM) as f32 as f64 } else { -1.0 };
1663    let mut point_box = None;
1664    if !along {
1665        let rotate = num(layout, "text-rotate", &lctx, 0.0);
1666        quads = glyph_quads(&shaping, gmap, text_offset, rotate, false);
1667        let box_scale = tile_pixel_ratio * layout_size / 24.0;
1668        let pad = num(layout, "text-padding", &lctx, 2.0) * tile_pixel_ratio;
1669        point_box = Some(rotated_envelope(
1670            [shaping.left * box_scale - pad, shaping.top * box_scale - pad, shaping.right * box_scale + pad, shaping.bottom * box_scale + pad],
1671            rotate,
1672        ));
1673    }
1674    Some((
1675        TextPart {
1676            quads,
1677            fontstack: stack,
1678            size: num(layout, "text-size", &ctx, 16.0),
1679            style: sdf_style(paint, "text", &ctx),
1680            along: None,
1681            shift: (0.0, 0.0),
1682        },
1683        offsets,
1684        shaping.right - shaping.left,
1685        diameter,
1686        text_offset,
1687        point_box,
1688        ((shaping.left, shaping.right, shaping.top, shaping.bottom), layout_size / ONE_EM),
1689        vertical,
1690    ))
1691}
1692
1693/// MapLibre's bucket zoom for a symbol tile (its overscaled z).
1694fn tile_zoom_of(st: &SymbolTile) -> f64 {
1695    st.coord.0 as f64 + st.overscaling.log2()
1696}
1697
1698/// Symbol instances of a line- or line-center-placed layer in one tile.
1699#[allow(clippy::too_many_arguments)]
1700fn line_instances(
1701    layer: &Json,
1702    st: &SymbolTile,
1703    ti: usize,
1704    assets: &SymbolAssets,
1705    zoom: f64,
1706    sort_key_j: Option<&Json>,
1707    sort_by_key: bool,
1708    icons_need_linear: &mut bool,
1709) -> Vec<Instance> {
1710    let layout = &layer["layout"];
1711    let paint = &layer["paint"];
1712    let placement_s = super::expr::layout_enum(layout, "symbol-placement", tile_zoom_of(st)).unwrap_or_else(|| "point".into());
1713    let placement = placement_s.as_str();
1714    let mut out = Vec::new();
1715    let Some(src) = st.tile.layers.get(super::mvt::source_layer(layer)) else { return out };
1716    let scale = EXTENT / src.extent as f64;
1717    let tile_zoom = st.coord.0 as f64 + st.overscaling.log2();
1718    let tile_pixel_ratio = EXTENT / (512.0 * st.overscaling);
1719    let text_pixel_ratio = 512.0 * st.overscaling / EXTENT;
1720    let has_text_field = layout.get("text-field").is_some();
1721    let has_icon_image = layout.get("icon-image").is_some();
1722
1723    let mut feats: Vec<line::LineFeature> = Vec::new();
1724    for f in &src.features {
1725        let ctx = Ctx { zoom: tile_zoom, feature: Some(f) };
1726        if layer.get("filter").map_or(false, |flt| !eval_filter(flt, &ctx)) {
1727            continue;
1728        }
1729        let geometry: Vec<Vec<(f64, f64)>> = match &f.geometry {
1730            Geometry::Lines(ls) => ls.iter().map(|l| l.iter().map(|&p| to_extent(p, scale)).collect()).collect(),
1731            Geometry::Polygons(ps) => ps.iter().flatten().map(|r| r.iter().map(|&p| to_extent(p, scale)).collect()).collect(),
1732            Geometry::Points(_) => continue,
1733        };
1734        let text = if has_text_field { feature_text(layer, f, tile_zoom) } else { None };
1735        feats.push(line::LineFeature { feature: f, text, geometry });
1736    }
1737    if placement == "line" {
1738        feats = line::merge_lines(feats);
1739    }
1740    let mut keyed: Vec<(f64, line::LineFeature)> = feats
1741        .into_iter()
1742        .map(|lf| {
1743            let key = if sort_by_key {
1744                let ctx = Ctx { zoom: tile_zoom, feature: Some(lf.feature) };
1745                sort_key_j.map(|j| eval_property(j, Kind::Number, &ctx)).and_then(|v| v.as_num()).unwrap_or(0.0)
1746            } else {
1747                0.0
1748            };
1749            (key, lf)
1750        })
1751        .collect();
1752    if sort_by_key {
1753        keyed.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
1754    }
1755
1756    // symbol-placement line/line-center resolve rotation-alignment 'auto' to 'map'.
1757    let text_rotate_to_line = super::expr::layout_enum(layout, "text-rotation-alignment", tile_zoom).as_deref() != Some("viewport");
1758    let icon_along = super::expr::layout_enum(layout, "icon-rotation-alignment", tile_zoom).as_deref() != Some("viewport");
1759    let mut compare_text: HashMap<String, Vec<(f64, f64)>> = HashMap::new();
1760
1761    for (key, lf) in keyed {
1762        let f = lf.feature;
1763        let ctx = Ctx { zoom, feature: Some(f) };
1764        let lctx = Ctx { zoom: tile_zoom, feature: Some(f) };
1765        let text = match (&lf.text, has_text_field) {
1766            (Some(t), true) if !t.is_empty() => {
1767                build_line_text(layer, f, t, assets, zoom, tile_zoom, text_rotate_to_line, tile_pixel_ratio)
1768            }
1769            _ => None,
1770        };
1771        let icon = if has_icon_image {
1772            build_icon(layer, f, assets, zoom, tile_zoom, tile_pixel_ratio, text.as_ref().map(|t| t.6))
1773        } else {
1774            None
1775        };
1776        if icon.as_ref().map_or(false, |i| i.2) {
1777            *icons_need_linear = true;
1778        }
1779        if text.is_none() && icon.is_none() {
1780            continue;
1781        }
1782        // getShapedLabelLength: max of the text width and the shaped icon
1783        // width (display size, before icon-size), in glyph units.
1784        let text_w = text.as_ref().map_or(0.0, |t| t.2);
1785        let icon_w = icon
1786            .as_ref()
1787            .and_then(|i| assets.sprite.images.get(&i.0.image))
1788            .map_or(0.0, |img| img.w as f64 / img.pixel_ratio);
1789        let label_len = text_w.max(icon_w);
1790        let text_max_size = num(layout, "text-size", &Ctx { zoom: 18.0, feature: Some(f) }, 16.0);
1791        let text_max_box_scale = tile_pixel_ratio * text_max_size / 24.0;
1792        let min_distance = tile_pixel_ratio * num(layout, "symbol-spacing", &lctx, 250.0);
1793        let max_angle = num(layout, "text-max-angle", &lctx, 45.0).to_radians();
1794        let repeat_distance = min_distance / 2.0;
1795        let ttr = num_pair(paint, "text-translate", &ctx);
1796        let itr = num_pair(paint, "icon-translate", &ctx);
1797
1798        let lines: Vec<Vec<(f64, f64)>> = if placement == "line" {
1799            line::clip_line(&lf.geometry, 0.0, 0.0, EXTENT, EXTENT)
1800        } else {
1801            lf.geometry.iter().filter(|l| l.len() > 1).cloned().collect()
1802        };
1803        for ln in &lines {
1804            let anchors: Vec<line::Anchor> = if placement == "line" {
1805                line::get_anchors(ln, min_distance, max_angle, text.is_some(), label_len, 24.0, text_max_box_scale, st.overscaling, EXTENT)
1806            } else {
1807                line::get_center_anchor(ln, max_angle, text.is_some(), label_len, 24.0, text_max_box_scale).into_iter().collect()
1808            };
1809            for a in anchors {
1810                if placement == "line" {
1811                    if let (Some(_), Some(t)) = (&text, &lf.text) {
1812                        // anchorIsTooClose
1813                        let list = compare_text.entry(t.clone()).or_default();
1814                        if list.iter().rev().any(|o| ((a.x - o.0).powi(2) + (a.y - o.1).powi(2)).sqrt() < repeat_distance) {
1815                            continue;
1816                        }
1817                        list.push((a.x, a.y));
1818                    }
1819                }
1820                if a.x < 0.0 || a.x >= EXTENT || a.y < 0.0 || a.y >= EXTENT {
1821                    continue;
1822                }
1823                let to_px = |p: (f64, f64), t: (f64, f64)| (st.ox + p.0 * st.unit_px + t.0, st.oy + p.1 * st.unit_px + t.1);
1824                let anchor_px = to_px((a.x, a.y), (0.0, 0.0));
1825                let mut text_line = None;
1826                // Viewport-aligned text: a point label at the anchor.
1827                let r = text_pixel_ratio;
1828                let point_text_box = text.as_ref().and_then(|t| t.5).map(|b| {
1829                    let (cx, cy) = (anchor_px.0 + ttr.0 + VIEWPORT_PADDING, anchor_px.1 + ttr.1 + VIEWPORT_PADDING);
1830                    [cx + b[0] * r, cy + b[1] * r, cx + b[2] * r, cy + b[3] * r]
1831                });
1832                let text_part = text.as_ref().map(|(part, offsets, _, diameter, text_offset, point_box, _, vertical)| {
1833                    if point_box.is_some() {
1834                        return part.clone();
1835                    }
1836                    let line_px: Vec<(f64, f64)> = ln.iter().map(|&p| to_px(p, ttr)).collect();
1837                    let anchor_t = to_px((a.x, a.y), ttr);
1838                    let font_scale = part.size / ONE_EM;
1839                    let pl = ProjectedLine { line: &line_px, anchor: anchor_t, segment: a.segment };
1840                    let path = line::collision_path(&pl, offsets, font_scale, *text_offset);
1841                    if *diameter > 0.0 {
1842                        let pad = num(layout, "text-padding", &lctx, 2.0);
1843                        text_line = Some(TextCircles { radius: diameter * 0.5 + pad, path });
1844                    }
1845                    let mut p = part.clone();
1846                    p.along = Some(AlongLine {
1847                        line_px,
1848                        segment: a.segment,
1849                        glyph_offsets: offsets.clone(),
1850                        line_offset: *text_offset,
1851                        keep_upright: layout["text-keep-upright"] != false,
1852                        rotate_to_line: text_rotate_to_line,
1853                        placement_scale: font_scale,
1854                        vertical: vertical.clone().map(Box::new),
1855                    });
1856                    p
1857                });
1858                let icon_box = icon.as_ref().map(|i| {
1859                    let (cx, cy) = (anchor_px.0 + itr.0 + VIEWPORT_PADDING, anchor_px.1 + itr.1 + VIEWPORT_PADDING);
1860                    [cx + i.1[0] * r, cy + i.1[1] * r, cx + i.1[2] * r, cy + i.1[3] * r]
1861                });
1862                let icon_part = icon.as_ref().map(|(part, _, _)| {
1863                    let mut p = part.clone();
1864                    if icon_along {
1865                        let line_px: Vec<(f64, f64)> = ln.iter().map(|&q| to_px(q, itr)).collect();
1866                        p.along = Some(AlongLine {
1867                            line_px,
1868                            segment: a.segment,
1869                            glyph_offsets: vec![0.0],
1870                            line_offset: num_pair(layout, "icon-offset", &lctx),
1871                            keep_upright: layout["icon-keep-upright"] == true,
1872                            rotate_to_line: text_rotate_to_line,
1873                            placement_scale: p.size / ONE_EM,
1874                            vertical: None,
1875                        });
1876                    }
1877                    p
1878                });
1879                out.push(Instance {
1880                    tile_idx: ti,
1881                    sort_key: key,
1882                    variants: Vec::new(),
1883                    text_box: point_text_box,
1884                    text_line,
1885                    icon_box,
1886                    vertical: None,
1887                    label: Label { anchor_px, text: text_part, icon: icon_part, tile: ti },
1888                });
1889            }
1890        }
1891    }
1892    out
1893}
1894
1895/// Run MapLibre's placement for every visible symbol layer.
1896pub fn place(style: &Json, tiles: &[SymbolTile], assets: &SymbolAssets, zoom: f64, width: f64, height: f64) -> Placement {
1897    let layers = style["layers"].as_array().map(|v| v.as_slice()).unwrap_or(&[]);
1898    // Tile order for placement: by x, then y (OverscaledTileID.isLessThan).
1899    let mut tile_order: Vec<usize> = (0..tiles.len()).collect();
1900    tile_order.sort_by(|&a, &b| {
1901        let (za, xa, ya) = tiles[a].coord;
1902        let (zb, xb, yb) = tiles[b].coord;
1903        zb.cmp(&za).then(tiles[a].wrap.cmp(&tiles[b].wrap)).then(xa.cmp(&xb)).then(ya.cmp(&yb))
1904    });
1905
1906    // Collision grid (brute force; same results as GridIndex).
1907    let mut items: Vec<Item> = Vec::new();
1908    let mut placed: HashMap<usize, Vec<Label>> = HashMap::new();
1909    let grid_w = width + 2.0 * VIEWPORT_PADDING;
1910    let grid_h = height + 2.0 * VIEWPORT_PADDING;
1911
1912    for (layer_idx, layer) in layers.iter().enumerate().rev() {
1913        if layer["type"] != "symbol" || !layer_visible(layer, zoom) {
1914            continue;
1915        }
1916        let layout = &layer["layout"];
1917        let has_text_field = layout.get("text-field").is_some();
1918        let has_icon_image = layout.get("icon-image").is_some();
1919        if !has_text_field && !has_icon_image {
1920            continue;
1921        }
1922        let placement = super::expr::layout_enum(layout, "symbol-placement", zoom.floor()).unwrap_or_else(|| "point".into());
1923        let sl = super::mvt::source_layer(layer);
1924        let paint = &layer["paint"];
1925        let sort_key_j = layout.get("symbol-sort-key");
1926        // text-writing-mode (point placement): the order writing modes are tried in.
1927        let modes = if placement == "point" { writing_modes(layout) } else { vec![false] };
1928        let allow_vertical = modes.contains(&true);
1929        let sort_by_key = super::expr::layout_enum(layout, "symbol-z-order", zoom.floor()).as_deref() != Some("viewport-y")
1930            && sort_key_j.map_or(false, is_data_driven);
1931        let overlap = |kind: &str| {
1932            layout[format!("{kind}-overlap")] == "always"
1933                || (layout.get(format!("{kind}-overlap")).is_none() && layout[format!("{kind}-allow-overlap")] == true)
1934        };
1935        let (text_always, icon_always) = (overlap("text"), overlap("icon"));
1936        let text_ignore = layout["text-ignore-placement"] == true;
1937        let icon_ignore = layout["icon-ignore-placement"] == true;
1938        let text_optional = layout["text-optional"] == true;
1939        let icon_optional = layout["icon-optional"] == true;
1940        // Bucket-level icon filtering (draw_symbol.ts).
1941        let icon_size_scaled = match layout.get("icon-size") {
1942            None => false,
1943            Some(j) if is_data_driven(j) => true,
1944            Some(j) => eval_property(j, Kind::Number, &Ctx { zoom, feature: None }).as_num() != Some(1.0),
1945        };
1946        let mut icons_need_linear = false;
1947        // draw_symbol.ts samples icons LINEAR when they are "transformed":
1948        // pitched with the map (icon-pitch-alignment map, which 'auto'
1949        // inherits from icon-rotation-alignment, itself 'map' for line
1950        // placement), even with the camera looking straight down.
1951        let icon_rotation_map = match super::expr::layout_enum(layout, "icon-rotation-alignment", zoom.floor()).as_deref() {
1952            Some("map") => true,
1953            Some("viewport") => false,
1954            _ => placement != "point",
1955        };
1956        let icon_pitch_map = match super::expr::layout_enum(layout, "icon-pitch-alignment", zoom.floor()).as_deref() {
1957            Some("map") => true,
1958            Some("viewport") => false,
1959            _ => icon_rotation_map,
1960        };
1961
1962        let mut instances: Vec<Instance> = Vec::new();
1963        let layer_source = layer["source"].as_str().unwrap_or("");
1964        for &ti in &tile_order {
1965            let st = &tiles[ti];
1966            if st.source != layer_source {
1967                continue;
1968            }
1969            if placement != "point" {
1970                instances.extend(line_instances(
1971                    layer, st, ti, assets, zoom, sort_key_j, sort_by_key, &mut icons_need_linear,
1972                ));
1973                continue;
1974            }
1975            let Some(src) = st.tile.layers.get(sl) else { continue };
1976            let scale = EXTENT / src.extent as f64;
1977            let tile_zoom = st.coord.0 as f64 + st.overscaling.log2();
1978            let tile_pixel_ratio = EXTENT / (512.0 * st.overscaling);
1979            let text_pixel_ratio = 512.0 * st.overscaling / EXTENT;
1980
1981            let mut feats: Vec<(f64, &Feature)> = Vec::new();
1982            for f in &src.features {
1983                let ctx = Ctx { zoom: tile_zoom, feature: Some(f) };
1984                if layer.get("filter").map_or(false, |flt| !eval_filter(flt, &ctx)) {
1985                    continue;
1986                }
1987                let key = if sort_by_key {
1988                    sort_key_j.map(|j| eval_property(j, Kind::Number, &ctx)).and_then(|v| v.as_num()).unwrap_or(0.0)
1989                } else {
1990                    0.0
1991                };
1992                feats.push((key, f));
1993            }
1994            if sort_by_key {
1995                feats.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
1996            }
1997
1998            for (key, f) in feats {
1999                let ctx = Ctx { zoom, feature: Some(f) };
2000                let lctx_f = Ctx { zoom: tile_zoom, feature: Some(f) };
2001                // Variable anchors: text shaped per justification the anchors use.
2002                let var_offsets = if has_text_field { variable_anchor_offsets(layout, &lctx_f) } else { None };
2003                let mut by_justify: Vec<(String, (TextPart, [f64; 4], (TextExtents, f64)))> = Vec::new();
2004                if let Some(vo) = &var_offsets {
2005                    let tj = string(layout, "text-justify", &lctx_f, "center");
2006                    for (a, _) in vo {
2007                        let j = if tj == "auto" { anchor_justification(a).to_owned() } else { tj.clone() };
2008                        if by_justify.iter().any(|(k, _)| *k == j) {
2009                            continue;
2010                        }
2011                        if let Some(t) = build_text(layer, f, assets, zoom, tile_zoom, tile_pixel_ratio, Some(&j), false) {
2012                            by_justify.push((j, t));
2013                        }
2014                    }
2015                }
2016                let text = if var_offsets.is_some() {
2017                    by_justify.first().map(|(_, t)| t.clone())
2018                } else if has_text_field {
2019                    build_text(layer, f, assets, zoom, tile_zoom, tile_pixel_ratio, None, false)
2020                } else {
2021                    None
2022                };
2023                // Vertical point text (not combined with variable anchors here).
2024                let vertical_text = if allow_vertical && var_offsets.is_none() && text.is_some() {
2025                    build_text(layer, f, assets, zoom, tile_zoom, tile_pixel_ratio, None, true)
2026                } else {
2027                    None
2028                };
2029                let icon = if has_icon_image {
2030                    build_icon(layer, f, assets, zoom, tile_zoom, tile_pixel_ratio, text.as_ref().map(|t| t.2))
2031                } else {
2032                    None
2033                };
2034                if icon.as_ref().map_or(false, |i| i.2) {
2035                    icons_need_linear = true;
2036                }
2037                if text.is_none() && icon.is_none() {
2038                    continue;
2039                }
2040
2041                // Anchors (addFeature).
2042                let mut anchors: Vec<(f64, f64)> = Vec::new();
2043                match &f.geometry {
2044                    Geometry::Points(pts) => anchors.extend(pts.iter().map(|&p| to_extent(p, scale))),
2045                    Geometry::Lines(ls) => anchors.extend(ls.iter().filter_map(|l| l.first().map(|&p| to_extent(p, scale)))),
2046                    Geometry::Polygons(polys) => {
2047                        for poly in polys {
2048                            let rings: Vec<Vec<(f64, f64)>> =
2049                                poly.iter().map(|r| r.iter().map(|&p| to_extent(p, scale)).collect()).collect();
2050                            anchors.push(pole_of_inaccessibility(&rings, 16.0));
2051                        }
2052                    }
2053                }
2054                let ttr = num_pair(paint, "text-translate", &ctx);
2055                let itr = num_pair(paint, "icon-translate", &ctx);
2056                for (ax, ay) in anchors {
2057                    if ax < 0.0 || ax >= EXTENT || ay < 0.0 || ay >= EXTENT {
2058                        continue;
2059                    }
2060                    let px = st.ox + ax * st.unit_px;
2061                    let py = st.oy + ay * st.unit_px;
2062                    let r = text_pixel_ratio;
2063                    let proj = |b: [f64; 4], t: (f64, f64)| {
2064                        let (cx, cy) = (px + t.0 + VIEWPORT_PADDING, py + t.1 + VIEWPORT_PADDING);
2065                        [cx + b[0] * r, cy + b[1] * r, cx + b[2] * r, cy + b[3] * r]
2066                    };
2067                    // calculateVariableLayoutShift / RenderShift per anchor.
2068                    let mut variants = Vec::new();
2069                    if let (Some(vo), Some(base)) = (&var_offsets, &text) {
2070                        let b = base.1;
2071                        let (w, h) = (b[2] - b[0], b[3] - b[1]);
2072                        // SymbolInstance.textBoxScale is a Float32.
2073                        let box_scale = (tile_pixel_ratio * (base.2).1) as f32 as f64;
2074                        let fit = super::expr::layout_enum(layout, "icon-text-fit", tile_zoom).is_some_and(|m| m != "none");
2075                        for (a, (ox, oy)) in vo {
2076                            let tj = string(layout, "text-justify", &lctx_f, "center");
2077                            let j = if tj == "auto" { anchor_justification(a).to_owned() } else { tj };
2078                            let Some((_, part)) = by_justify.iter().find(|(k, _)| *k == j) else { continue };
2079                            let (ha, va) = anchor_alignment(a);
2080                            let shift_tile = (-(ha - 0.5) * w + ox * box_scale, -(va - 0.5) * h + oy * box_scale);
2081                            let fs = part.0.size / ONE_EM;
2082                            let shift_px = ((-(ha - 0.5) * w / box_scale + ox) * fs, (-(va - 0.5) * h / box_scale + oy) * fs);
2083                            let sb = [b[0] + shift_tile.0, b[1] + shift_tile.1, b[2] + shift_tile.0, b[3] + shift_tile.1];
2084                            let mut tp = part.0.clone();
2085                            tp.shift = shift_px;
2086                            let icon_v = if fit {
2087                                icon.as_ref().map(|i| {
2088                                    let ib = [i.1[0] + shift_tile.0, i.1[1] + shift_tile.1, i.1[2] + shift_tile.0, i.1[3] + shift_tile.1];
2089                                    (proj(ib, itr), shift_px)
2090                                })
2091                            } else {
2092                                None
2093                            };
2094                            variants.push((proj(sb, ttr), tp, icon_v));
2095                        }
2096                    }
2097                    instances.push(Instance {
2098                        tile_idx: ti,
2099                        sort_key: key,
2100                        variants,
2101                        text_line: None,
2102                        text_box: text.as_ref().map(|t| proj(t.1, ttr)),
2103                        icon_box: icon.as_ref().map(|i| proj(i.1, itr)),
2104                        vertical: vertical_text.as_ref().map(|t| (proj(t.1, ttr), t.0.clone())),
2105                        label: Label {
2106                            anchor_px: (px, py),
2107                            text: text.as_ref().map(|t| t.0.clone()),
2108                            icon: icon.as_ref().map(|i| i.0.clone()),
2109                            tile: ti,
2110                        },
2111                    });
2112                }
2113            }
2114        }
2115        if sort_by_key {
2116            instances.sort_by(|a, b| a.sort_key.partial_cmp(&b.sort_key).unwrap_or(std::cmp::Ordering::Equal));
2117        }
2118        let has_icon_data = instances.iter().any(|i| i.icon_box.is_some());
2119        let has_text_data = instances.iter().any(|i| i.text_box.is_some() || i.text_line.is_some());
2120        let always_show_text = text_always && (icon_always || !has_icon_data || icon_optional);
2121        let always_show_icon = icon_always && (text_always || !has_text_data || text_optional);
2122
2123        let mut layer_labels: Vec<(f64, usize, Label)> = Vec::new();
2124        for mut inst in instances {
2125            let placeable = |b: &[f64; 4], always: bool, items: &Vec<Item>| {
2126                let inside = b[2] >= 0.0 && b[0] < grid_w && b[3] >= 0.0 && b[1] < grid_h;
2127                inside && (always || !hit_box(items, b, grid_w, grid_h))
2128            };
2129            let mut circles: Vec<(f64, f64, f64)> = Vec::new();
2130            // Variable anchors: the first anchor whose shifted box fits (a
2131            // second round allowing overlap with text-allow-overlap).
2132            let mut variant_placed: Option<bool> = None;
2133            if !inst.variants.is_empty() {
2134                let n = inst.variants.len();
2135                let attempts = if text_always { 2 * n } else { n };
2136                let mut chosen = None;
2137                for i in 0..attempts {
2138                    let (b, _, iv) = &inst.variants[i % n];
2139                    let allow = i >= n;
2140                    let icon_ok = iv.as_ref().map_or(true, |(ib, _)| placeable(ib, icon_always, &items));
2141                    if placeable(b, allow, &items) && icon_ok {
2142                        chosen = Some(i % n);
2143                        break;
2144                    }
2145                }
2146                let k = chosen.unwrap_or(0);
2147                let (b, tp, iv) = inst.variants[k].clone();
2148                inst.text_box = Some(b);
2149                inst.label.text = Some(tp);
2150                if let (Some((ib, sh)), Some(ic)) = (iv, inst.label.icon.as_mut()) {
2151                    inst.icon_box = Some(ib);
2152                    ic.shift = sh;
2153                }
2154                variant_placed = Some(chosen.is_some());
2155            }
2156            // placeTextForPlacementModes: the first writing mode whose box fits.
2157            if let (Some((vb, vpart)), Some(hb), None) = (inst.vertical.take(), inst.text_box, variant_placed) {
2158                let mut fit = None;
2159                for &m in &modes {
2160                    if placeable(if m { &vb } else { &hb }, text_always, &items) {
2161                        fit = Some(m);
2162                        break;
2163                    }
2164                }
2165                if fit == Some(true) {
2166                    inst.text_box = Some(vb);
2167                    inst.label.text = Some(vpart);
2168                }
2169                variant_placed = Some(fit.is_some());
2170            }
2171            let mut place_text = match (&inst.text_box, &inst.text_line) {
2172                (Some(_), _) if variant_placed.is_some() => variant_placed.unwrap(),
2173                (Some(b), _) => placeable(b, text_always, &items),
2174                (None, Some(tc)) => {
2175                    let (c, collided) = match &tc.path {
2176                        Some(path) => place_circles(&items, path, tc.radius, width, height, text_always),
2177                        None => (Vec::new(), false),
2178                    };
2179                    circles = c;
2180                    text_always || (!circles.is_empty() && !collided)
2181                }
2182                (None, None) => false,
2183            };
2184            let mut place_icon = inst.icon_box.as_ref().map_or(false, |b| placeable(b, icon_always, &items));
2185            let has_text = inst.text_box.is_some() || inst.text_line.is_some();
2186            let icon_without_text = text_optional || !has_text;
2187            let text_without_icon = icon_optional || inst.icon_box.is_none();
2188            if !icon_without_text && !text_without_icon {
2189                let both = place_icon && place_text;
2190                place_icon = both;
2191                place_text = both;
2192            } else if !text_without_icon {
2193                place_text = place_icon && place_text;
2194            } else if !icon_without_text {
2195                place_icon = place_icon && place_text;
2196            }
2197            if place_text && !text_ignore {
2198                if let Some(b) = inst.text_box {
2199                    items.push(Item::Box(b));
2200                }
2201                for &(x, y, r) in &circles {
2202                    items.push(Item::Circle(x, y, r));
2203                }
2204            }
2205            if place_icon && !icon_ignore {
2206                items.push(Item::Box(inst.icon_box.unwrap()));
2207            }
2208            let text_visible = place_text || (always_show_text && has_text);
2209            let icon_visible = place_icon || (always_show_icon && inst.icon_box.is_some());
2210            if !text_visible {
2211                inst.label.text = None;
2212            }
2213            if !icon_visible {
2214                inst.label.icon = None;
2215            }
2216            if let Some(ic) = inst.label.icon.as_mut() {
2217                ic.linear = ic.sdf || icon_size_scaled || icons_need_linear || icon_pitch_map;
2218            }
2219            if inst.label.text.is_some() || inst.label.icon.is_some() {
2220                layer_labels.push((inst.sort_key, inst.tile_idx, inst.label));
2221            }
2222        }
2223        // Draw order: per tile, symbols in bucket order (sort-key order).
2224        layer_labels.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)));
2225        placed.insert(layer_idx, layer_labels.into_iter().map(|l| l.2).collect());
2226    }
2227    Placement { labels: placed }
2228}
2229
2230/// A label offset for evaluateVariableOffset: radial, or an explicit
2231/// text-offset (in 24 px glyph units).
2232#[derive(Clone, Copy)]
2233enum VarOffset {
2234    Radial(f64),
2235    Xy(f64, f64),
2236}
2237
2238/// evaluateVariableOffset: the offset (24 px glyph units) of a label placed
2239/// at `anchor`, including MapLibre's 7-unit baseline adjustment for top and
2240/// bottom anchors.
2241fn variable_offset(anchor: &str, off: VarOffset) -> (f64, f64) {
2242    match off {
2243        VarOffset::Xy(x, y) => {
2244            let (x, y) = (x.abs(), y.abs());
2245            let oy = match anchor {
2246                "top-right" | "top-left" | "top" => y - 7.0,
2247                "bottom-right" | "bottom-left" | "bottom" => 7.0 - y,
2248                _ => 0.0,
2249            };
2250            let ox = match anchor {
2251                "top-right" | "bottom-right" | "right" => -x,
2252                "top-left" | "bottom-left" | "left" => x,
2253                _ => 0.0,
2254            };
2255            (ox, oy)
2256        }
2257        VarOffset::Radial(r) => {
2258            let r = r.max(0.0);
2259            let h = r / std::f64::consts::SQRT_2;
2260            let oy = match anchor {
2261                "top-right" | "top-left" => h - 7.0,
2262                "bottom-right" | "bottom-left" => 7.0 - h,
2263                "bottom" => 7.0 - r,
2264                "top" => r - 7.0,
2265                _ => 0.0,
2266            };
2267            let ox = match anchor {
2268                "top-right" | "bottom-right" => -h,
2269                "top-left" | "bottom-left" => h,
2270                "left" => r,
2271                "right" => -r,
2272                _ => 0.0,
2273            };
2274            (ox, oy)
2275        }
2276    }
2277}
2278
2279/// getTextVariableAnchorOffset: the anchors a label tries, in order, with
2280/// their offsets (24 px glyph units), from text-variable-anchor-offset or
2281/// text-variable-anchor (+ text-radial-offset / text-offset). None when the
2282/// layer has neither.
2283fn variable_anchor_offsets(layout: &Json, ctx: &Ctx) -> Option<Vec<(String, (f64, f64))>> {
2284    // Plain arrays start with an anchor name, which the expression evaluator
2285    // would take for an operator: read those literally.
2286    const ANCHORS: [&str; 9] = ["center", "left", "right", "top", "bottom", "top-left", "top-right", "bottom-left", "bottom-right"];
2287    let literal = |j: &Json| j.as_array().and_then(|a| a.first()).and_then(|f| f.as_str()).is_some_and(|f| ANCHORS.contains(&f));
2288    let eval = |j: &Json| if literal(j) { Val::from_json(j) } else { eval_property(j, Kind::Array, ctx) };
2289    if let Some(j) = layout.get("text-variable-anchor-offset").filter(|j| !j.is_null()) {
2290        let v = eval(j);
2291        let items = match v {
2292            Val::Array(a) => a,
2293            _ => return None,
2294        };
2295        let mut out = Vec::new();
2296        for pair in items.chunks(2) {
2297            let (Some(Val::Str(a)), Some(o)) = (pair.first(), pair.get(1)) else { continue };
2298            let o = o.as_num_array().unwrap_or_default();
2299            let (x, mut y) = (o.first().copied().unwrap_or(0.0) * ONE_EM, o.get(1).copied().unwrap_or(0.0) * ONE_EM);
2300            if a.starts_with("top") {
2301                y -= 7.0;
2302            } else if a.starts_with("bottom") {
2303                y += 7.0;
2304            }
2305            out.push((a.clone(), (x, y)));
2306        }
2307        return (!out.is_empty()).then_some(out);
2308    }
2309    let anchors = layout.get("text-variable-anchor").filter(|j| !j.is_null())?;
2310    let anchors: Vec<String> = match eval(anchors) {
2311        Val::Array(a) => a.into_iter().filter_map(|v| if let Val::Str(s) = v { Some(s) } else { None }).collect(),
2312        _ => return None,
2313    };
2314    let off = if layout.get("text-radial-offset").is_some_and(|j| !j.is_null()) {
2315        VarOffset::Radial(num(layout, "text-radial-offset", ctx, 0.0) * ONE_EM)
2316    } else {
2317        let o = num_pair(layout, "text-offset", ctx);
2318        VarOffset::Xy(o.0 * ONE_EM, o.1 * ONE_EM)
2319    };
2320    let out: Vec<(String, (f64, f64))> = anchors.into_iter().map(|a| {
2321        let o = variable_offset(&a, off);
2322        (a, o)
2323    }).collect();
2324    (!out.is_empty()).then_some(out)
2325}
2326
2327/// getAnchorJustification.
2328fn anchor_justification(anchor: &str) -> &'static str {
2329    match anchor {
2330        "right" | "top-right" | "bottom-right" => "right",
2331        "left" | "top-left" | "bottom-left" => "left",
2332        _ => "center",
2333    }
2334}
2335
2336/// Halo passes for a layer (draw_symbol.ts): a separate halo pass when the
2337/// (constant) halo width exceeds 1, is data-driven, or letter spacing is
2338/// negative; otherwise halo and fill in one pass.
2339fn halo_passes(paint: &Json, layout: &Json, prefix: &str) -> &'static [(bool, bool)] {
2340    let halo_j = paint.get(format!("{prefix}-halo-width"));
2341    let has_halo = halo_j.map_or(true, |j| is_data_driven(j) || j.as_f64() != Some(0.0));
2342    let halo_const = halo_j.and_then(|j| if is_data_driven(j) { None } else { j.as_f64() });
2343    let spacing_neg = layout.get("text-letter-spacing").and_then(|j| j.as_f64()).map_or(false, |s| s * ONE_EM < 0.0);
2344    let glyph_overlap = spacing_neg || halo_const.map_or(halo_j.is_some(), |hw| hw > 1.0);
2345    if has_halo && glyph_overlap {
2346        &[(true, false), (false, true)]
2347    } else if has_halo {
2348        &[(true, true)]
2349    } else {
2350        &[(false, true)]
2351    }
2352}
2353
2354/// Draw the placed symbols of one layer: icons for all tiles, then text.
2355/// Draw one symbol layer. Placement is in CSS pixels (`css` is the CSS
2356/// viewport size); quads are drawn `dpr` times larger.
2357pub fn draw_layer(
2358    fb: &mut Framebuffer,
2359    layer: &Json,
2360    layer_idx: usize,
2361    placement: &Placement,
2362    assets: &SymbolAssets,
2363    dpr: f64,
2364    css: (usize, usize),
2365) {
2366    let Some(labels) = placement.labels.get(&layer_idx) else { return };
2367    let (w, h) = (fb.w, fb.h);
2368    let full = Clip { x0: 0.0, y0: 0.0, x1: w as f64, y1: h as f64 };
2369    let paint = &layer["paint"];
2370    let layout = &layer["layout"];
2371
2372    for is_text in [false, true] {
2373        let passes = if is_text { halo_passes(paint, layout, "text") } else { halo_passes(paint, layout, "icon") };
2374        let mut start = 0;
2375        while start < labels.len() {
2376            let tile = labels[start].tile;
2377            let end = labels[start..].iter().position(|l| l.tile != tile).map_or(labels.len(), |p| start + p);
2378            let group = &labels[start..end];
2379            if is_text {
2380                for &(is_halo, is_plain) in passes {
2381                    for l in group {
2382                        if let Some(t) = &l.text {
2383                            let a = (l.anchor_px.0 + t.shift.0, l.anchor_px.1 + t.shift.1);
2384                            draw_text(fb, a, t, &assets.glyphs, is_halo, is_plain, &full, dpr, css);
2385                        }
2386                    }
2387                }
2388            } else {
2389                let sdf = group.iter().any(|l| l.icon.as_ref().map_or(false, |i| i.sdf));
2390                let icon_passes: &[(bool, bool)] = if sdf { passes } else { &[(false, true)] };
2391                for &(is_halo, is_plain) in icon_passes {
2392                    for l in group {
2393                        if let Some(ic) = &l.icon {
2394                            let a = (l.anchor_px.0 + ic.shift.0, l.anchor_px.1 + ic.shift.1);
2395                            draw_icon(fb, a, ic, &assets.sprite, is_halo, is_plain, &full, dpr, css);
2396                        }
2397                    }
2398                }
2399            }
2400            start = end;
2401        }
2402    }
2403}
2404
2405/// symbol_sdf.fragment.glsl for one fragment.
2406fn sdf_fragment(dist: f64, font_scale: f64, s: &SdfStyle, is_halo: bool, is_plain: bool, dpr: f64) -> [f64; 4] {
2407    // EDGE_GAMMA = 0.105 / DEVICE_PIXEL_RATIO
2408    let edge_gamma = EDGE_GAMMA / dpr;
2409    let gamma = edge_gamma / font_scale;
2410    let inner_edge = (256.0 - 64.0) / 256.0;
2411    let fill = [s.fill.r as f64, s.fill.g as f64, s.fill.b as f64, s.fill.a as f64];
2412    let halo = [s.halo.r as f64, s.halo.g as f64, s.halo.b as f64, s.halo.a as f64];
2413    let op = s.opacity;
2414    let mut text = [0f64; 4];
2415    if is_plain {
2416        let a = smoothstep(inner_edge - gamma, inner_edge + gamma, dist);
2417        for i in 0..4 {
2418            text[i] = op * a * fill[i];
2419        }
2420    }
2421    if !is_halo {
2422        return text;
2423    }
2424    let gamma_halo = (s.halo_blur * 1.19 / SDF_PX + edge_gamma) / font_scale;
2425    let inner_edge_halo = inner_edge + gamma_halo;
2426    let halo_edge = (6.0 - s.halo_width / font_scale) / SDF_PX;
2427    let ah = smoothstep(inner_edge_halo - gamma_halo, inner_edge_halo + gamma_halo, dist);
2428    let ah = smoothstep(halo_edge - gamma_halo, halo_edge + gamma_halo, dist).min(1.0 - ah);
2429    let mut out = [0f64; 4];
2430    for i in 0..4 {
2431        let hc = op * ah * halo[i];
2432        out[i] = if is_plain { text[i] + (1.0 - text[3]) * hc } else { hc };
2433    }
2434    out
2435}
2436
2437fn blend_out(fb: &mut Framebuffer, x: usize, y: usize, out: [f64; 4]) {
2438    if out[3] > 0.0 || out[0] > 0.0 || out[1] > 0.0 || out[2] > 0.0 {
2439        fb.blend(x, y, [out[0] as f32, out[1] as f32, out[2] as f32, out[3] as f32]);
2440    }
2441}
2442
2443/// Per-quad screen origin and rotation: the anchor (angle 0) for point
2444/// symbols, or glyphs placed along the projected line (updateLineLabels).
2445/// None when the symbol is hidden.
2446fn along_positions(along: Option<&AlongLine>, anchor: (f64, f64), n: usize, w: usize, h: usize) -> Option<Vec<((f64, f64), f64)>> {
2447    let Some(al) = along else { return Some(vec![(anchor, 0.0); n]) };
2448    along_layout(al, anchor, n, w, h, None).map(|(_, p)| p)
2449}
2450
2451/// The quads to draw for a text part and each quad's (origin, angle): its
2452/// horizontal quads, or the vertical shaping's when updateLineLabels picks
2453/// it for a line running vertically.
2454fn text_layout(t: &TextPart, anchor: (f64, f64), w: usize, h: usize) -> Option<(&[GlyphQuad], Vec<((f64, f64), f64)>)> {
2455    let Some(al) = &t.along else { return Some((&t.quads, vec![(anchor, 0.0); t.quads.len()])) };
2456    let (vertical, pos) = along_layout(al, anchor, t.quads.len(), w, h, al.vertical.as_deref())?;
2457    Some((if vertical { &al.vertical.as_ref()?.quads } else { &t.quads }, pos))
2458}
2459
2460/// updateLineLabels for one symbol (and its vertical counterpart): whether
2461/// the vertical version is drawn, and the glyph positions.
2462fn along_layout(
2463    al: &AlongLine,
2464    anchor: (f64, f64),
2465    n: usize,
2466    w: usize,
2467    h: usize,
2468    vertical: Option<&VerticalAlong>,
2469) -> Option<(bool, Vec<((f64, f64), f64)>)> {
2470    // isVisible: anchor within the clip-space padding.
2471    let (bx, by) = (256.0 / w as f64 * 2.0 + 1.0, 256.0 / h as f64 * 2.0 + 1.0);
2472    let (cx, cy) = (anchor.0 / w as f64 * 2.0 - 1.0, 1.0 - anchor.1 / h as f64 * 2.0);
2473    if cx < -bx || cx > bx || cy < -by || cy > by {
2474        return None;
2475    }
2476    let pl = ProjectedLine { line: &al.line_px, anchor, segment: al.segment };
2477    let mode = if vertical.is_some() { line::WritingMode::Horizontal } else { line::WritingMode::HorizontalOnly };
2478    let place = |offsets: &[f64], mode| {
2479        line::place_glyphs_for_render(&pl, offsets, al.placement_scale, al.line_offset, al.keep_upright, al.rotate_to_line, mode)
2480    };
2481    let positions = |g: Vec<line::PlacedGlyph>, n: usize| (g.len() == n).then(|| g.into_iter().map(|p| (p.point, p.angle)).collect());
2482    match place(&al.glyph_offsets, mode) {
2483        line::GlyphsPlacement::Placed(g) => positions(g, n).map(|p| (false, p)),
2484        line::GlyphsPlacement::UseVertical => {
2485            let v = vertical?;
2486            match place(&v.glyph_offsets, line::WritingMode::Vertical) {
2487                line::GlyphsPlacement::Placed(g) => positions(g, v.quads.len()).map(|p| (true, p)),
2488                _ => None,
2489            }
2490        }
2491        line::GlyphsPlacement::Hidden => None,
2492    }
2493}
2494
2495#[allow(clippy::too_many_arguments)]
2496fn draw_text(
2497    fb: &mut Framebuffer,
2498    anchor: (f64, f64),
2499    t: &TextPart,
2500    glyphs: &GlyphMap,
2501    is_halo: bool,
2502    is_plain: bool,
2503    clip: &Clip,
2504    dpr: f64,
2505    css: (usize, usize),
2506) {
2507    let (w, h) = (clip.x1 as usize, clip.y1 as usize);
2508    if t.style.opacity < 0.1 {
2509        return; // symbol_sdf.vertex: total_opacity < 0.1 is culled
2510    }
2511    let Some(gmap) = glyphs.stacks.get(&t.fontstack) else { return };
2512    let font_scale = t.size / 24.0;
2513    let Some((quads, positions)) = text_layout(t, anchor, css.0, css.1) else { return };
2514    for (qi, q) in quads.iter().enumerate() {
2515        let Some(g) = gmap.get(&q.codepoint) else { continue };
2516        let tex = [(0.0, 0.0), (g.rect_w as f64, 0.0), (0.0, g.rect_h as f64), (g.rect_w as f64, g.rect_h as f64)];
2517        let (origin, angle) = positions[qi];
2518        let (sa, ca) = (angle.sin(), angle.cos());
2519        let v: Vec<Vert<2>> = (0..4)
2520            .map(|i| {
2521                let (ox, oy) = (q.corners[i].0 * font_scale, q.corners[i].1 * font_scale);
2522                Vert {
2523                    x: (origin.0 + ca * ox - sa * oy) * dpr,
2524                    y: (origin.1 + sa * ox + ca * oy) * dpr,
2525                    v: [tex[i].0, tex[i].1],
2526                }
2527            })
2528            .collect();
2529        for tri in [[0usize, 2, 1], [1, 2, 3]] {
2530            raster_triangle(w, h, [v[tri[0]], v[tri[1]], v[tri[2]]], clip, |x, y, tc| {
2531                let out = sdf_fragment(g.sample(tc[0], tc[1]), font_scale, &t.style, is_halo, is_plain, dpr);
2532                blend_out(fb, x, y, out);
2533            });
2534        }
2535    }
2536}
2537
2538#[allow(clippy::too_many_arguments)]
2539fn draw_icon(
2540    fb: &mut Framebuffer,
2541    anchor: (f64, f64),
2542    ic: &IconPart,
2543    sprite: &Sprite,
2544    is_halo: bool,
2545    is_plain: bool,
2546    clip: &Clip,
2547    dpr: f64,
2548    css: (usize, usize),
2549) {
2550    let (w, h) = (clip.x1 as usize, clip.y1 as usize);
2551    if ic.style.opacity < 0.1 {
2552        return;
2553    }
2554    let Some(img) = sprite.images.get(&ic.image) else { return };
2555    let Some(positions) = along_positions(ic.along.as_ref(), anchor, 1, css.0, css.1) else { return };
2556    let (origin, angle) = positions[0];
2557    let (sa, ca) = (angle.sin(), angle.cos());
2558    for q in &ic.quads {
2559    let (tx, ty, tw, th) = q.tex;
2560    let tex = [(tx, ty), (tx + tw, ty), (tx, ty + th), (tx + tw, ty + th)];
2561    let corners = q.corners(ic.size);
2562    let v: Vec<Vert<2>> = (0..4)
2563        .map(|i| {
2564            let (ox, oy) = corners[i];
2565            Vert {
2566                x: (origin.0 + ca * ox - sa * oy) * dpr,
2567                y: (origin.1 + sa * ox + ca * oy) * dpr,
2568                v: [tex[i].0, tex[i].1],
2569            }
2570        })
2571        .collect();
2572    for tri in [[0usize, 2, 1], [1, 2, 3]] {
2573        raster_triangle(w, h, [v[tri[0]], v[tri[1]], v[tri[2]]], clip, |x, y, tc| {
2574            let s = img.sample(tc[0], tc[1], ic.linear);
2575            let out = if ic.sdf {
2576                sdf_fragment(s[3] / 255.0, ic.size, &ic.style, is_halo, is_plain, dpr)
2577            } else {
2578                let op = ic.style.opacity;
2579                [s[0] / 255.0 * op, s[1] / 255.0 * op, s[2] / 255.0 * op, s[3] / 255.0 * op]
2580            };
2581            blend_out(fb, x, y, out);
2582        });
2583    }
2584    }
2585}
2586
2587// ── SVG output ───────────────────────────────────────────────────────────────
2588
2589/// Affine map from a quad's texture cell (u, v in [0, cw] x [0, ch]) to its
2590/// screen corners tl, tr, bl.
2591fn cell_to_screen(c: [(f64, f64); 4], cw: f64, ch: f64) -> impl Fn((f64, f64)) -> (f64, f64) {
2592    let (tl, tr, bl) = (c[0], c[1], c[2]);
2593    move |(u, v)| {
2594        (
2595            tl.0 + (tr.0 - tl.0) * u / cw + (bl.0 - tl.0) * v / ch,
2596            tl.1 + (tr.1 - tl.1) * u / cw + (bl.1 - tl.1) * v / ch,
2597        )
2598    }
2599}
2600
2601/// Screen corners (tl, tr, bl, br) of a quad placed at `origin`, rotated by
2602/// `angle`, with corner offsets scaled by `scale`.
2603fn quad_screen(corners: &[(f64, f64); 4], origin: (f64, f64), angle: f64, scale: f64) -> [(f64, f64); 4] {
2604    let (sa, ca) = (angle.sin(), angle.cos());
2605    corners.map(|(x, y)| {
2606        let (ox, oy) = (x * scale, y * scale);
2607        (origin.0 + ca * ox - sa * oy, origin.1 + sa * ox + ca * oy)
2608    })
2609}
2610
2611/// SDF outline paths for one quad, as the SDF shader would draw it: for the
2612/// halo pass a ring (the halo contour minus the contour where the halo fades
2613/// out inside the glyph), for the fill pass the glyph contour at the edge
2614/// threshold. Rings wind consistently, so `nonzero` subtracts the inner ring.
2615#[allow(clippy::too_many_arguments)]
2616fn svg_sdf_quad(
2617    out: &mut String,
2618    cache: &mut HashMap<(String, u32, i64), Vec<Vec<(f64, f64)>>>,
2619    key: (&str, u32),
2620    w: usize,
2621    h: usize,
2622    value: &dyn Fn(usize, usize) -> f64,
2623    map: &dyn Fn((f64, f64)) -> (f64, f64),
2624    font_scale: f64,
2625    s: &SdfStyle,
2626    is_halo: bool,
2627    is_plain: bool,
2628) {
2629    use super::svg;
2630    use std::fmt::Write as _;
2631    let mut rings_at = |thr: f64, reverse: bool| -> Vec<Vec<(f64, f64)>> {
2632        let k = (key.0.to_owned(), key.1, (thr * 10_000.0).round() as i64);
2633        let rings = cache.entry(k).or_insert_with(|| svg::trace_contours(w, h, value, thr));
2634        rings
2635            .iter()
2636            .map(|r| {
2637                let mut pts: Vec<(f64, f64)> = r.iter().map(|&p| map(p)).collect();
2638                if reverse {
2639                    pts.reverse();
2640                }
2641                pts
2642            })
2643            .collect()
2644    };
2645    // symbol_sdf.fragment.glsl: alpha = smoothstep(edge - gamma, edge + gamma,
2646    // dist), a ramp about 0.84 px wide at any size (EDGE_GAMMA at ratio 1).
2647    // SVG has no such ramp, so it is approximated by SDF_BANDS nested
2648    // outlines traced where the smoothstep crosses (k - 1/2) / N, with
2649    // opacities that stack to k/N of the colour's alpha.
2650    let inner_edge = (256.0 - 64.0) / 256.0;
2651    let mut banded = |out: &mut String, hex: &str, a: f64, edge: f64, gamma: f64, hole: Option<f64>| {
2652        let n = SDF_BANDS;
2653        let mut below = 0.0; // stacked alpha so far
2654        for k in 1..=n {
2655            let y = (k as f64 - 0.5) / n as f64;
2656            let t = 0.5 - ((1.0 - 2.0 * y).asin() / 3.0).sin(); // smoothstep^-1(y)
2657            let thr = edge + gamma * BAND_SPREAD * (2.0 * t - 1.0);
2658            let target = a * k as f64 / n as f64;
2659            let layer = if below >= 1.0 { 0.0 } else { ((target - below) / (1.0 - below)).clamp(0.0, 1.0) };
2660            below = target;
2661            let mut rings = rings_at(thr, false);
2662            if let Some(h) = hole {
2663                rings.extend(rings_at(h, true));
2664            }
2665            if !rings.is_empty() && layer > 0.0 {
2666                let _ = write!(out, r#"<path d="{}" fill="{hex}" fill-opacity="{}"/>"#, svg::path_data(&rings, true), svg::alpha(layer));
2667            }
2668        }
2669    };
2670    if is_halo && s.halo_width > 0.0 && s.halo.a > 0.0 {
2671        if let Some((hex, a)) = svg::paint(s.halo, s.opacity) {
2672            let gamma_halo = (s.halo_blur * 1.19 / SDF_PX + EDGE_GAMMA) / font_scale;
2673            let halo_edge = (6.0 - s.halo_width / font_scale) / SDF_PX;
2674            banded(out, &hex, a, halo_edge, gamma_halo, Some(inner_edge + gamma_halo));
2675        }
2676    }
2677    if is_plain {
2678        if let Some((hex, a)) = svg::paint(s.fill, s.opacity) {
2679            banded(out, &hex, a, inner_edge, EDGE_GAMMA / font_scale, None);
2680        }
2681    }
2682}
2683
2684/// Outlines per SDF edge in SVG output (see svg_sdf_quad), and how far apart
2685/// they sit relative to the smoothstep's quantiles. Measured against MapLibre
2686/// (resvg rasterisation): 2 bands at 0.85 fit best; more bands over-soften,
2687/// because the rasteriser's own edge antialiasing adds to the ramp.
2688const SDF_BANDS: usize = 2;
2689const BAND_SPREAD: f64 = 0.85;
2690
2691/// SVG glyphs drawn from MapLibre's SDF bitmaps: each glyph's distance field
2692/// embedded once as an image (in its alpha channel), drawn through a filter
2693/// whose transfer tables are symbol_sdf.fragment.glsl's edge functions
2694/// (fill smoothstep, halo ring), so the viewer interpolates the field and
2695/// thresholds it at screen resolution, as the shader does.
2696#[derive(Default)]
2697struct SdfBitmaps {
2698    /// Prefix making ids unique in the document (style and layer).
2699    tag: String,
2700    images: HashMap<(String, u32), String>,
2701    filters: HashMap<String, String>,
2702}
2703
2704impl SdfBitmaps {
2705    #[allow(clippy::too_many_arguments)]
2706    fn glyph(
2707        &mut self,
2708        out: &mut String,
2709        defs: &mut String,
2710        prefix: &str,
2711        stack: &str,
2712        cp: u32,
2713        g: &Glyph,
2714        q: [(f64, f64); 4],
2715        font_scale: f64,
2716        s: &SdfStyle,
2717        is_halo: bool,
2718        is_plain: bool,
2719    ) {
2720        use super::svg;
2721        use std::fmt::Write as _;
2722        if g.rect_w == 0 || g.rect_h == 0 {
2723            return;
2724        }
2725        let draw_halo = is_halo && s.halo_width > 0.0 && s.halo.a > 0.0;
2726        let fill = if is_plain { svg::paint(s.fill, s.opacity) } else { None };
2727        let halo = if draw_halo { svg::paint(s.halo, s.opacity) } else { None };
2728        if fill.is_none() && halo.is_none() {
2729            return;
2730        }
2731        let n = self.images.len();
2732        let img = self
2733            .images
2734            .entry((stack.to_owned(), cp))
2735            .or_insert_with(|| {
2736                let id = format!("{prefix}{}sdf{n}", self.tag);
2737                let mut rgba = Vec::with_capacity(g.rect_w * g.rect_h * 4);
2738                // Field in the colour channels, opaque: alpha marks the glyph
2739                // quad, so the filter can clip to it (MapLibre draws nothing
2740                // outside the quad, even where a wide halo's ramp is non-zero
2741                // at field value 0).
2742                for &v in &g.cell {
2743                    rgba.extend_from_slice(&[v, v, v, 255]);
2744                }
2745                let _ = write!(
2746                    defs,
2747                    r#"<image id="{id}" width="{}" height="{}" href="{}"/>"#,
2748                    g.rect_w,
2749                    g.rect_h,
2750                    svg::png_data_uri(g.rect_w as u32, g.rect_h as u32, &rgba)
2751                );
2752                id
2753            })
2754            .clone();
2755        // Transfer tables over the field value 0..1 (dpr 1 EDGE_GAMMA).
2756        let inner_edge = (256.0 - 64.0) / 256.0;
2757        let gamma = EDGE_GAMMA / font_scale;
2758        let gamma_halo = (s.halo_blur * 1.19 / SDF_PX + EDGE_GAMMA) / font_scale;
2759        let halo_edge = (6.0 - s.halo_width / font_scale) / SDF_PX;
2760        let table = |f: &dyn Fn(f64) -> f64| -> String {
2761            (0..=128).map(|i| svg::alpha(f(i as f64 / 128.0).clamp(0.0, 1.0))).collect::<Vec<_>>().join(" ")
2762        };
2763        let fill_t = fill.as_ref().map(|_| table(&|d| smoothstep(inner_edge - gamma, inner_edge + gamma, d)));
2764        let halo_t = halo.as_ref().map(|_| {
2765            table(&|d| {
2766                let ih = inner_edge + gamma_halo;
2767                let ah = smoothstep(ih - gamma_halo, ih + gamma_halo, d);
2768                smoothstep(halo_edge - gamma_halo, halo_edge + gamma_halo, d).min(1.0 - ah)
2769            })
2770        });
2771        let key = format!("{:?}|{:?}|{:?}|{:?}", fill, halo, fill_t.as_ref().map(|t| t.len()), (svg::num(font_scale * 1000.0), svg::num(s.halo_width * 100.0), svg::num(s.halo_blur * 100.0)));
2772        let m = self.filters.len();
2773        let filter = self
2774            .filters
2775            .entry(key)
2776            .or_insert_with(|| {
2777                let id = format!("{prefix}{}sdff{m}", self.tag);
2778                let mut body = String::from(r#"<feColorMatrix in="SourceGraphic" type="matrix" values="0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0" result="sdf"/>"#);
2779                if let (Some((hex, a)), Some(t)) = (&halo, &halo_t) {
2780                    let _ = write!(
2781                        body,
2782                        r#"<feComponentTransfer in="sdf" result="ha"><feFuncA type="table" tableValues="{t}"/></feComponentTransfer><feFlood flood-color="{hex}" flood-opacity="{}"/><feComposite in2="ha" operator="in" result="h"/>"#,
2783                        svg::alpha(*a)
2784                    );
2785                }
2786                if let (Some((hex, a)), Some(t)) = (&fill, &fill_t) {
2787                    let _ = write!(
2788                        body,
2789                        r#"<feComponentTransfer in="sdf" result="fa"><feFuncA type="table" tableValues="{t}"/></feComponentTransfer><feFlood flood-color="{hex}" flood-opacity="{}"/><feComposite in2="fa" operator="in" result="f"/>"#,
2790                        svg::alpha(*a)
2791                    );
2792                }
2793                let mut merge = String::new();
2794                if halo.is_some() {
2795                    merge.push_str(r#"<feMergeNode in="h"/>"#);
2796                }
2797                if fill.is_some() {
2798                    merge.push_str(r#"<feMergeNode in="f"/>"#);
2799                }
2800                let _ = write!(
2801                    defs,
2802                    r#"<filter id="{id}" color-interpolation-filters="sRGB">{body}<feMerge result="m">{merge}</feMerge><feComposite in="m" in2="SourceAlpha" operator="in"/></filter>"#
2803                );
2804                id
2805            })
2806            .clone();
2807        // Cell (u, v) -> screen, as for icons.
2808        let (tl, tr, bl) = (q[0], q[1], q[2]);
2809        let (cw, ch) = (g.rect_w as f64, g.rect_h as f64);
2810        let (a_, b_) = ((tr.0 - tl.0) / cw, (tr.1 - tl.1) / cw);
2811        let (c_, d_) = ((bl.0 - tl.0) / ch, (bl.1 - tl.1) / ch);
2812        let _ = write!(
2813            out,
2814            r##"<g filter="url(#{filter})"><use href="#{img}" transform="matrix({} {} {} {} {} {})"/></g>"##,
2815            a_,
2816            b_,
2817            c_,
2818            d_,
2819            svg::num(tl.0),
2820            svg::num(tl.1)
2821        );
2822    }
2823}
2824
2825/// Write one symbol layer as SVG in draw_layer's order: icons, then text,
2826/// each per tile with the shader's halo passes. Glyphs and SDF icons are
2827/// outlines traced from their SDFs at the shader's thresholds, one path per
2828/// quad (MapLibre blends each quad separately); other icons are embedded
2829/// sprite images.
2830#[allow(clippy::too_many_arguments)]
2831pub fn svg_layer(
2832    out: &mut String,
2833    defs: &mut String,
2834    layer: &Json,
2835    layer_idx: usize,
2836    placement: &Placement,
2837    assets: &SymbolAssets,
2838    w: usize,
2839    h: usize,
2840    prefix: &str,
2841    text_mode: super::fonts::SvgText,
2842    fonts: Option<&super::fonts::SvgFonts>,
2843) {
2844    use super::fonts::SvgText;
2845    use super::svg;
2846    use std::fmt::Write as _;
2847    let Some(labels) = placement.labels.get(&layer_idx) else { return };
2848    let mut bitmaps = SdfBitmaps { tag: format!("L{layer_idx}"), ..Default::default() };
2849    let paint = &layer["paint"];
2850    let layout = &layer["layout"];
2851    let mut cache: HashMap<(String, u32, i64), Vec<Vec<(f64, f64)>>> = HashMap::new();
2852    let mut image_ids: HashMap<String, String> = HashMap::new();
2853    let lid = layer["id"].as_str().unwrap_or("").replace(|c: char| !c.is_ascii_alphanumeric(), "_");
2854    out.push_str(r#"<g fill-rule="nonzero">"#);
2855
2856    let tile_groups = || {
2857        let mut groups = Vec::new();
2858        let mut start = 0;
2859        while start < labels.len() {
2860            let tile = labels[start].tile;
2861            let end = labels[start..].iter().position(|l| l.tile != tile).map_or(labels.len(), |p| start + p);
2862            groups.push(&labels[start..end]);
2863            start = end;
2864        }
2865        groups
2866    };
2867
2868    // Icons.
2869    let icon_halo_passes = halo_passes(paint, layout, "icon");
2870    for group in tile_groups() {
2871        let sdf = group.iter().any(|l| l.icon.as_ref().map_or(false, |i| i.sdf));
2872        let passes: &[(bool, bool)] = if sdf { icon_halo_passes } else { &[(false, true)] };
2873        for &(is_halo, is_plain) in passes {
2874            for l in group {
2875                let Some(ic) = &l.icon else { continue };
2876                if ic.style.opacity < 0.1 {
2877                    continue;
2878                }
2879                let Some(img) = assets.sprite.images.get(&ic.image) else { continue };
2880                let Some(pos) = along_positions(ic.along.as_ref(), (l.anchor_px.0 + ic.shift.0, l.anchor_px.1 + ic.shift.1), 1, w, h) else { continue };
2881                let (cw, ch) = (img.w + 2, img.h + 2);
2882                let multi = ic.quads.len() > 1;
2883                for (qi, iq) in ic.quads.iter().enumerate() {
2884                // Corners at the icon's size (pixel offsets included).
2885                let q = quad_screen(&iq.corners(ic.size), pos[0].0, pos[0].1, 1.0);
2886                let _ = qi;
2887                let (tx, ty, tw, th) = iq.tex;
2888                // Affine map from cell (u, v) to screen for this quad.
2889                let (tl, tr, bl) = (q[0], q[1], q[2]);
2890                let (a_, b_) = ((tr.0 - tl.0) / tw, (tr.1 - tl.1) / tw);
2891                let (c_, d_) = ((bl.0 - tl.0) / th, (bl.1 - tl.1) / th);
2892                let (e_, f_) = (tl.0 - a_ * tx - c_ * ty, tl.1 - b_ * tx - d_ * ty);
2893                let clip_open = if multi {
2894                    let d = svg::path_data(&[vec![q[0], q[1], q[3], q[2]]], true);
2895                    let cid = format!("{prefix}{lid}_q{}", image_ids.len() * 1000 + defs.len());
2896                    let _ = write!(defs, r#"<clipPath id="{cid}"><path d="{d}"/></clipPath>"#);
2897                    let _ = write!(out, r#"<g clip-path="url(#{cid})">"#);
2898                    true
2899                } else {
2900                    false
2901                };
2902                if img.sdf {
2903                    let map = move |p: (f64, f64)| (a_ * p.0 + c_ * p.1 + e_, b_ * p.0 + d_ * p.1 + f_);
2904                    let value = |i: usize, j: usize| img.cell[(j * cw + i) * 4 + 3] as f64 / 255.0;
2905                    let key = format!("icon:{}", ic.image);
2906                    svg_sdf_quad(out, &mut cache, (&key, 0), cw, ch, &value, &map, ic.size, &ic.style, is_halo, is_plain);
2907                    if clip_open {
2908                        out.push_str("</g>");
2909                    }
2910                    continue;
2911                }
2912                let n = image_ids.len();
2913                let id = image_ids
2914                    .entry(ic.image.clone())
2915                    .or_insert_with(|| {
2916                        let id = format!("{prefix}{lid}_img{n}");
2917                        let _ = write!(defs, r#"<image id="{id}" width="{}" height="{}" href="{}"/>"#, img.w, img.h, img.png_data_uri());
2918                        id
2919                    })
2920                    .clone();
2921                // matrix maps cell (u, v) to screen; the image sits at cell (1, 1).
2922                let render = if ic.linear { "" } else { r#" style="image-rendering:pixelated""# };
2923                let _ = write!(
2924                    out,
2925                    r##"<use href="#{id}" x="1" y="1" opacity="{}" transform="matrix({} {} {} {} {} {})"{render}/>"##,
2926                    svg::alpha(ic.style.opacity.min(1.0)),
2927                    a_,
2928                    b_,
2929                    c_,
2930                    d_,
2931                    svg::num(e_),
2932                    svg::num(f_)
2933                );
2934                if clip_open {
2935                    out.push_str("</g>");
2936                }
2937                }
2938            }
2939        }
2940    }
2941
2942    // Text as editable <text>: one element per label, each glyph at its
2943    // MapLibre position (and rotation along lines), the halo as a stroke
2944    // painted beneath the fill.
2945    if let (SvgText::Editable, Some(fonts)) = (text_mode, fonts) {
2946        let rb = GLYPH_PBF_BORDER + ATLAS_PADDING as f64;
2947        let mut shifts: HashMap<String, f64> = HashMap::new();
2948        for group in tile_groups() {
2949            for l in group {
2950                let Some(t) = &l.text else { continue };
2951                if t.style.opacity < 0.1 {
2952                    continue;
2953                }
2954                let Some(gmap) = assets.glyphs.stacks.get(&t.fontstack) else { continue };
2955                let fs = t.size / 24.0;
2956                let Some((quads, pos)) = text_layout(t, (l.anchor_px.0 + t.shift.0, l.anchor_px.1 + t.shift.1), w, h) else { continue };
2957                // No exact font for this label: MapLibre's own glyph bitmaps.
2958                let label_text: String = quads.iter().filter_map(|q| char::from_u32(q.codepoint)).collect();
2959                if !fonts.covers(&t.fontstack, &label_text) {
2960                    for (qi, q) in quads.iter().enumerate() {
2961                        let Some(g) = gmap.get(&q.codepoint) else { continue };
2962                        let sq = quad_screen(&q.corners, pos[qi].0, pos[qi].1, fs);
2963                        bitmaps.glyph(out, defs, prefix, &t.fontstack, q.codepoint, g, sq, fs, &t.style, true, true);
2964                    }
2965                    continue;
2966                }
2967                let shift = *shifts.entry(t.fontstack.clone()).or_insert_with(|| {
2968                    let tops: Vec<(u32, f64)> = gmap.iter().filter(|(_, g)| g.height > 0.0).map(|(cp, g)| (*cp, g.top)).collect();
2969                    fonts.baseline_shift(&t.fontstack, &tops)
2970                });
2971                let (mut xs, mut ys, mut rs, mut text) = (Vec::new(), Vec::new(), Vec::new(), String::new());
2972                for (qi, q) in quads.iter().enumerate() {
2973                    let (Some(g), Some(ch)) = (gmap.get(&q.codepoint), char::from_u32(q.codepoint)) else { continue };
2974                    // Baseline origin of the glyph in quad space: the quad's
2975                    // top-left is (left - buffer, -top - buffer) from it,
2976                    // possibly rotated (text-rotate).
2977                    let c = q.corners;
2978                    let rot = if c[1] == c[0] { 0.0 } else { (c[1].1 - c[0].1).atan2(c[1].0 - c[0].0) };
2979                    let (s0, c0) = (rot.sin(), rot.cos());
2980                    let tlu = (c0 * c[0].0 + s0 * c[0].1, -s0 * c[0].0 + c0 * c[0].1);
2981                    let ou = (tlu.0 - (g.left - rb), tlu.1 + g.top + rb + shift);
2982                    let ol = (c0 * ou.0 - s0 * ou.1, s0 * ou.0 + c0 * ou.1);
2983                    let (origin, angle) = pos[qi];
2984                    let (sa, ca) = (angle.sin(), angle.cos());
2985                    let (ox, oy) = (ol.0 * fs, ol.1 * fs);
2986                    xs.push(svg::num(origin.0 + ca * ox - sa * oy));
2987                    ys.push(svg::num(origin.1 + sa * ox + ca * oy));
2988                    rs.push((rot + angle).to_degrees());
2989                    text.push(ch);
2990                }
2991                if text.trim().is_empty() {
2992                    continue;
2993                }
2994                fonts.note_text(&t.fontstack, &text);
2995                let rotate = if rs.iter().any(|r| r.abs() > 0.01) {
2996                    format!(r#" rotate="{}""#, rs.iter().map(|r| svg::num(*r)).collect::<Vec<_>>().join(" "))
2997                } else {
2998                    String::new()
2999                };
3000                let mut paint_attrs = String::new();
3001                if let Some((hex, a)) = svg::paint(t.style.fill, t.style.opacity) {
3002                    let _ = write!(paint_attrs, r#" fill="{hex}" fill-opacity="{}""#, svg::alpha(a));
3003                } else {
3004                    paint_attrs.push_str(r#" fill="none""#);
3005                }
3006                if t.style.halo_width > 0.0 {
3007                    if let Some((hex, a)) = svg::paint(t.style.halo, t.style.opacity) {
3008                        let _ = write!(
3009                            paint_attrs,
3010                            r#" stroke="{hex}" stroke-opacity="{}" stroke-width="{}" stroke-linejoin="round" paint-order="stroke""#,
3011                            svg::alpha(a),
3012                            svg::num(2.0 * t.style.halo_width)
3013                        );
3014                    }
3015                }
3016                // Glyphs are already in visual order (and Arabic in its
3017                // presentation forms): viewers must not reorder them again.
3018                if text.chars().any(super::rtl::is_rtl_char) {
3019                    paint_attrs.push_str(r#" direction="ltr" unicode-bidi="bidi-override""#);
3020                }
3021                let _ = write!(
3022                    out,
3023                    r#"<text xml:space="preserve" {} font-size="{}" x="{}" y="{}"{rotate}{paint_attrs}>{}</text>"#,
3024                    fonts.text_attrs(&t.fontstack),
3025                    svg::num(t.size),
3026                    xs.join(" "),
3027                    ys.join(" "),
3028                    svg::xml_escape(&text)
3029                );
3030            }
3031        }
3032        out.push_str("</g>");
3033        return;
3034    }
3035
3036    if text_mode == SvgText::Bitmap {
3037        let text_passes = halo_passes(paint, layout, "text");
3038        for group in tile_groups() {
3039            for &(is_halo, is_plain) in text_passes {
3040                for l in group {
3041                    let Some(t) = &l.text else { continue };
3042                    if t.style.opacity < 0.1 {
3043                        continue;
3044                    }
3045                    let Some(gmap) = assets.glyphs.stacks.get(&t.fontstack) else { continue };
3046                    let fs = t.size / 24.0;
3047                    let Some((quads, pos)) = text_layout(t, (l.anchor_px.0 + t.shift.0, l.anchor_px.1 + t.shift.1), w, h) else { continue };
3048                    for (qi, q) in quads.iter().enumerate() {
3049                        let Some(g) = gmap.get(&q.codepoint) else { continue };
3050                        let sq = quad_screen(&q.corners, pos[qi].0, pos[qi].1, fs);
3051                        bitmaps.glyph(out, defs, prefix, &t.fontstack, q.codepoint, g, sq, fs, &t.style, is_halo, is_plain);
3052                    }
3053                }
3054            }
3055        }
3056        out.push_str("</g>");
3057        return;
3058    }
3059
3060    // Text as traced glyph outlines.
3061    let text_passes = halo_passes(paint, layout, "text");
3062    for group in tile_groups() {
3063        for &(is_halo, is_plain) in text_passes {
3064            for l in group {
3065                let Some(t) = &l.text else { continue };
3066                if t.style.opacity < 0.1 {
3067                    continue;
3068                }
3069                let Some(gmap) = assets.glyphs.stacks.get(&t.fontstack) else { continue };
3070                let fs = t.size / 24.0;
3071                let Some((quads, pos)) = text_layout(t, (l.anchor_px.0 + t.shift.0, l.anchor_px.1 + t.shift.1), w, h) else { continue };
3072                for (qi, q) in quads.iter().enumerate() {
3073                    let Some(g) = gmap.get(&q.codepoint) else { continue };
3074                    let sq = quad_screen(&q.corners, pos[qi].0, pos[qi].1, fs);
3075                    let map = cell_to_screen(sq, g.rect_w as f64, g.rect_h as f64);
3076                    let value = |i: usize, j: usize| g.cell[j * g.rect_w + i] as f64 / 255.0;
3077                    svg_sdf_quad(
3078                        out,
3079                        &mut cache,
3080                        (&t.fontstack, q.codepoint),
3081                        g.rect_w,
3082                        g.rect_h,
3083                        &value,
3084                        &map,
3085                        fs,
3086                        &t.style,
3087                        is_halo,
3088                        is_plain,
3089                    );
3090                }
3091            }
3092        }
3093    }
3094    out.push_str("</g>");
3095}
3096
3097#[cfg(test)]
3098mod tests {
3099    use super::*;
3100
3101    fn glyphs_fixed(advance: f64) -> HashMap<u32, Glyph> {
3102        let mut m = HashMap::new();
3103        for c in [' ', 'a', 'b', 'c'] {
3104            m.insert(
3105                c as u32,
3106                Glyph { width: 10.0, height: 10.0, left: 0.0, top: -5.0, advance, rect_w: 18, rect_h: 18, cell: vec![0; 324] },
3107            );
3108        }
3109        m
3110    }
3111
3112    #[test]
3113    fn single_line_centered() {
3114        let g = glyphs_fixed(10.0);
3115        let s = shape_text("abc", &g, 240.0, 28.8, "center", "center", 0.0, (0.0, 0.0), false, false).unwrap();
3116        assert_eq!(s.lines.len(), 1);
3117        assert_eq!((s.left, s.right), (-15.0, 15.0));
3118        assert_eq!(s.lines[0][0].x, -15.0);
3119    }
3120
3121    #[test]
3122    fn breaks_long_text() {
3123        let g = glyphs_fixed(10.0);
3124        // 11 words of 3 chars + spaces, max width 50 -> several lines.
3125        let s = shape_text("abc abc abc abc", &g, 50.0, 28.8, "center", "center", 0.0, (0.0, 0.0), false, false).unwrap();
3126        assert!(s.lines.len() >= 2);
3127    }
3128
3129    #[test]
3130    fn pole_of_square_is_centre() {
3131        let sq = vec![vec![(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0), (0.0, 0.0)]];
3132        let (x, y) = pole_of_inaccessibility(&sq, 1.0);
3133        assert!((x - 50.0).abs() < 1.0 && (y - 50.0).abs() < 1.0);
3134    }
3135}