drawland-core 0.4.0

Maps drawn for pen plotters: OSM features to a layered SVG. No I/O.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
//! Labels: names written on the map, placed so that none covers another.
//!
//! Placement is greedy, as web maps do it: every named feature is a candidate,
//! ranked by importance (a road's class, an area's size), and the most
//! important are placed first. A label is kept only if the box of each of its
//! glyphs, grown by `padding`, is clear of every label already kept and inside
//! the frame; otherwise the next position along the road is tried, and then
//! the feature goes unlabelled.
//!
//! On a road the text runs along the centreline, reading left to right: in a
//! straight line where the stretch under it is straight, glyph by glyph along
//! the curve where it is not (and the turns are gentle enough to read). A long
//! road is labelled again every `spacing`. An area is labelled level on the
//! page, inside it.
//!
//! What comes out is geometry, never ink: the pen strokes of the letters, and
//! the shape they cover. A single-stroke font covers nothing until it is
//! buffered; an outline font covers its glyphs, counters left open.

use crate::geom::{self, Lines};
use crate::osm::Feature;
use crate::select::{self, TagTest};
use crate::text::{self, LabelFont, LabelGlyph, LabelLayout};
use crate::units::Mm;
use geo::{Area, Centroid, Contains, Coord, InteriorPoint, LineString, MultiPolygon, Point, Polygon};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::{BTreeMap, HashMap};

/// Font file bytes (TTF, OTF or WOFF2) keyed by [`text::google_font_key`].
pub type GoogleFonts = BTreeMap<String, Vec<u8>>;

/// Single-stroke font file bytes (SVG or JHF) keyed by URL / catalog URL.
pub type StrokeFonts = BTreeMap<String, Vec<u8>>;

/// How labels look and how close they may come. Every field has a default.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Style {
    /// `"futural"`, catalog stroke id, `{ origin: "drawland" | "stroke" | "google", … }`.
    pub font: LabelFont,
    /// Capital height of the most important labels.
    pub size: Mm,
    /// Capital height of the least important.
    pub min_size: Mm,
    /// Clear space kept around every glyph.
    pub padding: Mm,
    /// Distance between two labels of the same name.
    pub spacing: Mm,
    /// Bend text along curving roads; off, only straight stretches are labelled.
    pub curved: bool,
    /// Write the names in capitals.
    pub upper: bool,
    /// The tags the text is read from, the first one present.
    pub keys: Vec<String>,
    /// Concentric outlines drawn around each placed name (0 = the strokes only).
    pub buffer: u32,
    /// Half-width added per buffer pass, round caps.
    pub buffer_step: Mm,
    /// When `buffer` > 0, keep the letters' own strokes as well as the outlines.
    pub keep_centerline: bool,
    /// A dot this big (radius, mm) at a place's point, its name set beside it
    /// rather than on it; the dot is part of the label's area. 0 = no dot.
    pub marker: Mm,
    /// The first rule whose `tags` match wins; its fields override the ones above.
    pub rules: Vec<LabelRule>,
}

impl Default for Style {
    fn default() -> Style {
        Style {
            font: LabelFont::drawland("futural"),
            size: Mm(2.0),
            min_size: Mm(1.1),
            padding: Mm(0.5),
            spacing: Mm(70.0),
            curved: true,
            upper: false,
            keys: vec!["name".into(), "ref".into()],
            buffer: 0,
            buffer_step: Mm(0.1),
            keep_centerline: true,
            marker: Mm(0.0),
            rules: Vec::new(),
        }
    }
}

/// One user-defined override, for the features whose tags pass `tags` (the
/// tests of `features.where`). Unset fields keep the style's.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LabelRule {
    /// When set, labels placed under this rule also land in `labels.<id>` in
    /// the profile (their own `lines` and `area` handles).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(serialize_with = "tags_out", deserialize_with = "tags_in")]
    pub tags: Vec<(String, TagTest)>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub font: Option<LabelFont>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub size: Option<Mm>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_size: Option<Mm>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub padding: Option<Mm>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spacing: Option<Mm>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub curved: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub upper: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub buffer: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub buffer_step: Option<Mm>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub keep_centerline: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub marker: Option<Mm>,
}

fn tags_in<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<(String, TagTest)>, D::Error> {
    let map = serde_json::Map::deserialize(d)?;
    select::parse_tag_tests(map).map_err(|e| serde::de::Error::custom(format!("rule tags: {e}")))
}

fn tags_out<S: Serializer>(tags: &[(String, TagTest)], s: S) -> Result<S::Ok, S::Error> {
    select::tag_tests_to_map(tags).serialize(s)
}

/// How one feature's label looks: the style, overridden by the first rule
/// its tags pass.
#[derive(Debug, Clone)]
struct Look {
    font: LabelFont,
    size: Mm,
    min_size: Mm,
    padding: Mm,
    spacing: Mm,
    curved: bool,
    upper: bool,
    buffer: u32,
    buffer_step: Mm,
    keep_centerline: bool,
    marker: Mm,
}

impl Style {
    /// The resolved look and, when the matching rule has an `id`, that bucket name.
    fn look(&self, f: &Feature) -> (Look, Option<String>) {
        let none = LabelRule::default();
        let r = self.rules.iter().find(|r| select::passes(&r.tags, f)).unwrap_or(&none);
        let look = Look {
            font: r.font.clone().unwrap_or_else(|| self.font.clone()),
            size: r.size.unwrap_or(self.size),
            min_size: r.min_size.unwrap_or(self.min_size),
            padding: r.padding.unwrap_or(self.padding),
            spacing: r.spacing.unwrap_or(self.spacing),
            curved: r.curved.unwrap_or(self.curved),
            upper: r.upper.unwrap_or(self.upper),
            buffer: r.buffer.unwrap_or(self.buffer),
            buffer_step: r.buffer_step.unwrap_or(self.buffer_step),
            keep_centerline: r.keep_centerline.unwrap_or(self.keep_centerline),
            marker: r.marker.unwrap_or(self.marker),
        };
        let bucket = if self.rules.iter().any(|rule| select::passes(&rule.tags, f)) {
            r.id.clone()
        } else {
            None
        };
        (look, bucket)
    }

    /// Every distinct `id` on a rule, in order.
    pub fn rule_ids(&self) -> Vec<String> {
        let mut out = Vec::new();
        for r in &self.rules {
            if let Some(id) = &r.id {
                if !out.iter().any(|x| x == id) {
                    out.push(id.clone());
                }
            }
        }
        out
    }

    /// The style's font and every rule's.
    fn fonts(&self) -> impl Iterator<Item = &LabelFont> {
        std::iter::once(&self.font).chain(self.rules.iter().filter_map(|r| r.font.as_ref()))
    }
}

