Skip to main content

basemapper_core/vector/
render.rs

1//! Render decoded vector tiles with a MapLibre style, modelling MapLibre GL
2//! JS's WebGL pipeline in software (see `gl.rs`).
3//!
4//! The view is centred on the bbox centre at MapLibre's scale zoom (512 px
5//! tiles), exactly as MapLibre's transform places it. Layers are drawn in style
6//! order; fill and line fragments are clipped to their tile's square (MapLibre's
7//! stencil test). Circles are not clipped; points outside the tile are dropped,
8//! as MapLibre's CircleBucket does.
9
10use super::expr::{eval_filter, eval_property, is_data_driven, Color, Ctx, Kind, Val};
11use super::gl::{
12    raster_gl_line, raster_polygon, raster_triangle, smoothstep, Cap, Clip, Dash, Framebuffer, Join,
13    LineBuilder, Vert, ATLAS_W, EXTENT,
14};
15use super::mvt::{self, Feature, Geometry, Tile};
16use super::svg;
17use super::symbol::{self, SymbolAssets, SymbolTile};
18use crate::tile_fetcher::TileCoord;
19use serde_json::Value as Json;
20
21const EARTH_HALF: f64 = 20_037_508.342_789_244;
22const EARTH_CIRC: f64 = 2.0 * EARTH_HALF;
23/// MapLibre vector tiles are laid out on a 512 px grid.
24pub const TILE_PX: f64 = 512.0;
25
26/// MapLibre's scale zoom for a bbox drawn `width` pixels wide.
27pub fn scale_zoom(bbox: [f64; 4], width: u32) -> f64 {
28    let mpp = (bbox[2] - bbox[0]) / width as f64;
29    let z = (EARTH_CIRC / (TILE_PX * mpp)).log2();
30    // MapLibre picks tiles by floor(zoom); don't let float noise from a
31    // bbox computed for an integer zoom (12.99994…) drop a whole level.
32    if (z - z.round()).abs() < 1e-3 {
33        z.round()
34    } else {
35        z
36    }
37}
38
39/// Tiles covering `bbox` at tile zoom `z`, as (canonical tile, wrap). Columns
40/// past ±180° belong to a wrapped world copy: wrap -1 is the copy to the
41/// west, +1 to the east (MapLibre's renderWorldCopies).
42pub fn covering_tiles(bbox: [f64; 4], z: u8) -> Vec<(TileCoord, i32)> {
43    let n = 1i64 << z;
44    let col = |x: f64| ((x + EARTH_HALF) / EARTH_CIRC * n as f64).floor() as i64;
45    let row = |y: f64| (((EARTH_HALF - y) / EARTH_CIRC * n as f64).floor() as i64).clamp(0, n - 1);
46    let (x0, x1) = (col(bbox[0]), col(bbox[2]));
47    let (y0, y1) = (row(bbox[3]), row(bbox[1]));
48    let mut out = Vec::new();
49    for x in x0..=x1 {
50        for y in y0..=y1 {
51            let c = TileCoord { z, x: x.rem_euclid(n) as u32, y: y as u32 };
52            out.push((c, x.div_euclid(n) as i32));
53        }
54    }
55    out
56}
57
58/// Tile zoom MapLibre would request for a vector source at this view.
59pub fn tile_zoom(scale_zoom: f64, source_maxzoom: Option<u8>) -> u8 {
60    let z = scale_zoom.floor().clamp(0.0, 22.0) as u8;
61    source_maxzoom.map_or(z, |m| z.min(m))
62}
63
64struct PlacedTile {
65    coord: TileCoord,
66    /// World copy: -1 west, 0 the primary world, +1 east.
67    wrap: i32,
68    tile: Tile,
69    /// Canvas position of the tile's top-left corner, in px.
70    ox: f64,
71    oy: f64,
72    /// Canvas px per 8192-extent tile unit.
73    unit_px: f64,
74    clip: Clip,
75    overscaling: f64,
76    /// Device pixels per CSS pixel; `ox`, `oy`, `unit_px` and `clip` are in
77    /// device pixels (MapLibre's drawing buffer), placement uses CSS pixels.
78    ratio: f64,
79}
80
81/// Device pixels for `css` CSS pixels at `ratio` (MapLibre's drawing buffer
82/// is the canvas size times devicePixelRatio).
83pub fn device_px(css: u32, ratio: f64) -> u32 {
84    ((css as f64 * ratio).round() as u32).max(1)
85}
86
87/// Raster tiles of one source at the zoom MapLibre covers the view with.
88pub struct RasterTiles {
89    pub zoom: u8,
90    pub tiles: Vec<(TileCoord, Vec<u8>)>,
91}
92
93/// Tiles for every tile source a style's layers use, keyed by source id.
94/// Vector tiles carry their world-copy wrap (see [`covering_tiles`]).
95#[derive(Default)]
96pub struct SourceTiles {
97    pub vector: std::collections::HashMap<String, Vec<(TileCoord, i32, Vec<u8>)>>,
98    pub raster: std::collections::HashMap<String, RasterTiles>,
99    /// `raster-dem` sources (hillshade layers).
100    pub dem: std::collections::HashMap<String, super::hillshade::DemTiles>,
101}
102
103impl SourceTiles {
104    /// One vector source (as styles with a single source have).
105    pub fn single_vector(id: &str, tiles: Vec<(TileCoord, i32, Vec<u8>)>) -> Self {
106        let mut s = SourceTiles::default();
107        s.vector.insert(id.to_owned(), tiles);
108        s
109    }
110}
111
112/// Placed vector tiles per source id.
113type Placed = std::collections::HashMap<String, Vec<PlacedTile>>;
114
115/// The placed tiles of `layer`'s source (empty when it has none).
116fn layer_tiles<'a>(placed: &'a Placed, layer: &Json) -> &'a [PlacedTile] {
117    layer["source"].as_str().and_then(|s| placed.get(s)).map_or(&[], |v| v.as_slice())
118}
119
120pub struct RenderOutput {
121    /// Device pixel size of `pixels`.
122    pub width: u32,
123    pub height: u32,
124    pub pixels: Vec<u8>,
125    /// Layer types present in the style that this renderer does not draw yet.
126    pub skipped_layer_types: Vec<String>,
127}
128
129/// Decode `tiles` and place them on a `width x height` view of `bbox` at
130/// MapLibre's scale zoom (centre point minus half the viewport). `width` and
131/// `height` are CSS pixels; tiles are placed in device pixels (`ratio`).
132fn prepare(sources: &SourceTiles, bbox: [f64; 4], width: u32, height: u32, ratio: f64) -> (f64, Placed) {
133    let zoom = scale_zoom(bbox, width);
134    let placed = sources
135        .vector
136        .iter()
137        .map(|(id, tiles)| (id.clone(), place_tiles(tiles, bbox, width, height, ratio, zoom)))
138        .collect();
139    (zoom, placed)
140}
141
142fn place_tiles(
143    tiles: &[(TileCoord, i32, Vec<u8>)],
144    bbox: [f64; 4],
145    width: u32,
146    height: u32,
147    ratio: f64,
148    zoom: f64,
149) -> Vec<PlacedTile> {
150    let world_px = TILE_PX * 2f64.powf(zoom);
151    let cx = ((bbox[0] + bbox[2]) / 2.0 + EARTH_HALF) / EARTH_CIRC * world_px;
152    let cy = (EARTH_HALF - (bbox[1] + bbox[3]) / 2.0) / EARTH_CIRC * world_px;
153    let view_x0 = cx - width as f64 / 2.0;
154    let view_y0 = cy - height as f64 / 2.0;
155    let mut placed = Vec::with_capacity(tiles.len());
156    for (c, wrap, bytes) in tiles {
157        let tile = match mvt::decode(bytes) {
158            Ok(t) => t,
159            Err(e) => {
160                log::warn!("skipping undecodable tile {}/{}/{}: {e}", c.z, c.x, c.y);
161                continue;
162            }
163        };
164        let tile_px = world_px / 2f64.powi(c.z as i32);
165        let ox = (c.x as f64 + (*wrap as f64) * 2f64.powi(c.z as i32)) * tile_px - view_x0;
166        let oy = c.y as f64 * tile_px - view_y0;
167        placed.push(PlacedTile {
168            coord: *c,
169            wrap: *wrap,
170            tile,
171            ox: ox * ratio,
172            oy: oy * ratio,
173            unit_px: tile_px / EXTENT * ratio,
174            clip: Clip { x0: ox * ratio, y0: oy * ratio, x1: (ox + tile_px) * ratio, y1: (oy + tile_px) * ratio },
175            overscaling: 2f64.powi((zoom.floor() as i32 - c.z as i32).max(0)),
176            ratio,
177        });
178    }
179    placed
180}
181
182fn symbol_tiles(placed: &Placed) -> Vec<SymbolTile<'_>> {
183    let mut ids: Vec<&String> = placed.keys().collect();
184    ids.sort();
185    ids.into_iter()
186        .flat_map(|id| placed[id].iter().map(move |p| (id, p)))
187        .map(|(id, p)| SymbolTile {
188            source: id.as_str(),
189            coord: (p.coord.z, p.coord.x, p.coord.y),
190            wrap: p.wrap,
191            tile: &p.tile,
192            ox: p.ox / p.ratio,
193            oy: p.oy / p.ratio,
194            unit_px: p.unit_px / p.ratio,
195            overscaling: p.overscaling,
196        })
197        .collect()
198}
199
200/// Render `tiles` (raw MVT bytes) with `style` over `bbox` at `width × height`.
201/// `assets` holds glyphs and sprite images for symbol layers (may be empty).
202/// Each tile carries its world-copy `wrap` (see [`covering_tiles`]).
203/// `width` and `height` are CSS pixels; the image is `ratio` times larger
204/// (MapLibre's devicePixelRatio: same view and layout, drawn denser).
205#[allow(clippy::too_many_arguments)]
206pub fn render(
207    style: &Json,
208    sources: &SourceTiles,
209    assets: &SymbolAssets,
210    bbox: [f64; 4],
211    width: u32,
212    height: u32,
213    ratio: f64,
214) -> Result<RenderOutput, String> {
215    let (zoom, placed) = prepare(sources, bbox, width, height, ratio);
216    let (dw, dh) = (device_px(width, ratio), device_px(height, ratio));
217    let mut fb = Framebuffer::new(dw as usize, dh as usize);
218    let mut depth3d: Vec<f64> = Vec::new();
219
220    // Symbol placement runs once, top layer first, before drawing.
221    let placement = symbol::place(style, &symbol_tiles(&placed), assets, zoom, width as f64, height as f64);
222
223    let mut skipped: Vec<String> = Vec::new();
224    for (layer_idx, layer) in style["layers"].as_array().map(|v| v.as_slice()).unwrap_or(&[]).iter().enumerate() {
225        let ltype = layer["type"].as_str().unwrap_or("");
226        if layer["layout"]["visibility"] == "none" {
227            continue;
228        }
229        if layer["minzoom"].as_f64().map_or(false, |mz| zoom < mz)
230            || layer["maxzoom"].as_f64().map_or(false, |mz| zoom >= mz)
231        {
232            continue;
233        }
234        match ltype {
235            "background" => draw_background(&mut fb, layer, zoom),
236            "fill" => draw_fill_layer(&mut fb, layer, zoom, layer_tiles(&placed, layer), ratio, assets),
237            "line" => draw_line_layer(&mut fb, layer, zoom, layer_tiles(&placed, layer), ratio, assets),
238            "circle" => draw_circle_layer(&mut fb, layer, zoom, layer_tiles(&placed, layer), ratio),
239            "fill-extrusion" => {
240                let view = ExtrusionView::new(style, bbox, width, height, ratio, zoom);
241                draw_fill_extrusion_layer(&mut fb, layer, zoom, layer_tiles(&placed, layer), &view, assets, &mut depth3d);
242            }
243            "raster" => {
244                if let Some(rt) = layer["source"].as_str().and_then(|s| sources.raster.get(s)) {
245                    draw_raster_layer(&mut fb, layer, zoom, rt, bbox, ratio);
246                }
247            }
248            "hillshade" => {
249                if let Some(dem) = layer["source"].as_str().and_then(|s| sources.dem.get(s)) {
250                    let nearest = super::hillshade::source_nearest(style, layer["source"].as_str().unwrap_or(""), zoom);
251                    super::hillshade::draw_layer(&mut fb, layer, zoom, dem, bbox, width, height, ratio, nearest);
252                }
253            }
254            "symbol" => symbol::draw_layer(
255                &mut fb,
256                layer,
257                layer_idx,
258                &placement,
259                assets,
260                ratio,
261                (width as usize, height as usize),
262            ),
263            other => {
264                if !skipped.iter().any(|s| s == other) {
265                    skipped.push(other.to_owned());
266                }
267            }
268        }
269    }
270
271    Ok(RenderOutput { width: dw, height: dh, pixels: fb.into_straight_rgba(), skipped_layer_types: skipped })
272}
273
274/// Features of `layer`'s source-layer in `pt` that pass the layer filter,
275/// with the scale from the layer's extent to MapLibre's 8192 extent.
276fn features<'a>(layer: &'a Json, pt: &'a PlacedTile, zoom: f64) -> impl Iterator<Item = (&'a Feature, f64)> + 'a {
277    let src = pt.tile.layers.get(mvt::source_layer(layer));
278    let scale = src.map_or(1.0, |l| EXTENT / l.extent as f64);
279    let feats = src.map(|l| l.features.as_slice()).unwrap_or(&[]);
280    feats.iter().filter_map(move |f| {
281        let ctx = Ctx { zoom, feature: Some(f) };
282        match layer.get("filter") {
283            Some(filter) if !eval_filter(filter, &ctx) => None,
284            _ => Some((f, scale)),
285        }
286    })
287}
288
289/// MapLibre's `loadGeometry`: scale to the 8192 extent and round.
290#[inline]
291fn to_extent(p: (f32, f32), scale: f64) -> (f64, f64) {
292    ((p.0 as f64 * scale + 0.5).floor(), (p.1 as f64 * scale + 0.5).floor())
293}
294
295// ── Paint properties ─────────────────────────────────────────────────────────
296
297/// A paint property, hoisted to a constant when it doesn't depend on feature
298/// data (MapLibre passes those as uniforms; data-driven ones as attributes).
299enum Prop<'a> {
300    Const(Val),
301    Data(&'a Json, Kind),
302    Absent,
303}
304
305impl<'a> Prop<'a> {
306    fn new(j: Option<&'a Json>, kind: Kind, zoom: f64) -> Self {
307        match j {
308            None | Some(Json::Null) => Prop::Absent,
309            Some(j) if is_data_driven(j) => Prop::Data(j, kind),
310            Some(j) => Prop::Const(eval_property(j, kind, &Ctx { zoom, feature: None })),
311        }
312    }
313
314    fn get(&self, ctx: &Ctx) -> Option<Val> {
315        match self {
316            Prop::Const(v) => Some(v.clone()),
317            Prop::Data(j, k) => Some(eval_property(j, *k, ctx)),
318            Prop::Absent => None,
319        }
320    }
321
322    fn num(&self, ctx: &Ctx, default: f64) -> f64 {
323        self.get(ctx).and_then(|v| v.as_num()).unwrap_or(default)
324    }
325
326    /// Data-driven colors are packed into 8-bit attributes (`packColor`
327    /// floors each premultiplied channel); uniforms keep full precision.
328    fn color(&self, ctx: &Ctx, default: Color) -> Color {
329        let c = self.get(ctx).and_then(|v| v.as_color()).unwrap_or(default);
330        if matches!(self, Prop::Data(..)) {
331            let q = |v: f32| (v * 255.0).floor().clamp(0.0, 255.0) / 255.0;
332            Color::new(q(c.r), q(c.g), q(c.b), q(c.a))
333        } else {
334            c
335        }
336    }
337
338    fn is_set(&self) -> bool {
339        !matches!(self, Prop::Absent)
340    }
341
342    fn translate(&self, ctx: &Ctx) -> (f64, f64) {
343        match self.get(ctx).and_then(|v| v.as_num_array()) {
344            Some(t) if t.len() == 2 => (t[0], t[1]),
345            _ => (0.0, 0.0),
346        }
347    }
348
349    /// `translate` in device pixels.
350    fn translate_px(&self, ctx: &Ctx, ratio: f64) -> (f64, f64) {
351        let (x, y) = self.translate(ctx);
352        (x * ratio, y * ratio)
353    }
354}
355
356#[inline]
357fn rgba(c: Color, k: f64) -> [f32; 4] {
358    let k = k as f32;
359    [c.r * k, c.g * k, c.b * k, c.a * k]
360}
361
362#[inline]
363fn scaled(c: [f32; 4], a: f64) -> [f32; 4] {
364    let a = a as f32;
365    [c[0] * a, c[1] * a, c[2] * a, c[3] * a]
366}
367
368// ── Background ───────────────────────────────────────────────────────────────
369
370fn draw_background(fb: &mut Framebuffer, layer: &Json, zoom: f64) {
371    let ctx = Ctx { zoom, feature: None };
372    let p = &layer["paint"];
373    let color = Prop::new(p.get("background-color"), Kind::Color, zoom).color(&ctx, Color::BLACK);
374    let opacity = Prop::new(p.get("background-opacity"), Kind::Number, zoom).num(&ctx, 1.0);
375    let c = rgba(color, opacity);
376    if c[3] <= 0.0 {
377        return;
378    }
379    for y in 0..fb.h {
380        for x in 0..fb.w {
381            fb.blend(x, y, c);
382        }
383    }
384}
385
386// ── Fill ─────────────────────────────────────────────────────────────────────
387
388type Rings = Vec<Vec<(f64, f64)>>;
389
390fn polys_px(pt: &PlacedTile, f: &Feature, scale: f64, t: (f64, f64)) -> Vec<Rings> {
391    let Geometry::Polygons(polys) = &f.geometry else { return Vec::new() };
392    polys
393        .iter()
394        .map(|poly| {
395            poly.iter()
396                .map(|ring| {
397                    ring.iter()
398                        .map(|&q| {
399                            let (x, y) = to_extent(q, scale);
400                            (pt.ox + x * pt.unit_px + t.0, pt.oy + y * pt.unit_px + t.1)
401                        })
402                        .collect()
403                })
404                .collect()
405        })
406        .collect()
407}
408
409/// fill_pattern shaders: where a fragment falls in the pattern. The pattern
410/// repeats in tile space with its display size (image px / pixelRatio) in
411/// CSS px at the tile's integer zoom, phased by the tile's world pixel
412/// position (u_pixel_coord), so it lines up across tiles and stretches with
413/// the fractional zoom. Only pattern B shows (no cross-fade).
414struct PatternFrame {
415    ox: f64,
416    oy: f64,
417    unit_px: f64,
418    tile_ratio: f64,
419    world_x: f64,
420    world_y: f64,
421}
422
423impl PatternFrame {
424    fn new(pt: &PlacedTile) -> Self {
425        let n = 2f64.powi(pt.coord.z as i32);
426        let tile_px = TILE_PX * pt.overscaling;
427        PatternFrame {
428            ox: pt.ox,
429            oy: pt.oy,
430            unit_px: pt.unit_px,
431            tile_ratio: tile_px / EXTENT,
432            world_x: tile_px * (pt.coord.x as f64 + pt.wrap as f64 * n),
433            world_y: tile_px * pt.coord.y as f64,
434        }
435    }
436
437    /// Pattern coordinates (in repeats) at device position (x, y), with the
438    /// layer's translate `t` (device px) removed.
439    fn coord(&self, img: &symbol::SpriteImage, x: f64, y: f64, t: (f64, f64)) -> (f64, f64) {
440        let size = (img.w as f64 / img.pixel_ratio, img.h as f64 / img.pixel_ratio);
441        let pos = ((x - t.0 - self.ox) / self.unit_px, (y - t.1 - self.oy) / self.unit_px);
442        (
443            (self.tile_ratio * pos.0 + self.world_x.rem_euclid(size.0)) / size.0,
444            (self.tile_ratio * pos.1 + self.world_y.rem_euclid(size.1)) / size.1,
445        )
446    }
447
448    /// Premultiplied colour (0..1) of `img` at device pixel (x, y).
449    fn sample(&self, img: &symbol::SpriteImage, x: usize, y: usize, t: (f64, f64)) -> [f64; 4] {
450        let v = self.coord(img, x as f64 + 0.5, y as f64 + 0.5, t);
451        let s = img.sample_wrapped(v.0.rem_euclid(1.0) * img.w as f64, v.1.rem_euclid(1.0) * img.h as f64);
452        [s[0] / 255.0, s[1] / 255.0, s[2] / 255.0, s[3] / 255.0]
453    }
454}
455
456fn draw_fill_layer(fb: &mut Framebuffer, layer: &Json, zoom: f64, placed: &[PlacedTile], dpr: f64, assets: &SymbolAssets) {
457    let p = &layer["paint"];
458    let color = Prop::new(p.get("fill-color"), Kind::Color, zoom);
459    let opacity = Prop::new(p.get("fill-opacity"), Kind::Number, zoom);
460    let outline = Prop::new(p.get("fill-outline-color"), Kind::Color, zoom);
461    let translate = Prop::new(p.get("fill-translate"), Kind::Array, zoom);
462    let antialias = p["fill-antialias"].as_bool().unwrap_or(true);
463    let pattern = Prop::new(p.get("fill-pattern"), Kind::Enum, zoom);
464    if pattern.is_set() {
465        return draw_fill_pattern_layer(fb, layer, zoom, placed, dpr, assets, &pattern, &opacity, &outline, &translate, antialias);
466    }
467
468    // draw_fill.ts: opaque layers go through the opaque pass and write depth,
469    // so their default outline (sublayer 0) only lands outside the fill.
470    let opaque = matches!(&color, Prop::Const(v) if v.as_color().map_or(false, |c| c.a == 1.0))
471        && match &opacity {
472            Prop::Absent => true,
473            Prop::Const(v) => v.as_num() == Some(1.0),
474            Prop::Data(..) => false,
475        };
476    let cull_outline = opaque && !outline.is_set();
477    let (w, h) = (fb.w, fb.h);
478    let mut covered = if cull_outline { vec![false; w * h] } else { Vec::new() };
479
480    // Pass 1: interiors for all tiles (drawFillTiles, isOutline = false).
481    for pt in placed {
482        for (f, scale) in features(layer, pt, zoom) {
483            let ctx = Ctx { zoom, feature: Some(f) };
484            let c = rgba(color.color(&ctx, Color::BLACK), opacity.num(&ctx, 1.0));
485            if c[3] <= 0.0 {
486                continue;
487            }
488            for poly in polys_px(pt, f, scale, translate.translate_px(&ctx, dpr)) {
489                raster_polygon(w, h, &poly, &pt.clip, |x, y| {
490                    fb.blend(x, y, c);
491                    if cull_outline {
492                        covered[y * w + x] = true;
493                    }
494                });
495            }
496        }
497    }
498
499    // Pass 2: 1 px antialiasing outlines (gl.LINES + fill_outline shader).
500    if !antialias {
501        return;
502    }
503    for pt in placed {
504        for (f, scale) in features(layer, pt, zoom) {
505            let ctx = Ctx { zoom, feature: Some(f) };
506            let oc = if outline.is_set() { outline.color(&ctx, Color::BLACK) } else { color.color(&ctx, Color::BLACK) };
507            let base = rgba(oc, opacity.num(&ctx, 1.0));
508            if base[3] <= 0.0 {
509                continue;
510            }
511            for poly in polys_px(pt, f, scale, translate.translate_px(&ctx, dpr)) {
512                for ring in &poly {
513                    for seg in ring.windows(2) {
514                        raster_gl_line(w, h, seg[0], seg[1], &pt.clip, |x, y, d| {
515                            if cull_outline && covered[y * w + x] {
516                                return;
517                            }
518                            fb.blend(x, y, scaled(base, 1.0 - smoothstep(0.0, 1.0, d)));
519                        });
520                    }
521                }
522            }
523        }
524    }
525}
526
527/// draw_fill.ts with a pattern: always the translucent pass; interiors with
528/// fill_pattern, then (fill-antialias) outlines with fill_outline_pattern, or
529/// in fill-outline-color when one is set. Features whose image is missing
530/// are not drawn.
531#[allow(clippy::too_many_arguments)]
532fn draw_fill_pattern_layer(
533    fb: &mut Framebuffer,
534    layer: &Json,
535    zoom: f64,
536    placed: &[PlacedTile],
537    dpr: f64,
538    assets: &SymbolAssets,
539    pattern: &Prop,
540    opacity: &Prop,
541    outline: &Prop,
542    translate: &Prop,
543    antialias: bool,
544) {
545    let (w, h) = (fb.w, fb.h);
546    let image_of = |ctx: &Ctx| -> Option<&symbol::SpriteImage> {
547        match pattern.get(ctx)? {
548            Val::Str(name) => assets.sprite.images.get(&name),
549            _ => None,
550        }
551    };
552    for pass_outline in [false, true] {
553        if pass_outline && !antialias {
554            break;
555        }
556        for pt in placed {
557            let frame = PatternFrame::new(pt);
558            for (f, scale) in features(layer, pt, zoom) {
559                let ctx = Ctx { zoom, feature: Some(f) };
560                let Some(img) = image_of(&ctx) else { continue };
561                let op = opacity.num(&ctx, 1.0);
562                if op <= 0.0 {
563                    continue;
564                }
565                let t = translate.translate_px(&ctx, dpr);
566                let polys = polys_px(pt, f, scale, t);
567                if !pass_outline {
568                    for poly in &polys {
569                        raster_polygon(w, h, poly, &pt.clip, |x, y| {
570                            let c = frame.sample(img, x, y, t);
571                            fb.blend(x, y, [(c[0] * op) as f32, (c[1] * op) as f32, (c[2] * op) as f32, (c[3] * op) as f32]);
572                        });
573                    }
574                    continue;
575                }
576                let plain = outline.is_set().then(|| rgba(outline.color(&ctx, Color::BLACK), op));
577                for poly in &polys {
578                    for ring in poly {
579                        for seg in ring.windows(2) {
580                            raster_gl_line(w, h, seg[0], seg[1], &pt.clip, |x, y, d| {
581                                let k = 1.0 - smoothstep(0.0, 1.0, d);
582                                let c = match plain {
583                                    Some(c) => scaled(c, k),
584                                    None => {
585                                        let s = frame.sample(img, x, y, t);
586                                        let m = op * k;
587                                        [(s[0] * m) as f32, (s[1] * m) as f32, (s[2] * m) as f32, (s[3] * m) as f32]
588                                    }
589                                };
590                                fb.blend(x, y, c);
591                            });
592                        }
593                    }
594                }
595            }
596        }
597    }
598}
599
600// ── Line ─────────────────────────────────────────────────────────────────────
601
602fn draw_line_layer(fb: &mut Framebuffer, layer: &Json, zoom: f64, placed: &[PlacedTile], dpr: f64, assets: &SymbolAssets) {
603    let p = &layer["paint"];
604    // line-pattern replaces color and dashes (the linePattern program).
605    let pattern = Prop::new(p.get("line-pattern"), Kind::Enum, zoom);
606    let l = &layer["layout"];
607    let color = Prop::new(p.get("line-color"), Kind::Color, zoom);
608    let opacity = Prop::new(p.get("line-opacity"), Kind::Number, zoom);
609    let width = Prop::new(p.get("line-width"), Kind::Number, zoom);
610    let floor_width = Prop::new(p.get("line-width"), Kind::Number, zoom.floor());
611    let gap = Prop::new(p.get("line-gap-width"), Kind::Number, zoom);
612    let offset = Prop::new(p.get("line-offset"), Kind::Number, zoom);
613    let blur = Prop::new(p.get("line-blur"), Kind::Number, zoom);
614    let translate = Prop::new(p.get("line-translate"), Kind::Array, zoom);
615    // line-dasharray is not interpolatable: legacy functions default to
616    // "interval" (Kind::Enum), unlike interpolatable arrays such as offsets.
617    let dasharray = Prop::new(p.get("line-dasharray"), Kind::Enum, zoom);
618    let tz = zoom.floor();
619    let cap = match super::expr::layout_enum(l, "line-cap", tz).as_deref() {
620        Some("round") => Cap::Round,
621        Some("square") => Cap::Square,
622        _ => Cap::Butt,
623    };
624    let join = match super::expr::layout_enum(l, "line-join", tz).as_deref() {
625        Some("round") => Join::Round,
626        Some("bevel") => Join::Bevel,
627        _ => Join::Miter,
628    };
629    let miter_limit = l["line-miter-limit"].as_f64().unwrap_or(2.0);
630    let round_limit = l["line-round-limit"].as_f64().unwrap_or(1.05);
631
632    // line_sdf uniforms (lineSDFUniformValues): only pattern B shows
633    // (u_mix = 1 with no fade); gamma uses the smaller cross-fade width.
634    let dash = match &dasharray {
635        Prop::Const(v) => v
636            .as_num_array()
637            .filter(|d| d.len() >= 2 && d.iter().sum::<f64>() > 0.0)
638            .map(|d| Dash::new(&d, cap == Cap::Round)),
639        _ => None,
640    };
641    let from_scale = if zoom > zoom.floor() { 2.0 } else { 0.5 };
642
643    let (w, h) = (fb.w, fb.h);
644    for pt in placed {
645        for (f, scale) in features(layer, pt, zoom) {
646            let ctx = Ctx { zoom, feature: Some(f) };
647            let fctx = Ctx { zoom: zoom.floor(), feature: Some(f) };
648            let (lines, is_polygon): (Vec<&Vec<(f32, f32)>>, bool) = match &f.geometry {
649                Geometry::Lines(ls) => (ls.iter().collect(), false),
650                Geometry::Polygons(ps) => (ps.iter().flatten().collect(), true),
651                Geometry::Points(_) => continue,
652            };
653            let image = if pattern.is_set() {
654                match pattern.get(&ctx) {
655                    Some(Val::Str(name)) => match assets.sprite.images.get(&name) {
656                        Some(img) => Some(img),
657                        None => continue,
658                    },
659                    _ => continue,
660                }
661            } else {
662                None
663            };
664            let op = opacity.num(&ctx, 1.0);
665            let c = if image.is_some() { [op as f32; 4] } else { rgba(color.color(&ctx, Color::BLACK), op) };
666            if c[3] <= 0.0 {
667                continue;
668            }
669            // Widths in device pixels (CSS width * devicePixelRatio); the
670            // antialiasing ramp stays one device pixel wide.
671            let lw_css = width.num(&ctx, 1.0);
672            let lw = lw_css * dpr;
673            // line.vertex.glsl: gapwidth / 2, halfwidth = width / 2, offset negated.
674            let gapw = gap.num(&ctx, 0.0) * dpr / 2.0;
675            let halfwidth = lw / 2.0;
676            let line_offset = -offset.num(&ctx, 0.0) * dpr;
677            let aa = 0.5; // ANTIALIASING = 1 / devicePixelRatio / 2 CSS px
678            let inset = gapw + if gapw > 0.0 { aa } else { 0.0 };
679            let outset =
680                gapw + halfwidth * if gapw > 0.0 { 2.0 } else { 1.0 } + if halfwidth == 0.0 { 0.0 } else { aa };
681            if outset <= 0.0 {
682                continue;
683            }
684            let blur2 = blur.num(&ctx, 0.0) * dpr + 1.0;
685            // Dash pattern scale is in CSS pixels (ratio-independent).
686            let floorwidth = floor_width.num(&fctx, lw_css);
687            let (tx, ty) = translate.translate_px(&ctx, dpr);
688
689            // line_pattern.fragment.glsl (pattern B, toScale 1): one repeat
690            // spans display_w / tileZoomRatio * floorwidth / display_h tile
691            // units along the line and the full outset across it, mapped onto
692            // the image plus its 1 px atlas padding.
693            let pattern_params = image.map(|img| {
694                let tile_ratio = TILE_PX * pt.overscaling / EXTENT;
695                let (dw, dh) = (img.w as f64 / img.pixel_ratio, img.h as f64 / img.pixel_ratio);
696                (img, tile_ratio * dh / (dw * floorwidth))
697            });
698            let dash_params = dash.as_ref().filter(|_| image.is_none()).map(|d| {
699                let width_b = d.width;
700                let width_a = d.width * from_scale;
701                let sdfgamma = ATLAS_W as f64 / (width_a.min(width_b) * 256.0 * dpr) / 2.0;
702                // lineSDFUniformValues: tileRatio = 1 / pixelsToTileUnits(tile, 1,
703                // tileZoom); an overscaled tile is 512 * overscaling px wide.
704                let tile_ratio = TILE_PX * pt.overscaling / EXTENT;
705                (d, tile_ratio / width_b / floorwidth, sdfgamma / floorwidth)
706            });
707
708            let mut b = LineBuilder::new(pt.overscaling);
709            for line in &lines {
710                let pts: Vec<(f64, f64)> = line.iter().map(|&q| to_extent(q, scale)).collect();
711                b.add_line(&pts, is_polygon, join, cap, miter_limit, round_limit);
712            }
713
714            // line.vertex.glsl, per vertex.
715            let verts: Vec<Vert<3>> = b
716                .verts
717                .iter()
718                .map(|v| {
719                    let ny = if v.up { 1.0 } else { -1.0 };
720                    let u = 0.5 * v.dir;
721                    let t = 1.0 - u.abs();
722                    let (ox, oy) = (line_offset * v.ex * ny, line_offset * v.ey * ny);
723                    let offset2 = (ox * t - oy * u, ox * u + oy * t);
724                    let dist = (outset * v.ex, outset * v.ey);
725                    Vert {
726                        x: pt.ox + v.x * pt.unit_px + offset2.0 + dist.0 + tx,
727                        y: pt.oy + v.y * pt.unit_px + offset2.1 + dist.1 + ty,
728                        v: [if v.round { 1.0 } else { 0.0 }, ny, v.linesofar],
729                    }
730                })
731                .collect();
732
733            for tri in &b.tris {
734                let t = [verts[tri[0] as usize], verts[tri[1] as usize], verts[tri[2] as usize]];
735                raster_triangle(w, h, t, &pt.clip, |x, y, var| {
736                    // line.fragment.glsl / line_sdf.fragment.glsl
737                    let d = (var[0] * var[0] + var[1] * var[1]).sqrt() * outset;
738                    let mut alpha = ((d - (inset - blur2)).min(outset - d) / blur2).clamp(0.0, 1.0);
739                    if let Some((dash, sx, g)) = dash_params {
740                        let sdf = dash.sample(var[2] * sx, dash.n as f64 * (1.0 - var[1]));
741                        alpha *= smoothstep(0.5 - g, 0.5 + g, sdf);
742                    }
743                    if alpha > 0.0 {
744                        if let Some((img, k)) = pattern_params {
745                            let xb = (var[2] * k).rem_euclid(1.0);
746                            let yb = 0.5 * var[1] + 0.5;
747                            let s = img.sample_atlas_pattern((img.w as f64 + 2.0) * xb, (img.h as f64 + 2.0) * yb);
748                            let m = alpha * op / 255.0;
749                            fb.blend(x, y, [(s[0] * m) as f32, (s[1] * m) as f32, (s[2] * m) as f32, (s[3] * m) as f32]);
750                        } else {
751                            fb.blend(x, y, scaled(c, alpha));
752                        }
753                    }
754                });
755            }
756        }
757    }
758}
759
760// ── Fill extrusion ───────────────────────────────────────────────────────────
761
762/// MapLibre's camera for 3D layers at pitch 0: a perspective camera
763/// cameraToCenterDistance = 0.5 / tan(fov / 2) * height (fov 36.87°, so 1.5
764/// heights) above the view centre. A point at height Z (px) projects to
765/// centre + offset * d / (d - Z). Heights convert from metres with
766/// mercatorZfromAltitude at the centre latitude (Earth radius 6371008.8 m).
767struct ExtrusionView {
768    /// Projection centre in device px.
769    cx: f64,
770    cy: f64,
771    /// Camera distance in CSS px.
772    d: f64,
773    /// CSS px per metre of height.
774    px_per_m: f64,
775    /// Light (style "light", viewport anchor, pitch/bearing 0).
776    light_pos: [f64; 3],
777    light_color: [f64; 3],
778    light_intensity: f64,
779}
780
781impl ExtrusionView {
782    fn new(style: &Json, bbox: [f64; 4], width: u32, height: u32, ratio: f64, zoom: f64) -> Self {
783        let world = TILE_PX * 2f64.powf(zoom);
784        let lat = (2.0 * (((bbox[1] + bbox[3]) / 2.0) / (EARTH_CIRC / (2.0 * std::f64::consts::PI))).exp().atan()
785            - std::f64::consts::FRAC_PI_2)
786            .to_degrees();
787        let maplibre_circ = 2.0 * std::f64::consts::PI * 6_371_008.8;
788        let fov: f64 = 0.643_501_108_793_284_4;
789        let light = &style["light"];
790        let ctx = Ctx { zoom, feature: None };
791        let pos = light.get("position").map(|j| eval_property(j, Kind::Array, &ctx)).and_then(|v| v.as_num_array());
792        let pos = pos.filter(|p| p.len() == 3).unwrap_or_else(|| vec![1.15, 210.0, 30.0]);
793        // sphericalToCartesian
794        let az = (pos[1] + 90.0).to_radians();
795        let polar = pos[2].to_radians();
796        let light_pos = [pos[0] * az.cos() * polar.sin(), pos[0] * az.sin() * polar.sin(), pos[0] * polar.cos()];
797        let color = light
798            .get("color")
799            .map(|j| eval_property(j, Kind::Color, &ctx))
800            .and_then(|v| v.as_color())
801            .unwrap_or(Color::new(1.0, 1.0, 1.0, 1.0));
802        let intensity = light.get("intensity").map(|j| eval_property(j, Kind::Number, &ctx)).and_then(|v| v.as_num()).unwrap_or(0.5);
803        ExtrusionView {
804            cx: width as f64 * ratio / 2.0,
805            cy: height as f64 * ratio / 2.0,
806            d: 0.5 / (fov / 2.0).tan() * height as f64,
807            px_per_m: world / (maplibre_circ * lat.to_radians().cos()),
808            light_pos,
809            light_color: [color.r as f64, color.g as f64, color.b as f64],
810            light_intensity: intensity,
811        }
812    }
813
814    /// Screen position (device px) and depth key 1 / (d - Z) of a map point
815    /// (device px) at `h` metres.
816    fn project(&self, p: (f64, f64), h: f64) -> (f64, f64, f64) {
817        let z = h * self.px_per_m;
818        let s = self.d / (self.d - z);
819        (self.cx + (p.0 - self.cx) * s, self.cy + (p.1 - self.cy) * s, 1.0 / (self.d - z))
820    }
821
822    /// fill_extrusion.vertex.glsl lighting for one vertex: premultiplied
823    /// colour (before opacity).
824    #[allow(clippy::too_many_arguments)]
825    fn shade(&self, color: [f64; 4], normal: (f64, f64, f64), t: f64, base: f64, height: f64, vertical_gradient: bool) -> [f64; 3] {
826        let i = self.light_intensity;
827        let colorvalue = color[0] * 0.2126 + color[1] * 0.7152 + color[2] * 0.0722;
828        let c = [color[0] + 0.03, color[1] + 0.03, color[2] + 0.03];
829        let lp = self.light_pos;
830        let mut directional = (normal.0 * lp[0] + normal.1 * lp[1] + normal.2 * lp[2]).clamp(0.0, 1.0);
831        let hi = (1.0 - colorvalue + i).max(1.0);
832        directional = (1.0 - i) * (1.0 - directional) + hi * directional;
833        if normal.1 != 0.0 {
834            let vg = if vertical_gradient { 1.0 } else { 0.0 };
835            let lo = 0.7 * i + 0.98 * (1.0 - i);
836            directional *= (1.0 - vg) + vg * ((t + base) * (height / 150.0).sqrt()).clamp(lo, 1.0);
837        }
838        let mut out = [0.0; 3];
839        for k in 0..3 {
840            let lc = self.light_color[k];
841            out[k] = (c[k] * directional * lc).clamp(0.3 * (1.0 - lc), 1.0);
842        }
843        out
844    }
845}
846
847impl ExtrusionView {
848    /// fill_extrusion_pattern.vertex.glsl lighting for one vertex (the
849    /// texture's multiplier, before opacity).
850    fn shade_pattern(&self, normal: (f64, f64, f64), t: f64, base: f64, height: f64, vertical_gradient: bool) -> [f64; 3] {
851        let i = self.light_intensity;
852        let lp = self.light_pos;
853        let mut directional = (normal.0 * lp[0] + normal.1 * lp[1] + normal.2 * lp[2]).clamp(0.0, 1.0);
854        let hi = (0.5 + i).max(1.0);
855        directional = (1.0 - i) * (1.0 - directional) + hi * directional;
856        if normal.1 != 0.0 {
857            let vg = if vertical_gradient { 1.0 } else { 0.0 };
858            let lo = 0.7 * i + 0.98 * (1.0 - i);
859            directional *= (1.0 - vg) + vg * ((t + base) * (height / 150.0).sqrt()).clamp(lo, 1.0);
860        }
861        let mut out = [0.0; 3];
862        for k in 0..3 {
863            let lc = self.light_color[k];
864            out[k] = (directional * lc).clamp(0.3 * (1.0 - lc), 1.0);
865        }
866        out
867    }
868
869    /// Map position (device px) under screen point (x, y) on a plane `h`
870    /// metres up.
871    fn unproject(&self, x: f64, y: f64, h: f64) -> (f64, f64) {
872        let s = self.d / (self.d - h * self.px_per_m);
873        (self.cx + (x - self.cx) / s, self.cy + (y - self.cy) / s)
874    }
875}
876
877/// FillExtrusionBucket's isEntirelyOutside: every point beyond one tile edge.
878fn ring_entirely_outside(ring: &[(f64, f64)]) -> bool {
879    let e = EXTENT;
880    ring.iter().all(|p| p.0 < 0.0) || ring.iter().all(|p| p.0 > e) || ring.iter().all(|p| p.1 < 0.0) || ring.iter().all(|p| p.1 > e)
881}
882
883/// fill-extrusion at pitch 0 (draw_fill_extrusion.ts): per polygon, side
884/// walls (skipping edges along the tile boundary) then the top face, with
885/// per-vertex lighting interpolated perspective-correctly and a depth test.
886/// Translucent layers draw only the closest surface per pixel (a depth
887/// pre-pass, then colour where the depth matches, once per pixel).
888#[allow(clippy::too_many_arguments)]
889fn draw_fill_extrusion_layer(
890    fb: &mut Framebuffer,
891    layer: &Json,
892    zoom: f64,
893    placed: &[PlacedTile],
894    view: &ExtrusionView,
895    assets: &SymbolAssets,
896    depth: &mut Vec<f64>,
897) {
898    let p = &layer["paint"];
899    let color = Prop::new(p.get("fill-extrusion-color"), Kind::Color, zoom);
900    let height = Prop::new(p.get("fill-extrusion-height"), Kind::Number, zoom);
901    let base = Prop::new(p.get("fill-extrusion-base"), Kind::Number, zoom);
902    let opacity = Prop::new(p.get("fill-extrusion-opacity"), Kind::Number, zoom).num(&Ctx { zoom, feature: None }, 1.0);
903    let vertical_gradient = p["fill-extrusion-vertical-gradient"].as_bool().unwrap_or(true);
904    // fill-extrusion-pattern (the fillExtrusionPattern program): the image
905    // replaces the colour, lit without it; always drawn in two passes.
906    let pattern = Prop::new(p.get("fill-extrusion-pattern"), Kind::Enum, zoom);
907    let patterned = pattern.is_set();
908    if opacity <= 0.0 {
909        return;
910    }
911    let (w, h) = (fb.w, fb.h);
912    let full = Clip { x0: 0.0, y0: 0.0, x1: w as f64, y1: h as f64 };
913
914    // Triangles in screen space: vertices (x, y, [r/w, g/w, b/w, u/w, v/w,
915    // 1/w]), (u, v) the pattern position in repeats.
916    let mut tris: Vec<[Vert<6>; 3]> = Vec::new();
917    // Top faces: one planar polygon each (constant depth, colour), with the
918    // height for the pattern's inverse projection.
919    let mut tops: Vec<(Rings, f64, [f64; 3], f64)> = Vec::new();
920    // Patterned pieces: the image and the tile's pattern frame.
921    type Pat<'a> = Option<(Option<&'a symbol::SpriteImage>, usize)>;
922    let mut frames: Vec<PatternFrame> = Vec::new();
923    // Draw order: MapLibre's bucket order (per polygon: walls, then top).
924    enum Piece<'a> {
925        Tris(usize, usize, Pat<'a>),
926        Top(usize, Pat<'a>),
927    }
928    let mut order: Vec<Piece> = Vec::new();
929    for pt in placed {
930        let frame = PatternFrame::new(pt);
931        // get_pattern_pos for a wall: (edgedistance, elevation *
932        // u_height_factor) in tile units, u_height_factor = -2^z / tileSize / 8
933        // (z overscaled, tileSize 512 times the overscaling).
934        let height_factor = -(2f64.powi(pt.coord.z as i32)) / TILE_PX / 8.0;
935        let world = (frame.world_x, frame.world_y);
936        let tile_ratio = frame.tile_ratio;
937        frames.push(frame);
938        let fi = frames.len() - 1;
939        for (f, scale) in features(layer, pt, zoom) {
940            let Geometry::Polygons(polys) = &f.geometry else { continue };
941            let ctx = Ctx { zoom, feature: Some(f) };
942            // A feature whose pattern image is missing gets no pattern
943            // attributes: it draws nothing but still takes depth.
944            let img = match pattern.get(&ctx) {
945                Some(Val::Str(name)) if patterned => assets.sprite.images.get(&name),
946                _ => None,
947            };
948            let pat: Pat = patterned.then_some((img, fi));
949            let size = img.map_or((1.0, 1.0), |i| (i.w as f64 / i.pixel_ratio, i.h as f64 / i.pixel_ratio));
950            let pattern_pos = |pos: (f64, f64)| {
951                (
952                    (tile_ratio * pos.0 + world.0.rem_euclid(size.0)) / size.0,
953                    (tile_ratio * pos.1 + world.1.rem_euclid(size.1)) / size.1,
954                )
955            };
956            let c = color.color(&ctx, Color::BLACK);
957            let col = [c.r as f64, c.g as f64, c.b as f64, c.a as f64];
958            let hgt = height.num(&ctx, 0.0).max(0.0);
959            let bse = base.num(&ctx, 0.0).max(0.0);
960            for poly in polys {
961                let rings: Vec<Vec<(f64, f64)>> = poly.iter().map(|r| r.iter().map(|&q| to_extent(q, scale)).collect()).collect();
962                if rings.first().map_or(true, |r| ring_entirely_outside(r)) {
963                    continue;
964                }
965                let to_px = |q: (f64, f64)| (pt.ox + q.0 * pt.unit_px, pt.oy + q.1 * pt.unit_px);
966                let first = tris.len();
967                for ring in &rings {
968                    if ring_entirely_outside(ring) {
969                        continue;
970                    }
971                    let mut edge_distance = 0.0f64;
972                    for e in ring.windows(2) {
973                        // FillExtrusionBucket: p1 is the current point, p2 the previous.
974                        let (p1, p2) = (e[1], e[0]);
975                        if (p1.0 == p2.0 && (p1.0 < 0.0 || p1.0 > EXTENT)) || (p1.1 == p2.1 && (p1.1 < 0.0 || p1.1 > EXTENT)) {
976                            continue; // isBoundaryEdge
977                        }
978                        let (dx, dy) = (p1.0 - p2.0, p1.1 - p2.1);
979                        let len = (dx * dx + dy * dy).sqrt();
980                        if edge_distance + len > 32768.0 {
981                            edge_distance = 0.0;
982                        }
983                        // a_normal_ed is Int16: the distance is truncated (and
984                        // 32768 wraps).
985                        let ed1 = edge_distance.trunc();
986                        edge_distance += len;
987                        let ed2 = (edge_distance.trunc() as i64 as i16) as f64;
988                        if len == 0.0 {
989                            continue;
990                        }
991                        // perp of (p1 - p2), unit; encoded y is exact, x carries the top flag.
992                        let n = (-dy / len, dx / len, 0.0);
993                        let ny = (n.1 * 16384.0).trunc() / 16384.0;
994                        let vert = |q: (f64, f64), t: f64, ed: f64| -> Vert<6> {
995                            let elevation = if t > 0.0 { hgt } else { bse };
996                            let (x, y, iw) = view.project(to_px(q), elevation);
997                            let s = if patterned {
998                                view.shade_pattern((n.0, ny, n.2), t, bse, hgt, vertical_gradient)
999                            } else {
1000                                view.shade(col, (n.0, ny, n.2), t, bse, hgt, vertical_gradient)
1001                            };
1002                            let (u, v) = pattern_pos((ed, elevation * height_factor));
1003                            Vert { x, y, v: [s[0] * iw, s[1] * iw, s[2] * iw, u * iw, v * iw, iw] }
1004                        };
1005                        let v = [vert(p1, 0.0, ed1), vert(p1, 1.0, ed1), vert(p2, 0.0, ed2), vert(p2, 1.0, ed2)];
1006                        tris.push([v[0], v[2], v[1]]);
1007                        tris.push([v[1], v[2], v[3]]);
1008                    }
1009                }
1010                order.push(Piece::Tris(first, tris.len(), pat));
1011                let (_, _, iw) = view.project((0.0, 0.0), hgt);
1012                let top: Rings = rings
1013                    .iter()
1014                    .map(|r| r.iter().map(|&q| { let (x, y, _) = view.project(to_px(q), hgt); (x, y) }).collect())
1015                    .collect();
1016                let light = if patterned {
1017                    view.shade_pattern((0.0, 0.0, 1.0), 1.0, bse, hgt, vertical_gradient)
1018                } else {
1019                    view.shade(col, (0.0, 0.0, 1.0), 1.0, bse, hgt, vertical_gradient)
1020                };
1021                tops.push((top, iw, light, hgt));
1022                order.push(Piece::Top(tops.len() - 1, pat));
1023            }
1024        }
1025    }
1026
1027    // One depth buffer for all 3D layers (cleared once per frame).
1028    if depth.len() != w * h {
1029        *depth = vec![0.0f64; w * h];
1030    }
1031    let mut drawn = vec![false; w * h];
1032    let translucent = opacity < 1.0 || patterned;
1033    let passes: &[bool] = if translucent { &[true, false] } else { &[false] };
1034    for &depth_only in passes {
1035        for piece in &order {
1036            let mut frag = |x: usize, y: usize, iw: f64, rgba: [f64; 4], fb: &mut Framebuffer| {
1037                let k = y * w + x;
1038                if depth_only {
1039                    if iw > depth[k] {
1040                        depth[k] = iw;
1041                    }
1042                    return;
1043                }
1044                if translucent {
1045                    if iw < depth[k] || drawn[k] {
1046                        return;
1047                    }
1048                    drawn[k] = true;
1049                } else {
1050                    if iw < depth[k] {
1051                        return;
1052                    }
1053                    depth[k] = iw;
1054                }
1055                let a = opacity;
1056                fb.blend(x, y, [(rgba[0] * a) as f32, (rgba[1] * a) as f32, (rgba[2] * a) as f32, (rgba[3] * a) as f32]);
1057            };
1058            match piece {
1059                Piece::Tris(a, b, pat) => {
1060                    for t in &tris[*a..*b] {
1061                        // CullFaceMode.backCCW: GL's clip space is y-up, so a
1062                        // front (CCW) face winds the other way on screen.
1063                        let cross = (t[1].x - t[0].x) * (t[2].y - t[0].y) - (t[1].y - t[0].y) * (t[2].x - t[0].x);
1064                        if cross > 0.0 {
1065                            continue;
1066                        }
1067                        raster_triangle(w, h, *t, &full, |x, y, v| {
1068                            let iw = v[5];
1069                            if iw > 0.0 {
1070                                let c = if depth_only {
1071                                    [0.0; 4]
1072                                } else {
1073                                    extrusion_texel(*pat, v[3] / iw, v[4] / iw, [v[0] / iw, v[1] / iw, v[2] / iw])
1074                                };
1075                                frag(x, y, iw, c, fb);
1076                            }
1077                        });
1078                    }
1079                }
1080                Piece::Top(i, pat) => {
1081                    let (rings, iw, rgb, hgt) = &tops[*i];
1082                    raster_polygon(w, h, rings, &full, |x, y| {
1083                        let c = match pat {
1084                            Some((Some(img), fi)) if !depth_only => {
1085                                // get_pattern_pos for a top: a_pos (no translate).
1086                                let m = view.unproject(x as f64 + 0.5, y as f64 + 0.5, *hgt);
1087                                let (u, v) = frames[*fi].coord(img, m.0, m.1, (0.0, 0.0));
1088                                extrusion_texel(*pat, u, v, *rgb)
1089                            }
1090                            _ if depth_only => [0.0; 4],
1091                            _ => extrusion_texel(*pat, 0.0, 0.0, *rgb),
1092                        };
1093                        frag(x, y, *iw, c, fb)
1094                    });
1095                }
1096            }
1097        }
1098    }
1099}
1100
1101/// fill_extrusion(_pattern).fragment.glsl before opacity: the pattern texel
1102/// at (u, v) repeats times the lighting, or the lit colour.
1103fn extrusion_texel(pat: Option<(Option<&symbol::SpriteImage>, usize)>, u: f64, v: f64, rgb: [f64; 3]) -> [f64; 4] {
1104    match pat {
1105        Some((None, _)) => [0.0; 4],
1106        Some((Some(img), _)) => {
1107            let s = img.sample_wrapped(u.rem_euclid(1.0) * img.w as f64, v.rem_euclid(1.0) * img.h as f64);
1108            [s[0] / 255.0 * rgb[0], s[1] / 255.0 * rgb[1], s[2] / 255.0 * rgb[2], s[3] / 255.0]
1109        }
1110        None => [rgb[0], rgb[1], rgb[2], 1.0],
1111    }
1112}
1113
1114/// fill-extrusion as SVG: every visible face (walls facing the camera, tops)
1115/// as a polygon, sorted far to near (painter's algorithm), walls shaded with
1116/// their mean vertex colour. The layer opacity goes on the group, so only
1117/// the nearest surface shows through it, as MapLibre draws translucent
1118/// extrusions.
1119fn svg_fill_extrusion(out: &mut String, layer: &Json, zoom: f64, placed: &[PlacedTile], view: &ExtrusionView) {
1120    use std::fmt::Write as _;
1121    let p = &layer["paint"];
1122    let color = Prop::new(p.get("fill-extrusion-color"), Kind::Color, zoom);
1123    let height = Prop::new(p.get("fill-extrusion-height"), Kind::Number, zoom);
1124    let base = Prop::new(p.get("fill-extrusion-base"), Kind::Number, zoom);
1125    let opacity = Prop::new(p.get("fill-extrusion-opacity"), Kind::Number, zoom).num(&Ctx { zoom, feature: None }, 1.0);
1126    let vertical_gradient = p["fill-extrusion-vertical-gradient"].as_bool().unwrap_or(true);
1127    if opacity <= 0.0 {
1128        return;
1129    }
1130    // (depth key, path data, colour)
1131    let mut faces: Vec<(f64, String, [f64; 3])> = Vec::new();
1132    for pt in placed {
1133        for (f, scale) in features(layer, pt, zoom) {
1134            let Geometry::Polygons(polys) = &f.geometry else { continue };
1135            let ctx = Ctx { zoom, feature: Some(f) };
1136            let c = color.color(&ctx, Color::BLACK);
1137            let col = [c.r as f64, c.g as f64, c.b as f64, c.a as f64];
1138            let hgt = height.num(&ctx, 0.0).max(0.0);
1139            let bse = base.num(&ctx, 0.0).max(0.0);
1140            for poly in polys {
1141                let rings: Vec<Vec<(f64, f64)>> = poly.iter().map(|r| r.iter().map(|&q| to_extent(q, scale)).collect()).collect();
1142                if rings.first().map_or(true, |r| ring_entirely_outside(r)) {
1143                    continue;
1144                }
1145                let to_px = |q: (f64, f64)| (pt.ox + q.0 * pt.unit_px, pt.oy + q.1 * pt.unit_px);
1146                for ring in &rings {
1147                    if ring_entirely_outside(ring) {
1148                        continue;
1149                    }
1150                    for e in ring.windows(2) {
1151                        let (p1, p2) = (e[1], e[0]);
1152                        if (p1.0 == p2.0 && (p1.0 < 0.0 || p1.0 > EXTENT)) || (p1.1 == p2.1 && (p1.1 < 0.0 || p1.1 > EXTENT)) {
1153                            continue;
1154                        }
1155                        let (dx, dy) = (p1.0 - p2.0, p1.1 - p2.1);
1156                        let len = (dx * dx + dy * dy).sqrt();
1157                        if len == 0.0 {
1158                            continue;
1159                        }
1160                        let n = (-dy / len, ((dx / len) * 16384.0).trunc() / 16384.0, 0.0);
1161                        let a = view.project(to_px(p1), bse);
1162                        let b = view.project(to_px(p1), hgt);
1163                        let c2 = view.project(to_px(p2), bse);
1164                        let d2 = view.project(to_px(p2), hgt);
1165                        // Back-face culling, as for the PNG (triangle a, c2, b).
1166                        let cross = (c2.0 - a.0) * (b.1 - a.1) - (c2.1 - a.1) * (b.0 - a.0);
1167                        if cross > 0.0 {
1168                            continue;
1169                        }
1170                        let s0 = view.shade(col, n, 0.0, bse, hgt, vertical_gradient);
1171                        let s1 = view.shade(col, n, 1.0, bse, hgt, vertical_gradient);
1172                        let rgb = [(s0[0] + s1[0]) / 2.0, (s0[1] + s1[1]) / 2.0, (s0[2] + s1[2]) / 2.0];
1173                        let quad = vec![(a.0, a.1), (c2.0, c2.1), (d2.0, d2.1), (b.0, b.1)];
1174                        faces.push(((a.2 + b.2 + c2.2 + d2.2) / 4.0, svg::path_data(&[quad], true), rgb));
1175                    }
1176                }
1177                let top: Vec<Vec<(f64, f64)>> = rings
1178                    .iter()
1179                    .map(|r| r.iter().map(|&q| { let (x, y, _) = view.project(to_px(q), hgt); (x, y) }).collect())
1180                    .collect();
1181                let (_, _, iw) = view.project((0.0, 0.0), hgt);
1182                faces.push((iw + 1e-12, svg::path_data(&top, true), view.shade(col, (0.0, 0.0, 1.0), 1.0, bse, hgt, vertical_gradient)));
1183            }
1184        }
1185    }
1186    faces.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
1187    let _ = write!(out, r#"<g opacity="{}" fill-rule="evenodd">"#, svg::alpha(opacity.min(1.0)));
1188    for (_, d, rgb) in faces {
1189        let hex = format!(
1190            "#{:02x}{:02x}{:02x}",
1191            (rgb[0].clamp(0.0, 1.0) * 255.0).round() as u8,
1192            (rgb[1].clamp(0.0, 1.0) * 255.0).round() as u8,
1193            (rgb[2].clamp(0.0, 1.0) * 255.0).round() as u8
1194        );
1195        let _ = write!(out, r#"<path d="{d}" fill="{hex}"/>"#);
1196    }
1197    out.push_str("</g>");
1198}
1199
1200// ── Raster ───────────────────────────────────────────────────────────────────
1201
1202/// raster.fragment.glsl uniforms: saturation, contrast and hue-rotate factors.
1203fn raster_factors(saturation: f64, contrast: f64, hue_deg: f64) -> (f64, f64, [f64; 3]) {
1204    let sat = if saturation > 0.0 { 1.0 - 1.0 / (1.001 - saturation) } else { -saturation };
1205    let con = if contrast > 0.0 { 1.0 / (1.0 - contrast) } else { 1.0 + contrast };
1206    let a = hue_deg.to_radians();
1207    let (s, c) = (a.sin(), a.cos());
1208    let spin = [(2.0 * c + 1.0) / 3.0, (-(3f64.sqrt()) * s - c + 1.0) / 3.0, (3f64.sqrt() * s - c + 1.0) / 3.0];
1209    (sat, con, spin)
1210}
1211
1212/// The view's raster tiles composited at device size (tiles snapped to the
1213/// CSS pixel grid, linearly resampled, as for raster-only styles), as
1214/// straight-alpha RGBA. None when nothing could be decoded.
1215fn raster_image(rt: &RasterTiles, bbox: [f64; 4], w: usize, h: usize, ratio: f64) -> Option<image::RgbaImage> {
1216    crate::renderer::composite_raster_tiles(&rt.tiles, bbox, rt.zoom, w as u32, h as u32, true, ratio)
1217        .map_err(|e| log::warn!("raster layer: {e}"))
1218        .ok()
1219}
1220
1221/// A raster layer inside a vector style: raster.fragment.glsl per pixel
1222/// (opacity, hue rotation, saturation, contrast, brightness range), blended
1223/// premultiplied like every MapLibre layer.
1224fn draw_raster_layer(fb: &mut Framebuffer, layer: &Json, zoom: f64, rt: &RasterTiles, bbox: [f64; 4], ratio: f64) {
1225    let ctx = Ctx { zoom, feature: None };
1226    let p = &layer["paint"];
1227    let num = |k: &str, d: f64| Prop::new(p.get(k), Kind::Number, zoom).num(&ctx, d);
1228    let opacity = num("raster-opacity", 1.0);
1229    if opacity <= 0.0 {
1230        return;
1231    }
1232    let (sat, con, spin) = raster_factors(num("raster-saturation", 0.0), num("raster-contrast", 0.0), num("raster-hue-rotate", 0.0));
1233    let (lo, hi) = (num("raster-brightness-min", 0.0), num("raster-brightness-max", 1.0));
1234    let identity = sat == 0.0 && con == 1.0 && spin == [1.0, 0.0, 0.0] && lo == 0.0 && hi == 1.0;
1235    let Some(img) = raster_image(rt, bbox, fb.w, fb.h, ratio) else { return };
1236    for (x, y, px) in img.enumerate_pixels() {
1237        let a = px[3] as f64 / 255.0;
1238        if a <= 0.0 {
1239            continue;
1240        }
1241        let mut rgb = [px[0] as f64 / 255.0, px[1] as f64 / 255.0, px[2] as f64 / 255.0];
1242        if !identity {
1243            let r = rgb;
1244            rgb = [
1245                r[0] * spin[0] + r[1] * spin[1] + r[2] * spin[2],
1246                r[0] * spin[2] + r[1] * spin[0] + r[2] * spin[1],
1247                r[0] * spin[1] + r[1] * spin[2] + r[2] * spin[0],
1248            ];
1249            let avg = (r[0] + r[1] + r[2]) / 3.0;
1250            for c in rgb.iter_mut() {
1251                *c += (avg - *c) * sat;
1252                *c = (*c - 0.5) * con + 0.5;
1253                *c = lo + (hi - lo) * *c;
1254            }
1255        }
1256        let a = a * opacity;
1257        fb.blend(x as usize, y as usize, [(rgb[0] * a) as f32, (rgb[1] * a) as f32, (rgb[2] * a) as f32, a as f32]);
1258    }
1259}
1260
1261// ── Circle ───────────────────────────────────────────────────────────────────
1262
1263fn draw_circle_layer(fb: &mut Framebuffer, layer: &Json, zoom: f64, placed: &[PlacedTile], dpr: f64) {
1264    let p = &layer["paint"];
1265    let radius = Prop::new(p.get("circle-radius"), Kind::Number, zoom);
1266    let color = Prop::new(p.get("circle-color"), Kind::Color, zoom);
1267    let opacity = Prop::new(p.get("circle-opacity"), Kind::Number, zoom);
1268    let blur = Prop::new(p.get("circle-blur"), Kind::Number, zoom);
1269    let stroke_width = Prop::new(p.get("circle-stroke-width"), Kind::Number, zoom);
1270    let stroke_color = Prop::new(p.get("circle-stroke-color"), Kind::Color, zoom);
1271    let stroke_opacity = Prop::new(p.get("circle-stroke-opacity"), Kind::Number, zoom);
1272    let translate = Prop::new(p.get("circle-translate"), Kind::Array, zoom);
1273    let (w, h) = (fb.w, fb.h);
1274    let full = Clip { x0: 0.0, y0: 0.0, x1: w as f64, y1: h as f64 };
1275
1276    for pt in placed {
1277        for (f, scale) in features(layer, pt, zoom) {
1278            let Geometry::Points(points) = &f.geometry else { continue };
1279            let ctx = Ctx { zoom, feature: Some(f) };
1280            let r = radius.num(&ctx, 5.0) * dpr;
1281            let sw = stroke_width.num(&ctx, 0.0) * dpr;
1282            let fill = rgba(color.color(&ctx, Color::BLACK), opacity.num(&ctx, 1.0));
1283            let stroke = rgba(stroke_color.color(&ctx, Color::BLACK), stroke_opacity.num(&ctx, 1.0));
1284            // circle.vertex.glsl: antialiasblur = -max(1 / dpr / (r + sw), blur),
1285            // with r and sw in CSS px (here device px, so no 1 / dpr).
1286            let aablur = -(1.0 / (r + sw)).max(blur.num(&ctx, 0.0));
1287            let (tx, ty) = translate.translate_px(&ctx, dpr);
1288            let ext = r + sw;
1289            for &q in points {
1290                let (x, y) = to_extent(q, scale);
1291                // CircleBucket: points outside the tile are not drawn.
1292                if x < 0.0 || x >= EXTENT || y < 0.0 || y >= EXTENT {
1293                    continue;
1294                }
1295                let (cx, cy) = (pt.ox + x * pt.unit_px + tx, pt.oy + y * pt.unit_px + ty);
1296                let corner = |ex: f64, ey: f64| Vert { x: cx + ex * ext, y: cy + ey * ext, v: [ex, ey] };
1297                let quad = [corner(-1.0, -1.0), corner(1.0, -1.0), corner(1.0, 1.0), corner(-1.0, 1.0)];
1298                for tri in [[0, 1, 2], [0, 2, 3]] {
1299                    raster_triangle(w, h, [quad[tri[0]], quad[tri[1]], quad[tri[2]]], &full, |px, py, v| {
1300                        // circle.fragment.glsl
1301                        let el = (v[0] * v[0] + v[1] * v[1]).sqrt();
1302                        let opacity_t = smoothstep(0.0, aablur, el - 1.0);
1303                        let color_t = if sw < 0.01 { 0.0 } else { smoothstep(aablur, 0.0, el - r / (r + sw)) };
1304                        if opacity_t > 0.0 {
1305                            let mut out = [0f32; 4];
1306                            for i in 0..4 {
1307                                out[i] = ((fill[i] as f64 * (1.0 - color_t) + stroke[i] as f64 * color_t)
1308                                    * opacity_t) as f32;
1309                            }
1310                            fb.blend(px, py, out);
1311                        }
1312                    });
1313                }
1314            }
1315        }
1316    }
1317}
1318
1319#[cfg(test)]
1320mod tests {
1321    use super::*;
1322
1323    #[test]
1324    fn scale_zoom_matches_maplibre_convention() {
1325        // 800 px over the fixture bbox is MapLibre zoom 13 (GL JS reports 12.99994).
1326        let z = scale_zoom([-12459252.0, 4963454.0, -12451608.0, 4969187.0], 800);
1327        assert_eq!(z, 13.0);
1328        assert_eq!(tile_zoom(13.7, None), 13);
1329        assert_eq!(tile_zoom(13.7, Some(12)), 12);
1330    }
1331}
1332
1333
1334// ── SVG output ───────────────────────────────────────────────────────────────
1335
1336/// One style rendered as SVG fragments (ids prefixed so several styles can
1337/// share one document).
1338pub struct SvgParts {
1339    pub defs: String,
1340    pub body: String,
1341    pub skipped_layer_types: Vec<String>,
1342}
1343
1344/// Render `tiles` with `style` as vector SVG: the same view, tile clipping,
1345/// evaluated style values and label placement as [`render`], written as
1346/// paths instead of pixels. Labels are glyph outlines traced from the
1347/// style's SDF glyphs at the shader's edge threshold.
1348pub fn render_svg(
1349    style: &Json,
1350    sources: &SourceTiles,
1351    assets: &SymbolAssets,
1352    bbox: [f64; 4],
1353    width: u32,
1354    height: u32,
1355    id_prefix: &str,
1356    text_mode: super::fonts::SvgText,
1357    fonts: Option<&super::fonts::SvgFonts>,
1358) -> Result<SvgParts, String> {
1359    use std::fmt::Write as _;
1360    let (zoom, placed) = prepare(sources, bbox, width, height, 1.0);
1361    let placement = symbol::place(style, &symbol_tiles(&placed), assets, zoom, width as f64, height as f64);
1362    let mut defs = String::new();
1363    // Tile clip paths per source: "{prefix}{source number}t{tile index}".
1364    let mut source_ids: Vec<&String> = placed.keys().collect();
1365    source_ids.sort();
1366    let clip_prefix: std::collections::HashMap<&str, String> =
1367        source_ids.iter().enumerate().map(|(k, id)| (id.as_str(), format!("{id_prefix}{k}"))).collect();
1368    for id in &source_ids {
1369        let cp = &clip_prefix[id.as_str()];
1370        for (i, pt) in placed[*id].iter().enumerate() {
1371            let _ = write!(
1372                defs,
1373                r#"<clipPath id="{cp}t{i}"><rect x="{}" y="{}" width="{}" height="{}" shape-rendering="crispEdges"/></clipPath>"#,
1374                svg::num(pt.clip.x0),
1375                svg::num(pt.clip.y0),
1376                svg::num(pt.clip.x1 - pt.clip.x0),
1377                svg::num(pt.clip.y1 - pt.clip.y0)
1378            );
1379        }
1380    }
1381    let mut pattern_ids: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1382    let mut depth3d: Vec<f64> = Vec::new();
1383    let layer_clip = |layer: &Json| -> String {
1384        layer["source"].as_str().and_then(|s| clip_prefix.get(s)).cloned().unwrap_or_default()
1385    };
1386    let mut body = String::new();
1387    let mut skipped: Vec<String> = Vec::new();
1388    for (layer_idx, layer) in style["layers"].as_array().map(|v| v.as_slice()).unwrap_or(&[]).iter().enumerate() {
1389        let ltype = layer["type"].as_str().unwrap_or("");
1390        if !symbol::layer_visible(layer, zoom) {
1391            continue;
1392        }
1393        let id = svg::xml_escape(layer["id"].as_str().unwrap_or(""));
1394        let mut out = String::new();
1395        match ltype {
1396            "background" => {
1397                let ctx = Ctx { zoom, feature: None };
1398                let p = &layer["paint"];
1399                let c = Prop::new(p.get("background-color"), Kind::Color, zoom).color(&ctx, Color::BLACK);
1400                let o = Prop::new(p.get("background-opacity"), Kind::Number, zoom).num(&ctx, 1.0);
1401                if let Some((hex, a)) = svg::paint(c, o) {
1402                    let _ = write!(out, r#"<rect width="{width}" height="{height}" fill="{hex}" fill-opacity="{}"/>"#, svg::alpha(a));
1403                }
1404            }
1405            "fill" => svg_fill(&mut out, &mut defs, layer, zoom, layer_tiles(&placed, layer), &layer_clip(layer), assets, &mut pattern_ids),
1406            "line" if layer["paint"].get("line-pattern").map_or(false, |v| !v.is_null()) => {
1407                // Patterned lines stay raster: the layer drawn alone, embedded.
1408                let mut lfb = Framebuffer::new(width as usize, height as usize);
1409                draw_line_layer(&mut lfb, layer, zoom, layer_tiles(&placed, layer), 1.0, assets);
1410                if lfb.px.iter().any(|p| p[3] > 0 || p[0] > 0 || p[1] > 0 || p[2] > 0) {
1411                    let px = lfb.into_straight_rgba();
1412                    let _ = write!(out, r#"<image width="{width}" height="{height}" href="{}"/>"#, svg::png_data_uri(width, height, &px));
1413                }
1414            }
1415            "line" => svg_line(&mut out, layer, zoom, layer_tiles(&placed, layer), &layer_clip(layer)),
1416            "circle" => svg_circle(&mut out, layer, zoom, layer_tiles(&placed, layer)),
1417            "fill-extrusion" => {
1418                let view = ExtrusionView::new(style, bbox, width, height, 1.0, zoom);
1419                if layer["paint"].get("fill-extrusion-pattern").map_or(false, |v| !v.is_null()) {
1420                    // Patterned extrusions stay raster: the layer drawn alone, embedded.
1421                    let mut lfb = Framebuffer::new(width as usize, height as usize);
1422                    draw_fill_extrusion_layer(&mut lfb, layer, zoom, layer_tiles(&placed, layer), &view, assets, &mut depth3d);
1423                    if lfb.px.iter().any(|p| p[3] > 0 || p[0] > 0 || p[1] > 0 || p[2] > 0) {
1424                        let px = lfb.into_straight_rgba();
1425                        let _ = write!(out, r#"<image width="{width}" height="{height}" href="{}"/>"#, svg::png_data_uri(width, height, &px));
1426                    }
1427                } else {
1428                    svg_fill_extrusion(&mut out, layer, zoom, layer_tiles(&placed, layer), &view);
1429                }
1430            }
1431            "raster" => {
1432                // Raster tiles stay raster: the composited view, embedded.
1433                if let Some(rt) = layer["source"].as_str().and_then(|s| sources.raster.get(s)) {
1434                    let ctx = Ctx { zoom, feature: None };
1435                    let op = Prop::new(layer["paint"].get("raster-opacity"), Kind::Number, zoom).num(&ctx, 1.0);
1436                    if let Some(img) = raster_image(rt, bbox, width as usize, height as usize, 1.0) {
1437                        let _ = write!(
1438                            out,
1439                            r#"<image width="{width}" height="{height}" opacity="{}" href="{}"/>"#,
1440                            svg::alpha(op.clamp(0.0, 1.0)),
1441                            svg::png_data_uri(width, height, img.as_raw())
1442                        );
1443                    }
1444                }
1445            }
1446            "hillshade" => {
1447                // Shading stays raster: the layer drawn alone, embedded.
1448                if let Some(dem) = layer["source"].as_str().and_then(|s| sources.dem.get(s)) {
1449                    let mut lfb = Framebuffer::new(width as usize, height as usize);
1450                    let nearest = super::hillshade::source_nearest(style, layer["source"].as_str().unwrap_or(""), zoom);
1451                    super::hillshade::draw_layer(&mut lfb, layer, zoom, dem, bbox, width, height, 1.0, nearest);
1452                    if lfb.px.iter().any(|p| p[3] > 0 || p[0] > 0 || p[1] > 0 || p[2] > 0) {
1453                        let px = lfb.into_straight_rgba();
1454                        let _ = write!(out, r#"<image width="{width}" height="{height}" href="{}"/>"#, svg::png_data_uri(width, height, &px));
1455                    }
1456                }
1457            }
1458            "symbol" => symbol::svg_layer(&mut out, &mut defs, layer, layer_idx, &placement, assets, width as usize, height as usize, id_prefix, text_mode, fonts),
1459            other => {
1460                if !skipped.iter().any(|x| x == other) {
1461                    skipped.push(other.to_owned());
1462                }
1463            }
1464        }
1465        if !out.is_empty() {
1466            let _ = write!(body, r#"<g id="{id_prefix}{id}">{out}</g>"#);
1467        }
1468    }
1469    Ok(SvgParts { defs, body, skipped_layer_types: skipped })
1470}
1471
1472/// Fills as draw_fill_layer draws them: interiors are sampled at pixel
1473/// centres without antialiasing (`crispEdges`), one path per polygon (each
1474/// polygon is triangulated and blended on its own), then the 1 px
1475/// antialiasing outline in the fill colour (or `fill-outline-color`). For
1476/// opaque layers MapLibre draws that outline only outside the fills, which is
1477/// the same as drawing it beneath them. The outline is an aliased gl.LINES
1478/// line (one pixel per column, alpha 1 - smoothstep(0, 1, d)), which covers
1479/// about 0.81 px on average: hence a 0.8 px stroke.
1480#[allow(clippy::too_many_arguments)]
1481fn svg_fill(
1482    out: &mut String,
1483    defs: &mut String,
1484    layer: &Json,
1485    zoom: f64,
1486    placed: &[PlacedTile],
1487    prefix: &str,
1488    assets: &SymbolAssets,
1489    pattern_ids: &mut std::collections::HashMap<String, String>,
1490) {
1491    use std::fmt::Write as _;
1492    let p = &layer["paint"];
1493    let color = Prop::new(p.get("fill-color"), Kind::Color, zoom);
1494    let opacity = Prop::new(p.get("fill-opacity"), Kind::Number, zoom);
1495    let outline = Prop::new(p.get("fill-outline-color"), Kind::Color, zoom);
1496    let translate = Prop::new(p.get("fill-translate"), Kind::Array, zoom);
1497    let antialias = p["fill-antialias"].as_bool().unwrap_or(true);
1498    let pattern = Prop::new(p.get("fill-pattern"), Kind::Enum, zoom);
1499    // fill-pattern: an SVG <pattern> per image, aligned to the world grid as
1500    // the fill_pattern shader tiles it (see PatternFrame), for interiors and
1501    // the antialiasing outline. Always the translucent pass (outline above).
1502    let mut pattern_paint = |ctx: &Ctx, pt: &PlacedTile| -> Option<String> {
1503        let Some(Val::Str(name)) = pattern.get(ctx) else { return None };
1504        let img = assets.sprite.images.get(&name)?;
1505        let frame = PatternFrame::new(pt);
1506        let k = pt.unit_px / frame.tile_ratio; // screen px per CSS px at tile zoom
1507        let (sw, sh) = (img.w as f64 / img.pixel_ratio * k, img.h as f64 / img.pixel_ratio * k);
1508        let (x0, y0) = (pt.ox - frame.world_x * k, pt.oy - frame.world_y * k);
1509        let key = format!("{name}@{}", svg::num(k * 1000.0));
1510        let n = pattern_ids.len();
1511        let id = pattern_ids
1512            .entry(key)
1513            .or_insert_with(|| {
1514                let id = format!("{prefix}pat{n}");
1515                let _ = write!(
1516                    defs,
1517                    r#"<pattern id="{id}" patternUnits="userSpaceOnUse" x="{}" y="{}" width="{}" height="{}"><image width="{}" height="{}" preserveAspectRatio="none" href="{}"/></pattern>"#,
1518                    svg::num(x0.rem_euclid(sw)),
1519                    svg::num(y0.rem_euclid(sh)),
1520                    sw,
1521                    sh,
1522                    sw,
1523                    sh,
1524                    img.png_data_uri()
1525                );
1526                id
1527            })
1528            .clone();
1529        Some(format!("url(#{id})"))
1530    };
1531    let opaque = matches!(&color, Prop::Const(v) if v.as_color().map_or(false, |c| c.a == 1.0))
1532        && match &opacity {
1533            Prop::Absent => true,
1534            Prop::Const(v) => v.as_num() == Some(1.0),
1535            Prop::Data(..) => false,
1536        };
1537    let outline_beneath = opaque && !outline.is_set() && !pattern.is_set();
1538
1539    let mut fills = String::new();
1540    let mut outlines = String::new();
1541    for (i, pt) in placed.iter().enumerate() {
1542        let (mut gf, mut go) = (String::new(), String::new());
1543        for (f, scale) in features(layer, pt, zoom) {
1544            let ctx = Ctx { zoom, feature: Some(f) };
1545            let op = opacity.num(&ctx, 1.0);
1546            let polys = polys_px(pt, f, scale, translate.translate(&ctx));
1547            if polys.is_empty() {
1548                continue;
1549            }
1550            if pattern.is_set() {
1551                // Features whose pattern image is missing are not drawn.
1552                let Some(paint) = pattern_paint(&ctx, pt) else { continue };
1553                if op <= 0.0 {
1554                    continue;
1555                }
1556                for poly in &polys {
1557                    let _ = write!(gf, r#"<path d="{}" fill="{paint}" fill-opacity="{}"/>"#, svg::path_data(poly, true), svg::alpha(op.min(1.0)));
1558                }
1559                if antialias {
1560                    let rings: Vec<Vec<(f64, f64)>> = polys.into_iter().flatten().collect();
1561                    let stroke = match outline.is_set().then(|| svg::paint(outline.color(&ctx, Color::BLACK), op)).flatten() {
1562                        Some((hex, a)) => format!(r#"stroke="{hex}" stroke-opacity="{}""#, svg::alpha(a)),
1563                        None => format!(r#"stroke="{paint}" stroke-opacity="{}""#, svg::alpha(op.min(1.0))),
1564                    };
1565                    let _ = write!(go, r#"<path d="{}" {stroke}/>"#, svg::path_data(&rings, true));
1566                }
1567                continue;
1568            }
1569            if let Some((hex, a)) = svg::paint(color.color(&ctx, Color::BLACK), op) {
1570                for poly in &polys {
1571                    let _ = write!(gf, r#"<path d="{}" fill="{hex}" fill-opacity="{}"/>"#, svg::path_data(poly, true), svg::alpha(a));
1572                }
1573            }
1574            if antialias {
1575                let oc = if outline.is_set() { outline.color(&ctx, Color::BLACK) } else { color.color(&ctx, Color::BLACK) };
1576                if let Some((hex, a)) = svg::paint(oc, op) {
1577                    let rings: Vec<Vec<(f64, f64)>> = polys.into_iter().flatten().collect();
1578                    let _ = write!(go, r#"<path d="{}" stroke="{hex}" stroke-opacity="{}"/>"#, svg::path_data(&rings, true), svg::alpha(a));
1579                }
1580            }
1581        }
1582        if !gf.is_empty() {
1583            let _ = write!(fills, r#"<g clip-path="url(#{prefix}t{i})">{gf}</g>"#);
1584        }
1585        if !go.is_empty() {
1586            let _ = write!(outlines, r#"<g clip-path="url(#{prefix}t{i})">{go}</g>"#);
1587        }
1588    }
1589    let fills = format!(r#"<g fill-rule="evenodd" shape-rendering="crispEdges">{fills}</g>"#);
1590    let outlines = if outlines.is_empty() { outlines } else { format!(r#"<g fill="none" stroke-width="0.8">{outlines}</g>"#) };
1591    if outline_beneath {
1592        out.push_str(&outlines);
1593        out.push_str(&fills);
1594    } else {
1595        out.push_str(&fills);
1596        out.push_str(&outlines);
1597    }
1598}
1599
1600
1601/// A MapLibre dasharray as an SVG one: (even-length pattern, phase).
1602/// MapLibre's line atlas joins an odd array's last dash onto its first
1603/// (getDashRanges starts the first dash at -last), so [1, 2, 3] is a dash
1604/// of 4 and a gap of 2 entered 3 units into the dash; SVG would instead
1605/// repeat it as 1 2 3 1 2 3. A single value is a solid line. None when no
1606/// dashes show.
1607fn even_dash_pattern(d: &[f64]) -> Option<(Vec<f64>, f64)> {
1608    match d.len() {
1609        0 | 1 => None,
1610        n if n % 2 == 0 => Some((d.to_vec(), 0.0)),
1611        n => {
1612            let last = d[n - 1];
1613            let mut p = vec![d[0] + last];
1614            p.extend_from_slice(&d[1..n - 1]);
1615            Some((p, last))
1616        }
1617    }
1618}
1619
1620/// Offset a polyline perpendicular to its direction (positive = right of
1621/// the direction in screen space), with mitred vertex normals.
1622/// With `closed`, `pts` is a ring (no repeated end point) and the offset
1623/// wraps around it.
1624fn offset_polyline(pts: &[(f64, f64)], d: f64, closed: bool, join: &str, miter_limit: f64, round_limit: f64) -> Vec<(f64, f64)> {
1625    if pts.len() < 2 || d == 0.0 {
1626        return pts.to_vec();
1627    }
1628    let normal = |a: (f64, f64), b: (f64, f64)| {
1629        let (dx, dy) = (b.0 - a.0, b.1 - a.1);
1630        let len = (dx * dx + dy * dy).sqrt();
1631        if len == 0.0 { (0.0, 0.0) } else { (-dy / len, dx / len) }
1632    };
1633    let n = pts.len();
1634    let mut out = Vec::with_capacity(n + 8);
1635    for i in 0..n {
1636        let p = pts[i];
1637        let n1 = if i > 0 {
1638            normal(pts[i - 1], p)
1639        } else if closed {
1640            normal(pts[n - 1], p)
1641        } else {
1642            normal(p, pts[1])
1643        };
1644        let n2 = if i + 1 < n {
1645            normal(p, pts[i + 1])
1646        } else if closed {
1647            normal(p, pts[0])
1648        } else {
1649            n1
1650        };
1651        let (mut mx, mut my) = (n1.0 + n2.0, n1.1 + n2.1);
1652        let m = (mx * mx + my * my).sqrt();
1653        if m < 1e-9 {
1654            mx = n2.0;
1655            my = n2.1;
1656        } else {
1657            mx /= m;
1658            my /= m;
1659        }
1660        let cos = (mx * n2.0 + my * n2.1).max(1e-6);
1661        let miter_len = 1.0 / cos;
1662        // The offset side is the outside of the turn when the next segment
1663        // heads away from it (its direction is n2 rotated back by 90°).
1664        let dir2 = (n2.1, -n2.0);
1665        let outer = (dir2.0 * n1.0 + dir2.1 * n1.1) * d < -1e-9;
1666        // MapLibre offsets each join vertex along its extrusion, so the offset
1667        // path takes the join's shape on the outside of a turn (LineBucket:
1668        // round joins below round_limit and miters within the limit stay
1669        // mitred; otherwise round arcs or bevels).
1670        let shape = if !outer {
1671            "miter"
1672        } else {
1673            match join {
1674                "round" if miter_len >= round_limit => "round",
1675                "round" => "miter",
1676                "bevel" => "bevel",
1677                _ if miter_len > miter_limit => "bevel",
1678                _ => "miter",
1679            }
1680        };
1681        match shape {
1682            "round" => {
1683                let a0 = n1.1.atan2(n1.0);
1684                let mut sweep = n2.1.atan2(n2.0) - a0;
1685                while sweep > std::f64::consts::PI {
1686                    sweep -= 2.0 * std::f64::consts::PI;
1687                }
1688                while sweep < -std::f64::consts::PI {
1689                    sweep += 2.0 * std::f64::consts::PI;
1690                }
1691                let steps = ((sweep.abs() / (std::f64::consts::PI / 12.0)).ceil() as usize).max(1);
1692                for k in 0..=steps {
1693                    let a = a0 + sweep * k as f64 / steps as f64;
1694                    out.push((p.0 + a.cos() * d, p.1 + a.sin() * d));
1695                }
1696            }
1697            "bevel" => {
1698                out.push((p.0 + n1.0 * d, p.1 + n1.1 * d));
1699                out.push((p.0 + n2.0 * d, p.1 + n2.1 * d));
1700            }
1701            _ => {
1702                let k = if cos > 0.1 { d / cos } else { d };
1703                out.push((p.0 + mx * k, p.1 + my * k));
1704            }
1705        }
1706    }
1707    out
1708}
1709
1710fn svg_line(out: &mut String, layer: &Json, zoom: f64, placed: &[PlacedTile], prefix: &str) {
1711    use std::fmt::Write as _;
1712    let p = &layer["paint"];
1713    let l = &layer["layout"];
1714    let color = Prop::new(p.get("line-color"), Kind::Color, zoom);
1715    let opacity = Prop::new(p.get("line-opacity"), Kind::Number, zoom);
1716    let width = Prop::new(p.get("line-width"), Kind::Number, zoom);
1717    let floor_width = Prop::new(p.get("line-width"), Kind::Number, zoom.floor());
1718    let gap = Prop::new(p.get("line-gap-width"), Kind::Number, zoom);
1719    let offset = Prop::new(p.get("line-offset"), Kind::Number, zoom);
1720    let translate = Prop::new(p.get("line-translate"), Kind::Array, zoom);
1721    let dasharray = Prop::new(p.get("line-dasharray"), Kind::Enum, zoom);
1722    let blur = Prop::new(p.get("line-blur"), Kind::Number, zoom);
1723    let cap_s = super::expr::layout_enum(l, "line-cap", zoom.floor()).unwrap_or_else(|| "butt".into());
1724    let join_s = super::expr::layout_enum(l, "line-join", zoom.floor()).unwrap_or_else(|| "miter".into());
1725    let (cap, join) = (cap_s.as_str(), join_s.as_str());
1726    let miter = l["line-miter-limit"].as_f64().unwrap_or(2.0);
1727    let round_limit = l["line-round-limit"].as_f64().unwrap_or(1.05);
1728    let dash = match &dasharray {
1729        Prop::Const(v) => v.as_num_array().filter(|d| d.len() >= 2 && d.iter().sum::<f64>() > 0.0),
1730        _ => None,
1731    };
1732    for (i, pt) in placed.iter().enumerate() {
1733        let mut g = String::new();
1734        for (f, scale) in features(layer, pt, zoom) {
1735            let ctx = Ctx { zoom, feature: Some(f) };
1736            let fctx = Ctx { zoom: zoom.floor(), feature: Some(f) };
1737            // Polygon rings are closed lines (LineBucket's isPolygon): their
1738            // first vertex gets a join, not caps.
1739            let (lines, closed): (Vec<&Vec<(f32, f32)>>, bool) = match &f.geometry {
1740                Geometry::Lines(ls) => (ls.iter().collect(), false),
1741                Geometry::Polygons(ps) => (ps.iter().flatten().collect(), true),
1742                Geometry::Points(_) => continue,
1743            };
1744            let lw = width.num(&ctx, 1.0);
1745            if lw <= 0.0 {
1746                continue;
1747            }
1748            let Some((hex, a)) = svg::paint(color.color(&ctx, Color::BLACK), opacity.num(&ctx, 1.0)) else { continue };
1749            let (tx, ty) = translate.translate(&ctx);
1750            let px: Vec<Vec<(f64, f64)>> = lines
1751                .iter()
1752                .map(|ln| {
1753                    let mut v: Vec<(f64, f64)> = ln
1754                        .iter()
1755                        .map(|&q| {
1756                            let (x, y) = to_extent(q, scale);
1757                            (pt.ox + x * pt.unit_px + tx, pt.oy + y * pt.unit_px + ty)
1758                        })
1759                        .collect();
1760                    if closed && v.len() > 2 && v.first() == v.last() {
1761                        v.pop();
1762                    }
1763                    v
1764                })
1765                .collect();
1766            let off = offset.num(&ctx, 0.0);
1767            let gw = gap.num(&ctx, 0.0);
1768            let offsets: Vec<f64> = if gw > 0.0 { vec![off - (gw / 2.0 + lw / 2.0), off + (gw / 2.0 + lw / 2.0)] } else { vec![off] };
1769            let mut dash_attr = String::new();
1770            if let Some((pattern, phase)) = dash.as_deref().and_then(even_dash_pattern) {
1771                // MapLibre dash lengths are multiples of the line width at
1772                // floor(zoom). Round caps are used as-is: compared against
1773                // MapLibre, untrimmed SVG round dashes match best.
1774                // The pattern is laid out in pixels at the tile's integer zoom
1775                // (tileRatio), so it stretches with the fractional zoom.
1776                let fw = floor_width.num(&fctx, lw) * pt.unit_px * EXTENT / (TILE_PX * pt.overscaling);
1777                let vals: Vec<String> = pattern.iter().map(|&v| svg::num(v * fw)).collect();
1778                let offset = phase * fw;
1779                dash_attr = format!(r#" stroke-dasharray="{}""#, vals.join(" "));
1780                if offset != 0.0 {
1781                    dash_attr += &format!(r#" stroke-dashoffset="{}""#, svg::num(offset));
1782                }
1783            }
1784            // line.fragment.glsl ramps alpha over one pixel centred on each
1785            // edge, so a line of width w < 1 covers (w + 1)^2 / 4 px, not w:
1786            // stroke at the width with that coverage.
1787            let stroke_w = if lw < 1.0 { (lw + 1.0).powi(2) / 4.0 } else { lw };
1788            // line-blur widens the edge ramp to blur + 1 px (blur2), centred
1789            // half the blur inside the edge: nested strokes whose edges spread
1790            // over the blur (the rasteriser's 1 px antialiasing adds the
1791            // rest), with opacities stacking to the line's alpha.
1792            let b = blur.num(&ctx, 0.0).max(0.0);
1793            let bands: Vec<(f64, f64)> = if b > 0.0 {
1794                let n = 3;
1795                let mut below = 0.0;
1796                (1..=n)
1797                    .map(|k| {
1798                        let y = (k as f64 - 0.5) / n as f64;
1799                        let half = (lw / 2.0 - b / 2.0 + b * (0.5 - y)).max(0.05);
1800                        let target = a * k as f64 / n as f64;
1801                        let layer = if below >= 1.0 { 0.0 } else { ((target - below) / (1.0 - below)).clamp(0.0, 1.0) };
1802                        below = target;
1803                        (2.0 * half, layer)
1804                    })
1805                    .collect()
1806            } else {
1807                vec![(stroke_w, a)]
1808            };
1809            // One path per line: MapLibre blends each line on its own, so
1810            // translucent lines darken where they overlap.
1811            for (sw, op) in bands {
1812                if op <= 0.0 {
1813                    continue;
1814                }
1815                let _ = write!(
1816                    g,
1817                    r#"<g fill="none" stroke="{hex}" stroke-opacity="{}" stroke-width="{}" stroke-linecap="{cap}" stroke-linejoin="{join}" stroke-miterlimit="{}"{dash_attr}>"#,
1818                    svg::alpha(op),
1819                    svg::num(sw),
1820                    svg::num(miter)
1821                );
1822                for o in &offsets {
1823                    for r in &px {
1824                        let line = offset_polyline(r, *o, closed, join, miter, round_limit);
1825                        let _ = write!(g, r#"<path d="{}"/>"#, svg::path_data(std::slice::from_ref(&line), closed));
1826                    }
1827                }
1828                g.push_str("</g>");
1829            }
1830        }
1831        if !g.is_empty() {
1832            let _ = write!(out, r#"<g clip-path="url(#{prefix}t{i})">{g}</g>"#);
1833        }
1834    }
1835}
1836
1837fn svg_circle(out: &mut String, layer: &Json, zoom: f64, placed: &[PlacedTile]) {
1838    use std::fmt::Write as _;
1839    let p = &layer["paint"];
1840    let radius = Prop::new(p.get("circle-radius"), Kind::Number, zoom);
1841    let color = Prop::new(p.get("circle-color"), Kind::Color, zoom);
1842    let opacity = Prop::new(p.get("circle-opacity"), Kind::Number, zoom);
1843    let stroke_width = Prop::new(p.get("circle-stroke-width"), Kind::Number, zoom);
1844    let stroke_color = Prop::new(p.get("circle-stroke-color"), Kind::Color, zoom);
1845    let stroke_opacity = Prop::new(p.get("circle-stroke-opacity"), Kind::Number, zoom);
1846    let translate = Prop::new(p.get("circle-translate"), Kind::Array, zoom);
1847    for pt in placed {
1848        for (f, scale) in features(layer, pt, zoom) {
1849            let Geometry::Points(points) = &f.geometry else { continue };
1850            let ctx = Ctx { zoom, feature: Some(f) };
1851            let r = radius.num(&ctx, 5.0);
1852            let sw = stroke_width.num(&ctx, 0.0);
1853            let (tx, ty) = translate.translate(&ctx);
1854            for &q in points {
1855                let (x, y) = to_extent(q, scale);
1856                if x < 0.0 || x >= EXTENT || y < 0.0 || y >= EXTENT {
1857                    continue;
1858                }
1859                let (cx, cy) = (pt.ox + x * pt.unit_px + tx, pt.oy + y * pt.unit_px + ty);
1860                if let Some((hex, a)) = svg::paint(color.color(&ctx, Color::BLACK), opacity.num(&ctx, 1.0)) {
1861                    let _ = write!(out, r#"<circle cx="{}" cy="{}" r="{}" fill="{hex}" fill-opacity="{}"/>"#, svg::num(cx), svg::num(cy), svg::num(r), svg::alpha(a));
1862                }
1863                if sw > 0.0 {
1864                    if let Some((hex, a)) = svg::paint(stroke_color.color(&ctx, Color::BLACK), stroke_opacity.num(&ctx, 1.0)) {
1865                        let _ = write!(
1866                            out,
1867                            r#"<circle cx="{}" cy="{}" r="{}" fill="none" stroke="{hex}" stroke-opacity="{}" stroke-width="{}"/>"#,
1868                            svg::num(cx),
1869                            svg::num(cy),
1870                            svg::num(r + sw / 2.0),
1871                            svg::alpha(a),
1872                            svg::num(sw)
1873                        );
1874                    }
1875                }
1876            }
1877        }
1878    }
1879}