library:map: a flat style file, and no expression interpreter
- Commit
31d599e44f13b7fc44de6e6b2dbee5971ce4e13a- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-27 23:37 UTC (3 months ago)
- Parents
653af99
Diff
library/map/src/main/rust/examples/probe_archive.rs
diff --git a/library/map/src/main/rust/examples/probe_archive.rs b/library/map/src/main/rust/examples/probe_archive.rsindex 9f03c14c3f..9345d91727 100644--- a/library/map/src/main/rust/examples/probe_archive.rs+++ b/library/map/src/main/rust/examples/probe_archive.rs@@ -308,7 +308,7 @@ fn main() { // whose fill covers far less than the polygons it was given is dropping geometry, // which on screen is ocean showing through the middle of a continent. for m in &mesh.meshes {- let id = layers[m.layer_index].id;+ let id = &layers[m.layer_index].id; let stride = match m.kind { style::LayerKind::Fill => fill::FLOATS_PER_VERTEX, style::LayerKind::Line => stroke::FLOATS_PER_VERTEX,
library/map/src/main/rust/src/bridge.rs
diff --git a/library/map/src/main/rust/src/bridge.rs b/library/map/src/main/rust/src/bridge.rsindex d39c21e245..84167b68a9 100644--- a/library/map/src/main/rust/src/bridge.rs+++ b/library/map/src/main/rust/src/bridge.rs@@ -92,7 +92,7 @@ enum TileResult { /// Everything one map surface owns. Handed to Kotlin as an opaque `jlong`. struct MapHandle { renderer: Renderer,- layers: Vec<Layer>,+ layers: &'static [Layer], /// Meshes finished by the workers, waiting to be uploaded on the render thread. finished: Receiver<(u64, TileResult)>, /// Tiles the workers should fetch.
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.rsdeleted file mode 100644index 73fbbb0601..0000000000--- a/library/map/src/main/rust/src/style/expr.rs+++ /dev/null@@ -1,718 +0,0 @@-//! Evaluating MapLibre style expressions.-//!-//! Enough of the spec to render `style/basemap.json`, and deliberately no more. The-//! operators here are exactly the ones that file uses in `fill` and `line` layers, counted-//! from the file itself rather than guessed:-//!-//! | operator | uses | | operator | uses |-//! |---|---|---|---|---|-//! | `get` | 90 | | `literal` | 22 |-//! | `zoom` | 73 | | `case` | 16 |-//! | `interpolate` | 67 | | `coalesce` | 12 |-//! | `exponential` | 54 | | `step` | 5 |-//! | `in` | 37 | | `match` | 3 |-//! | `linear` | 13 | | comparisons | 65 |-//!-//! # Why this exists-//!-//! The previous version of this module was a hand-written table of constants approximating-//! the authored style. It could not converge: every fix revealed another mismatch, because-//! the real values — 34 `landuse` kinds, opacity ramps, per-kind colour cases — are already-//! written down in a file that MapLibre renders correctly. Transcribing a 71-layer style by-//! eye is not a strategy. Evaluating it is.-//!-//! # What is deliberately missing-//!-//! `concat`, `to-string` and the other string operators, because they appear only in-//! `text-field` on `symbol` layers, and labels are a later phase. An unknown operator is an-//! error rather than a silent default, so if that changes it will say so.--use serde_json::Value as Json;-use std::collections::HashMap;--/// A value flowing through an expression.-#[derive(Clone, Debug, PartialEq)]-pub enum Value {- Null,- Bool(bool),- Number(f64),- String(String),- /// A `["literal", [...]]` array, used as the haystack of `in`.- List(Vec<Value>),-}--impl Value {- pub fn as_number(&self) -> Option<f64> {- match self {- Value::Number(n) => Some(*n),- _ => None,- }- }-- pub fn as_str(&self) -> Option<&str> {- match self {- Value::String(s) => Some(s.as_str()),- _ => None,- }- }-- /// Truthiness, as the style spec defines it for `case` and the boolean operators.- pub fn truthy(&self) -> bool {- match self {- Value::Null => false,- Value::Bool(b) => *b,- Value::Number(n) => *n != 0.0 && !n.is_nan(),- Value::String(s) => !s.is_empty(),- Value::List(l) => !l.is_empty(),- }- }-- fn from_json(json: &Json) -> Value {- match json {- Json::Null => Value::Null,- Json::Bool(b) => Value::Bool(*b),- Json::Number(n) => Value::Number(n.as_f64().unwrap_or(0.0)),- Json::String(s) => Value::String(s.clone()),- Json::Array(items) => Value::List(items.iter().map(Value::from_json).collect()),- // An object has no expression meaning here; treat it as absent rather than- // inventing a representation for it.- Json::Object(_) => Value::Null,- }- }-}--/// What an expression is evaluated against: one feature, at one zoom.-///-/// `zoom` is separate from the properties because it is the camera's, not the feature's, and-/// it is what every `interpolate` in the style keys on.-pub struct Context<'a> {- pub zoom: f64,- pub properties: &'a HashMap<String, Value>,- /// `Point`, `LineString` or `Polygon`, for the legacy `["==", "$type", ...]` filter.- pub geometry_type: &'a str,-}--impl<'a> Context<'a> {- fn get(&self, key: &str) -> Value {- match key {- // The legacy filter spelling; `geometry-type` is the expression spelling.- "$type" => Value::String(self.geometry_type.to_string()),- _ => self.properties.get(key).cloned().unwrap_or(Value::Null),- }- }-}--pub type Result<T> = std::result::Result<T, String>;--/// Evaluate `expr` in `context`.-///-/// A plain JSON scalar evaluates to itself, so a paint property that is simply `"#80deea"`-/// or `0.5` needs no special case at the call site.-pub fn eval(expr: &Json, context: &Context) -> Result<Value> {- let items = match expr {- Json::Array(items) => items,- // Not an expression: a literal value.- other => return Ok(Value::from_json(other)),- };- let Some(op) = items.first().and_then(|v| v.as_str()) else {- // An array that does not start with an operator is a plain array value, which is- // what the inner array of `["literal", [...]]` looks like once unwrapped.- return Ok(Value::from_json(expr));- };- let args = &items[1..];-- match op {- "literal" => {- let arg = args.first().ok_or("literal needs an argument")?;- Ok(Value::from_json(arg))- }- "get" => {- let key = eval(args.first().ok_or("get needs a key")?, context)?;- let key = key.as_str().ok_or("get's key must be a string")?;- Ok(context.get(key))- }- "has" => {- let key = eval(args.first().ok_or("has needs a key")?, context)?;- let key = key.as_str().ok_or("has's key must be a string")?;- Ok(Value::Bool(context.get(key) != Value::Null))- }- "!has" => {- let key = eval(args.first().ok_or("!has needs a key")?, context)?;- let key = key.as_str().ok_or("!has's key must be a string")?;- Ok(Value::Bool(context.get(key) == Value::Null))- }- "zoom" => Ok(Value::Number(context.zoom)),- "geometry-type" => Ok(Value::String(context.geometry_type.to_string())),-- "all" => {- for arg in args {- if !eval(arg, context)?.truthy() {- return Ok(Value::Bool(false));- }- }- Ok(Value::Bool(true))- }- "any" => {- for arg in args {- if eval(arg, context)?.truthy() {- return Ok(Value::Bool(true));- }- }- Ok(Value::Bool(false))- }- "!" => {- let v = eval(args.first().ok_or("! needs an argument")?, context)?;- Ok(Value::Bool(!v.truthy()))- }-- // `in` has two shapes in this style: the legacy filter `["in", key, v1, v2, ...]`- // where the key is a bare property name, and the expression- // `["in", needle, ["literal", [...]]]`. They are told apart by the second argument- // being a haystack rather than a value.- "in" | "!in" => {- let negate = op == "!in";- let first = args.first().ok_or("in needs a needle")?;- let rest = &args[1..];-- let (needle, haystack) = if rest.len() == 1 {- let candidate = eval(&rest[0], context)?;- if let Value::List(items) = candidate {- (eval(first, context)?, items)- } else {- // A single non-list argument: legacy form with one candidate value.- (legacy_key(first, context)?, vec![candidate])- }- } else {- let mut haystack = Vec::with_capacity(rest.len());- for arg in rest {- haystack.push(eval(arg, context)?);- }- (legacy_key(first, context)?, haystack)- };- let found = haystack.contains(&needle);- Ok(Value::Bool(found != negate))- }-- "==" | "!=" | "<" | "<=" | ">" | ">=" => {- let lhs = legacy_key(args.first().ok_or("a comparison needs two sides")?, context)?;- let rhs = eval(args.get(1).ok_or("a comparison needs two sides")?, context)?;- compare(op, &lhs, &rhs)- }-- "coalesce" => {- for arg in args {- let v = eval(arg, context)?;- if v != Value::Null {- return Ok(v);- }- }- Ok(Value::Null)- }-- "case" => {- // Pairs of condition/output, then a final fallback.- let mut i = 0;- while i + 1 < args.len() {- if eval(&args[i], context)?.truthy() {- return eval(&args[i + 1], context);- }- i += 2;- }- eval(args.last().ok_or("case needs a fallback")?, context)- }-- "match" => {- let subject = eval(args.first().ok_or("match needs a subject")?, context)?;- let mut i = 1;- while i + 1 < args.len() {- // Labels are **literals**, not expressions — the spec requires it. Evaluating- // them would read `["a","b"]` as a call to an operator named `a`.- let label = Value::from_json(&args[i]);- // A label may be a single value or a list of alternatives.- let matched = match &label {- Value::List(alternatives) => alternatives.contains(&subject),- single => *single == subject,- };- if matched {- return eval(&args[i + 1], context);- }- i += 2;- }- eval(args.last().ok_or("match needs a fallback")?, context)- }-- "step" => {- // ["step", input, base, stop1, out1, stop2, out2, ...]- let input = eval(args.first().ok_or("step needs an input")?, context)?- .as_number()- .ok_or("step's input must be a number")?;- let mut chosen = args.get(1).ok_or("step needs a base output")?;- let mut i = 2;- while i + 1 < args.len() {- let stop = eval(&args[i], context)?- .as_number()- .ok_or("a step stop must be a number")?;- if input < stop {- break;- }- chosen = &args[i + 1];- i += 2;- }- eval(chosen, context)- }-- "interpolate" => interpolate(args, context),-- other => Err(format!("unsupported style expression operator `{other}`")),- }-}--/// The left-hand side of a legacy filter is a bare property name, not a `get`.-///-/// `["==", "kind", "park"]` means the *property* `kind`, while the expression form is-/// `["==", ["get", "kind"], "park"]`. Both appear in this style, so a bare string on the-/// left is read as a property lookup and anything else is evaluated normally.-fn legacy_key(arg: &Json, context: &Context) -> Result<Value> {- if let Json::String(key) = arg {- return Ok(context.get(key));- }- eval(arg, context)-}--fn compare(op: &str, lhs: &Value, rhs: &Value) -> Result<Value> {- let result = match op {- "==" => lhs == rhs,- "!=" => lhs != rhs,- _ => {- // Ordering only makes sense for numbers here; the style compares zoom and- // numeric properties.- let (a, b) = match (lhs.as_number(), rhs.as_number()) {- (Some(a), Some(b)) => (a, b),- // A missing property is not orderable, and the spec's answer is false rather- // than an error — a feature without the property simply does not match.- _ => return Ok(Value::Bool(false)),- };- match op {- "<" => a < b,- "<=" => a <= b,- ">" => a > b,- ">=" => a >= b,- _ => unreachable!("checked by the caller"),- }- }- };- Ok(Value::Bool(result))-}--/// `["interpolate", ["linear"] | ["exponential", base], input, stop, out, ...]`-fn interpolate(args: &[Json], context: &Context) -> Result<Value> {- let kind = args.first().ok_or("interpolate needs an interpolation type")?;- let base = match kind {- Json::Array(items) => match items.first().and_then(|v| v.as_str()) {- Some("linear") => 1.0,- Some("exponential") => items- .get(1)- .and_then(|v| v.as_f64())- .ok_or("exponential interpolation needs a base")?,- // `cubic-bezier` is not used by this style; erroring is better than silently- // interpolating it as linear and being subtly wrong everywhere.- other => return Err(format!("unsupported interpolation `{other:?}`")),- },- other => return Err(format!("unsupported interpolation `{other:?}`")),- };-- let input = eval(args.get(1).ok_or("interpolate needs an input")?, context)?- .as_number()- .ok_or("interpolate's input must be a number")?;-- let stops = &args[2..];- if stops.len() < 2 {- return Err("interpolate needs at least one stop".into());- }-- let stop_at = |i: usize| -> Result<f64> {- eval(&stops[i], context)?.as_number().ok_or_else(|| "a stop must be a number".into())- };-- // Below the first stop and above the last, the spec clamps.- if input <= stop_at(0)? {- return eval(&stops[1], context);- }- let last = stops.len() - 2;- if input >= stop_at(last)? {- return eval(&stops[last + 1], context);- }-- let mut i = 0;- while i + 3 < stops.len() {- let lower = stop_at(i)?;- let upper = stop_at(i + 2)?;- if input >= lower && input <= upper {- let span = upper - lower;- let t = if span <= 0.0 {- 0.0- } else if base == 1.0 {- (input - lower) / span- } else {- // The spec's exponential curve.- (base.powf(input - lower) - 1.0) / (base.powf(span) - 1.0)- };- let a = eval(&stops[i + 1], context)?;- let b = eval(&stops[i + 3], context)?;- return mix(&a, &b, t);- }- i += 2;- }- eval(&stops[last + 1], context)-}--/// Interpolate between two outputs. Numbers blend; colours are handled by the caller, which-/// knows to parse them.-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, 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() })- }- _ => Err("cannot interpolate between these value types".into()),- }-}--/// 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::*;-- fn ctx<'a>(- zoom: f64,- properties: &'a HashMap<String, Value>,- geometry_type: &'a str,- ) -> Context<'a> {- Context { zoom, properties, geometry_type }- }-- fn props(pairs: &[(&str, Value)]) -> HashMap<String, Value> {- pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()- }-- fn parse(source: &str) -> Json {- serde_json::from_str(source).expect("valid JSON")- }-- fn eval_str(source: &str, zoom: f64, properties: &[(&str, Value)]) -> Value {- let p = props(properties);- eval(&parse(source), &ctx(zoom, &p, "Polygon")).expect("evaluates")- }-- fn s(v: &str) -> Value {- Value::String(v.to_string())- }-- #[test]- fn a_plain_scalar_is_its_own_value() {- // So a paint property that is simply a colour or a number needs no special case.- assert_eq!(eval_str(r##""#80deea""##, 0.0, &[]), s("#80deea"));- assert_eq!(eval_str("0.5", 0.0, &[]), Value::Number(0.5));- }-- #[test]- fn get_reads_a_property_and_missing_is_null() {- assert_eq!(eval_str(r#"["get","kind"]"#, 0.0, &[("kind", s("park"))]), s("park"));- assert_eq!(eval_str(r#"["get","kind"]"#, 0.0, &[]), Value::Null);- }-- #[test]- fn has_and_not_has_follow_property_presence() {- // `!has` appears 32 times in this style, mostly to exclude tunnels and bridges.- assert_eq!(eval_str(r#"["has","is_tunnel"]"#, 0.0, &[("is_tunnel", Value::Bool(true))]), Value::Bool(true));- assert_eq!(eval_str(r#"["has","is_tunnel"]"#, 0.0, &[]), Value::Bool(false));- assert_eq!(eval_str(r#"["!has","is_tunnel"]"#, 0.0, &[]), Value::Bool(true));- }-- #[test]- fn the_legacy_filter_form_treats_a_bare_string_as_a_property() {- // `["==","kind","park"]` means the property, not the literal string "kind". Reading- // it as a literal makes every such filter compare "kind" to "park" and match nothing.- assert_eq!(- eval_str(r#"["==","kind","park"]"#, 0.0, &[("kind", s("park"))]),- Value::Bool(true),- );- assert_eq!(- eval_str(r#"["==","kind","park"]"#, 0.0, &[("kind", s("wood"))]),- Value::Bool(false),- );- // And the expression form must still work.- assert_eq!(- eval_str(r#"["==",["get","kind"],"park"]"#, 0.0, &[("kind", s("park"))]),- Value::Bool(true),- );- }-- #[test]- fn the_dollar_type_filter_reads_the_geometry_type() {- let p = props(&[]);- let expr = parse(r#"["==","$type","Polygon"]"#);- assert_eq!(eval(&expr, &ctx(0.0, &p, "Polygon")).unwrap(), Value::Bool(true));- assert_eq!(eval(&expr, &ctx(0.0, &p, "LineString")).unwrap(), Value::Bool(false));- }-- #[test]- fn in_supports_both_the_legacy_and_expression_forms() {- // Legacy: ["in", key, v1, v2, ...]- assert_eq!(- eval_str(r#"["in","kind","park","wood","grass"]"#, 0.0, &[("kind", s("wood"))]),- Value::Bool(true),- );- assert_eq!(- eval_str(r#"["in","kind","park","wood"]"#, 0.0, &[("kind", s("pier"))]),- Value::Bool(false),- );- // Expression: ["in", needle, ["literal", [...]]]- assert_eq!(- eval_str(- r#"["in",["get","kind"],["literal",["national_park","park"]]]"#,- 0.0,- &[("kind", s("national_park"))],- ),- Value::Bool(true),- );- assert_eq!(- eval_str(r#"["!in","kind","park"]"#, 0.0, &[("kind", s("wood"))]),- Value::Bool(true),- );- }-- #[test]- fn all_and_any_short_circuit_correctly() {- assert_eq!(- eval_str(- r#"["all",["==","kind","other"],["!has","is_tunnel"]]"#,- 0.0,- &[("kind", s("other"))],- ),- Value::Bool(true),- );- assert_eq!(- eval_str(- r#"["all",["==","kind","other"],["!has","is_tunnel"]]"#,- 0.0,- &[("kind", s("other")), ("is_tunnel", Value::Bool(true))],- ),- Value::Bool(false),- );- assert_eq!(eval_str(r#"["any",["==","kind","a"],["==","kind","b"]]"#, 0.0, &[("kind", s("b"))]), Value::Bool(true));- assert_eq!(eval_str(r#"["all"]"#, 0.0, &[]), Value::Bool(true), "an empty all is true");- assert_eq!(eval_str(r#"["any"]"#, 0.0, &[]), Value::Bool(false), "an empty any is false");- }-- #[test]- fn comparisons_on_a_missing_property_are_false_rather_than_an_error() {- // The style compares numeric properties that many features simply lack.- assert_eq!(eval_str(r#"[">=","min_zoom",5]"#, 0.0, &[]), Value::Bool(false));- assert_eq!(eval_str(r#"["<","min_zoom",5]"#, 0.0, &[]), Value::Bool(false));- assert_eq!(- eval_str(r#"[">=","min_zoom",5]"#, 0.0, &[("min_zoom", Value::Number(7.0))]),- Value::Bool(true),- );- }-- #[test]- fn case_picks_the_first_true_arm_and_falls_back() {- let expr = r##"["case",["==","kind","park"],"#9cd3b4",["==","kind","wood"],"#a0d9a0","#e2dfda"]"##;- assert_eq!(eval_str(expr, 0.0, &[("kind", s("park"))]), s("#9cd3b4"));- assert_eq!(eval_str(expr, 0.0, &[("kind", s("wood"))]), s("#a0d9a0"));- assert_eq!(eval_str(expr, 0.0, &[("kind", s("pier"))]), s("#e2dfda"), "the fallback");- }-- #[test]- fn match_supports_list_labels_and_a_fallback() {- // The landcover colour expression is a `match` whose arms are single values.- let expr = r#"["match",["get","kind"],"grassland","rgba(210,239,207,1)","barren","rgba(255,243,215,1)","rgba(196,231,210,1)"]"#;- assert_eq!(eval_str(expr, 0.0, &[("kind", s("grassland"))]), s("rgba(210,239,207,1)"));- assert_eq!(eval_str(expr, 0.0, &[("kind", s("barren"))]), s("rgba(255,243,215,1)"));- assert_eq!(eval_str(expr, 0.0, &[("kind", s("wetland"))]), s("rgba(196,231,210,1)"));- // A label that is itself a list means "any of these".- let listed = r#"["match",["get","kind"],["a","b"],"hit","miss"]"#;- assert_eq!(eval_str(listed, 0.0, &[("kind", s("b"))]), s("hit"));- assert_eq!(eval_str(listed, 0.0, &[("kind", s("c"))]), s("miss"));- }-- #[test]- fn step_holds_each_output_until_the_next_stop() {- // `["step", ["zoom"], base, 6, a, 10, b]`- let expr = r#"["step",["zoom"],0,6,1,10,2]"#;- assert_eq!(eval_str(expr, 0.0, &[]), Value::Number(0.0), "below the first stop");- assert_eq!(eval_str(expr, 5.9, &[]), Value::Number(0.0));- assert_eq!(eval_str(expr, 6.0, &[]), Value::Number(1.0), "inclusive at the stop");- assert_eq!(eval_str(expr, 9.9, &[]), Value::Number(1.0));- assert_eq!(eval_str(expr, 10.0, &[]), Value::Number(2.0));- assert_eq!(eval_str(expr, 22.0, &[]), Value::Number(2.0));- }-- #[test]- fn linear_interpolation_matches_the_landcover_opacity_ramp() {- // The real expression, and the one whose absence painted a green blanket over the- // whole map: opacity 1 at z5 falling to 0 at z7.- let expr = r#"["interpolate",["linear"],["zoom"],5,1,7,0]"#;- assert_eq!(eval_str(expr, 4.0, &[]).as_number().unwrap(), 1.0, "clamped below");- assert_eq!(eval_str(expr, 5.0, &[]).as_number().unwrap(), 1.0);- assert!((eval_str(expr, 6.0, &[]).as_number().unwrap() - 0.5).abs() < 1e-9, "halfway");- assert_eq!(eval_str(expr, 7.0, &[]).as_number().unwrap(), 0.0);- assert_eq!(eval_str(expr, 15.0, &[]).as_number().unwrap(), 0.0, "clamped above");- }-- #[test]- fn the_landuse_opacity_ramp_keeps_it_off_at_world_zoom() {- // 0 at z6 rising to 1 at z11. Ignoring this drew continent-sized national parks at- // world zoom, whose tile-clipped edges looked like cuts slashed across the map.- let expr = r#"["interpolate",["linear"],["zoom"],6,0,11,1]"#;- assert_eq!(eval_str(expr, 1.0, &[]).as_number().unwrap(), 0.0);- assert_eq!(eval_str(expr, 6.0, &[]).as_number().unwrap(), 0.0);- assert!((eval_str(expr, 8.5, &[]).as_number().unwrap() - 0.5).abs() < 1e-9);- assert_eq!(eval_str(expr, 11.0, &[]).as_number().unwrap(), 1.0);- assert_eq!(eval_str(expr, 20.0, &[]).as_number().unwrap(), 1.0);- }-- #[test]- fn exponential_interpolation_matches_a_real_line_width_ramp() {- // `roads_runway`: ["interpolate",["exponential",1.6],["zoom"],10,0,12,4,18,30]- let expr = r#"["interpolate",["exponential",1.6],["zoom"],10,0,12,4,18,30]"#;- assert_eq!(eval_str(expr, 9.0, &[]).as_number().unwrap(), 0.0, "clamped below");- assert_eq!(eval_str(expr, 10.0, &[]).as_number().unwrap(), 0.0);- assert_eq!(eval_str(expr, 12.0, &[]).as_number().unwrap(), 4.0, "exactly on a stop");- assert_eq!(eval_str(expr, 18.0, &[]).as_number().unwrap(), 30.0);- assert_eq!(eval_str(expr, 22.0, &[]).as_number().unwrap(), 30.0, "clamped above");-- // Between stops the curve is below the straight line, which is the whole point of an- // exponential base above 1.- let midpoint = eval_str(expr, 11.0, &[]).as_number().unwrap();- assert!(midpoint > 0.0 && midpoint < 2.0, "got {midpoint}, expected under the linear 2.0");- }-- #[test]- fn interpolation_between_colour_stops_does_not_error() {- // Colour ramps exist in this style; the numeric path must not be the only one.- let expr = r##"["interpolate",["linear"],["zoom"],0,"#000000",10,"#ffffff"]"##;- assert_eq!(eval_str(expr, 0.0, &[]), s("#000000"));- assert_eq!(eval_str(expr, 10.0, &[]), s("#ffffff"));- assert!(matches!(eval_str(expr, 5.0, &[]), Value::String(_)));- }-- #[test]- fn coalesce_takes_the_first_present_value() {- assert_eq!(- eval_str(r#"["coalesce",["get","name:en"],["get","name"],""]"#, 0.0, &[("name", s("Paris"))]),- s("Paris"),- );- assert_eq!(- eval_str(r#"["coalesce",["get","a"],["get","b"]]"#, 0.0, &[]),- Value::Null,- );- }-- #[test]- fn an_unknown_operator_is_an_error_rather_than_a_silent_default() {- // Silently defaulting would render a subtly wrong map with nothing to indicate why,- // which is the failure mode this whole module exists to end.- let p = props(&[]);- let expr = parse(r#"["cubic-bezier",0,0,1,1]"#);- let error = eval(&expr, &ctx(0.0, &p, "Polygon")).expect_err("must not be silently ignored");- assert!(error.contains("cubic-bezier"), "unhelpful message: {error}");- }-- #[test]- fn truthiness_follows_the_spec() {- assert!(!Value::Null.truthy());- assert!(!Value::Bool(false).truthy());- assert!(Value::Bool(true).truthy());- assert!(!Value::Number(0.0).truthy());- assert!(Value::Number(1.0).truthy());- 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 669298f2c8..c4ac678428 100644--- a/library/map/src/main/rust/src/style/mod.rs+++ b/library/map/src/main/rust/src/style/mod.rs@@ -1,41 +1,36 @@ //! Which layers are drawn, in what order, in what colour - in light and dark. //!-//! # Where the fills come from+//! # Where the layers come from //!-//! 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.+//! `style/basemap.flat.json`, one authored entry per drawn layer, read by [`paint`]. Order in+//! the file **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 renderer draws+//! layer-major across all tiles rather than tile-major across all layers. //!-//! 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-//! renderer draws layer-major across all tiles rather than tile-major across all layers.+//! That file replaced a runtime interpretation of `style/basemap.json`, a 71-layer MapLibre+//! style: an expression evaluator, a filter reader, and a derivation that expanded one+//! data-driven layer into several because fill colour reaches the GPU as one push constant per+//! draw. All of it existed to reduce a general style to the seven properties this renderer+//! actually supports, and the last two rendering bugs lived in that reduction. The flat file+//! **is** one layer per colour, authored, so there is nothing left to derive — and+//! `paint::the_flat_style_agrees_with_basemap_json` cross-checks every value that exists in+//! both files, which is what keeps writing values down from becoming a third failed+//! transcription. //! //! # Where the colours come from //!-//! Not from a third-party style. `maps/src/main/java/com/vayunmathur/maps/ui/theme/BasemapPalette.kt`-//! already owns a **contrast-checked dark palette for this exact archive**, and its module-//! docs explain the reasoning: a road label does not sit on a surface, it sits on the-//! basemap, so deriving basemap colours from the Material scheme "would let an unlucky-//! accent produce grey-on-grey terrain". Light mode there is the bundled Protomaps style's-//! own paint and "the runtime recolour is what dark mode is".+//! Light is the bundled Protomaps style's own paint, except on lines — see [`paint`]'s docs for+//! that exception. Dark is not from a third-party style:+//! `maps/src/main/java/com/vayunmathur/maps/ui/theme/BasemapPalette.kt` already owns a+//! **contrast-checked dark palette for this exact archive**, and its module docs explain the+//! reasoning: a road label does not sit on a surface, it sits on the basemap, so deriving+//! basemap colours from the Material scheme "would let an unlucky accent produce grey-on-grey+//! terrain". //!-//! So the dark values here are `BasemapPalette.darkFill`'s, by role, and the light ones-//! are the Protomaps paint. Two consequences worth having: the schema matches by-//! construction — these are the colours written for `v4.pmtiles`' own layer names — and-//! the five consumer apps end up looking like the same product as `maps` rather than-//! merely adjacent to it.+//! So the dark values in the flat file are `BasemapPalette.darkFill`'s, by role. Two+//! consequences worth having: the schema matches by construction — these are the colours+//! written for `v4.pmtiles`' own layer names — and the five consumer apps end up looking like+//! the same product as `maps` rather than merely adjacent to it. //! //! # Switching variants is free //!@@ -44,9 +39,10 @@ //! is why this is a runtime switch rather than a startup choice: the app can follow the //! system theme. -pub mod expr; pub mod paint; +use paint::{Ramp, Stroke};+ /// What pipeline a layer draws with. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum LayerKind {@@ -77,7 +73,7 @@ impl Variant { /// recede so a colour-ramp overlay drawn on top of it stays readable. It is **derived** /// rather than authored — every colour is blended toward the background by /// [`MUTED_BLEND`] — which is what muting a basemap does, and it means there is one-/// palette to keep correct rather than four. Phase 3 may author it properly.+/// palette to keep correct rather than four. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct Palette { pub variant: Variant,@@ -106,63 +102,81 @@ fn blend(color: u32, toward: u32, amount: f32) -> u32 { (color & 0xFF00_0000) | (mix(16) << 16) | (mix(8) << 8) | mix(0) } -/// One drawn layer.+/// One drawn layer, as the flat style file states it. pub struct Layer {- pub id: &'static str,- /// The MVT layer to read, e.g. `roads`.- pub source_layer: &'static str,+ pub id: String,+ /// The tile layer to read, e.g. `roads`.+ pub source_layer: String, pub kind: LayerKind, /// Feature `kind` values to draw, or empty for every feature in the layer.- pub kinds: &'static [&'static str],- /// ARGB in light mode: the Protomaps style's own paint.+ pub kinds: Vec<String>,+ /// ARGB in light mode. pub light: u32,- /// ARGB in dark mode, from `BasemapPalette`'s contrast-checked palette.+ /// ARGB in dark mode. pub dark: u32,- /// Stroke width in Dp. Ignored by fills, and superseded per frame by- /// [`line_paint`](Self::line_paint)'s ramps wherever that is set.- pub width_dp: f32,- /// Gap between the two halves of a casing, in Dp. Non-zero turns the stroke into two- /// bands standing off the centreline — how 17 layers of the real style draw road- /// casings.- ///- /// Still load-bearing as a *boolean* even when [`line_paint`](Self::line_paint) supplies- /// the distance: [`gapped`](Self::gapped) reads it, and that is what decides at- /// tessellation time whether one centred band is emitted or two offset ones. A layer- /// whose ramp has a gap but whose constant is zero would tessellate a plain stroke and- /// silently discard the gap.- pub gap_width_dp: f32,- /// Authored `line` layer ids whose width ramps govern this layer, most specific first.+ /// Fill opacity, in 0..=1. Always 1 for a line. ///- /// Empty means the constants above stand. More than one is how the authored style's- /// `*_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 —+ /// Applied per frame against the camera's fractional zoom rather than folded into+ /// [`light`](Self::light)/[`dark`](Self::dark), because a fill has to fade *across* a zoom: /// 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,+ /// z6 where the ramp asks for half.+ pub opacity: Ramp,+ /// Stroke width in Dp. Zero for a fill.+ pub width: Ramp,+ /// Gap between the two halves of a casing, in Dp.+ ///+ /// Non-zero turns the stroke into two bands standing off the centreline — how the real+ /// style draws road casings. Whether there is a gap *at all* is decided once, at+ /// tessellation time, by [`gapped`](Self::gapped).+ pub gap_width: Ramp, /// Dash and gap lengths in line widths, as `line-dasharray` defines them. pub dash: (f32, f32), pub min_zoom: u8, pub max_zoom: u8,+ /// The `style/basemap.json` layer this was transcribed from.+ ///+ /// Provenance, and the key the cross-check test joins the two files on — see+ /// [`paint::tests::the_flat_style_agrees_with_basemap_json`]. Nothing in the render path+ /// reads it.+ pub authored: String, } impl Layer { /// Does this layer draw a feature whose `kind` is `kind`? pub fn matches(&self, kind: Option<&str>) -> bool {- self.kinds.is_empty() || kind.is_some_and(|k| self.kinds.contains(&k))+ self.kinds.is_empty() || kind.is_some_and(|k| self.kinds.iter().any(|own| own == k)) } + /// Is this layer worth asking the archive for at `zoom`?+ ///+ /// A data-and-cost gate, not paint: it says which pyramid levels carry the layer. Paint is+ /// [`stroke`](Self::stroke) and [`opacity_at`](Self::opacity_at), which follow the *camera*.+ /// Deriving this from the opacity ramp instead 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. pub fn draws_at(&self, zoom: u8) -> bool { zoom >= self.min_zoom && zoom <= self.max_zoom } /// A casing: two bands offset either side of the centreline.+ ///+ /// Read at tessellation time, so it cannot vary with zoom — one geometry has to serve every+ /// frame. A layer whose ramp has a gap but which tessellates a plain stroke would discard+ /// the pushed gap silently, which is why this is the ramp's peak rather than its value+ /// anywhere in particular. pub fn gapped(&self) -> bool {- self.gap_width_dp > 0.0+ self.gap_width.peak() > 0.0+ }++ /// The stroke this layer draws at `zoom`, in Dp.+ pub fn stroke(&self, zoom: f64) -> Stroke {+ Stroke { width_dp: self.width.at(zoom), gap_width_dp: self.gap_width.at(zoom) }+ }++ /// The fill opacity this layer draws at `zoom`, in 0..=1.+ pub fn opacity_at(&self, zoom: f64) -> f32 {+ self.opacity.at(zoom).clamp(0.0, 1.0) } pub fn color(&self, palette: Palette) -> u32 {@@ -187,7 +201,7 @@ impl Layer { /// competing detail, not less geography: `weather`'s overlay is meaningless without a /// recognisable coastline under it. fn is_base(&self) -> bool {- matches!(self.source_layer, "earth" | "water")+ matches!(self.source_layer.as_str(), "earth" | "water") } } @@ -198,284 +212,19 @@ impl Layer { /// likely to be sea than land — so an unloaded map should read as ocean with land appearing /// on top of it, rather than the reverse. pub fn background(variant: Variant) -> u32 {+ let (light, dark) = paint::style().background; match variant {- // The authored style's own `water` paint.- Variant::Light => 0xFF80DEEA,- // BasemapPalette.Fill.Water.- Variant::Dark => 0xFF0D1B2A,- }-}--const NO_DASH: (f32, f32) = (0.0, 0.0);--/// A shorthand for the many fields a [`Layer`] has that most layers do not set.-const fn layer(- id: &'static str,- source_layer: &'static str,- kind: LayerKind,- kinds: &'static [&'static str],- light: u32,- dark: u32,-) -> Layer {- Layer {- id,- source_layer,- kind,- kinds,- light,- dark,- width_dp: 0.0,- gap_width_dp: 0.0,- line_paint: &[],- fill_paint: "",- dash: NO_DASH,- min_zoom: 0,- max_zoom: 22,+ Variant::Light => light,+ Variant::Dark => dark, } } -/// The dark colour of each authored fill layer, RGB only.-///-/// `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)];--/// 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)-}- /// Every layer the renderer draws, in draw order. ///-/// 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![- // 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- // land behind them is also dark.- //- // The widths below are the fallback only: `line_paint` names the authored ramps that- // actually size these strokes, and the constants are what a road would be if the- // authored file stopped naming it.- Layer {- width_dp: 1.0,- gap_width_dp: 3.0,- min_zoom: 13,- line_paint: &["roads_minor_casing"],- ..layer(- "roads-minor-casing",- "roads",- LayerKind::Line,- &["minor_road", "other"],- 0xFFD5D0C6,- 0xFF111318,- )- },- Layer {- width_dp: 1.0,- gap_width_dp: 4.5,- min_zoom: 9,- line_paint: &["roads_major_casing_early", "roads_major_casing_late"],- ..layer(- "roads-major-casing",- "roads",- LayerKind::Line,- &["major_road"],- 0xFFD8C9A6,- 0xFF111318,- )- },- Layer {- width_dp: 1.25,- gap_width_dp: 6.0,- line_paint: &["roads_highway_casing_early", "roads_highway_casing_late"],- ..layer(- "roads-highway-casing",- "roads",- LayerKind::Line,- &["highway"],- 0xFFE0B96A,- 0xFF111318,- )- },- Layer {- width_dp: 1.0,- dash: (2.0, 1.5),- min_zoom: 15,- // The authored layer that draws `path`, alongside `other`.- line_paint: &["roads_other"],- ..layer("roads-path", "roads", LayerKind::Line, &["path"], 0xFFC7BFAE, 0xFF26282E)- },- Layer {- width_dp: 3.0,- min_zoom: 13,- line_paint: &["roads_minor"],- ..layer(- "roads-minor",- "roads",- LayerKind::Line,- &["minor_road", "other"],- 0xFFFFFFFF,- 0xFF34383F,- )- },- Layer {- width_dp: 4.5,- min_zoom: 9,- line_paint: &["roads_major"],- ..layer(- "roads-major",- "roads",- LayerKind::Line,- &["major_road"],- 0xFFFFF8E6,- 0xFF464B54,- )- },- Layer {- width_dp: 6.0,- line_paint: &["roads_highway"],- ..layer("roads-highway", "roads", LayerKind::Line, &["highway"], 0xFFFFE9B0, 0xFF464B54)- },- Layer {- width_dp: 1.0,- dash: (3.0, 3.0),- min_zoom: 13,- line_paint: &["roads_rail"],- ..layer("roads-rail", "roads", LayerKind::Line, &["rail"], 0xFFC0BAB0, 0xFF3A3E45)- },- // The degenerate dash case: `boundaries_country` produces [2, 0] through a `step`,- // and a zero gap has to render solid. See line.frag.- Layer {- width_dp: 1.0,- dash: (2.0, 0.0),- // One layer stands in for the authored `boundaries_country`/`boundaries` pair,- // which differ by `kind_detail`; the country lines are what carries the map at- // the zooms where boundaries dominate.- line_paint: &["boundaries_country"],- ..layer("boundaries", "boundaries", LayerKind::Line, &[], 0xFFA8A296, 0xFF4A4F57)- },- ]+/// A borrow rather than a fresh list: the flat style is a constant table that happens to need a+/// parser, so it is parsed once for the process and handed out.+pub fn layers() -> &'static [Layer] {+ &paint::style().layers } #[cfg(test)]@@ -490,110 +239,82 @@ mod tests { 0.2126 * r + 0.7152 * g + 0.0722 * b } + fn find(id: &str) -> &'static Layer {+ layers().iter().find(|l| l.id == id).unwrap_or_else(|| panic!("{id}"))+ }+ #[test] fn landcover_is_a_low_zoom_tint_and_stops_before_street_level() {- // 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();+ // The opacity ramp is the only thing that gates landcover. Drawing it at every zoom —+ // which a transcribed table with no ramp to read did — lays a blanket over the map that+ // follows vegetation polygons rather than coastlines or borders, so it lines up with+ // nothing. let landcovers: Vec<&Layer> =- layers.iter().filter(|l| l.source_layer == "landcover").collect();+ 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!(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);+ assert!(l.opacity_at(4.0) > 0.0, "{} should tint low zooms", l.id);+ assert_eq!(l.opacity_at(7.0), 0.0, "{} is at zero opacity by z7", l.id);+ assert_eq!(l.opacity_at(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.+ /// The other half of the same story: `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");+ layers().iter().filter(|l| l.id.starts_with("landuse_park")).collect();+ assert_eq!(parks.len(), 4, "one layer per authored colour"); 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);+ assert_eq!(l.opacity_at(6.0), 0.0, "{} is at zero opacity at z6", l.id);+ assert_eq!(l.opacity_at(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.+ /// The gate that decides whether geometry is *built* must not come from the opacity ramp:+ /// `min_zoom` is compared against the **tile's** pyramid level while the ramp follows the+ /// **camera**. See [`Layer::draws_at`] for what deriving one from the other did. Only+ /// `buildings` carries a floor, and that one is a cost decision — it is the densest layer in+ /// the schema, so a tessellation pass plus a draw call per tile is worth avoiding even where+ /// the archive would return nothing. #[test]- fn a_fills_zoom_range_is_not_derived_from_its_opacity_ramp() {+ fn only_a_declared_cost_floor_gates_a_fill_by_zoom() { 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);+ let expected = if l.id == "buildings" { 14 } else { 0 }; assert_eq!( (l.min_zoom, l.max_zoom),- (floor, paint::MAX_ZOOM),+ (expected, 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.+ /// Spot-checked against the authored values rather than asserting a count, so a restyle+ /// changes one colour rather than breaking the test. Every colour is cross-checked against+ /// `basemap.json` wholesale by `paint::the_flat_style_agrees_with_basemap_json`. #[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);+ assert_eq!(find("earth").light, 0xFFE2DFDA, "the authored `#e2dfda`");+ assert_eq!(find("water").light, 0xFF80DEEA, "the authored `#80deea`");+ // A `match` arm the authored file writes as `rgba(210, 239, 207, 1)`.+ assert_eq!(find("landcover:grassland").light, 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);+ assert_eq!(find("landuse_park:military").light, 0xFFC6DCDC);+ // Opacity is a per-frame ramp, not a baked alpha.+ assert_eq!(find("buildings").light, 0xFFCCCCCC);+ assert_eq!(find("landuse_urban_green").light, 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.+ /// A kind the authored `case` gives its own colour has its own layer, and a kind that shares+ /// a colour with another sits in the same layer rather than adding a draw. #[test]- fn a_data_driven_fill_becomes_one_layer_per_colour() {- let layers = layers();+ fn a_data_driven_fill_is_one_layer_per_colour() { 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<_>>());+ layers().iter().filter(|l| l.id.starts_with("landuse_park")).collect(); 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"));@@ -606,15 +327,14 @@ mod tests { // most of what makes a low zoom readable: it is why the Sahara does not look like the // Congo. Collapsing a palette's whole column to one literal paints every landmass a // single flat tint that follows vegetation polygons and lines up with nothing.- let layers = layers(); for palette in [Palette::new(false, false), Palette::new(true, false)] { let mut seen: Vec<(u32, &str)> = Vec::new();- for l in layers.iter().filter(|l| l.source_layer == "landcover") {+ for l in layers().iter().filter(|l| l.source_layer == "landcover") { let colour = l.color(palette); if let Some((_, other)) = seen.iter().find(|(c, _)| *c == colour) { panic!("{} and {} share {colour:#010X} in {palette:?}", l.id, other); }- seen.push((colour, l.id));+ seen.push((colour, &l.id)); } assert_eq!(seen.len(), 7, "every authored `match` arm needs a layer here"); }@@ -624,9 +344,8 @@ mod tests { fn landcover_kinds_are_lighter_than_the_earth_they_tint() { // A tint sits *on* the land, so in light mode it must not be darker than the land // itself or it reads as a separate landmass.- let layers = layers();- let earth = layers.iter().find(|l| l.id == "earth").expect("earth");- for l in layers.iter().filter(|l| l.source_layer == "landcover") {+ let earth = find("earth");+ for l in layers().iter().filter(|l| l.source_layer == "landcover") { assert!( luminance(l.light) > luminance(earth.light) - 0.06, "{} is darker than earth, so it reads as land rather than a tint",@@ -637,11 +356,10 @@ mod tests { #[test] fn the_unfiltered_landcover_layer_is_drawn_first_so_specific_kinds_win() {- // The authored style's `match` has a fallback arm; here that is a separate- // unfiltered layer, which only behaves like a fallback if it draws under nothing- // else — i.e. it must come first, before the kind-specific ones paint over it.- let layers = layers();- let indices: Vec<(usize, &Layer)> = layers+ // The authored style's `match` has a fallback arm; here that is a separate unfiltered+ // layer, which only behaves like a fallback if it draws under nothing else — i.e. it+ // must come first, before the kind-specific ones paint over it.+ let indices: Vec<(usize, &Layer)> = layers() .iter() .enumerate() .filter(|(_, l)| l.source_layer == "landcover")@@ -660,11 +378,10 @@ mod tests { } #[test]- fn casings_are_drawn_under_their_fills() {- // Order is draw order, and the renderer draws layer-major so it holds across- // tiles. A casing drawn after its fill would outline the road on top of itself.- let layers = layers();- let index = |id: &str| layers.iter().position(|l| l.id == id).expect(id);+ fn draw_order_is_the_order_in_the_file() {+ // Order is draw order, and the renderer draws layer-major so it holds across tiles. A+ // casing drawn after its fill would outline the road on top of itself.+ let index = |id: &str| layers().iter().position(|l| l.id == id).expect(id); for kind in ["minor", "major", "highway"] { assert!( index(&format!("roads-{kind}-casing")) < index(&format!("roads-{kind}")),@@ -673,21 +390,17 @@ mod tests { } assert!(index("earth") < index("water"), "water draws over earth"); assert!(index("water") < index("roads-major"), "roads draw over water");- }-- #[test]- fn a_casing_is_gapped_and_a_plain_stroke_is_not() {- let layers = layers();- let find = |id: &str| layers.iter().find(|l| l.id == id).expect(id);- assert!(find("roads-major-casing").gapped());- assert!(!find("roads-major").gapped());- assert!(!find("earth").gapped());+ // 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.+ assert!(index("landuse_park:national_park") < index("water"));+ assert!(index("landuse_runway") < index("water"));+ assert!(index("water") < index("landuse_pedestrian"));+ assert!(index("landuse_pier") < index("buildings")); } #[test] fn the_kind_filter_is_a_whitelist_and_empty_means_everything() {- let layers = layers();- let find = |id: &str| layers.iter().find(|l| l.id == id).expect(id); let highway = find("roads-highway"); assert!(highway.matches(Some("highway"))); assert!(!highway.matches(Some("major_road")));@@ -700,8 +413,6 @@ mod tests { #[test] fn zoom_ranges_gate_the_expensive_layers() {- let layers = layers();- let find = |id: &str| layers.iter().find(|l| l.id == id).expect(id); // Buildings are the densest layer in the schema, so they stay off until they are // worth drawing. assert!(!find("buildings").draws_at(13));@@ -712,31 +423,20 @@ mod tests { #[test] fn the_degenerate_dash_is_present_so_the_shader_path_is_exercised() {- let layers = layers();- let boundaries = layers.iter().find(|l| l.id == "boundaries").expect("boundaries");- assert_eq!(boundaries.dash, (2.0, 0.0), "the [2, 0] pattern must reach the shader");+ // `boundaries_country`'s authored `[2, 0]`: a zero gap has to render solid. See+ // line.frag.+ assert_eq!(find("boundaries").dash, (2.0, 0.0)); } #[test] fn every_layer_id_is_unique() {- let layers = layers();- let mut ids: Vec<&str> = layers.iter().map(|l| l.id).collect();+ let mut ids: Vec<&str> = layers().iter().map(|l| l.id.as_str()).collect(); ids.sort_unstable(); let count = ids.len(); ids.dedup(); assert_eq!(count, ids.len(), "layer ids are used as identities"); } - #[test]- fn a_line_layer_has_a_width_and_a_fill_does_not() {- for l in layers() {- match l.kind {- LayerKind::Line => assert!(l.width_dp > 0.0, "{} needs a width", l.id),- LayerKind::Fill => assert_eq!(l.width_dp, 0.0, "{} is a fill", l.id),- }- }- }- // --- light and dark ---------------------------------------------------- #[test]@@ -745,9 +445,9 @@ mod tests { // background, which is the single most visible way to get this wrong. for l in layers() { assert_ne!(l.light, l.dark, "{} has the same colour in both variants", l.id);- // Translucency is legitimate — the authored style draws buildings at- // `fill-opacity` 0.5 — but a fully transparent layer is a layer that silently- // does nothing.+ // Translucency is legitimate — buildings draw at 0.5 — but that lives in the+ // opacity ramp, so a fully transparent colour is a layer that silently does+ // nothing. assert!(l.light >> 24 > 0, "{} light colour is fully transparent", l.id); assert!(l.dark >> 24 > 0, "{} dark colour is fully transparent", l.id); }@@ -759,9 +459,7 @@ mod tests { // BasemapPalette's Background, which is a hair from its Water, so the whole map was a // flat navy field with no coastline. Asserted in every variant *and* muted, because // muting pulls colours toward the background and could collapse them again.- let layers = layers();- let earth = layers.iter().find(|l| l.id == "earth").expect("earth");- let water = layers.iter().find(|l| l.id == "water").expect("water");+ let (earth, water) = (find("earth"), find("water")); for dark in [false, true] { for muted in [false, true] { let palette = Palette::new(dark, muted);@@ -779,9 +477,7 @@ mod tests { fn the_backdrop_is_the_ocean_rather_than_the_land() { // An unloaded map should read as sea with land appearing on top, so a gap in coverage // never looks like a continent.- let layers = layers();- let earth = layers.iter().find(|l| l.id == "earth").expect("earth");- let water = layers.iter().find(|l| l.id == "water").expect("water");+ let (earth, water) = (find("earth"), find("water")); for variant in [Variant::Light, Variant::Dark] { let backdrop = background(variant); let palette = Palette { variant, muted: false };@@ -826,10 +522,9 @@ mod tests { #[test] fn roads_stay_legible_against_the_land_behind_them() {- // The reason BasemapPalette exists: a road has to read against the terrain, and in- // dark mode both are dark. Assert real separation rather than merely different hex.- let layers = layers();- let find = |id: &str| layers.iter().find(|l| l.id == id).expect(id);+ // The reason BasemapPalette exists, and the reason the line colours are the app's own+ // rather than the authored white-on-grey: a road has to read against the terrain, and+ // in dark mode both are dark. Assert real separation rather than merely different hex. for dark in [false, true] { let palette = Palette::new(dark, false); let land = background(palette.variant);@@ -848,12 +543,11 @@ mod tests { fn muting_moves_every_colour_toward_the_background() { // What weather needs, and what Positron gave it: the basemap recedes so a colour // ramp on top of it stays readable.- let layers = layers(); for dark in [false, true] { let plain = Palette::new(dark, false); let muted = Palette::new(dark, true); let land = background(plain.variant);- for l in &layers {+ for l in layers() { let before = distance(l.color(plain), land); let after = distance(l.color(muted), land); assert!(@@ -863,7 +557,7 @@ mod tests { ); } // And it actually does something measurable to a high-contrast layer.- let road = layers.iter().find(|l| l.id == "roads-major").expect("roads-major");+ let road = find("roads-major"); assert!( distance(road.color(muted), land) < distance(road.color(plain), land) * 0.75, "muting barely changed roads-major, dark={dark}",@@ -891,12 +585,7 @@ mod tests { // `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!(paint::authored_fills().opacity(buildings, 16.0), 0.5);+ assert_eq!(find("buildings").opacity_at(16.0), 0.5); } #[test]@@ -904,8 +593,6 @@ mod tests { // In dark mode the casing is what separates two adjacent roads, since the land // behind them is dark too. A casing lighter than its road would read as a second // road.- let layers = layers();- let find = |id: &str| layers.iter().find(|l| l.id == id).expect(id); let dark = Palette::new(true, false); for kind in ["minor", "major", "highway"] { let casing = luminance(find(&format!("roads-{kind}-casing")).color(dark));@@ -915,22 +602,20 @@ mod tests { } #[test]- fn switching_variant_changes_no_geometry() {- // Colour is a push constant and the layer set is identical, so a variant switch- // re-tessellates and re-uploads nothing. This pins that: the two lists must agree- // on everything except colour.- let light = layers();- let dark = layers();- assert_eq!(light.len(), dark.len());- for (a, b) in light.iter().zip(dark.iter()) {- assert_eq!(a.id, b.id);- assert_eq!(a.source_layer, b.source_layer);- assert_eq!(a.kind, b.kind);- assert_eq!(a.kinds, b.kinds);- assert_eq!(a.width_dp, b.width_dp);- assert_eq!(a.gap_width_dp, b.gap_width_dp);- assert_eq!(a.dash, b.dash);- assert_eq!((a.min_zoom, a.max_zoom), (b.min_zoom, b.max_zoom));+ fn a_variant_switch_changes_hue_and_nothing_else() {+ // Colour is a push constant and the layer set is one table read by both variants, so a+ // switch re-tessellates and re-uploads nothing. What could still go wrong is a variant+ // changing *alpha*, which changes blending rather than geometry — and would mean the+ // dark column had smuggled an opacity decision out of the ramp.+ for l in layers() {+ for muted in [false, true] {+ assert_eq!(+ l.color(Palette::new(false, muted)) >> 24,+ l.color(Palette::new(true, muted)) >> 24,+ "{} changes alpha with the variant",+ l.id,+ );+ } } } }
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 36b158c757..60967c0b1c 100644--- a/library/map/src/main/rust/src/style/paint.rs+++ b/library/map/src/main/rust/src/style/paint.rs@@ -1,62 +1,71 @@-//! Paint read from the authored style instead of transcribed into constants.+//! The flat style: a file that says only what this renderer can draw, and a loader for it. //!-//! 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-//! and grows, which is how the authored style both scales roads and gates them on. A single-//! number cannot express that, and no choice of number can — one that reads correctly at-//! street level is continent-wide at world level.+//! `style/basemap.flat.json` is one entry per drawn layer, in draw order, with a fixed set of+//! properties: a source layer, a `kind` whitelist, a zoom range, a light and a dark colour, and+//! opacity, width, gap width and dash. Nothing is derived at runtime and there are no+//! expressions — a property that varies with zoom is a list of stops and an interpolation, and+//! that is the only shape a property can take. //!-//! So the ramps are kept unevaluated here and evaluated per frame against the camera. That is-//! affordable because width reaches the GPU as a push constant and `shaders/line.vert`-//! extrudes the centreline to it, so a width that changes every frame re-tessellates-//! nothing. It is also why this is per *frame* and not per tile: the-//! 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.+//! # Why a stops list rather than a number //!-//! ## Fills+//! A stroke width is not a property of a layer, it is a function of the camera's zoom, and no+//! single number can stand in for one: a width that reads correctly at street level is+//! continent-wide at world level. The same is true of a fill's opacity, which is the whole of+//! how the low zooms are meant to look — `landcover` fades out between z5 and z7, and+//! `landuse_park` fades in between z6 and z11. Collapsing either to a constant plus an integer+//! zoom gate drew `landcover` at **full** strength at z6 where the ramp asks for half, laying a+//! flat mint blanket over a continent. //!-//! [`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.+//! Evaluating a [`Ramp`] per frame is affordable because both reach the GPU as push constants:+//! `shaders/line.vert` extrudes the centreline to the width it is given, so a width that+//! changes every frame re-tessellates nothing. It is per *frame* and not per tile because the+//! camera's zoom is fractional and continuous, and quantising it to the integer tile zoom is+//! exactly what makes a layer pop instead of fade. //!-//! 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;+//! # Where the values come from+//!+//! `style/basemap.json`, the 71-layer MapLibre style this used to interpret at runtime, is kept+//! vendored beside the flat file for one reason: `the_flat_style_agrees_with_basemap_json`+//! cross-checks every value that exists in both, so a transcription slip fails a build instead+//! of being found on a screenshot. Two columns are deliberately **ours** and are not+//! cross-checked:+//!+//! * **The dark colours.** `basemap.json` is light-only. These are+//! `maps/src/main/java/com/vayunmathur/maps/ui/theme/BasemapPalette.kt`'s contrast-checked+//! values by role — see [`super`]'s module docs for why that palette rather than a third+//! party's.+//! * **The line colours.** The authored file draws roads white on grey casings; these are the+//! warmer set the app has always drawn, and `roads_stay_legible_against_the_land_behind_them`+//! is what holds them honest.+//!+//! One flattening is worth naming. The authored style splits two road casings into+//! `*_casing_early`/`*_casing_late` pairs at z12, one gated by `maxzoom` and the other by+//! `minzoom`. A flat layer carries one ramp, so it carries the `_late` half, which is the one+//! that spans the whole range. Where the casing is wide enough to draw at all the halves differ+//! by at most 0.4 Dp — a little over half a pixel per edge on a density-3 screen — and the worst+//! of that is immediately below the z12 split, which is where two ramps meeting at a point are+//! furthest apart. `a_collapsed_casing_pair_matches_its_authored_late_half` pins the bound.++use super::{Layer, LayerKind}; use serde_json::Value as Json;-use std::collections::HashMap; use std::sync::OnceLock; -/// The authored style, vendored beside the sources.+/// The flat style, vendored beside the sources. ///-/// Compiled in rather than read from assets: it is 61 KB, it is the same file for every host-/// app, and it makes the loader host-testable rather than reachable only from a device.-const BASEMAP: &str = include_str!("../../style/basemap.json");+/// Compiled in rather than read from assets: it is one file for every host app, and it makes+/// the loader host-testable rather than reachable only from a device.+const FLAT: &str = include_str!("../../style/basemap.flat.json"); -/// The deepest zoom the renderer draws at, and the top of every derived zoom gate.+/// The deepest zoom the renderer draws at, and the default top of a layer's zoom range. ///-/// The archive stops at z14 and the renderer overzooms past it; 22 is where-/// [`super::Layer::max_zoom`] has always been pinned.+/// The archive stops at z14 and the renderer overzooms past it. 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;- /// The narrowest half-width worth drawing, in device pixels. ///-/// The authored ramps go continuously to zero and the line pipeline is single-sampled with no-/// coverage term in its shader, so a quad narrower than a pixel is filled only where it happens-/// to straddle a pixel centre. That rasterises as stipple which crawls along the road while+/// The ramps go continuously to zero and the line pipeline is single-sampled with no coverage+/// term in its shader, so a quad narrower than a pixel is filled only where it happens to+/// straddle a pixel centre. That rasterises as stipple which crawls along the road while /// panning, rather than as the faint continuous line the ramp is asking for. Holding it at one /// pixel wide is what a renderer that antialiased its line edges would end up drawing anyway. pub const MIN_HALF_WIDTH_PX: f32 = 0.5;@@ -74,8 +83,8 @@ impl Stroke { /// Would this stroke put anything on screen? /// /// A casing with a gap but no width is two bands of zero thickness, so width alone decides.- /// A zoom where this is false is a zoom the authored style ramped the layer out at, which is- /// the style's own gate and the reason road layers need no `min_zoom`.+ /// A zoom where this is false is a zoom the style ramped the layer out at, which is the+ /// style's own gate and the reason road layers need no `min_zoom`. pub fn visible(&self) -> bool { self.width_dp > 0.0 }@@ -93,552 +102,406 @@ impl Stroke { } } -/// One authored `line` layer's width ramps, held unevaluated.-pub struct LinePaint {- pub id: String,- min_zoom: f64,- max_zoom: f64,- width: Option<Json>,- gap_width: Option<Json>,-}--impl LinePaint {- fn parse(json: &Json) -> Option<LinePaint> {- let paint = json.get("paint");- Some(LinePaint {- id: json.get("id").and_then(Json::as_str)?.to_string(),- 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),- width: paint.and_then(|p| p.get("line-width")).cloned(),- gap_width: paint.and_then(|p| p.get("line-gap-width")).cloned(),- })- }-- /// Does this authored layer draw at `zoom`?- ///- /// `maxzoom` is exclusive, as the spec defines it, and that is what makes the style's- /// `*_casing_early`/`*_casing_late` pairs work: they are split at z12 by one's `maxzoom`- /// and the other's `minzoom`, so exactly one of the two applies at any zoom.- fn covers(&self, zoom: f64) -> bool {- zoom >= self.min_zoom && zoom < self.max_zoom- }-- fn stroke(&self, zoom: f64) -> Stroke {- // A ramp this evaluator cannot read is better left undrawn than drawn at a guessed- // 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, "LineString"),- evaluate(self.gap_width.as_ref(), zoom, 0.0, "LineString"),- ) else {- return Stroke::NONE;- };- Stroke { width_dp, gap_width_dp }- }-}--/// Evaluate one width ramp at `zoom`, or `None` if it will not evaluate.+/// A property as a function of zoom: a list of stops and how to interpolate between them. ///-/// 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, 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 };- 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 {- layers: Vec<LinePaint>,+/// The whole of what the flat format can say about a varying value, and enough for every ramp+/// the authored style uses. A constant is a single stop, so nothing downstream has to branch on+/// whether a property varies.+#[derive(Clone, Debug, PartialEq)]+pub struct Ramp {+ /// The exponential base, or `1.0` for linear.+ base: f64,+ /// Zoom and value, ascending by zoom, never empty.+ stops: Vec<(f64, f32)>, } -impl LineStyle {- pub fn parse(source: &str) -> Result<LineStyle, String> {- let root: Json =- serde_json::from_str(source).map_err(|e| format!("basemap.json is not JSON: {e}"))?;- let layers = root- .get("layers")- .and_then(Json::as_array)- .ok_or("basemap.json has no `layers` array")?;- Ok(LineStyle {- layers: layers- .iter()- .filter(|layer| layer.get("type").and_then(Json::as_str) == Some("line"))- .filter_map(LinePaint::parse)- .collect(),- })- }-- pub fn get(&self, id: &str) -> Option<&LinePaint> {- self.layers.iter().find(|layer| layer.id == id)+impl Ramp {+ /// A property that does not vary.+ pub fn constant(value: f32) -> Ramp {+ Ramp { base: 1.0, stops: vec![(0.0, value)] } } - /// The stroke `layer` draws at `zoom`, in Dp.- ///- /// A layer naming no authored counterpart keeps its constants, which is what leaves fills- /// and the layers this change does not cover alone. A layer that names counterparts but- /// whose every counterpart gates `zoom` out draws nothing.- pub fn stroke(&self, layer: &Layer, zoom: f64) -> Stroke {- if layer.line_paint.is_empty() {- return Stroke { width_dp: layer.width_dp, gap_width_dp: layer.gap_width_dp };- }- layer- .line_paint- .iter()- .filter_map(|id| self.get(id))- .find(|paint| paint.covers(zoom))- .map_or(Stroke::NONE, |paint| paint.stroke(zoom))- }-}--/// The vendored style's line paint, parsed once.-///-/// Immutable and derived from a compiled-in string, so this is a constant table that happens-/// to need a parser rather than shared state. Keeping it here rather than threading it from-/// Kotlin also keeps the render and tessellation threads reading the same paint without-/// having to agree on it across JNI.-pub fn authored() -> &'static LineStyle {- static AUTHORED: OnceLock<LineStyle> = OnceLock::new();- 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 value at `zoom`, clamped to the first and last stop outside the ramp's range. ///- /// 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(),+ /// The exponential curve is the style spec's: `t = (base^dz - 1) / (base^span - 1)`, which+ /// is what makes a road grow slowly at low zoom and quickly at high.+ pub fn at(&self, zoom: f64) -> f32 {+ let last = self.stops.len() - 1;+ if zoom <= self.stops[0].0 {+ return self.stops[0].1;+ }+ if zoom >= self.stops[last].0 {+ return self.stops[last].1;+ }+ let index = self.stops.windows(2).position(|pair| zoom <= pair[1].0).unwrap_or(0);+ let (lower_zoom, lower) = self.stops[index];+ let (upper_zoom, upper) = self.stops[index + 1];+ let span = upper_zoom - lower_zoom;+ let t = if span <= 0.0 {+ 0.0+ } else if self.base == 1.0 {+ (zoom - lower_zoom) / span+ } else {+ (self.base.powf(zoom - lower_zoom) - 1.0) / (self.base.powf(span) - 1.0) };- layer.draws = layer.derive_draws();- Some(layer)+ lower + (upper - lower) * t as f32 } - /// Does this authored layer draw at `zoom`?+ /// The largest value any stop takes. ///- /// `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+ /// Interpolation never leaves the interval between two stops, so this bounds the whole ramp+ /// — which is what makes it the right answer to "does this layer have a gap at all", a+ /// question [`Layer::gapped`] has to answer once rather than per zoom.+ pub fn peak(&self) -> f32 {+ self.stops.iter().fold(f32::NEG_INFINITY, |peak, (_, value)| peak.max(*value)) } - 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,+ fn parse(json: Option<&Json>, id: &str, property: &str, default: f32) -> Result<Ramp, String> {+ let Some(json) = json else {+ return Ok(Ramp::constant(default)); };-- // 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));- }+ if let Some(value) = json.as_f64() {+ return Ok(Ramp::constant(value as f32)); }- 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)),+ let where_ = || format!("`{id}`'s {property}");+ let base = match json.get("interpolate").and_then(Json::as_str) {+ Some("linear") => 1.0,+ Some("exponential") => json+ .get("base")+ .and_then(Json::as_f64)+ .ok_or_else(|| format!("{}: an exponential ramp needs a `base`", where_()))?,+ other => {+ return Err(format!("{}: unknown interpolation {other:?}", where_())); }+ };+ let stops: Vec<(f64, f32)> = json+ .get("stops")+ .and_then(Json::as_array)+ .ok_or_else(|| format!("{}: a ramp needs `stops`", where_()))?+ .iter()+ .map(|stop| match stop.as_array().map(|pair| pair.as_slice()) {+ Some([zoom, value]) => match (zoom.as_f64(), value.as_f64()) {+ (Some(zoom), Some(value)) => Ok((zoom, value as f32)),+ _ => Err(format!("{}: a stop must be two numbers", where_())),+ },+ _ => Err(format!("{}: a stop must be `[zoom, value]`", where_())),+ })+ .collect::<Result<_, _>>()?;+ if stops.is_empty() {+ return Err(format!("{}: a ramp needs at least one stop", where_())); }- // 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();+ // Ascending zooms are what `at`'s scan relies on, and what makes clamping to the+ // first and last stop mean what it says.+ if stops.windows(2).any(|pair| pair[1].0 <= pair[0].0) {+ return Err(format!("{}: stops must ascend by zoom", where_())); }- draws+ Ok(Ramp { base, stops }) } } -/// 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(),- }+/// The whole style: the backdrop, and every layer in draw order.+pub struct Style {+ /// ARGB behind everything, light and dark.+ pub background: (u32, u32),+ pub layers: Vec<Layer>, } -/// 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+/// Parse a flat style file.+pub fn parse(source: &str) -> Result<Style, String> {+ let root: Json =+ serde_json::from_str(source).map_err(|e| format!("the flat style is not JSON: {e}"))?;+ let background = root.get("background").ok_or("the flat style has no `background`")?;+ let layers = root+ .get("layers")+ .and_then(Json::as_array)+ .ok_or("the flat style has no `layers` array")?;+ Ok(Style {+ background: (+ color(background.get("light"), "background.light")?,+ color(background.get("dark"), "background.dark")?,+ ),+ layers: layers.iter().map(layer).collect::<Result<_, _>>()?,+ }) } -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);- }+fn layer(json: &Json) -> Result<Layer, String> {+ let string = |key: &str| -> Result<String, String> {+ json.get(key)+ .and_then(Json::as_str)+ .map(str::to_string)+ .ok_or_else(|| format!("a layer has no `{key}`: {json}"))+ };+ let id = string("id")?;+ // Every property this format has. A hand-authored file is the source of truth now, so a+ // misspelling has to be a load failure: `gapwidth` or `minZoom` would otherwise take the+ // default and render something plausible that nobody asked for.+ const KNOWN: &[&str] = &[+ "id",+ "authored",+ "source",+ "type",+ "kinds",+ "light",+ "dark",+ "opacity",+ "width",+ "gap_width",+ "dash",+ "minzoom",+ "maxzoom",+ ];+ for key in json.as_object().ok_or_else(|| format!("`{id}` is not an object"))?.keys() {+ if !KNOWN.contains(&key.as_str()) {+ return Err(format!("`{id}` has an unknown property `{key}`")); }- _ => {} }+ let kind = match json.get("type").and_then(Json::as_str) {+ Some("fill") => LayerKind::Fill,+ Some("line") => LayerKind::Line,+ other => return Err(format!("`{id}` has an unknown type {other:?}")),+ };+ let zoom = |key: &str, default: u8| -> Result<u8, String> {+ match json.get(key) {+ None => Ok(default),+ Some(value) => value+ .as_u64()+ .filter(|z| *z <= MAX_ZOOM as u64)+ .map(|z| z as u8)+ .ok_or_else(|| {+ format!("`{id}`'s {key} must be a whole zoom in 0..={MAX_ZOOM}")+ }),+ }+ };+ let dash = match json.get("dash").and_then(Json::as_array).map(|d| d.as_slice()) {+ None => (0.0, 0.0),+ Some([on, off]) => match (on.as_f64(), off.as_f64()) {+ (Some(on), Some(off)) => (on as f32, off as f32),+ _ => return Err(format!("`{id}`'s dash must be two numbers")),+ },+ Some(_) => return Err(format!("`{id}`'s dash must be `[on, off]`")),+ };+ Ok(Layer {+ source_layer: string("source")?,+ authored: string("authored")?,+ kind,+ kinds: match json.get("kinds") {+ None => Vec::new(),+ Some(Json::Array(kinds)) => kinds+ .iter()+ .map(|kind| {+ kind.as_str()+ .map(str::to_string)+ .ok_or_else(|| format!("`{id}`'s kinds must be strings"))+ })+ .collect::<Result<_, _>>()?,+ Some(_) => return Err(format!("`{id}`'s kinds must be an array")),+ },+ light: color(json.get("light"), &id)?,+ dark: color(json.get("dark"), &id)?,+ opacity: Ramp::parse(json.get("opacity"), &id, "opacity", 1.0)?,+ width: Ramp::parse(json.get("width"), &id, "width", 0.0)?,+ gap_width: Ramp::parse(json.get("gap_width"), &id, "gap_width", 0.0)?,+ dash,+ min_zoom: zoom("minzoom", 0)?,+ max_zoom: zoom("maxzoom", MAX_ZOOM)?,+ id,+ }) } -/// The authored style's `fill` paint, expanded to one entry per colour.-#[derive(Default)]-pub struct FillStyle {- layers: Vec<FillPaint>,+/// Parse a `#rrggbb` or `#rrggbbaa` colour into ARGB.+///+/// The one spelling the flat file uses. `basemap.json`'s `rgba(...)` form is gone from the+/// production path along with the evaluator that needed it; the cross-check test reads it,+/// because the authored file still writes seven colours that way.+fn color(json: Option<&Json>, what: &str) -> Result<u32, String> {+ let source = json+ .and_then(Json::as_str)+ .ok_or_else(|| format!("`{what}` has no colour string"))?;+ parse_hex(source).ok_or_else(|| format!("`{what}`'s colour `{source}` will not parse")) } -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))+/// `#rrggbb` or `#rrggbbaa` to ARGB, or `None`.+///+/// `None` rather than a default: a colour that will not parse must fail the load, because any+/// substituted colour is a plausible-looking wrong map.+fn parse_hex(source: &str) -> Option<u32> {+ let hex = source.strip_prefix('#')?;+ // Explicitly, rather than leaving it to `from_str_radix`, which accepts a leading `+`.+ if !hex.chars().all(|c| c.is_ascii_hexdigit()) {+ return None;+ }+ let pair = |i: usize| u32::from_str_radix(&hex[i..i + 2], 16).ok();+ match hex.len() {+ 6 => Some(0xFF00_0000 | (pair(0)? << 16) | (pair(2)? << 8) | pair(4)?),+ 8 => Some((pair(6)? << 24) | (pair(0)? << 16) | (pair(2)? << 8) | pair(4)?),+ _ => None, } } -/// 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())+/// The vendored flat style, parsed once.+///+/// Immutable and derived from a compiled-in string, so this is a constant table that happens to+/// need a parser. Keeping it here rather than threading it from Kotlin also keeps the render and+/// tessellation threads reading the same paint without having to agree on it across JNI.+///+/// A parse failure panics. The file ships inside the binary and+/// `the_vendored_flat_style_parses` fails the build if it will not load, so the alternative — a+/// blank map with no diagnostic — is strictly worse than a crash that names the line.+pub fn style() -> &'static Style {+ static STYLE: OnceLock<Style> = OnceLock::new();+ STYLE.get_or_init(|| parse(FLAT).unwrap_or_else(|e| panic!("style/basemap.flat.json: {e}"))) } #[cfg(test)] mod tests { use super::*;- use crate::style::{layers, LayerKind};+ use crate::style::{layers, Layer, LayerKind}; /// The archive's zoom range, plus the overzoom the renderer allows past it. const ZOOMS: std::ops::RangeInclusive<i32> = 0..=22; - fn style() -> &'static LineStyle {- authored()- }+ /// The authored MapLibre style, for the cross-check only.+ const BASEMAP: &str = include_str!("../../style/basemap.json"); - fn line_layers() -> Vec<Layer> {- layers().into_iter().filter(|layer| layer.kind == LayerKind::Line).collect()+ fn line_layers() -> Vec<&'static Layer> {+ layers().iter().filter(|layer| layer.kind == LayerKind::Line).collect() } - fn width_of(id: &str, zoom: f64) -> f32 {- style().get(id).map_or(f32::NAN, |paint| paint.stroke(zoom).width_dp)+ fn find(id: &str) -> &'static Layer {+ layers().iter().find(|layer| layer.id == id).unwrap_or_else(|| panic!("{id}")) } + // --- the loader --------------------------------------------------------+ #[test]- fn the_vendored_style_parses_and_holds_its_line_layers() {- let parsed = LineStyle::parse(BASEMAP).expect("basemap.json should parse");- // 41 `line` layers in the authored file; asserting the exact count would fail on any- // harmless restyle, but losing most of them means the filter broke.- assert!(parsed.layers.len() > 30, "found {} line layers", parsed.layers.len());- assert!(parsed.get("roads_highway").is_some());- assert!(parsed.get("roads_highway_casing_early").is_some());- // A `fill` layer must not be picked up by the `line` filter.- assert!(parsed.get("buildings").is_none());+ fn the_vendored_flat_style_parses() {+ let style = parse(FLAT).expect("style/basemap.flat.json should parse");+ // 24 fills and 9 lines. Asserted exactly: the file is the layer set, so a layer+ // appearing or disappearing is a decision rather than an incidental restyle.+ let fills = style.layers.iter().filter(|l| l.kind == LayerKind::Fill).count();+ let lines = style.layers.iter().filter(|l| l.kind == LayerKind::Line).count();+ assert_eq!((fills, lines), (24, 9));+ assert_eq!(style.background, (0xFF80DEEA, 0xFF0D1B2A)); } #[test]- fn every_authored_layer_a_style_layer_names_actually_exists() {- for layer in layers() {- for id in layer.line_paint {- assert!(- style().get(id).is_some(),- "`{}` names authored layer `{id}`, which is not in basemap.json",- layer.id,- );- }+ fn a_malformed_style_fails_to_load_rather_than_loading_partly() {+ let cases = [+ (r##"{}"##, "no background"),+ (r##"{"background":{"light":"#fff","dark":"#000"},"layers":[]}"##, "a bad colour"),+ (+ r##"{"background":{"light":"#ffffff","dark":"#000000"},+ "layers":[{"id":"x","authored":"x","source":"s","type":"blob",+ "light":"#ffffff","dark":"#000000"}]}"##,+ "an unknown type",+ ),+ (+ r##"{"background":{"light":"#ffffff","dark":"#000000"},+ "layers":[{"id":"x","authored":"x","source":"s","type":"fill",+ "light":"#ffffff","dark":"#000000",+ "width":{"interpolate":"exponential","stops":[[1,2]]}}]}"##,+ "an exponential ramp with no base",+ ),+ (+ r##"{"background":{"light":"#ffffff","dark":"#000000"},+ "layers":[{"id":"x","authored":"x","source":"s","type":"fill",+ "light":"#ffffff","dark":"#000000",+ "width":{"interpolate":"linear","stops":[[5,1],[3,0]]}}]}"##,+ "descending stops",+ ),+ (+ r##"{"background":{"light":"#ffffff","dark":"#000000"},+ "layers":[{"id":"x","authored":"x","source":"s","type":"fill",+ "light":"#ffffff","dark":"#000000","gapwidth":3}]}"##,+ "a misspelled property",+ ),+ (+ r##"{"background":{"light":"#ffffff","dark":"#000000"},+ "layers":[{"id":"x","authored":"x","source":"s","type":"fill",+ "light":"#ffffff","dark":"#000000","minzoom":14.0}]}"##,+ "a fractional minzoom",+ ),+ (+ r##"{"background":{"light":"#ffffff","dark":"#000000"},+ "layers":[{"id":"x","authored":"x","source":"s","type":"fill",+ "light":"#ffffff","dark":"#000000","maxzoom":40}]}"##,+ "a zoom past the renderer's own maximum",+ ),+ ];+ for (source, what) in cases {+ assert!(parse(source).is_err(), "{what} should not load"); } } #[test]- fn every_width_ramp_evaluates_across_the_zoom_range() {- let properties = HashMap::new();- for layer in style().layers.iter() {- // Tenths, not integers: every authored stop is an integer or a half, so integer- // zooms alone would only ever land on segment boundaries.- for tenth in 0..=220 {- let context = Context {- zoom: tenth as f64 / 10.0,- properties: &properties,- geometry_type: "LineString",- };- for (property, expr) in- [("line-width", &layer.width), ("line-gap-width", &layer.gap_width)]- {- let Some(expr) = expr else { continue };- let value = expr::eval(expr, &context).unwrap_or_else(|e| {- panic!("{} {property} at z{}: {e}", layer.id, tenth as f64 / 10.0)- });- assert!(- value.as_number().is_some(),- "{} {property} at z{} is not a number: {value:?}",- layer.id,- tenth as f64 / 10.0,- );- }- }+ fn a_hex_colour_parses_and_anything_else_does_not() {+ assert_eq!(parse_hex("#80deea"), Some(0xFF80DEEA));+ assert_eq!(parse_hex("#E2DFDA"), Some(0xFFE2DFDA), "case does not matter");+ assert_eq!(parse_hex("#11223380"), Some(0x80112233));+ for source in ["", "#", "#abc", "#12345", "#gg0000", "cornflowerblue", "rgb(1,2,3)"] {+ assert_eq!(parse_hex(source), None, "{source:?} must not parse"); }+ // `from_str_radix` would take these; a colour column must not.+ assert_eq!(parse_hex("#+12345"), None);+ assert_eq!(parse_hex("#12 345"), None); } - /// `gapped()` reads the *constant* gap width and it is what decides, at tessellation time,- /// whether a layer emits one centred band or two offset ones. The ramp only sets the- /// distance. So the constant has to agree with the ramp about whether there is a gap at- /// all: a layer that tessellates a plain stroke discards the pushed gap silently.+ // --- ramps -------------------------------------------------------------+ #[test]- fn the_constant_that_picks_the_casing_geometry_agrees_with_the_authored_gap_ramp() {- for layer in line_layers() {- if layer.line_paint.is_empty() {- continue;- }- let authored_gap = (0..=220).any(|tenth| {- style().stroke(&layer, tenth as f64 / 10.0).gap_width_dp > 0.0- });- assert_eq!(- layer.gapped(),- authored_gap,- "`{}` tessellates {} but the authored ramp says {}",- layer.id,- if layer.gapped() { "two bands" } else { "one band" },- if authored_gap { "there is a gap" } else { "there is none" },- );+ fn a_ramp_clamps_outside_its_stops_and_interpolates_inside() {+ let ramp = Ramp { base: 1.0, stops: vec![(5.0, 1.0), (7.0, 0.0)] };+ assert_eq!(ramp.at(0.0), 1.0, "clamped below the first stop");+ assert_eq!(ramp.at(5.0), 1.0);+ assert_eq!(ramp.at(6.0), 0.5, "halfway, linearly");+ assert_eq!(ramp.at(7.0), 0.0);+ assert_eq!(ramp.at(22.0), 0.0, "clamped above the last");+ assert_eq!(ramp.peak(), 1.0);+ }++ #[test]+ fn an_exponential_ramp_grows_slowly_at_first_as_the_spec_defines_it() {+ let ramp = Ramp { base: 1.6, stops: vec![(0.0, 0.0), (2.0, 1.0)] };+ // (1.6^1 - 1) / (1.6^2 - 1) = 0.6 / 1.56.+ assert!((ramp.at(1.0) - 0.3846).abs() < 1e-4, "{}", ramp.at(1.0));+ assert!(ramp.at(1.0) < 0.5, "an exponential curve lags a linear one");+ assert_eq!(Ramp { base: 1.0, stops: vec![(0.0, 0.0), (2.0, 1.0)] }.at(1.0), 0.5);+ }++ #[test]+ fn a_constant_is_a_ramp_with_one_stop() {+ let ramp = Ramp::constant(0.7);+ for tenth in 0..=220 {+ assert_eq!(ramp.at(tenth as f64 / 10.0), 0.7); }+ assert_eq!(ramp.peak(), 0.7); } - /// A ramp that will not evaluate must leave the layer undrawn rather than pick a width:- /// any single guessed number is constant across zoom, which is the defect being removed. #[test]- fn a_ramp_this_evaluator_cannot_read_draws_nothing() {- let unreadable = LinePaint {- id: "synthetic".to_string(),- min_zoom: 0.0,- max_zoom: f64::INFINITY,- width: Some(serde_json::json!(["cubic-bezier", 0.4, 0.0, 0.6, 1.0])),- gap_width: None,- };- assert!(expr::eval(- unreadable.width.as_ref().expect("width"),- &Context {- zoom: 4.0,- properties: &HashMap::new(),- geometry_type: "LineString",- },- )- .is_err());- assert_eq!(unreadable.stroke(4.0), Stroke::NONE);- assert!(!unreadable.stroke(4.0).visible());+ fn a_ramp_picks_the_right_segment_of_several() {+ let ramp =+ Ramp { base: 1.0, stops: vec![(0.0, 0.0), (10.0, 10.0), (20.0, 0.0)] };+ assert_eq!(ramp.at(5.0), 5.0, "the rising segment");+ assert_eq!(ramp.at(15.0), 5.0, "the falling one");+ assert_eq!(ramp.at(10.0), 10.0, "the shared stop");+ assert_eq!(ramp.peak(), 10.0, "the peak is not the last stop"); } - /// The defect: a constant width is a street-level width applied at world level.+ // --- lines -------------------------------------------------------------++ #[test]+ fn every_line_layer_draws_something_somewhere_in_the_zoom_range() {+ for layer in line_layers() {+ let drawn = ZOOMS.into_iter().any(|zoom| layer.stroke(zoom as f64).visible());+ assert!(drawn, "`{}` is invisible at every zoom", layer.id);+ }+ }++ /// The defect a constant width had: a street-level width applied at world level. #[test] fn a_highway_at_world_zoom_is_a_small_fraction_of_its_width_at_street_zoom() {- let world = width_of("roads_highway", 4.0);- let street = width_of("roads_highway", 14.0);+ let highway = find("roads-highway");+ let (world, street) = (highway.stroke(4.0).width_dp, highway.stroke(14.0).width_dp); assert!(world > 0.0 && street > 0.0, "world {world}, street {street}"); assert!( world < street * 0.15,@@ -654,80 +517,61 @@ mod tests { for layer in line_layers() { for tenth in 0..80 { let zoom = tenth as f64 / 10.0;- let stroke = style().stroke(&layer, zoom);+ let stroke = layer.stroke(zoom); let total = stroke.width_dp * 2.0 + stroke.gap_width_dp * 2.0;- assert!(- total <= 10.0,- "`{}` is {total} Dp across at z{zoom}",- layer.id,- );+ assert!(total <= 10.0, "`{}` is {total} Dp across at z{zoom}", layer.id); } } } #[test] fn width_grows_continuously_with_zoom_rather_than_stepping_per_level() {- // Across an integer boundary the authored ramp is inside one segment, so a width that- // is quantised to the tile zoom would repeat itself here.+ // Across an integer boundary the ramp is inside one segment, so a width quantised to+ // the tile zoom would repeat itself here.+ let highway = find("roads-highway"); let widths: Vec<f32> =- (0..=10).map(|step| width_of("roads_highway", 13.5 + step as f64 / 10.0)).collect();+ (0..=10).map(|step| highway.stroke(13.5 + step as f64 / 10.0).width_dp).collect(); for pair in widths.windows(2) {- let (lower, upper) = (pair[0], pair[1]);- assert!(upper > lower, "width stepped rather than grew: {widths:?}");+ assert!(pair[1] > pair[0], "width stepped rather than grew: {widths:?}"); }- // And it really is the same segment either side of z14, not a coincidence of stops. assert!(widths[4] < widths[5] && widths[5] < widths[6], "{widths:?}"); } #[test] fn a_highway_grows_monotonically_across_the_whole_zoom_range() {+ let highway = find("roads-highway"); let mut previous = -1.0; for tenth in 0..=220 {- let width = width_of("roads_highway", tenth as f64 / 10.0);+ let width = highway.stroke(tenth as f64 / 10.0).width_dp; assert!(width >= previous, "width fell at z{}", tenth as f64 / 10.0); previous = width; } } - #[test]- fn the_casing_pair_split_at_z12_applies_exactly_one_of_the_two() {- for id in ["roads_highway_casing", "roads_major_casing"] {- let early = style().get(&format!("{id}_early")).expect("early half");- let late = style().get(&format!("{id}_late")).expect("late half");- for tenth in 0..=220 {- let zoom = tenth as f64 / 10.0;- assert_ne!(- early.covers(zoom),- late.covers
Diff truncated.