/// Every draw.land font named in `style` must be built in; Google fonts load at run time.
pub fn validate_style(style: &Style) -> Result<(), String> {
    style.fonts().try_for_each(text::validate_label_font)?;
    let mut seen = std::collections::BTreeSet::new();
    for r in &style.rules {
        if let Some(id) = &r.id {
            if id.is_empty() {
                return Err("labels: rule id is a non-empty name".into());
            }
            if !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') || id.starts_with(|c: char| c.is_ascii_digit()) {
                return Err(format!("labels: rule id {:?} is not a name (letters, digits, underscore)", id));
            }
            if !seen.insert(id.clone()) {
                return Err(format!("labels: duplicate rule id {:?}", id));
            }
        }
    }
    Ok(())
}

/// Every Google font key any `tools_labels` def in the grammar needs (`Roboto:400`, …).
pub fn google_font_keys_in_grammar(grammar: &crate::grammar::Grammar) -> Vec<String> {
    font_keys_in_grammar(grammar, FontKeyKind::Google)
}

pub fn stroke_font_keys_in_grammar(grammar: &crate::grammar::Grammar) -> Vec<String> {
    font_keys_in_grammar(grammar, FontKeyKind::Stroke)
}

enum FontKeyKind {
    Google,
    Stroke,
}

fn font_keys_in_grammar(grammar: &crate::grammar::Grammar, kind: FontKeyKind) -> Vec<String> {
    use crate::grammar::Op;
    let mut keys: Vec<String> = grammar
        .all_defs()
        .flat_map(|def| match &def.op {
            Op::Labels(l) => l.style.fonts().filter_map(|f| match kind {
                FontKeyKind::Google => LabelFont::google_key(f),
                FontKeyKind::Stroke => f.stroke_font_key(),
            }).collect::<Vec<_>>(),
            Op::Text(t) | Op::TextArea(t) => match kind {
                FontKeyKind::Google => t.font.google_key().into_iter().collect(),
                FontKeyKind::Stroke => t.font.stroke_font_key().into_iter().collect(),
            },
            Op::Graticule(g) | Op::GraticuleArea(g) if g.look.part == crate::grammar::GraticulePart::Labels => match kind {
                FontKeyKind::Google => g.look.font.google_key().into_iter().collect(),
                FontKeyKind::Stroke => g.look.font.stroke_font_key().into_iter().collect(),
            },
            _ => vec![],
        })
        .collect();
    keys.sort();
    keys.dedup();
    keys
}

/// The labels as placed: the pen strokes of their letters, and what each
/// label covers.
/// How far a single-stroke letter covers each side of its strokes, mm: a
/// pen nib's half width, so `labels.area` is the ink on the paper.
pub const STROKE_NIB: f64 = 0.15;

#[derive(Debug, Clone, Default)]
pub struct Bucket {
    lines: Lines,
    shapes: Vec<MultiPolygon<f64>>,
    dots: Vec<MultiPolygon<f64>>,
}

#[derive(Debug, Clone, Default)]
pub struct Placed {
    /// Every label's strokes together.
    pub lines: Lines,
    /// One filled silhouette per label (counters open) for hatch inside letters.
    pub shapes: Vec<MultiPolygon<f64>>,
    /// Solid footprint per label for masking fills below: the silhouette with
    /// counters closed, so the hole follows the letters rather than a box.
    pub mask: Vec<MultiPolygon<f64>>,
    /// Labels whose matching rule had an `id`.
    pub buckets: BTreeMap<String, Bucket>,
    /// The dot at each place with a `marker`, on its own: a pen draws or
    /// fills it apart from the letters (they are also in `shapes` and `mask`).
    pub dots: Vec<MultiPolygon<f64>>,
}

impl Placed {
    /// What every label covers together when subtracting ink below it.
    pub fn area(&self) -> MultiPolygon<f64> {
        if !self.mask.is_empty() {
            return geom::union_multi(&self.mask);
        }
        geom::union_multi(&self.shapes)
    }

    pub fn lines_for(&self, rule: Option<&str>) -> Lines {
        match rule {
            None => self.lines.clone(),
            Some(id) => self.buckets.get(id).map(|b| b.lines.clone()).unwrap_or_default(),
        }
    }

    /// The places' dots, for every label or a rule's.
    pub fn dots_for(&self, rule: Option<&str>) -> MultiPolygon<f64> {
        match rule {
            None => geom::union_multi(&self.dots),
            Some(id) => self.buckets.get(id).map(|b| geom::union_multi(&b.dots)).unwrap_or_else(geom::empty),
        }
    }

    pub fn area_for(&self, rule: Option<&str>) -> MultiPolygon<f64> {
        match rule {
            None => self.area(),
            Some(id) => self
                .buckets
                .get(id)
                .map(|b| geom::union_multi(&b.shapes))
                .unwrap_or_else(geom::empty),
        }
    }
}

/// `strokes` with `passes` concentric outlines around them (each pass buffers
/// them all by one more step), and the area inside the outermost one.
fn buffered(strokes: Lines, passes: u32, step: Mm, keep_strokes: bool) -> (Lines, MultiPolygon<f64>) {
    if passes == 0 || step.0 <= 0.0 {
        return (strokes, geom::empty());
    }
    let mut out = if keep_strokes { strokes.clone() } else { Lines::new() };
    let mut outer = geom::empty();
    for pass in 1..=passes {
        let radius = pass as f64 * step.0;
        let parts: Vec<MultiPolygon<f64>> = strokes.iter().map(|l| geom::buffer_line_round(l, radius)).collect();
        outer = geom::union_multi(&parts);
        out.extend(geom::rings(&outer));
    }
    (out, outer)
}

/// How much a road matters, 0 to 1, by its OpenMapTiles class or OSM `highway`.
fn road_rank(f: &Feature) -> f64 {
    let class = f.tag("class").or_else(|| f.tag("highway")).unwrap_or("");
    let class = class.trim_end_matches("_link");
    match class {
        "motorway" => 1.0,
        "trunk" => 0.9,
        "primary" => 0.8,
        "secondary" => 0.65,
        "tertiary" => 0.5,
        "minor" | "residential" | "unclassified" | "living_street" => 0.3,
        "service" | "busway" => 0.15,
        "rail" | "transit" => 0.2,
        "track" | "path" | "footway" | "cycleway" | "pedestrian" => 0.05,
        // A ferry's line is named for its stops ("Ferrovia - Colonna"):
        // below the streets, or a lagoon's boats outname its islands.
        "ferry" => 0.1,
        _ => 0.3,
    }
}

