geolith-dataset-builder 0.5.0

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
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
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
//! The PNG map layer of one period.
//!
//! Each tile is a pre-coloured RGBA PNG: every pixel takes the colour of the
//! raster cell under its centre (nearest cell, no smoothing) through the
//! config's colour ramp. Pixels on nodata, outside the raster or outside the
//! clip mask are transparent; a tile with no opaque pixel is not written.
//!
//! A windowed raster reads one window per tile at the level that suits the
//! zoom: an overview when the file has them, else level 0, or for low zooms
//! of a file without overviews a [`BlockLevel`] of block means built once.

use std::cmp::Ordering;
use std::path::Path;
use std::time::Instant;

use crate::error::{DatasetError, IoOp, IoResultExt as _, Result, WithinExt as _};
use geo::{BoundingRect as _, Contains as _, Coord, MultiPolygon, Point, Polygon, Rect, coord};
use geolith::geometry::mercator::{MAX_LAT, TileCoord, world_to_wgs84};
use geolith::output::hilbert::tile_to_pmtiles_id;
use geolith::output::writer::{Compression, PmtilesWriter, TileType};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::json;

use crate::config::{DatasetConfig, RampStop};
use crate::coverage::Grid;
use crate::inspect;
use crate::source::{Raster, ReadStats, WindowedRaster, run_pool};
use geolith::terrain::cog::Cog;
use geolith::terrain::crs::Crs;
use geolith::terrain::dem::{Dem, GeoTransform};
use geolith::terrain::tile_range_for_bounds;

/// Colour of `value` on `ramp`.
///
/// Below the first stop it is the first colour, above the last stop the last
/// colour; between two stops each channel is interpolated linearly and
/// rounded half away from zero. An empty ramp gives transparent.
#[must_use]
pub fn ramp_color(ramp: &[RampStop], value: f64) -> [u8; 4] {
    let (Some(first), Some(last)) = (ramp.first(), ramp.last()) else {
        return [0, 0, 0, 0];
    };
    if value <= first.value {
        return first.color;
    }
    if value >= last.value {
        return last.color;
    }
    for pair in ramp.windows(2) {
        let [low, high] = pair else { continue };
        if value <= high.value {
            let t = (value - low.value) / (high.value - low.value);
            let mut color = [0_u8; 4];
            for (out, (&a, &b)) in color.iter_mut().zip(low.color.iter().zip(&high.color)) {
                let (a, b) = (f64::from(a), f64::from(b));
                *out = (a + (b - a) * t).round().clamp(0.0, 255.0) as u8;
            }
            return color;
        }
    }
    last.color
}

/// A clip shape in lon/lat: pixels outside it are transparent.
#[derive(Debug, Clone)]
pub struct ClipMask {
    /// Each polygon with its bounding box.
    parts: Vec<(Polygon<f64>, Rect<f64>)>,
    /// Bounding box of the whole shape; `None` when it is empty.
    bbox: Option<Rect<f64>>,
}

impl ClipMask {
    /// A clip mask of `shape`. An empty shape contains no point.
    #[must_use]
    pub fn new(shape: MultiPolygon<f64>) -> Self {
        let bbox = shape.bounding_rect();
        let parts = shape
            .0
            .into_iter()
            .filter_map(|polygon| polygon.bounding_rect().map(|r| (polygon, r)))
            .collect();
        Self { parts, bbox }
    }

    /// Whether `(lon, lat)` lies inside the shape: bounding boxes first, then
    /// point in polygon.
    #[must_use]
    pub fn contains(&self, lon: f64, lat: f64) -> bool {
        let coord = Coord { x: lon, y: lat };
        if !self.bbox.is_some_and(|r| in_rect(r, coord)) {
            return false;
        }
        let point = Point(coord);
        self.parts
            .iter()
            .any(|(polygon, r)| in_rect(*r, coord) && polygon.contains(&point))
    }

    /// Which pixel centres of the `size` x `size` tile `coord` lie inside the
    /// shape, row-major, `true` inside; the same answer as [`Self::contains`]
    /// at each centre, computed by scanline.
    ///
    /// Each row takes its centre latitude; every edge of a part whose bounding
    /// box meets the tile and whose latitude span holds the row half-open
    /// (`min_y <= lat < max_y`) gives one crossing longitude. Per part the
    /// sorted crossings of its exterior and holes together fill even-odd;
    /// parts are OR-ed. A column is inside when its centre longitude lies
    /// strictly inside a filled span, so boundary points stay outside.
    #[must_use]
    pub fn tile_mask(&self, coord: TileCoord, size: u32) -> Vec<bool> {
        let edge = size as usize;
        let mut mask = vec![false; edge * edge];
        if self.bbox.is_none() || edge == 0 {
            return mask;
        }
        let n = f64::from(1_u32 << coord.z);
        let size_f = f64::from(size);
        // Mercator is separable: longitude depends on the column alone and
        // latitude on the row alone, as in `render_layer_tile`.
        let centre = |tile: u32, i: usize| (f64::from(tile) + (i as f64 + 0.5) / size_f) / n;
        let lons: Vec<f64> = (0..edge)
            .map(|col| world_to_wgs84(centre(coord.x, col), 0.5).0)
            .collect();
        let lats: Vec<f64> = (0..edge)
            .map(|row| world_to_wgs84(0.5, centre(coord.y, row)).1)
            .collect();
        let (Some(&west), Some(&east), Some(&north), Some(&south)) =
            (lons.first(), lons.last(), lats.first(), lats.last())
        else {
            return mask;
        };
        let parts: Vec<&(Polygon<f64>, Rect<f64>)> = self
            .parts
            .iter()
            .filter(|(_, r)| {
                r.max().x >= west && r.min().x <= east && r.max().y >= south && r.min().y <= north
            })
            .collect();
        if parts.is_empty() {
            return mask;
        }
        let mut crossings: Vec<f64> = Vec::new();
        for (line, &lat) in mask.chunks_exact_mut(edge).zip(&lats) {
            for (polygon, r) in &parts {
                if lat < r.min().y || lat >= r.max().y {
                    continue;
                }
                crossings.clear();
                for ring in std::iter::once(polygon.exterior()).chain(polygon.interiors()) {
                    for segment in ring.lines() {
                        let (a, b) = (segment.start, segment.end);
                        if a.y.min(b.y) <= lat && lat < a.y.max(b.y) {
                            crossings.push(a.x + (lat - a.y) * (b.x - a.x) / (b.y - a.y));
                        }
                    }
                }
                crossings.sort_unstable_by(f64::total_cmp);
                for [from, to] in crossings.as_chunks::<2>().0 {
                    let start = lons.partition_point(|&lon| lon <= *from);
                    let end = lons.partition_point(|&lon| lon < *to);
                    if start < end {
                        line[start..end].fill(true);
                    }
                }
            }
        }
        mask
    }
}

/// Whether `c` lies in `r`, edges included.
fn in_rect(r: Rect<f64>, c: Coord<f64>) -> bool {
    c.x >= r.min().x && c.x <= r.max().x && c.y >= r.min().y && c.y <= r.max().y
}

/// The cell `(col, row)` of `transform` holding `(lon, lat)`.
fn nearest_cell(transform: &GeoTransform, crs: Crs, lon: f64, lat: f64) -> (i64, i64) {
    let (x, y) = crs.from_wgs84(lon, lat);
    // `to_pixel` puts integer indices at cell centres, so the cell holding
    // the point is the nearest centre: floor of the index plus one half.
    let (fx, fy) = transform.to_pixel(x, y);
    ((fx + 0.5).floor() as i64, (fy + 0.5).floor() as i64)
}

/// Encode an RGBA8 buffer of `size` x `size` pixels as a PNG.
fn encode_rgba(rgba: &[u8], size: u32) -> Vec<u8> {
    let mut out = Vec::with_capacity(rgba.len() / 4);
    {
        let mut encoder = png::Encoder::new(&mut out, size, size);
        encoder.set_color(png::ColorType::Rgba);
        encoder.set_depth(png::BitDepth::Eight);
        encoder.set_compression(png::Compression::Balanced);
        // The buffer holds exactly size * size * 4 bytes and the sink is a Vec,
        // so neither write can fail.
        let mut writer = encoder
            .write_header()
            .expect("png header write to Vec is infallible");
        writer
            .write_image_data(rgba)
            .expect("png image write to Vec is infallible");
    }
    out
}

