Skip to main content

dfui_map/
lib.rs

1//! Experimental vector maps for dfui: the app projects its geometry (e.g.
2//! from OpenStreetMap) with a [`MapBuilder`], which packs it into tiled
3//! [`Shape`]s at a few levels of detail, and [`map`] pans and zooms them.
4//! Shapes are stored on the GPU as they come into view, so moving the map
5//! mostly moves the rects they're drawn into.
6
7use std::cell::{Cell, OnceCell};
8use std::collections::HashMap;
9use std::ops::Range;
10use std::rc::Rc;
11use std::time::Duration;
12
13use dfui::path::{CAP_STEPS, Point, Quad, Stroke, stroke};
14use dfui::taffy::{Dimension, Size, Style};
15use dfui::widgets::Styled;
16use dfui::{
17    Color, Element, Event, EventCx, Font, Instant, PaintCx, Path, Rect, Shape, Text, Widget,
18};
19
20/// Most segments in one shape: the shader walks a band's segments per pixel.
21const MAX_QUADS: usize = 128;
22/// Cells aren't split below this side, metres.
23const MIN_CELL: f32 = 16.0;
24/// How far past its cell a tile's geometry is cut, metres, so the cut edge
25/// stays outside the cell's clip and never antialiases into a seam. Exact
26/// while it is half a px or more: from 0.25 px per metre.
27const MARGIN: f32 = 2.0;
28const EARTH_RADIUS: f64 = 6_371_000.0;
29/// Font size, logical px, at which a label starts to show.
30const MIN_LABEL_PX: f32 = 7.0;
31/// Least screen distance between labels with the same text, logical px.
32const LABEL_SPACING_PX: f32 = 300.0;
33/// Sharpest turn between neighbouring glyphs of a label, radians.
34const MAX_LABEL_TURN: f32 = 0.35;
35/// Pointer travel before a press becomes a pan, logical px.
36const SLOP: f32 = 6.0;
37/// Scales, logical px per metre, where a finer level of detail takes over;
38/// from the last one up the map draws at full detail.
39const LEVELS: [f32; 6] = [1.0 / 32.0, 1.0 / 16.0, 1.0 / 8.0, 0.25, 0.5, 1.0];
40const FULL: usize = LEVELS.len();
41/// How far a simplified line may stray, px at the largest scale of its level.
42const TOLERANCE_PX: f32 = 0.25;
43/// Features smaller than this, px, are left out of a level.
44const MIN_FEATURE_PX: f32 = 0.75;
45/// Narrower lines get no caps or bevels in a level, px.
46const JOIN_PX: f32 = 1.5;
47/// Largest tile side, px at the largest scale of its level: a tile costs
48/// every pixel it covers, so a sparse layer (a single bus line) mustn't
49/// spread few segments over a large cell.
50const MAX_CELL_PX: f32 = 256.0;
51/// Scale [`MAX_CELL_PX`] is measured at for full detail, px per metre.
52const FULL_CELL_SCALE: f32 = 4.0;
53/// Time a frame spends storing new tiles before leaving the rest for the
54/// next frames, coarser levels standing in.
55const BUDGET: Duration = Duration::from_millis(4);
56
57/// Collects areas and lines in metres around an origin and packs them into
58/// [`MapData`]. Layers draw in the order they were added.
59pub struct MapBuilder {
60    origin: (f64, f64),
61    cos: f64,
62    layers: Vec<LayerData>,
63    /// One tile each, drawn over every layer.
64    labels: Vec<Tile>,
65    /// Centres of the labels placed so far, by text.
66    placed: HashMap<String, Vec<Point>>,
67}
68
69struct LayerData {
70    color: Color,
71    min_scale: f32,
72    /// Closed rings, outlines wound positive and holes negative, so they
73    /// fill by nonzero winding however they're cut into tiles.
74    rings: Vec<Vec<Point>>,
75    lines: Vec<Run>,
76}
77
78/// A line by its middle, stroked when its tile is drawn.
79#[derive(Clone, Debug, PartialEq)]
80struct Run {
81    points: Vec<Point>,
82    width: f32,
83    /// Round caps at the first and last point; none where a tile cut it.
84    caps: [bool; 2],
85    /// Fill the outside of each bend.
86    bevels: bool,
87}
88
89impl Run {
90    /// The line as outlines, see [`stroke`].
91    fn stroke(&self) -> Vec<Vec<Point>> {
92        let style = Stroke {
93            width: self.width,
94            caps: self.caps,
95            bevels: self.bevels,
96        };
97        stroke(&self.points, style)
98    }
99}
100
101/// One of a [`MapBuilder`]'s layers.
102#[derive(Clone, Copy, Debug)]
103pub struct Layer(usize);
104
105impl MapBuilder {
106    /// A map centred on `lat`, `lon` in degrees.
107    pub fn new(lat: f64, lon: f64) -> Self {
108        MapBuilder {
109            origin: (lat, lon),
110            cos: lat.to_radians().cos(),
111            layers: Vec::new(),
112            labels: Vec::new(),
113            placed: HashMap::new(),
114        }
115    }
116
117    /// `lat`, `lon` in metres east and south of the origin; an
118    /// equirectangular projection, fine for a city.
119    pub fn point(&self, lat: f64, lon: f64) -> Point {
120        let x = (lon - self.origin.1).to_radians() * self.cos * EARTH_RADIUS;
121        let y = (self.origin.0 - lat).to_radians() * EARTH_RADIUS;
122        [x as f32, y as f32]
123    }
124
125    /// A layer drawn in `color`, hidden while zoomed out below `min_scale`
126    /// logical px per metre (0 always shows it).
127    pub fn layer(&mut self, color: Color, min_scale: f32) -> Layer {
128        self.layers.push(LayerData {
129            color,
130            min_scale,
131            rings: Vec::new(),
132            lines: Vec::new(),
133        });
134        Layer(self.layers.len() - 1)
135    }
136
137    /// A filled area, e.g. an OSM multipolygon: `outers` filled, `holes` cut
138    /// out of them. Rings may wind either way.
139    pub fn area(&mut self, layer: Layer, outers: &[Vec<Point>], holes: &[Vec<Point>]) {
140        let rings = &mut self.layers[layer.0].rings;
141        let all = outers.iter().map(|r| (r, true));
142        rings.extend(
143            all.chain(holes.iter().map(|r| (r, false)))
144                .filter_map(|(r, outer)| orient(r.clone(), outer)),
145        );
146    }
147
148    /// A line `width` metres wide through `points`, with round caps and
149    /// bevelled joins.
150    pub fn line(&mut self, layer: Layer, points: &[Point], width: f32) {
151        let mut points = points.to_vec();
152        points.dedup();
153        if points.len() >= 2 {
154            self.layers[layer.0].lines.push(Run {
155                points,
156                width,
157                caps: [true, true],
158                bevels: true,
159            });
160        }
161    }
162
163    /// `s` at `size` metres along the polyline, e.g. a street's name inside
164    /// it: centred, reading left to right, each glyph turned to the line
165    /// under its middle. Shows once `size` reaches [`MIN_LABEL_PX`] and the
166    /// same text placed earlier is [`LABEL_SPACING_PX`] away; false,
167    /// adding nothing, when the text is longer than the line or the line
168    /// bends too sharply under it.
169    pub fn label(
170        &mut self,
171        layer: Layer,
172        points: &[Point],
173        text: &Text,
174        font: Font,
175        s: &str,
176        size: f32,
177    ) -> bool {
178        let mut pts = points.to_vec();
179        pts.dedup();
180        if pts.len() < 2 {
181            return false;
182        }
183        if pts[pts.len() - 1][0] < pts[0][0] {
184            pts.reverse();
185        }
186        let mut along = vec![0.0];
187        for w in pts.windows(2) {
188            along.push(along[along.len() - 1] + (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1]));
189        }
190        let length = along[along.len() - 1];
191        let layout = text.layout(s, font, size, None);
192        if layout.width + size > length {
193            return false;
194        }
195        let start = (length - layout.width) / 2.0;
196        // Point and unit direction at distance `d` along the line.
197        let at = |d: f32| {
198            let i = along.partition_point(|&a| a <= d).clamp(1, pts.len() - 1);
199            let (a, b) = (pts[i - 1], pts[i]);
200            let len = along[i] - along[i - 1];
201            let t = [(b[0] - a[0]) / len, (b[1] - a[1]) / len];
202            let k = d - along[i - 1];
203            ([a[0] + t[0] * k, a[1] + t[1] * k], t)
204        };
205        let mid_y = layout.height / 2.0;
206        let mut contours = Vec::new();
207        let mut last: Option<f32> = None;
208        for g in text.glyph_paths(s, font, size) {
209            let xs = g.contours.iter().flatten().flatten().map(|p| p[0]);
210            let (lo, hi) = xs.fold((f32::MAX, f32::MIN), |(l, h), x| (l.min(x), h.max(x)));
211            let mid_x = (lo + hi) / 2.0;
212            let (o, t) = at(start + mid_x);
213            let angle = t[1].atan2(t[0]);
214            if let Some(a) = last {
215                let turn = (angle - a + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU);
216                if (turn - std::f32::consts::PI).abs() > MAX_LABEL_TURN {
217                    return false;
218                }
219            }
220            last = Some(angle);
221            // Glyph x runs along the line and y (down) to its right.
222            let place = |[x, y]: Point| {
223                let (u, v) = (x - mid_x, y - mid_y);
224                [o[0] + u * t[0] - v * t[1], o[1] + u * t[1] + v * t[0]]
225            };
226            contours.extend(
227                g.contours
228                    .into_iter()
229                    .map(|c| c.into_iter().map(|q| q.map(place)).collect::<Vec<_>>()),
230            );
231        }
232        let glyphs = Path { contours };
233        let Some(view) = bounds(glyphs.contours.iter().flatten().flatten()) else {
234            return false;
235        };
236        let (c, _) = at(length / 2.0);
237        let near = self.placed.entry(s.to_owned()).or_default();
238        let d = near.iter().map(|p| (p[0] - c[0]).hypot(p[1] - c[1]));
239        let spaced = LABEL_SPACING_PX / d.fold(f32::MAX, f32::min);
240        near.push(c);
241        let l = &self.layers[layer.0];
242        let pad = size / 4.0;
243        let cell = Rect::new(
244            view.x - pad,
245            view.y - pad,
246            view.w + 2.0 * pad,
247            view.h + 2.0 * pad,
248        );
249        let min_scale = l.min_scale.max(MIN_LABEL_PX / size).max(spaced);
250        let geo = Geometry {
251            glyphs,
252            ..Geometry::default()
253        };
254        self.labels.push(Tile::new(
255            cell,
256            l.color,
257            min_scale,
258            (layer.0 as u32, LABELS),
259            geo,
260        ));
261        true
262    }
263
264    /// Cuts every layer at each level of detail into quadtree cells of at
265    /// most [`MAX_QUADS`] segments.
266    pub fn build(self) -> MapData {
267        let (mut tiles, mut table) = (Vec::new(), Vec::new());
268        for (i, l) in self.layers.iter().enumerate() {
269            let mut serve = [FULL as u8; FULL + 1];
270            let mut finer = usize::MAX;
271            for level in (level_of(l.min_scale)..=FULL).rev() {
272                let (rings, runs) = detail(l, level);
273                // Not worth a level unless it halves what the finer one draws.
274                let c = cost(&rings, &runs);
275                if c.saturating_mul(2) > finer {
276                    serve[level] = serve[level + 1];
277                    continue;
278                }
279                (serve[level], finer) = (level as u8, c);
280                let lines = runs.iter().flat_map(|r| {
281                    let h = r.width / 2.0;
282                    r.points
283                        .iter()
284                        .flat_map(move |p| [[p[0] - h, p[1] - h], [p[0] + h, p[1] + h]])
285                });
286                let all: Vec<Point> = rings.iter().flatten().copied().chain(lines).collect();
287                if let Some(b) = bounds(all.iter()) {
288                    let from = tiles.len();
289                    split(l, (i as u32, level as u32), b, rings, runs, &mut tiles);
290                    tiles[from..].sort_by(|a, b| a.cell.x.total_cmp(&b.cell.x));
291                }
292            }
293            table.push((l.color, serve));
294        }
295        let full = tiles.iter().filter(|t| t.level == FULL as u32);
296        let bounds = full.map(|t| t.cell).reduce(|a, b| a.union(&b));
297        let mut labels = self.labels;
298        labels.sort_by(|a, b| a.cell.x.total_cmp(&b.cell.x));
299        tiles.extend(labels);
300        MapData::new(tiles, table, bounds.unwrap_or_default(), &[])
301    }
302}
303
304/// Which level draws at `scale`.
305fn level_of(scale: f32) -> usize {
306    LEVELS.iter().filter(|&&s| s <= scale).count()
307}
308
309/// A layer's rings and lines as drawn at `level`: simplified, small features
310/// left out, thin lines without caps or bevels.
311fn detail(l: &LayerData, level: usize) -> (Vec<Vec<Point>>, Vec<Run>) {
312    let Some(&px) = LEVELS.get(level) else {
313        return (l.rings.clone(), l.lines.clone());
314    };
315    let tol = TOLERANCE_PX / px;
316    let big = |pts: &[Point], pad: f32| {
317        bounds(pts.iter()).is_some_and(|b| (b.w.max(b.h) + pad) * px >= MIN_FEATURE_PX)
318    };
319    let rings = l.rings.iter().filter(|r| big(r, 0.0)).filter_map(|r| {
320        let mut closed = r.clone();
321        closed.push(r[0]);
322        let mut s = simplify(&closed, tol);
323        s.pop();
324        let outer = signed_area(r) > 0.0;
325        (s.len() >= 3 && (signed_area(&s) > 0.0) == outer && signed_area(&s) != 0.0).then_some(s)
326    });
327    let runs = l.lines.iter().filter(|r| big(&r.points, r.width)).map(|r| {
328        let fine = r.width * px >= JOIN_PX;
329        Run {
330            points: simplify(&r.points, tol),
331            width: r.width,
332            caps: r.caps.map(|c| c && fine),
333            bevels: r.bevels && fine,
334        }
335    });
336    (rings.collect(), runs.collect())
337}
338
339/// `pts` with the points that move it by no more than `tol` left out
340/// (Douglas–Peucker); the ends stay.
341fn simplify(pts: &[Point], tol: f32) -> Vec<Point> {
342    let n = pts.len();
343    if n < 3 {
344        return pts.to_vec();
345    }
346    let mut keep = vec![false; n];
347    (keep[0], keep[n - 1]) = (true, true);
348    let mut todo = vec![(0, n - 1)];
349    while let Some((a, b)) = todo.pop() {
350        let (mut far, mut most) = (0, tol);
351        for (i, &p) in pts.iter().enumerate().take(b).skip(a + 1) {
352            let d = distance(p, pts[a], pts[b]);
353            if d > most {
354                (far, most) = (i, d);
355            }
356        }
357        if far != 0 {
358            keep[far] = true;
359            todo.extend([(a, far), (far, b)]);
360        }
361    }
362    pts.iter()
363        .zip(keep)
364        .filter(|(_, k)| *k)
365        .map(|(p, _)| *p)
366        .collect()
367}
368
369/// From `p` to the segment `a`–`b`.
370fn distance(p: Point, a: Point, b: Point) -> f32 {
371    let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
372    let len2 = dx * dx + dy * dy;
373    let t = match len2 > 0.0 {
374        true => (((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / len2).clamp(0.0, 1.0),
375        false => 0.0,
376    };
377    (p[0] - a[0] - t * dx).hypot(p[1] - a[1] - t * dy)
378}
379
380/// `ring` wound positive for an outline, negative for a hole; `None` when
381/// it encloses nothing.
382fn orient(mut ring: Vec<Point>, outer: bool) -> Option<Vec<Point>> {
383    let area = signed_area(&ring);
384    if ring.len() < 3 || area == 0.0 {
385        return None;
386    }
387    if (area > 0.0) != outer {
388        ring.reverse();
389    }
390    Some(ring)
391}
392
393/// Twice the ring's area, positive when it winds clockwise on screen (y down).
394fn signed_area(ring: &[Point]) -> f32 {
395    let n = ring.len();
396    (0..n)
397        .map(|i| {
398            let (a, b) = (ring[i], ring[(i + 1) % n]);
399            a[0] * b[1] - b[0] * a[1]
400        })
401        .sum()
402}
403
404fn bounds<'a>(points: impl Iterator<Item = &'a Point>) -> Option<Rect> {
405    let (mut lo, mut hi) = ([f32::MAX; 2], [f32::MIN; 2]);
406    for p in points {
407        lo = [lo[0].min(p[0]), lo[1].min(p[1])];
408        hi = [hi[0].max(p[0]), hi[1].max(p[1])];
409    }
410    (lo[0] <= hi[0]).then(|| Rect::new(lo[0], lo[1], hi[0] - lo[0], hi[1] - lo[1]))
411}
412
413fn grow(r: Rect, by: f32) -> Rect {
414    Rect::new(r.x - by, r.y - by, r.w + 2.0 * by, r.h + 2.0 * by)
415}
416
417/// Segments the shape of these rings and runs will have, roughly.
418fn cost(rings: &[Vec<Point>], runs: &[Run]) -> usize {
419    let lines = runs.iter().map(|r| {
420        let n = r.points.len() - 1;
421        let caps = r.caps.iter().filter(|c| **c).count();
422        4 * n + if r.bevels { 3 * (n - 1) } else { 0 } + caps * (CAP_STEPS + 1)
423    });
424    rings.iter().map(Vec::len).sum::<usize>() + lines.sum::<usize>()
425}
426
427/// One tile for `rings` and `runs` (already cut to `cell` plus [`MARGIN`]),
428/// or four for its quarters while it holds too many segments.
429fn split(
430    l: &LayerData,
431    at: (u32, u32),
432    cell: Rect,
433    rings: Vec<Vec<Point>>,
434    runs: Vec<Run>,
435    tiles: &mut Vec<Tile>,
436) {
437    if rings.is_empty() && runs.is_empty() {
438        return;
439    }
440    let px = LEVELS
441        .get(at.1 as usize)
442        .copied()
443        .unwrap_or(FULL_CELL_SCALE);
444    let side = cell.w.max(cell.h);
445    if (cost(&rings, &runs) <= MAX_QUADS && side * px <= MAX_CELL_PX) || side < MIN_CELL {
446        let geo = Geometry {
447            rings,
448            runs,
449            glyphs: Path::default(),
450        };
451        tiles.push(Tile::new(cell, l.color, l.min_scale, at, geo));
452        return;
453    }
454    let (w, h) = (cell.w / 2.0, cell.h / 2.0);
455    for (i, j) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)] {
456        let c = Rect::new(cell.x + i * w, cell.y + j * h, w, h);
457        let m = grow(c, MARGIN);
458        let cut = rings.iter().filter_map(|r| clip(r, m)).collect();
459        // Past the margin by half the width, a segment's outline can't reach it.
460        let pieces = runs.iter().flat_map(|r| cut_run(r, grow(m, r.width / 2.0)));
461        split(l, at, c, cut, pieces.collect(), tiles);
462    }
463}
464
465/// `ring` cut to `r` (Sutherland–Hodgman): for a concave ring the pieces stay
466/// joined along `r`'s edges, by edges that cancel out when filled.
467fn clip(ring: &[Point], r: Rect) -> Option<Vec<Point>> {
468    let b = bounds(ring.iter())?;
469    let inside = b.x >= r.x && b.y >= r.y && b.x + b.w <= r.x + r.w && b.y + b.h <= r.y + r.h;
470    if inside {
471        return Some(ring.to_vec());
472    }
473    let hit = r.intersect(&b);
474    if hit.w <= 0.0 || hit.h <= 0.0 {
475        return None;
476    }
477    let edges = [
478        (0, r.x, 1.0),
479        (0, r.x + r.w, -1.0),
480        (1, r.y, 1.0),
481        (1, r.y + r.h, -1.0),
482    ];
483    let mut out = ring.to_vec();
484    for (axis, at, side) in edges {
485        let keep = |p: Point| (p[axis] - at) * side >= 0.0;
486        let input = std::mem::take(&mut out);
487        for (k, &a) in input.iter().enumerate() {
488            let b = input[(k + 1) % input.len()];
489            if keep(a) {
490                out.push(a);
491            }
492            if keep(a) != keep(b) {
493                let t = (at - a[axis]) / (b[axis] - a[axis]);
494                out.push([a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])]);
495            }
496        }
497        if out.is_empty() {
498            return None;
499        }
500    }
501    (out.len() >= 3 && signed_area(&out) != 0.0).then_some(out)
502}
503
504/// The pieces of `run` inside `r`; ends made by the cut get no cap.
505fn cut_run(run: &Run, r: Rect) -> Vec<Run> {
506    let Some(b) = bounds(run.points.iter()) else {
507        return Vec::new();
508    };
509    if b.x >= r.x && b.y >= r.y && b.x + b.w <= r.x + r.w && b.y + b.h <= r.y + r.h {
510        return vec![run.clone()];
511    }
512    let (mut out, mut cur, mut cap) = (Vec::new(), Vec::new(), false);
513    let mut flush = |cur: &mut Vec<Point>, caps: [bool; 2]| {
514        let mut points = std::mem::take(cur);
515        points.dedup();
516        if points.len() >= 2 {
517            out.push(Run {
518                points,
519                caps,
520                ..*run
521            });
522        }
523    };
524    let last = run.points.len() - 2;
525    for (i, w) in run.points.windows(2).enumerate() {
526        let Some((a, z, t0, t1)) = clip_segment(w[0], w[1], r) else {
527            flush(&mut cur, [cap, false]);
528            continue;
529        };
530        if cur.is_empty() {
531            cur.push(a);
532            cap = run.caps[0] && i == 0 && t0 == 0.0;
533        }
534        cur.push(z);
535        if t1 < 1.0 {
536            flush(&mut cur, [cap, false]);
537        } else if i == last {
538            flush(&mut cur, [cap, run.caps[1]]);
539        }
540    }
541    out
542}
543
544/// The part of `a`–`b` inside `r` and where it starts and ends along it
545/// (Liang–Barsky).
546fn clip_segment(a: Point, b: Point, r: Rect) -> Option<(Point, Point, f32, f32)> {
547    let d = [b[0] - a[0], b[1] - a[1]];
548    let (mut t0, mut t1) = (0.0f32, 1.0f32);
549    for (p, q) in [
550        (-d[0], a[0] - r.x),
551        (d[0], r.x + r.w - a[0]),
552        (-d[1], a[1] - r.y),
553        (d[1], r.y + r.h - a[1]),
554    ] {
555        if p == 0.0 {
556            if q < 0.0 {
557                return None;
558            }
559        } else if p < 0.0 {
560            t0 = t0.max(q / p);
561        } else {
562            t1 = t1.min(q / p);
563        }
564    }
565    let at = |t: f32| [a[0] + t * d[0], a[1] + t * d[1]];
566    (t0 <= t1).then(|| (at(t0), at(t1), t0, t1))
567}
568
569/// What a tile draws: areas cut to its cell, lines by their middle and,
570/// for a label, glyph outlines.
571#[derive(Default, Debug, PartialEq)]
572struct Geometry {
573    rings: Vec<Vec<Point>>,
574    runs: Vec<Run>,
575    glyphs: Path,
576}
577
578impl Geometry {
579    /// Everything as one path, lines stroked and cut to `margin`.
580    fn path(&self, margin: Rect) -> Path {
581        let mut stroked = Vec::new();
582        for r in &self.runs {
583            stroked.extend(r.stroke());
584        }
585        let cut = stroked.iter().filter_map(|r| clip(r, margin));
586        let rings = self.rings.iter().cloned().chain(cut);
587        let mut contours: Vec<Vec<Quad>> = rings.flat_map(|r| Path::polygon(&r).contours).collect();
588        contours.extend(self.glyphs.contours.iter().cloned());
589        Path { contours }
590    }
591}
592
593/// The level of label tiles, drawn over every layer at every scale.
594const LABELS: u32 = u32::MAX;
595
596struct Tile {
597    /// What the tile covers and is clipped to when drawn, metres.
598    cell: Rect,
599    color: Color,
600    min_scale: f32,
601    layer: u32,
602    /// Index into [`LEVELS`], [`FULL`], or [`LABELS`].
603    level: u32,
604    /// Set for a built map; a map read from bytes decodes it from `at`.
605    geo: Option<Geometry>,
606    at: Range<usize>,
607    /// The shape and its view box, made on first use.
608    shape: OnceCell<Option<(Shape, Rect)>>,
609    /// Drawn at least once, so its shape is on the GPU.
610    stored: Cell<bool>,
611}
612
613impl Tile {
614    fn new(
615        cell: Rect,
616        color: Color,
617        min_scale: f32,
618        (layer, level): (u32, u32),
619        geo: Geometry,
620    ) -> Tile {
621        Tile {
622            cell,
623            color,
624            min_scale,
625            layer,
626            level,
627            geo: Some(geo),
628            at: 0..0,
629            shape: OnceCell::new(),
630            stored: Cell::new(false),
631        }
632    }
633}
634
635/// Tiles of one layer at one level, or the labels, sorted by their cell's
636/// left edge.
637#[derive(Clone, Debug, Default, PartialEq)]
638struct Group {
639    tiles: Range<usize>,
640    /// The widest cell, to find the tiles that may reach into a view.
641    widest: f32,
642}
643
644/// Geometry ready to draw, from [`MapBuilder::build`] or
645/// [`MapData::from_bytes`]. Make it once and share it, e.g. in the `App`.
646pub struct MapData {
647    /// By layer then level, labels last.
648    tiles: Vec<Tile>,
649    /// Each layer's tiles at each level.
650    layers: Vec<[Group; FULL + 1]>,
651    /// Each layer's color and the level that draws in place of each.
652    table: Vec<(Color, [u8; FULL + 1])>,
653    labels: Group,
654    bounds: Rect,
655    /// What [`MapData::from_bytes`] read; the tiles' geometry lies in it.
656    bytes: &'static [u8],
657}
658
659/// Coordinates are stored on this grid, metres: fine enough at the deepest zoom.
660const GRID: f32 = 0.001;
661
662/// Zigzag varints of grid coordinates, as deltas from the previous point.
663struct Writer {
664    out: Vec<u8>,
665    origin: Point,
666    at: [i64; 2],
667}
668
669impl Writer {
670    fn put(&mut self, v: i64) {
671        let mut u = ((v << 1) ^ (v >> 63)) as u64;
672        while u >= 0x80 {
673            self.out.push(u as u8 | 0x80);
674            u >>= 7;
675        }
676        self.out.push(u as u8);
677    }
678
679    fn grid(&self, p: Point) -> [i64; 2] {
680        let g = |v: f32, o: f32| ((v - o) / GRID).round() as i64;
681        [g(p[0], self.origin[0]), g(p[1], self.origin[1])]
682    }
683
684    fn point(&mut self, p: Point) {
685        let q = self.grid(p);
686        self.put(q[0] - self.at[0]);
687        self.put(q[1] - self.at[1]);
688        self.at = q;
689    }
690
691    fn points(&mut self, pts: &[Point]) {
692        self.put(pts.len() as i64);
693        for &p in pts {
694            self.point(p);
695        }
696    }
697}
698
699struct Reader<'a> {
700    bytes: std::slice::Iter<'a, u8>,
701    origin: Point,
702    at: [i64; 2],
703}
704
705impl Reader<'_> {
706    fn get(&mut self) -> Option<i64> {
707        let (mut u, mut shift) = (0u64, 0);
708        loop {
709            let b = *self.bytes.next()?;
710            u |= u64::from(b & 0x7f) << shift.min(63);
711            if b < 0x80 {
712                return Some((u >> 1) as i64 ^ -((u & 1) as i64));
713            }
714            shift += 7;
715        }
716    }
717
718    fn count(&mut self) -> Option<usize> {
719        usize::try_from(self.get()?).ok()
720    }
721
722    fn pos(&self, q: [i64; 2]) -> Point {
723        [
724            self.origin[0] + q[0] as f32 * GRID,
725            self.origin[1] + q[1] as f32 * GRID,
726        ]
727    }
728
729    fn point(&mut self) -> Option<Point> {
730        self.at = [self.at[0] + self.get()?, self.at[1] + self.get()?];
731        Some(self.pos(self.at))
732    }
733
734    fn points(&mut self) -> Option<Vec<Point>> {
735        (0..self.count()?).map(|_| self.point()).collect()
736    }
737}
738
739/// A tile's geometry, compactly: its rings as counted point lists; its
740/// runs each with a width in grid steps, a flags varint (caps at either
741/// end, bevels) and the points; then the glyph contours, each a count of
742/// quads, its start point and each quad's end point and, for a curve, its
743/// control point. Points are grid steps from the cell's corner, stored as
744/// zigzag varint deltas; a straight glyph edge, whose control point is its
745/// middle, stores none and flags that in the low bit of its first delta.
746fn encode(geo: &Geometry, origin: Point) -> Vec<u8> {
747    let mut w = Writer {
748        out: Vec::new(),
749        origin,
750        at: [0, 0],
751    };
752    w.put(geo.rings.len() as i64);
753    for r in &geo.rings {
754        w.points(r);
755    }
756    w.put(geo.runs.len() as i64);
757    for r in &geo.runs {
758        w.put((r.width / GRID).round() as i64);
759        let flags = [r.caps[0], r.caps[1], r.bevels];
760        w.put(flags.iter().rev().fold(0, |f, &b| f << 1 | i64::from(b)));
761        w.points(&r.points);
762    }
763    w.put(geo.glyphs.contours.len() as i64);
764    for c in &geo.glyphs.contours {
765        w.put(c.len() as i64);
766        w.point(c.first().map_or(origin, |s| s[0]));
767        for &[a, ctl, b] in c {
768            let curve = ctl != [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0];
769            let (e, k) = (w.grid(b), w.grid(ctl));
770            let at = w.at;
771            w.put((e[0] - at[0]) * 2 + i64::from(curve));
772            w.put(e[1] - at[1]);
773            if curve {
774                w.put(k[0] - at[0]);
775                w.put(k[1] - at[1]);
776            }
777            w.at = e;
778        }
779    }
780    w.out
781}
782
783/// The geometry [`encode`] wrote; `None` if `bytes` are truncated.
784fn decode(bytes: &[u8], origin: Point) -> Option<Geometry> {
785    let mut r = Reader {
786        bytes: bytes.iter(),
787        origin,
788        at: [0, 0],
789    };
790    let rings = (0..r.count()?).map(|_| r.points()).collect::<Option<_>>()?;
791    let mut runs = Vec::new();
792    for _ in 0..r.count()? {
793        let width = r.get()? as f32 * GRID;
794        let f = r.get()?;
795        runs.push(Run {
796            width,
797            caps: [f & 1 != 0, f & 2 != 0],
798            bevels: f & 4 != 0,
799            points: r.points()?,
800        });
801    }
802    let mut contours = Vec::new();
803    for _ in 0..r.count()? {
804        let n = r.count()?;
805        r.point()?;
806        let mut quads = Vec::new();
807        for _ in 0..n {
808            let (dx, dy) = (r.get()?, r.get()?);
809            let (a, curve) = (r.pos(r.at), dx & 1 == 1);
810            let e = [r.at[0] + (dx - i64::from(curve)) / 2, r.at[1] + dy];
811            let ctl = match curve {
812                true => {
813                    let k = [r.at[0] + r.get()?, r.at[1] + r.get()?];
814                    r.pos(k)
815                }
816                false => [(a[0] + r.pos(e)[0]) / 2.0, (a[1] + r.pos(e)[1]) / 2.0],
817            };
818            quads.push([a, ctl, r.pos(e)]);
819            r.at = e;
820        }
821        contours.push(quads);
822    }
823    Some(Geometry {
824        rings,
825        runs,
826        glyphs: Path { contours },
827    })
828}
829
830/// Words per tile in the index: cell, min_scale, layer and level, and the
831/// length of its geometry.
832const INDEX_WORDS: usize = 7;
833
834impl MapData {
835    fn new(
836        tiles: Vec<Tile>,
837        table: Vec<(Color, [u8; FULL + 1])>,
838        bounds: Rect,
839        bytes: &'static [u8],
840    ) -> MapData {
841        let mut layers: Vec<[Group; FULL + 1]> = vec![Default::default(); table.len()];
842        let mut labels = Group::default();
843        let span = |g: &mut Group, i: usize| {
844            let r = &mut g.tiles;
845            *r = if r.start == r.end {
846                i..i + 1
847            } else {
848                r.start.min(i)..r.end.max(i + 1)
849            };
850            g.widest = g.widest.max(tiles[i].cell.w);
851        };
852        for (i, t) in tiles.iter().enumerate() {
853            if t.level == LABELS {
854                span(&mut labels, i);
855                continue;
856            }
857            if let Some(l) = layers.get_mut(t.layer as usize) {
858                span(&mut l[(t.level as usize).min(FULL)], i);
859            }
860        }
861        for (l, (_, serve)) in layers.iter_mut().zip(&table) {
862            *l = serve.map(|k| l[(k as usize).min(FULL)].clone());
863        }
864        MapData {
865            tiles,
866            layers,
867            table,
868            labels,
869            bounds,
870            bytes,
871        }
872    }
873
874    /// The map as [`MapData::from_bytes`] reads it, little-endian: `DFM2`,
875    /// the bounds as four f32; a u32 count of layers and for each its color
876    /// as four f32 and a u32 of the level drawn in place of each, four bits
877    /// a level; a u32 count of tiles and for each its cell as four f32,
878    /// min_scale, a u32 of its layer and (high byte, 255 for labels) level
879    /// and a u32 length of its geometry; then each tile's geometry as
880    /// [`encode`] writes it.
881    pub fn to_bytes(&self) -> Vec<u8> {
882        let geos: Vec<Vec<u8>> = self
883            .tiles
884            .iter()
885            .map(|t| match &t.geo {
886                Some(g) => encode(g, [t.cell.x, t.cell.y]),
887                None => self.bytes[t.at.clone()].to_vec(),
888            })
889            .collect();
890        let b = self.bounds;
891        let bits = f32::from_bits;
892        let mut words = vec![b.x, b.y, b.w, b.h, bits(self.table.len() as u32)];
893        for (k, serve) in &self.table {
894            let packed = serve.iter().rev().fold(0, |p, &l| p << 4 | u32::from(l));
895            words.extend([k.r, k.g, k.b, k.a, bits(packed)]);
896        }
897        words.push(bits(self.tiles.len() as u32));
898        for (t, geo) in self.tiles.iter().zip(&geos) {
899            let c = t.cell;
900            let at = t.layer | t.level.min(255) << 24;
901            words.extend([
902                c.x,
903                c.y,
904                c.w,
905                c.h,
906                t.min_scale,
907                bits(at),
908                bits(geo.len() as u32),
909            ]);
910        }
911        let mut out = b"DFM2".to_vec();
912        out.extend(words.iter().flat_map(|w| w.to_le_bytes()));
913        out.extend(geos.concat());
914        out
915    }
916
917    /// A map written by [`MapData::to_bytes`], usually `include_bytes!`d.
918    /// Only the index is read here; each tile is decoded the first time
919    /// it's drawn. `None` if `bytes` aren't one or are truncated.
920    pub fn from_bytes(bytes: &'static [u8]) -> Option<MapData> {
921        let body = bytes.strip_prefix(b"DFM2")?;
922        let word = |i: usize| {
923            let w = body.get(i * 4..i * 4 + 4)?;
924            Some(f32::from_le_bytes(w.try_into().ok()?))
925        };
926        let rect = |i: usize| {
927            Some(Rect::new(
928                word(i)?,
929                word(i + 1)?,
930                word(i + 2)?,
931                word(i + 3)?,
932            ))
933        };
934        let bits = |i: usize| Some(word(i)?.to_bits());
935        let (bounds, layers) = (rect(0)?, bits(4)? as usize);
936        let mut table = Vec::new();
937        for i in (0..layers).map(|i| 5 + i * 5) {
938            let (k, packed) = (rect(i)?, bits(i + 4)?);
939            let color = Color {
940                r: k.x,
941                g: k.y,
942                b: k.w,
943                a: k.h,
944            };
945            let serve: [u8; FULL + 1] = std::array::from_fn(|l| (packed >> (4 * l) & 15) as u8);
946            table.push((color, serve));
947        }
948        let first = 5 + layers.checked_mul(5)? + 1;
949        let n = bits(first - 1)? as usize;
950        let mut at = 4 + (first + n.checked_mul(INDEX_WORDS)?) * 4;
951        let mut tiles = Vec::with_capacity(n.min(bytes.len()));
952        for i in (0..n).map(|i| first + i * INDEX_WORDS) {
953            let (packed, len) = (bits(i + 5)?, bits(i + 6)? as usize);
954            let layer = packed & 0xff_ffff;
955            let level = match packed >> 24 {
956                255 => LABELS,
957                l => l,
958            };
959            tiles.push(Tile {
960                cell: rect(i)?,
961                color: table.get(layer as usize)?.0,
962                min_scale: word(i + 4)?,
963                layer,
964                level,
965                geo: None,
966                at: at..at + len,
967                shape: OnceCell::new(),
968                stored: Cell::new(false),
969            });
970            at += len;
971        }
972        (at <= bytes.len()).then(|| MapData::new(tiles, table, bounds, bytes))
973    }
974
975    /// The tile's shape and view box, made on first use; `None` if it has
976    /// nothing to draw or its bytes are corrupt.
977    fn shape<'a>(&self, t: &'a Tile) -> Option<&'a (Shape, Rect)> {
978        t.shape
979            .get_or_init(|| {
980                let decoded;
981                let geo = match &t.geo {
982                    Some(g) => g,
983                    None => {
984                        decoded = decode(&self.bytes[t.at.clone()], [t.cell.x, t.cell.y])?;
985                        &decoded
986                    }
987                };
988                let path = geo.path(grow(t.cell, MARGIN));
989                let view = bounds(path.contours.iter().flatten().flatten())?;
990                Some((Shape::new(path, view), view))
991            })
992            .as_ref()
993    }
994
995    /// The group's tiles whose cells may overlap `view`.
996    fn near(&self, g: &Group, view: Rect) -> &[Tile] {
997        let tiles = &self.tiles[g.tiles.clone()];
998        let lo = tiles.partition_point(|t| t.cell.x + g.widest < view.x);
999        let hi = tiles.partition_point(|t| t.cell.x <= view.x + view.w);
1000        &tiles[lo..hi.max(lo)]
1001    }
1002
1003    /// The tiles across every level, for gauging how heavy a map is.
1004    pub fn tiles(&self) -> usize {
1005        self.tiles.len()
1006    }
1007
1008    /// The segments across all tiles, each 32 bytes on the GPU once drawn.
1009    pub fn segments(&self) -> usize {
1010        let quads = self
1011            .tiles
1012            .iter()
1013            .filter_map(|t| self.shape(t))
1014            .map(|(s, _)| s.path().contours.iter().map(Vec::len).sum::<usize>());
1015        quads.sum()
1016    }
1017}
1018
1019#[derive(Default)]
1020struct View {
1021    /// Metres at the widget's centre.
1022    center: Point,
1023    /// Logical px per metre; 0 until fitted to the widget.
1024    scale: f32,
1025    /// Where the press began and the last pointer position.
1026    press: Option<(Point, Point)>,
1027    panning: bool,
1028    /// The last [`Map::focus`] applied.
1029    focused: Option<(Point, f32)>,
1030}
1031
1032impl View {
1033    fn fit(&mut self, map: &Map, r: Rect) {
1034        let b = map.data.bounds;
1035        if self.scale <= 0.0 && b.w > 0.0 {
1036            (self.center, self.scale) = map.start.unwrap_or((
1037                [b.x + b.w / 2.0, b.y + b.h / 2.0],
1038                (r.w / b.w).min(r.h / b.h),
1039            ));
1040        }
1041        if map.focus != self.focused {
1042            if let Some((center, scale)) = map.focus {
1043                (self.center, self.scale) = (center, self.scale.max(scale));
1044            }
1045            self.focused = map.focus;
1046        }
1047    }
1048
1049    /// Zooms by `k` keeping the metre under `(x, y)` in place.
1050    fn zoom(&mut self, data: &MapData, r: Rect, x: f32, y: f32, k: f32) {
1051        let fit = (r.w / data.bounds.w).min(r.h / data.bounds.h);
1052        let to = (self.scale * k).clamp(fit / 4.0, 200.0);
1053        let (dx, dy) = (x - r.x - r.w / 2.0, y - r.y - r.h / 2.0);
1054        let d = 1.0 / self.scale - 1.0 / to;
1055        self.center = [self.center[0] + dx * d, self.center[1] + dy * d];
1056        self.scale = to;
1057    }
1058}
1059/// A pannable, zoomable map of `data`: drag to pan; wheel, ctrl+wheel or
1060/// pinch to zoom. Fills its parent's space by default.
1061pub fn map(data: &Rc<MapData>) -> Map {
1062    Map {
1063        data: data.clone(),
1064        style: Style {
1065            size: Size {
1066                width: Dimension::percent(1.0),
1067                height: Dimension::percent(1.0),
1068            },
1069            ..Style::default()
1070        },
1071        start: None,
1072        focus: None,
1073        on_tap: None,
1074        overlay: None,
1075    }
1076}
1077
1078type TapFn = dyn Fn(&mut EventCx, Point);
1079type OverlayFn = dyn Fn(&mut PaintCx, &dyn Fn(Point) -> Point);
1080
1081/// See [`map`].
1082pub struct Map {
1083    data: Rc<MapData>,
1084    style: Style,
1085    start: Option<(Point, f32)>,
1086    focus: Option<(Point, f32)>,
1087    on_tap: Option<Rc<TapFn>>,
1088    overlay: Option<Rc<OverlayFn>>,
1089}
1090
1091impl Map {
1092    /// Opens centred on `center` (from [`MapBuilder::point`]) at `scale`
1093    /// logical px per metre, instead of fitting the whole map.
1094    pub fn start(mut self, center: Point, scale: f32) -> Self {
1095        self.start = Some((center, scale));
1096        self
1097    }
1098
1099    /// Centres on `center` and zooms in to at least `scale` whenever this
1100    /// differs from the focus of the last build, e.g. to show a search result.
1101    pub fn focus(mut self, focus: Option<(Point, f32)>) -> Self {
1102        self.focus = focus;
1103        self
1104    }
1105
1106    /// Paints over the map, given a function from map points to logical px,
1107    /// e.g. to draw markers that keep their size while zooming.
1108    pub fn overlay(mut self, f: impl Fn(&mut PaintCx, &dyn Fn(Point) -> Point) + 'static) -> Self {
1109        self.overlay = Some(Rc::new(f));
1110        self
1111    }
1112
1113    /// Runs on a tap that didn't pan or pinch, with the map point under it
1114    /// in [`MapBuilder::point`] metres.
1115    pub fn on_tap(mut self, f: impl Fn(&mut EventCx, Point) + 'static) -> Self {
1116        self.on_tap = Some(Rc::new(f));
1117        self
1118    }
1119}
1120
1121impl From<Map> for Element {
1122    fn from(w: Map) -> Self {
1123        Element::new(w)
1124    }
1125}
1126
1127impl Styled for Map {
1128    fn style_mut(&mut self) -> &mut Style {
1129        &mut self.style
1130    }
1131}
1132
1133impl Widget for Map {
1134    fn style(&self) -> Style {
1135        self.style.clone()
1136    }
1137
1138    fn paint(&self, cx: &mut PaintCx) {
1139        let r = cx.rect;
1140        let v = cx.state.get::<View>();
1141        v.fit(self, r);
1142        let (s, c) = (v.scale, v.center);
1143        let visible = Rect::new(c[0] - r.w / 2.0 / s, c[1] - r.h / 2.0 / s, r.w / s, r.h / s);
1144        let screen = |b: Rect| {
1145            let x = r.x + r.w / 2.0 + (b.x - c[0]) * s;
1146            let y = r.y + r.h / 2.0 + (b.y - c[1]) * s;
1147            Rect::new(x, y, b.w * s, b.h * s)
1148        };
1149        let data = &*self.data;
1150        let (level, start) = (level_of(s), Instant::now());
1151        let mut pending = false;
1152        let seen = |c: Rect| {
1153            let hit = visible.intersect(&c);
1154            hit.w > 0.0 && hit.h > 0.0
1155        };
1156        let draw = |cx: &mut PaintCx, t: &Tile, clip: Rect| {
1157            if let Some((shape, view)) = data.shape(t) {
1158                cx.with_clip(screen(clip), |cx| cx.shape(shape, screen(*view), t.color));
1159            }
1160            t.stored.set(true);
1161        };
1162        cx.with_clip(r, |cx| {
1163            for levels in &data.layers {
1164                let tiles = data.near(&levels[level], visible);
1165                if tiles.first().is_none_or(|t| s < t.min_scale) {
1166                    continue;
1167                }
1168                let mut holes = Vec::new();
1169                for t in tiles.iter().filter(|t| seen(t.cell)) {
1170                    if t.stored.get() || start.elapsed() < BUDGET {
1171                        draw(cx, t, t.cell);
1172                    } else {
1173                        holes.push(t.cell);
1174                    }
1175                }
1176                if holes.is_empty() {
1177                    continue;
1178                }
1179                pending = true;
1180                // Coarser levels in view, finest first, skipping ones that
1181                // reuse a finer level's tiles.
1182                let mut coarser: Vec<Vec<&Tile>> = Vec::new();
1183                let mut used = vec![levels[level].clone()];
1184                for l in (0..level).rev() {
1185                    if !used.contains(&levels[l]) {
1186                        used.push(levels[l].clone());
1187                        let tiles = data.near(&levels[l], visible);
1188                        coarser.push(tiles.iter().filter(|t| seen(t.cell)).collect());
1189                    }
1190                }
1191                // The finest that has all it needs stored stands in, else the coarsest.
1192                for hole in holes {
1193                    let over = |t: &&&Tile| {
1194                        let hit = t.cell.intersect(&hole);
1195                        hit.w > 0.0 && hit.h > 0.0
1196                    };
1197                    let mut cover: Vec<&Tile> = Vec::new();
1198                    for tiles in &coarser {
1199                        let here: Vec<&Tile> = tiles.iter().filter(over).copied().collect();
1200                        if here.is_empty() {
1201                            continue;
1202                        }
1203                        cover = here;
1204                        if cover.iter().all(|t| t.stored.get()) {
1205                            break;
1206                        }
1207                    }
1208                    for t in cover {
1209                        draw(cx, t, t.cell.intersect(&hole));
1210                    }
1211                }
1212            }
1213            for t in data.near(&data.labels, visible) {
1214                if s < t.min_scale || !seen(t.cell) {
1215                    continue;
1216                }
1217                if t.stored.get() || start.elapsed() < BUDGET {
1218                    draw(cx, t, t.cell);
1219                } else {
1220                    pending = true;
1221                }
1222            }
1223            if let Some(f) = &self.overlay {
1224                let at = |p: Point| {
1225                    [
1226                        r.x + r.w / 2.0 + (p[0] - c[0]) * s,
1227                        r.y + r.h / 2.0 + (p[1] - c[1]) * s,
1228                    ]
1229                };
1230                f(cx, &at);
1231            }
1232        });
1233        if pending {
1234            cx.request_frame();
1235        }
1236    }
1237
1238    fn event(&self, ev: &Event, cx: &mut EventCx) {
1239        let (r, data) = (cx.rect, &*self.data);
1240        let inside = |x, y| cx.rect.contains(x, y) && cx.clip.contains(x, y);
1241        let (mut capture, mut stop, mut tap) = (false, false, None);
1242        let v = cx.state.get::<View>();
1243        v.fit(self, r);
1244        match *ev {
1245            Event::PointerDown { x, y } if inside(x, y) => {
1246                v.press = Some(([x, y], [x, y]));
1247                v.panning = false;
1248            }
1249            Event::PointerMove { x, y } => {
1250                let Some((start, last)) = v.press else { return };
1251                v.panning |= (x - start[0]).hypot(y - start[1]) > SLOP;
1252                if v.panning {
1253                    let s = v.scale;
1254                    v.center = [
1255                        v.center[0] - (x - last[0]) / s,
1256                        v.center[1] - (y - last[1]) / s,
1257                    ];
1258                    v.press = Some((start, [x, y]));
1259                    capture = true;
1260                }
1261            }
1262            Event::PointerUp { x, y } => {
1263                if v.press.take().is_some() && !v.panning && inside(x, y) {
1264                    let s = v.scale;
1265                    let c = v.center;
1266                    tap = Some([
1267                        c[0] + (x - r.x - r.w / 2.0) / s,
1268                        c[1] + (y - r.y - r.h / 2.0) / s,
1269                    ]);
1270                }
1271            }
1272            Event::Cancel => v.press = None,
1273            Event::Wheel { x, y, dy, .. } if inside(x, y) => {
1274                v.zoom(data, r, x, y, (-dy / 200.0).exp());
1275                stop = true;
1276            }
1277            Event::Pinch { x, y, scale } if inside(x, y) || v.press.is_some() => {
1278                v.zoom(data, r, x, y, scale);
1279                // Two fingers held still are a pinch, not a tap.
1280                (v.panning, capture, stop) = (true, true, true);
1281            }
1282            _ => return,
1283        }
1284        if capture {
1285            cx.capture();
1286        }
1287        if stop {
1288            cx.stop();
1289        }
1290        if let (Some(p), Some(f)) = (tap, &self.on_tap) {
1291            f(cx, p);
1292        }
1293        cx.request_redraw();
1294    }
1295}
1296
1297#[cfg(test)]
1298mod tests {
1299    use super::*;
1300
1301    fn square(x: f32, y: f32, side: f32) -> Vec<Point> {
1302        vec![[x, y], [x + side, y], [x + side, y + side], [x, y + side]]
1303    }
1304
1305    /// Nonzero winding of `rings` around `p`.
1306    fn covers(rings: &[Vec<Point>], p: Point) -> bool {
1307        let mut w = 0;
1308        for r in rings {
1309            for (k, &a) in r.iter().enumerate() {
1310                let b = r[(k + 1) % r.len()];
1311                let side = (b[0] - a[0]) * (p[1] - a[1]) - (p[0] - a[0]) * (b[1] - a[1]);
1312                if a[1] <= p[1] && b[1] > p[1] && side > 0.0 {
1313                    w += 1;
1314                } else if a[1] > p[1] && b[1] <= p[1] && side < 0.0 {
1315                    w -= 1;
1316                }
1317            }
1318        }
1319        w != 0
1320    }
1321
1322    fn empty() -> Rc<MapData> {
1323        Rc::new(MapData::new(
1324            Vec::new(),
1325            Vec::new(),
1326            Rect::new(0.0, 0.0, 100.0, 100.0),
1327            &[],
1328        ))
1329    }
1330
1331    #[test]
1332    fn lines_and_holes_wind_by_role() {
1333        let mut b = MapBuilder::new(48.0, 11.0);
1334        let l = b.layer(Color::BLACK, 0.0);
1335        let mut hole = square(0.0, 0.0, 5.0);
1336        hole.reverse();
1337        b.area(l, &[square(0.0, 0.0, 10.0)], &[hole]);
1338        b.line(l, &[[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]], 2.0);
1339        let signs: Vec<bool> = b.layers[0]
1340            .rings
1341            .iter()
1342            .map(|r| signed_area(r) > 0.0)
1343            .collect();
1344        assert_eq!(signs, [true, false]);
1345        let mut stroked = Vec::new();
1346        stroked.extend(b.layers[0].lines[0].stroke());
1347        // Two caps, two segments and a bevel outside the bend.
1348        assert_eq!(stroked.len(), 5);
1349        assert!(stroked.iter().all(|r| signed_area(r) > 0.0));
1350    }
1351
1352    #[test]
1353    fn clip_cuts_contains_and_drops() {
1354        let sq = square(0.0, 0.0, 10.0);
1355        let half = clip(&sq, Rect::new(5.0, -1.0, 10.0, 12.0)).unwrap();
1356        assert_eq!(signed_area(&half), 100.0);
1357        let inner = clip(&sq, Rect::new(2.0, 2.0, 2.0, 2.0)).unwrap();
1358        assert_eq!(signed_area(&inner), 8.0);
1359        assert!(clip(&sq, Rect::new(20.0, 0.0, 5.0, 5.0)).is_none());
1360    }
1361
1362    #[test]
1363    fn cut_lines_stroke_the_same_inside_the_margin() {
1364        let run = Run {
1365            points: vec![
1366                [-30.0, 5.0],
1367                [12.0, 18.0],
1368                [3.0, 26.0],
1369                [40.0, 31.0],
1370                [9.0, -20.0],
1371            ],
1372            width: 6.0,
1373            caps: [true, true],
1374            bevels: true,
1375        };
1376        let margin = Rect::new(0.0, 0.0, 30.0, 30.0);
1377        let pieces = cut_run(&run, grow(margin, run.width / 2.0));
1378        assert!(pieces.len() > 1);
1379        assert!(
1380            pieces.iter().all(|p| p.caps == [false, false]),
1381            "every end is a cut"
1382        );
1383        let (mut whole, mut cut) = (Vec::new(), Vec::new());
1384        whole.extend(run.stroke());
1385        for p in &pieces {
1386            cut.extend(p.stroke());
1387        }
1388        let cut: Vec<_> = cut.iter().filter_map(|r| clip(r, margin)).collect();
1389        for i in 0..60 {
1390            for j in 0..60 {
1391                let p = [0.25 + i as f32 * 0.5, 0.25 + j as f32 * 0.5];
1392                assert_eq!(covers(&whole, p), covers(&cut, p), "at {p:?}");
1393            }
1394        }
1395        let inside = cut_run(&run, Rect::new(-100.0, -100.0, 200.0, 200.0));
1396        assert_eq!(inside, [run]);
1397    }
1398
1399    #[test]
1400    fn simplify_keeps_the_ends_and_the_corners() {
1401        let pts = [[0.0, 0.0], [5.0, 0.1], [10.0, 0.0], [10.0, 10.0]];
1402        assert_eq!(
1403            simplify(&pts, 0.25),
1404            [[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]]
1405        );
1406        assert_eq!(simplify(&pts, 0.05), pts);
1407    }
1408
1409    #[test]
1410    fn coarse_levels_are_lighter() {
1411        let mut b = MapBuilder::new(48.0, 11.0);
1412        let l = b.layer(Color::BLACK, 0.0);
1413        let wiggle: Vec<Point> = (0..400)
1414            .map(|i| [i as f32 * 5.0, (i % 2) as f32 * 0.5])
1415            .collect();
1416        b.line(l, &wiggle, 3.0);
1417        b.area(l, &[square(0.0, 50.0, 2.0)], &[]);
1418        let data = b.build();
1419        let weight = |level: usize| {
1420            let tiles = &data.tiles[data.layers[0][level].tiles.clone()];
1421            let shapes = tiles.iter().filter_map(|t| data.shape(t));
1422            shapes
1423                .map(|(s, _)| s.path().contours.iter().map(Vec::len).sum::<usize>())
1424                .sum::<usize>()
1425        };
1426        assert!(
1427            weight(0) * 10 < weight(FULL),
1428            "{} vs {}",
1429            weight(0),
1430            weight(FULL)
1431        );
1432        let coarse = &data.tiles[data.layers[0][0].tiles.clone()];
1433        let geo = coarse.iter().map(|t| t.geo.as_ref().unwrap());
1434        assert!(
1435            geo.clone().all(|g| g.rings.is_empty()),
1436            "the 2 m square is too small"
1437        );
1438        assert!(
1439            geo.flat_map(|g| &g.runs)
1440                .all(|r| r.caps == [false, false] && !r.bevels)
1441        );
1442        assert_eq!(
1443            (level_of(0.01), level_of(0.25), level_of(5.0)),
1444            (0, 4, FULL)
1445        );
1446    }
1447
1448    #[test]
1449    fn dense_layers_split_into_small_tiles() {
1450        let mut b = MapBuilder::new(48.0, 11.0);
1451        let l = b.layer(Color::BLACK, 0.0);
1452        for i in 0..20 {
1453            for j in 0..20 {
1454                b.area(l, &[square(i as f32 * 20.0, j as f32 * 20.0, 10.0)], &[]);
1455            }
1456        }
1457        let data = b.build();
1458        assert!(data.layers[0][FULL].tiles.len() > 1);
1459        for t in &data.tiles {
1460            let (shape, _) = data.shape(t).unwrap();
1461            let n: usize = shape.path().contours.iter().map(Vec::len).sum();
1462            assert!(n <= MAX_QUADS, "{n} segments");
1463        }
1464        assert_eq!(data.bounds, Rect::new(0.0, 0.0, 390.0, 390.0));
1465        // Too small for the coarsest level, too plain to simplify in between.
1466        assert!(data.layers[0][0].tiles.is_empty());
1467        assert_eq!(data.layers[0][3], data.layers[0][FULL]);
1468    }
1469
1470    #[test]
1471    fn labels_run_along_upright_and_spaced() {
1472        let text = Text::default();
1473        let mut b = MapBuilder::new(48.0, 11.0);
1474        let l = b.layer(Color::BLACK, 0.0);
1475        let label =
1476            |b: &mut MapBuilder, pts: &[Point]| b.label(l, pts, &text, Font::DEFAULT, "Hi", 10.0);
1477        assert!(!label(&mut b, &[[0.0, 0.0], [10.0, 0.0]]), "too short");
1478        let bend = [[0.0, 0.0], [50.0, 0.0], [50.0, 50.0]];
1479        assert!(!label(&mut b, &bend), "turns under the text");
1480        // Drawn right to left, still read left to right: 'H' comes first.
1481        assert!(label(&mut b, &[[100.0, 0.0], [0.0, 0.0]]));
1482        let t = &b.labels[0];
1483        let glyphs = &t.geo.as_ref().unwrap().glyphs;
1484        let v = bounds(glyphs.contours.iter().flatten().flatten()).unwrap();
1485        assert!((v.x + v.w / 2.0 - 50.0).abs() < 2.0);
1486        assert!((v.y + v.h / 2.0).abs() < 4.0, "centred on the line");
1487        assert!(glyphs.contours[0][0][0][0] < 50.0);
1488        assert_eq!(t.min_scale, MIN_LABEL_PX / 10.0);
1489        // The same text 100 m on waits until they're far enough apart on screen.
1490        assert!(label(&mut b, &[[100.0, 0.0], [200.0, 0.0]]));
1491        assert_eq!(b.labels[1].min_scale, LABEL_SPACING_PX / 100.0);
1492    }
1493
1494    #[test]
1495    fn maps_round_trip_through_bytes() {
1496        let mut b = MapBuilder::new(52.37, 4.89);
1497        let roads = b.layer(Color::WHITE, 0.0);
1498        let names = b.layer(Color::BLACK, 0.5);
1499        b.line(roads, &[[0.0, 0.0], [300.0, 40.0], [600.0, 0.0]], 10.0);
1500        b.area(roads, &[square(100.0, 100.0, 50.0)], &[]);
1501        b.label(
1502            names,
1503            &[[0.0, 0.0], [600.0, 0.0]],
1504            &Text::default(),
1505            Font::DEFAULT,
1506            "Damrak",
1507            8.0,
1508        );
1509        let built = b.build();
1510        let bytes: &'static [u8] = Vec::leak(built.to_bytes());
1511        let read = MapData::from_bytes(bytes).unwrap();
1512        assert_eq!(read.to_bytes(), bytes);
1513        assert_eq!(
1514            (read.tiles(), read.segments()),
1515            (built.tiles(), built.segments())
1516        );
1517        assert_eq!(
1518            (read.layers.clone(), read.labels.clone()),
1519            (built.layers.clone(), built.labels.clone())
1520        );
1521        for (a, z) in built.tiles.iter().zip(&read.tiles) {
1522            assert_eq!(
1523                (a.cell, a.min_scale, a.level),
1524                (z.cell, z.min_scale, z.level)
1525            );
1526            let (va, vz) = (data_view(&built, a), data_view(&read, z));
1527            // Grid rounding moves edges met at a shallow angle by more.
1528            assert!((va.x - vz.x).abs() < 1e-2 && (va.w - vz.w).abs() < 1e-2);
1529        }
1530        assert!(MapData::from_bytes(&bytes[..bytes.len() - 1]).is_none());
1531    }
1532
1533    fn data_view(d: &MapData, t: &Tile) -> Rect {
1534        d.shape(t).unwrap().1
1535    }
1536
1537    #[test]
1538    fn panning_in_stores_the_tiles_in_view() {
1539        struct App(Rc<MapData>);
1540        impl dfui::App for App {
1541            fn view(&self) -> Element {
1542                map(&self.0).start([200.0, 200.0], 4.0).into()
1543            }
1544        }
1545        let mut b = MapBuilder::new(48.0, 11.0);
1546        let l = b.layer(Color::BLACK, 0.0);
1547        for i in 0..40 {
1548            b.line(
1549                l,
1550                &[[0.0, i as f32 * 10.0], [400.0, i as f32 * 10.0 + 3.0]],
1551                2.0,
1552            );
1553        }
1554        let data = Rc::new(b.build());
1555        let mut bench = dfui::Bench::new(App(data.clone()), (100.0, 100.0));
1556        bench.settle();
1557        let view = Rect::new(187.5, 187.5, 25.0, 25.0);
1558        let stored = |t: &Tile| t.stored.get();
1559        let shown = data.tiles[data.layers[0][FULL].tiles.clone()]
1560            .iter()
1561            .filter(|t| {
1562                let hit = t.cell.intersect(&view);
1563                hit.w > 0.0 && hit.h > 0.0
1564            });
1565        assert!(shown.clone().count() > 0 && shown.clone().all(stored));
1566        let off = data
1567            .tiles
1568            .iter()
1569            .filter(|t| t.cell.intersect(&view).w <= 0.0 || t.cell.intersect(&view).h <= 0.0);
1570        assert!(!off.clone().any(stored), "nothing out of view is stored");
1571    }
1572
1573    #[test]
1574    fn zoom_keeps_the_point_under_the_pointer() {
1575        let data = empty();
1576        let r = Rect::new(0.0, 0.0, 100.0, 100.0);
1577        let mut v = View::default();
1578        v.fit(&map(&data), r);
1579        let at = |v: &View| {
1580            [
1581                v.center[0] + (80.0 - 50.0) / v.scale,
1582                v.center[1] + (20.0 - 50.0) / v.scale,
1583            ]
1584        };
1585        let before = at(&v);
1586        v.zoom(&data, r, 80.0, 20.0, 3.0);
1587        assert_eq!(v.scale, 3.0);
1588        let after = at(&v);
1589        assert!((before[0] - after[0]).abs() < 1e-4 && (before[1] - after[1]).abs() < 1e-4);
1590    }
1591
1592    #[test]
1593    fn taps_report_the_map_point_and_pans_dont() {
1594        use std::cell::RefCell;
1595
1596        struct App(Rc<MapData>, Rc<RefCell<Vec<Point>>>);
1597        impl dfui::App for App {
1598            fn view(&self) -> Element {
1599                let taps = self.1.clone();
1600                map(&self.0)
1601                    .on_tap(move |_, p| taps.borrow_mut().push(p))
1602                    .into()
1603            }
1604        }
1605        let taps = Rc::new(RefCell::new(Vec::new()));
1606        let mut b = dfui::Bench::new(App(empty(), taps.clone()), (100.0, 100.0));
1607        b.settle();
1608        b.event(Event::PointerDown { x: 80.0, y: 20.0 });
1609        b.event(Event::PointerUp { x: 80.0, y: 20.0 });
1610        b.event(Event::PointerDown { x: 50.0, y: 50.0 });
1611        b.event(Event::PointerMove { x: 10.0, y: 50.0 });
1612        b.event(Event::PointerUp { x: 10.0, y: 50.0 });
1613        assert_eq!(*taps.borrow(), [[80.0, 20.0]]);
1614    }
1615
1616    #[test]
1617    fn focus_moves_the_view_once_per_change() {
1618        let data = empty();
1619        let r = Rect::new(0.0, 0.0, 100.0, 100.0);
1620        let mut v = View::default();
1621        let focused = map(&data).focus(Some(([10.0, 20.0], 5.0)));
1622        v.fit(&focused, r);
1623        assert_eq!((v.center, v.scale), ([10.0, 20.0], 5.0));
1624        v.center = [0.0, 0.0];
1625        v.fit(&focused, r);
1626        assert_eq!(v.center, [0.0, 0.0]);
1627    }
1628}