/// Whether a feature names a place (a city, a quarter, an island): from
/// the tiles' `place` layer or with OSM's `place` tag. Places are placed
/// before every other name, as a web map's place layers sit over its road
/// names: a quarter's name is not lost to the streets in it.
fn is_place(f: &Feature) -> bool {
    f.tag("tiles:layer") == Some("place") || f.tag("tiles:layer").is_none() && f.tag("place").is_some()
}

fn pin_rank(f: &Feature) -> f64 {
    let layer = f.tag("tiles:layer").unwrap_or("");
    if is_place(f) {
        let class = if layer == "place" { f.tag("class") } else { f.tag("place") }.unwrap_or("");
        // The class sets the band: a city over a town over a quarter. Inside
        // it OpenMapTiles' rank orders them (1 the most important: Milan 3,
        // Pavia 11, towns from 12, and a city's quarters numbered on past 50
        // by local importance), never flattening the long tail to one value.
        let (lo, hi) = match class {
            "continent" | "country" => (0.9, 1.0),
            "state" | "province" => (0.8, 0.95),
            "city" => (0.75, 1.0),
            "town" => (0.6, 0.8),
            "village" | "suburb" => (0.45, 0.6),
            "quarter" => (0.35, 0.5),
            "neighbourhood" | "neighborhood" => (0.3, 0.45),
            "island" => (0.3, 0.8),
            "hamlet" => (0.25, 0.4),
            _ => (0.2, 0.35),
        };
        let within = match f.tag("rank").and_then(|r| r.parse::<f64>().ok()) {
            Some(rank) => 1.0 / (1.0 + (rank - 1.0).max(0.0) / 8.0),
            None => 0.5,
        };
        let bonus = match f.tag("capital") {
            Some("2") => 0.25,
            Some("3") | Some("4") => 0.1,
            _ => 0.0,
        };
        return (lo + (hi - lo) * within + bonus).min(1.0);
    }
    if layer == "poi" {
        return 0.25;
    }
    0.2
}

/// Where a name goes: along a road, inside an area, beside a point.
#[derive(Debug, Clone)]
pub enum Shape {
    Road(Vec<Coord<f64>>),
    Area(Polygon<f64>),
    Pin(Coord<f64>),
}

/// A name to place, before any font: what it says, where, and how much it
/// matters. The pen's labels and a screen's are placed from these.
#[derive(Debug, Clone)]
pub struct Named {
    pub text: String,
    /// 0 to 1: a city over a village, a motorway over a lane, a big park
    /// over a small one.
    pub rank: f64,
    /// Length or the square root of the area, mm: the tie-break, larger first.
    pub extent: f64,
    pub shape: Shape,
    /// The feature it names (the first piece of a road's chain), in `features`.
    pub feature: usize,
}

/// The names of `features` (output millimetres), places first, then the
/// most important. A road comes in pieces: one chain per name and class, so
/// a street is one name however the data cut it. `page` is the page's area, mm², which an
/// area's rank is a share of.
pub fn named(features: &[Feature], keys: &[String], page: f64) -> Vec<Named> {
    let page = page.max(1.0);
    let mut out = Vec::new();
    let mut roads: BTreeMap<(String, String), (f64, Lines, usize)> = BTreeMap::new();
    for (i, f) in features.iter().enumerate() {
        let Some(text) = pick_feature_label(f, keys) else {
            continue;
        };
        let text = text.to_string();
        let polys = geom::polygons(&f.geometry);
        if let Some(poly) = polys.into_iter().max_by(|a, b| a.unsigned_area().total_cmp(&b.unsigned_area())) {
            let area = poly.unsigned_area();
            let rank = (0.25 + (area / page).sqrt()).min(1.0);
            out.push(Named { text, rank, extent: area.sqrt(), shape: Shape::Area(poly), feature: i });
        } else if let geo::Geometry::Point(p) = &f.geometry {
            // A point the projection cannot show (a globe's far side) is not named.
            if !(p.x().is_finite() && p.y().is_finite()) {
                continue;
            }
            out.push(Named { text, rank: pin_rank(f), extent: 1.0, shape: Shape::Pin(p.0), feature: i });
        } else {
            let class = f.tag("class").or_else(|| f.tag("highway")).unwrap_or("").to_string();
            let entry = roads.entry((text, class)).or_insert_with(|| (road_rank(f), Vec::new(), i));
            entry.1.extend(geom::lines_of(&f.geometry));
        }
    }
    for ((text, _), (rank, lines, feature)) in roads {
        for chain in geom::linemerge(&lines) {
            let pts: Vec<Coord<f64>> = chain.0;
            if pts.len() < 2 {
                continue;
            }
            let extent = Path::new(pts.clone()).length();
            out.push(Named { text: text.clone(), rank, extent, shape: Shape::Road(pts), feature });
        }
    }
    // Places first, as a web map's place layers sit over its road names;
    // then by rank, then by extent.
    out.sort_by(|a, b| {
        let (pa, pb) = (is_place(&features[a.feature]), is_place(&features[b.feature]));
        pb.cmp(&pa).then(b.rank.total_cmp(&a.rank)).then(b.extent.total_cmp(&a.extent))
    });
    out
}

struct Candidate {
    text: String,
    rank: f64,
    shape: Shape,
    look: Look,
    /// The matching rule's `id`, when it has one.
    rule: Option<String>,
}

/// A glyph's footprint: four corners, in order.
#[derive(Clone, Copy)]
struct Quad([Coord<f64>; 4]);

/// Whether a glyph's quad touches `area`.
fn touches(area: &MultiPolygon<f64>, q: &Quad) -> bool {
    use geo::Intersects;
    let mut ring = q.0.to_vec();
    ring.push(q.0[0]);
    area.intersects(&Polygon::new(LineString::new(ring), vec![]))
}

impl Quad {
    fn bounds(&self) -> (f64, f64, f64, f64) {
        let xs = self.0.map(|c| c.x);
        let ys = self.0.map(|c| c.y);
        let min = |v: [f64; 4]| v.into_iter().fold(f64::MAX, f64::min);
        let max = |v: [f64; 4]| v.into_iter().fold(f64::MIN, f64::max);
        (min(xs), min(ys), max(xs), max(ys))
    }

    /// Separating axes: two convex quads overlap unless one of their edge
    /// normals splits them.
    fn overlaps(&self, other: &Quad) -> bool {
        for q in [self, other] {
            for i in 0..4 {
                let (a, b) = (q.0[i], q.0[(i + 1) % 4]);
                let n = Coord { x: a.y - b.y, y: b.x - a.x };
                let span = |p: &Quad| {
                    let d = p.0.map(|c| c.x * n.x + c.y * n.y);
                    (d.into_iter().fold(f64::MAX, f64::min), d.into_iter().fold(f64::MIN, f64::max))
                };
                let (a0, a1) = span(self);
                let (b0, b1) = span(other);
                if a1 < b0 || b1 < a0 {
                    return false;
                }
            }
        }
        true
    }

