library:map: fade a fill by its authored opacity ramp, not a zoom gate
- Commit
c3b42aa6dc98f784143a58aa35329dda4031712b- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-27 23:04 UTC (3 months ago)
- Parents
b34c8a6
Diff
library/map/src/main/rust/src/style/expr.rs
diff --git a/library/map/src/main/rust/src/style/expr.rs b/library/map/src/main/rust/src/style/expr.rsindex a200fbc2a4..73fbbb0601 100644--- a/library/map/src/main/rust/src/style/expr.rs+++ b/library/map/src/main/rust/src/style/expr.rs@@ -371,9 +371,11 @@ fn interpolate(args: &[Json], context: &Context) -> Result<Value> { fn mix(a: &Value, b: &Value, t: f64) -> Result<Value> { match (a, b) { (Value::Number(a), Value::Number(b)) => Ok(Value::Number(a + (b - a) * t)),- // Colour stops are strings at this level. Returning the nearer endpoint would be a- // visible banding artifact, so the colour-typed caller interpolates instead; see- // `paint::color_at`.+ // Colour stops are strings at this level, and blending them means parsing them, which+ // is [`super::paint::color_at`]'s job rather than this evaluator's. Returning the+ // nearer endpoint bands a colour ramp; no *fill* colour in this style interpolates, so+ // nothing renders wrong today, and a `line-color` ramp that needs it should go through+ // `color_at` instead of widening `Value`. (Value::String(_), Value::String(_)) => { Ok(if t < 0.5 { a.clone() } else { b.clone() }) }@@ -381,6 +383,62 @@ fn mix(a: &Value, b: &Value, t: f64) -> Result<Value> { } } +/// Parse a style colour string into ARGB.+///+/// The two spellings `style/basemap.json` uses, and no more: `#rrggbb` for the 13 literal+/// fill colours and `rgba(r, g, b, a)` -- with the spaces the file writes -- for the seven+/// `landcover` arms. `#rgb`, `#rrggbbaa` and `rgb(...)` fall out of the same two branches for+/// free.+///+/// `None` rather than a default: a colour that will not parse must leave the layer undrawn,+/// because any substituted colour is a plausible-looking wrong map.+pub fn parse_color(source: &str) -> Option<u32> {+ let source = source.trim();+ if let Some(hex) = source.strip_prefix('#') {+ if !hex.is_ascii() {+ return None;+ }+ let digit = |i: usize| u32::from_str_radix(&hex[i..i + 1], 16).ok();+ let pair = |i: usize| u32::from_str_radix(&hex[i..i + 2], 16).ok();+ return match hex.len() {+ // The shorthand doubles each digit, so `#abc` is `#aabbcc`.+ 3 | 4 => {+ let a = if hex.len() == 4 { digit(3)? * 0x11 } else { 0xFF };+ Some(+ (a << 24)+ | ((digit(0)? * 0x11) << 16)+ | ((digit(1)? * 0x11) << 8)+ | (digit(2)? * 0x11),+ )+ }+ 6 | 8 => {+ let a = if hex.len() == 8 { pair(6)? } else { 0xFF };+ Some((a << 24) | (pair(0)? << 16) | (pair(2)? << 8) | pair(4)?)+ }+ _ => None,+ };+ }++ let (name, rest) = source.split_once('(')?;+ if !matches!(name.trim(), "rgb" | "rgba") {+ return None;+ }+ let parts: Vec<f64> = rest+ .strip_suffix(')')?+ .split(',')+ .map(|part| part.trim().parse::<f64>())+ .collect::<std::result::Result<_, _>>()+ .ok()?;+ let channel = |v: f64| v.round().clamp(0.0, 255.0) as u32;+ // Alpha is 0..1 in the functional notation, unlike the 0..255 of the channels.+ let alpha = match parts.len() {+ 3 => 0xFF,+ 4 => channel(parts[3] * 255.0),+ _ => return None,+ };+ Some((alpha << 24) | (channel(parts[0]) << 16) | (channel(parts[1]) << 8) | channel(parts[2]))+}+ #[cfg(test)] mod tests { use super::*;@@ -632,4 +690,29 @@ mod tests { assert!(!Value::String(String::new()).truthy()); assert!(s("x").truthy()); }++ #[test]+ fn both_colour_spellings_the_style_uses_parse() {+ // The 13 literal fill colours.+ assert_eq!(parse_color("#80deea"), Some(0xFF80DEEA));+ assert_eq!(parse_color("#E2DFDA"), Some(0xFFE2DFDA), "case does not matter");+ // The seven `landcover` arms, spaces and all.+ assert_eq!(parse_color("rgba(196, 231, 210, 1)"), Some(0xFFC4E7D2));+ assert_eq!(parse_color("rgba(255,255,255,1)"), Some(0xFFFFFFFF));+ // A fractional alpha is 0..1 in the functional notation, not 0..255.+ assert_eq!(parse_color("rgba(0, 0, 0, 0.5)"), Some(0x80000000));+ assert_eq!(parse_color("rgb(1, 2, 3)"), Some(0xFF010203));+ // Shorthand and the eight-digit form.+ assert_eq!(parse_color("#abc"), Some(0xFFAABBCC));+ assert_eq!(parse_color("#11223380"), Some(0x80112233));+ }++ /// A colour that will not parse has to be `None`: any substituted colour renders a+ /// plausible-looking wrong map, which is the failure mode with no symptom.+ #[test]+ fn an_unparseable_colour_is_none_rather_than_a_default() {+ for source in ["", "#", "#12345", "#gg0000", "cornflowerblue", "hsl(0, 0%, 0%)", "rgba(1,2)", "rgba(1,2,3"] {+ assert_eq!(parse_color(source), None, "{source:?} must not parse");+ }+ } }
library/map/src/main/rust/src/style/mod.rs
diff --git a/library/map/src/main/rust/src/style/mod.rs b/library/map/src/main/rust/src/style/mod.rsindex e45cf0c490..669298f2c8 100644--- a/library/map/src/main/rust/src/style/mod.rs+++ b/library/map/src/main/rust/src/style/mod.rs@@ -1,17 +1,22 @@ //! Which layers are drawn, in what order, in what colour - in light and dark. //!-//! # Being replaced+//! # Where the fills come from //!-//! The constants below are a hand-written approximation of `style/basemap.json`, and they-//! could not converge on it: 34 `landuse` kinds, opacity ramps and per-kind colour cases are-//! already written down in a file MapLibre renders correctly, so transcribing it by eye was-//! never going to work. [`expr`] evaluates that file instead, and these constants go once it-//! is wired through.+//! Every `fill` layer in [`layers`] is **derived** from `style/basemap.json` rather than+//! transcribed: draw order, `source-layer`, the `kind` whitelist, the colour and the zoom gate+//! all come from the file, via [`paint::FillStyle`]. That file is what MapLibre renders+//! correctly, and the previous hand-written table could not converge on it — 34 `landuse`+//! kinds collapsed into 13 layers, opacity ramps approximated as hard zoom cutoffs, and no+//! fallback layer at all, so an unlisted `kind` simply was not drawn. //!-//! Deliberately flat and constant: no expressions, no data-driven paint. Phase 3 replaces-//! the constants with the small expression evaluator the plan scopes out (`interpolate`,-//! `step`, `case`, `match`, `get`, `coalesce`), and this is the seam that lets the-//! renderer be finished and profiled first.+//! Two things are still by hand, and both are deliberate:+//!+//! * **The dark column.** `basemap.json` is light-only.+//! [`DARK_FILL`] is a per-authored-layer override, sourced from the contrast-checked values+//! in `maps/src/main/java/com/vayunmathur/maps/ui/theme/BasemapPalette.kt` (see below). A+//! missing entry is a test failure rather than a light colour rendered on a dark map.+//! * **The line layers.** Their widths already come from the authored ramps through+//! [`paint::LineStyle`]; their colours, dashes and `kind` filters do not yet. //! //! Order in [`layers`] **is** draw order, and it is global rather than per tile: a road //! casing from one tile must never cover the road fill of the tile next to it, so the@@ -132,6 +137,13 @@ pub struct Layer { /// `*_casing_early`/`*_casing_late` pairs are followed: they are one layer split in two /// at z12, and [`paint::LineStyle::stroke`] picks whichever covers the camera's zoom. pub line_paint: &'static [&'static str],+ /// The authored `fill` layer id whose `fill-opacity` ramp governs this layer.+ ///+ /// Empty means fully opaque. Evaluated per frame by [`paint::FillStyle::opacity`] against+ /// the camera's fractional zoom, exactly as [`line_paint`](Self::line_paint)'s widths are —+ /// a constant alpha plus an integer zoom gate is what drew `landcover` at full strength at+ /// z6 where the authored ramp asks for half.+ pub fill_paint: &'static str, /// Dash and gap lengths in line widths, as `line-dasharray` defines them. pub dash: (f32, f32), pub min_zoom: u8,@@ -215,164 +227,148 @@ const fn layer( width_dp: 0.0, gap_width_dp: 0.0, line_paint: &[],+ fill_paint: "", dash: NO_DASH, min_zoom: 0, max_zoom: 22, } } -/// A `landuse` fill.+/// The dark colour of each authored fill layer, RGB only. ///-/// `min_zoom` is 6 because the authored style ramps this family's `fill-opacity` from 0 at-/// z6 to 1 at z11. Drawing it below that puts continent-sized `national_park`,-/// `nature_reserve` and `military` polygons on the map, and their tile-clipped edges read as-/// straight cuts slashed across the shape.-const fn landuse(- id: &'static str,- kinds: &'static [&'static str],- light: u32,- dark: u32,-) -> Layer {- Layer { min_zoom: LANDUSE_MIN_ZOOM, ..layer(id, "landuse", LayerKind::Fill, kinds, light, dark) }-}--/// Where the authored style's `landuse` opacity ramp leaves zero.-pub const LANDUSE_MIN_ZOOM: u8 = 6;+/// `basemap.json` is light-only, so this is the one part of fill paint still maintained by+/// hand. Keyed by the id [`paint::FillDraw`] derives — the authored layer's own id, suffixed+/// with a `kind` for the two layers that paint more than one colour — so a restyle that+/// renames or re-splits a layer breaks the lookup loudly.+///+/// Alpha is **not** here: it comes from the authored `fill-opacity` in both variants, because+/// a translucent layer is translucent for a reason that has nothing to do with the theme.+///+/// Values are `BasemapPalette.darkFill`'s by role. Where the authored file has an arm the+/// palette has no counterpart for, the nearest role is used and noted.+const DARK_FILL: &[(&str, u32)] = &[+ // Not `BasemapPalette.Fill.Background`, which is what `earth` maps to there: that palette+ // was built for a raster style where the background *is* the land, so collapsing the two+ // is harmless. Here earth is a polygon drawn over water, and giving it the background+ // colour erased the coastline outright — the map became a single flat navy field with no+ // way to tell land from ocean. So dark earth is lifted to a neutral clearly above the+ // water, in the same family as the palette's Buildings (#22262C) and Other (#26282E).+ ("earth", 0x24262C),+ // Landcover's authored paint is near-white pastels that would wash out a dark map. Each is+ // a tint of the same hue held a few units off `earth`, which is what keeps a gap in+ // landcover coverage from reading as a different surface: earth is blue-dominant, so a+ // green-dominant tint of the same luminance shows up as a mauve patch where cover stops.+ ("landcover", 0x262B2A),+ ("landcover:grassland", 0x262C28),+ ("landcover:barren", 0x2C2A24),+ ("landcover:urban_area", 0x2A2B2E),+ ("landcover:farmland", 0x272D29),+ ("landcover:glacier", 0x34373D),+ ("landcover:scrub", 0x2A2C26),+ ("landuse_park:national_park", 0x1E2B20),+ ("landuse_park:wood", 0x1E2B20),+ ("landuse_park:scrub", 0x1F2A22),+ ("landuse_park:military", 0x26282E),+ ("landuse_urban_green", 0x23362A),+ ("landuse_hospital", 0x2B2528),+ ("landuse_industrial", 0x20262B),+ ("landuse_school", 0x282520),+ ("landuse_beach", 0x2C2A22),+ ("landuse_zoo", 0x213030),+ ("landuse_aerodrome", 0x212228),+ // No palette counterpart: the authored #e9e9ed is a shade off `landuse_aerodrome`'s+ // #dadbdf, so the dark value is held the same distance the other way.+ ("landuse_runway", 0x262931),+ // BasemapPalette.Fill.Water, and the same value `background` uses.+ ("water", 0x0D1B2A),+ ("landuse_pedestrian", 0x242229),+ ("landuse_pier", 0x202225),+ ("buildings", 0x22262C),+];++/// Zoom ranges the renderer imposes on a derived fill for its own reasons, not the style's.+///+/// A derived fill is otherwise gated by nothing but its authored `fill-opacity` ramp, and that+/// is deliberate. [`Layer::min_zoom`] and [`Layer::max_zoom`] are compared against the *tile's*+/// pyramid level in `tile::geometry::build`, so deriving them from the ramp — which is a+/// function of the *camera* — meant `landcover` geometry was never built for a tile deeper than+/// z6 even though the ramp wants it visible up to camera z7. Whether a shape existed then+/// depended on which pyramid level happened to be resident, so shapes appeared and vanished as+/// the camera zoomed. Cost is handled instead by the archive itself: `geometry::build` skips a+/// layer the tile does not contain, and Planetiler only puts `landcover` in shallow tiles and+/// `landuse`/`buildings` in deep ones.+///+/// `buildings` keeps a floor because that one *is* a cost decision rather than a paint one: it+/// is the densest layer in the schema, and a tessellation pass plus a draw call per tile is+/// worth avoiding even where the archive would return nothing.+const ZOOM_FLOOR: &[(&str, u8)] = &[("buildings", 14)]; -/// A `landcover` tint: light is the authored style's own paint, dark is a same-hue tint-/// lifted just off `earth`, and both are gone above z7 where the authored style's opacity-/// ramp reaches zero.-const fn landcover(- id: &'static str,- kinds: &'static [&'static str],- light: u32,- dark: u32,-) -> Layer {- Layer {- max_zoom: LANDCOVER_MAX_ZOOM,- ..layer(id, "landcover", LayerKind::Fill, kinds, light, dark)- }+/// The dark colour for a derived fill, or a safe neutral if the table has fallen behind.+///+/// A missing entry is pinned as a test failure by `every_derived_fill_has_a_dark_override`;+/// falling back to the dark earth here means the worst a stale table can do at runtime is+/// paint a layer the colour of the land, rather than a light colour on a dark map.+fn dark_fill(id: &str) -> u32 {+ const EARTH: u32 = 0x24262C;+ DARK_FILL.iter().find(|(key, _)| *key == id).map_or(EARTH, |(_, rgb)| *rgb) } -/// Where the authored style's `landcover` opacity ramp reaches zero.-pub const LANDCOVER_MAX_ZOOM: u8 = 7;--/// The stand-in style: enough to see the basemap and judge the geometry renderer.+/// Every layer the renderer draws, in draw order. ///-/// The authored style is Phase 3's job and is scoped to ~15–20 layers against `maps`' 71-/// authored (141 at runtime). What matters here is that every *code path* the real style-/// needs is exercised: fills, plain strokes, casings via `line-gap-width`, and dashes-/// including the degenerate `[2, 0]`.+/// The fills are derived from `style/basemap.json`; the line layers below them are still a+/// hand-written table, though their widths come from the authored ramps through+/// [`paint::LineStyle`]. All fills precede all lines, which is both the authored order and what+/// `casings_are_drawn_under_their_fills` pins. /// /// Layer and `kind` names follow the Protomaps v4 schema the archive is built to — as /// `tilecodec`'s `v5ca_z11_tile.mvt` fixture shows. pub fn layers() -> Vec<Layer> {+ let mut out: Vec<Layer> = paint::authored_fills().draws().map(fill_layer).collect();+ out.extend(line_layers());+ out+}++/// One derived fill draw as a [`Layer`].+///+/// Everything but the dark colour and the renderer's own zoom floor comes from the authored+/// file. The `&'static str`s borrow from the parsed style, which lives for the process — see+/// [`paint::authored_fills`].+///+/// The zoom range is the **whole** range unless [`ZOOM_FLOOR`] says otherwise: what a frame+/// shows is decided by the authored `fill-opacity` ramp against the camera, and the geometry has+/// to exist at every pyramid level the archive carries it at or shapes come and go with zoom.+fn fill_layer(draw: &'static paint::FillDraw) -> Layer {+ let min_zoom = ZOOM_FLOOR+ .iter()+ .find(|(id, _)| *id == draw.id)+ .map_or(0, |(_, floor)| *floor);+ Layer {+ id: &draw.id,+ source_layer: draw.source_layer,+ kind: LayerKind::Fill,+ kinds: &draw.kinds,+ light: draw.color,+ // Alpha comes from the authored colour itself in both variants; only the hue is themed.+ // The `fill-opacity` ramp is not baked in here — see `Layer::fill_paint`.+ dark: (draw.color & 0xFF00_0000) | dark_fill(&draw.id),+ width_dp: 0.0,+ gap_width_dp: 0.0,+ line_paint: &[],+ fill_paint: draw.authored,+ dash: NO_DASH,+ min_zoom,+ max_zoom: paint::MAX_ZOOM,+ }+}++/// The line layers, still hand-written.+///+/// Only the widths are authored, via [`Layer::line_paint`]. Colour, dashes and the `kind`+/// whitelists are transcribed, and the same derivation the fills now use would replace them —+/// but a line layer's colour is not the only thing to derive: `line-dasharray` is a `step`, and+/// the authored file splits a single road class across bridge, tunnel and casing layers.+fn line_layers() -> Vec<Layer> { vec![- // The land itself, and the only thing separating it from the sea.- //- // Light is the authored style's own `earth` paint. Dark is **not**- // `BasemapPalette.Fill.Background`, which is what `earth` maps to there: that palette- // was built for a raster style where the background *is* the land, so collapsing the- // two is harmless. Here earth is a polygon drawn over water, and giving it the- // background colour erased the coastline outright — the map became a single flat- // navy field with no way to tell land from ocean. So dark earth is lifted to a- // neutral clearly above the water, in the same family as the palette's Buildings- // (#22262C) and Other (#26282E).- layer("earth", "earth", LayerKind::Fill, &[], 0xFFE2DFDA, 0xFF24262C),- // Landcover is a **low-zoom tint**, not a landmass.- //- // The authored style ramps `fill-opacity` from 1 at z5 to 0 at z7, so above z7 it- // is not drawn at all, and its colours are light pastels keyed on `kind`. Painting- // it one solid colour at every zoom instead — which is what this did — lays a- // blanket over the whole map that follows coarse vegetation polygons rather than- // coastlines or borders, so it lines up with nothing. That is the single most- // visible way to get a basemap wrong.- //- // Without expression support there is no opacity ramp yet, so the ramp's endpoint- // becomes a hard `max_zoom` of 7.- //- // The authored `fill-color` is a `match` on `kind`, where a feature takes exactly one- // arm. Here each arm is a separate layer, so the unfiltered fallback — which- // `matches()` every kind — has to be drawn *first* and let the specific kinds paint- // over it. Drawn last it overpaints all of them, collapsing seven colours into one.- //- // The dark column is not the authored paint: those are near-white pastels that would- // wash out a dark map. Each is a tint of the same hue held a few units off `earth`- // (#24262C), which is what keeps a gap in landcover coverage from reading as a- // different surface. Earth is blue-dominant, so a green-dominant tint of the same- // luminance shows up as a mauve patch wherever coverage stops.- landcover("landcover-other", &[], 0xFFC4E7D2, 0xFF262B2A),- landcover("landcover-grassland", &["grassland"], 0xFFD2EFCF, 0xFF262C28),- landcover("landcover-farmland", &["farmland"], 0xFFD8EFD2, 0xFF272D29),- landcover("landcover-scrub", &["scrub"], 0xFFEAEFD2, 0xFF2A2C26),- landcover("landcover-barren", &["barren"], 0xFFFFF3D7, 0xFF2C2A24),- landcover("landcover-glacier", &["glacier"], 0xFFFFFFFF, 0xFF34373D),- landcover("landcover-urban", &["urban_area"], 0xFFE6E6E6, 0xFF2A2B2E),- // Water, including the ocean — `water.kind` really does contain `ocean`, so the sea- // is a polygon rather than the backdrop showing through. `#80deea` is the authored- // paint: a bright cyan, and deliberately nothing like `earth`. A washed-out blue- // here is what made land and sea indistinguishable. Drawn further down, in the- // authored position between landuse_runway and landuse_pedestrian.- // Landuse, by the authored style's own grouping, paint **and order**.- //- // Order matters: the authored style draws `landuse_park` through `landuse_runway`- // *before* `water` (indices 3-13 against water's 14), and only `landuse_pedestrian`- // and `landuse_pier` after it. Drawing all of landuse after water instead puts parks- // and industrial areas on top of rivers and coastline.- //- // Two things here were badly wrong before. Its `fill-opacity` ramps from 0 at z6 to- // 1 at z11, so it must not be drawn at world zoom at all — drawing it everywhere put- // continent-sized `national_park`, `nature_reserve` and `military` polygons on the- // map, whose tile-clipped edges are the straight "random cuts" across the shapes.- // And they are not all green: `military` is a pale blue-grey, `sand` is stone, and- // the fallback is simply the earth colour.- landuse(- "landuse-park",- &[- "national_park",- "park",- "cemetery",- "protected_area",- "nature_reserve",- "forest",- "golf_course",- ],- 0xFF9CD3B4,- 0xFF1E2B20,- ),- landuse("landuse-wood", &["wood"], 0xFFA0D9A0, 0xFF1E2B20),- landuse("landuse-grass", &["scrub", "grassland", "grass", "meadow"], 0xFF99D2BB, 0xFF1F2A22),- landuse(- "landuse-urban-green",- &["allotments", "village_green", "playground", "garden", "dog_park", "pitch"],- 0xFF9CD3B4,- 0xFF23362A,- ),- landuse("landuse-military", &["military", "naval_base", "airfield"], 0xFFC6DCDC, 0xFF26282E),- landuse("landuse-zoo", &["zoo"], 0xFFC6DCDC, 0xFF213030),- landuse("landuse-hospital", &["hospital"], 0xFFE4DAD9, 0xFF2B2528),- landuse("landuse-industrial", &["industrial", "railway"], 0xFFD1DDE1, 0xFF20262B),- landuse("landuse-school", &["school", "university", "college"], 0xFFE4DED7, 0xFF282520),- landuse("landuse-beach", &["beach", "sand", "bare_rock"], 0xFFE8E4D0, 0xFF2C2A22),- landuse("landuse-aerodrome", &["aerodrome"], 0xFFDADBDF, 0xFF212228),- // Water sits here: after most of landuse, before pedestrian and pier, exactly as the- // authored style orders them.- layer("water", "water", LayerKind::Fill, &[], 0xFF80DEEA, 0xFF0D1B2A),- landuse("landuse-pedestrian", &["pedestrian", "dam"], 0xFFE3E0D4, 0xFF242229),- landuse("landuse-pier", &["pier"], 0xFFE0E0E0, 0xFF202225),- // The authored style draws buildings at `fill-opacity` 0.5 over whatever is beneath,- // so the alpha is part of the colour rather than a solid slab of grey.- Layer {- min_zoom: 14,- ..layer(- "buildings",- "buildings",- LayerKind::Fill,- &["building", "building_part"],- 0x80CCCCCC,- 0xFF22262C,- )- }, // Casings first, then fills, so each road reads as one line rather than a chain of // overlapping outlines. Both use line-gap-width. In dark mode a casing is *darker* // than the road it outlines, which is what separates two adjacent roads when the@@ -496,21 +492,114 @@ mod tests { #[test] fn landcover_is_a_low_zoom_tint_and_stops_before_street_level() {- // The authored style ramps landcover's opacity to zero by z7. Drawing it at every- // zoom lays a blanket over the map that follows vegetation polygons rather than- // coastlines or borders, which lines up with nothing — the exact bug this pins.+ // The authored `fill-opacity` ramps landcover from 1 at z5 to 0 at z7, and that ramp is+ // the only thing that gates it. Drawing it at every zoom — which the transcribed table+ // did, because it had no ramp to read — lays a blanket over the map that follows+ // vegetation polygons rather than coastlines or borders, so it lines up with nothing. let layers = layers();+ let fills = paint::authored_fills(); let landcovers: Vec<&Layer> = layers.iter().filter(|l| l.source_layer == "landcover").collect(); assert!(!landcovers.is_empty(), "landcover must still be drawn at low zoom"); for l in &landcovers {- assert_eq!(l.max_zoom, LANDCOVER_MAX_ZOOM, "{} must stop at z7", l.id);- assert!(l.draws_at(4), "{} should tint low zooms", l.id);- assert!(!l.draws_at(8), "{} must be gone by z8", l.id);- assert!(!l.draws_at(14), "{} must not reach street level", l.id);+ assert!(fills.opacity(l, 4.0) > 0.0, "{} should tint low zooms", l.id);+ assert_eq!(fills.opacity(l, 7.0), 0.0, "{} is at zero opacity by z7", l.id);+ assert_eq!(fills.opacity(l, 14.0), 0.0, "{} must not reach street level", l.id); } } + /// The other half of the same derivation: `landuse_park`'s ramp is 0 at z6 rising to 1 at+ /// z11, so it must not be drawn at world zoom. Ignoring it put continent-sized+ /// `national_park`, `nature_reserve` and `military` polygons on the map, whose tile-clipped+ /// edges read as straight cuts slashed across the shape.+ #[test]+ fn the_landuse_park_family_is_gated_off_at_world_zoom() {+ let layers = layers();+ let fills = paint::authored_fills();+ let parks: Vec<&Layer> =+ layers.iter().filter(|l| l.id.starts_with("landuse_park")).collect();+ assert!(!parks.is_empty(), "the authored landuse_park layer must be derived");+ for l in &parks {+ assert_eq!(fills.opacity(l, 6.0), 0.0, "{} is at zero opacity at z6", l.id);+ assert_eq!(fills.opacity(l, 11.0), 1.0, "{} is fully on by z11", l.id);+ }+ }++ /// The gate that decides whether geometry is *built* must not come from the opacity ramp.+ ///+ /// `Layer::min_zoom`/`max_zoom` are compared against the **tile's** pyramid level in+ /// `tile::geometry::build`, while the ramp is a function of the **camera**. Deriving one+ /// from the other meant `landcover` was never tessellated for a tile deeper than z6 even+ /// though its ramp wants it visible up to camera z7 — so whether a shape existed depended on+ /// which pyramid level happened to be resident, and shapes appeared and vanished while+ /// zooming. Every ramp-driven fill therefore spans the whole zoom range.+ #[test]+ fn a_fills_zoom_range_is_not_derived_from_its_opacity_ramp() {+ for l in layers().iter().filter(|l| l.kind == LayerKind::Fill) {+ let floor = ZOOM_FLOOR.iter().find(|(id, _)| *id == l.id).map_or(0, |(_, z)| *z);+ assert_eq!(+ (l.min_zoom, l.max_zoom),+ (floor, paint::MAX_ZOOM),+ "`{}` carries a zoom gate that is not a declared cost floor",+ l.id,+ );+ }+ }++ /// The dark table is the only part of fill paint still written by hand, so a restyle that+ /// renames or re-splits a layer must not silently leave it painted light-on-dark.+ #[test]+ fn every_derived_fill_has_a_dark_override() {+ for l in layers().iter().filter(|l| l.kind == LayerKind::Fill) {+ assert!(+ DARK_FILL.iter().any(|(id, _)| *id == l.id),+ "`{}` is derived from basemap.json but has no entry in DARK_FILL",+ l.id,+ );+ }+ // And nothing stale in the other direction, which would be a colour nobody reads.+ let ids: Vec<&str> = layers().iter().map(|l| l.id).collect();+ for (id, _) in DARK_FILL {+ assert!(ids.contains(id), "DARK_FILL names `{id}`, which no layer is derived as");+ }+ }++ /// Fill paint comes from the file, not from this module. Spot-checked against the authored+ /// values rather than asserting a count, so a restyle changes one colour rather than+ /// breaking the test.+ #[test]+ fn fill_colour_is_the_authored_colour() {+ let layers = layers();+ let color = |id: &str| {+ layers.iter().find(|l| l.id == id).unwrap_or_else(|| panic!("{id}")).light+ };+ assert_eq!(color("earth"), 0xFFE2DFDA, "the authored `#e2dfda`");+ assert_eq!(color("water"), 0xFF80DEEA, "the authored `#80deea`");+ // A `match` arm written as `rgba(210, 239, 207, 1)`, spaces and all.+ assert_eq!(color("landcover:grassland"), 0xFFD2EFCF);+ // A `case` arm reached through `landuse_park`'s `in` conditions.+ assert_eq!(color("landuse_park:military"), 0xFFC6DCDC);+ // `fill-opacity` is a per-frame ramp now, not a baked alpha: see+ // `paint::fill_opacity_is_a_ramp_evaluated_per_frame_not_a_baked_alpha`.+ assert_eq!(color("buildings"), 0xFFCCCCCC);+ assert_eq!(color("landuse_urban_green"), 0xFF9CD3B4);+ }++ /// A kind the authored `case` gives its own colour must get its own layer, and a kind that+ /// shares a colour with an earlier arm must share its layer rather than adding a draw.+ #[test]+ fn a_data_driven_fill_becomes_one_layer_per_colour() {+ let layers = layers();+ let park: Vec<&Layer> =+ layers.iter().filter(|l| l.id.starts_with("landuse_park")).collect();+ // Four distinct colours across the authored `case`'s reachable arms.+ assert_eq!(park.len(), 4, "{:?}", park.iter().map(|l| l.id).collect::<Vec<_>>());+ let of = |kind: &str| park.iter().find(|l| l.matches(Some(kind))).map(|l| l.light);+ assert_eq!(of("national_park"), of("cemetery"), "one arm, one colour, one layer");+ assert_ne!(of("national_park"), of("military"));+ assert_eq!(of("pier"), None, "a kind the authored filter excludes is not drawn here");+ }+ #[test] fn every_landcover_kind_has_its_own_colour_in_both_palettes() { // The authored `fill-color` gives each kind a different colour, and that difference is@@ -527,7 +616,7 @@ mod tests { } seen.push((colour, l.id)); }- assert_eq!(seen.len(), 7, "every authored `match` arm needs an arm here");+ assert_eq!(seen.len(), 7, "every authored `match` arm needs a layer here"); } } @@ -799,12 +888,15 @@ mod tests { #[test] fn buildings_are_translucent_as_the_authored_style_draws_them() {- // `fill-opacity: 0.5` in the authored style. Pinned because it is the one layer- // whose alpha is load-bearing, and because it means tile overspill drawn twice- // would darken visibly — unlike an opaque layer, where double-drawing is harmless.+ // `fill-opacity: 0.5` in the authored style. Pinned because it is the one layer whose+ // translucency is load-bearing, and because it means tile overspill drawn twice would+ // darken visibly — unlike an opaque layer, where double-drawing is harmless.+ //+ // The 0.5 lives in the authored ramp and is applied per frame, so it is asserted+ // through `FillStyle::opacity` rather than on the layer's own alpha. let layers = layers(); let buildings = layers.iter().find(|l| l.id == "buildings").expect("buildings");- assert_eq!(buildings.light >> 24, 0x80, "the authored style draws these at half alpha");+ assert_eq!(paint::authored_fills().opacity(buildings, 16.0), 0.5); } #[test]
library/map/src/main/rust/src/style/paint.rs
diff --git a/library/map/src/main/rust/src/style/paint.rs b/library/map/src/main/rust/src/style/paint.rsindex e79454e8b0..36b158c757 100644--- a/library/map/src/main/rust/src/style/paint.rs+++ b/library/map/src/main/rust/src/style/paint.rs@@ -1,4 +1,4 @@-//! Line width read from the authored style instead of transcribed into constants.+//! Paint read from the authored style instead of transcribed into constants. //! //! A stroke width is not a property of a layer, it is a function of the camera's zoom: every //! road width in `style/basemap.json` is an `interpolate` on `["zoom"]` that starts at zero@@ -13,10 +13,25 @@ //! camera's zoom is fractional and continuous, and quantising it to the integer tile zoom //! would make roads jump in width at each level instead of growing smoothly. //!-//! Scoped to `line-width` and `line-gap-width`. Colour, dashes, fills and per-feature filters-//! still come from [`super::layers`]' constants.--use super::expr::{self, Context};+//! ## Fills+//!+//! [`FillStyle`] does the same job for `fill` layers, but the answer it computes is a *layer+//! list* rather than a per-frame number. Fill colour reaches the GPU as one push constant per+//! (layer, tile) draw, so a `fill-color` that varies per feature cannot be expressed in one+//! draw — it has to become one synthetic layer per colour. Only two of the authored fill+//! layers are data-driven (`landcover`'s `match` on `kind` and `landuse_park`'s `case`), and+//! expanding those by evaluating the authored expression per admitted `kind` is what+//! [`super::layers`] now does instead of transcribing 20 colours by eye.+//!+//! Fill opacity is evaluated per frame too, for the same reason and with the same machinery.+//! The authored ramps are the whole of how low zooms are meant to look: `landcover` fades from+//! 1 at z5 to 0 at z7 and `landuse_park` rises from 0 at z6 to 1 at z11. Baking either into a+//! constant alpha plus an integer zoom gate draws `landcover` at **full** strength at z6 where+//! the ramp asks for half, which lays a flat mint blanket over a whole continent, and pops+//! `landuse_park` on at full strength at z7 where the ramp asks for a fifth. Both were plainly+//! visible on device; neither shows up in a host test that only measures tessellated area.++use super::expr::{self, Context, Value}; use super::Layer; use serde_json::Value as Json; use std::collections::HashMap;@@ -28,6 +43,12 @@ use std::sync::OnceLock; /// app, and it makes the loader host-testable rather than reachable only from a device. const BASEMAP: &str = include_str!("../../style/basemap.json"); +/// The deepest zoom the renderer draws at, and the top of every derived zoom gate.+///+/// The archive stops at z14 and the renderer overzooms past it; 22 is where+/// [`super::Layer::max_zoom`] has always been pinned.+pub const MAX_ZOOM: u8 = 22;+ /// `line-width`'s default in the style spec. `line-gap-width`'s is zero. const DEFAULT_WIDTH_DP: f32 = 1.0; @@ -107,8 +128,8 @@ impl LinePaint { // width, because a guess is constant across zoom and a constant width is the defect // this replaces. let (Some(width_dp), Some(gap_width_dp)) = (- evaluate(self.width.as_ref(), zoom, DEFAULT_WIDTH_DP),- evaluate(self.gap_width.as_ref(), zoom, 0.0),+ evaluate(self.width.as_ref(), zoom, DEFAULT_WIDTH_DP, "LineString"),+ evaluate(self.gap_width.as_ref(), zoom, 0.0, "LineString"), ) else { return Stroke::NONE; };@@ -121,15 +142,31 @@ impl LinePaint { /// Width ramps key on nothing but zoom, so there is no feature to evaluate against. An absent /// property is the spec default; an expression that *fails* is not, and the two are /// deliberately different — see [`LinePaint::stroke`].-fn evaluate(expr: Option<&Json>, zoom: f64, default: f32) -> Option<f32> {+fn evaluate(expr: Option<&Json>, zoom: f64, default: f32, geometry_type: &str) -> Option<f32> { let Some(expr) = expr else { return Some(default); }; let properties = HashMap::new();- let context = Context { zoom, properties: &properties, geometry_type: "LineString" };+ let context = Context { zoom, properties: &properties, geometry_type }; expr::eval(expr, &context).ok()?.as_number().map(|width| width as f32) } +/// Evaluate a colour-valued paint property, for one feature's properties at one zoom.+///+/// The seam [`super::expr`]'s `mix` points at: a colour is a string to the evaluator and an+/// ARGB word to everything downstream, and this is the only place that knows both. An exact+/// stop lookup, which is all the authored fill paint needs — no `fill-color` in the file+/// interpolates.+pub fn color_at(+ paint: Option<&Json>,+ zoom: f64,+ properties: &HashMap<String, Value>,+) -> Option<u32> {+ let context = Context { zoom, properties, geometry_type: "Polygon" };+ let value = expr::eval(paint?, &context).ok()?;+ expr::parse_color(value.as_str()?)+}+ /// The authored style's `line` paint. #[derive(Default)] pub struct LineStyle {@@ -186,6 +223,294 @@ pub fn authored() -> &'static LineStyle { AUTHORED.get_or_init(|| LineStyle::parse(BASEMAP).unwrap_or_default()) } +// --- fills ---------------------------------------------------------------------------------++/// The parsed style, held for the whole process so what it borrows out lives as long.+///+/// [`super::Layer`] carries `&'static str` for its id and its `kind` whitelist, so the derived+/// fill layers have to borrow their strings from somewhere permanent. Borrowing them from a+/// parse that lives in a `static` is what makes that work without leaking a string per kind.+fn root() -> &'static Json {+ static ROOT: OnceLock<Json> = OnceLock::new();+ ROOT.get_or_init(|| serde_json::from_str(BASEMAP).unwrap_or(Json::Null))+}++/// One colour an authored `fill` layer paints, and the feature `kind`s that take it.+///+/// An authored layer whose `fill-color` is a literal string has exactly one of these. The two+/// that are data-driven have one per distinct colour, because fill colour reaches the GPU as+/// one push constant per (layer, tile) draw: a `match` on `kind` cannot be expressed inside a+/// draw, so it has to become several draws.+pub struct FillDraw {+ /// The authored layer's id, suffixed with the first `kind` of the arm when the layer+ /// paints more than one colour.+ pub id: String,+ /// The authored layer this was derived from, which is what owns the `fill-opacity` ramp.+ pub authored: &'static str,+ pub source_layer: &'static str,+ /// The `kind`s that take this colour, or empty for every feature the layer admits.+ ///+ /// Empty only ever happens for the arm derived from the authored expression's *fallback*,+ /// and only when the authored layer has no `kind` filter to restrict it — which is why the+ /// fallback is emitted first and the specific arms paint over it.+ pub kinds: Vec<&'static str>,+ /// ARGB at **full** `fill-opacity`.+ ///+ /// The ramp is not folded in here: it is a function of the camera's zoom, so it is+ /// evaluated per frame by [`FillStyle::opacity`] exactly as a line's width is. Any alpha in+ /// this word came from the authored colour itself, e.g. an `rgba()` literal.+ pub color: u32,+}++/// One authored `fill` layer, and the draws derived from it.+pub struct FillPaint {+ pub id: &'static str,+ pub source_layer: &'static str,+ min_zoom: f64,+ max_zoom: f64,+ filter: Option<&'static Json>,+ color: Option<&'static Json>,+ opacity: Option<&'static Json>,+ draws: Vec<FillDraw>,+}++impl FillPaint {+ fn parse(json: &'static Json) -> Option<FillPaint> {+ let paint = json.get("paint");+ let mut layer = FillPaint {+ id: json.get("id").and_then(Json::as_str)?,+ source_layer: json.get("source-layer").and_then(Json::as_str)?,+ min_zoom: json.get("minzoom").and_then(Json::as_f64).unwrap_or(0.0),+ max_zoom: json.get("maxzoom").and_then(Json::as_f64).unwrap_or(f64::INFINITY),+ filter: json.get("filter"),+ color: paint.and_then(|p| p.get("fill-color")),+ opacity: paint.and_then(|p| p.get("fill-opacity")),+ draws: Vec::new(),+ };+ layer.draws = layer.derive_draws();+ Some(layer)+ }++ /// Does this authored layer draw at `zoom`?+ ///+ /// `maxzoom` is exclusive, as the spec defines it. No `fill` layer in the file sets either+ /// bound, so today this is the identity — but a restyle that adds one should be followed+ /// rather than ignored.+ fn covers(&self, zoom: f64) -> bool {+ zoom >= self.min_zoom && zoom < self.max_zoom+ }++ fn opacity_at(&self, zoom: f64) -> f32 {+ // An opacity ramp this evaluator cannot read leaves the layer undrawn, for the same+ // reason a width ramp does: a guessed constant is the defect being removed.+ evaluate(self.opacity, zoom, 1.0, "Polygon").unwrap_or(0.0)+ }++ /// The shallowest integer zoom the authored `fill-opacity` is non-zero at, if any.+ ///+ /// Used only to pick a zoom at which to *read the colour*. It is deliberately **not** a+ /// gate: [`super::Layer::min_zoom`] is about which tiles carry the layer, and deriving it+ /// from the ramp instead made the geometry that exists depend on which pyramid level+ /// happened to be resident — so shapes came and went as the camera zoomed, which is a far+ /// worse defect than the one it was meant to avoid.+ fn first_drawn_zoom(&self) -> Option<u8> {+ (0..=MAX_ZOOM).find(|&zoom| self.covers(zoom as f64) && self.opacity_at(zoom as f64) > 0.0)+ }++ /// The colour this layer paints a feature of `kind`, at full opacity.+ fn color_for(&self, kind: Option<&'static str>, zoom: f64) -> Option<u32> {+ let mut properties = HashMap::new();+ if let Some(kind) = kind {+ properties.insert("kind".to_string(), Value::String(kind.to_string()));+ }+ color_at(self.color, zoom, &properties)+ }++ fn derive_draws(&self) -> Vec<FillDraw> {+ // A layer whose ramp is zero everywhere draws nothing at any zoom.+ let Some(first_zoom) = self.first_drawn_zoom() else {+ return Vec::new();+ };+ let admitted = filter_kinds(self.filter);+ // Where the candidate `kind`s come from: a layer with a `kind` filter can only ever+ // draw those, so any arm of its colour expression outside the filter is unreachable. A+ // layer without one can draw anything, so the only kinds worth asking about are the+ // ones its own colour expression names.+ let candidates: Vec<&'static str> = if admitted.is_empty() {+ self.color.map(kind_labels).unwrap_or_default()+ } else {+ admitted.clone()+ };+ // Colour is read at the shallowest zoom the layer draws at. No `fill-color` in the file+ // keys on zoom, so this only has to be a zoom the layer is actually drawn at.+ let zoom = first_zoom as f64;++ let mut draws: Vec<FillDraw> = Vec::new();+ let make = |id: String, kinds: Vec<&'static str>, color: u32| FillDraw {+ id,+ authored: self.id,+ source_layer: self.source_layer,+ kinds,+ color,+ };++ // The expression's fallback arm, drawn first so the specific kinds paint over it. Only+ // for a layer with no `kind` filter: an unfiltered draw over a filtered layer would+ // paint the very kinds the authored filter excludes.+ if admitted.is_empty() {+ if let Some(color) = self.color_for(None, zoom) {+ draws.push(make(self.id.to_string(), Vec::new(), color));+ }+ }+ for kind in candidates {+ let Some(color) = self.color_for(Some(kind), zoom) else { continue };+ match draws.iter_mut().find(|draw| draw.color == color) {+ // Already drawn: either by the unfiltered fallback, which covers this kind+ // anyway, or by an earlier arm this kind shares a colour with.+ Some(draw) if draw.kinds.is_empty() => {}+ Some(draw) => draw.kinds.push(kind),+ None => draws.push(make(format!("{}:{kind}", self.id), vec![kind], color)),+ }+ }+ // A layer that paints one colour needs no arm suffix, which is 13 of the 15.+ if let [only] = draws.as_mut_slice() {+ only.id = self.id.to_string();+ }+ draws+ }+}++/// The `kind` values an authored filter admits, or an empty list for "any of them".+///+/// The four shapes `style/basemap.json` uses on its `fill` layers, and no more. Anything else+/// reads as unrestricted, which is what MapLibre would draw if the filter passed everything —+/// the permissive answer, so a restyle shows up as too much on screen rather than a layer+/// silently missing.+fn filter_kinds(filter: Option<&'static Json>) -> Vec<&'static str> {+ let Some(Json::Array(items)) = filter else {+ return Vec::new();+ };+ let op = items.first().and_then(Json::as_str).unwrap_or_default();+ let args = &items[1..];+ match op {+ // `["==", "kind", K]`. A `$type` filter restricts geometry, not `kind`.+ "==" if args.first().and_then(Json::as_str) == Some("kind") => {+ args.get(1).and_then(Json::as_str).into_iter().collect()+ }+ // `["in", "kind", K, ...]`+ "in" if args.first().and_then(Json::as_str) == Some("kind") => {+ args[1..].iter().filter_map(Json::as_str).collect()+ }+ // `["any", inner, ...]` — a union, and unrestricted if any branch is.+ "any" => {+ let mut out = Vec::new();+ for inner in args {+ let kinds = filter_kinds(Some(inner));+ if kinds.is_empty() {+ return Vec::new();+ }+ out.extend(kinds);+ }+ out+ }+ _ => Vec::new(),+ }+}++/// Every `kind` value a colour expression names, in the order it names them.+///+/// Used only to discover which kinds are worth asking [`FillPaint::color_for`] about; the+/// colour itself always comes from evaluating the authored expression, never from reading its+/// shape. Strings that are colours, operator names or the `kind` key itself are not kinds.+fn kind_labels(paint: &'static Json) -> Vec<&'static str> {+ let mut out = Vec::new();+ collect_labels(paint, &mut out);+ out+}++fn collect_labels(paint: &'static Json, out: &mut Vec<&'static str>) {+ match paint {+ Json::String(s) => {+ if s != "kind" && expr::parse_color(s).is_none() && !out.contains(&s.as_str()) {+ out.push(s);+ }+ }+ Json::Array(items) => {+ let op = items.first().and_then(Json::as_str);+ // `["get", k]` and friends name a property, not a value it can take.+ if matches!(op, Some("get") | Some("has") | Some("!has")) {+ return;+ }+ for item in &items[usize::from(op.is_some())..] {+ collect_labels(item, out);+ }+ }+ _ => {}+ }+}++/// The authored style's `fill` paint, expanded to one entry per colour.+#[derive(Default)]+pub struct FillStyle {+ layers: Vec<FillPaint>,+}++impl FillStyle {+ /// Read the `fill` layers out of an already-parsed style.+ ///+ /// Takes the parsed root rather than the source text, unlike [`LineStyle::parse`], because+ /// what it produces borrows from it — see [`root`].+ pub fn read(root: &'static Json) -> Result<FillStyle, String> {+ let layers = root+ .get("layers")+ .and_then(Json::as_array)+ .ok_or("basemap.json has no `layers` array")?;+ Ok(FillStyle {+ layers: layers+ .iter()+ .filter(|layer| layer.get("type").and_then(Json::as_str) == Some("fill"))+ .filter_map(FillPaint::parse)+ .collect(),+ })+ }++ pub fn get(&self, id: &str) -> Option<&FillPaint> {+ self.layers.iter().find(|layer| layer.id == id)+ }++ /// Every derived draw, in the authored file's own layer order.+ ///+ /// Order **is** draw order, which is why this is a flat list rather than a lookup: the+ /// authored style draws `landuse_park` through `landuse_runway` before `water` and only+ /// `landuse_pedestrian` and `landuse_pier` after it, and getting that wrong puts parks on+ /// top of rivers.+ pub fn draws(&self) -> impl Iterator<Item = &FillDraw> {+ self.layers.iter().flat_map(|layer| layer.draws.iter())+ }++ /// The `fill-opacity` `layer` draws at `zoom`, in 0..=1.+ ///+ /// The fill counterpart of [`LineStyle::stroke`], and per *frame* for the same reason: the+ /// camera's zoom is fractional and continuous, so quantising it to the integer tile zoom is+ /// what makes a layer appear at a step instead of fading in.+ ///+ /// A layer naming no authored counterpart is fully opaque, which is what leaves the+ /// hand-written line layers alone. A ramp this evaluator cannot read draws nothing, exactly+ /// as an unreadable width ramp does: a guessed constant is the defect being removed.+ pub fn opacity(&self, layer: &Layer, zoom: f64) -> f32 {+ if layer.fill_paint.is_empty() {+ return 1.0;+ }+ self.get(layer.fill_paint).map_or(0.0, |paint| paint.opacity_at(zoom))+ }+}++/// The vendored style's fill paint, parsed and expanded once.+pub fn authored_fills() -> &'static FillStyle {+ static AUTHORED: OnceLock<FillStyle> = OnceLock::new();+ AUTHORED.get_or_init(|| FillStyle::read(root()).unwrap_or_default())+}+ #[cfg(test)] mod tests { use super::*;@@ -452,6 +777,191 @@ mod tests { assert_eq!(Stroke { width_dp: 2.0, gap_width_dp: 0.1 }.half_px(3.0).1, 0.15); } + // --- fills -------------------------------------------------------------++ fn fills() -> &'static FillStyle {+ authored_fills()+ }++ #[test]+ fn the_vendored_style_parses_and_holds_its_fill_layers() {+ // 15 `fill` layers in the authored file.+ assert_eq!(fills().layers.len(), 15, "found {} fill layers", fills().layers.len());+ assert!(fills().get("earth").is_some());+ assert!(fills().get("landuse_park").is_some());+ // A `line` layer must not be picked up by the `fill` filter.+ assert!(fills().get("roads_highway").is_none());+ }++ /// The derived draws are in the authored file's own order, which is draw order. The authored+ /// style puts `landuse_park` through `landuse_runway` *before* `water` and only+ /// `landuse_pedestrian` and `landuse_pier` after it; flattening landuse to one side of water+ /// puts parks on top of rivers or rivers on top of parks.+ #[test]+ fn the_derived_draws_keep_the_authored_order() {+ let ids: Vec<&str> = fills().draws().map(|draw| draw.id.as_str()).collect();+ let at = |id: &str| ids.iter().position(|other| *other == id).unwrap_or_else(|| panic!("{id}"));+ assert!(at("earth") < at("landcover"));+ assert!(at("landuse_park:national_park") < at("water"));+ assert!(at("landuse_runway") < at("water"));+ assert!(at("water") < at("landuse_pedestrian"));+ assert!(at("landuse_pier") < at("buildings"));+ }++ /// A data-driven `fill-color` becomes one draw per colour, with the expression's **fallback+ /// first**: it is unfiltered, so it has to draw under the specific kinds rather than over+ /// them. Drawn last it collapses seven colours into one.+ #[test]+ fn an_unfiltered_fallback_arm_is_derived_first() {+ let landcover = fills().get("landcover").expect("landcover");+ let (first, rest) = landcover.draws.split_first().expect("at least the fallback");+ assert_eq!(first.id, "landcover");+ assert!(first.kinds.is_empty(), "the fallback draws every kind");+ assert_eq!(rest.len(), 6, "one per authored `match` arm");+ for draw in rest {+ assert!(!draw.kinds.is_empty(), "{} must be filtered", draw.id);+ }+ }++ /// A layer whose authored filter is a `kind` whitelist gets **no** unfiltered arm: one would+ /// draw the very kinds the filter excludes, in the fallback colour.+ #[test]+ fn a_filtered_layer_derives_no_unfiltered_arm() {+ for id in ["landuse_park", "buildings", "landuse_school"] {+ let layer = fills().get(id).expect(id);+ for draw in &layer.draws {+ assert!(!draw.kinds.is_empty(), "{} derived an unfiltered arm", draw.id);+ }+ }+ // And the kinds it does derive are all admitted by the authored filter.+ let admitted = filter_kinds(fills().get("landuse_park").expect("landuse_park").filter);+ for draw in &fills().get("landuse_park").expect("landuse_park").draws {+ for kind in &draw.kinds {+ assert!(admitted.contains(kind), "`{kind}` is outside the authored filter");+ }+ }+ }++ /// The authored `fill-opacity` ramp is the *only* thing that gates a fill, and it is+ /// continuous. Pinned at the zooms that were visibly wrong on device.+ #[test]+ fn the_opacity_ramp_is_the_only_gate_and_it_is_continuous() {+ for id in ["landcover", "landuse_park"] {+ let layer = fills().get(id).expect(id);+ let mut previous = f32::NAN;+ for tenth in 0..=(MAX_ZOOM as u32 * 10) {+ let zoom = tenth as f64 / 10.0;+ let opacity = layer.opacity_at(zoom);+ assert!((0.0..=1.0).contains(&opacity), "{id} at z{zoom} is {opacity}");+ // No step larger than the ramp's own slope between adjacent tenths: a jump+ // means something quantised the zoom, which is how a layer pops instead of+ // fading.+ if previous.is_finite() {+ assert!(+ (opacity - previous).abs() < 0.06,+ "{id} jumped {previous} -> {opacity} at z{zoom}",+ );+ }+ previous = opacity;+ }+ }+ // And the shallowest drawn zoom, which is only used to pick a zoom to read colour at.+ assert_eq!(fills().get("landcover").expect("landcover").first_drawn_zoom(), Some(0));+ assert_eq!(fills().get("landuse_park").expect("landuse_park").first_drawn_zoom(), Some(7));+ }++ /// `fill-opacity` is **not** folded into the layer table: it is a function of the camera's+ /// zoom, so it is evaluated per frame. Baking it in drew `landcover` at full strength at z6+ /// where the authored ramp asks for half.+ #[test]+ fn fill_opacity_is_a_ramp_evaluated_per_frame_not_a_baked_alpha() {+ let alpha = |id: &str| {+ fills().draws().find(|d| d.id == id).unwrap_or_else(|| panic!("{id}")).color >> 24+ };+ assert_eq!(alpha("buildings"), 0xFF, "the 0.5 is the ramp's, not the colour's");+ assert_eq!(alpha("landuse_urban_green"), 0xFF);+ assert_eq!(alpha("earth"), 0xFF);+ assert_eq!(alpha("landcover:glacier"), 0xFF, "rgba(255, 255, 255, 1)");++ // And the ramps themselves read the authored values.+ let at = |id: &str, zoom: f64| fills().get(id).unwrap_or_else(|| panic!("{id}")).opacity_at(zoom);+ assert_eq!(at("buildings", 16.0), 0.5, "a literal fill-opacity");+ assert_eq!(at("landuse_urban_green", 16.0), 0.7);+ assert_eq!(at("earth", 4.0), 1.0, "no fill-opacity is fully opaque");+ // The two ramps, at the zooms that were visibly wrong on device.+ assert_eq!(at("landcover", 5.0), 1.0);+ assert_eq!(at("landcover", 6.0), 0.5, "half, not the full blanket");+ assert_eq!(at("landcover", 7.0), 0.0);+ assert_eq!(at("landuse_park", 6.0), 0.0);+ assert!((at("landuse_park", 7.0) - 0.2).abs() < 1e-6, "a fifth, not full green");+ assert_eq!(at("landuse_park", 11.0), 1.0);+ }++ /// The fill counterpart of `LineStyle::stroke`, resolved through a real derived layer.+ #[test]+ fn the_opacity_of_a_derived_layer_follows_its_authored_ramp() {+ let layers = crate::style::layers();+ let of = |id: &str| layers.iter().find(|l| l.id == id).unwrap_or_else(|| panic!("{id}"));+ let grassland = of("landcover:grassland");+ assert_eq!(fills().opacity(grassland, 5.0), 1.0);+ assert_eq!(fills().opacity(grassland, 6.0), 0.5, "an arm inherits its layer's ramp");+ assert_eq!(fills().opacity(grassland, 7.0), 0.0, "which is also its gate");+ // Continuous, not stepped: the whole point of evaluating per frame.+ let half = fills().opacity(grassland, 6.5);+ assert!(half > 0.2 && half < 0.3, "got {half}");+ // A layer naming no authored fill paint is opaque, which leaves the line layers alone.+ let road = of("roads-major");+ assert_eq!(fills().opacity(road, 10.0), 1.0);+ }++ /// A filter shape this does not understand reads as unrestricted, which is the permissive+ /// answer: too much on screen is a visible bug, a silently missing layer is not.+ #[test]+ fn the_filter_reader_handles_the_shapes_the_style_uses() {+ let read = |source: &str| {+ let json: Json = serde_json::from_str(source).expect("valid JSON");+ // Leaked so the borrow is 'static, as it is in the real parse.+ filter_kinds(Some(Box::leak(Box::new(json))))+ };+ assert_eq!(read(r#"["==","kind","pier"]"#), vec!["pier"]);+ assert_eq!(read(r#"["in","kind","school","college"]"#), vec!["school", "college"]);+ assert_eq!(read(r#"["any",["in","kind","runway","taxiway"]]"#), vec!["runway", "taxiway"]);+ // `$type` restricts geometry, not `kind`, so it admits everything.+ assert!(read(r#"["==","$type","Polygon"]"#).is_empty());+ assert!(filter_kinds(None).is_empty());+ assert!(read(r#"["!in","kind","pier"]"#).is_empty(), "unrecognised reads as any");+ }++ /// The kind labels are only used to decide which kinds are worth asking about; the colour+ /// itself always comes from evaluating the authored expression.+ #[test]+ fn the_kind_labels_of_a_colour_expression_exclude_colours_and_operators() {+ let expr: &'static Json = Box::leak(Box::new(+ serde_json::from_str(+ r##"["match",["get","kind"],"grassland","rgba(1, 2, 3, 1)","barren","#fff3d7","#c4e7d2"]"##,+ )+ .expect("valid JSON"),+ ));+ assert_eq!(kind_labels(expr), vec!["grassland", "barren"]);+ }++ #[test]+ fn color_at_reads_a_data_driven_colour_for_one_feature() {+ let paint: &Json = &serde_json::json!([+ "case",+ ["in", ["get", "kind"], ["literal", ["military"]]],+ "#c6dcdc",+ "#e2dfda",+ ]);+ let mut properties = HashMap::new();+ properties.insert("kind".to_string(), Value::String("military".to_string()));+ assert_eq!(color_at(Some(paint), 8.0, &properties), Some(0xFFC6DCDC));+ assert_eq!(color_at(Some(paint), 8.0, &HashMap::new()), Some(0xFFE2DFDA), "the fallback");+ // A colour this cannot read is `None`, never a substituted default.+ assert_eq!(color_at(Some(&serde_json::json!("chartreuse")), 8.0, &HashMap::new()), None);+ assert_eq!(color_at(None, 8.0, &HashMap::new()), None);+ }+ /// What should actually appear on a density-3 phone at the zooms the defect was measured at. /// This is the closest a host test gets to the device, so the numbers are spelled out. #[test]
library/map/src/main/rust/src/tile/geometry.rs
diff --git a/library/map/src/main/rust/src/tile/geometry.rs b/library/map/src/main/rust/src/tile/geometry.rsindex c9127f4f9c..4ed8dc2f69 100644--- a/library/map/src/main/rust/src/tile/geometry.rs+++ b/library/map/src/main/rust/src/tile/geometry.rs@@ -152,7 +152,10 @@ mod tests { // one that would still cost a draw. assert!(mesh_for(&mesh, &layers, "buildings").is_none(), "no buildings layer here"); assert!(mesh_for(&mesh, &layers, "roads-highway").is_none(), "the road is a major_road");- assert!(mesh_for(&mesh, &layers, "landuse-park").is_none(), "no landuse layer");+ assert!(+ mesh_for(&mesh, &layers, "landuse_park:national_park").is_none(),+ "no landuse layer",+ ); } #[test]@@ -329,6 +332,7 @@ mod tests { width_dp: 1.0, gap_width_dp: 0.0, line_paint: &[],+ fill_paint: "", dash: (0.0, 0.0), min_zoom: 0, max_zoom: 22,
library/map/src/main/rust/src/vulkan/renderer.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer.rs b/library/map/src/main/rust/src/vulkan/renderer.rsindex 9686a43fd7..b0f0f5ea32 100644--- a/library/map/src/main/rust/src/vulkan/renderer.rs+++ b/library/map/src/main/rust/src/vulkan/renderer.rs@@ -401,21 +401,27 @@ impl Renderer { ordered.sort_by_key(|tile| tile.z); for (index, layer) in layers.iter().enumerate() {- // Visibility is the camera's business, not the tile's. Meshes are tessellated for- // a *window* of zooms (see `geometry::build`), so an ancestor standing in below- // its own zoom carries layers that the style says have already faded out — a z5- // tile's landcover is still in its buffers at camera z9, where the authored- // opacity ramp reached zero two levels earlier. Gating here is what makes a- // fill's zoom range follow the camera the way the authored ramps do.+ // `min_zoom`/`max_zoom` are a data-and-cost gate, not paint: they say which zooms+ // the archive is worth asking for this layer at. Paint is the authored ramp below. if !layer.draws_at(camera.zoom.floor().clamp(0.0, 22.0) as u8) { continue; }- // Width comes from the authored style, evaluated against the *camera's* fractional- // zoom rather than the tile's, so a stroke grows smoothly while zooming instead of- // jumping a step at every level. It is a push constant, so this re-tessellates- // nothing, and it does not vary per tile.- let stroke = match layer.kind {- LayerKind::Fill => Stroke::NONE,+ // Width and opacity come from the authored style, evaluated against the *camera's*+ // fractional zoom rather than the tile's, so a stroke grows and a fill fades+ // smoothly while zooming instead of jumping a step at every level. Both are push+ // constants, so this re-tessellates nothing, and neither varies per tile.+ let (stroke, opacity) = match layer.kind {+ // The ramp is what makes a fill visible, and it is the *only* thing: gating a+ // fill on an integer zoom drew `landcover` at full strength at z6 where the+ // ramp asks for half, and popped `landuse_park` on at full strength at z7+ // where it asks for a fifth.+ LayerKind::Fill => {+ let opacity = paint::authored_fills().opacity(layer, camera.zoom);+ if opacity <= 0.0 {+ continue;+ }+ (Stroke::NONE, opacity)+ } LayerKind::Line => { let stroke = paint::authored().stroke(layer, camera.zoom); // The authored ramps reach zero outside the zooms a layer is meant for,@@ -424,7 +430,7 @@ impl Renderer { if !stroke.visible() { continue; }- stroke+ (stroke, 1.0) } }; for tile in &ordered {@@ -447,7 +453,7 @@ impl Renderer { let (half_width_px, half_gap_px) = stroke.half_px(camera.density); let push = Push { tile_to_clip: camera.tile_to_clip(tile.z, tile.x, tile.y),- color: argb_to_rgba(layer.color(palette)),+ color: argb_to_rgba(scale_alpha(layer.color(palette), opacity)), line: [half_width_px, half_gap_px, layer.dash.0, layer.dash.1], misc: [camera.tile_span_px(tile.z), 0.0, 0.0, 0.0], };@@ -534,6 +540,18 @@ impl Drop for Renderer { } } +/// Multiply a colour's alpha by `opacity`, for the authored `fill-opacity` ramps.+///+/// The ramp is applied here rather than folded into the layer table because it is a function of+/// the camera's zoom: a fill has to fade across a zoom, not switch at one.+fn scale_alpha(argb: u32, opacity: f32) -> u32 {+ if opacity >= 1.0 {+ return argb;+ }+ let alpha = (((argb >> 24) & 0xFF) as f32 * opacity.clamp(0.0, 1.0)).round() as u32;+ (alpha << 24) | (argb & 0x00FF_FFFF)+}+ /// ARGB to the linear RGBA the shaders and clear values take. fn argb_to_rgba(argb: u32) -> [f32; 4] { [