Skip to main content

basemapper_core/vector/
hillshade.rs

1//! `hillshade` layers over `raster-dem` sources: a CPU port of MapLibre GL
2//! JS's two-pass hillshading.
3//!
4//! 1. DEMData: each DEM tile image is decoded into a stride `dim + 2` buffer
5//!    whose 1 px border repeats the edge pixels, then is backfilled from the
6//!    neighbouring tiles that are loaded (MapLibre backfills only from tiles
7//!    it has, i.e. the view's covering tiles).
8//! 2. hillshade_prepare.fragment.glsl: per DEM pixel, the Sobel x / y slope
9//!    from the 3 × 3 neighbourhood, vertically exaggerated below z15, stored
10//!    in an RGBA8 texture as `deriv / 8 + 0.5`.
11//! 3. hillshade.fragment.glsl: per screen pixel, the slope texture sampled
12//!    `LINEAR` (or `NEAREST` with `resampling: nearest`), corrected for the
13//!    Mercator scale at the pixel's latitude and shaded by `hillshade-method`
14//!    (standard, basic, combined, igor, multidirectional), blended
15//!    premultiplied. Tiles are placed with MapLibre's pixel-aligned raster
16//!    matrix.
17
18use super::expr::{eval_property, Color, Ctx, Kind, Val};
19use super::gl::Framebuffer;
20use crate::tile_fetcher::TileCoord;
21use serde_json::Value as Json;
22use std::collections::HashMap;
23use std::f64::consts::PI;
24
25const EARTH_HALF: f64 = 20_037_508.342_789_244;
26const TILE_PX: f64 = 512.0;
27
28/// DEM tiles of one `raster-dem` source at the zoom MapLibre covers the view
29/// with, and the source's unpack vector (`redFactor`, `greenFactor`,
30/// `blueFactor`, `baseShift`).
31pub struct DemTiles {
32    pub zoom: u8,
33    pub tiles: Vec<(TileCoord, Vec<u8>)>,
34    pub unpack: [f64; 4],
35}
36
37/// The unpack vector of a `raster-dem` source (DEMData's constructor).
38pub fn unpack_vector(src: &Json) -> [f64; 4] {
39    match src["encoding"].as_str() {
40        Some("terrarium") => [256.0, 1.0, 1.0 / 256.0, 32768.0],
41        Some("custom") => [
42            src["redFactor"].as_f64().unwrap_or(1.0),
43            src["greenFactor"].as_f64().unwrap_or(1.0),
44            src["blueFactor"].as_f64().unwrap_or(1.0),
45            src["baseShift"].as_f64().unwrap_or(0.0),
46        ],
47        _ => [6553.6, 25.6, 0.1, 10000.0],
48    }
49}
50
51/// A decoded DEM tile: elevations (metres) with a 1 px border.
52struct Dem {
53    dim: usize,
54    /// `(dim + 2)²` elevations, row-major, `(-1, -1)` first.
55    ele: Vec<f64>,
56}
57
58impl Dem {
59    fn decode(bytes: &[u8], unpack: [f64; 4]) -> Option<Dem> {
60        let img = image::load_from_memory(bytes).map_err(|e| log::warn!("DEM tile: {e}")).ok()?.to_rgba8();
61        if img.width() != img.height() || img.width() == 0 {
62            log::warn!("DEM tiles must be square");
63            return None;
64        }
65        let dim = img.width() as usize;
66        let stride = dim + 2;
67        let mut ele = vec![0.0; stride * stride];
68        for (x, y, p) in img.enumerate_pixels() {
69            ele[(y as usize + 1) * stride + x as usize + 1] =
70                p[0] as f64 * unpack[0] + p[1] as f64 * unpack[1] + p[2] as f64 * unpack[2] - unpack[3];
71        }
72        let mut d = Dem { dim, ele };
73        let n = dim as i64;
74        for i in 0..n {
75            d.set(-1, i, d.get(0, i));
76            d.set(n, i, d.get(n - 1, i));
77            d.set(i, -1, d.get(i, 0));
78            d.set(i, n, d.get(i, n - 1));
79        }
80        d.set(-1, -1, d.get(0, 0));
81        d.set(n, -1, d.get(n - 1, 0));
82        d.set(-1, n, d.get(0, n - 1));
83        d.set(n, n, d.get(n - 1, n - 1));
84        Some(d)
85    }
86
87    #[inline]
88    fn idx(&self, x: i64, y: i64) -> usize {
89        ((y + 1) as usize) * (self.dim + 2) + (x + 1) as usize
90    }
91    #[inline]
92    fn get(&self, x: i64, y: i64) -> f64 {
93        self.ele[self.idx(x, y)]
94    }
95    #[inline]
96    fn set(&mut self, x: i64, y: i64, v: f64) {
97        let i = self.idx(x, y);
98        self.ele[i] = v;
99    }
100
101    /// DEMData#backfillBorder: copy the border strip facing `other`, the
102    /// neighbour at offset (dx, dy).
103    fn backfill(&mut self, other: &Dem, dx: i64, dy: i64) {
104        if self.dim != other.dim {
105            return;
106        }
107        let n = self.dim as i64;
108        let (mut x0, mut x1, mut y0, mut y1) = (dx * n, dx * n + n, dy * n, dy * n + n);
109        match dx {
110            -1 => x0 = x1 - 1,
111            1 => x1 = x0 + 1,
112            _ => {}
113        }
114        match dy {
115            -1 => y0 = y1 - 1,
116            1 => y1 = y0 + 1,
117            _ => {}
118        }
119        let (ox, oy) = (-dx * n, -dy * n);
120        for y in y0..y1 {
121            for x in x0..x1 {
122                let v = other.get(x + ox, y + oy);
123                self.set(x, y, v);
124            }
125        }
126    }
127
128    /// hillshade_prepare.fragment.glsl: the slope texture (R, G), `dim²`.
129    fn prepare(&self, z: u8) -> Vec<[u8; 2]> {
130        let n = self.dim as i64;
131        let zf = z as f64;
132        let factor = if zf < 2.0 { 0.4 } else if zf < 4.5 { 0.35 } else { 0.3 };
133        let exaggeration = if zf < 15.0 { (zf - 15.0) * factor } else { 0.0 };
134        let k = self.dim as f64 / 2f64.powf(exaggeration + (28.2562 - zf));
135        let unorm = |v: f64| ((v / 8.0 + 0.5).clamp(0.0, 1.0) * 255.0).round() as u8;
136        let mut out = Vec::with_capacity(self.dim * self.dim);
137        for y in 0..n {
138            for x in 0..n {
139                let e = |dx: i64, dy: i64| self.get(x + dx, y + dy);
140                let (a, b, c) = (e(-1, -1), e(0, -1), e(1, -1));
141                let (d, f) = (e(-1, 0), e(1, 0));
142                let (g, h, i) = (e(-1, 1), e(0, 1), e(1, 1));
143                let dx = ((c + f + f + i) - (a + d + d + g)) * k;
144                let dy = ((g + h + h + i) - (a + b + b + c)) * k;
145                out.push([unorm(dx), unorm(dy)]);
146            }
147        }
148        out
149    }
150}
151
152#[derive(Clone, Copy, PartialEq)]
153enum Method {
154    Standard,
155    Basic,
156    Combined,
157    Igor,
158    Multidirectional,
159}
160
161/// The evaluated hillshade paint properties (uniforms).
162struct Shading {
163    method: Method,
164    exaggeration: f64,
165    accent: [f64; 4],
166    /// Per illumination source: azimuth (rad), altitude (rad), shadow, highlight.
167    azimuths: Vec<f64>,
168    altitudes: Vec<f64>,
169    shadows: Vec<[f64; 4]>,
170    highlights: Vec<[f64; 4]>,
171    nearest: bool,
172}
173
174fn c4(c: Color) -> [f64; 4] {
175    [c.r as f64, c.g as f64, c.b as f64, c.a as f64]
176}
177
178/// A number-or-array property (`hillshade-illumination-direction`, ...).
179fn numbers(p: &Json, key: &str, ctx: &Ctx, default: f64) -> Vec<f64> {
180    let Some(j) = p.get(key).filter(|j| !j.is_null()) else { return vec![default] };
181    let v = match j {
182        Json::Array(a) if a.first().map_or(false, |f| f.is_number()) => Val::from_json(j),
183        _ => eval_property(j, Kind::Array, ctx),
184    };
185    let out: Vec<f64> = match v {
186        Val::Num(n) => vec![n],
187        Val::Array(a) => a.iter().filter_map(|v| if let Val::Num(n) = v { Some(*n) } else { None }).collect(),
188        _ => vec![],
189    };
190    if out.is_empty() { vec![default] } else { out }
191}
192
193/// A color-or-array property (`hillshade-shadow-color`, ...).
194fn colors(p: &Json, key: &str, ctx: &Ctx, default: &str) -> Vec<[f64; 4]> {
195    let fallback = || vec![c4(Color::parse(default).unwrap())];
196    let Some(j) = p.get(key).filter(|j| !j.is_null()) else { return fallback() };
197    // A literal array of color strings (its head is a color, not an operator).
198    if let Json::Array(a) = j {
199        let parsed: Option<Vec<[f64; 4]>> = a.iter().map(|s| s.as_str().and_then(Color::parse).map(c4)).collect();
200        if let Some(cs) = parsed.filter(|c| !c.is_empty()) {
201            return cs;
202        }
203    }
204    let out: Vec<[f64; 4]> = match eval_property(j, Kind::Color, ctx) {
205        Val::Color(c) => vec![c4(c)],
206        Val::Array(a) => a
207            .iter()
208            .filter_map(|v| match v {
209                Val::Color(c) => Some(c4(*c)),
210                Val::Str(s) => Color::parse(s).map(c4),
211                _ => None,
212            })
213            .collect(),
214        Val::Str(s) => Color::parse(&s).map(c4).into_iter().collect(),
215        _ => vec![],
216    };
217    if out.is_empty() { fallback() } else { out }
218}
219
220impl Shading {
221    fn new(layer: &Json, zoom: f64) -> Shading {
222        let ctx = Ctx { zoom, feature: None };
223        let p = &layer["paint"];
224        let num = |k: &str, d: f64| match p.get(k).filter(|j| !j.is_null()) {
225            Some(j) => match eval_property(j, Kind::Number, &ctx) {
226                Val::Num(n) => n,
227                _ => d,
228            },
229            None => d,
230        };
231        let enum_ = |k: &str, d: &str| match p.get(k).filter(|j| !j.is_null()) {
232            Some(j) => match eval_property(j, Kind::Enum, &ctx) {
233                Val::Str(s) => s,
234                _ => d.to_owned(),
235            },
236            None => d.to_owned(),
237        };
238        let method = match enum_("hillshade-method", "standard").as_str() {
239            "basic" => Method::Basic,
240            "combined" => Method::Combined,
241            "igor" => Method::Igor,
242            "multidirectional" => Method::Multidirectional,
243            _ => Method::Standard,
244        };
245        let mut dir = numbers(p, "hillshade-illumination-direction", &ctx, 335.0);
246        let mut alt = numbers(p, "hillshade-illumination-altitude", &ctx, 45.0);
247        let mut hi = colors(p, "hillshade-highlight-color", &ctx, "#FFFFFF");
248        let mut sh = colors(p, "hillshade-shadow-color", &ctx, "#000000");
249        // getIlluminationProperties: pad every list with its last value.
250        let n = dir.len().max(alt.len()).max(hi.len()).max(sh.len());
251        fn pad<T: Copy>(v: &mut Vec<T>, n: usize) {
252            let last = *v.last().unwrap();
253            v.resize(n, last);
254        }
255        pad(&mut dir, n);
256        pad(&mut alt, n);
257        pad(&mut hi, n);
258        pad(&mut sh, n);
259        // The bearing is always 0 here, so `hillshade-illumination-anchor`
260        // (viewport or map) does not change the azimuth.
261        let accent = colors(p, "hillshade-accent-color", &ctx, "#000000")[0];
262        Shading {
263            method,
264            exaggeration: num("hillshade-exaggeration", 0.5),
265            accent,
266            azimuths: dir.iter().map(|d| d.to_radians()).collect(),
267            altitudes: alt.iter().map(|a| a.to_radians()).collect(),
268            shadows: sh,
269            highlights: hi,
270            nearest: enum_("resampling", "linear") == "nearest",
271        }
272    }
273
274    /// hillshade.fragment.glsl's methods: premultiplied RGBA for `deriv`.
275    fn shade(&self, deriv: [f64; 2]) -> [f64; 4] {
276        let add = |a: [f64; 4], b: [f64; 4]| [a[0] + b[0], a[1] + b[1], a[2] + b[2], a[3] + b[3]];
277        let mul = |a: [f64; 4], k: f64| [a[0] * k, a[1] * k, a[2] * k, a[3] * k];
278        let len = (deriv[0] * deriv[0] + deriv[1] * deriv[1]).sqrt();
279        let aspect = |d: [f64; 2]| if d[0] != 0.0 { d[1].atan2(-d[0]) } else { PI / 2.0 * if d[1] > 0.0 { 1.0 } else { -1.0 } };
280        // GLSL mod: x - y * floor(x / y).
281        let gmod = |x: f64, y: f64| x - y * (x / y).floor();
282        let cang_of = |d: [f64; 2], cos_az: f64, sin_az: f64, alt: f64| {
283            let (cos_alt, sin_alt) = (alt.cos(), alt.sin());
284            (sin_alt - (d[1] * cos_az * cos_alt - d[0] * sin_az * cos_alt)) / (1.0 + d[0] * d[0] + d[1] * d[1]).sqrt()
285        };
286        match self.method {
287            Method::Standard => {
288                let azimuth = self.azimuths[0] + PI;
289                let slope = (0.625 * len).atan();
290                let intensity = self.exaggeration;
291                let base = 1.875 - intensity * 1.75;
292                let max_value = 0.5 * PI;
293                let scaled = if intensity != 0.5 {
294                    ((base.powf(slope) - 1.0) / (base.powf(max_value) - 1.0)) * max_value
295                } else {
296                    slope
297                };
298                let accent = scaled.cos();
299                let k = (intensity * 2.0).clamp(0.0, 1.0);
300                let accent_color = mul(self.accent, (1.0 - accent) * k);
301                let shade = (gmod((aspect(deriv) + azimuth) / PI + 0.5, 2.0) - 1.0).abs();
302                let (s, h) = (self.shadows[0], self.highlights[0]);
303                let mix = [0, 1, 2, 3].map(|i| s[i] + (h[i] - s[i]) * shade);
304                let shade_color = mul(mix, scaled.sin() * k);
305                add(mul(accent_color, 1.0 - shade_color[3]), shade_color)
306            }
307            Method::Basic => {
308                let d = [deriv[0] * self.exaggeration * 2.0, deriv[1] * self.exaggeration * 2.0];
309                let azimuth = self.azimuths[0] + PI;
310                let shade = cang_of(d, azimuth.cos(), azimuth.sin(), self.altitudes[0]).clamp(0.0, 1.0);
311                if shade > 0.5 {
312                    mul(self.highlights[0], 2.0 * shade - 1.0)
313                } else {
314                    mul(self.shadows[0], 1.0 - 2.0 * shade)
315                }
316            }
317            Method::Multidirectional => {
318                let d = [deriv[0] * self.exaggeration * 2.0, deriv[1] * self.exaggeration * 2.0];
319                let n = self.azimuths.len() as f64;
320                let mut out = [0.0; 4];
321                for i in 0..self.azimuths.len() {
322                    let az = self.azimuths[i];
323                    let shade = cang_of(d, -az.cos(), -az.sin(), self.altitudes[i]).clamp(0.0, 1.0);
324                    out = if shade > 0.5 {
325                        add(out, mul(self.highlights[i], (2.0 * shade - 1.0) / n))
326                    } else {
327                        add(out, mul(self.shadows[i], (1.0 - 2.0 * shade) / n))
328                    };
329                }
330                out
331            }
332            Method::Combined => {
333                let d = [deriv[0] * self.exaggeration * 2.0, deriv[1] * self.exaggeration * 2.0];
334                let azimuth = self.azimuths[0] + PI;
335                let cang = cang_of(d, azimuth.cos(), azimuth.sin(), self.altitudes[0]).clamp(-1.0, 1.0).acos().clamp(0.0, PI / 2.0);
336                let l = (d[0] * d[0] + d[1] * d[1]).sqrt().atan();
337                let shade = cang * l * 4.0 / PI / PI;
338                let highlight = (PI / 2.0 - cang) * l * 4.0 / PI / PI;
339                add(mul(self.shadows[0], shade), mul(self.highlights[0], highlight))
340            }
341            Method::Igor => {
342                let d = [deriv[0] * self.exaggeration * 2.0, deriv[1] * self.exaggeration * 2.0];
343                let azimuth = self.azimuths[0] + PI;
344                let slope = (d[0] * d[0] + d[1] * d[1]).sqrt().atan() * 2.0 / PI;
345                let aspect_strength = 1.0 - (gmod((aspect(d) + azimuth) / PI + 0.5, 2.0) - 1.0).abs();
346                add(mul(self.shadows[0], slope * aspect_strength), mul(self.highlights[0], slope * (1.0 - aspect_strength)))
347            }
348        }
349    }
350}
351
352/// Latitude (degrees) of the Mercator y in [0, 1].
353fn lat_of(y: f64) -> f64 {
354    let y2 = 180.0 - y * 360.0;
355    360.0 / PI * (y2 * PI / 180.0).exp().atan() - 90.0
356}
357
358/// Whether the slope textures of `source` are sampled `NEAREST`. MapLibre
359/// prepares one texture per DEM tile, shared by every hillshade layer of the
360/// source, and sets its filter when the first layer (in style order) with an
361/// offscreen pass creates it: that layer's `resampling` applies to all.
362pub fn source_nearest(style: &Json, source: &str, zoom: f64) -> bool {
363    let layers = style["layers"].as_array().map(|v| v.as_slice()).unwrap_or(&[]);
364    layers
365        .iter()
366        .find(|l| {
367            l["type"] == "hillshade"
368                && l["source"] == source
369                && super::symbol::layer_visible(l, zoom)
370                && Shading::new(l, zoom).exaggeration != 0.0
371        })
372        .map_or(false, |l| Shading::new(l, zoom).nearest)
373}
374
375/// Draw a `hillshade` layer from `dem` into `fb` (device pixels) for the view
376/// `bbox` at `width × height` CSS pixels, scale zoom `zoom`. `nearest`: the
377/// source's texture filter (see [`source_nearest`]).
378#[allow(clippy::too_many_arguments)]
379pub fn draw_layer(
380    fb: &mut Framebuffer,
381    layer: &Json,
382    zoom: f64,
383    dem: &DemTiles,
384    bbox: [f64; 4],
385    width: u32,
386    height: u32,
387    ratio: f64,
388    nearest: bool,
389) {
390    let mut sh = Shading::new(layer, zoom);
391    sh.nearest = nearest;
392    // hasOffscreenPass: nothing is prepared (or drawn) at exaggeration 0.
393    if sh.exaggeration == 0.0 {
394        return;
395    }
396    // Decode, then backfill borders from loaded neighbours.
397    let mut dems: HashMap<(u32, u32), Dem> = HashMap::new();
398    for (c, bytes) in &dem.tiles {
399        if let Some(d) = Dem::decode(bytes, dem.unpack) {
400            dems.insert((c.x, c.y), d);
401        }
402    }
403    let z = dem.zoom;
404    let n = 1i64 << z;
405    let keys: Vec<(u32, u32)> = dems.keys().copied().collect();
406    for &(x, y) in &keys {
407        for dy in -1i64..=1 {
408            for dx in -1i64..=1 {
409                if dx == 0 && dy == 0 {
410                    continue;
411                }
412                let ny = y as i64 + dy;
413                if ny < 0 || ny >= n {
414                    continue;
415                }
416                let nx = (x as i64 + dx).rem_euclid(n);
417                let Some(other) = dems.get(&(nx as u32, ny as u32)) else { continue };
418                // Borrow juggling: the neighbour is read while this tile is written.
419                let other = Dem { dim: other.dim, ele: other.ele.clone() };
420                dems.get_mut(&(x, y)).unwrap().backfill(&other, dx, dy);
421            }
422        }
423    }
424
425    // MapLibre's pixel-aligned raster projection (alignedProjMatrix).
426    let world_px = TILE_PX * 2f64.powf(zoom);
427    let cx = ((bbox[0] + bbox[2]) / 2.0 + EARTH_HALF) / (2.0 * EARTH_HALF) * world_px;
428    let cy = (EARTH_HALF - (bbox[1] + bbox[3]) / 2.0) / (2.0 * EARTH_HALF) * world_px;
429    let align = |c: f64, size: u32| {
430        let shift = (size % 2) as f64 / 2.0;
431        let d = c - c.round() + shift;
432        c - if d > 0.5 { d - 1.0 } else { d }
433    };
434    let view_x0 = align(cx, width) - width as f64 / 2.0;
435    let view_y0 = align(cy, height) - height as f64 / 2.0;
436    let tile_px = world_px / n as f64;
437
438    let mut keys = keys;
439    keys.sort();
440    for (tx, ty) in keys {
441        let d = &dems[&(tx, ty)];
442        let tex = d.prepare(z);
443        let dim = d.dim;
444        let lat0 = lat_of(ty as f64 / n as f64);
445        let lat1 = lat_of((ty + 1) as f64 / n as f64);
446        let ox = (tx as f64 * tile_px - view_x0) * ratio;
447        let oy = (ty as f64 * tile_px - view_y0) * ratio;
448        let size = tile_px * ratio;
449        // Pixels whose centres fall inside the tile.
450        let px0 = (ox - 0.5).ceil().max(0.0) as i64;
451        let py0 = (oy - 0.5).ceil().max(0.0) as i64;
452        let px1 = ((ox + size - 0.5).ceil() as i64).min(fb.w as i64);
453        let py1 = ((oy + size - 0.5).ceil() as i64).min(fb.h as i64);
454        let texel = |x: i64, y: i64| {
455            let x = x.clamp(0, dim as i64 - 1) as usize;
456            let y = y.clamp(0, dim as i64 - 1) as usize;
457            let t = tex[y * dim + x];
458            [t[0] as f64 / 255.0, t[1] as f64 / 255.0]
459        };
460        for py in py0..py1 {
461            let v = (py as f64 + 0.5 - oy) / size;
462            let scale_factor = ((lat0 - lat1) * (1.0 - v) + lat1).to_radians().cos();
463            for px in px0..px1 {
464                let u = (px as f64 + 0.5 - ox) / size;
465                let rg = if sh.nearest {
466                    texel((u * dim as f64).floor() as i64, (v * dim as f64).floor() as i64)
467                } else {
468                    let (s, t) = (u * dim as f64 - 0.5, v * dim as f64 - 0.5);
469                    let (i0, j0) = (s.floor(), t.floor());
470                    let (fx, fy) = (s - i0, t - j0);
471                    let (i0, j0) = (i0 as i64, j0 as i64);
472                    let (a, b, c, e) = (texel(i0, j0), texel(i0 + 1, j0), texel(i0, j0 + 1), texel(i0 + 1, j0 + 1));
473                    [0, 1].map(|k| (a[k] * (1.0 - fx) + b[k] * fx) * (1.0 - fy) + (c[k] * (1.0 - fx) + e[k] * fx) * fy)
474                };
475                let deriv = [(rg[0] * 8.0 - 4.0) / scale_factor, (rg[1] * 8.0 - 4.0) / scale_factor];
476                let c = sh.shade(deriv).map(|v| v.clamp(0.0, 1.0) as f32);
477                if c[3] > 0.0 || c[0] > 0.0 || c[1] > 0.0 || c[2] > 0.0 {
478                    fb.blend(px as usize, py as usize, c);
479                }
480            }
481        }
482    }
483}
484
485#[cfg(test)]
486mod tests {
487    use super::*;
488
489    fn png(w: u32, f: impl Fn(u32, u32) -> [u8; 3]) -> Vec<u8> {
490        let mut img = image::RgbaImage::new(w, w);
491        for (x, y, p) in img.enumerate_pixels_mut() {
492            let c = f(x, y);
493            *p = image::Rgba([c[0], c[1], c[2], 255]);
494        }
495        let mut out = Vec::new();
496        img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
497        out
498    }
499
500    #[test]
501    fn flat_dem_has_zero_slope_and_draws_nothing() {
502        let unpack = unpack_vector(&serde_json::json!({"encoding": "terrarium"}));
503        let d = Dem::decode(&png(8, |_, _| [128, 0, 0]), unpack).unwrap();
504        assert_eq!(d.get(3, 3), 0.0);
505        // deriv 0 → 0.5 → 128 (rounded).
506        assert!(d.prepare(10).iter().all(|t| *t == [128, 128]));
507        let sh = Shading::new(&serde_json::json!({"paint": {}}), 10.0);
508        // A flat pixel (128/255 → deriv ≈ 0.0157) is almost transparent.
509        let c = sh.shade([0.0, 0.0]);
510        assert!(c[3].abs() < 1e-9, "{c:?}");
511    }
512
513    #[test]
514    fn east_facing_slope_is_shaded_by_the_northwest_light() {
515        // Elevation falling to the east (mapbox encoding: blue steps of 0.1 m).
516        let d = Dem::decode(&png(16, |x, _| [1, 134, (255 - x * 10) as u8]), unpack_vector(&Json::Null)).unwrap();
517        let tex = d.prepare(12);
518        assert!(tex[5 * 16 + 5][0] < 128, "x slope negative: {:?}", tex[5 * 16 + 5]);
519        assert_eq!(tex[5 * 16 + 5][1], 128);
520        // Shadow side under the default light from 335°.
521        let sh = Shading::new(&serde_json::json!({"paint": {}}), 12.0);
522        let c = sh.shade([-1.0, 0.0]);
523        assert!(c[3] > 0.0 && c[0] < c[3], "{c:?}");
524    }
525
526    #[test]
527    fn backfill_copies_the_neighbour_edge() {
528        let unpack = unpack_vector(&serde_json::json!({"encoding": "terrarium"}));
529        let mut a = Dem::decode(&png(4, |_, _| [128, 0, 0]), unpack).unwrap();
530        let b = Dem::decode(&png(4, |x, _| [128, x as u8 * 10, 0]), unpack).unwrap();
531        a.backfill(&b, 1, 0);
532        // a's right border is b's first column (x = 0 → 0 m).
533        assert_eq!(a.get(4, 2), 0.0);
534        a.backfill(&b, -1, 0);
535        // a's left border is b's last column (x = 3 → 30 m).
536        assert_eq!(a.get(-1, 2), 30.0);
537    }
538
539    #[test]
540    fn literal_arrays_pad_to_the_longest() {
541        let layer = serde_json::json!({"paint": {
542            "hillshade-method": "multidirectional",
543            "hillshade-illumination-direction": [270, 315, 0],
544            "hillshade-highlight-color": ["#ff0000", "#00ff00"],
545        }});
546        let sh = Shading::new(&layer, 10.0);
547        assert_eq!(sh.azimuths.len(), 3);
548        assert_eq!(sh.highlights.len(), 3);
549        assert_eq!(sh.highlights[2], [0.0, 1.0, 0.0, 1.0]);
550        assert_eq!(sh.altitudes, vec![45f64.to_radians(); 3]);
551        assert!(sh.method == Method::Multidirectional);
552    }
553}