    fn polygon(&self) -> Polygon<f64> {
        Polygon::new(LineString::from(vec![self.0[0], self.0[1], self.0[2], self.0[3], self.0[0]]), vec![])
    }
}

/// The glyph boxes kept so far, bucketed on a grid for the collision test.
struct Taken {
    cell: f64,
    quads: Vec<Quad>,
    grid: HashMap<(i64, i64), Vec<usize>>,
}

impl Taken {
    fn new(cell: f64) -> Taken {
        Taken { cell, quads: Vec::new(), grid: HashMap::new() }
    }

    fn cells(&self, q: &Quad) -> impl Iterator<Item = (i64, i64)> {
        let (x0, y0, x1, y1) = q.bounds();
        let c = self.cell;
        let (i0, i1, j0, j1) = ((x0 / c).floor() as i64, (x1 / c).floor() as i64, (y0 / c).floor() as i64, (y1 / c).floor() as i64);
        (i0..=i1).flat_map(move |i| (j0..=j1).map(move |j| (i, j)))
    }

    fn hits(&self, q: &Quad) -> bool {
        self.cells(q).any(|k| self.grid.get(&k).is_some_and(|ids| ids.iter().any(|&i| self.quads[i].overlaps(q))))
    }

    fn add(&mut self, q: Quad) {
        let i = self.quads.len();
        let cells: Vec<_> = self.cells(&q).collect();
        self.quads.push(q);
        for k in cells {
            self.grid.entry(k).or_default().push(i);
        }
    }
}

/// A polyline walked by arc length.
struct Path {
    pts: Vec<Coord<f64>>,
    at: Vec<f64>,
}

impl Path {
    fn new(pts: Vec<Coord<f64>>) -> Path {
        let mut at = vec![0.0];
        for w in pts.windows(2) {
            at.push(at.last().unwrap() + dist(w[0], w[1]));
        }
        Path { pts, at }
    }

    fn length(&self) -> f64 {
        *self.at.last().unwrap()
    }

    fn point(&self, s: f64) -> Coord<f64> {
        let s = s.clamp(0.0, self.length());
        let i = self.at.partition_point(|&a| a <= s).clamp(1, self.pts.len() - 1);
        let (a, b) = (self.at[i - 1], self.at[i]);
        let t = if b > a { (s - a) / (b - a) } else { 0.0 };
        lerp(self.pts[i - 1], self.pts[i], t)
    }

    /// How far the path between `s0` and `s1` strays from the straight line
    /// joining its ends.
    fn bow(&self, s0: f64, s1: f64) -> f64 {
        let (p0, p1) = (self.point(s0), self.point(s1));
        let d = sub(p1, p0);
        let len = norm(d).max(1e-9);
        self.pts
            .iter()
            .zip(&self.at)
            .filter(|(_, &a)| a > s0 && a < s1)
            .map(|(p, _)| ((p.x - p0.x) * d.y - (p.y - p0.y) * d.x).abs() / len)
            .fold(0.0, f64::max)
    }
}

fn dist(a: Coord<f64>, b: Coord<f64>) -> f64 {
    norm(sub(b, a))
}
fn sub(a: Coord<f64>, b: Coord<f64>) -> Coord<f64> {
    Coord { x: a.x - b.x, y: a.y - b.y }
}
fn norm(a: Coord<f64>) -> f64 {
    a.x.hypot(a.y)
}
fn unit(a: Coord<f64>) -> Coord<f64> {
    let n = norm(a).max(1e-12);
    Coord { x: a.x / n, y: a.y / n }
}
fn lerp(a: Coord<f64>, b: Coord<f64>, t: f64) -> Coord<f64> {
    Coord { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }
}

/// One glyph of a layout set down: font-unit point `(x, y)` (x from the
/// glyph's left edge) goes to `origin + x·k·u + (y - mid)·k·v`, `v` the text's
/// downward and `mid` the middle of the layout's line.
struct Pose {
    glyph: usize,
    origin: Coord<f64>,
    u: Coord<f64>,
    k: f64,
}

impl Pose {
    fn v(&self) -> Coord<f64> {
        Coord { x: -self.u.y, y: self.u.x }
    }

    fn map(&self, layout: &LabelLayout, (x, y): (f64, f64)) -> Coord<f64> {
        let v = self.v();
        let mid = (layout.top + layout.bottom) / 2.0;
        let (a, b) = (x * self.k, (y - mid) * self.k);
        Coord { x: self.origin.x + a * self.u.x + b * v.x, y: self.origin.y + a * self.u.y + b * v.y }
    }

    fn quad(&self, layout: &LabelLayout, pad: f64) -> Quad {
        let p = pad / self.k;
        let advance = layout.glyphs[self.glyph].advance;
        let (x0, x1, y0, y1) = (-p, advance + p, layout.top - p, layout.bottom + p);
        Quad([
            self.map(layout, (x0, y0)),
            self.map(layout, (x1, y0)),
            self.map(layout, (x1, y1)),
            self.map(layout, (x0, y1)),
        ])
    }

    fn strokes(&self, layout: &LabelLayout) -> Lines {
        layout.glyphs[self.glyph]
            .strokes
            .iter()
            .map(|s| LineString::from(s.iter().map(|&p| self.map(layout, p)).collect::<Vec<_>>()))
            .collect()
    }
}

const LATIN_FALLBACK_KEYS: &[&str] = &[
    "name:en",
    "name:latin",
    "name_en",
    "name_int",
    "int_name",
    "name:fr",
];

fn pick_feature_label<'a>(f: &'a Feature, keys: &[String]) -> Option<&'a str> {
    let (key, raw) = keys
        .iter()
        .find_map(|k| f.tag(k).map(str::trim).filter(|s| !s.is_empty()).map(|s| (k.as_str(), s)))?;
    if key == "name" && !crate::stroke_font::has_native_glyphs(raw) {
        if let Some(latin) = LATIN_FALLBACK_KEYS
            .iter()
            .find_map(|k| f.tag(k).map(str::trim).filter(|s| !s.is_empty() && crate::stroke_font::has_native_glyphs(s)))
        {
            return Some(latin);
        }
    }
    Some(raw)
}

/// The labels of `features` (output millimetres).
pub fn place(
    features: &[Feature],
    frame: &MultiPolygon<f64>,
    style: &Style,
    google_fonts: &GoogleFonts,
    stroke_fonts: &StrokeFonts,
) -> Result<Placed, String> {
    place_avoiding(features, frame, None, style, google_fonts, stroke_fonts)
}