/// One map-layer tile as an RGBA PNG of `config.tile_size` pixels.
///
/// Each pixel centre is turned into lon/lat, then into the raster cell that
/// holds it; the cell value is decoded and coloured with the ramp. Pixels on
/// nodata, outside the raster or outside `clip` are `[0, 0, 0, 0]`; the clip
/// is rasterised once per tile with [`ClipMask::tile_mask`]. `None` when
/// every pixel is transparent.
#[must_use]
pub fn render_layer_tile(
    dem: &Dem,
    config: &DatasetConfig,
    clip: Option<&ClipMask>,
    coord: TileCoord,
) -> Option<Vec<u8>> {
    render_with(config, clip, coord, |lon, lat| {
        let (col, row) = nearest_cell(&dem.transform, dem.crs, lon, lat);
        dem.value_at(col, row).and_then(|raw| config.decode(raw))
    })
}

/// One tile whose pixel at `(lon, lat)` inside `clip` takes the ramp colour
/// of `value(lon, lat)`; every other pixel is transparent. `None` when every
/// pixel is transparent.
fn render_with(
    config: &DatasetConfig,
    clip: Option<&ClipMask>,
    coord: TileCoord,
    value: impl Fn(f64, f64) -> Option<f64>,
) -> Option<Vec<u8>> {
    let size = config.tile_size;
    let edge = size as usize;
    let n = f64::from(1_u32 << coord.z);
    let size_f = f64::from(size);
    let mask = clip.map(|c| c.tile_mask(coord, size));
    let mut rgba = vec![0_u8; edge * edge * 4];
    let mut opaque = false;
    for (row, line) in rgba.chunks_exact_mut(edge * 4).enumerate() {
        let wy = (f64::from(coord.y) + (row as f64 + 0.5) / size_f) / n;
        for (col, pixel) in line.as_chunks_mut::<4>().0.iter_mut().enumerate() {
            let inside = mask.as_ref().is_none_or(|m| m[row * edge + col]);
            let wx = (f64::from(coord.x) + (col as f64 + 0.5) / size_f) / n;
            let (lon, lat) = world_to_wgs84(wx, wy);
            let color = if inside {
                value(lon, lat).map_or([0, 0, 0, 0], |v| ramp_color(&config.ramp, v))
            } else {
                [0, 0, 0, 0]
            };
            opaque |= color[3] != 0;
            *pixel = color;
        }
    }
    opaque.then(|| encode_rgba(&rgba, size))
}

/// One window read from a [`Cog`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Read {
    level: usize,
    x0: i64,
    y0: i64,
    width: u32,
    height: u32,
}

/// Add `read` to `stats`.
fn count(stats: &mut ReadStats, read: &Read) {
    stats.windows += 1;
    stats.pixels += u64::from(read.width) * u64::from(read.height);
}

/// The window of tile `coord` on a level of `size` cells with `transform`:
/// the cells holding the tile corners plus one cell on every side, cut to the
/// level. Every pixel centre of the tile has its cell inside it, or none.
fn tile_window(
    transform: &GeoTransform,
    crs: Crs,
    size: (u32, u32),
    level: usize,
    coord: TileCoord,
) -> Read {
    let n = f64::from(1_u32 << coord.z);
    let (west, north) = world_to_wgs84(f64::from(coord.x) / n, f64::from(coord.y) / n);
    let (east, south) = world_to_wgs84(
        (f64::from(coord.x) + 1.0) / n,
        (f64::from(coord.y) + 1.0) / n,
    );
    let (c0, r0) = nearest_cell(transform, crs, west, north);
    let (c1, r1) = nearest_cell(transform, crs, east, south);
    let x0 = (c0.min(c1) - 1).max(0);
    let y0 = (r0.min(r1) - 1).max(0);
    let x1 = (c0.max(c1) + 1).min(i64::from(size.0) - 1);
    let y1 = (r0.max(r1) + 1).min(i64::from(size.1) - 1);
    let span = |lo: i64, hi: i64| u32::try_from(hi - lo + 1).unwrap_or(0);
    Read {
        level,
        x0,
        y0,
        width: span(x0, x1),
        height: span(y0, y1),
    }
}

/// One map-layer tile of `level` of `cog`: one window, nearest cell per
/// pixel, raw values decoded per pixel; with the window read.
fn render_windowed_tile(
    cog: &mut Cog,
    level: usize,
    config: &DatasetConfig,
    clip: Option<&ClipMask>,
    coord: TileCoord,
) -> Result<(Option<Vec<u8>>, Read)> {
    let missing = || format!("level {level} does not exist");
    let transform = cog
        .geo_transform(level)
        .ok_or_else(|| DatasetError::data(missing()))?;
    let size = cog
        .size(level)
        .ok_or_else(|| DatasetError::data(missing()))?;
    let crs = cog.crs();
    let w = tile_window(&transform, crs, size, level, coord);
    let samples = cog.read_window(level, w.x0, w.y0, w.width, w.height)?;
    let (width, height) = (i64::from(w.width), i64::from(w.height));
    let png = render_with(config, clip, coord, |lon, lat| {
        let (col, row) = nearest_cell(&transform, crs, lon, lat);
        let (x, y) = (col - w.x0, row - w.y0);
        if x < 0 || y < 0 || x >= width || y >= height {
            return None;
        }
        config.decode(samples[(y * width + x) as usize])
    });
    Ok((png, w))
}

/// The highest index `i` with `level_pixel_deg[i] <= target_deg`, else 0:
/// the coarsest level not coarser than the target pixel.
#[must_use]
pub fn pick_level(level_pixel_deg: &[f64], target_deg: f64) -> usize {
    level_pixel_deg
        .iter()
        .rposition(|&pixel| pixel <= target_deg)
        .unwrap_or(0)
}

/// Degrees per tile pixel at `zoom`: `360 / (tile_size * 2^zoom)`.
fn target_deg(tile_size: u32, zoom: u8) -> f64 {
    360.0 / (f64::from(tile_size) * f64::from(1_u32 << zoom))
}

/// The largest power of two `f` with `f * pixel0 <= target`, when the target
/// is at least two level-0 pixels.
fn block_factor(pixel0: f64, target: f64) -> Option<u32> {
    if target
        .partial_cmp(&(2.0 * pixel0))
        .is_none_or(Ordering::is_lt)
    {
        return None;
    }
    let mut factor = 2_u32;
    while let Some(next) = factor.checked_mul(2)
        && f64::from(next) * pixel0 <= target
    {
        factor = next;
    }
    Some(factor)
}

/// Means of the valid decoded level-0 cells of each `factor` x `factor`
/// block over a bounding box, for a raster without overviews.
#[derive(Debug, Clone, PartialEq)]
pub struct BlockLevel {
    /// Level-0 cells per block side.
    factor: u32,
    /// The blocks: origin at the first level-0 cell of the box, cells of
    /// `factor` level-0 cells.
    grid: Grid,
    /// Mean per block, row-major; NaN for a block without a valid cell.
    values: Vec<f32>,
}

/// Sums and counts of valid decoded values per block.
struct BlockSums {
    width: u32,
    height: u32,
    sums: Vec<f64>,
    counts: Vec<u32>,
}

impl BlockSums {
    fn new(width: u32, height: u32) -> Self {
        let len = width as usize * height as usize;
        Self {
            width,
            height,
            sums: vec![0.0; len],
            counts: vec![0; len],
        }
    }

    /// Blocks twice as wide, each summing four of these.
    fn halve(&self) -> Self {
        let mut next = Self::new(self.width.div_ceil(2), self.height.div_ceil(2));
        for row in 0..self.height as usize {
            for col in 0..self.width as usize {
                let from = row * self.width as usize + col;
                let to = row / 2 * next.width as usize + col / 2;
                next.sums[to] += self.sums[from];
                next.counts[to] += self.counts[from];
            }
        }
        next
    }

    fn means(&self) -> Vec<f32> {
        self.sums
            .iter()
            .zip(&self.counts)
            .map(|(&sum, &n)| {
                if n == 0 {
                    f32::NAN
                } else {
                    (sum / f64::from(n)) as f32
                }
            })
            .collect()
    }
}

/// Rows per chunk (tile or strip) of the full-resolution image of `path`.
///
/// `Cog` keeps its chunk size private, so the tags are read with
/// [`inspect::levels`].
fn level0_chunk_rows(path: &Path) -> Result<u32> {
    let levels = inspect::levels(path)?;
    let rows = levels
        .first()
        .ok_or_else(|| DatasetError::data(format!("{}: no full-resolution image", path.display())))?
        .chunk_height;
    if rows == 0 {
        return Err(DatasetError::data(format!(
            "{}: chunks of zero rows",
            path.display()
        )));
    }
    Ok(rows)
}

/// The block levels of `factors` (powers of two from 2) over `bbox`.
///
/// Factor 2 comes from level 0, read in bands of whole chunk rows; each next
/// factor (x 2) from the previous one, so level 0 of the box is never held
/// whole. A block's value is the mean of its valid decoded cells, NaN when it
/// has none. Levels come back in ascending factor order.
///
/// # Errors
///
/// Fails when a factor is not a power of two of at least 2, or, naming the
/// file, when a window cannot be read.
pub fn block_levels(
    raster: &WindowedRaster,
    config: &DatasetConfig,
    bbox: Rect<f64>,
    factors: &[u32],
) -> Result<Vec<BlockLevel>> {
    block_levels_with_reads(raster, config, bbox, factors).map(|(levels, _)| levels)
}

