termzzz 0.0.2

Screen savers and visual effects for terminal
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
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
use crate::buffer::Cell;
use crate::canvas::Canvas;
use crate::common::{DEFAULT_SEED, EffectRng, TerminalEffect, seeded_rng};
use crate::render::BrailleGrid;
use crate::render::braille::{DOTS_X, DOTS_Y};
use crossterm::style;
use rand::RngExt;
use serde::{Deserialize, Serialize};

/// The DVD wordmark, as a dot bitmap: 60 dots across by 28 down, which is
/// exactly 30 by 7 terminal cells at braille's 2x4.
///
/// Supplied as braille art -- thirty columns of the U+2800 block, which is
/// precisely what braille decodes to -- and transcribed here as `#` for an inked
/// dot and `.` for a blank, one character per dot.
///
/// Stored as dots rather than as the braille characters it came from, for two
/// reasons. The renderer only ever needs the dot grid, so a bitmap needs no
/// decoding step to read. And a literal of 1680 U+28xx codepoints is a
/// thousand glyphs that all look alike, so a typo in it is invisible in a diff
/// and invisible in a code review; the same art as `#` and `.` reads as a
/// picture of the shape in the source file.
///
/// The lower half is not damage. It is a 3D extrusion of the wordmark -- a
/// reflection below the baseline -- and it is most of why this reads as *the*
/// DVD logo rather than as the three letters D, V and D. Do not tidy it away.
///
/// This replaced a hand-invented seven-row block letter, which was wrong in the
/// way an approximation always is: it read as `DVD` only if you were already
/// told that is what it was. There is no `DUD` risk here -- a real wordmark
/// does not have that failure mode -- and there is no outline-font problem
/// either, because at 2x4 there is no longer a choice between a slab and a
/// hairline.
const DVD_WORDMARK: &str = "\
.....#######################.........#################......
.....#######################........#####################...
.....#######################........######################..
....########################.......########################.
....######.....##############.....#############.....########
....######.......############.....######.######......#######
...#######.......############....######.#######......#######
...######........######.######..######..######.......#######
...######........######.######..######.#######.......#######
...######.......#######..############..#######.......######.
...######......#######...###########...#######.....########.
...######....########....##########....######.....########..
###################.....########.....##################.....
#################.......#######......################.......
###############.........#######......##############.........
############.............#####.......############...........
...........................####.............................
...........................###..............................
...........................##...............................
....................#################.......................
.......###########################################..........
...##################################################.......
.###########.##..###.####....####...####.....##########.....
###############.####.####.##.####.#####.####.############...
#############..#####.####.##.####.######.###.###########....
..############.#####.####....####...####....##########......
.....###############################################........
..............#############################.................";

/// Whether a logo character leaves its dot unraised.
///
/// A space is, because that is what the character-grid logos this replaced
/// used, and `.` is, because that is the alphabet the wordmark is written in.
/// Everything else is ink, which is what keeps `logo = "DVD"` -- and any
/// config file still carrying the old block letter, a row of `â–ˆ` and spaces --
/// drawing something rather than silently becoming 60 blank dots. See
/// [`DvdOptions::logo`].
fn is_blank(symbol: char) -> bool {
    symbol == ' ' || symbol == '.'
}

/// The logo's colours, in the order it cycles through them.
///
/// Every entry sits in a narrow band of relative luminance, 0.12 to 0.25, and
/// that is the whole design constraint. Against a pure white background a
/// colour is legible at 3:1 or better only below relative luminance 0.30, and
/// against pure black only above 0.10. A terminal profile is whichever of the
/// two the user runs, and a screensaver has no way to ask, so the band that
/// works on both is the band every colour has to be in.
///
/// The first entry used to be `(235, 235, 245)` -- a near-white, luminance
/// 0.83. On a light profile that is 1.03:1, which is invisible, and since
/// `color_index` is randomised at construction the logo was invisible for one
/// frame in six. It is now the deep rose, which is 4.3:1 on white and 4.8:1 on
/// black, and it is first because a red logo is what a DVD logo should be.
///
/// `every_colour_reads_on_a_light_and_on_a_dark_profile` enforces the band, for
/// every entry and not only the first, because `color_index` is randomised so
/// any of them can be the colour a run starts on.
///
/// Twelve rather than six, because consecutive colours are seen seconds apart and
/// need to be obviously different. Six was enough when a change was a
/// once-a-minute event, which is what a corner-only rule amounts to. Hues are
/// spread roughly every thirty degrees at constant luminance, which means the
/// perceived *brightness* never jumps even though the hue always does -- varying
/// luminance as well would read as a flash, and a flash is the complaint
/// [`ColorChange`] is now built to avoid.
const PALETTE: [(u8, u8, u8); 12] = [
    (224, 34, 34),
    (171, 98, 26),
    (120, 120, 18),
    (75, 130, 20),
    (20, 135, 20),
    (20, 133, 76),
    (19, 128, 128),
    (31, 117, 204),
    (90, 70, 240),
    (193, 0, 232),
    (194, 31, 209),
    (214, 32, 138),
];

const DT: f64 = 1.0 / 60.0;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DvdOptions {
    /// Logo to bounce around the screen, as a dot bitmap: one character per dot.
    ///
    /// Rows are separated by `\n`, `#` is an inked dot and `.` is a blank, which
    /// is the alphabet [`DVD_WORDMARK`] is written in. The default is 60 by 28
    /// dots, so 30 by 7 cells.
    ///
    /// The rule is "anything that is not blank is ink" rather than "only `#` is
    /// ink", and that is deliberate, for the sake of every config file already
    /// on disk. `logo = "DVD"` was a legal value under the old character-grid
    /// format and still draws as three inked dots; a row of `â–ˆ` and spaces still
    /// draws as a row of full-height strokes. A stricter alphabet would have made
    /// both of them a field of blanks -- and per the trap in `AGENTS.md`, a
    /// config file *is* how a user ends up pinned to whatever the default was
    /// when they ran `--print-config`.
    pub logo: String,
    /// Base bounce speed in cells per second, along the horizontal axis.
    pub speed: f32,
    /// Cells travelled horizontally per cell travelled vertically.
    ///
    /// This is the other half of "it should go diagonally". The logo moved one
    /// cell right and one cell down for every step, which on a cell grid is *not*
    /// 45 degrees: a terminal cell is roughly twice as tall as it is wide, so equal
    /// cell deltas draw a line at 50 to 63 degrees. Travelling two cells across for
    /// every one down puts the visual angle back at 45.
    ///
    /// Set to 1.0 for equal cell deltas, which is what the classic bouncing logo
    /// does in a character grid.
    pub slope: f32,
    /// When the logo changes colour.
    ///
    /// Was a bool meaning "on corners", and corners are almost unreachable: a
    /// corner hit needs both axes to reverse on the same frame, and the bounce
    /// periods are `2 * max_x / vx` and `2 * max_y / vy`. On an 80x24 terminal
    /// with the default 30-cell logo those are 8.3 and 5.7 seconds, so the two
    /// are least-commonly-aligned after 25 and 17 of them -- 142 seconds, and
    /// even then float accumulation tends to put the two walls on adjacent
    /// frames rather than the same one.
    ///
    /// The original note here put that at "about 95 seconds" and treated it as
    /// the reason the logo sat at one colour too long. Same complaint, much
    /// worse number: over 1,000 seconds of measured simulation the corner
    /// happened **once** at 80x24 and **zero** times at 200x50 and 400x200. See
    /// [`ColorChange::Corner`].
    /// lemonyte's `dvd-screensaver`, which is the reference for this effect,
    /// recolours on *every* wall hit, and that is what [`ColorChange::Bounce`]
    /// still does. It is no longer the default: with a 30-cell wordmark and a
    /// 3D extrusion under it, a full-slab hue change every second and a half is a
    /// strobe rather than a logo. [`ColorChange::Steady`] is the default and is
    /// the same idea slowed by [`RECOLOR_EVERY_N_BOUNCES`].
    pub color_change: ColorChange,
    /// Start the logo from a corner instead of the middle.
    pub start_in_corner: bool,
    /// Throw a ripple of light out of a corner when the logo hits one.
    ///
    /// Independent of [`color_change`](Self::color_change), and it has to be:
    /// [`ColorChange::Corner`] gates on the same conjunction, so tying the wave to
    /// that mode would mean the wave's visibility depends on which recolour rule
    /// the user picked. As it is, `Never` still throws waves.
    ///
    /// **How often you will see one is a measurement, and it is not often.**
    /// A corner needs both axes to clamp on the same frame; over 1,000 seconds at
    /// the shipped defaults that happened once at 80x24 and not at all at 200x50 or
    /// 400x200. See [`ColorChange::Corner`] for the arithmetic. Two fixes were
    /// tried and are recorded there because both were confident: solving `vy` for a
    /// rational ratio of the two bounce periods made corners *rarer* as the ratio
    /// approached 1, and a proximity window (calling a corner any two wall hits
    /// within N frames) works at 80x24 -- one per 100s at N=3, one per 34s at
    /// N=10 -- but does nothing at 400x200, where the periods differ by 2.66s per
    /// cycle and the relative phase walks through a full cycle every 25 minutes.
    ///
    /// So this is honest about being an easter egg rather than a feature you watch
    /// for. If you want it on a predictable beat, the proximity window is the lever
    /// and it is a small change from here.
    ///
    /// The detection is `hit_x && hit_y`, which `step` already computes for the
    /// colour rule, so it costs nothing to watch for it under every mode.
    ///
    /// A screensaver that marks its rarest event is the point of the effect. The
    /// logo is a flat silhouette crossing a flat field, and the only thing that
    /// ever happens to it is bounce-and-recolour; a corner is the one moment with
    /// a *place* in it, and it costs nothing to acknowledge it.
    pub corner_wave: bool,
    /// Seed for the starting corner and colour.
    pub seed: u64,
}

/// How fast a corner wave's radius grows, in cells per second.
///
/// 46, which is about four screens wide a second at 400x200. Chosen against the
/// logo's own speed rather than in the abstract: the default logo crosses its own
/// width in 2.5 seconds, so a wave that took four would still be inside the logo
/// when the logo left the corner, and would read as a smear trailing the logo
/// rather than as something that happened where the logo was. Slower than the
/// logo, faster than the eye tracks a single cell.
const WAVE_SPEED: f64 = 46.0;

/// How long a corner wave lives, in seconds.
///
/// 1.1, at which the radius reaches about 50 cells -- past the logo, and past the
/// near side of an 80x24 terminal in about a second. The wave's own fade is the
/// real limiter; this is the backstop that stops a paused-then-resumed run
/// carrying a dead wave around for ever.
const WAVE_LIFE: f64 = 1.1;

/// Half the wave's thickness in cells, measured as a radial band rather than a
/// hard edge.
///
/// Two, which at 60 Hz is about a cell and a half of travel per frame: a
/// one-cell ring would strobe as it crossed cell boundaries, and a wider one stops
/// reading as a wave and starts reading as a disc.
const WAVE_HALF_WIDTH: f64 = 2.0;

/// The mark a wave is drawn in.
///
/// `·`, a middle dot, and mid-cell on purpose. A baseline glyph would draw a
/// ring whose centre sits below where the ring is, which reads as a ring around
/// the wrong point; `·` is Latin-1 supplement, so it is the same ambiguous-width
/// class the crate already accepts for `â–‘â–’â–“â–ˆ`, and it is a dot rather than a bar
/// so that where the ring crosses a row of text it does not look like more text.
const WAVE_GLYPH: char = '\u{00B7}';

/// The most corner waves alive at once.
///
/// Three. A corner is effectively unreachable at the shipped defaults -- see
/// [`ColorChange::Corner`] -- so on a real run this is never more than one, and
/// this is for the configurations where it is not: a small logo on a large
/// terminal corners on *every* bounce, so the list would otherwise grow without
/// bound. Dropping the oldest is right rather than dropping the newest: a wave
/// from a corner the logo has already left is the one with nothing left to say.
const MAX_WAVES: usize = 3;

/// One ripple of light, expanding from a corner.
struct CornerWave {
    /// The corner, in cells, with the wave's origin at the corner cell itself.
    cx: f64,
    cy: f64,
    /// Seconds since it was thrown. Advances on the frame delta, so it obeys the
    /// pause and speed keys along with everything else in the effect.
    age: f64,
}

/// How many wall hits separate two colour changes in [`ColorChange::Steady`].
///
/// Three, and the complaint that set the number is "it flickers". What flickers
/// is not the logo moving -- it is the *whole* slab changing hue at once, which
/// at 30 by 7 cells is a lot of pixels to repaint simultaneously. On an 80x24
/// terminal a wall hit arrives roughly every 1.4 seconds, so one hue change per
/// hit is a change every 1.4 seconds and one per three is a change every 4.3.
///
/// Bounce count rather than elapsed time or distance travelled, because those two
/// are the same thing once `speed` is fixed, and neither is stable across a
/// resize: a distance rule is throttled by time on a small terminal and not at
/// all on a 400x200 one, where wall hits are half a minute apart and every one
/// of them would qualify. Counting hits is one counter, it is the same fraction
/// of the visible event on every terminal, and it makes the behaviour a pure
/// function of state that a test can drive without a stopwatch.
const RECOLOR_EVERY_N_BOUNCES: u32 = 3;