/// [`place`], the letters (grown by `padding`) also kept off `avoid`: the
/// lines of a transit map, say. A place's point and its dot are not held to
/// it, so a station on a line still gets its name beside it.
pub fn place_avoiding(
    features: &[Feature],
    frame: &MultiPolygon<f64>,
    avoid: Option<&MultiPolygon<f64>>,
    style: &Style,
    google_fonts: &GoogleFonts,
    stroke_fonts: &StrokeFonts,
) -> Result<Placed, String> {
    validate_style(style)?;
    // Each font file decoded once, not once per label.
    let mut faces: HashMap<String, Vec<Vec<u8>>> = HashMap::new();
    for key in style.fonts().filter_map(LabelFont::google_key) {
        if let Some(bytes) = google_fonts.get(&key) {
            faces.insert(key, crate::google_fonts::faces_of(bytes)?);
        }
    }
    let mut cached_faces: HashMap<String, text::CachedGoogleFont<'_>> = HashMap::new();
    for (k, files) in &faces {
        cached_faces.insert(k.clone(), text::CachedGoogleFont::parse_all(files)?);
    }
    let candidates: Vec<Candidate> = named(features, &style.keys, frame.unsigned_area())
        .into_iter()
        .map(|n| {
            let (look, rule) = style.look(&features[n.feature]);
            let text = if look.upper { n.text.to_uppercase() } else { n.text };
            Candidate { text, rank: n.rank, shape: n.shape, look, rule }
        })
        .collect();

    let max_cap = candidates.iter().map(|c| c.look.size.0.max(c.look.min_size.0)).fold(style.size.0, f64::max);
    let mut taken = Taken::new(max_cap * 4.0);
    let mut named: HashMap<String, Vec<Coord<f64>>> = HashMap::new();
    let mut out = Placed::default();
    let frame_rect = geo::BoundingRect::bounding_rect(frame);
    let pt_in_frame = |c: Coord<f64>| {
        if let Some(r) = frame_rect {
            if c.x < r.min().x || c.x > r.max().x || c.y < r.min().y || c.y > r.max().y {
                return false;
            }
        }
        frame.contains(&Point::from(c))
    };
    let inside = |q: &Quad| q.0.iter().all(|&c| pt_in_frame(c));
    for c in &candidates {
        let look = &c.look;
        let layout = match look.font.google_key() {
            Some(k) => {
                let cf = cached_faces.get_mut(&k).ok_or_else(|| {
                    let (family, _, _) = look.font.google_spec().unwrap_or(("", 400, false));
                    format!("labels: google font {:?} ({}) was not loaded", family, k)
                })?;
                cf.layout(&c.text)
            }
            None => {
                let stroke = look.font.stroke_font_key().and_then(|k| stroke_fonts.get(&k).map(Vec::as_slice));
                text::layout(&look.font, None, stroke, &c.text)?
            }
        };
        let (big, small) = (look.size.0.max(0.1), look.min_size.0.max(0.1));
        let size = small + (big - small) * c.rank.clamp(0.0, 1.0);
        let k = size / layout.cap_height;
        let width = layout.width * k;
        let clear = |poses: &[Pose], taken: &Taken| {
            poses.iter().all(|p| {
                let grown = p.quad(&layout, look.padding.0);
                inside(&p.quad(&layout, 0.0)) && !taken.hits(&grown) && avoid.is_none_or(|a| !touches(a, &grown))
            })
        };
        let far = |at: Coord<f64>, named: &HashMap<String, Vec<Coord<f64>>>| {
            named.get(&c.text).is_none_or(|seen| seen.iter().all(|&s| dist(s, at) >= look.spacing.0))
        };
        let bucket = c.rule.clone();
        let keep = |poses: Vec<Pose>, at: Coord<f64>, taken: &mut Taken, out: &mut Placed, named: &mut HashMap<String, Vec<Coord<f64>>>| {
            let mut strokes = Lines::new();
            let mut glyphs = Vec::new();
            for p in &poses {
                taken.add(p.quad(&layout, look.padding.0));
                let s = p.strokes(&layout);
                if layout.outline {
                    // The pen traces the letter's edge, not the contours it
                    // was built from: those overlap inside the letter.
                    let shape = text::glyph_silhouette(&s);
                    strokes.extend(geom::rings(&shape));
                    glyphs.push(shape);
                } else {
                    strokes.extend(s);
                }
            }
            // A single-stroke letter covers its strokes as far as a pen nib
            // reaches each side: without it the label would cover nothing,
            // and `areas.grow(labels.area, …)` would clear paper round nothing.
            if !layout.outline {
                let nib: Vec<MultiPolygon<f64>> = strokes.iter().map(|l| geom::buffer_line_round(l, STROKE_NIB)).collect();
                glyphs.push(geom::union_multi(&nib));
            }
            let (lines, outer) = buffered(strokes, look.buffer, look.buffer_step, look.keep_centerline);
            out.lines.extend(lines.clone());
            glyphs.push(outer);
            let silhouette = geom::union_multi(&glyphs);
            // The mask closes the counters (the holes in O, 4, 8) whatever the font.
            let mask = geom::fill_holes(&silhouette);
            if !silhouette.0.is_empty() {
                out.shapes.push(silhouette.clone());
            }
            if !mask.0.is_empty() {
                out.mask.push(mask);
            }
            if let Some(id) = &bucket {
                let b = out.buckets.entry(id.clone()).or_default();
                b.lines.extend(lines);
                if !silhouette.0.is_empty() {
                    b.shapes.push(silhouette);
                }
            }
            named.entry(c.text.clone()).or_default().push(at);
        };
        match &c.shape {
            Shape::Road(pts) => {
                let path = Path::new(pts.clone());
                let len = path.length();
                if len < width + size {
                    continue;
                }
                let (lo, hi) = (width / 2.0, len - width / 2.0);
                let step = (width / 4.0).max(size * 2.0);
                let mid = len / 2.0;
                let tries = ((hi - lo) / step).ceil() as i64;
                let mut placed: Vec<f64> = Vec::new();
                // Every straight stretch first; bent text only where none is left.
                let passes: &[bool] = if look.curved { &[false, true] } else { &[false] };
                for &bend in passes {
                    for i in 0..=2 * tries {
                        let off = ((i + 1) / 2) as f64 * step * if i % 2 == 1 { 1.0 } else { -1.0 };
                        let s = mid + off;
                        if s < lo - 1e-9 || s > hi + 1e-9 {
                            continue;
                        }
                        if placed.iter().any(|&p| (p - s).abs() < look.spacing.0.max(width + size)) {
                            continue;
                        }
                        let at = path.point(s);
                        if !far(at, &named) {
                            continue;
                        }
                        let Some(poses) = along(&path, s, width, size, k, &layout.glyphs, bend) else { continue };
                        if clear(&poses, &taken) {
                            keep(poses, at, &mut taken, &mut out, &mut named);
                            placed.push(s);
                        }
                    }
                }
            }
            Shape::Area(poly) => {
                let poly_rect = geo::BoundingRect::bounding_rect(poly);
                let fits = |poses: &[Pose]| {
                    poses.iter().all(|p| {
                        let q = p.quad(&layout, 0.0);
                        if let Some(r) = poly_rect {
                            let (x0, y0, x1, y1) = q.bounds();
                            if x0 < r.min().x || x1 > r.max().x || y0 < r.min().y || y1 > r.max().y {
                                return false;
                            }
                        }
                        poly.contains(&q.polygon())
                    })
                };
                for at in area_spots(poly, width, size) {
                    if !far(at, &named) {
                        continue;
                    }
                    let poses = horizontal_label(&layout, at, width, k);
                    if fits(&poses) && clear(&poses, &taken) {
                        keep(poses, at, &mut taken, &mut out, &mut named);
                        break;
                    }
                }
            }
            Shape::Pin(at) => {
                if !pt_in_frame(*at) || !far(*at, &named) {
                    continue;
                }
                if look.marker.0 <= 0.0 {
                    let poses = horizontal_label(&layout, *at, width, k);
                    if clear(&poses, &taken) {
                        keep(poses, *at, &mut taken, &mut out, &mut named);
                    }
                    continue;
                }
                // A dot at the place, bigger the more it matters, and the name
                // beside it: right, left, the four diagonals, above, below —
                // the first spot clear of every label already set down.
                let r = look.marker.0 * (0.6 + 0.4 * c.rank.clamp(0.0, 1.0));
                let pad = look.padding.0;
                let dot = Quad([
                    Coord { x: at.x - r - pad, y: at.y - r - pad },
                    Coord { x: at.x + r + pad, y: at.y - r - pad },
                    Coord { x: at.x + r + pad, y: at.y + r + pad },
                    Coord { x: at.x - r - pad, y: at.y + r + pad },
                ]);
                if taken.hits(&dot) || !inside(&dot) {
                    continue;
                }
                let (half, gap, rise) = (width / 2.0, r + size * 0.45, size * 0.8);
                let side = gap + half;
                let diag = gap * 0.6 + half;
                // Close in first; then the same directions a step farther out,
                // for a long name beside a line that a close spot clips.
                let near = [(side, 0.0), (-side, 0.0), (diag, -rise), (diag, rise), (-diag, -rise), (-diag, rise), (0.0, -(r + size * 1.1)), (0.0, r + size * 1.1)];
                let far = near.map(|(dx, dy)| (dx + dx.signum() * size * 0.6, dy * 1.7));
                for (dx, dy) in near.into_iter().chain(far) {
                    let poses = horizontal_label(&layout, Coord { x: at.x + dx, y: at.y + dy }, width, k);
                    if clear(&poses, &taken) {
                        keep(poses, *at, &mut taken, &mut out, &mut named);
                        taken.add(dot);
                        let disc = geom::disc(*at, r);
                        out.shapes.push(disc.clone());
                        out.mask.push(disc.clone());
                        out.dots.push(disc.clone());
                        if let Some(id) = &bucket {
                            let b = out.buckets.entry(id.clone()).or_default();
                            b.shapes.push(disc.clone());
                            b.dots.push(disc);
                        }
                        break;
                    }
                }
            }
        }
    }
    Ok(out)
}