/// [`block_levels`] with the windows read.
fn block_levels_with_reads(
    raster: &WindowedRaster,
    config: &DatasetConfig,
    bbox: Rect<f64>,
    factors: &[u32],
) -> Result<(Vec<BlockLevel>, Vec<Read>)> {
    for &factor in factors {
        if factor < 2 || !factor.is_power_of_two() {
            return Err(DatasetError::data(format!(
                "block factor {factor} is not a power of two of at least 2"
            )));
        }
    }
    let Some(&max) = factors.iter().max() else {
        return Ok((Vec::new(), Vec::new()));
    };
    let grid = raster.grid();
    let t = grid.transform;
    let clamp = |v: f64, n: u32| (v as i64).clamp(0, i64::from(n));
    let c0 = clamp(
        ((bbox.min().x - t.origin_x) / t.pixel_width).floor(),
        grid.width,
    );
    let c1 = clamp(
        ((bbox.max().x - t.origin_x) / t.pixel_width).ceil(),
        grid.width,
    );
    let r0 = clamp(
        ((t.origin_y - bbox.max().y) / t.pixel_height).floor(),
        grid.height,
    );
    let r1 = clamp(
        ((t.origin_y - bbox.min().y) / t.pixel_height).ceil(),
        grid.height,
    );
    let cols = u32::try_from(c1 - c0).unwrap_or(0);
    let rows = u32::try_from(r1 - r0).unwrap_or(0);

    let mut sums = BlockSums::new(cols.div_ceil(2), rows.div_ceil(2));
    let mut reads = Vec::new();
    if cols > 0 && rows > 0 {
        let chunk_rows = i64::from(level0_chunk_rows(raster.path())?);
        reads.reserve(usize::try_from((r1 - r0) / chunk_rows + 2).unwrap_or(0));
        let mut cog = raster.open_cog()?;
        let mut y = r0;
        while y < r1 {
            let end = ((y / chunk_rows + 1) * chunk_rows).min(r1);
            let read = Read {
                level: 0,
                x0: c0,
                y0: y,
                width: cols,
                height: u32::try_from(end - y).unwrap_or(0),
            };
            let samples = cog
                .read_window(0, read.x0, read.y0, read.width, read.height)
                .within(raster.path().display().to_string())?;
            for (dy, line) in samples.chunks_exact(cols as usize).enumerate() {
                let block_row = ((y - r0) as usize + dy) / 2;
                let base = block_row * sums.width as usize;
                for (dx, &raw) in line.iter().enumerate() {
                    if let Some(value) = config.decode(raw) {
                        sums.sums[base + dx / 2] += value;
                        sums.counts[base + dx / 2] += 1;
                    }
                }
            }
            reads.push(read);
            y = end;
        }
    }

    let mut levels = Vec::with_capacity(factors.len());
    let mut factor = 2_u32;
    loop {
        if factors.contains(&factor) {
            let size = f64::from(factor);
            levels.push(BlockLevel {
                factor,
                grid: Grid {
                    width: sums.width,
                    height: sums.height,
                    transform: GeoTransform {
                        origin_x: t.origin_x + c0 as f64 * t.pixel_width,
                        origin_y: t.origin_y - r0 as f64 * t.pixel_height,
                        pixel_width: t.pixel_width * size,
                        pixel_height: t.pixel_height * size,
                    },
                },
                values: sums.means(),
            });
        }
        if factor >= max {
            break;
        }
        sums = sums.halve();
        factor *= 2;
    }
    Ok((levels, reads))
}

/// One map-layer tile of the block level `level`: nearest block per pixel.
fn render_block_tile(
    level: &BlockLevel,
    config: &DatasetConfig,
    clip: Option<&ClipMask>,
    coord: TileCoord,
) -> Option<Vec<u8>> {
    let (width, height) = (i64::from(level.grid.width), i64::from(level.grid.height));
    render_with(config, clip, coord, |lon, lat| {
        let (col, row) = nearest_cell(&level.grid.transform, Crs::Wgs84, lon, lat);
        if col < 0 || row < 0 || col >= width || row >= height {
            return None;
        }
        let value = level.values[(row * width + col) as usize];
        (!value.is_nan()).then(|| f64::from(value))
    })
}

/// A rendered tile: `PMTiles` id and PNG bytes.
type Tile = (u64, Vec<u8>);

/// Where the tiles of one zoom come from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ZoomSource {
    /// A level of the file: 0 or an overview.
    Level(usize),
    /// The block level of this factor.
    Block(u32),
}

/// The map layer of a windowed raster: a source per zoom and the block
/// levels those zooms need.
struct WindowedLayer<'a> {
    raster: &'a WindowedRaster,
    /// One per zoom `0..=max_zoom`.
    sources: Vec<ZoomSource>,
    /// Ascending factor.
    blocks: Vec<BlockLevel>,
}

impl<'a> WindowedLayer<'a> {
    /// Pick a source per zoom and build the block levels over `bbox`; with
    /// the windows read for them. A config with `flags` ignores the file's
    /// overviews: resampling blends flag codes into values that decode as
    /// valid, so its low zooms use block levels, which mask flags per cell.
    fn new(
        raster: &'a WindowedRaster,
        config: &DatasetConfig,
        bbox: Rect<f64>,
    ) -> Result<(Self, Vec<Read>)> {
        let pixel0 = raster.grid().transform.pixel_width;
        let levels = raster.levels();
        let full = levels.first().map_or(1, |&(width, _)| width);
        let level_pixel_deg: Vec<f64> = levels
            .iter()
            .map(|&(width, _)| pixel0 * f64::from(full) / f64::from(width))
            .collect();
        let sources: Vec<ZoomSource> = (0..=config.max_zoom)
            .map(|zoom| {
                let target = target_deg(config.tile_size, zoom);
                if levels.len() > 1 && config.flags.is_empty() {
                    ZoomSource::Level(pick_level(&level_pixel_deg, target))
                } else {
                    block_factor(pixel0, target).map_or(ZoomSource::Level(0), ZoomSource::Block)
                }
            })
            .collect();
        let max = sources
            .iter()
            .filter_map(|s| match s {
                ZoomSource::Block(factor) => Some(*factor),
                ZoomSource::Level(_) => None,
            })
            .max();
        let factors: Vec<u32> = max.map_or_else(Vec::new, |max| {
            std::iter::successors(Some(2_u32), |f| f.checked_mul(2))
                .take_while(|&f| f <= max)
                .collect()
        });
        let (blocks, reads) = block_levels_with_reads(raster, config, bbox, &factors)?;
        Ok((
            Self {
                raster,
                sources,
                blocks,
            },
            reads,
        ))
    }

    /// The non-empty tiles of `coords` at `zoom`, keyed by `PMTiles` id, with
    /// the windows read: one per tile on a file level, none on a block level.
    fn render_zoom(
        &self,
        config: &DatasetConfig,
        clip: Option<&ClipMask>,
        zoom: u8,
        coords: &[TileCoord],
    ) -> Result<(Vec<Tile>, Vec<Read>)> {
        let source = self
            .sources
            .get(usize::from(zoom))
            .ok_or_else(|| DatasetError::data(format!("zoom {zoom} is past max_zoom")))?;
        match *source {
            ZoomSource::Block(factor) => {
                let level = self
                    .blocks
                    .iter()
                    .find(|b| b.factor == factor)
                    .ok_or_else(|| {
                        DatasetError::data(format!("block level {factor} was not built"))
                    })?;
                let tiles = coords
                    .par_iter()
                    .filter_map(|&coord| {
                        render_block_tile(level, config, clip, coord)
                            .map(|png| (tile_to_pmtiles_id(coord), png))
                    })
                    .collect();
                Ok((tiles, Vec::new()))
            }
            ZoomSource::Level(level) => {
                let results = run_pool(
                    coords.len(),
                    rayon::current_num_threads(),
                    || self.raster.open_cog(),
                    |cog, i| render_windowed_tile(cog, level, config, clip, coords[i]),
                )
                .within(format!("{}: zoom {zoom}", self.raster.path().display()))?;
                let mut tiles = Vec::with_capacity(results.len());
                let mut reads = Vec::with_capacity(results.len());
                for ((png, read), &coord) in results.into_iter().zip(coords) {
                    if let Some(png) = png {
                        tiles.push((tile_to_pmtiles_id(coord), png));
                    }
                    reads.push(read);
                }
                Ok((tiles, reads))
            }
        }
    }
}