/// When the bouncing logo changes colour.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ColorChange {
    /// Every third wall hit: the same idea as [`ColorChange::Bounce`] without
    /// changing colour on every single one.
    ///
    /// It was the default once, on the theory that a recolour of a solid 30x7
    /// slab is a large simultaneous change and therefore a strobe. That was the
    /// wrong diagnosis. The flicker is the *speed*, not the colour: the logo is
    /// a braille bitmap, so it is already snapped to whole dots, and at 18 cells
    /// a second that is a one-dot step on most frames -- and a one-dot shift
    /// rewrites nearly every glyph in a dense letterform, because a braille glyph
    /// *is* its bit pattern. Halving the speed removed the shimmer, and with wall
    /// hits eight seconds apart rather than one and a half, recolouring on every
    /// one of them stopped being a strobe too.
    ///
    /// Kept for anyone who wants fewer colour changes than bounces. The
    /// serialised name is unchanged, so a config saying `"steady"` still means
    /// what it meant.
    Steady,
    /// On every wall hit. The default, and what the reference implementation
    /// does.
    ///
    /// This was briefly *not* the default, on the theory that recolouring every
    /// bounce flickered. See [`ColorChange::Steady`] for why that diagnosis was
    /// wrong, what the real cause turned out to be, and why fixing it made this
    /// safe to put back.
    #[default]
    Bounce,
    /// Only when both axes reverse on the same frame, which is the easter egg the
    /// reference's README jokes about -- "it could hit the corner if you look at
    /// it long enough".
    ///
    /// **In practice you will probably never see this fire, and that is a
    /// measurement rather than an opinion.** A corner needs both axes to clamp on
    /// the *same* frame, which is a measure-zero condition: the two bounce periods
    /// are `2*max_x/vx` and `2*max_y/vy`, and with the shipped 30-cell wordmark at
    /// 80x24 those are 8.3 and 5.7 seconds, a ratio of 25:17 whose least common
    /// alignment is 142 seconds away -- and float accumulation means the two walls
    /// are then crossed on *adjacent* frames rather than the same one, which is not
    /// a corner.
    ///
    /// Measured over 1,000 seconds of real simulation at the shipped defaults:
    ///
    /// ```text
    /// terminal   x-hits  y-hits  corners
    /// 80x24        240     350       1
    /// 200x50        70     139       0
    /// 400x200       32      31       0
    /// ```
    ///
    /// See [`DvdOptions::color_change`] for the arithmetic, and the note on
    /// [`DvdOptions::corner_wave`] for what was tried against it.
    Corner,
    /// Never. One colour for the whole run.
    Never,
}

impl ColorChange {
    /// Every variant, so a test can check all of them.
    pub const ALL: &'static [ColorChange] = &[
        ColorChange::Steady,
        ColorChange::Bounce,
        ColorChange::Corner,
        ColorChange::Never,
    ];

    /// Whether a wall hit of these two axes should change the colour.
    ///
    /// `wall_hits` is the caller's own running count of wall hits since the last
    /// recolour. [`ColorChange::Steady`] gates on it and the other three ignore
    /// it. It is a parameter rather than a field so that the rule stays a pure
    /// function and can be checked directly, which
    /// `the_colour_rule_is_what_each_mode_says` does.
    pub fn should_change(self, hit_x: bool, hit_y: bool, wall_hits: u32) -> bool {
        match self {
            ColorChange::Steady => {
                (hit_x || hit_y) && wall_hits >= RECOLOR_EVERY_N_BOUNCES
            }
            ColorChange::Bounce => hit_x || hit_y,
            ColorChange::Corner => hit_x && hit_y,
            ColorChange::Never => false,
        }
    }
}

impl Default for DvdOptions {
    /// Hand-written so it is the single source of truth.
    ///
    /// The builder carried the real defaults while the derived `Default`
    /// produced zeros, and serde used the derived one, so a config file
    /// that omitted a section silently zeroed it.
    fn default() -> Self {
        Self {
            logo: String::from(DVD_WORDMARK),
            // 12.0, and it is set by how often the picture changes rather than
            // by how fast the logo looks like it is travelling.
            //
            // The logo is a braille bitmap, so it can only move in whole dots and
            // the smallest possible jump is one dot -- which rewrites most of a
            // dense letterform, because a braille glyph *is* its bit pattern.
            // That part is irreducible. What is not irreducible is how often it
            // jumps, and it turns out that is the whole of the complaint.
            //
            // Measured over 600 frames at 80x24, by accumulating every diff the
            // way a terminal does and comparing the on-screen dots frame to
            // frame:
            //
            //   speed  5    8   10   12   15   18
            //   moved 17%  28%  34%  40%  51%  82%
            //
            // At 5 the logo moves on **one frame in six** and holds for the
            // other five. That is not slow motion, it is a slideshow: the eye
            // gets five identical frames and then a jump, and reports flicker.
            // The dot step is one dot at every speed in the table -- raising the
            // speed does not make the jumps bigger, only more frequent, so
            // there is no smoothness argument against going faster.
            //
            // 12 puts it at 40%, i.e. movement on roughly every other frame,
            // which at 60 Hz is the point where the eye stops seeing discrete
            // steps and starts integrating them as motion. 15 and 18 keep
            // going up and there is no cliff; this is a taste line, and
            // `speed` in the config moves it.
            //
            // ## The two wrong answers this replaced
            //
            // It was 18, derived as `24 * 23/30` -- the old cap scaled by the
            // old logo's width over the new one. That holds
            // `cells_per_second * width` constant, which is not a quantity that
            // means anything, and it explicitly does *not* preserve the time to
            // cross one logo width; that would want 31. The test asserted 18
            // while its own comment claimed to preserve something it did not.
            //
            // Then 5, derived from lemonyte's screensaver: 50 px/s across a
            // 1920 px window with a logo a sixth of that width, which crosses
            // one logo width every 6.4 seconds, or 4.7 cells a second here.
            // That derivation is arithmetically fine and it is the wrong
            // question -- it asks what the reference *feels* like without asking
            // what the reference is made of. A 1920-pixel window has 1920
            // positions to choose from; a braille cell has two dots, so this
            // logo has 160 columns * 2. **Copying the reference's pace onto a
            // medium with a hundredth of its spatial resolution does not copy
            // its pace, it copies a stutter.** The same comment claimed the
            // slow value avoided "the staircase" by stepping less often, which
            // is precisely backwards: a step is one dot out of sixty, 1.7% of
            // the logo's width, so the *jumps* were never the problem.
            //
            // What this trades against: `ColorChange::Bounce` recolours the
            // whole slab on every wall hit, and a wall hit is 50 cells away, so
            // at 12 that is a full-logo hue change about every four seconds.
            // `color_change = "steady"` thins it to every third if that is what
            // the flicker turns out to be.
            speed: 12.0,
            slope: 2.0,
            color_change: ColorChange::default(),
            start_in_corner: true,
            corner_wave: true,
            seed: DEFAULT_SEED,
        }
    }
}

pub struct Dvd {
    screen_size: (u16, u16),
    options: DvdOptions,
    canvas: Canvas,
    /// The logo's dots, encoded at 2x4 per cell. See [`BrailleGrid`].
    ///
    /// Sized to the *logo's* bounding box in cells, not to the screen: the draw
    /// reads straight through from the source bitmap at a sub-cell offset, so
    /// there is nothing here for a full-screen grid to hold. At 400x200 that is
    /// 30 by 7 cells rather than 80000.
    grid: BrailleGrid,
    /// The logo source, one character per dot. See [`is_blank`].
    rows: Vec<Vec<char>>,
    x: f64,
    y: f64,
    vx: f64,
    vy: f64,
    color_index: usize,
    /// Wall hits since the last recolour. What [`ColorChange::Steady`] counts.
    wall_hits: u32,
    /// Whether the frame just stepped reversed *both* axes: a corner hit.
    ///
    /// Stored rather than re-derived, for the reason on the assignment in
    /// [`step`](Self::step). Read it after `step` and it means the frame just
    /// processed; it is not a latch.
    corner_this_frame: bool,
    /// Ripples currently expanding out of a corner. See [`DvdOptions::corner_wave`].
    waves: Vec<CornerWave>,
    rng: EffectRng,
}

impl TerminalEffect for Dvd {
    fn get_diff(&mut self) -> Vec<(usize, usize, Cell)> {
        self.draw()
    }

    fn update(&mut self) {
        self.step(DT);
    }

    fn update_with_context(&mut self, context: &crate::runtime::FrameContext) {
        self.step(context.delta.as_secs_f64().min(0.1));
    }

    fn update_size(&mut self, width: u16, height: u16) {
        self.screen_size = (width.max(1), height.max(1));
        self.canvas.resize(self.screen_size.0, self.screen_size.1);
        self.reset();
    }

    fn reset(&mut self) {
        self.canvas
            .resize(self.screen_size.0.max(1), self.screen_size.1.max(1));
        self.rows = Self::parse_logo(&self.options.logo);
        // Sized to the logo, plus the spare cell that absorbs the sub-cell skew;
        // see `grid_w`. The logo is what changed size when this moved to braille:
        // 60 dots across is 30 cells and 28 dots down is 7. `resize` is a no-op
        // when the dimensions already match, so this costs nothing on the frames
        // where they do not.
        self.grid.resize(self.grid_w(), self.grid_h());

        // Reseeded rather than merely carried over: a resize is a new screen, and
        // re-rolling the corner and colour is what makes a resize feel like a
        // fresh run instead of a jump cut.
        self.rng = seeded_rng(self.options.seed, "dvd");

        let logo_width = self.logo_width();
        let logo_height = self.logo_height();
        let max_x = (self.screen_size.0 as f64 - logo_width).max(0.0);
        let max_y = (self.screen_size.1 as f64 - logo_height).max(0.0);

        let speed = self.options.speed.max(0.1) as f64;

        if self.options.start_in_corner {
            let corner = self.rng.random_range(0..4);
            self.x = if corner & 1 == 0 { 0.0 } else { max_x };
            self.y = if corner & 2 == 0 { 0.0 } else { max_y };
            // `slope` cells across per cell down, so the *visual* angle is 45
            // degrees on a cell grid that is taller than it is wide.
            let across = speed;
            let down = speed / f64::from(self.options.slope).max(0.1);
            self.vx = if self.x <= 0.0 { across } else { -across };
            self.vy = if self.y <= 0.0 { down } else { -down };
        } else {
            self.x = max_x / 2.0;
            self.y = max_y / 2.0;
            self.vx = speed;
            self.vy = speed / f64::from(self.options.slope).max(0.1);
        }
        self.color_index = self.rng.random_range(0..PALETTE.len());
        // A fresh run has not bounced yet, so the first wall hit it sees is the
        // first of its `RECOLOR_EVERY_N_BOUNCES`. Carrying the count over a
        // resize would make the first post-resize colour depend on how long the
        // previous run had been going.
        self.wall_hits = 0;
        self.corner_this_frame = false;
        // And the same for the waves: one thrown from a corner that no longer
        // exists would expand across a new screen from an old screen's geometry.
        self.waves.clear();
    }
}

impl Dvd {
    pub fn new(options: DvdOptions, screen_size: (u16, u16)) -> Self {
        let screen_size = (screen_size.0.max(1), screen_size.1.max(1));
        let seed = options.seed;
        let mut effect = Self {
            screen_size,
            canvas: Canvas::new(screen_size.0, screen_size.1),
            // Replaced by `reset` below; this only has to be a valid grid.
            grid: BrailleGrid::new(1, 1),
            rows: Vec::new(),
            x: 0.0,
            y: 0.0,
            vx: 1.0,
            vy: 1.0,
            color_index: 0,
            wall_hits: 0,
            corner_this_frame: false,
            waves: Vec::new(),
            // Replaced by `reset` below; this only has to be a valid generator.
            rng: seeded_rng(seed, "dvd"),
            options,
        };
        effect.reset();
        effect
    }

    /// The logo source as a grid of characters, one per dot.
    ///
    /// Blank-only rows are dropped, as they always were, which is what lets a
    /// wordmark be written with leading and trailing blank lines. An empty logo
    /// falls back to a single `*`, so there is always something to draw and
    /// `logo_dot_width` is never zero.
    fn parse_logo(logo: &str) -> Vec<Vec<char>> {
        let rows: Vec<Vec<char>> = logo
            .split('\n')
            .filter(|row| !row.trim().is_empty())
            .map(|row| row.chars().collect())
            .collect();

        if rows.is_empty() {
            vec![vec!['*']]
        } else {
            rows
        }
    }

    /// The widest row of the logo, in dots.
    fn logo_dot_width(&self) -> usize {
        self.rows.iter().map(Vec::len).fold(0, usize::max).max(1)
    }

    /// The logo's height, in dots.
    fn logo_dot_height(&self) -> usize {
        self.rows.len().max(1)
    }

    /// The logo's bounding box in cells.
    fn logo_cells_w(&self) -> usize {
        self.logo_dot_width().div_ceil(DOTS_X)
    }

    fn logo_cells_h(&self) -> usize {
        self.logo_dot_height().div_ceil(DOTS_Y)
    }