/// The glyphs of a label centred at arc length `s` on `path`, or `None` where
/// the road turns too sharply under it to be read.
fn along(path: &Path, s: f64, width: f64, size: f64, k: f64, glyphs: &[LabelGlyph], curved: bool) -> Option<Vec<Pose>> {
    let (s0, s1) = (s - width / 2.0, s + width / 2.0);
    let (p0, p1) = (path.point(s0), path.point(s1));
    let d = sub(p1, p0);
    // Read left to right; a road straight up the page reads bottom to top.
    let flip = d.x < -1e-6 || (d.x.abs() <= 1e-6 && d.y > 0.0);
    if path.bow(s0, s1) <= 0.25 * size {
        let (a, b) = if flip { (p1, p0) } else { (p0, p1) };
        let u = unit(sub(b, a));
        return Some(
            glyphs
                .iter()
                .enumerate()
                .map(|(glyph, g)| Pose { glyph, origin: Coord { x: a.x + g.x * k * u.x, y: a.y + g.x * k * u.y }, u, k })
                .collect(),
        );
    }
    if !curved {
        return None;
    }
    let mut poses = Vec::with_capacity(glyphs.len());
    let mut last: Option<Coord<f64>> = None;
    let mut turned = 0.0;
    for (glyph, g) in glyphs.iter().enumerate() {
        let half = g.advance * k / 2.0;
        let mid = (g.x * k) + half;
        let sign = if flip { -1.0 } else { 1.0 };
        let at = if flip { s1 - mid } else { s0 + mid };
        let reach = half.max(size * 0.8);
        let u = unit(sub(path.point(at + sign * reach), path.point(at - sign * reach)));
        if let Some(prev) = last {
            let turn = (prev.x * u.y - prev.y * u.x).atan2(prev.x * u.x + prev.y * u.y).abs();
            if turn > 35f64.to_radians() {
                return None;
            }
            turned += turn;
        }
        last = Some(u);
        let c = path.point(at);
        poses.push(Pose { glyph, origin: Coord { x: c.x - half * u.x, y: c.y - half * u.y }, u, k });
    }
    (turned <= 120f64.to_radians()).then_some(poses)
}

fn horizontal_label(layout: &LabelLayout, at: Coord<f64>, width: f64, k: f64) -> Vec<Pose> {
    let start = Coord { x: at.x - width / 2.0, y: at.y };
    (0..layout.glyphs.len())
        .map(|i| Pose {
            glyph: i,
            origin: Coord { x: start.x + layout.glyphs[i].x * k, y: start.y },
            u: Coord { x: 1.0, y: 0.0 },
            k,
        })
        .collect()
}