/// Render counts and time of one zoom level.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ZoomStats {
    /// Zoom level.
    pub zoom: u8,
    /// Tiles rendered: every tile of the bounds at this zoom.
    pub candidates: u64,
    /// Tiles with at least one opaque pixel, written to the archive.
    pub written: u64,
    /// Wall time of rendering this zoom, in milliseconds.
    pub ms: f64,
}

/// Counts and timings of one map-layer archive.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LayerStats {
    /// Tiles written, counting duplicates.
    pub tiles_written: u64,
    /// Distinct tile blobs stored.
    pub unique_tiles: u64,
    /// Size of the archive in bytes.
    pub bytes: u64,
    /// Render wall time over all zooms, in milliseconds.
    pub render_ms_total: f64,
    /// `render_ms_total` divided by the tiles rendered (candidates).
    pub render_ms_per_tile: f64,
    /// One entry per zoom, z0 first.
    pub per_zoom: Vec<ZoomStats>,
}

/// The renderer of one map layer.
enum Renderer<'a> {
    /// The P1 path over a raster in memory.
    Whole(&'a Dem),
    /// One window per tile.
    Windowed(WindowedLayer<'a>),
}

/// Geographic bounds of `raster` as `(min_lon, min_lat, max_lon, max_lat)`.
fn raster_bounds(raster: &Raster) -> (f64, f64, f64, f64) {
    match raster {
        Raster::Whole(dem) => dem.wgs84_bounds(),
        Raster::Windowed(w) => {
            let g = w.grid();
            let t = g.transform;
            let east = t.origin_x + f64::from(g.width) * t.pixel_width;
            let south = t.origin_y - f64::from(g.height) * t.pixel_height;
            (t.origin_x, south, east, t.origin_y)
        }
    }
}

/// Write the map layer of one period to the `PMTiles` archive `out`.
///
/// Zooms `0..=config.max_zoom`, PNG tiles without compression. The bounds are
/// those of `clip` when given, else of the raster, with latitudes clamped to
/// the Mercator limit. Tiles of a zoom render in parallel. A whole raster
/// renders as in P1 and reads no window; a windowed one reads one window per
/// tile at the level [`pick_level`] picks, or, without overviews, renders low
/// zooms from [`block_levels`] over the bounds (whose band reads count too).
/// The second result counts the windows read. The metadata holds
/// `name`, `format`, `type`, `tileSize`, `minzoom`, `maxzoom`, `bounds`,
/// `attribution`, `dataset`, `unit`, `period_end`, `legend` (the ramp stops)
/// and `generator`.
///
/// # Errors
///
/// Fails, naming `out`, when the archive cannot be created, written or
/// stat'ed. For a windowed raster it also fails, naming the raster, when its
/// level-0 chunk size cannot be read (or is zero rows), when a window read
/// fails while the block levels are built or a zoom is rendered (that zoom
/// named), when a tile's overview level does not exist, or when a zoom needs
/// a block level that was not built.
pub fn write_layer_pmtiles(
    raster: &Raster,
    config: &DatasetConfig,
    clip: Option<&ClipMask>,
    out: &Path,
    period_end: &str,
    override_bounds: Option<[f64; 4]>,
) -> Result<(LayerStats, ReadStats)> {
    let (min_lon, min_lat, max_lon, max_lat) = match override_bounds {
        Some([min_lon, min_lat, max_lon, max_lat]) => (min_lon, min_lat, max_lon, max_lat),
        None => match clip.and_then(|c| c.bbox) {
            Some(r) => (r.min().x, r.min().y, r.max().x, r.max().y),
            None => raster_bounds(raster),
        },
    };
    let bounds = (
        min_lon,
        min_lat.clamp(-MAX_LAT, MAX_LAT),
        max_lon,
        max_lat.clamp(-MAX_LAT, MAX_LAT),
    );

    let mut reads = ReadStats::default();
    let renderer = match raster {
        Raster::Whole(dem) => Renderer::Whole(dem),
        Raster::Windowed(w) => {
            let bbox = Rect::new(
                coord! { x: bounds.0, y: bounds.1 },
                coord! { x: bounds.2, y: bounds.3 },
            );
            let started = Instant::now();
            let (layer, block_reads) = WindowedLayer::new(w, config, bbox)?;
            for read in &block_reads {
                count(&mut reads, read);
            }
            tracing::info!(
                levels = layer.blocks.len(),
                windows = block_reads.len(),
                ms = started.elapsed().as_secs_f64() * 1000.0,
                "dataset layer block levels built"
            );
            Renderer::Windowed(layer)
        }
    };

    let mut writer =
        PmtilesWriter::create(out, Compression::None, TileType::Png, 0, config.max_zoom)
            .io_at(IoOp::Create, out)?;
    writer.set_bounds(bounds.0, bounds.1, bounds.2, bounds.3);

    let mut per_zoom = Vec::with_capacity(usize::from(config.max_zoom) + 1);
    for zoom in 0..=config.max_zoom {
        let (min_x, min_y, max_x, max_y) = tile_range_for_bounds(bounds, zoom);
        let coords: Vec<TileCoord> = (min_y..=max_y)
            .flat_map(|y| (min_x..=max_x).map(move |x| TileCoord::new(zoom, x, y)))
            .collect();
        let started = Instant::now();
        let rendered: Vec<(u64, Vec<u8>)> = match &renderer {
            Renderer::Whole(dem) => coords
                .par_iter()
                .filter_map(|&coord| {
                    render_layer_tile(dem, config, clip, coord)
                        .map(|png| (tile_to_pmtiles_id(coord), png))
                })
                .collect(),
            Renderer::Windowed(layer) => {
                let (tiles, zoom_reads) = layer.render_zoom(config, clip, zoom, &coords)?;
                for read in &zoom_reads {
                    count(&mut reads, read);
                }
                tiles
            }
        };
        let ms = started.elapsed().as_secs_f64() * 1000.0;
        for (id, png) in &rendered {
            writer.write_tile(*id, png).io_at(IoOp::Write, out)?;
        }
        tracing::info!(
            zoom,
            candidates = coords.len(),
            written = rendered.len(),
            ms,
            "dataset layer zoom rendered"
        );
        per_zoom.push(ZoomStats {
            zoom,
            candidates: coords.len() as u64,
            written: rendered.len() as u64,
            ms,
        });
    }

    let tiles_written = writer.tiles_written();
    let unique_tiles = writer.unique_tiles() as u64;
    let metadata = json!({
        "name": config.name,
        "format": "png",
        "type": "overlay",
        "tileSize": config.tile_size,
        "minzoom": 0,
        "maxzoom": config.max_zoom,
        "bounds": format!("{},{},{},{}", bounds.0, bounds.1, bounds.2, bounds.3),
        "attribution": config.attribution,
        "dataset": config.id,
        "unit": config.unit,
        "period_end": period_end,
        "legend": config.ramp,
        "generator": concat!("geolith ", env!("CARGO_PKG_VERSION")),
    });
    writer
        .finalize(serde_json::to_string(&metadata)?.as_bytes())
        .io_at(IoOp::Write, out)?;
    let bytes = std::fs::metadata(out).io_at(IoOp::Stat, out)?.len();

    let render_ms_total: f64 = per_zoom.iter().map(|z| z.ms).sum();
    let candidates: u64 = per_zoom.iter().map(|z| z.candidates).sum();
    let render_ms_per_tile = if candidates == 0 {
        0.0
    } else {
        render_ms_total / candidates as f64
    };
    Ok((
        LayerStats {
            tiles_written,
            unique_tiles,
            bytes,
            render_ms_total,
            render_ms_per_tile,
            per_zoom,
        },
        reads,
    ))
}

#[cfg(test)]
mod tests {
    use std::io::Read as _;

    use geo::LineString;

    use super::*;
    use geolith::terrain::Crs;
    use geolith::terrain::dem::GeoTransform;

    fn rainfall() -> DatasetConfig {
        let path =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("data/datasets/rainfall.json");
        DatasetConfig::load(&path).expect("rainfall.json loads")
    }

    /// EPSG:4326, origin (0, 10), 0.05°, 200 x 200 (lon 0..10, lat 0..10),
    /// value 50 everywhere except a nodata block over lon 2..3 x lat 2..3.
    fn fixture_dem() -> Dem {
        let (width, height) = (200_u32, 200_u32);
        let mut values = vec![50.0_f32; (width * height) as usize];
        // lon 2..3 -> cols 40..60; lat 3..2 -> rows 140..160.
        for row in 140..160 {
            for col in 40..60 {
                values[row * width as usize + col] = f32::NAN;
            }
        }
        Dem {
            width,
            height,
            values,
            transform: GeoTransform {
                origin_x: 0.0,
                origin_y: 10.0,
                pixel_width: 0.05,
                pixel_height: 0.05,
            },
            crs: Crs::Wgs84,
        }
    }

    /// The tile at zoom `z` holding `(lon, lat)` and the pixel `(col, row)`
    /// of that point inside a `size`-pixel tile, by the spherical Mercator
    /// formulas.
    fn locate(lon: f64, lat: f64, z: u8, size: u32) -> (TileCoord, u32, u32) {
        let n = f64::from(1_u32 << z);
        let wx = (lon + 180.0) / 360.0 * n;
        let phi = lat.to_radians();
        let wy = (1.0 - (phi.tan() + 1.0 / phi.cos()).ln() / std::f64::consts::PI) / 2.0 * n;
        let (tx, ty) = (wx.floor(), wy.floor());
        let size_f = f64::from(size);
        let col = ((wx - tx) * size_f).floor() as u32;
        let row = ((wy - ty) * size_f).floor() as u32;
        (TileCoord::new(z, tx as u32, ty as u32), col, row)
    }

    /// Decoded RGBA pixels and the edge of one PNG tile.
    fn decode_png(bytes: &[u8]) -> (Vec<u8>, u32) {
        let decoder = png::Decoder::new(std::io::Cursor::new(bytes));
        let mut reader = decoder.read_info().expect("png header");
        let mut buf = vec![0_u8; reader.output_buffer_size().expect("buffer size")];
        let info = reader.next_frame(&mut buf).expect("png frame");
        assert_eq!(info.color_type, png::ColorType::Rgba);
        assert_eq!(info.bit_depth, png::BitDepth::Eight);
        assert_eq!(info.width, info.height);
        buf.truncate(info.buffer_size());
        (buf, info.width)
    }

    /// RGBA of the pixel holding `(lon, lat)` at zoom `z`.
    fn pixel_at(
        dem: &Dem,
        config: &DatasetConfig,
        clip: Option<&ClipMask>,
        lon: f64,
        lat: f64,
        z: u8,
    ) -> [u8; 4] {
        let (coord, col, row) = locate(lon, lat, z, config.tile_size);
        let png = render_layer_tile(dem, config, clip, coord).expect("tile has data");
        let (rgba, size) = decode_png(&png);
        assert_eq!(size, config.tile_size);
        let i = ((row * size + col) * 4) as usize;
        [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
    }

    fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> MultiPolygon<f64> {
        MultiPolygon(vec![Polygon::new(
            LineString::from(vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)]),
            vec![],
        )])
    }

    #[test]
    fn ramp_endpoints_and_midpoint() {
        let ramp = [
            RampStop {
                value: 0.0,
                color: [0, 0, 0, 255],
            },
            RampStop {
                value: 10.0,
                color: [255, 255, 255, 255],
            },
        ];
        assert_eq!(ramp_color(&ramp, -1.0), [0, 0, 0, 255]);
        assert_eq!(ramp_color(&ramp, 5.0), [128, 128, 128, 255]);
        assert_eq!(ramp_color(&ramp, 20.0), [255, 255, 255, 255]);
    }

    #[test]
    fn ramp_hits_stops_exactly() {
        assert_eq!(ramp_color(&rainfall().ramp, 50.0), [0x41, 0xb6, 0xc4, 255]);
    }

    #[test]
    fn data_pixels_get_the_ramp_colour() {
        let config = rainfall();
        let rgba = pixel_at(&fixture_dem(), &config, None, 5.0, 5.0, 0);
        assert_eq!(rgba, [0x41, 0xb6, 0xc4, 255]);
    }

    #[test]
    fn outside_and_nodata_are_transparent() {
        let (dem, config) = (fixture_dem(), rainfall());
        let nodata = pixel_at(&dem, &config, None, 2.5, 2.5, 5);
        assert_eq!(nodata[3], 0, "nodata pixel {nodata:?}");
        let outside = pixel_at(&dem, &config, None, -50.0, 5.0, 0);
        assert_eq!(outside[3], 0, "outside pixel {outside:?}");
    }

    #[test]
    fn the_clip_makes_pixels_transparent() {
        let (dem, config) = (fixture_dem(), rainfall());
        let clip = ClipMask::new(rect(0.0, 0.0, 5.0, 5.0));
        let east = pixel_at(&dem, &config, Some(&clip), 7.5, 2.5, 5);
        assert_eq!(east[3], 0, "east of the clip {east:?}");
        let north = pixel_at(&dem, &config, Some(&clip), 2.5, 7.5, 5);
        assert_eq!(north[3], 0, "north of the clip {north:?}");
        let inside = pixel_at(&dem, &config, Some(&clip), 4.0, 4.0, 5);
        assert_eq!(inside, [0x41, 0xb6, 0xc4, 255]);
    }

    #[test]
    fn sampling_is_nearest_cell() {
        let config = rainfall();
        let dem = Dem {
            width: 2,
            height: 1,
            values: vec![0.0, 100.0],
            transform: GeoTransform {
                origin_x: 0.0,
                origin_y: 0.05,
                pixel_width: 0.05,
                pixel_height: 0.05,
            },
            crs: Crs::Wgs84,
        };
        let low = [0xff, 0xff, 0xd9, 255];
        let high = [0x1d, 0x91, 0xc0, 255];
        assert_eq!(pixel_at(&dem, &config, None, 0.025, 0.025, 12), low);
        // Near the shared edge each side keeps its own cell's colour.
        assert_eq!(pixel_at(&dem, &config, None, 0.045, 0.025, 12), low);
        assert_eq!(pixel_at(&dem, &config, None, 0.055, 0.025, 12), high);
        assert_eq!(pixel_at(&dem, &config, None, 0.075, 0.025, 12), high);
    }

    #[test]
    fn an_empty_tile_is_none() {
        assert!(
            render_layer_tile(&fixture_dem(), &rainfall(), None, TileCoord::new(5, 0, 0)).is_none()
        );
    }

    /// A U-shaped polygon with a square hole in its base and another in its
    /// left leg, plus a disjoint triangle; no vertex sits on a pixel centre.
    fn u_shape() -> MultiPolygon<f64> {
        let ring = |points: &[(f64, f64)]| LineString::from(points.to_vec());
        let u = Polygon::new(
            ring(&[
                (1.013, 1.017),
                (8.991, 1.017),
                (8.991, 8.973),
                (6.987, 8.973),
                (6.987, 3.031),
                (3.019, 3.031),
                (3.019, 8.973),
                (1.013, 8.973),
                (1.013, 1.017),
            ]),
            vec![
                ring(&[
                    (4.003, 1.509),
                    (5.997, 1.509),
                    (5.997, 2.493),
                    (4.003, 2.493),
                    (4.003, 1.509),
                ]),
                ring(&[
                    (1.511, 5.007),
                    (2.487, 5.007),
                    (2.487, 6.993),
                    (1.511, 6.993),
                    (1.511, 5.007),
                ]),
            ],
        );
        let triangle = Polygon::new(
            ring(&[
                (11.007, 2.011),
                (14.993, 2.011),
                (12.997, 7.989),
                (11.007, 2.011),
            ]),
            vec![],
        );
        MultiPolygon(vec![u, triangle])
    }

    /// Every tile at zoom `z` touched by the bounding box of `shape`.
    fn tiles_over(shape: &MultiPolygon<f64>, z: u8) -> Vec<TileCoord> {
        let r = shape.bounding_rect().expect("non-empty shape");
        let (x0, y0, x1, y1) =
            tile_range_for_bounds((r.min().x, r.min().y, r.max().x, r.max().y), z);
        (y0..=y1)
            .flat_map(|y| (x0..=x1).map(move |x| TileCoord::new(z, x, y)))
            .collect()
    }

    /// Lon/lat of the centre of pixel `(col, row)` of `coord`.
    fn pixel_centre(coord: TileCoord, size: u32, col: u32, row: u32) -> (f64, f64) {
        let n = f64::from(1_u32 << coord.z);
        let size_f = f64::from(size);
        let wx = (f64::from(coord.x) + (f64::from(col) + 0.5) / size_f) / n;
        let wy = (f64::from(coord.y) + (f64::from(row) + 0.5) / size_f) / n;
        world_to_wgs84(wx, wy)
    }

    #[test]
    fn tile_mask_equals_contains_on_a_concave_shape_with_a_hole() {
        let size = 256_u32;
        let shape = u_shape();
        let clip = ClipMask::new(shape.clone());
        let (mut inside, mut outside) = (0_u64, 0_u64);
        for z in 3..=5 {
            for coord in tiles_over(&shape, z) {
                let mask = clip.tile_mask(coord, size);
                assert_eq!(mask.len(), (size * size) as usize, "{coord:?}");
                for row in 0..size {
                    for col in 0..size {
                        let (lon, lat) = pixel_centre(coord, size, col, row);
                        let expected = clip.contains(lon, lat);
                        let got = mask[(row * size + col) as usize];
                        assert_eq!(
                            got, expected,
                            "{coord:?} pixel ({col}, {row}) at {lon}, {lat}"
                        );
                        if expected {
                            inside += 1;
                        } else {
                            outside += 1;
                        }
                    }
                }
            }
        }
        assert!(
            inside > 0 && outside > 0,
            "inside {inside}, outside {outside}"
        );
        // The holes and the gap between the legs are cut out of the U.
        for (lon, lat) in [(5.0, 2.0), (2.0, 6.0), (5.0, 6.0), (10.0, 5.0)] {
            assert!(!clip.contains(lon, lat), "({lon}, {lat}) should be outside");
        }
    }

    #[test]
    fn tile_mask_is_all_false_outside_the_bbox() {
        let size = 256_u32;
        let clip = ClipMask::new(u_shape());
        let (far, _, _) = locate(-100.0, 40.0, 5, size);
        let mask = clip.tile_mask(far, size);
        assert_eq!(mask.len(), (size * size) as usize);
        assert!(mask.iter().all(|&inside| !inside));
        let empty = ClipMask::new(MultiPolygon(vec![])).tile_mask(TileCoord::new(0, 0, 0), size);
        assert_eq!(empty.len(), (size * size) as usize);
        assert!(empty.iter().all(|&inside| !inside));
    }

    /// Reference renderer: `ClipMask::contains` per pixel, nearest cell by
    /// direct lon/lat arithmetic on an EPSG:4326 raster.
    fn reference_tile(
        dem: &Dem,
        config: &DatasetConfig,
        clip: &ClipMask,
        coord: TileCoord,
    ) -> Option<Vec<u8>> {
        let size = config.tile_size;
        let mut rgba = Vec::with_capacity((size * size * 4) as usize);
        for row in 0..size {
            for col in 0..size {
                let (lon, lat) = pixel_centre(coord, size, col, row);
                let t = &dem.transform;
                let c = ((lon - t.origin_x) / t.pixel_width).floor() as i64;
                let r = ((t.origin_y - lat) / t.pixel_height).floor() as i64;
                let color = if clip.contains(lon, lat) {
                    dem.value_at(c, r)
                        .and_then(|raw| config.decode(raw))
                        .map_or([0, 0, 0, 0], |v| ramp_color(&config.ramp, v))
                } else {
                    [0, 0, 0, 0]
                };
                rgba.extend_from_slice(&color);
            }
        }
        rgba.iter()
            .skip(3)
            .step_by(4)
            .any(|&a| a != 0)
            .then(|| encode_rgba(&rgba, size))
    }

    #[test]
    fn render_layer_tile_bytes_are_unchanged_by_the_mask() {
        let config = rainfall();
        // 4 x 4 cells of 4° over lon 0..16, lat 0..16; one nodata cell.
        let mut values: Vec<f32> = (0..16).map(|i| i as f32 * 15.0).collect();
        values[5] = f32::NAN;
        let dem = Dem {
            width: 4,
            height: 4,
            values,
            transform: GeoTransform {
                origin_x: 0.0,
                origin_y: 16.0,
                pixel_width: 4.0,
                pixel_height: 4.0,
            },
            crs: Crs::Wgs84,
        };
        let shape = u_shape();
        let clip = ClipMask::new(shape.clone());
        let mut compared = 0;
        for z in 3..=5 {
            for coord in tiles_over(&shape, z) {
                let ours = render_layer_tile(&dem, &config, Some(&clip), coord);
                let reference = reference_tile(&dem, &config, &clip, coord);
                assert_eq!(ours, reference, "{coord:?}");
                compared += usize::from(reference.is_some());
            }
        }
        assert!(compared > 0, "no tile with opaque pixels compared");
    }

    #[test]
    fn the_archive_has_png_tiles_and_attribution() {
        let (dem, config) = (fixture_dem(), rainfall());
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("tiles.pmtiles");
        let (stats, reads) = write_layer_pmtiles(
            &Raster::Whole(dem),
            &config,
            None,
            &path,
            "2026-11-10",
            None,
        )
        .expect("write layer");
        assert_eq!(
            reads,
            ReadStats::default(),
            "a whole raster reads no window"
        );
        let bytes = std::fs::read(&path).expect("archive bytes");
        assert_eq!(&bytes[0..7], b"PMTiles");
        assert_eq!(bytes[99], 2, "tile type PNG");
        assert_eq!(stats.bytes, bytes.len() as u64);
        let field =
            |at: usize| u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes")) as usize;
        let (offset, length) = (field(24), field(32));
        let mut metadata = String::new();
        flate2::read::GzDecoder::new(&bytes[offset..offset + length])
            .read_to_string(&mut metadata)
            .expect("gunzip metadata");
        assert!(
            metadata.contains("Rainfall: CHIRPS v3.0, Climate Hazards Center"),
            "{metadata}"
        );
        assert!(metadata.contains("\"maxzoom\":6"), "{metadata}");
        let json: serde_json::Value = serde_json::from_str(&metadata).expect("metadata json");
        assert_eq!(json["period_end"], "2026-11-10");
        assert_eq!(json["format"], "png");
        assert!(stats.tiles_written > 0, "{stats:?}");
        assert_eq!(stats.per_zoom.len(), 7, "{stats:?}");
        let zooms: std::collections::BTreeSet<u8> = stats.per_zoom.iter().map(|z| z.zoom).collect();
        assert_eq!(zooms, (0..=6).collect());
    }

    /// Samples of a test raster level.
    enum Samples {
        F32(Vec<f32>),
        U8(Vec<u8>),
    }

    impl Samples {
        fn bits(&self) -> u16 {
            match self {
                Samples::F32(_) => 32,
                Samples::U8(_) => 8,
            }
        }

        fn format(&self) -> u16 {
            match self {
                Samples::F32(_) => 3,
                Samples::U8(_) => 1,
            }
        }

        /// Little-endian bytes of sample `i`, zero past the end.
        fn bytes(&self, i: Option<usize>) -> Vec<u8> {
            match self {
                Samples::F32(v) => i.map_or(0.0, |i| v[i]).to_le_bytes().to_vec(),
                Samples::U8(v) => vec![i.map_or(0, |i| v[i])],
            }
        }
    }

    /// Internal tile edge of the test rasters.
    const CHUNK: u32 = 16;
    /// North-west corner of the test rasters.
    const ORIGIN: (f64, f64) = (70.0, 30.0);

    fn le<T: Copy, const N: usize>(values: &[T], f: impl Fn(T) -> [u8; N]) -> Vec<u8> {
        values.iter().flat_map(|&v| f(v)).collect()
    }

    /// An uncompressed little-endian EPSG:4326 `GeoTIFF` with 16 x 16 internal
    /// tiles, origin [`ORIGIN`] and `pixel` degrees at level 0; every later
    /// entry of `levels` is an overview IFD (`NewSubfileType` 1) over the
    /// same extent.
    fn write_cog(path: &Path, pixel: f64, levels: &[(u32, u32, Samples)]) {
        let mut out = vec![b'I', b'I', 42, 0, 0, 0, 0, 0];
        let mut next_at = 4_usize;
        for (level, (width, height, samples)) in levels.iter().enumerate() {
            let (width, height) = (*width, *height);
            let (mut offsets, mut counts) = (Vec::new(), Vec::new());
            for ty in 0..height.div_ceil(CHUNK) {
                for tx in 0..width.div_ceil(CHUNK) {
                    offsets.push(out.len() as u32);
                    let start = out.len();
                    for y in ty * CHUNK..(ty + 1) * CHUNK {
                        for x in tx * CHUNK..(tx + 1) * CHUNK {
                            let inside = x < width && y < height;
                            out.extend(samples.bytes(inside.then(|| (y * width + x) as usize)));
                        }
                    }
                    counts.push((out.len() - start) as u32);
                }
            }
            let shorts = |v: &[u16]| le(v, u16::to_le_bytes);
            let longs = |v: &[u32]| le(v, u32::to_le_bytes);
            // (tag, type, count, bytes); types 3 SHORT, 4 LONG, 12 DOUBLE.
            let mut entries: Vec<(u16, u16, u32, Vec<u8>)> = Vec::with_capacity(16);
            if level > 0 {
                entries.push((254, 4, 1, longs(&[1])));
            }
            entries.extend([
                (256, 4, 1, longs(&[width])),
                (257, 4, 1, longs(&[height])),
                (258, 3, 1, shorts(&[samples.bits()])),
                (259, 3, 1, shorts(&[1])),
                (262, 3, 1, shorts(&[1])),
                (277, 3, 1, shorts(&[1])),
                (284, 3, 1, shorts(&[1])),
                (322, 4, 1, longs(&[CHUNK])),
                (323, 4, 1, longs(&[CHUNK])),
                (324, 4, offsets.len() as u32, longs(&offsets)),
                (325, 4, counts.len() as u32, longs(&counts)),
                (339, 3, 1, shorts(&[samples.format()])),
            ]);
            if level == 0 {
                let geokeys = [1, 1, 0, 3, 1024, 0, 1, 2, 1025, 0, 1, 1, 2048, 0, 1, 4326];
                entries.extend([
                    (33550, 12, 3, le(&[pixel, pixel, 0.0], f64::to_le_bytes)),
                    (
                        33922,
                        12,
                        6,
                        le(&[0.0, 0.0, 0.0, ORIGIN.0, ORIGIN.1, 0.0], f64::to_le_bytes),
                    ),
                    (34735, 3, geokeys.len() as u32, shorts(&geokeys)),
                ]);
            }
            let mut fields = Vec::with_capacity(entries.len());
            for (tag, kind, count, bytes) in entries {
                let value = if bytes.len() <= 4 {
                    let mut inline = bytes;
                    inline.resize(4, 0);
                    inline
                } else {
                    if out.len() % 2 == 1 {
                        out.push(0);
                    }
                    let at = out.len() as u32;
                    out.extend(bytes);
                    at.to_le_bytes().to_vec()
                };
                fields.push((tag, kind, count, value));
            }
            if out.len() % 2 == 1 {
                out.push(0);
            }
            let ifd = out.len() as u32;
            out[next_at..next_at + 4].copy_from_slice(&ifd.to_le_bytes());
            out.extend((fields.len() as u16).to_le_bytes());
            for (tag, kind, count, value) in fields {
                out.extend(tag.to_le_bytes());
                out.extend(kind.to_le_bytes());
                out.extend(count.to_le_bytes());
                out.extend(value);
            }
            next_at = out.len();
            out.extend(0_u32.to_le_bytes());
        }
        std::fs::write(path, out).expect("write tiff");
    }

    /// A test config read the `reader` way, ramp 0 -> #ffffd9, 5 -> #0c2c84.
    fn test_config(reader: &str) -> DatasetConfig {
        DatasetConfig::from_json_str(&format!(
            r##"{{"id": "t", "name": "T", "unit": "mm", "period": "pentad",
                "scale": 1.0, "offset": 0.0, "valid_min": 0.0, "valid_max": 5000.0,
                "nodata": -9999.0, "crs_epsg": 4326,
                "file_template": "t.{{year}}.{{month}}.{{pentad}}.tif",
                "max_zoom": 6, "tile_size": 256, "season_start": "06-01",
                "stale_after_days": 18, "attribution": "a", "source_url": "https://example.org",
                "licence": "CC BY 4.0", "reader": "{reader}",
                "ramp": [{{"value": 0.0, "color": "#ffffd9"}},
                         {{"value": 5.0, "color": "#0c2c84"}}]}}"##
        ))
        .expect("test config is valid")
    }

    fn ndvi() -> DatasetConfig {
        DatasetConfig::from_json_str(include_str!("../data/datasets/ndvi.json"))
            .expect("the ndvi config is valid")
    }

    fn open_windowed(path: &Path, config: &DatasetConfig) -> WindowedRaster {
        match Raster::open(path, config).expect("open") {
            Raster::Windowed(raster) => raster,
            other => panic!("a windowed config opens a windowed raster: {other:?}"),
        }
    }

    /// Values that differ in every cell, nodata (-9999) on every 7th.
    fn varied(width: u32, height: u32) -> Vec<f32> {
        (0..width * height)
            .map(|i| {
                if i % 7 == 3 {
                    -9999.0
                } else {
                    ((i * 37) % 101) as f32 * 0.05
                }
            })
            .collect()
    }

    /// Lon/lat of the north-west corner of cell `(col, row)` at `pixel`.
    fn corner(pixel: f64, col: u32, row: u32) -> (f64, f64) {
        (
            ORIGIN.0 + f64::from(col) * pixel,
            ORIGIN.1 - f64::from(row) * pixel,
        )
    }

    fn tiles_of(bounds: Rect<f64>, z: u8) -> Vec<TileCoord> {
        let (x0, y0, x1, y1) = tile_range_for_bounds(
            (
                bounds.min().x,
                bounds.min().y,
                bounds.max().x,
                bounds.max().y,
            ),
            z,
        );
        (y0..=y1)
            .flat_map(|y| (x0..=x1).map(move |x| TileCoord::new(z, x, y)))
            .collect()
    }

    /// RGBA of pixel `(col, row)` of a PNG tile.
    fn rgba_at(png: &[u8], col: u32, row: u32) -> [u8; 4] {
        let (rgba, size) = decode_png(png);
        let i = ((row * size + col) * 4) as usize;
        [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
    }

    #[test]
    fn pick_level_takes_the_coarsest_level_not_coarser_than_the_target() {
        let pixels = [1.0, 2.0, 4.0];
        assert_eq!(pick_level(&pixels, 3.0), 1);
        assert_eq!(pick_level(&pixels, 0.5), 0);
        assert_eq!(pick_level(&pixels, 9.0), 2);
    }

    #[test]
    fn windowed_tile_at_level_0_equals_the_dem_tile() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("t.tif");
        let (width, height, pixel) = (40, 24, 0.05);
        write_cog(
            &path,
            pixel,
            &[(width, height, Samples::F32(varied(width, height)))],
        );
        let whole_config = test_config("whole");
        let Raster::Whole(dem) = Raster::open(&path, &whole_config).expect("whole") else {
            panic!("a whole config opens a whole raster");
        };
        let config = test_config("windowed");
        let raster = open_windowed(&path, &config);
        let (x0, y0) = corner(pixel, 7, 3);
        let (x1, y1) = corner(pixel, 31, 20);
        let clip = ClipMask::new(rect(x0 + 0.013, y1 + 0.021, x1 - 0.017, y0 - 0.009));
        let bounds = Rect::new(corner(pixel, 0, height), corner(pixel, width, 0));
        let (layer, _) = WindowedLayer::new(&raster, &config, bounds).expect("layer");
        let mut compared = 0;
        for z in 4..=9 {
            // 360 / (256 * 2^4) = 0.088 < 2 x 0.05: level 0 from z4 up.
            assert_eq!(block_factor(pixel, target_deg(config.tile_size, z)), None);
            if let Some(source) = layer.sources.get(usize::from(z)) {
                assert_eq!(*source, ZoomSource::Level(0), "z{z}");
            }
            let coords = tiles_of(bounds, z);
            for clip in [None, Some(&clip)] {
                let mut cog = raster.open_cog().expect("cog");
                for &coord in &coords {
                    let (windowed, read) =
                        render_windowed_tile(&mut cog, 0, &config, clip, coord).expect("tile");
                    let whole = render_layer_tile(&dem, &whole_config, clip, coord);
                    assert_eq!(windowed, whole, "{coord:?} clip {}", clip.is_some());
                    assert_eq!(read.level, 0);
                    compared += usize::from(whole.is_some());
                }
            }
        }
        assert!(compared > 12, "compared {compared} tiles with data");
    }

    /// Level 0: 40 x 24 cells of 0.5° holding 1.0; one overview of 20 x 12
    /// cells of 1° holding 4.0.
    fn write_with_overview(path: &Path) {
        write_cog(
            path,
            0.5,
            &[
                (40, 24, Samples::F32(vec![1.0; 40 * 24])),
                (20, 12, Samples::F32(vec![4.0; 20 * 12])),
            ],
        );
    }

    #[test]
    fn one_window_per_tile() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("t.tif");
        write_with_overview(&path);
        let config = test_config("windowed");
        let raster = Raster::open(&path, &config).expect("open");
        let out = dir.path().join("tiles.pmtiles");
        let (stats, reads) =
            write_layer_pmtiles(&raster, &config, None, &out, "2026-11-10", None).expect("layer");
        let candidates: u64 = stats.per_zoom.iter().map(|z| z.candidates).sum();
        assert!(candidates >= 7, "{stats:?}");
        assert_eq!(reads.windows, candidates, "{stats:?}");
        assert!(reads.pixels > 0, "{reads:?}");
        assert!(stats.tiles_written > 0, "{stats:?}");
    }

    #[test]
    fn overview_levels_are_used_when_present() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("t.tif");
        write_with_overview(&path);
        let config = test_config("windowed");
        let raster = open_windowed(&path, &config);
        assert_eq!(raster.levels(), &[(40, 24), (20, 12)]);
        let bounds = Rect::new(corner(0.5, 0, 24), corner(0.5, 40, 0));
        let (layer, block_reads) = WindowedLayer::new(&raster, &config, bounds).expect("layer");
        assert!(block_reads.is_empty(), "no block averages with overviews");
        // z0 wants 1.41° pixels: the 1° overview; z1 wants 0.70°: level 0.
        for (zoom, level) in [(0_u8, 1_usize), (1, 0)] {
            let coords = tiles_of(bounds, zoom);
            let (tiles, reads) = layer
                .render_zoom(&config, None, zoom, &coords)
                .expect("render");
            assert_eq!(reads.len(), coords.len(), "z{zoom}");
            assert!(reads.iter().all(|r| r.level == level), "z{zoom}: {reads:?}");
            // Lon 80, lat 24 is inside the raster at the centre.
            let (coord, col, row) = locate(80.0, 24.0, zoom, config.tile_size);
            let id = tile_to_pmtiles_id(coord);
            let (_, png) = tiles.iter().find(|(t, _)| *t == id).expect("centre tile");
            let value = if level == 1 { 4.0 } else { 1.0 };
            assert_eq!(
                rgba_at(png, col, row),
                ramp_color(&config.ramp, value),
                "z{zoom}"
            );
        }
    }

    /// 4 x 4 NDVI cells of 0.05°; the four 2 x 2 blocks hold
    /// {100, 100, 255, 254}, {255, 254, 253, 252}, {0, 200, 251, 250} and 7s.
    fn ndvi_blocks() -> Vec<u8> {
        vec![
            100, 100, 255, 254, //
            255, 254, 253, 252, //
            0, 200, 7, 7, //
            251, 250, 7, 7,
        ]
    }

    #[test]
    fn block_average_skips_invalid_cells() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("ndvi.tif");
        write_cog(&path, 0.05, &[(4, 4, Samples::U8(ndvi_blocks()))]);
        let config = ndvi();
        let raster = open_windowed(&path, &config);
        let bbox = Rect::new(corner(0.05, 0, 4), corner(0.05, 4, 0));
        let levels = block_levels(&raster, &config, bbox, &[2]).expect("levels");
        let level = levels.iter().find(|l| l.factor == 2).expect("factor 2");
        assert_eq!((level.grid.width, level.grid.height), (2, 2));
        assert!((level.grid.transform.pixel_width - 0.1).abs() < 1e-12);
        let at = |col: usize, row: usize| level.values[row * 2 + col];
        // 0.004 * 100 - 0.08; 254 is water and 255 missing.
        assert!((at(0, 0) - 0.32).abs() < 1e-6, "{}", at(0, 0));
        assert!(at(1, 0).is_nan(), "{}", at(1, 0));
        // (-0.08 + 0.72 + 0.92) / 3; 251 decodes past valid_max.
        assert!((at(0, 1) - 0.52).abs() < 1e-6, "{}", at(0, 1));
        assert!((at(1, 1) - (-0.052)).abs() < 1e-6, "{}", at(1, 1));

        // At z8 the raster is a few pixels inside one tile.
        let pixel = |lon: f64, lat: f64| {
            let (coord, col, row) = locate(lon, lat, 8, config.tile_size);
            let png = render_block_tile(level, &config, None, coord).expect("tile has data");
            rgba_at(&png, col, row)
        };
        assert_eq!(pixel(70.15, 29.95)[3], 0, "the all-invalid block");
        assert_eq!(
            pixel(70.05, 29.95),
            ramp_color(&config.ramp, f64::from(at(0, 0)))
        );
    }

    #[test]
    fn block_levels_never_read_level_0_whole() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("t.tif");
        let (width, height, pixel) = (40_u32, 56_u32, 0.05);
        let values = varied(width, height);
        write_cog(
            &path,
            pixel,
            &[(width, height, Samples::F32(values.clone()))],
        );
        let config = test_config("windowed");
        let raster = open_windowed(&path, &config);
        // Cells 3..37 x 5..50, edges inside the cells.
        let (x0, y0) = corner(pixel, 3, 5);
        let (x1, y1) = corner(pixel, 37, 50);
        let bbox = Rect::new((x0 + 0.01, y1 + 0.01), (x1 - 0.01, y0 - 0.01));
        let (levels, reads) =
            block_levels_with_reads(&raster, &config, bbox, &[2, 4]).expect("levels");
        assert!(reads.len() >= 3, "{reads:?}");
        assert!(
            reads.iter().all(|r| r.level == 0 && r.height <= CHUNK),
            "{reads:?}"
        );
        assert_eq!(reads.iter().map(|r| r.height).sum::<u32>(), 45, "{reads:?}");
        assert!(
            reads.iter().all(|r| r.x0 == 3 && r.width == 34),
            "{reads:?}"
        );

        // Brute force: the mean of the valid cells of each block of level 0.
        for factor in [2_u32, 4] {
            let level = levels.iter().find(|l| l.factor == factor).expect("level");
            let (ox, oy) = corner(pixel, 3, 5);
            assert!((level.grid.transform.origin_x - ox).abs() < 1e-9);
            assert!((level.grid.transform.origin_y - oy).abs() < 1e-9);
            assert_eq!(level.grid.width, 34_u32.div_ceil(factor));
            assert_eq!(level.grid.height, 45_u32.div_ceil(factor));
            for brow in 0..level.grid.height {
                for bcol in 0..level.grid.width {
                    let mut valid = Vec::new();
                    for row in 5 + brow * factor..(5 + (brow + 1) * factor).min(50) {
                        for col in 3 + bcol * factor..(3 + (bcol + 1) * factor).min(37) {
                            let raw = values[(row * width + col) as usize];
                            if raw != -9999.0 {
                                valid.push(f64::from(raw));
                            }
                        }
                    }
                    let got = level.values[(brow * level.grid.width + bcol) as usize];
                    if valid.is_empty() {
                        assert!(got.is_nan(), "f{factor} ({bcol}, {brow}): {got}");
                    } else {
                        let mean = valid.iter().sum::<f64>() / valid.len() as f64;
                        assert!(
                            (f64::from(got) - mean).abs() < 1e-5,
                            "f{factor} ({bcol}, {brow}): {got} vs {mean}"
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn a_flagged_raster_ignores_blended_overviews() {
        // Level 0: west half water (254), east half raw 100 (NDVI 0.32). The
        // overview holds 200 everywhere, as cubic resampling blends water and
        // land into a valid-looking code.
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("ndvi.tif");
        let level0: Vec<u8> = (0..40 * 24)
            .map(|i| if i % 40 < 20 { 254 } else { 100 })
            .collect();
        write_cog(
            &path,
            0.5,
            &[
                (40, 24, Samples::U8(level0)),
                (20, 12, Samples::U8(vec![200; 20 * 12])),
            ],
        );
        let config = ndvi();
        let raster = open_windowed(&path, &config);
        assert_eq!(raster.levels(), &[(40, 24), (20, 12)]);
        let bounds = Rect::new(corner(0.5, 0, 24), corner(0.5, 40, 0));
        let (layer, _) = WindowedLayer::new(&raster, &config, bounds).expect("layer");
        let coords = tiles_of(bounds, 0);
        let (tiles, _) = layer
            .render_zoom(&config, None, 0, &coords)
            .expect("render");
        let pixel = |lon: f64, lat: f64| {
            let (coord, col, row) = locate(lon, lat, 0, config.tile_size);
            let id = tile_to_pmtiles_id(coord);
            let (_, png) = tiles.iter().find(|(t, _)| *t == id).expect("z0 tile");
            rgba_at(png, col, row)
        };
        assert_eq!(pixel(75.0, 24.0)[3], 0, "water stays transparent at z0");
        assert_eq!(pixel(85.0, 24.0), ramp_color(&config.ramp, 0.32));
    }

    #[test]
    fn a_raster_without_overviews_uses_block_levels_at_low_zooms() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("t.tif");
        write_cog(&path, 0.05, &[(40, 24, Samples::F32(varied(40, 24)))]);
        let config = test_config("windowed");
        let raster = open_windowed(&path, &config);
        let bounds = Rect::new(corner(0.05, 0, 24), corner(0.05, 40, 0));
        let (layer, reads) = WindowedLayer::new(&raster, &config, bounds).expect("layer");
        // Targets 1.41, 0.70, 0.35, 0.18 and 0.088° over 0.05° cells.
        let expected = [
            ZoomSource::Block(16),
            ZoomSource::Block(8),
            ZoomSource::Block(4),
            ZoomSource::Block(2),
            ZoomSource::Level(0),
        ];
        assert_eq!(&layer.sources[..5], &expected);
        let factors: Vec<u32> = layer.blocks.iter().map(|b| b.factor).collect();
        assert_eq!(factors, [2, 4, 8, 16]);
        assert!(!reads.is_empty());
        let coords = tiles_of(bounds, 0);
        let (tiles, zoom_reads) = layer
            .render_zoom(&config, None, 0, &coords)
            .expect("render");
        assert!(zoom_reads.is_empty(), "block zooms read no window");
        assert_eq!(tiles.len(), 1);
    }
}