    /// The grid's width in cells: the logo's box plus one.
    ///
    /// The spare cell is what absorbs the sub-cell skew. A braille cell's two
    /// dots sit in *one* screen cell, so a logo whose origin is an odd number of
    /// dots across has its last column of dots pushed into the following cell --
    /// and without the spare column that column of ink is silently clipped, on
    /// half the frames, only at the wall.
    ///
    /// It is not a fudge. `x` is clamped to `max_x`, an integer number of cells,
    /// so at the wall the origin is always a whole number of dots and the logo
    /// never does need the spare cell there; it needs it at the skewed positions
    /// just short of the wall, where it lands in the last real cell. The spare
    /// cell is blank whenever the skew is zero, and the write skips blank cells,
    /// so it costs nothing.
    fn grid_w(&self) -> usize {
        self.logo_cells_w() + 1
    }

    fn grid_h(&self) -> usize {
        self.logo_cells_h() + 1
    }

    /// The logo's width in cells: dots across, rounded *up*.    ///
    /// This is the number the bounce has to respect, and it is the thing that
    /// stopped being a count of characters when the logo became a bitmap. A
    /// 60-dot row is 30 cells, not 60, and rounding up rather than down is what
    /// keeps the logo's right-hand column on screen when `x` is at `max_x` --
    /// `the_logo_is_never_clipped_and_never_escapes` is what would catch it the
    /// other way.
    fn logo_width(&self) -> f64 {
        self.logo_cells_w() as f64
    }

    /// The logo's height in cells: dots down, rounded up. Seven for the wordmark.
    fn logo_height(&self) -> f64 {
        self.logo_cells_h() as f64
    }

    /// Whether the logo's dot at `(dot_x, dot_y)` is inked.
    ///
    /// Coordinates are logo-local. Outside the source is blank, which is what
    /// clips the logo at its own bounding box.
    fn ink_at(&self, dot_x: usize, dot_y: usize) -> bool {
        self.rows
            .get(dot_y)
            .and_then(|row| row.get(dot_x))
            .is_some_and(|symbol| !is_blank(*symbol))
    }

    fn step(&mut self, delta: f64) {
        let logo_width = self.logo_width();
        let logo_height = self.logo_height();
        let max_x = (self.screen_size.0 as f64 - logo_width).max(0.0);
        let max_y = (self.screen_size.1 as f64 - logo_height).max(0.0);

        self.x += self.vx * delta;
        self.y += self.vy * delta;

        let mut hit_x = false;
        let mut hit_y = false;

        if max_x > 0.0 {
            if self.x <= 0.0 {
                self.x = 0.0;
                self.vx = self.vx.abs();
                hit_x = true;
            } else if self.x >= max_x {
                self.x = max_x;
                self.vx = -self.vx.abs();
                hit_x = true;
            }
        } else {
            self.x = 0.0;
            self.vx = 0.0;
        }

        if max_y > 0.0 {
            if self.y <= 0.0 {
                self.y = 0.0;
                self.vy = self.vy.abs();
                hit_y = true;
            } else if self.y >= max_y {
                self.y = max_y;
                self.vy = -self.vy.abs();
                hit_y = true;
            }
        } else {
            self.y = 0.0;
            self.vy = 0.0;
        }

        // Counted on every wall hit whatever the mode, so the counter means the
        // same thing to `Steady` as it does to a test reading it. Saturating,
        // because `Never` never resets it: at 60 wall hits a second that is a
        // quarter of a million years, but a debug build panics on the overflow
        // rather than wrapping, and a screensaver is exactly the thing that
        // nobody closes.
        if hit_x || hit_y {
            self.wall_hits = self.wall_hits.saturating_add(1);
        }

        // A corner is both axes reversing on the same frame, which is the
        // conjunction `ColorChange::Corner` already tests. Watched here rather
        // than inside the colour rule because the wave is not the colour rule:
        // `Never` still throws waves, and `Bounce` throws one on the same rare
        // occasion.
        //
        // The position is read after the clamps above, so `x` and `y` are exactly
        // `0.0` or `max_x`/`max_y` on a frame that hit, and this is the corner
        // rather than a position just past it.
        //
        // **Stored rather than re-derived.** The obvious alternative is for a
        // caller to infer it from `waves` -- "was one pushed this frame?" -- and
        // the way to do that is to look for an age of zero, which does not work
        // because the ageing below runs *after* the push, so a wave thrown on a
        // given frame is already one step old by the time `step` returns. That
        // was tried and reported ten disagreements where there were ten corners
        // and no disagreements. An event rare enough that it happens a handful of
        // times in twenty thousand frames is not something to ask about by
        // measuring something else.
        self.corner_this_frame = hit_x && hit_y;
        if self.corner_this_frame && self.options.corner_wave {
            self.waves.push(CornerWave {
                cx: self.x,
                cy: self.y,
                age: 0.0,
            });
            if self.waves.len() > MAX_WAVES {
                self.waves.remove(0);
            }
        }

        // Ageing after the throw, so a wave thrown this frame is one step old
        // rather than one step *younger* -- which would make it lag the logo by
        // one frame on every wave, on a ring that is expanding.
        //
        // `retain` rather than `remove` so the two cannot drift: a wave is
        // dropped by exactly the condition that ends it being drawn.
        for wave in &mut self.waves {
            wave.age += delta;
        }
        self.waves.retain(|wave| wave.age < WAVE_LIFE);

        if self
            .options
            .color_change
            .should_change(hit_x, hit_y, self.wall_hits)
        {
            self.color_index = (self.color_index + 1) % PALETTE.len();
            self.wall_hits = 0;
        }
    }

    /// Paints every live wave's ring onto the canvas, dimmer than the logo.
    ///
    /// Drawn *before* the logo, so the logo occludes the ring where they cross.
    /// A wave is light in the room, not paint on the logo, and having the ring
    /// cut through the wordmark as it passes reads as a rendering fault. The cost
    /// of that choice is that the ring is invisible behind the logo, which is
    /// correct and also most of why a wave reads as coming *from* the corner.
    ///
    /// ## Why this walks the ring instead of scanning for it
    ///
    /// The obvious way to draw a ring is to iterate the bounding box of its
    /// annulus and test each cell's distance. At 400x200 a wave at radius 200
    /// would have a bounding box of the whole screen, so that is 80,000 `hypot`s
    /// a frame to draw about 1,250 cells -- two thirds of this crate's frame
    /// budget spent on arithmetic whose answer is "not in the ring" 98% of the
    /// time, and a number that grows with the *square* of the radius.
    ///
    /// Walking the ring parametrically costs O(circumference) instead: for each
    /// radius in the band, step the angle by whatever keeps consecutive samples
    /// one cell apart. The step is `1/r` radians, so the number of samples is
    /// `ceil(2*pi*r)` and the ring is always connected no matter how far out it
    /// is. That is the whole reason this is a loop over angles and not a loop
    /// over cells.
    fn draw_waves(&mut self, ink: style::Color) {
        let style::Color::Rgb { r, g, b } = ink else {
            return;
        };

        // Copied out before the drawing loop because the loop needs `&mut self`
        // for the canvas and `&self.waves` at once. Three waves, so this is three
        // copies rather than a borrow conflict and a `split_at_mut`.
        let waves: Vec<(f64, f64, f64)> = self
            .waves
            .iter()
            .map(|wave| (wave.cx, wave.cy, wave.age))
            .collect();

        for (cx, cy, age) in waves {
            // Fade on the same curve the radius uses, so the ring dims as it
            // spreads rather than blinking out at the end of its life.
            let remaining = 1.0 - (age / WAVE_LIFE).clamp(0.0, 1.0);
            let color = style::Color::Rgb {
                r: (r as f64 * remaining) as u8,
                g: (g as f64 * remaining) as u8,
                b: (b as f64 * remaining) as u8,
            };

            // At age zero the radius is zero and there is no ring to draw, so a
            // wave is thrown invisible and becomes visible on the next frame. One
            // frame at 60 Hz, and cheaper than the special case that would avoid
            // it.
            let radius = WAVE_SPEED * age;
            let inner = (radius - WAVE_HALF_WIDTH).max(0.0);
            let outer = radius + WAVE_HALF_WIDTH;

            // One radius per cell, so the band is filled rather than being two
            // hairlines with a gap between them.
            let mut r = inner;
            while r <= outer {
                if r > 0.0 {
                    self.stamp_ring(cx, cy, r, color);
                }
                r += 1.0;
            }
        }
    }

    /// Writes one circle of `WAVE_GLYPH`, one sample per cell of arc.
    fn stamp_ring(&mut self, cx: f64, cy: f64, radius: f64, color: style::Color) {
        // One sample per cell of circumference. The division is what keeps the
        // ring connected: a fixed angle count would leave gaps at large radii, and
        // a gap in a ring is not a thinner ring, it is two arcs.
        let samples = (std::f64::consts::TAU * radius).ceil().max(8.0) as usize;
        let cell = Cell::new(WAVE_GLYPH, color, style::Attribute::Reset);

        for index in 0..samples {
            let angle = std::f64::consts::TAU * index as f64 / samples as f64;
            // `.round()` and not `.floor()`. A floor biases every sample down and
            // the ring is very slightly *thinner* than it is centred on, which
            // shows up as the ring and its centre drifting apart as it expands --
            // the same rounding the logo's own sub-cell offset had to agree on.
            let x = (cx + radius * angle.cos()).round();
            let y = (cy + radius * angle.sin()).round();
            if x < 0.0 || y < 0.0 {
                continue;
            }
            let (x, y) = (x as usize, y as usize);
            if x >= self.canvas.width() || y >= self.canvas.height() {
                continue;
            }
            self.canvas.set(x, y, cell);
        }
    }

    /// Draws the logo at its current position into the canvas.
    ///
    /// Sampled *through* a [`BrailleGrid`] rather than rasterised into one, and
    /// that direction is the point. The logo moves at a sub-cell rate, so for
    /// each cell of the grid and each of its eight dots the source is asked
    /// whether *that* dot is inked, at the position the logo has actually
    /// reached. Writing the logo into a screen-sized grid first and encoding
    /// that grid works at whole-cell positions and nowhere else.
    ///
    /// The offset convention is the one the quadrant renderer used, and getting it
    /// wrong is the classic bug here because the failure is quiet: `left` and
    /// `top` are the *screen dot* positions of the logo's origin, and source dot
    /// `(i, j)` lands at `origin + (i, j)`. Round the same way in both places or
    /// the logo jitters against the position `step` reports.
    ///
    /// The old version did `self.x as usize` and `self.y as usize` at the top of
    /// its loops, which threw away every sub-cell part of the position `step` had
    /// carefully integrated. At the old default of nine cells per second that is
    /// 0.15 cells per frame, so the drawn position changed once every seven frames:
    /// the logo sat perfectly still for six frames out of seven and then jumped a
    /// whole cell diagonally. That is the "laggy, like stairs" report.
    ///
    /// Why braille, given quadrant was here first and is still in the crate.
    /// Quadrant spends a cell's foreground *and* its background on a two-tone
    /// split, so every edge cell pays an `ESC[48;2;r;g;b` on the wire and paints
    /// its un-inked half solid black -- which is also why the old logo was
    /// invisible against anything but a black terminal. The DVD wordmark is one
    /// flat colour, because a logo is a silhouette and not a gradient, so that
    /// second colour was buying nothing at all. Braille trades it for 2x across
    /// and 4x down rather than 2x and 2x, and an unraised dot leaves the
    /// terminal's own background showing through the logo's gaps.
    fn draw(&mut self) -> Vec<(usize, usize, Cell)> {
        let (r, g, b) = PALETTE[self.color_index % PALETTE.len()];
        let ink = style::Color::Rgb { r, g, b };

        self.grid.clear();
        // The grid is only as big as the logo, so the canvas still has to be
        // cleared here or the previous frame's logo stays on screen and the two
        // smear into each other.
        self.canvas.clear();

        // Before the logo, so the logo occludes it. See `draw_waves`.
        self.draw_waves(ink);

        // Position in dots, not cells, so the sub-cell part of the position is
        // drawn rather than discarded. A different multiplier per axis, on
        // purpose: braille is 2 across and 4 down, and one constant for both is
        // how the vertical resolution gets thrown away.
        let left = (self.x * DOTS_X as f64).floor().max(0.0) as usize;
        let top = (self.y * DOTS_Y as f64).floor().max(0.0) as usize;
        self.paint_at(left, top);

        // The grid's origin is the logo's origin in cells. `left` is already a
        // whole number of dots, so this is the screen cell holding the logo's
        // first dot -- and when the origin is skewed the logo's *last* dot is one
        // cell further on, which is what the spare cell in `grid_w` is for.
        let left_cell = left / DOTS_X;
        let top_cell = top / DOTS_Y;
        for cell_y in 0..self.grid.height() {
            let y = top_cell + cell_y;
            if y >= self.canvas.height() {
                break;
            }
            for cell_x in 0..self.grid.width() {
                // Only cells with ink are written. A blank braille cell is a
                // space, and painting one would cost a byte and erase whatever
                // the terminal's background is showing there -- which is what
                // lets `[global] background` show through the wordmark's gaps.
                let symbol = self.grid.cell_char(cell_x, cell_y);
                if symbol == ' ' {
                    continue;
                }
                let x = left_cell + cell_x;
                if x >= self.canvas.width() {
                    continue;
                }
                self.canvas.set(
                    x,
                    y,
                    Cell::new(symbol, ink, style::Attribute::Reset),
                );
            }
        }
        self.canvas.commit()
    }