/// Where to try an area's label, best first: its interior point, its centroid,
/// then a grid over it nearest the middle first.
fn area_spots(poly: &Polygon<f64>, width: f64, size: f64) -> Vec<Coord<f64>> {
    let mut spots: Vec<Coord<f64>> = Vec::new();
    let first = poly.interior_point().map(|p| p.0);
    spots.extend(first);
    spots.extend(poly.centroid().map(|p| p.0).filter(|c| poly.contains(&Point::from(*c))));
    let Some(rect) = geo::BoundingRect::bounding_rect(poly) else { return spots };
    let step = (width / 3.0).max(size * 3.0);
    let (nx, ny) = (((rect.width() / step) as usize).min(40), ((rect.height() / step) as usize).min(40));
    let mut grid: Vec<Coord<f64>> = (0..=nx)
        .flat_map(|i| (0..=ny).map(move |j| (i, j)))
        .map(|(i, j)| Coord { x: rect.min().x + i as f64 * step, y: rect.min().y + j as f64 * step })
        .filter(|c| poly.contains(&Point::from(*c)))
        .collect();
    let centre = first.unwrap_or(rect.center());
    grid.sort_by(|a, b| dist(*a, centre).total_cmp(&dist(*b, centre)));
    spots.extend(grid);
    spots
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::osm::Element;
    use geo::Geometry;

    fn road(name: &str, class: &str, pts: &[(f64, f64)]) -> Feature {
        Feature {
            element: Element::Tile,
            id: 0,
            tags: [("name", name), ("class", class)].into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
            geometry: Geometry::LineString(LineString::from(pts.to_vec())),
        }
    }

    fn park(name: &str) -> Feature {
        Feature {
            element: Element::Tile,
            id: 0,
            tags: [("name", name), ("tiles:layer", "park")]
                .into_iter()
                .map(|(k, v)| (k.into(), v.into()))
                .collect(),
            geometry: Geometry::Polygon(geo::Rect::new((10.0, 10.0), (90.0, 90.0)).to_polygon()),
        }
    }

    fn frame() -> MultiPolygon<f64> {
        MultiPolygon::new(vec![geo::Rect::new((0.0, 0.0), (100.0, 100.0)).to_polygon()])
    }

    fn place_pin(name: &str, class: &str, rank: &str, at: (f64, f64)) -> Feature {
        Feature {
            element: Element::Tile,
            id: 0,
            tags: [("name", name), ("tiles:layer", "place"), ("class", class), ("rank", rank)].into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
            geometry: Geometry::Point(at.into()),
        }
    }

    #[test]
    fn places_rank_by_class_then_by_their_rank() {
        // Central Milan's places as OpenMapTiles ranks them: a quarter's rank
        // runs on past 50, where (18 - rank) / 15 left every one at the floor
        // with the footpaths.
        let r = |class: &str, rank: &str| pin_rank(&place_pin("x", class, rank, (0.0, 0.0)));
        let order = [r("city", "3"), r("town", "15"), r("suburb", "13"), r("suburb", "23"), r("quarter", "34"), r("neighbourhood", "56")];
        assert!(order.windows(2).all(|w| w[0] > w[1]), "{order:?}");
        assert!(order[5] > 0.25, "{order:?}");
        // An OSM place, with no tiles' layer, is a place too.
        let osm = Feature { tags: [("name", "Brera"), ("place", "suburb")].into_iter().map(|(k, v)| (k.into(), v.into())).collect(), ..place_pin("x", "", "", (0.0, 0.0)) };
        assert!(is_place(&osm) && pin_rank(&osm) > 0.4);
        // A ferry's line is below the streets.
        assert!(road_rank(&road("Linea Rosa", "ferry", &[])) < road_rank(&road("Calle", "minor", &[])));
    }

    #[test]
    fn a_place_is_named_before_the_motorway_through_it() {
        // The motorway's name would sit on its middle, over the quarter's
        // point; the quarter is placed first and the motorway moves along.
        let style: Style = serde_json::from_value(serde_json::json!({
            "rules": [{ "id": "places", "tags": { "tiles:layer": "place" } }],
        }))
        .unwrap();
        let motorway = road("Autostrada dei Laghi", "motorway", &[(0.0, 50.0), (100.0, 50.0)]);
        let quarter = place_pin("Porta Romana", "quarter", "40", (50.0, 50.0));
        let placed = place(&[motorway, quarter], &frame(), &style, &GoogleFonts::new(), &StrokeFonts::new()).unwrap();
        assert!(placed.buckets.get("places").is_some_and(|b| !b.lines.is_empty()), "the quarter is named");
    }

    #[test]
    fn crossing_roads_do_not_overlap() {
        let a = road("Fulton Street", "primary", &[(0.0, 50.0), (100.0, 50.0)]);
        let b = road("Great Avenue", "minor", &[(50.0, 0.0), (50.0, 100.0)]);
        let out = place(&[a, b], &frame(), &Style::default(), &GoogleFonts::new(), &StrokeFonts::new()).unwrap().lines;
        assert!(!out.is_empty());
        // The primary is placed first, on its middle; the avenue is pushed off
        // the crossing.
        let near_cross = out.iter().flat_map(|l| l.0.iter()).filter(|c| (c.x - 50.0).abs() < 1.0 && (c.y - 50.0).abs() > 3.0).count();
        assert!(near_cross > 0, "the avenue is labelled away from the crossing");
    }

    #[test]
    fn text_reads_left_to_right() {
        let a = road("AB", "primary", &[(90.0, 50.0), (10.0, 50.0)]);
        let style = Style { font: LabelFont::drawland("futural"), ..Style::default() };
        let out = place(&[a], &frame(), &style, &GoogleFonts::new(), &StrokeFonts::new()).unwrap().lines;
        // The first stroke drawn is the `A`, left of the `B`.
        let first = out[0].0[0].x;
        let last = out.last().unwrap().0[0].x;
        assert!(first < last);
    }

    #[test]
    fn a_short_road_goes_unlabelled() {
        let a = road("A very long street name", "minor", &[(10.0, 10.0), (14.0, 10.0)]);
        assert!(place(&[a], &frame(), &Style::default(), &GoogleFonts::new(), &StrokeFonts::new()).unwrap().lines.is_empty());
    }

    #[test]
    fn rule_ids_split_lines_and_area() {
        let style: Style = serde_json::from_value(serde_json::json!({
            "rules": [{ "id": "park", "tags": { "tiles:layer": "park" }, "size": "8mm", "min_size": "8mm" }],
        }))
        .unwrap();
        let placed = place(&[park("Lake")], &frame(), &style, &GoogleFonts::new(), &StrokeFonts::new()).unwrap();
        let bucket = placed.buckets.get("park").expect("park bucket");
        assert!(!bucket.lines.is_empty());
        assert_eq!(placed.lines.len(), bucket.lines.len());
    }

    #[test]
    fn a_single_stroke_label_covers_its_strokes_and_its_buffer() {
        // Plain: the ink of its strokes, a nib wide, and no more.
        let plain = place(&[park("Lake")], &frame(), &Style::default(), &GoogleFonts::new(), &StrokeFonts::new()).unwrap();
        assert!(!plain.lines.is_empty());
        let area = plain.area();
        let grown = geom::buffer(&area, 1e-6);
        assert!(plain.lines.iter().flat_map(|l| l.0.iter()).all(|c| grown.contains(&Point::from(*c))), "every stroke is inside");
        // It follows the letters (counters closed), not the box round them.
        let rect = geo::BoundingRect::bounding_rect(&area).expect("covers something");
        assert!(area.unsigned_area() < 0.6 * rect.width() * rect.height(), "{} of a {}×{} box", area.unsigned_area(), rect.width(), rect.height());

        let style = Style { buffer: 2, keep_centerline: false, ..Style::default() };
        let thick = place(&[park("Lake")], &frame(), &style, &GoogleFonts::new(), &StrokeFonts::new()).unwrap();
        let area = thick.area();
        assert!(!area.0.is_empty());
        // Every outline lies on or inside the outermost one.
        let grown = geom::buffer(&area, 1e-6);
        assert!(thick.lines.iter().flat_map(|l| l.0.iter()).all(|c| grown.contains(&Point::from(*c))));
    }

    #[test]
    fn rules_override_the_style_and_reject_unknown_keys() {
        let style: Style = serde_json::from_value(serde_json::json!({
            "size": "2mm",
            "rules": [{ "tags": { "class": ["primary"] }, "size": "3mm", "buffer": 1 }],
        }))
        .unwrap();
        let back: Style = serde_json::from_value(serde_json::to_value(&style).unwrap()).unwrap();
        assert_eq!(back, style);
        let (look, bucket) = style.look(&road("A", "primary", &[(0.0, 0.0), (1.0, 0.0)]));
        assert_eq!((look.size, look.buffer), (Mm(3.0), 1));
        assert!(bucket.is_none());
        let (look, _) = style.look(&road("A", "minor", &[(0.0, 0.0), (1.0, 0.0)]));
        assert_eq!((look.size, look.buffer), (Mm(2.0), 0));
        let e = serde_json::from_value::<Style>(serde_json::json!({
            "rules": [{ "tags": { "class": "park" }, "fill": { "pattern": "lines" } }],
        }));
        assert!(e.is_err());
    }

    /// A TrueType face from the system, for the outline tests; they are
    /// skipped where there is none.
    fn system_face() -> Option<(LabelFont, GoogleFonts)> {
        let bytes = ["/System/Library/Fonts/Supplemental/Arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"]
            .iter()
            .find_map(|p| std::fs::read(p).ok())?;
        let font: LabelFont = serde_json::from_value(serde_json::json!({ "origin": "google", "family": "Test" })).unwrap();
        let fonts = GoogleFonts::from([(font.google_key().unwrap(), bytes)]);
        Some((font, fonts))
    }

    fn assert_glyphs_merge(font: LabelFont, bytes: &[u8], sample: &str) {
        let layout = text::layout(&font, Some(bytes), None, sample).unwrap();
        assert!(layout.outline);
        for (ch, g) in sample.chars().zip(&layout.glyphs) {
            if g.strokes.is_empty() {
                continue;
            }
            let contours: Lines = g
                .strokes
                .iter()
                .map(|s| LineString::from(s.iter().map(|&(x, y)| Coord { x, y }).collect::<Vec<_>>()))
                .collect();
            let parts = text::glyph_silhouette(&contours).0.len();
            let disjoint = ch == 'i' || ch == 'j';
            assert!(
                disjoint || parts <= 1,
                "'{ch}' should be one merged body, got {parts} parts from {} contours",
                g.strokes.len()
            );
        }
    }

    #[test]
    fn outline_glyph_overlapping_contours_merge_to_one_silhouette() {
        let Some((font, fonts)) = system_face() else { return };
        let bytes = fonts.values().next().unwrap();
        assert_glyphs_merge(font, bytes, "adng");
    }

    /// Google's Roboto (`fonts.gstatic.com`, the file the page downloads), a
    /// variable font whose contours overlap, `P` and `e` each within itself.
    /// Skipped unless it is at `/tmp/roboto.ttf`.
    #[test]
    fn roboto_glyphs_are_one_body_each_with_their_counters() {
        let Ok(bytes) = std::fs::read("/tmp/roboto.ttf") else { return };
        let font: LabelFont = serde_json::from_value(serde_json::json!({ "origin": "google", "family": "Roboto" })).unwrap();
        assert_glyphs_merge(font.clone(), &bytes, "Lands End");
        let sample = "LandsEOPeg";
        let counters = [0, 1, 0, 1, 0, 0, 1, 1, 1, 1];
        let layout = text::layout(&font, Some(&bytes), None, sample).unwrap();
        for ((ch, g), want) in sample.chars().zip(&layout.glyphs).zip(counters) {
            let contours: Lines = g
                .strokes
                .iter()
                .map(|s| LineString::from(s.iter().map(|&(x, y)| Coord { x, y }).collect::<Vec<_>>()))
                .collect();
            let shape = text::glyph_silhouette(&contours);
            assert_eq!(shape.0.len(), 1, "'{ch}' is one body");
            assert_eq!(shape.0[0].interiors().len(), want, "'{ch}' counters");
        }

        // The pen draws each letter's edge once: one ring per body and counter.
        let fonts = GoogleFonts::from([(font.google_key().unwrap(), bytes)]);
        let style = Style { font, size: Mm(6.0), min_size: Mm(6.0), ..Style::default() };
        let placed = place(&[park(sample)], &frame(), &style, &fonts, &StrokeFonts::new()).unwrap();
        assert_eq!(placed.lines.len(), sample.len() + counters.iter().sum::<usize>());
    }

    #[test]
    fn an_outline_font_covers_its_glyphs_with_the_counters_open() {
        let Some((font, fonts)) = system_face() else { return };
        let style = Style { font, size: Mm(6.0), min_size: Mm(6.0), ..Style::default() };
        let placed = place(&[park("OPg")], &frame(), &style, &fonts, &StrokeFonts::new()).unwrap();
        assert!(!placed.lines.is_empty(), "the contours are drawn");
        let ink = geom::union_multi(&placed.shapes);
        assert_eq!(ink.0.len(), 3);
        assert!(ink.0.iter().all(|p| p.interiors().len() == 1));
        // Mask below labels is each letter, solid: counters closed, no box.
        let mask = placed.area();
        assert_eq!(mask.0.len(), 3);
        assert!(mask.0.iter().all(|p| p.interiors().is_empty()));
        assert!((mask.unsigned_area() - geom::fill_holes(&ink).unsigned_area()).abs() < 1e-6);
        // One baseline: the `g` hangs below the capitals, whose bottoms line up.
        let bottom = |p: &Polygon<f64>| p.exterior().0.iter().map(|c| c.y).fold(f64::MIN, f64::max);
        let mut polys = ink.0.clone();
        polys.sort_by(|a, b| a.centroid().unwrap().x().total_cmp(&b.centroid().unwrap().x()));
        assert!((bottom(&polys[0]) - bottom(&polys[1])).abs() < 0.2);
        assert!(bottom(&polys[2]) > bottom(&polys[0]) + 0.5);
    }
}