    /// Raises the logo's dots into `self.grid`, with the logo's top-left dot at
    /// screen dot `(left, top)`.
    ///
    /// The grid is indexed by *screen* cell relative to the logo's own cell, not
    /// by the logo's dot, and the difference is the whole sub-cell offset. A
    /// braille cell's two dots live in one screen cell, so a logo whose origin
    /// falls on an odd dot is straddling a cell boundary: its last column of dots
    /// belongs to the *next* screen cell. Sampling the logo with
    /// `left + cell_x * DOTS_X + dx` instead -- which is the obvious transcription
    /// and what this did first -- indexes the source with a screen coordinate and
    /// therefore misses the logo entirely once `left` exceeds its width, drawing
    /// nothing at all.
    ///
    /// So the source index is the grid's own dot position less the skew: `left % 2`
    /// across and `top % 4` down, each handled as a signed offset so a negative
    /// result is blank rather than a huge `usize`. `the_logo_is_sampled_at_its
    /// _sub_cell_offset` is what catches getting this wrong.
    ///
    /// The loop runs over the grid, which is the logo's box plus one cell, and not
    /// over the terminal: 31 by 8 cells rather than 400 by 200.
    fn paint_at(&mut self, left: usize, top: usize) {
        let skew_x = (left % DOTS_X) as isize;
        let skew_y = (top % DOTS_Y) as isize;

        for cell_y in 0..self.grid.height() {
            for cell_x in 0..self.grid.width() {
                for dy in 0..DOTS_Y {
                    for dx in 0..DOTS_X {
                        let dot_x = (cell_x * DOTS_X + dx) as isize - skew_x;
                        let dot_y = (cell_y * DOTS_Y + dy) as isize - skew_y;
                        let raised = dot_x >= 0
                            && dot_y >= 0
                            && self.ink_at(dot_x as usize, dot_y as usize);
                        self.grid.set_dot(
                            cell_x * DOTS_X + dx,
                            cell_y * DOTS_Y + dy,
                            raised,
                        );
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::render::braille::{
        DOTS_PER_CELL, braille_bit, braille_dot_position,
    };
    use std::time::Duration;

    fn options() -> DvdOptions {
        DvdOptions {
            logo: String::from("DVD"),
            start_in_corner: false,
            ..Default::default()
        }
    }

    /// sRGB channel to relative luminance, per WCAG 2.x.
    fn linear(channel: u8) -> f64 {
        let c = f64::from(channel) / 255.0;
        if c <= 0.04045 {
            c / 12.92
        } else {
            ((c + 0.055) / 1.055).powf(2.4)
        }
    }

    fn luminance(color: (u8, u8, u8)) -> f64 {
        0.2126 * linear(color.0)
            + 0.7152 * linear(color.1)
            + 0.0722 * linear(color.2)
    }

    fn contrast(a: f64, b: f64) -> f64 {
        let (hi, lo) = if a > b { (a, b) } else { (b, a) };
        (hi + 0.05) / (lo + 0.05)
    }

    #[test]
    fn the_first_colour_is_not_a_near_white_one() {
        // `color_index` is randomised at construction, so this is the colour a
        // run actually starts on one time in six. It used to be
        // `(235, 235, 245)`, which is 1.03:1 against a white background: not
        // merely dull, invisible.
        let (r, g, b) = PALETTE[0];
        assert!(
            r.min(g).min(b) < 200,
            "PALETTE[0] is ({r}, {g}, {b}), close enough to white to disappear on \
             a light profile"
        );
        assert_ne!(PALETTE[0], (235, 235, 245));
    }

    #[test]
    fn every_colour_reads_on_a_light_and_on_a_dark_profile() {
        // Not only the first: `color_index` is randomised, so any entry can be
        // the colour a run starts on. Fixing one and leaving the other five
        // invisible would have left the same bug five times out of six.
        for color in PALETTE {
            let lum = luminance(color);
            let on_white = contrast(lum, 1.0);
            let on_black = contrast(lum, 0.0);

            assert!(
                on_white >= 3.0,
                "{color:?} is only {on_white:.1}:1 on a light profile"
            );
            assert!(
                on_black >= 3.0,
                "{color:?} is only {on_black:.1}:1 on a dark profile"
            );
        }
    }

    #[test]
    fn a_run_always_starts_on_a_legible_colour() {
        // The end-to-end version of the two above: whatever the seed picks, the
        // logo is drawn in something that can be seen.
        for seed in 0..64u64 {
            let mut effect = Dvd::new(
                DvdOptions {
                    seed,
                    start_in_corner: true,
                    ..Default::default()
                },
                (40, 12),
            );
            effect.get_diff();

            let (r, g, b) = PALETTE[effect.color_index];
            let lum = luminance((r, g, b));
            assert!(
                contrast(lum, 1.0) >= 3.0 && contrast(lum, 0.0) >= 3.0,
                "seed {seed} started on {r},{g},{b}"
            );
        }
    }

    #[test]
    fn new_tracks_screen_size() {
        let effect = Dvd::new(options(), (80, 24));
        assert_eq!(effect.screen_size, (80, 24));
        assert_eq!(effect.rows.len(), 1);
    }

    #[test]
    fn new_terminates_at_minimum_size() {
        let effect = Dvd::new(options(), (0, 0));
        assert_eq!(effect.screen_size, (1, 1));
    }

    #[test]
    fn supports_multiline_logos() {
        let mut effect = Dvd::new(options(), (40, 10));
        effect.options.logo = String::from("ab\ncd");
        effect.reset();

        assert_eq!(effect.rows, vec![vec!['a', 'b'], vec!['c', 'd']]);
    }

    #[test]
    fn blank_logo_falls_back_to_a_single_glyph() {
        let mut effect = Dvd::new(options(), (40, 10));
        effect.options.logo = String::from("   \n  ");
        effect.reset();

        assert_eq!(effect.rows, vec![vec!['*']]);
    }

    /// The logo is a bitmap, so its width in cells is a rounding of its width in
    /// dots, and the bounce has to respect the cell count.
    ///
    /// `options()` gives a three-*dot* logo, which is two cells across at 2 dots
    /// to the cell -- not three. An earlier version of this assertion said
    /// `20 - 3`, which was right when a character was a cell and is one cell too
    /// loose now, so a test like this cannot be left asserting a number from the
    /// old coordinate system.
    #[test]
    fn stays_within_bounds_while_bouncing() {
        let mut effect = Dvd::new(options(), (20, 8));
        assert_eq!(effect.logo_width(), 2.0, "three dots is two cells");
        for _ in 0..600 {
            effect.step(1.0 / 60.0);
            assert!(effect.x >= 0.0 && effect.x <= (20 - 2) as f64);
            assert!(effect.y >= 0.0 && effect.y <= (8 - 1) as f64);
        }
    }

    #[test]
    fn oversize_logo_is_pinned_to_the_origin() {
        let mut effect = Dvd::new(options(), (2, 1));
        effect.options.logo = String::from("TOOLONG");
        effect.reset();

        for _ in 0..120 {
            effect.step(1.0 / 60.0);
            assert_eq!(effect.x, 0.0);
            assert_eq!(effect.y, 0.0);
        }
    }

    /// Every wall hit has to change the colour, in [`ColorChange::Bounce`].
    ///
    /// This is the reference implementation's behaviour, and it is a real look
    /// that `Bounce` still offers. It is no longer the default -- see
    /// `the_colour_changes_far_less_often_than_the_logo_bounces` -- so this test
    /// pins the mode rather than the default.
    ///
    /// The previous option was `corner_color_change`, and corners are almost
    /// unreachable: a corner needs both axes to reverse on the same frame, and the
    /// bounce periods are `2 * max_x / vx` and `2 * max_y / vy`. This uses the
    /// three-*dot* `options()` logo rather than the wordmark, so `max_x` is 78 and
    /// `max_y` is 23 and the periods are 8.7 and 5.1 seconds -- the two only
    /// coincide after 39 and 23 of them, which is over three minutes. So
    /// corner-only was the same as never changing.
    ///
    /// The run is 1800 frames rather than 600 because a wall hit is rarer than it
    /// used to be: the cap came down from 24 to 18 cells a second (see
    /// `DvdOptions::default`) and a wall hit is a traversal, so ten seconds now
    /// buys three of them rather than four. Thirty seconds buys about nine, which
    /// clears the bound with room, and is still two orders of magnitude short of
    /// what a corner needs -- so the test would still fail against corner-only.
    #[test]
    fn every_wall_hit_changes_the_colour() {
        let mut effect = Dvd::new(
            DvdOptions {
                color_change: ColorChange::Bounce,
                ..options()
            },
            (80, 24),
        );
        let initial = effect.color_index;

        let mut changes = 0usize;
        for _ in 0..1800 {
            effect.step(1.0 / 60.0);
            if effect.color_index != initial {
                changes += 1;
            }
        }

        assert!(
            changes >= 3,
            "the colour changed {changes} times in thirty seconds of bouncing, so \
             the logo is effectively one colour. A wall hit every few seconds is \
             what makes this read as motion rather than as a still image drifting."
        );
    }

    /// The colour changes on every wall hit, which is what the reference does
    /// and what was asked for.
    ///
    /// This asserted the *opposite* for a while, and the reason it did is worth
    /// keeping: the belief was that a recolour of a solid 30x7 slab is a large
    /// simultaneous change and therefore a strobe. The diagnosis was wrong. The
    /// flicker was the logo moving -- a braille glyph is its bit pattern, so a
    /// one-dot step rewrites the whole letterform -- and at the speed this effect
    /// ran at then, wall hits were 1.4 seconds apart. At 5 cells a second they
    /// are about eight, and a colour change is an event again.
    ///
    /// So this is now a guard in the other direction: it fails if the default
    /// drifts back to a throttled mode, because that would be quietly
    /// reintroducing the decision this commit reversed.
    #[test]
    fn the_colour_changes_on_every_bounce() {
        let mut effect = Dvd::new(DvdOptions::default(), (80, 24));
        assert_eq!(
            effect.options.color_change,
            ColorChange::Bounce,
            "the default has to be a recolour on every wall hit, or the logo sits \
             at one colour for whole stretches of its run"
        );

        let mut seen = std::collections::BTreeSet::new();
        let mut previous = effect.color_index;
        seen.insert(previous);
        let mut bounces = 0u32;
        let mut changes = 0usize;

        // Stop on a bounce count rather than a frame count, so the run is the
        // same measurement whatever the speed and the screen are.
        //
        // A wall hit is detected by the velocity reversing, not by the position
        // standing still. `step` clamps the position to the wall, so on the frame
        // of a bounce the position has still moved by the overshoot -- a tenth of
        // a cell or so -- and a "did not move" test misses every single bounce.
        // Only the velocity is a clean signal, because `step` changes it if and
        // only if it clamped.
        while bounces < 90 {
            let (vx, vy) = (effect.vx, effect.vy);
            effect.step(1.0 / 60.0);
            if effect.vx != vx || effect.vy != vy {
                bounces += 1;
            }
            if effect.color_index != previous {
                previous = effect.color_index;
                changes += 1;
                seen.insert(effect.color_index);
            }
        }

        assert!(
            bounces >= 90,
            "only saw {bounces} wall hits, so the simulation never got going"
        );
        // Every wall hit, and no more than every wall hit: a mode that changed
        // colour more often than it bounced would be one the bounce counter
        // cannot see, which is how a bug here would hide.
        assert!(
            changes as u32 >= bounces,
            "{changes} colour changes over {bounces} wall hits, so some bounces \
             did not change the colour"
        );
        assert!(
            changes as u32 <= bounces * 2,
            "{changes} colour changes over {bounces} wall hits, so the colour is \
             changing on frames that are not bounces"
        );
        // A sanity floor as well as a ceiling. A rate of zero would satisfy the
        // bound above and is the other failure: the logo would be one colour for
        // the whole run, which is what the old corner-only rule was.
        assert!(
            changes >= 3,
            "only {changes} colour changes over {bounces} wall hits, so the logo \
             is effectively one colour"
        );
        assert!(
            seen.len() > 1 && seen.len() <= PALETTE.len(),
            "{} distinct colours seen, which is not a rotation of the palette",
            seen.len()
        );
    }

    /// [`ColorChange::Bounce`] has to keep changing on *every* hit, or the
    /// contrast with [`ColorChange::Steady`] is not a contrast.
    ///
    /// The same simulation as above, one mode over.
    #[test]
    fn the_reference_mode_changes_on_every_bounce() {
        let mut effect = Dvd::new(
            DvdOptions {
                color_change: ColorChange::Bounce,
                ..DvdOptions::default()
            },
            (80, 24),
        );
        let initial = effect.color_index;
        let mut bounces = 0u32;
        let mut changes = 0usize;
        let mut previous = initial;

        while bounces < 90 {
            let (vx, vy) = (effect.vx, effect.vy);
            effect.step(1.0 / 60.0);
            if effect.vx != vx || effect.vy != vy {
                bounces += 1;
            }
            if effect.color_index != previous {
                previous = effect.color_index;
                changes += 1;
            }
        }

        assert_eq!(
            changes, bounces as usize,
            "Bounce mode changed the colour on {changes} of {bounces} wall hits; it \
             is meant to be every one of them"
        );
        assert_ne!(initial, 0, "unreachable, but keeps `initial` read");
    }

    /// The corner mode has to stay available, because it is the easter egg.
    ///
    /// The reference README jokes that "it could hit the corner if you look at it
    /// long enough", and that is a real thing to be able to switch on.
    #[test]
    fn corner_mode_changes_only_when_both_axes_reverse_together() {
        // Small and square-ish, so the two bounce periods are close and coincide
        // quickly. The old test relied on exactly this, at 6x2.
        for (width, height) in [(6u16, 2u16), (20, 20)] {
            let mut effect = Dvd::new(
                DvdOptions {
                    color_change: ColorChange::Corner,
                    ..options()
                },
                (width, height),
            );
            let initial = effect.color_index;
            let mut changes = 0usize;
            let mut bounces = 0usize;

            for _ in 0..20_000 {
                // A wall hit is a velocity reversing, not a position standing
                // still: `step` clamps the position to the wall, so the position
                // has still moved by the overshoot on the frame of a bounce and a
                // "did not move" test misses them all.
                let (vx, vy) = (effect.vx, effect.vy);
                effect.step(1.0 / 60.0);
                if effect.vx != vx || effect.vy != vy {
                    bounces += 1;
                }
                if effect.color_index != initial {
                    changes += 1;
                    effect.color_index = initial;
                }
            }

            assert!(
                bounces > changes,
                "at {width}x{height} the colour changed {changes} times over \
                 {bounces} wall hits, so corner mode is firing on ordinary \
                 bounces"
            );
        }
    }

    /// `Never` has to actually never.
    #[test]
    fn never_mode_holds_one_colour() {
        let mut effect = Dvd::new(
            DvdOptions {
                color_change: ColorChange::Never,
                ..options()
            },
            (80, 24),
        );
        let initial = effect.color_index;
        for _ in 0..5_000 {
            effect.step(1.0 / 60.0);
            assert_eq!(effect.color_index, initial);
        }
    }

    /// The rule itself, for all four modes, without a simulation in the way.
    ///
    /// The third argument is the running count of wall hits since the last
    /// recolour, and only [`ColorChange::Steady`] reads it. The `wall_hits` values
    /// are swept from zero past the gate, so the boundary itself is pinned rather
    /// than assumed, and the modes that ignore the counter are checked at every
    /// one of them -- which is the whole difference between `Bounce` and `Steady`.
    #[test]
    fn the_colour_rule_is_what_each_mode_says() {
        for wall_hits in 0..=RECOLOR_EVERY_N_BOUNCES + 3 {
            // The reference mode ignores the counter entirely, which is the whole
            // difference between it and the default.
            for (hit_x, hit_y) in [(true, false), (false, true), (true, true)] {
                assert!(ColorChange::Bounce.should_change(hit_x, hit_y, wall_hits));
            }
            assert!(!ColorChange::Bounce.should_change(false, false, wall_hits));

            assert!(!ColorChange::Corner.should_change(true, false, wall_hits));
            assert!(!ColorChange::Corner.should_change(false, true, wall_hits));
            assert!(ColorChange::Corner.should_change(true, true, wall_hits));
            assert!(!ColorChange::Corner.should_change(false, false, wall_hits));

            for (hit_x, hit_y) in [(true, false), (false, true), (true, true)] {
                assert!(!ColorChange::Never.should_change(hit_x, hit_y, wall_hits));
            }

            // The gate: a wall hit that came too early is dropped, and a frame
            // that was not a wall hit is dropped whatever the count says.
            let expected = wall_hits >= RECOLOR_EVERY_N_BOUNCES;
            for (hit_x, hit_y) in [(true, false), (false, true), (true, true)] {
                assert_eq!(
                    ColorChange::Steady.should_change(hit_x, hit_y, wall_hits),
                    expected,
                    "a wall hit at {wall_hits} wall hits since the last change"
                );
            }
            assert!(!ColorChange::Steady.should_change(false, false, wall_hits));
        }
    }

    #[test]
    fn update_with_context_scales_with_delta() {
        let mut fast = Dvd::new(options(), (40, 12));
        let mut slow = Dvd::new(options(), (40, 12));
        fast.x = 0.0;
        slow.x = 0.0;
        fast.vx = 10.0;
        slow.vx = 10.0;
        fast.vy = 0.0;
        slow.vy = 0.0;

        let fast_context = crate::runtime::FrameContext::new(
            (40, 12),
            0,
            Duration::ZERO,
            Duration::from_millis(200),
            crate::runtime::InputState::default(),
        );
        let slow_context = crate::runtime::FrameContext::new(
            (40, 12),
            0,
            Duration::ZERO,
            Duration::from_millis(20),
            crate::runtime::InputState::default(),
        );

        fast.update_with_context(&fast_context);
        slow.update_with_context(&slow_context);

        assert!(fast.x > slow.x);
    }

    /// The picture has to change on almost every frame.
    ///
    /// This is the "it feels laggy, like stairs" complaint, measured.
    ///
    /// `draw` used to do `self.x as usize` and `self.y as usize`, discarding every
    /// sub-cell part of the position `step` had integrated. At the old default of
    /// nine cells per second that is 0.15 cells per frame, so the drawn position
    /// changed once every seven frames: still for six frames out of seven, then a
    /// jump. That is 86 changed frames in 600.
    ///
    /// Measured through the effect's own diff rather than by inspecting the canvas,
    /// for two reasons. It is what the terminal actually receives, and it is the
    /// only measure that works for a sub-cell renderer: with the logo placed at 2x2,
    /// the *cell* holding its top-left ink still only changes once per whole cell
    /// of travel, so a test watching the cell reports a staircase even while the
    /// glyph inside it moves every frame. A version of this test did exactly that
    /// and reported 280 of 600 while the screen was in fact changing 545 times.
    ///
    /// The logo moves on enough frames to read as motion rather than as a
    /// slideshow.
    ///
    /// This is the whole of "it flickers", and it is measured the only way that
    /// means anything: on the *drawn* dots, accumulated frame by frame the way a
    /// terminal does, rather than on the continuous position the effect is
    /// integrating. The continuous position is always perfectly smooth whatever
    /// the speed -- it is a float that advances 0.2 of a cell per frame -- and
    /// asserting anything about *it* only ever restates the speed back to
    /// itself. The previous version of this test did exactly that: a
    /// `worst_step < 0.2` bound on `dvd.x`, which is `speed / 60`.
    ///
    /// The dot step is irreducible. Braille moves in whole dots, so the smallest
    /// possible jump is one dot out of the logo's sixty, and that jump rewrites
    /// most of a dense letterform because a braille glyph *is* its bit pattern.
    /// What is adjustable is how often the jump happens, and the report was that
    /// it flickered, which is what a logo that jumps once every six frames looks
    /// like: five identical frames and then a lurch, with the eye reporting
    /// flicker rather than slowness.
    ///
    /// Measured over 600 frames at 80x24:
    ///
    ///   speed  5    8   10   12   15   18
    ///   moved 17%  28%  34%  40%  51%  82%
    ///
    /// A third is the floor, and it is set by the frame rate rather than by
    /// taste: at 60 Hz, movement on roughly every third frame is where discrete
    /// steps start integrating as motion. The default measures 40%, and the old
    /// default measured 17% -- one frame in six.
    #[test]
    fn the_logo_moves_on_enough_frames_to_read_as_motion() {
        // The dots currently on screen. A diff only carries *changes*, so the
        // frame has to be accumulated -- which is also what the terminal does, and
        // is the only reason this measures the picture rather than the delta.
        let mut cells: std::collections::HashMap<(usize, usize), u32> =
            Default::default();
        let on_screen = |cells: &std::collections::HashMap<(usize, usize), u32>| {
            let mut dots = std::collections::HashSet::new();
            for (&(x, y), &bits) in cells {
                // The bit layout comes from `BrailleGrid`, not from a table
                // written out here. This one carried its own copy with the
                // bottom two dots transposed -- bits 6 and 7 are dots 7 and 8,
                // and the local table had (1,3) at index 6. Counting how many
                // dots move does not care much, which is why it went unnoticed;
                // it is the same mapping as everywhere else, so it is read from
                // the one place that owns it.
                for i in 0..DOTS_PER_CELL {
                    if bits & (1 << i) != 0 {
                        let (dx, dy) = braille_dot_position(i);
                        dots.insert((
                            x as i64 * DOTS_X as i64 + dx as i64,
                            y as i64 * DOTS_Y as i64 + dy as i64,
                        ));
                    }
                }
            }
            dots
        };

        let mut dvd = Dvd::new(DvdOptions::default(), (80, 24));
        let mut previous = on_screen(&cells);
        let _ = dvd.get_diff();
        let mut moved = 0usize;
        for _ in 0..600 {
            dvd.update();
            for (x, y, cell) in dvd.get_diff() {
                let bits = if cell.symbol == ' ' {
                    0
                } else {
                    cell.symbol as u32 - 0x2800
                };
                cells.insert((x, y), bits);
            }
            let current = on_screen(&cells);
            if current != previous {
                moved += 1;
            }
            previous = current;
        }

        assert!(
            moved >= 200,
            "the logo moved on only {moved} of 600 frames, so it holds still for \
             most of them and lurches the rest of the time. At 5 cells a second \
             that is one frame in six, and it reads as a flicker rather than as \
             slow motion -- five identical frames, then a jump."
        );
    }

    /// The vertical position has to resolve finer than a whole cell.
    ///
    /// Half-block was the first attempt and gave 2x vertically; quadrant gave 2x
    /// as well; braille gives 4x. This pins the axis, and it is the axis the
    /// *other* renderers could not improve: horizontally everything in the crate
    /// is 2x, because a cell has one foreground and one background and a vertical
    /// split spends both.
    #[test]
    fn the_vertical_position_resolves_finer_than_a_cell() {
        let mut dvd = Dvd::new(DvdOptions::default(), (80, 24));
        let mut dots = std::collections::BTreeSet::new();
        let mut cells = std::collections::BTreeSet::new();
        // 480 frames rather than 60. The ratio is a ratio of two *distinct*
        // counts over a finite window, and at 5 cells a second the vertical
        // travels 20 cells in that time against 2.5 in one second -- so a
        // one-second window is only ten dot boundaries, and the discreteness of
        // two small samples dominated the ratio. Measured 3.33 over 60 frames and
        // 3.8 over 480, both of which are the sub-cell axis working; the short
        // window was just too short to show it.
        for _ in 0..480 {
            dvd.update();
            dots.insert((dvd.y * DOTS_Y as f64).floor() as i64);
            cells.insert(dvd.y.floor() as i64);
        }
        // The ratio, not an absolute count: the absolute number moves with the
        // speed and the terminal size, and a threshold on it is a threshold on the
        // wrong thing. Four dots per cell means the drawn positions must
        // outnumber the cell positions by close to four to one. The bound is 3.5
        // rather than 4 because the ratio is a ratio of two *distinct* counts over
        // a finite window, and a bounce can make the two agree by coincidence.
        let ratio = dots.len() as f32 / cells.len().max(1) as f32;
        assert!(
            ratio > 3.5,
            "{} distinct drawn vertical positions against {} at whole-cell \
             resolution, a ratio of {ratio:.2}, so the sub-cell vertical motion \
             is not being drawn",
            dots.len(),
            cells.len()
        );
    }

    /// The wordmark literal, checked as a literal.
    ///
    /// 1680 characters of `#` and `.` is a shape no eye can check and no review
    /// will read, so the dimensions are asserted instead: a mistyped row is a row
    /// of the wrong length, and one dropped row is one row fewer. Both are
    /// invisible in a diff and both are fatal here, because a short row silently
    /// truncates the logo's right-hand side rather than failing.
    #[test]
    fn the_wordmark_is_sixty_dots_by_twenty_eight() {
        let rows: Vec<&str> = DVD_WORDMARK.split('\n').collect();
        assert_eq!(
            rows.len(),
            28,
            "the wordmark is {} rows, not 28",
            rows.len()
        );
        for (index, row) in rows.iter().enumerate() {
            assert_eq!(
                row.chars().count(),
                60,
                "row {index} is {} dots wide, not 60: {row:?}",
                row.chars().count()
            );
        }
        // And nothing else is in there. A stray character would be read as ink,
        // so a stray space would put a hole in the logo and a stray letter would
        // put a lump in it, both without a word about it.
        let alphabet: std::collections::BTreeSet<char> =
            DVD_WORDMARK.chars().filter(|c| *c != '\n').collect();
        assert_eq!(
            alphabet,
            ['#', '.'].into_iter().collect(),
            "the wordmark alphabet is {alphabet:?}, not `#` and `.`"
        );
    }

    /// The wordmark has to be letters, not a slab and not nothing.
    ///
    /// A cheap structural guard on a literal, and the numbers are checked as a
    /// *band* rather than as an exact count: 1004 of 1680 dots is 0.60, which is
    /// about right for a heavy wordmark with a reflection under it -- the two
    /// together are mostly ink, and the gaps are inside the counters of the D and
    /// the V and between the letters. A band of 0.35 to 0.80 catches the two
    /// failures that matter, which are a truncated row (coverage collapses) and a
    /// transposed one (coverage stays plausible but the shape is wrong, which no
    /// coverage test can see -- the round-trip test below is what covers that).
    #[test]
    fn the_wordmark_is_neither_blank_nor_a_solid_slab() {
        let total: usize = DVD_WORDMARK.chars().filter(|c| *c != '\n').count();
        let ink = DVD_WORDMARK.chars().filter(|c| *c == '#').count();
        let coverage = ink as f64 / total as f64;

        assert!(
            coverage > 0.35 && coverage < 0.80,
            "the wordmark is {:.0}% inked ({ink} of {total} dots), which is \
             outside the band a wordmark with a reflection sits in",
            coverage * 100.0
        );
        // Ink and gaps, in the other sense: no row may be entirely one or the
        // other. The reflection rows in the middle are the sparsest, and a
        // mistyped one of those is a whole row gone.
        for (index, row) in DVD_WORDMARK.split('\n').enumerate() {
            let dots = row.chars().count();
            let inked = row.chars().filter(|c| *c == '#').count();
            assert!(
                inked > 0 && inked < dots,
                "row {index} is {inked} of {dots} dots, so it is entirely blank or \
                 entirely ink: {row:?}"
            );
        }
    }

    /// The logo is sampled at its sub-cell offset, not at a cell boundary.
    ///
    /// This is the bug the sub-cell offset invites, and it is worth writing down
    /// because the first version of this renderer had it in the most obvious
    /// possible form: it indexed the source with a *screen* coordinate, so
    /// `ink_at(left + cell_x * 2 + dx, ...)` -- which reads correctly while the
    /// logo is near the origin and then walks straight off the end of a 60-dot
    /// row, drew *nothing at all*. A blank screen, no panic, no warning.
    ///
    /// A braille cell's two dots live in one screen cell, so a logo whose origin
    /// lands on an odd dot straddles a cell boundary: dot 0 is the right-hand dot
    /// of one cell and dot 59 the left-hand dot of the one after. The grid has to
    /// be a whole cell bigger than the logo for that to fit, and it has to be
    /// sampled with a signed skew rather than a saturating one, or the last column
    /// is clipped on half the frames.
    ///
    /// Two assertions, and the first is the one that would have caught it:
    ///
    /// * the number of raised dots is the same for every skew, which says no ink
    ///   is lost off the end and none is duplicated across the boundary, and
    /// * the pattern at skew `s` is the pattern at skew 0 shifted by exactly `s`
    ///   dots, which pins the convention rather than just its result.
    #[test]
    fn the_logo_is_sampled_at_its_sub_cell_offset() {
        let mut dvd = Dvd::new(DvdOptions::default(), (80, 24));
        let (dot_w, dot_h) = (dvd.logo_dot_width(), dvd.logo_dot_height());
        let total_ink = (0..dot_w)
            .flat_map(|x| (0..dot_h).map(move |y| (x, y)))
            .filter(|(x, y)| dvd.ink_at(*x, *y))
            .count();

        dvd.grid.clear();
        dvd.paint_at(0, 0);
        let aligned: Vec<Vec<bool>> = (0..dot_h)
            .map(|y| (0..dot_w).map(|x| dvd.grid.dot(x, y)).collect())
            .collect();

        // Skews are 0 or 1 across and 0 to 3 down: the grid's own granularity.
        for skew_x in 0..DOTS_X {
            for skew_y in 0..DOTS_Y {
                dvd.grid.clear();
                dvd.paint_at(skew_x, skew_y);

                let raised = (0..dvd.grid.dot_width())
                    .flat_map(|x| (0..dvd.grid.dot_height()).map(move |y| (x, y)))
                    .filter(|(x, y)| dvd.grid.dot(*x, *y))
                    .count();
                assert_eq!(
                    raised, total_ink,
                    "at a skew of ({skew_x},{skew_y}) the grid holds {raised} raised \
                     dots rather than the wordmark's {total_ink}, so ink has been \
                     lost or doubled"
                );

                for (y, row) in aligned.iter().enumerate() {
                    for (x, expected) in row.iter().enumerate() {
                        assert_eq!(
                            dvd.grid.dot(x + skew_x, y + skew_y),
                            *expected,
                            "dot ({x},{y}) moved wrong at a skew of \
                             ({skew_x},{skew_y})"
                        );
                    }
                }
            }
        }

        // And the spare cell and row exist for a reason: the grid is one cell
        // bigger than the logo, and that cell has to be able to hold ink, or the
        // skewed pattern above would have been clipped and the dot count would
        // have come out short.
        assert_eq!(dvd.grid.width(), dvd.logo_cells_w() + 1);
        assert_eq!(dvd.grid.height(), dvd.logo_cells_h() + 1);
        dvd.grid.clear();
        dvd.paint_at(1, 1);
        assert!(
            dvd.grid.dot_width() > dot_w && dvd.grid.dot_height() > dot_h,
            "the grid is {}x{} dots, which does not have room for a logo of \
             {dot_w}x{dot_h} shifted by a dot",
            dvd.grid.dot_width(),
            dvd.grid.dot_height()
        );
    }

    /// The wordmark survives the trip through the renderer.
    ///
    /// The art was supplied as braille, so the only way to know the transcription
    /// is right is to encode it back and look at the result. This drives the
    /// effect's own `paint_at` at the origin -- not a reimplementation of it, or
    /// it would agree with a broken `paint_at` -- and then checks the encoding
    /// against the source: the box is 30 by 7 cells, and two named dots land
    /// where the bitmap says. The first of those is the top-left inked dot of the
    /// left stroke of the D and the second is the blank above it, so a renderer
    /// that shifted its origin by a cell or a row would fail on one or both.
    #[test]
    fn the_wordmark_round_trips_through_braille() {
        let mut dvd = Dvd::new(DvdOptions::default(), (80, 24));
        dvd.grid.clear();
        dvd.paint_at(0, 0);

        assert_eq!(dvd.logo_cells_w(), 30, "60 dots across at 2 to the cell");
        assert_eq!(dvd.logo_cells_h(), 7, "28 dots down at 4 to the cell");
        assert_eq!(dvd.grid.width(), 31, "the logo's 30 cells plus the spare");
        assert_eq!(dvd.grid.height(), 8, "seven cells plus the spare");
        assert_eq!(dvd.grid.dot_width(), 62);
        assert_eq!(dvd.grid.dot_height(), 32);

        // Named dots rather than a comparison against the source, because
        // comparing against the source would agree with a broken `paint_at` by
        // construction. These are what a shifted origin, a transposed one, or a
        // row dropped from the literal all break. Row 0 of the wordmark is
        // `.....#######################.........#################......`,
        // row 4 opens the counters, rows 16 to 18 are the point of the V, and
        // rows 19 to 27 are the reflection.
        for (dot_x, dot_y, expected, what) in [
            (0usize, 0usize, false, "the top-left corner"),
            (5, 0, true, "the left stroke of the first D"),
            (4, 0, false, "the blank one dot to its left"),
            (28, 0, false, "the gap between the D and the V at the top"),
            (37, 0, true, "the top of the second letter's left stroke"),
            (53, 0, true, "the far end of that letter's top bar"),
            (54, 0, false, "the blank beyond it"),
            (59, 0, false, "the top-right corner"),
            (10, 4, false, "inside the first D's counter"),
            (34, 4, true, "a stem of the V"),
            (52, 4, true, "the left stroke of the last D"),
            (27, 16, true, "the point of the V"),
            (26, 16, false, "just left of the point"),
            (20, 19, true, "the top bar of the reflection"),
            (19, 19, false, "just left of it"),
            (30, 20, true, "the middle of the reflection"),
            (14, 27, true, "the foot of the reflection"),
            (13, 27, false, "just left of the foot"),
            (43, 27, false, "just right of the foot"),
            (0, 27, false, "the bottom-left corner"),
        ] {
            assert_eq!(
                dvd.grid.dot(dot_x, dot_y),
                expected,
                "dot ({dot_x},{dot_y}) -- {what}"
            );
        }

        // And every dot of the grid agrees with the source, which is what makes
        // the named dots above a summary rather than the whole test.
        for dot_y in 0..dvd.grid.dot_height() {
            for dot_x in 0..dvd.grid.dot_width() {
                assert_eq!(
                    dvd.grid.dot(dot_x, dot_y),
                    dvd.ink_at(dot_x, dot_y),
                    "dot ({dot_x},{dot_y}) disagrees with the wordmark"
                );
            }
        }

        // And the encoding is braille, by name, for three cells whose bit patterns
        // are worked out by hand from the bitmap above. U+28FF is all eight dots,
        // which is the property a logo needs from a sub-cell renderer: a solid
        // interior has to come out solid, or the letter is visibly striped. U+28F8
        // is DOTS-4-5-6-7-8 -- the right-hand column of a cell raised on all four
        // rows plus the bottom-left dot -- which is the slanted left edge of the
        // first D. The fourth is the top-left corner, which has to be a space
        // rather than a blank pattern: `BrailleGrid` emits a space for an empty
        // cell because it is one byte narrower, and that is the byte-cost half of
        // only writing cells that have ink.
        //
        // This cell used to be asserted as U+28EA, which is DOTS-2-4-6-7-8. Under
        // the row-major reading that happened to be the set this art produced,
        // and it is a *different* set from U+28F8, so the assertion was pinning
        // the encoding rather than the picture. The comment described the encoded
        // bits, not the dots, which is how it read as a note about the art while
        // being a note about the arithmetic. The dots do not move when the mapping
        // is fixed, so the dot description above is the part that was always true.
        assert_eq!(dvd.grid.cell_char(2, 1), '\u{28ff}', "a solid interior");
        assert_eq!(dvd.grid.cell_char(2, 0), '\u{28f8}', "the slanted edge");
        assert_eq!(dvd.grid.cell_char(0, 0), ' ', "a cell with no ink");
        assert_eq!(dvd.grid.cell_char(29, 6), ' ', "the far bottom corner");
    }

    /// The logo is big.
    ///
    /// It was three characters on one line, which is a text label rather than a
    /// logo, and then a 23-cell block letter, which is bigger but not the thing.
    /// It was previously pinned by name in an integration test too, which had to
    /// be updated with it. The assertion follows the effect: 30 cells by 7 is the
    /// wordmark, at braille's 2x4, and it is exactly a quarter of an 80x24
    /// terminal's width, which is about what a bouncing logo should occupy.
    #[test]
    fn the_default_logo_is_a_real_wordmark() {
        let dvd = Dvd::new(DvdOptions::default(), (80, 24));
        assert_eq!(dvd.rows.len(), 28, "28 dot rows");
        assert_eq!(
            dvd.rows.iter().map(Vec::len).max().unwrap_or(0),
            60,
            "60 dots across"
        );
        assert_eq!(dvd.logo_width(), 30.0, "60 dots is 30 cells");
        assert_eq!(dvd.logo_height(), 7.0, "28 dots is 7 cells");
        assert_eq!(dvd.grid.width(), 31, "the logo's cells plus the skew spare");
        assert_eq!(dvd.grid.height(), 8);
    }

    /// The logo has to stay whole and stay on screen, at every position.
    ///
    /// `max_x` is `screen_width - logo_cells` and the draw is at
    /// `left_cell + cell_x`, so that bounds math is what keeps the logo's
    /// right-hand column on screen at the wall. If the width in cells were
    /// rounded the other way -- down, to 29 for a 58-dot logo -- the last column
    /// would be off the edge at the far wall, and `Canvas::set` would drop the
    /// write rather than panicking, so the right-hand sliver of the D would
    /// quietly disappear for a moment on every crossing.
    ///
    /// The positions checked are the four corners *and* the skewed positions just
    /// short of them, because those are different cases. At a wall `x` is a whole
    /// number of cells, so the origin is a whole number of dots and the logo
    /// occupies exactly its 30 cells. Half a cell short, the origin is an odd dot,
    /// the logo's last column of dots moves into the 31st cell, and that cell has
    /// to be the last *real* one rather than off the end.
    ///
    /// The check decodes what was written rather than counting it. A braille
    /// glyph is its own bit pattern, so a cell's glyph says exactly which of its
    /// eight dots are raised -- which means the whole claim can be checked dot by
    /// dot: every dot of the wordmark must be raised in the cell that contains it,
    /// and nothing else may be. That is stronger than a cell count (which changes
    /// with the skew, because shifting a pattern one dot moves ink between cells)
    /// and it catches clipping, doubling and a mis-signed offset alike.
    #[test]
    fn the_logo_is_never_clipped_and_never_escapes() {
        /// The raised dots of a braille glyph, or zero for anything else -- a
        /// space saturates to nothing rather than wrapping.
        fn dots_of(symbol: char) -> u8 {
            u32::from(symbol).saturating_sub(0x2800) as u8
        }

        let (width, height) = (80u16, 24u16);
        // Painted rather than read off a fresh grid: `draw` clears the grid before
        // filling it, so a `Dvd` that has never been drawn has an empty one.
        let mut template = Dvd::new(DvdOptions::default(), (width, height));
        template.grid.clear();
        template.paint_at(0, 0);
        let max_x = width as f64 - template.logo_width();
        let max_y = height as f64 - template.logo_height();
        let (dot_w, dot_h) =
            (template.logo_dot_width(), template.logo_dot_height());

        for x in [0.0, 0.5, max_x - 0.5, max_x] {
            for y in [0.0, 0.25, max_y - 0.25, max_y] {
                let mut dvd = Dvd::new(DvdOptions::default(), (width, height));
                dvd.x = x;
                dvd.y = y;
                let diff = dvd.get_diff();

                let mut written: std::collections::BTreeMap<(usize, usize), u8> =
                    Default::default();
                for (cx, cy, cell) in diff {
                    assert!(
                        cx < width as usize && cy < height as usize,
                        "at ({x}, {y}) the draw emitted ({cx},{cy}), outside the \
                         terminal"
                    );
                    assert_ne!(cell.symbol, ' ', "a blank cell was written");
                    written.insert((cx, cy), dots_of(cell.symbol));
                }

                let left = (x * DOTS_X as f64).floor() as usize;
                let top = (y * DOTS_Y as f64).floor() as usize;
                for dot_j in 0..dot_h {
                    for dot_i in 0..dot_w {
                        // Where this dot of the wordmark lands: the screen cell
                        // containing its screen dot, and its position *within*
                        // that cell. Both are offset by the origin, which is the
                        // whole point -- `dot_i % DOTS_X` would be the unskewed
                        // answer and would be wrong on every odd frame.
                        let screen_x = left + dot_i;
                        let screen_y = top + dot_j;
                        let cell_x = screen_x / DOTS_X;
                        let cell_y = screen_y / DOTS_Y;
                        let bit = braille_bit(screen_x % DOTS_X, screen_y % DOTS_Y);
                        let raised = written
                            .get(&(cell_x, cell_y))
                            .is_some_and(|bits| bits & bit != 0);
                        assert_eq!(
                            raised,
                            dvd.ink_at(dot_i, dot_j),
                            "at ({x}, {y}) the wordmark's dot ({dot_i},{dot_j}) is \
                             not drawn as the bitmap says"
                        );
                    }
                }
            }
        }
    }

    /// The diagonal has to be a diagonal, and 45 degrees visually.
    ///
    /// One cell right and one cell down is *not* 45 degrees on a cell grid: a
    /// terminal cell is roughly twice as tall as it is wide, so equal cell deltas
    /// draw a line at 50 to 63 degrees from horizontal.
    #[test]
    fn the_diagonal_is_corrected_for_the_cell_aspect_ratio() {
        let dvd = Dvd::new(DvdOptions::default(), (80, 24));
        let across_per_down =
            (dvd.vx.abs() / dvd.vy.abs().max(f64::MIN_POSITIVE)) as f32;
        assert!(
            (across_per_down - dvd.options.slope).abs() < 0.01,
            "the logo travels {across_per_down} cells across per cell down, but \
             slope is {}",
            dvd.options.slope
        );
        assert!(
            dvd.options.slope > 1.0,
            "a slope of {} draws equal cell deltas, which on this cell aspect \
             ratio is a line at 50 to 63 degrees rather than a diagonal",
            dvd.options.slope
        );
    }

    /// The speed is the frame-movement rate, not the reference's pace.
    ///
    /// This test pinned the reference's derived value for a while, and the
    /// derivation was arithmetically correct: lemonyte's screensaver moves 50
    /// px/s across a 1920 px window with a logo a sixth of that width, so it
    /// crosses one logo width every 6.4 seconds, which is 4.7 cells a second
    /// here. It was the wrong question. It asked what the reference *feels* like
    /// without asking what the reference is made of -- and a 1920-pixel window
    /// has 1920 positions to choose from where a braille cell has two dots, so
    /// this logo has 160 columns * 2.
    ///
    /// **Copying the reference's pace onto a medium with a hundredth of its
    /// spatial resolution does not copy its pace, it copies a stutter.** At 4.7
    /// cells a second the logo moved on one frame in six, and the report was
    /// flicker.
    ///
    /// The rule this pins instead: movement on at least a third of frames, which
    /// is where discrete dot steps start integrating as motion at 60 Hz. See
    /// `the_logo_moves_on_enough_frames_to_read_as_motion` for the measurement
    /// and the table behind it. This test guards the *number* so the two cannot
    /// drift apart; the other one is the claim itself.
    ///
    /// Asserted as a band, because a speed is something a user will want to move
    /// and because the table has no cliff at the top -- 15 and 18 both measured
    /// higher still.
    #[test]
    fn the_speed_gives_movement_on_at_least_a_third_of_frames() {
        // From the measured table, the speed at which the logo crosses a third of
        // frames. Linear in the speed, since the dot step is one dot at every
        // speed and only the frequency changes: 40% at 12, 34% at 10, so a third
        // lands at about 9.7.
        const THIRD_OF_FRAMES_AT: f32 = 10.0;
        let options = DvdOptions::default();
        assert!(
            options.speed >= THIRD_OF_FRAMES_AT,
            "the speed is {}, and below about {THIRD_OF_FRAMES_AT} the logo moves \
             on under a third of frames, which reads as a stutter rather than as \
             motion",
            options.speed
        );
        assert!(
            (THIRD_OF_FRAMES_AT..=18.0).contains(&options.speed),
            "the speed is {}, which is outside {THIRD_OF_FRAMES_AT}..=18",
            options.speed
        );
    }

    /// Only cells with ink are written, and none of them carry a background.
    ///
    /// This is the "only write cells that have ink" half of the braille change,
    /// and it is the half that shows up on the wire and on screen.
    ///
    /// A blank braille cell is a space, so painting one costs a byte and erases
    /// whatever the terminal's background is showing there. The wordmark is 60% ink
    /// inside its bounding box, and the 40% that is not is the counters of the
    /// letters and the space around the reflection -- which is exactly the part
    /// that should show the terminal's own background through.
    ///
    /// Measured on the *opening* frame, which is the only one where the claim is
    /// exact: the canvas starts blank, so every cell the draw reports is one it
    /// chose to write, and the count is the number of cells in the grid carrying
    /// at least one raised dot. A later frame also reports the cells the logo has
    /// just *left* -- those are erasures, they have to be reported or the old logo
    /// stays on screen, and they are not the same thing.
    ///
    /// The background half is the one that fails against the old renderer. The
    /// quadrant blocks spend a cell's foreground *and* its background on a
    /// two-tone split, so every edge cell came out as
    /// `Cell::with_bg(glyph, ink, Color::Rgb { 0, 0, 0 }, ..)`: an
    /// `ESC[48;2;0;0;0` per edge cell on the wire, and a hard black rectangle
    /// painted over the un-inked half of every one of them. That is also why the
    /// old logo was invisible on anything but a black terminal, and why
    /// `[global] background` never showed through it.
    #[test]
    fn only_inked_cells_are_written_and_none_of_them_carry_a_background() {
        let mut dvd = Dvd::new(DvdOptions::default(), (80, 24));
        let opening = dvd.get_diff();

        let inked_cells = (0..dvd.grid.height())
            .flat_map(|cell_y| (0..dvd.grid.width()).map(move |cx| (cx, cell_y)))
            .filter(|(cx, cy)| dvd.grid.cell_char(*cx, *cy) != ' ')
            .count();
        let bounding_box = dvd.grid.width() * dvd.grid.height();

        assert_eq!(
            opening.len(),
            inked_cells,
            "the opening frame wrote {} cells but only {inked_cells} of the logo's \
             {bounding_box} have ink, so blank cells are being painted",
            opening.len()
        );
        assert!(
            inked_cells < bounding_box,
            "{inked_cells} of {bounding_box} cells have ink, so this logo is a slab \
             and the test is not measuring what it thinks it is"
        );

        for (_, _, cell) in &opening {
            assert_ne!(cell.symbol, ' ', "a blank cell was written");
            assert_eq!(
                cell.bg,
                style::Color::Reset,
                "wrote {:?} with a background of {:?}; braille is one colour per \
                 cell and the wordmark is a single flat one",
                cell.symbol,
                cell.bg
            );
        }

        // And over a run, nothing ever acquires a background either -- including
        // the erasures, which are the cells a naive implementation would blank with
        // a hard black rather than with the terminal's own background.
        for _ in 0..200 {
            dvd.update();
            for (_, _, cell) in dvd.get_diff() {
                assert_eq!(cell.bg, style::Color::Reset);
            }
        }
    }

    /// What one frame costs on the wire, and what it does *not* scale with.
    ///
    /// This is the measurement `frame_times` reports, run inline so a regression
    /// is caught by `cargo test` rather than only by looking at a table.
    ///
    /// The structural claim is the second one and the one that matters: the cost
    /// is a property of the logo, not of the terminal. A 400x200 screen is
    /// eighty times the area of an 80x24 one and the logo still moves at the same
    /// rate, so the two must cost the same. A draw that walked the whole canvas,
    /// or a renderer that painted every cell in the logo's bounding box, would
    /// show up here as a factor of the terminal size.
    ///
    /// The absolute number is around 650 bytes a frame, and the reason is worth
    /// knowing: a braille cell *is* its bit pattern, so moving the logo one dot
    /// sideways changes every glyph in it and the diff is the whole logo rather
    /// than its leading edge. That is inherent to placing a shape at 8x, and it
    /// buys the dot of resolution that the old 2x2 renderer did not have.
    #[test]
    fn a_frame_costs_the_same_whatever_size_the_terminal_is() {
        fn mean_frame_bytes(size: (u16, u16)) -> (usize, usize) {
            let mut dvd = Dvd::new(DvdOptions::default(), size);
            let opening = {
                let mut out: Vec<u8> = Vec::new();
                crate::common::write_cells(
                    &mut out,
                    size,
                    &dvd.get_diff(),
                    crate::session::SessionColors::default(),
                )
                .expect("writing to a Vec cannot fail");
                out.len()
            };

            let mut total = 0usize;
            for _ in 0..120 {
                dvd.update();
                let mut out: Vec<u8> = Vec::new();
                crate::common::write_cells(
                    &mut out,
                    size,
                    &dvd.get_diff(),
                    crate::session::SessionColors::default(),
                )
                .expect("writing to a Vec cannot fail");
                total += out.len();
            }
            (opening, total / 120)
        }

        let (small_open, small) = mean_frame_bytes((80, 24));
        let (big_open, big) = mean_frame_bytes((400, 200));

        // A ceiling as well, so that a frame which happened to be small at 80x24
        // for the wrong reason would not pass the ratio below.
        assert!(
            small < 1_500 && big < 1_500,
            "a frame costs {small} bytes at 80x24 and {big} at 400x200, which is \
             more than a 210-cell logo moving a dot at a time should"
        );
        assert!(
            big * 10 <= small * 12,
            "a frame costs {small} bytes at 80x24 and {big} at 400x200, so the cost \
             scales with the terminal rather than with the logo"
        );
        assert!(
            small_open < 1_500 && big_open < 1_500,
            "the opening frame costs {small_open} bytes at 80x24 and {big_open} at \
             400x200"
        );
    }

    #[test]
    fn diff_stays_in_bounds() {
        let mut effect = Dvd::new(options(), (10, 4));
        for _ in 0..30 {
            effect.update();
            for (x, y, _) in effect.get_diff() {
                assert!(x < 10 && y < 4);
            }
        }
    }

    /// A configuration whose bounce periods are commensurate, so corners happen
    /// often and a test need not wait a quarter of an hour for one.
    ///
    /// **The corner is a geometric accident, and this leans on that.** A corner is
    /// "both axes reverse on the same frame", which is a measure-zero condition:
    /// the two bounce periods are `2*max_x/vx` and `2*max_y/vy`, and with the
    /// default 30-cell wordmark at 80x24 those are 8.3 and 5.7 seconds, a ratio
    /// of 25:17 whose least common alignment is 142 seconds away -- and float
    /// accumulation means the two walls are then crossed on *adjacent* frames
    /// rather than the same one, which is not a corner.
    ///
    /// Measured over 1,000 seconds of real simulation at the shipped defaults:
    ///
    /// ```text
    /// terminal   x-hits  y-hits  corners
    /// 80x24        240     350       1
    /// 200x50        70     139       0
    /// 400x200       32      31       0
    /// ```
    ///
    /// So the default logo almost never corners, and a test written against it is
    /// a test that measures how long you are willing to wait. This uses a
    /// three-character logo on a large terminal, where `logo_height` is one cell
    /// and the two periods come out *equal* -- 66.3 seconds each, measured -- so
    /// every single bounce is a corner. Deterministic, fast enough to run, and
    /// honest about being a special geometry.
    fn corner_rich() -> Dvd {
        Dvd::new(
            DvdOptions {
                logo: String::from("DVD"),
                start_in_corner: false,
                color_change: ColorChange::Never,
                ..Default::default()
            },
            (400, 200),
        )
    }

    /// A wave is thrown on a corner, and on no other frame.
    ///
    /// The distinction that matters is *both* axes. A single-axis wall hit arrives
    /// every second or two, and a wave there would be a constant effect rather
    /// than an event, which would spend the whole idea.
    ///
    /// The conjunction is checked against an *independent* prediction rather than
    /// against a count, because a count cannot tell "every wall hit throws a wave"
    /// from "corners are rare so the two counts happen to differ". Each axis's
    /// clamp is recomputed here from the position `step` leaves behind, which is
    /// the only thing the wave's rule is allowed to depend on.
    #[test]
    fn a_wave_is_thrown_exactly_when_both_axes_reverse_together() {
        let mut dvd = corner_rich();
        let mut throws = 0u32;
        let mut wall_hits = 0u32;
        let mut disagreements = 0u32;

        for _ in 0..20_000 {
            // Read *before* the step. Reading it after makes `grew` identically
            // false, which is a test that cannot fail and asserts nothing.
            let waves_before = dvd.waves.len();
            dvd.update();

            // The same conjunction, derived independently from the geometry.
            let max_x = (dvd.screen_size.0 as f64 - dvd.logo_width()).max(0.0);
            let max_y = (dvd.screen_size.1 as f64 - dvd.logo_height()).max(0.0);
            let clamped_x = max_x > 0.0 && (dvd.x == 0.0 || dvd.x == max_x);
            let clamped_y = max_y > 0.0 && (dvd.y == 0.0 || dvd.y == max_y);

            let grew = dvd.waves.len() > waves_before;
            // A wave thrown on the frame just stepped is the newest one. Age alone
            // is ambiguous -- it is `DT` old, not zero, because `step` ages after
            // it pushes -- so the flag is the authority and the age a cross-check.
            let youngest = dvd
                .waves
                .iter()
                .map(|wave| wave.age)
                .fold(f64::INFINITY, f64::min);

            if dvd.corner_this_frame {
                throws += 1;
            }
            if clamped_x || clamped_y {
                wall_hits += 1;
            }
            if dvd.corner_this_frame != (clamped_x && clamped_y) {
                disagreements += 1;
            }
            // Whatever the flag says, a throw must have added a wave and nothing
            // else may have.
            if dvd.corner_this_frame != grew {
                disagreements += 1;
            }
            if grew {
                assert!(
                    youngest <= DT * 1.5,
                    "a new wave is {youngest}s old on the frame it was thrown, so \
                     it was not zero-age when pushed"
                );
            }
        }

        assert_eq!(
            disagreements, 0,
            "{disagreements} frames where the stored corner flag and the geometry \
             disagreed, or where a flag without a wave"
        );
        assert!(
            throws > 5,
            "only {throws} corners in 20,000 frames, so this configuration is not \
             corner-rich and the rule above was never exercised"
        );
        // The fixture's own premise, asserted because everything above depends
        // on it: in this geometry every wall hit *is* a corner, so the two counts
        // must agree. If this stops holding, the two periods are no longer
        // commensurate and this test has quietly stopped testing the conjunction
        // -- it would be measuring a rare event again.
        assert_eq!(
            wall_hits, throws,
            "this fixture was chosen because its two bounce periods are equal, so \
             every one of its {wall_hits} wall hits should have been a corner"
        );
    }

    /// A single-axis wall hit throws no wave, which is the half of the rule the
    /// corner-rich fixture cannot see.
    ///
    /// A wall hit arrives every second or two and a corner arrives about once a
    /// quarter of an hour, so in this configuration the two counts differ by two
    /// orders of magnitude. That is the whole claim: a wave marks the *rare* event
    /// and not the common one, and a version keyed to `hit_x || hit_y` would pass
    /// the corner test above and fail this one.
    #[test]
    fn a_single_axis_wall_hit_throws_no_wave() {
        let mut dvd = Dvd::new(
            DvdOptions {
                color_change: ColorChange::Never,
                ..Default::default()
            },
            (80, 24),
        );

        let mut wall_hits = 0u32;
        let mut throws = 0u32;
        for _ in 0..20_000 {
            let before = dvd.wall_hits;
            dvd.update();
            if dvd.wall_hits != before {
                wall_hits += 1;
            }
            if dvd.corner_this_frame {
                throws += 1;
            }
        }

        assert!(
            wall_hits > 100,
            "only {wall_hits} wall hits in 20,000 frames, so the fixture is not \
             exercising the single-axis case"
        );
        assert!(
            throws * 20 < wall_hits,
            "{wall_hits} wall hits produced {throws} waves, so the wave is keyed to \
             a wall rather than to a corner"
        );
    }

    /// A corner is reachable in the shipped default configuration, given a seed
    /// that reaches one.
    ///
    /// Four pinned seeds rather than one, because the corner is rare enough that
    /// whether a *particular* run reaches one is a property of where that logo
    /// happened to start -- and `DEFAULT_SEED` means unset, so an unpinned effect
    /// draws a fresh one at every construction and a test against it is a test of
    /// the clock. See `corner_rich` for the measurement of how rare this is.
    #[test]
    fn a_corner_is_reachable_at_the_shipped_defaults() {
        let mut reached = 0;
        for seed in [1u64, 2, 3, 4] {
            let mut dvd = Dvd::new(
                DvdOptions {
                    color_change: ColorChange::Never,
                    seed,
                    ..Default::default()
                },
                (80, 24),
            );
            for _ in 0..60_000 {
                dvd.update();
                if dvd.corner_this_frame {
                    reached += 1;
                    break;
                }
            }
        }
        assert_eq!(
            reached, 4,
            "only {reached} of four seeded runs at 80x24 with the default wordmark \
             reached a corner in 1,000 seconds, so the wave is unreachable in the \
             shipped configuration"
        );
    }

    /// The wave's ring is a ring, at the radius the clock says it should be.
    ///
    /// A circle is a shape, and a shape cannot be checked by counting cells or
    /// checking that *something* was drawn -- a filled disc and a ring share a
    /// centre and mean opposite things. So this measures the distribution of the
    /// drawn cells' distances from the corner and asks whether the band is
    /// populated and whether anything outside it is.
    ///
    /// The tolerance is the cell diagonal, and it is not slack. `stamp_ring`
    /// samples a point at exactly radius `r` in continuous space and then rounds
    /// it to a cell, so a cell it writes can sit half a cell away in each axis
    /// from the circle -- `sqrt(0.5^2 + 0.5^2)`, about 0.71 cells. Measuring
    /// without that term fails against a *correct* ring, which is the more
    /// expensive mistake: it invites widening the renderer to satisfy a test.
    #[test]
    fn the_wave_draws_a_ring_at_the_radius_its_age_implies() {
        let (cx, cy) = (20.0, 12.0);
        let age = 0.5;
        let mut dvd = Dvd::new(options(), (80, 24));
        // Injected rather than driven: this is a test of `stamp_ring`'s geometry,
        // and reaching a real corner takes ~95 seconds of simulation. The wave
        // list is private state, so a test setting it directly is legitimate.
        dvd.waves.push(CornerWave { cx, cy, age });

        let diff = dvd.get_diff();
        let ring: Vec<f64> = diff
            .iter()
            .filter(|(_, _, cell)| cell.symbol == WAVE_GLYPH)
            .map(|(x, y, _)| (*x as f64 - cx).hypot(*y as f64 - cy))
            .collect();

        assert!(
            ring.len() > 40,
            "the ring drew only {} cells, which is not a ring",
            ring.len()
        );

        let radius = WAVE_SPEED * age;
        // Half the drawn band, plus the rounding.
        let tolerance = WAVE_HALF_WIDTH + 0.5 * std::f64::consts::SQRT_2;
        let inside = ring.iter().filter(|d| **d < radius - tolerance).count();
        let outside = ring.iter().filter(|d| **d > radius + tolerance).count();
        let in_band = ring.len() - inside - outside;

        assert!(
            in_band > 20,
            "only {in_band} of {} cells are within the band around r = {radius}",
            ring.len()
        );
        assert_eq!(
            inside + outside,
            0,
            "{inside} cells are inside the band and {outside} are outside it, so \
             this is a filled disc and not a ring"
        );
    }

    /// The ring is dimmer than the logo it came from.
    ///
    /// A wave in the logo's exact colour would be a second logo, and the eye
    /// would read the two as one object rather than as an event happening near
    /// one. The comparison is against the logo's own ink at the same moment, not
    /// against a constant, because the palette's brightest entries are close to
    /// white and a fixed bar would pass for a dark colour and fail for a bright
    /// one.
    #[test]
    fn the_wave_is_dimmer_than_the_logo() {
        let mut dvd = Dvd::new(options(), (80, 24));
        dvd.waves.push(CornerWave {
            cx: 0.0,
            cy: 0.0,
            age: 0.2,
        });
        let diff = dvd.get_diff();

        let logo = PALETTE[dvd.color_index % PALETTE.len()];
        let (lr, lg, lb) = (logo.0 as f64, logo.1 as f64, logo.2 as f64);
        let logo_luma = 0.2126 * lr + 0.7152 * lg + 0.0722 * lb;

        let mut wave_seen = false;
        for (_, _, cell) in &diff {
            if cell.symbol != WAVE_GLYPH {
                continue;
            }
            let style::Color::Rgb { r, g, b } = cell.color else {
                panic!("a wave cell is not truecolor: {:?}", cell.color);
            };
            wave_seen = true;
            let luma = 0.2126 * r as f64 + 0.7152 * g as f64 + 0.0722 * b as f64;
            assert!(
                luma < logo_luma,
                "a wave cell is at luma {luma:.1} against the logo's {logo_luma:.1}, \
                 so the wave is not dimmer than the logo"
            );
        }
        assert!(wave_seen, "the fixture drew no wave cells at all");
    }

    /// Turning the option off draws no wave, under every colour mode.
    ///
    /// `Never` is the interesting mode: the colour never changes, so a test that
    /// only used the default would not notice whether the wave is really
    /// independent of the colour rule or quietly hanging off it.
    #[test]
    fn the_wave_can_be_turned_off_without_touching_the_colour_rule() {
        for mode in ColorChange::ALL {
            let mut dvd = Dvd::new(
                DvdOptions {
                    color_change: *mode,
                    corner_wave: false,
                    ..options()
                },
                (80, 24),
            );
            for _ in 0..2_000 {
                dvd.update();
                let diff = dvd.get_diff();
                assert!(
                    !diff.iter().any(|(_, _, c)| c.symbol == WAVE_GLYPH),
                    "{mode:?} drew a wave with corner_wave off"
                );
            }
        }
    }

    /// A wave costs a ring, not a screen.
    ///
    /// The renderer walks the ring parametrically precisely so that its cost is
    /// the circumference rather than the bounding box, and this is the assertion
    /// that keeps it that way. The bounding-box version would draw a few hundred
    /// more cells here and would still *look* right, which is the dangerous
    /// failure: it is a performance regression with no visual symptom, found
    /// only by this test or by a frame table.
    ///
    /// Measured against the ring's own area at the same radius, so the bound is a
    /// property of the geometry rather than a number tuned to one terminal.
    #[test]
    fn a_wave_writes_a_ring_and_not_its_bounding_box() {
        let radius = 60.0;
        let mut dvd = Dvd::new(options(), (400, 200));
        // Age chosen so the ring's radius is `radius`, and pushed to the middle
        // of the screen so the whole ring is on it.
        dvd.waves.push(CornerWave {
            cx: 200.0,
            cy: 100.0,
            age: radius / WAVE_SPEED,
        });

        let written = dvd
            .get_diff()
            .iter()
            .filter(|(_, _, c)| c.symbol == WAVE_GLYPH)
            .count();
        let band_area = 2.0 * WAVE_HALF_WIDTH * std::f64::consts::TAU * radius;
        assert!(
            written as f64 >= band_area * 0.6,
            "the ring drew {written} cells, fewer than the {band_area:.0} its own \
             area implies, so it has gaps in it"
        );
        assert!(
            (written as f64) < band_area * 3.0,
            "the ring drew {written} cells against a {band_area:.0}-cell band, so \
             it is filling far more than its own width"
        );
        // And the absolute number, which is what would actually hurt: the whole
        // 400x200 screen is 80,000 cells.
        assert!(
            written < 4_000,
            "one wave wrote {written} cells on an 80,000-cell screen"
        );
    }

    /// A wave expires, and leaves nothing behind when it does.
    ///
    /// `Canvas::commit` diffs, so a wave that stops being drawn *does* erase
    /// itself -- but only because `draw` clears the canvas every frame. If the
    /// clear ever stops, or a wave is dropped from the list without being aged
    /// out, the ring would freeze on screen. So this checks the erasures are
    /// actually emitted.
    #[test]
    fn an_expired_wave_is_erased_rather_than_left_on_screen() {
        let mut dvd = Dvd::new(options(), (80, 24));
        dvd.waves.push(CornerWave {
            cx: 40.0,
            cy: 12.0,
            age: 0.1,
        });
        let during = dvd.get_diff();
        assert!(
            during.iter().any(|(_, _, c)| c.symbol == WAVE_GLYPH),
            "the fixture drew no ring"
        );

        // Age past its life. In steps rather than one big delta, because `step`
        // clamps the frame delta to 0.1s -- so a single call with a huge delta
        // would advance the wave by 0.1s and nothing else. That clamp is why a
        // wave cannot be skipped forward by a stall, and it is worth knowing
        // rather than rediscovering.
        let context = crate::runtime::FrameContext::new(
            dvd.screen_size,
            0,
            std::time::Duration::ZERO,
            std::time::Duration::from_secs_f64(0.1),
            crate::runtime::InputState::default(),
        );
        for _ in 0..(WAVE_LIFE as usize * 10 + 4) {
            dvd.update_with_context(&context);
        }
        assert!(
            dvd.waves.is_empty(),
            "a wave {}s old is still alive with a life of {WAVE_LIFE}s",
            dvd.waves.first().map_or(0.0, |w| w.age)
        );

        let after = dvd.get_diff();
        assert!(
            after.iter().all(|(_, _, c)| c.symbol != WAVE_GLYPH),
            "a wave cell survived its own removal"
        );
    }
}