pinch-points 0.9.0

A fast, kid-friendly crab-routing game: route streams of crabs into your sandcastle before time runs out
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
//! Render-side particles and floating score text: the game's moments made
//! visible. Everything here is cosmetic: spawned from *observed* sim state,
//! driven by frame time, and drawing on its own PRNG so the deterministic
//! sim stream is never touched.

use crate::app::art::Art;
use crate::app::layout::{self, TILE};
use crate::app::materials::PRINT;
use crate::app::palette;
use crate::app::sim_events::{BoardMemory, CurrentBoard, SimEvent};
use crate::sim::TileKind;
use bevy::color::Mix;
use bevy::prelude::*;

/// Which claw a crab put down last. A print is offset to one side of the
/// stride and the sides alternate.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Foot {
    Left,
    Right,
}

impl Foot {
    fn other(self) -> Foot {
        match self {
            Foot::Left => Foot::Right,
            Foot::Right => Foot::Left,
        }
    }

    /// How far to the side of the stride the print lands, signed.
    fn side(self) -> f32 {
        match self {
            Foot::Left => 5.0,
            Foot::Right => -5.0,
        }
    }
}

/// Where a crab last left a print, and with which foot.
#[derive(Clone, Copy, Debug)]
pub struct Footfall {
    last: Vec2,
    foot: Foot,
}

/// What putting a flourish on screen takes: somewhere to spawn it, the
/// art, the dice it is thrown with, and the settings that say whether the
/// player asked for less motion. Every system that decorates the beach
/// reads these four together.
#[derive(bevy::ecs::system::SystemParam)]
pub struct Fx<'w, 's> {
    pub commands: Commands<'w, 's>,
    pub art: Res<'w, Art>,
    pub rng: ResMut<'w, VisualRng>,
    pub settings: Res<'w, crate::app::settings::GameSettings>,
}

/// Smoothstep: 0 below 0, 1 above 1, and an S between that leaves and
/// arrives at rest. The easing every flourish on the beach starts and
/// stops by.
pub fn smoothstep(t: f32) -> f32 {
    let t = t.clamp(0.0, 1.0);
    t * t * (3.0 - 2.0 * t)
}

/// A cheap LCG for visual variety only. Never seed gameplay from this.
#[derive(Resource)]
pub struct VisualRng(u32);

impl Default for VisualRng {
    fn default() -> Self {
        VisualRng(0x9E37_79B9)
    }
}

impl VisualRng {
    /// Seeded from the wall clock, for variety that should differ from one
    /// launch to the next rather than open the same way every time.
    pub(crate) fn from_clock() -> Self {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |since| since.subsec_nanos() ^ since.as_secs() as u32);
        VisualRng(nanos | 1)
    }

    /// A fixed seed: the same draws every run, for tests and for scenery
    /// that should look the same every time its board is played.
    pub(crate) fn seeded(seed: u32) -> Self {
        VisualRng(seed)
    }

    pub(crate) fn next(&mut self) -> u32 {
        self.0 = self.0.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
        self.0
    }

    /// Uniform-ish float in `lo..hi`.
    pub(crate) fn range(&mut self, lo: f32, hi: f32) -> f32 {
        lo + (self.next() >> 8) as f32 / 16_777_216.0 * (hi - lo)
    }
}

/// How hard the camera is being shaken, 0 (still) to 1 (a raid).
///
/// A single pool rather than a queue of shakes: two events landing together
/// should not add up to a camera that leaves the window, and the square in
/// [`Trauma::offset`] is what makes a small knock read as a tap and a big
/// one as a blow. Written by the moment systems, read once a frame by
/// `boot::shake_camera` after the fit has placed the camera.
#[derive(Resource, Default)]
pub struct Trauma(f32);

impl Trauma {
    /// Ceiling on the pool: past this the shake stops growing, so a pile-up
    /// of raids in one frame is loud, not unwatchable.
    const MAX: f32 = 1.0;
    /// How much of the pool drains per second.
    const DECAY: f32 = 1.9;
    /// The worst displacement, in screen pixels, at full trauma.
    const THROW: f32 = 7.0;

    /// A knock. Clamped, so the pool cannot be filled past [`Trauma::MAX`].
    pub fn add(&mut self, amount: f32) {
        self.0 = (self.0 + amount).min(Self::MAX);
    }

    /// Drain the pool and answer where the camera should sit this frame,
    /// in screen pixels off its resting place.
    ///
    /// Two incommensurate sines per axis rather than a fresh random offset
    /// each frame: random jitter strobes at high frame rates and reads as a
    /// broken sprite, where this reads as a camera being shoved.
    pub fn offset(&mut self, dt: f32, elapsed: f32) -> Vec2 {
        self.0 = (self.0 - dt * Self::DECAY).max(0.0);
        if self.0 <= 0.0 {
            return Vec2::ZERO;
        }
        let throw = Self::THROW * self.0 * self.0;
        Vec2::new(
            (elapsed * 37.0).sin() * (elapsed * 17.0).cos(),
            (elapsed * 29.0).sin() * (elapsed * 23.0).cos(),
        ) * throw
    }
}

/// A short-lived drifting sprite (or floating text, when spawned with one).
#[derive(Component)]
pub struct Particle {
    velocity: Vec2,
    /// Pixels per second squared. What makes a kicked grain of sand fall
    /// back to the beach instead of sailing off the board.
    gravity: Vec2,
    /// Fraction of speed shed per second; 0.0 coasts for ever.
    drag: f32,
    /// Radians per second.
    spin: f32,
    /// Scale multiplier per second (1.0 = constant size).
    grow: f32,
    /// The scale it is drawn at before growing. 1.0 for everything but
    /// text, which is rasterized larger than it is shown (see
    /// [`score_pip`]).
    size: f32,
    /// A colour to drift to over life, and the one drifted from. `None`
    /// keeps the spawn colour and moves only its alpha.
    ramp: Option<(Color, Color)>,
    /// Fraction of life spent fading in. Nothing should arrive at full
    /// strength on the frame it is born: at 60 fps that is a pop.
    fade_in: f32,
    /// The alpha this was spawned at, read out of the sprite on the first
    /// frame and kept.
    ///
    /// It is the ceiling: a piece asked for at 60% never draws stronger
    /// than 60%, so a caller that wants full strength asks for 1.0. See
    /// [`Particle::shade`] for why it is read once and kept.
    peak: Option<f32>,
    /// The height it comes to rest at, falling: a grain of sand off a
    /// castle lies on the beach at the castle's foot rather than falling
    /// through it. `None` falls for ever.
    floor: Option<f32>,
    /// Fraction of life held at full strength before the fade begins, for
    /// a piece that lies a moment before it goes. Zero fades all the way.
    hold: f32,
    age: f32,
    life: f32,
}

impl Default for Particle {
    fn default() -> Self {
        Particle {
            velocity: Vec2::ZERO,
            gravity: Vec2::ZERO,
            drag: 0.0,
            spin: 0.0,
            grow: 0.0,
            size: 1.0,
            ramp: None,
            fade_in: 0.09,
            peak: None,
            floor: None,
            hold: 0.0,
            age: 0.0,
            life: 0.5,
        }
    }
}

impl Particle {
    /// Strength at the current age: up over the fade-in, then down to
    /// nothing at the end of life. With `fade_in` at zero this is the
    /// straight `1 - age/life` ramp it has always been.
    fn strength(&self) -> f32 {
        let rise = self.fade_in * self.life;
        let held = self.hold * self.life;
        if held > 0.0 {
            return match self.age < held {
                true => 1.0,
                false => 1.0 - (self.age - held) / (self.life - held).max(f32::EPSILON),
            };
        }
        if self.age < rise {
            self.age / rise.max(f32::EPSILON)
        } else {
            1.0 - (self.age - rise) / (self.life - rise).max(f32::EPSILON)
        }
    }

    /// How far through life, 0..1: where a colour ramp is read.
    fn progress(&self) -> f32 {
        (self.age / self.life.max(f32::EPSILON)).clamp(0.0, 1.0)
    }

    /// The colour to write this frame, given whatever the sprite is
    /// holding.
    ///
    /// The peak is taken out of the sprite exactly once and kept, which is
    /// the whole point of this existing. The alpha written back is already
    /// a fraction of the peak, so reading it out again next frame is a
    /// fraction of a fraction: the fade compounds, and every particle goes
    /// out several times faster than its life says, while each frame on
    /// its own looks right.
    fn shade(&mut self, current: Color) -> Color {
        let peak = *self.peak.get_or_insert(current.alpha());
        let progress = self.progress();
        let base = self
            .ramp
            .map_or(current, |(from, to)| from.mix(&to, progress));
        base.with_alpha(peak * self.strength())
    }
}

/// Sand as it leaves the ground, and as it looks by the time it lands.
/// A grain thrown up off dry sand comes down on damp, and a burst that
/// held one colour all the way through read as a puff of smoke.
const SAND_DRY: Color = Color::srgba(0.9, 0.82, 0.62, 0.75);
const SAND_DAMP: Color = Color::srgba(0.62, 0.55, 0.40, 0.75);

/// A gull's feather, and the grey of the wing it came out of.
const FEATHER_LIT: Color = Color::srgba(1.0, 1.0, 1.0, 0.95);
const FEATHER_GREY: Color = Color::srgba(0.72, 0.76, 0.82, 0.95);

/// A scatter of pieces thrown out of one point: what a bank, a raid, a
/// spawn and a gull's meal all look like, differing only in these.
///
/// A struct rather than eight positional arguments, six of them floats.
pub struct Burst {
    pub image: Handle<Image>,
    pub pos: Vec2,
    pub color: Color,
    pub count: usize,
    pub size: f32,
    /// Pixels per second, scattered outward; each piece draws between 40%
    /// and 100% of it.
    pub speed: f32,
    /// Downward pull. Sand and feathers fall back; spray and foam do not.
    pub gravity: f32,
}

/// Throw a [`Burst`] of pieces.
pub fn burst(commands: &mut Commands, rng: &mut VisualRng, spec: &Burst) {
    for _ in 0..spec.count {
        let angle = rng.range(0.0, std::f32::consts::TAU);
        let velocity = Vec2::from_angle(angle) * rng.range(spec.speed * 0.4, spec.speed);
        commands.spawn((
            Particle {
                velocity,
                gravity: Vec2::new(0.0, -spec.gravity),
                drag: 1.1,
                spin: rng.range(-4.0, 4.0),
                grow: rng.range(0.2, 0.7),
                life: rng.range(0.35, 0.6),
                ..default()
            },
            layout::image_sprite(
                &spec.image,
                spec.color,
                Vec2::splat(spec.size * rng.range(0.7, 1.3)),
            ),
            Transform::from_translation(spec.pos.extend(layout::z::PARTICLE)),
        ));
    }
}

/// A handful of grains knocked off a raided castle (see [`crumbs`]).
#[derive(Clone, Copy)]
pub(crate) struct Crumbs {
    /// Where they fall from: the keep's rim, over its middle.
    pub rim: Vec2,
    /// The height of the castle's foot, where they come to rest.
    pub foot: f32,
    /// The castle's own sand, which they are a little darker than.
    pub body: Color,
    pub count: usize,
    /// Seconds from falling to gone.
    pub life: f32,
}

/// Grains of sand knocked off a raided castle's rim: they drop from it,
/// scattered a little either side and tossed up, fall to the castle's
/// foot, lie there a moment and sink away, each a piece of the castle's
/// own sand.
pub(crate) fn crumbs(commands: &mut Commands, rng: &mut VisualRng, art: &Art, spec: &Crumbs) {
    let Crumbs {
        rim,
        foot,
        body,
        count,
        life,
    } = *spec;
    let body = body.to_srgba();
    for _ in 0..count {
        let side = if rng.range(0.0, 1.0) < 0.5 { -1.0 } else { 1.0 };
        let from = rim + Vec2::new(side * rng.range(4.3, 13.9), -rng.range(0.0, 5.3));
        let dark = rng.range(0.70, 0.86);
        commands.spawn((
            Particle {
                velocity: Vec2::new(side * rng.range(10.7, 32.0), rng.range(10.7, 37.3)),
                gravity: Vec2::new(0.0, -363.0),
                spin: rng.range(-3.0, 3.0),
                fade_in: 0.0,
                floor: Some(foot + rng.range(-8.5, 3.2)),
                hold: 0.55,
                life,
                ..default()
            },
            layout::image_sprite(
                &art.puff,
                Color::srgb(body.red * dark, body.green * dark, body.blue * dark),
                Vec2::splat(rng.range(4.5, 6.6)),
            ),
            // On the castle's tile, in front of it, under whatever walks
            // past.
            Transform::from_translation(from.extend(layout::z::TILE_FEATURE + 0.7)),
        ));
    }
}

/// What a gull leaves of a crab: feathers, lit as they fly and the grey of
/// the wing they came out of by the time they land.
///
/// The one place a burst's pieces change colour on the way, and what
/// [`Particle::ramp`] is for.
fn feathers(commands: &mut Commands, rng: &mut VisualRng, art: &Art, pos: Vec2) {
    for _ in 0..5 {
        let angle = rng.range(0.0, std::f32::consts::TAU);
        commands.spawn((
            Particle {
                velocity: Vec2::from_angle(angle) * rng.range(18.0, 46.0),
                gravity: Vec2::new(0.0, -90.0),
                drag: 1.6,
                spin: rng.range(-5.0, 5.0),
                ramp: Some((FEATHER_LIT, FEATHER_GREY)),
                life: rng.range(0.45, 0.8),
                ..default()
            },
            layout::image_sprite(
                &art.feather,
                FEATHER_LIT,
                Vec2::splat(rng.range(11.0, 18.0)),
            ),
            Transform::from_translation(pos.extend(layout::z::PARTICLE)),
        ));
    }
}

/// A gull a castle turned away, beating off the beach the way it faces
/// from the keep: a pale knock on the wall, and the bird climbing out,
/// swelling as it rises toward the camera and fading as it goes.
///
/// `calm` keeps the bird and drops the flight. It still fades where it
/// stood, which is the news: vanishing on the spot is what a raid does.
fn shooed(commands: &mut Commands, art: &Art, pos: Vec2, castle: Vec2, calm: bool) {
    let away = (pos - castle).try_normalize().unwrap_or(Vec2::Y);
    // Up the screen as well as out, so a bird leaving downward still
    // reads as taking off rather than as walking on.
    let heading = (away + Vec2::Y * 0.6).normalize();
    if !calm {
        ring(
            commands,
            art,
            castle,
            Color::srgba(0.95, 0.97, 1.0, 0.55),
            TILE * 0.55,
            2.0,
            0.3,
        );
    }
    flying_away(commands, art, pos, heading, calm);
}

/// A gull in the air leaving the beach from `pos` along `heading`, or,
/// with reduced motion, fading where it stood.
fn flying_away(commands: &mut Commands, art: &Art, pos: Vec2, heading: Vec2, calm: bool) {
    commands.spawn((
        Particle {
            velocity: if calm { Vec2::ZERO } else { heading * 150.0 },
            grow: if calm { 0.0 } else { 0.6 },
            fade_in: 0.0,
            life: 0.75,
            ..default()
        },
        layout::image_sprite(&art.gull_fly, Color::WHITE, Vec2::splat(TILE * 0.78)),
        Transform::from_translation(pos.extend(layout::z::PARTICLE))
            .with_rotation(Quat::from_rotation_z(heading.to_angle())),
    ));
}

/// A shockwave out of one tile: a bright circle swelling and thinning.
///
/// The shape every "something happened *here*" gets, so a tier-up, a post
/// going in and a gull touching down read as one kind of news at different
/// volumes.
pub fn ring(
    commands: &mut Commands,
    art: &Art,
    pos: Vec2,
    color: Color,
    size: f32,
    grow: f32,
    life: f32,
) {
    commands.spawn((
        Particle {
            grow,
            life,
            fade_in: 0.0,
            ..default()
        },
        Sprite {
            image: art.ring.clone(),
            color,
            custom_size: Some(Vec2::splat(size)),
            ..default()
        },
        Transform::from_translation(pos.extend(layout::z::PARTICLE)),
    ));
}

/// A single glint star that twinkles out in place.
pub fn glint(commands: &mut Commands, rng: &mut VisualRng, art: &Art, pos: Vec2, color: Color) {
    let offset = Vec2::new(rng.range(-14.0, 14.0), rng.range(-14.0, 14.0));
    commands.spawn((
        Particle {
            velocity: Vec2::new(0.0, rng.range(4.0, 10.0)),
            spin: rng.range(1.0, 3.0),
            grow: -0.8,
            life: rng.range(0.4, 0.7),
            ..default()
        },
        Sprite {
            image: art.star.clone(),
            color,
            custom_size: Some(Vec2::splat(rng.range(8.0, 15.0))),
            ..default()
        },
        Transform::from_translation((pos + offset).extend(layout::z::PARTICLE)),
    ));
}

/// Two sparks shed behind something worth following.
///
/// `back` points away from where it is going, so the ribbon lies along the
/// path it came by rather than scattering round it: at a glance the trail
/// is a heading, not a halo.
pub fn spark_trail(commands: &mut Commands, rng: &mut VisualRng, art: &Art, pos: Vec2, back: Vec2) {
    for _ in 0..2 {
        let spread = back.perp() * rng.range(-7.0, 7.0);
        commands.spawn((
            Particle {
                velocity: back * rng.range(10.0, 26.0),
                drag: 2.4,
                spin: rng.range(-5.0, 5.0),
                grow: -0.9,
                life: rng.range(0.35, 0.6),
                ..default()
            },
            layout::image_sprite(
                &art.star,
                Color::srgba(1.0, 0.92, 0.45, 0.9),
                Vec2::splat(rng.range(6.0, 11.0)),
            ),
            Transform::from_translation((pos + spread).extend(layout::z::PARTICLE)),
        ));
    }
}

/// Floating score text ("+3", "-12") rising from a board position.
///
/// Text on the board is rasterized at its font size in screen pixels and
/// then magnified with the board, so a pip on a zoomed-in beach came out a
/// blur. It is drawn [`layout::MAX_ZOOM`] times larger and shown at that
/// fraction of the scale: sharp at the closest the camera ever gets, and
/// merely downsampled at every other zoom.
pub fn score_pip(commands: &mut Commands, text: String, pos: Vec2, color: Color) {
    let oversample = layout::MAX_ZOOM;
    commands.spawn((
        Particle {
            velocity: Vec2::new(0.0, 46.0),
            // Thrown up and slowing: the number arrives, hangs, and is
            // gone, rather than sliding at one speed off the top.
            gravity: Vec2::new(0.0, -34.0),
            life: 1.2,
            fade_in: 0.0,
            size: 1.0 / oversample,
            ..default()
        },
        Text2d::new(text),
        crate::app::menu_ui::display_font(22.0 * oversample),
        TextColor(color),
        Transform::from_translation(pos.extend(layout::z::PIP))
            .with_scale(Vec3::splat(1.0 / oversample)),
    ));
}

/// Confetti for the winner: tinted stars raining over the board.
pub fn confetti(commands: &mut Commands, rng: &mut VisualRng, art: &Art, color: Color) {
    for _ in 0..46 {
        let x = rng.range(-6.5 * TILE, 6.5 * TILE);
        let y = rng.range(3.0 * TILE, 6.5 * TILE);
        commands.spawn((
            Particle {
                velocity: Vec2::new(rng.range(-18.0, 18.0), rng.range(-90.0, -40.0)),
                // Falling under its own weight against a little air, so
                // the pieces spread as they come down rather than dropping
                // on parallel rails.
                gravity: Vec2::new(0.0, -55.0),
                drag: 0.55,
                spin: rng.range(-6.0, 6.0),
                life: rng.range(1.6, 3.0),
                ..default()
            },
            layout::image_sprite(
                &art.star,
                color.lighter(rng.range(0.0, 0.2)),
                Vec2::splat(rng.range(8.0, 16.0)),
            ),
            Transform::from_translation(Vec3::new(x, y, layout::z::CONFETTI)),
        ));
    }
}

/// A crab on its last quarter-second: the sim has stopped counting it, and
/// the render layer walks it the rest of the way into the keep.
///
/// The bank is the game's most-repeated reward, so the crab is seen to
/// arrive rather than disappearing under a puff.
#[derive(Component)]
pub struct Hop {
    from: Vec2,
    to: Vec2,
    /// Seconds since it set off; below zero while it waits its turn.
    age: f32,
    /// Its shell colour, which a crab waiting to be swept glows away from.
    shell: Color,
    /// Which way it goes home, which sets how long it is in the air and
    /// the arc it flies.
    path: HopPath,
    /// Whether it pumps its claws on the doorstep before it hops in (see
    /// [`Homeward::Cheer`]): its age starts [`CHEER`] below zero.
    cheer: bool,
    /// Which side its big claw is on, which way the pump swings it.
    handed: crate::sim::Handedness,
    /// Whether its keep bounces when it lands: a crab that cost its owner
    /// points (a left claw under Right Claws) lands without a celebration.
    kicks: bool,
}

/// One of a hopping crab's claws, its body's child: the big one it always
/// has, or the small one it raises only while it cheers.
#[derive(Component)]
pub struct HopClaw {
    big: bool,
}

/// How a banked crab goes into its keep.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Homeward {
    /// Walked to the door and the first to bank there: it pumps both claws
    /// twice, bracing, before the hop.
    Cheer,
    /// Banked for nothing, or flown home by the tide and already at the
    /// gate: straight over the wall.
    Hop,
    /// Walked to the door behind one still waiting there to go in: it waits
    /// this many seconds on the doorstep, then goes straight over the wall,
    /// landing after the crab ahead of it. The sim has scored it already,
    /// so it does not cheer, and a castle bounces as each crab lands in it,
    /// so it must not land first.
    Behind(f32),
    /// Thrown home from across the beach by the tide, setting off this many
    /// slots after the first of its sweep.
    Swept(usize),
}

/// How long a crab cheers on the doorstep, and how many times it pumps
/// its claws in that time. Short, and the score pip is already up: the
/// cheer is the crab's, not the news.
const CHEER: f32 = 0.45;
const CHEER_PUMPS: f32 = 2.0;

/// How far a cheering crab's big claw swings out, in radians, how much it
/// grows, how far it pushes forward (world units), and how much the body
/// braces under it, all at the top of a pump.
const CHEER_SWING: f32 = 24.0 * std::f32::consts::PI / 180.0;
const CHEER_CLAW_GROW: f32 = 0.28;
const CHEER_PUSH: f32 = 3.2;
const CHEER_BRACE: f32 = 0.05;

/// Where a crab's claw roots on its body, as a fraction of its sprite's
/// side: forward and to the claw's side (the art's shoulder). The pump
/// swings and scales the claw about this point, so it stays on the crab.
const CLAW_ROOT: Vec2 = Vec2::new(0.22, 0.24);

/// How hard a cheering crab is pumping `cheered` seconds into its cheer:
/// 0 at rest, 1 at the top of a pump, [`CHEER_PUMPS`] humps over
/// [`CHEER`], each sharpened so the claws snap up and hang a moment.
fn pump(cheered: f32) -> f32 {
    if !(0.0..CHEER).contains(&cheered) {
        return 0.0;
    }
    let u = cheered / CHEER;
    (u * CHEER_PUMPS * std::f32::consts::PI)
        .sin()
        .abs()
        .powf(0.7)
}

/// Where a hopping crab's claw sits on its body at `pump`: swung out about
/// its root, grown and pushed forward, in the body's own frame (x along
/// its heading). `big` is the hand's claw; the small one is the other side
/// at 0.62 of the size, swinging the other way. `mirror` is a left hand.
fn claw_pose(side: f32, big: bool, mirror: bool, pump: f32) -> Transform {
    // Which side of the body it is on: the big claw is on the crab's
    // right (y down in its frame) unless it is mirrored, the small one on
    // the other side. Each swings out away from the body.
    let across = if big != mirror { -1.0 } else { 1.0 };
    let root = Vec2::new(CLAW_ROOT.x, CLAW_ROOT.y * across) * side;
    let swing = CHEER_SWING * pump * across;
    let (grow, push) = if big {
        (1.0 + CHEER_CLAW_GROW * pump, CHEER_PUSH * pump)
    } else {
        (0.62 * (1.0 + 0.25 * pump), CHEER_PUSH * 0.8 * pump)
    };
    let turn = Quat::from_rotation_z(swing);
    let held = root + (turn * (-root * grow).extend(0.0)).truncate() + Vec2::new(push, 0.0);
    Transform::from_translation(held.extend(CLAW_LIFT))
        .with_rotation(turn)
        .with_scale(Vec3::splat(grow))
}

/// How far over its body a hopping crab's claws are drawn, as
/// `creatures::crab_claw` lifts a walking crab's.
const CLAW_LIFT: f32 = 0.01;

/// How a banked crab gets into its keep.
#[derive(Clone, Copy, PartialEq, Debug)]
enum HopPath {
    /// Walked there: a short hop over the wall, off at once.
    OverWall,
    /// The tide threw it home from across the beach, on [`sweep_arc`].
    /// `waiting` is how long it has waited for the board to be clear,
    /// while it is still on the sand; it kicks up the sand it stood on
    /// when it goes, and then it is `None`.
    Swept { waiting: Option<f32> },
}

impl HopPath {
    /// Seconds in the air.
    fn span(self) -> f32 {
        match self {
            HopPath::OverWall => HOP,
            HopPath::Swept { .. } => SWEEP_HOP,
        }
    }
}

/// How long a crab is in the air on its way into the keep. Short: the
/// score has already moved, and a slow hop would read as lag.
const HOP: f32 = 0.19;

/// How high a crab hopping over the wall rises, in world units.
const HOP_LIFT: f32 = 12.0;

/// Where a crab waiting to be swept home is drawn: over the crabs round it,
/// since it is the one the banner is talking about.
pub(crate) const SWEEP_WAIT_Z: f32 = layout::z::CREATURE + 0.3;

/// Where a crab the tide throws home is, `progress` of the way from where
/// it stood to the keep, and how big it looks.
///
/// One arc for both ways a sweep is drawn: flown by the sim under
/// `sweep_flight` ([`crate::app::creatures::draw_sweeps`]) and hopped by
/// the render layer on an older board ([`bank_hop`]). Each kept its own
/// copy once, and the older one rose without limit and flew under the
/// fences.
pub(crate) fn sweep_arc(from: Vec2, to: Vec2, progress: f32) -> (Vec3, f32) {
    // Higher the further it goes, but never off the top of the beach: a
    // crab thrown corner to corner left the board at a third of it.
    let lift = (from.distance(to) * 0.35).min(TILE * 1.2);
    let (at, scale) = arc(from, to, lift, progress);
    // Over the fences while it is in the air.
    (at.extend(layout::z::WALL + 0.3), scale)
}

/// How long a crab the tide swept home is in the air, and how far behind
/// the one before it each sets off.
///
/// Crab Monopoly banks half the beach from wherever the crabs stand. At
/// [`HOP`] a crab five tiles out crossed the board in a fifth of a second,
/// shrinking as it went, and the whole sweep read as crabs blinking out:
/// the event a player had just been told about was nowhere to be seen. In
/// the air long enough to follow, one after another, it is a sweep.
const SWEEP_HOP: f32 = 0.75;
const SWEEP_STAGGER: f32 = 0.08;

/// The swept crabs wait, glowing, while a banner holds the middle of the
/// board ([`Announcer::holds_the_board`]): the event's own, and any queued
/// ahead of it. Flown at once, every crab in the middle rows went home
/// under it. They wait at least long enough for the event's banner to be
/// queued, which can be a frame after the sweep is seen, and never longer
/// than the most banners a queue can show.
///
/// [`Announcer::holds_the_board`]: crate::app::announce::Announcer::holds_the_board
const SWEEP_MIN_HOLD: f32 = 0.2;
const SWEEP_MAX_HOLD: f32 = 8.0;

/// Farther than any crab walking in is from the keep it walks into: a
/// bank from here was the tide's doing.
const SWEPT_FROM: f32 = TILE * 1.5;

/// Farther than this from its keep, a banked crab is on the doorstep, a
/// tile out: nearer, the tide has already flown it to the gate, and it has
/// no doorstep to cheer on.
const ON_THE_DOORSTEP: f32 = TILE * 0.25;

/// How long after the crab ahead of it sets off over the wall a crab
/// queued at the same door sets off: under a hop, so the two land in turn.
const QUEUE_GAP: f32 = 0.12;

/// How a crab the sim banked from `pos` into `keep`, worth `points`, goes
/// in. `sweeps` counts the crabs the tide has thrown home so far this
/// frame, and `doorsteps` holds, per keep, how long until the last crab
/// waiting at its door sets off; both are brought up to date.
///
/// The first crab at a door cheers there if it walked to the doorstep and
/// scored. One arriving while another still waits at that door queues
/// behind it and goes in after it: the castle bounces as each lands, and
/// it must not bounce for the second while the first is still outside.
fn homeward(
    pos: Vec2,
    keep: Vec2,
    points: i32,
    sweeps: &mut usize,
    doorsteps: &mut Vec<(Vec2, f32)>,
) -> Homeward {
    let out = pos.distance(keep);
    if out > SWEPT_FROM {
        *sweeps += 1;
        return Homeward::Swept(*sweeps - 1);
    }
    if let Some((_, wait)) = doorsteps.iter_mut().find(|(at, _)| at.distance(keep) < 1.0) {
        *wait += QUEUE_GAP;
        return Homeward::Behind(*wait);
    }
    if points > 0 && out > ON_THE_DOORSTEP {
        doorsteps.push((keep, CHEER));
        return Homeward::Cheer;
    }
    Homeward::Hop
}

/// A crab the sim has just banked, as its hop home needs it: which crab,
/// from the tile it vanished on to the keep it vanished into.
pub struct BankedCrab {
    pub id: u32,
    pub from: Vec2,
    pub to: Vec2,
    pub kind: crate::sim::CrabKind,
    pub handed: crate::sim::Handedness,
    /// Whether its claw wears the seat colour of a co-op stage
    /// ([`crate::app::creatures::claw_color`]), as it did walking there.
    pub coop: bool,
    /// What it did to its owner's score.
    pub points: i32,
}

/// Send a banked crab home over the wall: the crab that walked there, big
/// claw and all, on the side it was on, facing the keep. The first at its
/// door cheers there first ([`Homeward`]); one the tide swept home from
/// across the beach is flung there instead.
pub fn bank_hop(commands: &mut Commands, art: &Art, crab: &BankedCrab, way: Homeward) {
    use crate::app::creatures::{
        claw_color, crab_body, mirrored, shade_of, shell_color, sprite_side,
    };
    let BankedCrab {
        id,
        from,
        to,
        kind,
        handed,
        coop,
        points,
    } = *crab;
    let shell = shell_color(kind, shade_of(id));
    let (age, path, z) = match way {
        Homeward::Cheer => (-CHEER, HopPath::OverWall, layout::z::CREATURE + 0.1),
        Homeward::Hop => (0.0, HopPath::OverWall, layout::z::CREATURE + 0.1),
        // Under the one ahead of it, which it stands behind.
        Homeward::Behind(wait) => (-wait, HopPath::OverWall, layout::z::CREATURE + 0.05),
        Homeward::Swept(slot) => (
            -SWEEP_STAGGER * slot as f32,
            HopPath::Swept { waiting: Some(0.0) },
            SWEEP_WAIT_Z,
        ),
    };
    let cheer = way == Homeward::Cheer;
    let hop = Hop {
        from,
        to,
        age,
        shell,
        path,
        cheer,
        handed,
        kicks: points > 0,
    };
    // Facing the keep it walked to, as it walked: drawn square to the
    // board, a crab that came in from the right turned its back on its
    // own castle for the hop.
    let toward = to - from;
    let facing = match toward.length_squared() > 1.0 {
        true => Quat::from_rotation_z(toward.to_angle()),
        false => Quat::IDENTITY,
    };
    let side = sprite_side(kind);
    let mirror = mirrored(handed);
    let claw = |big: bool, color: Color| {
        (
            HopClaw { big },
            Sprite {
                image: art.claw.clone(),
                color,
                custom_size: Some(Vec2::splat(side)),
                // The small claw is the big one's art on the other side.
                flip_y: mirror == big,
                ..default()
            },
            claw_pose(side, big, mirror, 0.0),
        )
    };
    let mut body = commands.spawn((
        hop,
        crab_body(art, kind, handed, shell),
        Transform::from_translation(from.extend(z)).with_rotation(facing),
    ));
    body.with_child(claw(true, claw_color(handed, coop)));
    if cheer {
        body.with_child(claw(false, shell.with_alpha(0.0)));
    }
}

/// A banked crab under reduced motion: no hop over the wall, but not gone
/// on the spot either, which is what a crab eaten looks like with the
/// feathers taken away. It fades where it stood, claw and all, on the
/// doorstep of the castle whose number floats up beside it.
///
/// The claw is its own particle rather than the body's child, so each
/// fades and despawns itself: a child would hold its colour to the end.
fn bank_fade(commands: &mut Commands, art: &Art, crab: &BankedCrab) {
    use crate::app::creatures::{crab_body, crab_claw, shade_of, shell_color, sprite_side};
    let BankedCrab {
        id,
        from,
        to: _,
        kind,
        handed,
        coop,
        points: _,
    } = *crab;
    let shell = shell_color(kind, shade_of(id));
    let z = layout::z::CREATURE + 0.1;
    commands.spawn((
        standing_fade(),
        crab_body(art, kind, handed, shell),
        Transform::from_translation(from.extend(z)),
    ));
    let (claw, lift) = crab_claw(art, handed, coop, Vec2::splat(sprite_side(kind)));
    commands.spawn((
        standing_fade(),
        claw,
        Transform::from_translation(from.extend(z) + lift.translation),
    ));
}

/// A particle that stays exactly where and as big as it was spawned and
/// only fades: the reduced-motion shape of a thing leaving the board.
fn standing_fade() -> Particle {
    Particle {
        fade_in: 0.0,
        life: 0.5,
        ..default()
    }
}

/// Whether `event` still draws anything under reduced motion. The news
/// stays and the fireworks go: a raid's number, a gull seen leaving (or it
/// went *in*, which is a raid), a banked crab fading at the gate rather
/// than vanishing, and the ghost of a post traded away, which is how a
/// player sees which arrow they lost.
fn kept_when_calm(event: &SimEvent) -> bool {
    matches!(
        event,
        SimEvent::CastleRaided { .. }
            | SimEvent::GullShooed { .. }
            | SimEvent::GullFlewOff { .. }
            | SimEvent::CrabBanked { .. }
            | SimEvent::SignpostEvicted { .. }
    )
}

/// Where a banking crab is, and how big it looks, `progress` of the way
/// from the tile it vanished on to the keep it vanished into.
///
/// The two ends are the whole of it: a crab that starts anywhere but where
/// it was last drawn jumps on its first frame, and one that finishes
/// anywhere but at the gate is last seen standing on the wall.
pub(crate) fn arc(from: Vec2, to: Vec2, lift: f32, progress: f32) -> (Vec2, f32) {
    // Eased both ends, so it sets off and arrives rather than being
    // dragged across.
    let eased = progress * progress * (3.0 - 2.0 * progress);
    // Over the wall: zero lift at both ends, so the path meets the sand at
    // one end and the gate at the other.
    let lift = (progress * std::f32::consts::PI).sin() * lift;
    // Shrinking into the gate: the keep is a hole in the picture as far as
    // the crab is concerned.
    (
        from.lerp(to, eased) + Vec2::new(0.0, lift),
        1.0 - 0.7 * eased,
    )
}

/// Carry the hopping crabs over the wall and puff them out of sight, the
/// first at its door cheering there first, and bounce each keep as its
/// crab lands in it: a castle that bounced while its crab still stood on
/// the doorstep celebrated a crab that had not come in yet.
///
/// Held, not run, under a pause card: a crab does not go on over the wall
/// of a frozen beach. The round's end does not hold them: the crab banked
/// on the last tick still lands under the card.
#[allow(clippy::too_many_arguments)]
pub fn advance_hops(
    time: Res<Time>,
    mut commands: Commands,
    art: Res<Art>,
    mut rng: ResMut<VisualRng>,
    announcer: Res<crate::app::announce::Announcer>,
    round: crate::app::round_state::RoundState,
    sim: Res<crate::app::Sim>,
    mut hops: Query<(Entity, &mut Hop, &mut Transform, &mut Sprite, &Children)>,
    mut claws: Query<(&HopClaw, &mut Transform, &mut Sprite), Without<Hop>>,
    mut castles: Query<(
        &crate::app::board_render::CastleSprite,
        &mut crate::app::board_render::CastleKick,
    )>,
) {
    if round.held() {
        return;
    }
    let dt = time.delta_secs();
    for (entity, mut hop, mut transform, mut sprite, children) in &mut hops {
        let hop = &mut *hop;
        if let HopPath::Swept {
            waiting: Some(waited),
        } = &mut hop.path
        {
            // Picked out while the banner says what is about to happen.
            let glow = 0.45 + 0.35 * (*waited * 9.0).sin();
            layout::tint(&mut sprite, hop.shell.mix(&palette::GOLD, glow));
            let held = *waited < SWEEP_MIN_HOLD || announcer.holds_the_board();
            if held && *waited < SWEEP_MAX_HOLD {
                *waited += dt;
                continue;
            }
            // Then one after another, each its turn behind the last.
            hop.age += dt;
            if hop.age < 0.0 {
                continue;
            }
            hop.path = HopPath::Swept { waiting: None };
            layout::tint(&mut sprite, hop.shell);
            burst(
                &mut commands,
                &mut rng,
                &Burst {
                    image: art.puff.clone(),
                    pos: hop.from,
                    color: SAND_KICK,
                    count: 4,
                    size: 12.0,
                    speed: 36.0,
                    gravity: 30.0,
                },
            );
        } else {
            hop.age += dt;
        }
        let progress = (hop.age / hop.path.span()).clamp(0.0, 1.0);
        if progress >= 1.0 {
            commands.entity(entity).despawn();
            if hop.kicks {
                crate::app::board_render::kick_keep(&sim.0, &mut castles, hop.to);
            }
            // The sand it kicks up going over the wall, landing where it
            // landed rather than where it left.
            burst(
                &mut commands,
                &mut rng,
                &Burst {
                    image: art.puff.clone(),
                    pos: hop.to,
                    color: Color::srgba(0.95, 0.88, 0.7, 1.0),
                    count: 4,
                    size: 14.0,
                    speed: 40.0,
                    gravity: 40.0,
                },
            );
            continue;
        }
        match hop.path {
            HopPath::Swept { .. } => {
                let (at, scale) = sweep_arc(hop.from, hop.to, progress);
                transform.translation = at;
                transform.scale = Vec3::splat(scale);
            }
            HopPath::OverWall => {
                let (at, scale) = arc(hop.from, hop.to, HOP_LIFT, progress);
                transform.translation.x = at.x;
                transform.translation.y = at.y;
                transform.scale = Vec3::splat(scale);
            }
        }
        if hop.cheer {
            cheer(hop, &mut transform, children, &mut claws);
        }
    }
}

/// Pose a cheering crab on its doorstep: both claws up and out on each
/// pump, the body bracing under them, and everything back at rest, the
/// small claw gone, once the hop begins.
fn cheer(
    hop: &Hop,
    body: &mut Transform,
    children: &Children,
    claws: &mut Query<(&HopClaw, &mut Transform, &mut Sprite), Without<Hop>>,
) {
    let pumping = pump(hop.age + CHEER);
    if hop.age < 0.0 {
        body.scale = Vec3::splat(1.0 + CHEER_BRACE * pumping);
    }
    let mirror = crate::app::creatures::mirrored(hop.handed);
    for child in children {
        let Ok((claw, mut place, mut sprite)) = claws.get_mut(*child) else {
            continue;
        };
        let side = sprite.custom_size.map_or(TILE, |size| size.x);
        let pose = claw_pose(side, claw.big, mirror, pumping);
        place.translation = pose.translation;
        place.rotation = pose.rotation;
        place.scale = pose.scale;
        if !claw.big {
            let pumped = sprite.color.with_alpha(pumping);
            layout::tint(&mut sprite, pumped);
        }
    }
}

/// Dry sand thrown up by something landing in it.
pub(crate) const SAND_KICK: Color = Color::srgba(0.93, 0.86, 0.70, 0.95);

/// The most splashes a frame throws: a stream of crabs wading into a pool
/// lane is one crab after another, and past a few a frame it is spray,
/// not splashes.
const SPLASHES_PER_FRAME: usize = 4;

/// A splash where something wades into a pool: a ring on the water and a
/// few drops thrown up out of it.
fn splash(commands: &mut Commands, rng: &mut VisualRng, art: &Art, pos: Vec2, size: f32) {
    ring(
        commands,
        art,
        pos,
        Color::srgba(0.86, 0.95, 1.0, 0.55),
        TILE * 0.28 * size,
        2.2,
        0.45,
    );
    burst(
        commands,
        rng,
        &Burst {
            image: art.puff.clone(),
            pos,
            color: Color::srgba(0.78, 0.90, 0.98, 0.9),
            count: (5.0 * size).round() as usize,
            size: 6.0 * size,
            speed: 55.0,
            gravity: 120.0,
        },
    );
}

/// Whether the tile at `index` is a pool.
fn in_pool(board: &crate::sim::Board, index: u16) -> bool {
    let (x, y) = board.coords_u8(index);
    board.tile_at(x, y) == TileKind::Pool
}

/// Whether a creature that was `was` in a pool last frame, and is `now`,
/// has just waded in: from dry sand to water, and not when it is first
/// seen, since nothing it is standing in then is news.
fn wades_in(was: Option<bool>, now: bool) -> bool {
    now && was == Some(false)
}

/// Crabs and walking gulls splash as they wade into a pool from dry sand.
///
/// Once on the way in, not on every tile of it: a pool lane is a run of
/// pool tiles, and a stream crossing one would be spray from end to end.
/// A creature first seen is taken to be where it has always been, so a
/// level that starts with a crab in a pool, or a board reloading, does not
/// splash everything on it. Render-side: the sim is untouched.
pub fn splash_ponds(
    mut commands: Commands,
    current: CurrentBoard,
    art: Res<Art>,
    settings: Res<crate::app::settings::GameSettings>,
    mut rng: ResMut<VisualRng>,
    mut wet: Local<BoardMemory<(bool, u32), bool>>,
    mut seen: Local<bevy::platform::collections::HashSet<(bool, u32)>>,
) {
    let board = &current.sim.0;
    let wet = wet.of(&current);
    seen.clear();
    let mut thrown = 0;
    let creatures = board
        .crabs()
        .iter()
        .map(|crab| ((false, crab.id), crab.tile, crab.dir, crab.progress, 1.0))
        .chain(board.gulls().iter().filter_map(|gull| {
            matches!(gull.state, crate::sim::GullState::Walking).then_some((
                (true, gull.id),
                gull.tile,
                gull.dir,
                gull.progress,
                0.8,
            ))
        }));
    for (key, tile, dir, progress, size) in creatures {
        seen.insert(key);
        let now = in_pool(board, tile);
        let was = wet.insert(key, now);
        if wades_in(was, now) && !settings.reduced_motion && thrown < SPLASHES_PER_FRAME {
            thrown += 1;
            let pos = layout::creature_pos(board, tile, dir, progress);
            splash(&mut commands, &mut rng, &art, pos, size);
        }
    }
    wet.retain(|key, _| seen.contains(key));
}

/// Seconds between the gold rings a called hole sends out.
const GOLDEN_RING_EVERY: f32 = 0.45;

/// A gold ring out of the hole a golden crab is called to, every so often
/// for as long as the call is public (`Board::golden_call`): the banner
/// says a golden crab is coming, and this says from where, on a beach with
/// up to six holes. Reduced motion keeps the swollen hole and loses the
/// rings.
pub fn golden_call_rings(
    mut commands: Commands,
    sim: Res<crate::app::Sim>,
    art: Res<Art>,
    time: Res<Time>,
    settings: Res<crate::app::settings::GameSettings>,
    round: crate::app::round_state::RoundState,
    mut since: Local<f32>,
) {
    let Some((_, x, y)) = sim.0.golden_call() else {
        *since = GOLDEN_RING_EVERY;
        return;
    };
    // The round's time, so no rings go out over a frozen beach.
    round.run_clock(&sim.0, &mut since, time.delta_secs());
    if settings.reduced_motion || *since < GOLDEN_RING_EVERY {
        return;
    }
    *since = 0.0;
    let pos = layout::tile_center(&sim.0, x, y);
    ring(
        &mut commands,
        &art,
        pos,
        palette::GOLD,
        TILE * 0.5,
        2.4,
        0.5,
    );
}

/// Walking crabs scuff the sand: tiny alternating footprints that linger
/// and fade, plus the occasional kicked-up grain. Footfalls are paced by
/// distance walked, tracked per crab id. Pure decoration, sim untouched.
pub fn crab_trails(
    mut commands: Commands,
    current: CurrentBoard,
    art: Res<Art>,
    settings: Res<crate::app::settings::GameSettings>,
    mut rng: ResMut<VisualRng>,
    mut footfalls: Local<BoardMemory<u32, Footfall>>,
    mut seen: Local<bevy::platform::collections::HashSet<u32>>,
) {
    if settings.reduced_motion {
        return;
    }
    const STRIDE: f32 = 20.0;
    let board = &current.sim.0;
    let footfalls = footfalls.of(&current);
    seen.clear();
    for crab in board.crabs() {
        seen.insert(crab.id);
        let pos = layout::creature_pos(board, crab.tile, crab.dir, crab.progress);
        // A crab seen for the first time lands on a zero-length step
        // below, which the stride check skips.
        let fall = footfalls.entry(crab.id).or_insert(Footfall {
            last: pos,
            foot: Foot::Right,
        });
        let step = pos - fall.last;
        if step.length() < STRIDE {
            continue;
        }
        let side = step.normalize_or_zero().perp() * fall.foot.side();
        fall.last = pos;
        fall.foot = fall.foot.other();
        let (x, y) = board.coords_u8(crab.tile);
        if board.tile_at(x, y) != TileKind::Empty {
            continue; // prints only show on dry sand
        }
        let life = rng.range(1.4, 2.2);
        let size = rng.range(3.0, 4.2);
        commands.spawn((
            Particle {
                life,
                // A print is pressed into the sand, not dropped on it: it
                // arrives over a moment as the weight goes on.
                fade_in: 0.05,
                // Its size is its quad's scale, which the particle keeps.
                size,
                // The spawn alpha is honoured (see `Particle::shade`), so
                // a lighter print dims every print in the game.
                peak: Some(PRINT.alpha()),
                ..default()
            },
            art.shaded.quad(
                &art.shaded.prints,
                Transform::from_translation((pos + side).extend(layout::z::WET + 0.05)),
                Vec2::splat(size),
            ),
            crate::app::materials::fade_tag(PRINT.alpha()),
        ));
        // Now and then a grain of sand kicks up behind the crab.
        if rng.range(0.0, 1.0) < 0.3 {
            commands.spawn((
                Particle {
                    velocity: -step.normalize_or_zero() * rng.range(12.0, 26.0),
                    gravity: Vec2::new(0.0, -60.0),
                    spin: rng.range(-3.0, 3.0),
                    grow: 0.5,
                    ramp: Some((SAND_DRY, SAND_DAMP)),
                    life: rng.range(0.25, 0.4),
                    ..default()
                },
                layout::image_sprite(&art.puff, SAND_DRY, Vec2::splat(rng.range(5.0, 8.0))),
                Transform::from_translation(pos.extend(layout::z::PARTICLE)),
            ));
        }
    }
    // A set, not a list. This sweeps one entry per crab and asks after
    // each, so a linear scan makes it quadratic on the busiest boards -
    // and a busy six-seat beach carries well over a hundred crabs, every
    // frame, purely to take out the ones that have gone.
    footfalls.retain(|id, _| seen.contains(id));
}

/// A particle and whichever of the three ways it is drawn: a sprite, a
/// floating number, or a quad of a shared fading colour
/// ([`crate::app::materials::FadeMaterial`]) whose strength is its tag.
type ParticleParts = (
    Entity,
    &'static mut Particle,
    &'static mut Transform,
    Option<&'static mut Sprite>,
    Option<&'static mut TextColor>,
    Option<&'static mut bevy::mesh::MeshTag>,
);

/// Advance and expire particles: drift, fall, spin, grow, fade out.
///
/// Held, not run, under a pause card, like everything else the round
/// draws: a puff, a crumb or a floating score stands still over a frozen
/// beach and carries on when it starts again.
pub fn update_particles(
    time: Res<Time>,
    round: crate::app::round_state::RoundState,
    mut commands: Commands,
    mut particles: Query<ParticleParts>,
) {
    if round.held() {
        return;
    }
    let dt = time.delta_secs();
    for (entity, mut particle, mut transform, sprite, text_color, tag) in &mut particles {
        particle.age += dt;
        if particle.age >= particle.life {
            commands.entity(entity).despawn();
            continue;
        }
        // Read out first: `Mut` cannot hand out a shared and a unique
        // borrow of the same particle in one expression.
        let (gravity, drag) = (particle.gravity, particle.drag);
        particle.velocity += gravity * dt;
        if drag > 0.0 {
            particle.velocity *= (1.0 - drag * dt).clamp(0.0, 1.0);
        }
        transform.translation.x += particle.velocity.x * dt;
        transform.translation.y += particle.velocity.y * dt;
        transform.rotation *= Quat::from_rotation_z(particle.spin * dt);
        // Come to rest on the floor, falling onto it: it stays where it
        // lands, and only fades from there.
        if let Some(floor) = particle.floor
            && particle.velocity.y < 0.0
            && transform.translation.y <= floor
        {
            transform.translation.y = floor;
            particle.velocity = Vec2::ZERO;
            particle.gravity = Vec2::ZERO;
            particle.spin = 0.0;
        }
        let scale = (1.0 + particle.grow * particle.age).max(0.05);
        transform.scale = Vec3::splat(particle.size * scale);
        if let Some(mut sprite) = sprite {
            // The colour spawned with is the peak, alpha included: a piece
            // asked for at 60% never draws stronger than 60%.
            let shaded = particle.shade(sprite.color);
            layout::tint(&mut sprite, shaded);
        }
        if let Some(mut color) = text_color {
            // Through the same ceiling the sprites go through. It read the
            // alpha straight off the strength before, so a number asked
            // for at 60% arrived at full: the rule [`Particle::peak`]
            // states is a rule about particles, and a floating score is
            // one. No caller asks for less than full today, which is the
            // only reason nobody has seen it.
            color.0 = particle.shade(color.0);
        }
        if let Some(mut tag) = tag {
            // The colour is the material's; only the strength is the
            // quad's, and its peak was set at spawn.
            let alpha = particle.shade(Color::WHITE).alpha();
            tag.set_if_neq(crate::app::materials::fade_tag(alpha));
        }
    }
}

/// Turn sim events into their on-board moments: pips, puffs, flashes, and
/// the shove the camera takes for the loud ones.
pub fn moment_effects(
    fx: Fx,
    mut events: MessageReader<SimEvent>,
    cursors: Query<&crate::app::cursor::Cursor>,
    hops: Query<&Hop>,
    mut trauma: ResMut<Trauma>,
    sim: Res<crate::app::Sim>,
) {
    let Fx {
        mut commands,
        art,
        mut rng,
        settings,
    } = fx;
    // Reduced motion keeps the news and drops the fireworks: the score pip
    // for a raid still floats up (it is the only place that number appears),
    // but the puffs, the scatter, the shake and the full-tile white flash
    // do not. A gull turned away at a puzzle's castle still fades where it
    // stood, or it vanished into the keep, which is what a raid looks like.
    // What survives is [`kept_when_calm`].
    let calm = settings.reduced_motion;
    // Crabs swept home so far this frame, so each sets off after the last.
    let mut sweeps = 0usize;
    // The keeps with a crab still waiting at the door, from an earlier
    // frame or this one, and how long until the last of them sets off.
    let mut doorsteps: Vec<(Vec2, f32)> = Vec::new();
    for hop in &hops {
        if hop.path != HopPath::OverWall || hop.age >= 0.0 {
            continue;
        }
        match doorsteps
            .iter_mut()
            .find(|(at, _)| at.distance(hop.to) < 1.0)
        {
            Some((_, wait)) => *wait = wait.max(-hop.age),
            None => doorsteps.push((hop.to, -hop.age)),
        }
    }
    for event in events.read() {
        if calm && !kept_when_calm(event) {
            continue;
        }
        match event {
            // Walked home over the wall, and the puff waits for the
            // landing; a crab that vanished at the threshold was the one
            // moment the game repeated most and showed least.
            SimEvent::CrabBanked {
                id,
                pos,
                keep,
                kind,
                handed,
                points,
                owner: _,
            } => {
                let way = homeward(*pos, *keep, *points, &mut sweeps, &mut doorsteps);
                let crab = BankedCrab {
                    id: *id,
                    from: *pos,
                    to: *keep,
                    kind: *kind,
                    handed: *handed,
                    coop: crate::app::creatures::coop_claws(&sim.0),
                    points: *points,
                };
                if calm {
                    bank_fade(&mut commands, &art, &crab);
                } else {
                    bank_hop(&mut commands, &art, &crab, way);
                }
            }
            // A gull got one: sand, and the feathers that say what kind of
            // ending this was.
            SimEvent::CrabEaten { pos } => {
                burst(
                    &mut commands,
                    &mut rng,
                    &Burst {
                        image: art.puff.clone(),
                        pos: *pos,
                        color: Color::srgba(0.85, 0.92, 0.98, 1.0),
                        count: 5,
                        size: 12.0,
                        speed: 55.0,
                        gravity: 0.0,
                    },
                );
                feathers(&mut commands, &mut rng, &art, *pos);
                trauma.add(0.10);
            }
            // The ghost of the signpost that just got traded away, still
            // pointing where it pointed, swelling as it fades. Under the
            // versus cap a fourth placement takes your oldest, and it used
            // to vanish in silence somewhere else on the beach: the player
            // sees the arrow they lost, and where they lost it. Calm, it
            // fades where it stood without swelling: still the news.
            //
            // Only your own (or every one, watching), by the rule the
            // trade's sound asks: a bot past its cap trades a post every
            // few seconds, and a ghost for each was a stream of arrows
            // nobody here had lost.
            SimEvent::SignpostEvicted { owner, pos, dir }
                if crate::app::cursor::post_noticed_here(&cursors, *owner) =>
            {
                commands.spawn((
                    Particle {
                        grow: if calm { 0.0 } else { 1.1 },
                        life: 0.5,
                        fade_in: 0.0,
                        ..default()
                    },
                    // The arrow off the lost post, in its owner's paint.
                    layout::image_sprite(
                        &art.sign_paint,
                        palette::seat_paint(*owner),
                        Vec2::splat(layout::SIGN_SIZE),
                    ),
                    Transform::from_translation(pos.extend(layout::z::PARTICLE))
                        .with_rotation(layout::dir_rotation(*dir)),
                ));
            }
            SimEvent::CrabSpawned { pos } => burst(
                &mut commands,
                &mut rng,
                &Burst {
                    image: art.puff.clone(),
                    pos: *pos,
                    color: Color::srgba(0.9, 0.8, 0.6, 1.0),
                    count: 3,
                    size: 12.0,
                    speed: 35.0,
                    gravity: 50.0,
                },
            ),
            SimEvent::CastleRaided { pos, lost, .. } => {
                if calm {
                    score_pip(
                        &mut commands,
                        format!("-{lost}"),
                        *pos + Vec2::new(0.0, 10.0),
                        Color::srgb(0.96, 0.3, 0.25),
                    );
                    continue;
                }
                commands.spawn((
                    Particle {
                        grow: 1.6,
                        life: 0.3,
                        fade_in: 0.0,
                        ..default()
                    },
                    layout::image_sprite(
                        &art.puff,
                        Color::srgba(1.0, 1.0, 1.0, 1.0),
                        Vec2::splat(TILE * 1.1),
                    ),
                    Transform::from_translation(pos.extend(layout::z::FLASH)),
                ));
                burst(
                    &mut commands,
                    &mut rng,
                    &Burst {
                        image: art.puff.clone(),
                        pos: *pos,
                        color: Color::srgba(0.9, 0.8, 0.6, 1.0),
                        count: 8,
                        size: 16.0,
                        speed: 70.0,
                        gravity: 60.0,
                    },
                );
                ring(
                    &mut commands,
                    &art,
                    *pos,
                    Color::srgba(1.0, 0.5, 0.4, 0.85),
                    TILE * 0.7,
                    3.4,
                    0.45,
                );
                score_pip(
                    &mut commands,
                    format!("-{lost}"),
                    *pos + Vec2::new(0.0, 10.0),
                    Color::srgb(0.96, 0.3, 0.25),
                );
                // The loudest thing that happens to a player who is not
                // looking at their own castle.
                trauma.add(0.55);
            }
            SimEvent::GullLanded { pos } => {
                burst(
                    &mut commands,
                    &mut rng,
                    &Burst {
                        image: art.puff.clone(),
                        pos: *pos,
                        color: Color::srgba(0.92, 0.85, 0.68, 1.0),
                        count: 4,
                        size: 13.0,
                        speed: 45.0,
                        gravity: 70.0,
                    },
                );
                ring(
                    &mut commands,
                    &art,
                    *pos,
                    Color::srgba(0.95, 0.92, 0.85, 0.5),
                    TILE * 0.5,
                    2.2,
                    0.35,
                );
                trauma.add(0.14);
            }
            // Turned away at a puzzle's castle. The bird has to be seen
            // leaving, or it went *in*, and in versus that is a raid.
            SimEvent::GullShooed { pos, castle } => {
                shooed(&mut commands, &art, *pos, *castle, calm);
            }
            // Made room in a full flock: up and away from where it stood,
            // with no ring, since nothing here turned it away.
            SimEvent::GullFlewOff { pos } => {
                flying_away(&mut commands, &art, *pos, Vec2::Y, calm);
            }
            // A post going in gets a ring under it; the pop of the post
            // itself belongs to the sprite, which `board_render` owns.
            //
            // Only your own (or every one, watching), for the reason the
            // knock is only your own: on a six-seat beach five bots place
            // and lose a post every few seconds each, and a ring for every
            // one of them is a stream of particles over tiles nobody is
            // watching. The picture and the sound ask the one rule, so they
            // agree about whose beach this is, a watcher's included.
            SimEvent::SignpostPlaced { owner, pos }
                if crate::app::cursor::post_noticed_here(&cursors, *owner) =>
            {
                ring(
                    &mut commands,
                    &art,
                    *pos,
                    Color::srgba(1.0, 0.98, 0.9, 0.5),
                    TILE * 0.45,
                    1.9,
                    0.3,
                );
                // Driven in: the sand the stake shoved aside, thrown out
                // low and falling straight back.
                burst(
                    &mut commands,
                    &mut rng,
                    &Burst {
                        image: art.puff.clone(),
                        pos: *pos,
                        color: SAND_KICK,
                        count: 6,
                        size: 7.0,
                        speed: 48.0,
                        gravity: 95.0,
                    },
                );
            }
            SimEvent::SignpostRemoved { owner, pos }
                if crate::app::cursor::post_noticed_here(&cursors, *owner) =>
            {
                burst(
                    &mut commands,
                    &mut rng,
                    &Burst {
                        image: art.puff.clone(),
                        pos: *pos,
                        color: Color::srgba(0.92, 0.86, 0.72, 1.0),
                        count: 3,
                        size: 11.0,
                        speed: 30.0,
                        gravity: 50.0,
                    },
                );
            }
            // Somebody else's post: the board already shows it appearing
            // and going, which is all a rival's arrow owes anybody.
            SimEvent::SignpostPlaced { .. }
            | SimEvent::SignpostRemoved { .. }
            | SimEvent::SignpostEvicted { .. } => {}
            // The final scramble arrives with the sea behind it.
            SimEvent::SurgeStarted => trauma.add(0.7),
            // Out at last: what the rings have been pointing at. Gold
            // thrown up out of the hole, and a ring wide enough to catch an
            // eye watching another corner of the board.
            SimEvent::GoldenOut { pos } => {
                burst(
                    &mut commands,
                    &mut rng,
                    &Burst {
                        image: art.star.clone(),
                        pos: *pos,
                        color: palette::GOLD,
                        count: 14,
                        size: 14.0,
                        speed: 120.0,
                        gravity: 90.0,
                    },
                );
                ring(
                    &mut commands,
                    &art,
                    *pos,
                    palette::GOLD,
                    TILE * 0.7,
                    4.5,
                    0.8,
                );
                ring(
                    &mut commands,
                    &art,
                    *pos,
                    Color::srgba(1.0, 1.0, 0.85, 0.9),
                    TILE * 0.4,
                    3.0,
                    0.5,
                );
                trauma.add(0.25);
            }
            SimEvent::GoldenCalled { pos } => {
                ring(
                    &mut commands,
                    &art,
                    *pos,
                    palette::GOLD,
                    TILE * 0.6,
                    3.0,
                    0.6,
                );
            }
            SimEvent::GullIncoming { .. }
            | SimEvent::GullArrived
            | SimEvent::GullTookOff
            | SimEvent::TierUp { .. }
            | SimEvent::TideEventFired { .. }
            | SimEvent::LureStarted { .. }
            | SimEvent::WheelLocked { .. }
            | SimEvent::LureRefused { .. }
            | SimEvent::RoundEnded => {}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Reduced motion drops the fireworks and keeps the news. A banked crab
    /// and a post traded away are news: dropped, the crab vanished on the
    /// doorstep and the lost arrow went without a trace. Their calm shape
    /// stands still and only fades.
    #[test]
    fn reduced_motion_keeps_a_bank_and_a_lost_post_without_moving_them() {
        let banked = SimEvent::CrabBanked {
            id: 0,
            owner: 0,
            pos: Vec2::ZERO,
            keep: Vec2::X,
            points: 1,
            kind: crate::sim::CrabKind::Common,
            handed: crate::sim::Handedness::Right,
        };
        let evicted = SimEvent::SignpostEvicted {
            owner: 0,
            pos: Vec2::ZERO,
            dir: crate::sim::Direction::Up,
        };
        assert!(kept_when_calm(&banked), "a bank still shows");
        assert!(kept_when_calm(&evicted), "and so does a lost post");
        assert!(
            !kept_when_calm(&SimEvent::CrabEaten { pos: Vec2::ZERO }),
            "the feathers of an eaten crab are fireworks"
        );
        let calm = standing_fade();
        assert_eq!(calm.velocity, Vec2::ZERO, "it does not drift");
        assert_eq!(calm.gravity, Vec2::ZERO, "or fall");
        assert_eq!(calm.grow, 0.0, "or swell");
        assert_eq!(calm.spin, 0.0, "or turn");
        assert!(calm.life > 0.0, "it is there for a moment, then gone");
    }

    /// A beach for the effect systems to draw on: `seats` cursors at this
    /// machine (seats past them are bots, none at all is watching), and
    /// reduced motion when `calm`.
    fn stage(seats: u8, calm: bool) -> App {
        let mut app = App::new();
        app.insert_resource(Art::blank());
        app.init_resource::<VisualRng>();
        app.init_resource::<Trauma>();
        app.insert_resource(crate::app::settings::GameSettings {
            reduced_motion: calm,
            ..default()
        });
        app.init_resource::<crate::app::sim_events::BoardGeneration>();
        app.add_message::<SimEvent>();
        app.insert_resource(State::new(crate::app::Screen::Versus));
        app.init_resource::<crate::app::Paused>();
        app.init_resource::<crate::app::pause::PauseMenu>();
        app.init_resource::<crate::app::net::Online>();
        app.insert_resource(crate::app::Sim(crate::sim::Board::new(4, 4, 0)));
        for seat in 0..seats {
            app.world_mut()
                .spawn(crate::app::cursor::Cursor::seated(seat));
        }
        app
    }

    /// The particles drawn since the last call, swept away for the next.
    fn drawn(app: &mut App) -> usize {
        let world = app.world_mut();
        let live: Vec<Entity> = world
            .query_filtered::<Entity, With<Particle>>()
            .iter(world)
            .collect();
        for &entity in &live {
            world.entity_mut(entity).despawn();
        }
        live.len()
    }

    /// The ghost of a post traded away asks the rule its sound asks: your
    /// own lost arrow, or every one when watching. A bot past its cap
    /// trades a post every few seconds, and drew a ghost for each, calm or
    /// not, while the speaker kept quiet about them.
    #[test]
    fn a_lost_post_is_drawn_where_it_is_heard() {
        let traded = |owner| SimEvent::SignpostEvicted {
            owner,
            pos: Vec2::ZERO,
            dir: crate::sim::Direction::Up,
        };
        for calm in [false, true] {
            let mut app = stage(1, calm);
            app.add_systems(Update, moment_effects);
            app.world_mut().write_message(traded(0));
            app.update();
            assert_eq!(drawn(&mut app), 1, "your own lost arrow (calm: {calm})");
            app.world_mut().write_message(traded(4));
            app.update();
            assert_eq!(drawn(&mut app), 0, "not a bot's (calm: {calm})");
        }
        let mut app = stage(0, false);
        app.add_systems(Update, moment_effects);
        app.world_mut().write_message(traded(4));
        app.update();
        assert_eq!(drawn(&mut app), 1, "a watcher sees every seat's");
    }

    /// A grain falling onto a floor stops there and lies at full strength
    /// for its hold, then fades from where it lies.
    #[test]
    fn a_grain_comes_to_rest_on_its_floor_and_lies_there() {
        let mut app = stage(0, false);
        app.init_resource::<Time>();
        app.add_systems(Update, update_particles);
        let grain = app
            .world_mut()
            .spawn((
                Particle {
                    velocity: Vec2::new(10.0, 20.0),
                    gravity: Vec2::new(0.0, -400.0),
                    fade_in: 0.0,
                    floor: Some(-10.0),
                    hold: 0.5,
                    life: 2.0,
                    ..default()
                },
                Sprite::default(),
                Transform::default(),
            ))
            .id();
        let mut landed = None;
        for _ in 0..60 {
            app.world_mut()
                .resource_mut::<Time>()
                .advance_by(std::time::Duration::from_secs_f32(1.0 / 60.0));
            app.update();
            let at = app
                .world()
                .get::<Transform>(grain)
                .expect("alive")
                .translation;
            assert!(at.y >= -10.0, "fell through the floor to {}", at.y);
            if at.y == -10.0 {
                match landed {
                    None => landed = Some(at.x),
                    Some(x) => assert_eq!(at.x, x, "it slid once it landed"),
                }
            }
        }
        assert!(landed.is_some(), "it never landed");
        let held = app.world().get::<Particle>(grain).expect("alive");
        assert_eq!(held.strength(), 1.0, "still lying at full strength");
        let faded = Particle { age: 1.5, ..*held };
        assert!((faded.strength() - 0.5).abs() < 1e-5, "halfway out");
    }

    /// A footprint drawn as a fading quad shows, frame by frame, the
    /// alpha the same particle drawn as a sprite is given, in its tag,
    /// while the sprite's own colour, and so its material, would change.
    #[test]
    fn a_fading_quad_carries_the_alpha_a_sprite_would_wear() {
        let mut app = stage(0, false);
        app.init_resource::<Time>();
        app.add_systems(Update, update_particles);
        let like = || Particle {
            life: 1.0,
            fade_in: 0.05,
            peak: Some(PRINT.alpha()),
            ..default()
        };
        let quad = app
            .world_mut()
            .spawn((
                like(),
                crate::app::materials::fade_tag(PRINT.alpha()),
                Transform::default(),
            ))
            .id();
        let sprite = app
            .world_mut()
            .spawn((
                like(),
                Sprite::from_color(PRINT, Vec2::ONE),
                Transform::default(),
            ))
            .id();
        for _ in 0..8 {
            app.world_mut()
                .resource_mut::<Time>()
                .advance_by(std::time::Duration::from_secs_f32(0.1));
            app.update();
            let tag = app
                .world()
                .get::<bevy::mesh::MeshTag>(quad)
                .expect("alive")
                .value;
            let worn = app.world().get::<Sprite>(sprite).expect("alive").color;
            assert_eq!(f32::from_bits(tag), worn.alpha());
            assert!(worn.alpha() < PRINT.alpha(), "fading");
        }
    }

    /// Under a pause a particle holds where it is, as old as it was, and
    /// carries on from there once the round does.
    #[test]
    fn a_particle_holds_still_under_a_pause() {
        let mut app = stage(0, false);
        app.init_resource::<Time>();
        app.add_systems(Update, update_particles);
        let puff = app
            .world_mut()
            .spawn((
                Particle {
                    velocity: Vec2::new(30.0, 40.0),
                    life: 2.0,
                    ..default()
                },
                Sprite::default(),
                Transform::default(),
            ))
            .id();
        let step = |app: &mut App| {
            app.world_mut()
                .resource_mut::<Time>()
                .advance_by(std::time::Duration::from_secs_f32(0.1));
            app.update();
            let age = app.world().get::<Particle>(puff).expect("alive").age;
            let at = app
                .world()
                .get::<Transform>(puff)
                .expect("alive")
                .translation;
            (age, at)
        };
        step(&mut app);
        app.world_mut().resource_mut::<crate::app::Paused>().0 = true;
        let before = step(&mut app);
        assert_eq!(step(&mut app), before, "it moved under the pause");
        app.world_mut().resource_mut::<crate::app::Paused>().0 = false;
        assert!(step(&mut app).0 > before.0, "and carries on after it");
    }

    /// A crab banked at `keep` from beside it, worth `points`.
    fn banked_at(id: u32, keep: Vec2, points: i32) -> SimEvent {
        SimEvent::CrabBanked {
            id,
            owner: 0,
            pos: keep + Vec2::new(TILE * 0.5, 0.0),
            keep,
            points,
            kind: crate::sim::CrabKind::Common,
            handed: crate::sim::Handedness::Right,
        }
    }

    /// The cheering crabs on the beach, and the ones hopping straight in.
    fn cheers(app: &mut App) -> (usize, usize) {
        let world = app.world_mut();
        let hops: Vec<bool> = world.query::<&Hop>().iter(world).map(|h| h.cheer).collect();
        let cheering = hops.iter().filter(|&&c| c).count();
        (cheering, hops.len() - cheering)
    }

    /// Only the first crab at a door cheers there. Two banking at one keep
    /// on one frame, or one a frame behind a crab still cheering, go
    /// straight in; a crab at another keep cheers for its own, and one
    /// that cost its owner points does not cheer at all.
    #[test]
    fn only_the_first_crab_at_a_door_cheers() {
        let mut app = stage(1, false);
        app.add_systems(Update, moment_effects);
        let keep = Vec2::new(100.0, 0.0);
        app.world_mut().write_message(banked_at(1, keep, 1));
        app.world_mut().write_message(banked_at(2, keep, 1));
        app.update();
        assert_eq!(cheers(&mut app), (1, 1), "one cheers, one goes in");
        app.world_mut().write_message(banked_at(3, keep, 1));
        app.world_mut().write_message(banked_at(4, -keep, 1));
        app.world_mut().write_message(banked_at(5, keep * 3.0, -2));
        app.update();
        assert_eq!(cheers(&mut app), (2, 3), "the other keep cheers its own");
    }

    /// How long until each crab hopping into `keep` lands, soonest first.
    fn landings(app: &mut App, keep: Vec2) -> Vec<f32> {
        let world = app.world_mut();
        let mut out: Vec<f32> = world
            .query::<&Hop>()
            .iter(world)
            .filter(|hop| hop.to == keep)
            .map(|hop| hop.path.span() - hop.age)
            .collect();
        out.sort_by(f32::total_cmp);
        out
    }

    /// A crab banking at a door while another still cheers on its doorstep
    /// waits behind it and lands after it, on the same frame or a later
    /// one, and each lands on its own beat: the castle bounces as each
    /// crab lands, and must not for the second while the first is outside.
    #[test]
    fn a_crab_behind_a_cheering_one_lands_after_it() {
        let mut app = stage(1, false);
        app.add_systems(Update, moment_effects);
        let keep = Vec2::new(100.0, 0.0);
        app.world_mut().write_message(banked_at(1, keep, 1));
        app.world_mut().write_message(banked_at(2, keep, 1));
        app.update();
        app.world_mut().write_message(banked_at(3, keep, 1));
        app.update();
        let lands = landings(&mut app, keep);
        assert_eq!(lands.len(), 3, "{lands:?}");
        assert!(
            (lands[0] - (CHEER + HOP)).abs() < 1e-5,
            "the cheering crab lands first: {lands:?}"
        );
        for pair in lands.windows(2) {
            assert!(
                pair[1] - pair[0] >= QUEUE_GAP - 1e-5,
                "one at a time: {lands:?}"
            );
        }
    }

    /// A crab the tide has already flown to its gate banks there, with no
    /// doorstep under it: it goes straight in rather than pumping its claws
    /// on the castle's roof.
    #[test]
    fn a_crab_flown_to_its_gate_does_not_cheer_on_the_roof() {
        let mut app = stage(1, false);
        app.add_systems(Update, moment_effects);
        let keep = Vec2::new(100.0, 0.0);
        app.world_mut().write_message(SimEvent::CrabBanked {
            id: 1,
            owner: 0,
            pos: keep,
            keep,
            points: 1,
            kind: crate::sim::CrabKind::Common,
            handed: crate::sim::Handedness::Right,
        });
        app.update();
        assert_eq!(cheers(&mut app), (0, 1), "straight in");
        app.world_mut().write_message(banked_at(2, keep, 1));
        app.update();
        assert_eq!(cheers(&mut app), (1, 1), "and the next walking in cheers");
    }

    /// A pump is two humps over the cheer, at rest at both ends, and the
    /// claw it swings stays rooted on the body: the root is where it was
    /// at rest however hard the crab pumps.
    #[test]
    fn a_cheer_pumps_twice_about_the_claws_root() {
        assert_eq!(pump(0.0), 0.0);
        assert!(pump(CHEER - 1e-4) < 0.05, "at rest as the hop begins");
        assert_eq!(pump(CHEER + 0.1), 0.0);
        assert!((pump(CHEER * 0.25) - 1.0).abs() < 1e-3, "the first pump");
        assert!((pump(CHEER * 0.75) - 1.0).abs() < 1e-3, "the second");
        assert!(pump(CHEER * 0.5) < 0.01, "and down between");
        let side = 40.0;
        for (big, mirror) in [(true, false), (true, true), (false, false), (false, true)] {
            let rest = claw_pose(side, big, mirror, 0.0);
            let up = claw_pose(side, big, mirror, 1.0);
            let across = if big != mirror { -1.0 } else { 1.0 };
            let root = Vec2::new(CLAW_ROOT.x, CLAW_ROOT.y * across) * side;
            let push = if big { CHEER_PUSH } else { CHEER_PUSH * 0.8 };
            // Where each pose puts the point of the art that is its root,
            // less the push forward that carries the whole claw.
            let at = |pose: Transform, local: Vec2| {
                (pose.translation + pose.rotation * (local * pose.scale.x).extend(0.0)).truncate()
            };
            let rest_root = at(rest, root);
            let up_root = at(up, root) - Vec2::new(push, 0.0);
            assert!(
                rest_root.distance(up_root) < 0.5,
                "big {big} mirror {mirror}: {rest_root} vs {up_root}"
            );
            // Out, away from the body: the claw on the right turns clockwise.
            assert_eq!(up.rotation.to_euler(EulerRot::XYZ).2.signum(), across);
        }
    }

    /// Run `system` once on `first`, then once on `second` laid out in its
    /// place, and count what the second frame drew.
    fn drawn_on_the_next_board<M>(
        system: impl IntoScheduleConfigs<bevy::ecs::system::ScheduleSystem, M>,
        first: crate::sim::Board,
        second: crate::sim::Board,
    ) -> usize {
        let mut app = stage(1, false);
        app.insert_resource(crate::app::Sim(first));
        app.add_systems(
            Update,
            (crate::app::sim_events::track_board, system).chain(),
        );
        app.update();
        drawn(&mut app);
        app.insert_resource(crate::app::Sim(second));
        app.update();
        drawn(&mut app)
    }

    /// Crab ids start again at zero on every board. Remembered by id
    /// alone, the new board's first crab inherited the old one's: dry sand
    /// there and a pool here was a splash on the first frame.
    #[test]
    fn a_crab_new_to_the_beach_has_not_waded_in() {
        use crate::sim::{CrabKind, Direction, Handedness};
        let mut dry = crate::sim::Board::new(6, 4, 7);
        dry.spawn_crab(1, 1, Direction::Right, Handedness::Left, CrabKind::Common);
        let mut wet = crate::sim::Board::new(6, 4, 8);
        wet.set_tile(1, 1, TileKind::Pool);
        wet.spawn_crab(1, 1, Direction::Right, Handedness::Left, CrabKind::Common);
        assert_eq!(dry.crabs()[0].id, wet.crabs()[0].id, "the same id");
        assert_eq!(drawn_on_the_next_board(splash_ponds, dry, wet), 0);
    }

    /// And the footprints: the new board's crab across the beach from the
    /// old one's namesake pressed a print halfway between on its first
    /// frame, from a step it never took.
    #[test]
    fn a_crab_new_to_the_beach_has_not_walked_there() {
        use crate::sim::{CrabKind, Direction, Handedness};
        let mut west = crate::sim::Board::new(6, 4, 7);
        west.spawn_crab(0, 1, Direction::Right, Handedness::Left, CrabKind::Common);
        let mut east = crate::sim::Board::new(6, 4, 8);
        east.spawn_crab(5, 2, Direction::Left, Handedness::Left, CrabKind::Common);
        assert_eq!(west.crabs()[0].id, east.crabs()[0].id, "the same id");
        assert_eq!(drawn_on_the_next_board(crab_trails, west, east), 0);
    }

    /// A splash asks the tile a creature is on, by the board's own count:
    /// the pool it is in, and not the sand beside it or a row over.
    #[test]
    fn in_pool_reads_the_creatures_own_tile() {
        let mut board = crate::sim::Board::new(5, 4, 1);
        board.set_tile(2, 1, TileKind::Pool);
        let index = |x: u16, y: u16| y * 5 + x;
        assert!(in_pool(&board, index(2, 1)));
        assert!(!in_pool(&board, index(1, 1)), "the sand beside it");
        assert!(!in_pool(&board, index(2, 2)), "the row below");
    }

    /// A splash is the step from sand into water, once: not every tile of
    /// a pool lane, not the step back out, and not a crab that was already
    /// wading when it was first seen.
    #[test]
    fn a_splash_is_wading_in_and_only_that() {
        assert!(wades_in(Some(false), true), "sand to water");
        assert!(!wades_in(Some(true), true), "water to water, along a lane");
        assert!(!wades_in(Some(true), false), "climbing out");
        assert!(!wades_in(Some(false), false), "sand to sand");
        assert!(!wades_in(None, true), "first seen, already in");
    }

    /// `range` feeds particle lifetimes, sizes and spins straight into
    /// sprite maths, and a draw that lands on or past `hi` (a 24-bit
    /// mantissa scaled a hair too far) is a zero-length life or a
    /// negative size nobody will trace back here. Ten thousand draws stay
    /// in the half-open interval, for a plain range and a negative one.
    #[test]
    fn a_visual_draw_never_leaves_the_half_open_range() {
        let mut rng = VisualRng::default();
        for (lo, hi) in [(0.35f32, 0.6f32), (-4.0, 4.0), (0.0, std::f32::consts::TAU)] {
            let (mut min, mut max) = (f32::MAX, f32::MIN);
            for _ in 0..10_000 {
                let draw = rng.range(lo, hi);
                assert!((lo..hi).contains(&draw), "{draw} is outside {lo}..{hi}");
                min = min.min(draw);
                max = max.max(draw);
            }
            // And it actually spreads across the range rather than sitting
            // on one end of it.
            assert!(
                min < lo + (hi - lo) * 0.05,
                "min {min} never came near {lo}"
            );
            assert!(
                max > hi - (hi - lo) * 0.05,
                "max {max} never came near {hi}"
            );
        }
    }

    /// A particle's strength has to start at nothing, reach exactly full
    /// at the top of the fade-in, and reach exactly nothing at the end of
    /// life. The ends are what a reader sees: a particle that starts at
    /// half strength pops, and one that ends at half strength blinks out.
    #[test]
    fn a_particle_fades_in_and_out_of_its_whole_life() {
        let at = |age: f32, fade_in: f32| {
            Particle {
                age,
                life: 1.0,
                fade_in,
                ..Default::default()
            }
            .strength()
        };
        assert_eq!(at(0.0, 0.2), 0.0, "born at nothing");
        assert!((at(0.2, 0.2) - 1.0).abs() < 1e-6, "full at the top");
        assert!((at(0.6, 0.2) - 0.5).abs() < 1e-6, "half way down");
        assert!(at(1.0, 0.2).abs() < 1e-6, "gone at the end");
        // With no fade-in it is the plain ramp it has always been.
        assert!((at(0.0, 0.0) - 1.0).abs() < 1e-6);
        assert!((at(0.25, 0.0) - 0.75).abs() < 1e-6);
    }

    /// The fade must be a fraction of the colour a particle was *spawned*
    /// with, never of the colour it is currently wearing. Shading twice at
    /// one age has to land twice in the same place; when it did not, the
    /// alpha compounded every frame and crabs left no prints at all.
    #[test]
    fn shading_a_particle_twice_lands_in_the_same_place() {
        let mut particle = Particle {
            life: 1.0,
            fade_in: 0.0,
            age: 0.25,
            ..Default::default()
        };
        let spawn = Color::srgba(1.0, 0.9, 0.7, 0.8);
        let once = particle.shade(spawn);
        assert!(
            (once.alpha() - 0.6).abs() < 1e-6,
            "a peak of 0.8 at three-quarter strength: {}",
            once.alpha()
        );
        let twice = particle.shade(once);
        assert!(
            (twice.alpha() - once.alpha()).abs() < 1e-6,
            "the peak is the spawn alpha for ever, not what was written last: {} then {}",
            once.alpha(),
            twice.alpha()
        );
    }

    /// Floating text goes through the same ceiling the sprites do: taken
    /// straight off the strength, a number asked for at 60% arrives at
    /// full.
    #[test]
    fn floating_text_is_held_to_the_alpha_it_asked_for() {
        let mut particle = Particle {
            life: 1.0,
            fade_in: 0.0,
            ..default()
        };
        let asked = Color::srgba(1.0, 1.0, 1.0, 0.6);
        // Freshly born, at the top of its arc, and it is still only 60%.
        let opening = particle.shade(asked);
        assert!(
            (opening.alpha() - 0.6).abs() < 1e-5,
            "arrived at {} rather than the 0.6 it asked for",
            opening.alpha()
        );
        // And it fades from there rather than to there.
        particle.age = 0.5;
        let midway = particle.shade(opening);
        assert!((midway.alpha() - 0.3).abs() < 1e-5, "{}", midway.alpha());
        particle.age = 1.0;
        assert!(particle.shade(midway).alpha() < 1e-5, "gone by the end");
    }

    /// A ramped particle takes its colour from the ramp and its strength
    /// from the peak, so a feather thrown white and landing grey still
    /// fades out rather than holding at the grey.
    #[test]
    fn a_ramp_moves_the_colour_without_touching_the_fade() {
        let mut particle = Particle {
            life: 1.0,
            fade_in: 0.0,
            age: 1.0,
            ramp: Some((FEATHER_LIT, FEATHER_GREY)),
            ..Default::default()
        };
        let end = particle.shade(FEATHER_LIT);
        let grey = FEATHER_GREY.to_srgba();
        assert!(
            (end.to_srgba().blue - grey.blue).abs() < 1e-3,
            "arrived grey"
        );
        assert!(end.alpha() < 1e-6, "and gone at the end of life");
    }

    /// A kicked grain of sand has to come back down: gravity is what
    /// separates a puff of sand from a puff of smoke.
    #[test]
    fn gravity_brings_a_particle_back_down() {
        let mut particle = Particle {
            velocity: Vec2::new(0.0, 40.0),
            gravity: Vec2::new(0.0, -90.0),
            life: 2.0,
            ..Default::default()
        };
        let mut height = 0.0;
        let mut peak: f32 = 0.0;
        for _ in 0..60 {
            particle.velocity += particle.gravity * (1.0 / 60.0);
            height += particle.velocity.y * (1.0 / 60.0);
            peak = peak.max(height);
        }
        assert!(peak > 0.0, "it went up first: {peak}");
        assert!(height < peak, "and came back down: {height} under {peak}");
    }

    /// Drag slows a piece without ever turning it round. A frame long
    /// enough to drive the multiplier negative would send sand flying back
    /// into the crab that kicked it, which is why the clamp is there.
    #[test]
    fn drag_slows_a_particle_without_reversing_it() {
        for drag in [0.5f32, 1.1, 2.4, 40.0] {
            for dt in [1.0f32 / 240.0, 1.0 / 60.0, 0.5, 2.0] {
                let mut velocity = Vec2::new(30.0, -12.0);
                let before = velocity;
                velocity *= (1.0 - drag * dt).clamp(0.0, 1.0);
                assert!(
                    velocity.length() <= before.length() + 1e-6,
                    "drag {drag} at dt {dt} sped it up"
                );
                assert!(
                    velocity.x >= 0.0 && velocity.y <= 0.0,
                    "drag {drag} at dt {dt} turned it round: {velocity:?}"
                );
            }
        }
    }

    /// A print is put down with alternating claws, and the sides have to
    /// be opposite: both on one side and a crab walks a single rut instead
    /// of leaving a trail.
    #[test]
    fn the_claws_alternate_and_fall_on_opposite_sides() {
        assert_eq!(Foot::Left.other(), Foot::Right);
        assert_eq!(Foot::Right.other(), Foot::Left);
        assert_eq!(
            Foot::Left.other().other(),
            Foot::Left,
            "two steps is a cycle"
        );
        assert!(
            Foot::Left.side() * Foot::Right.side() < 0.0,
            "the two claws fall on the same side of the stride"
        );
    }

    /// A banking crab has to leave from exactly where it was last drawn
    /// and arrive at exactly the gate, and be off the ground in between,
    /// which is the only thing saying it went *over* rather than
    /// *through*.
    #[test]
    fn a_bank_starts_on_the_sand_and_finishes_in_the_gate() {
        let (from, to) = (Vec2::new(-120.0, 30.0), Vec2::new(64.0, 64.0));
        let (start, start_scale) = arc(from, to, 12.0, 0.0);
        assert_eq!(start, from);
        assert!((start_scale - 1.0).abs() < 1e-6, "full size on the sand");
        let (end, end_scale) = arc(from, to, 12.0, 1.0);
        assert!(end.distance(to) < 1e-3, "{end:?} vs {to:?}");
        assert!(end_scale < 0.35, "and all but gone: {end_scale}");
        let (middle, _) = arc(from, to, 12.0, 0.5);
        assert!(
            middle.y > from.lerp(to, 0.5).y,
            "off the ground in between: {middle:?}"
        );
    }

    /// A banking crab travels straight to the gate, never bowing sideways
    /// off it: a path that bowed would carry the crab over a wall on a
    /// corner-to-corner bank, through terrain it never touched.
    #[test]
    fn a_bank_travels_in_a_straight_line() {
        let (from, to) = (Vec2::new(0.0, 0.0), Vec2::new(400.0, 200.0));
        for step in 0..=10 {
            let (at, _) = arc(from, to, 12.0, step as f32 / 10.0);
            // Every point is on the segment once the lift is taken back
            // off: y is exactly half of x, which is what the two ends say.
            let lift = (step as f32 / 10.0 * std::f32::consts::PI).sin() * 12.0;
            assert!(
                (at.y - lift - at.x * 0.5).abs() < 1e-3,
                "bowed off the line at {step}: {at:?}"
            );
        }
    }

    /// A crab the tide throws corner to corner stays on the beach and over
    /// the fences the whole way, whichever of the two sweeps drew it.
    #[test]
    fn a_long_sweep_stays_under_the_cap_and_over_the_walls() {
        let (from, to) = (Vec2::new(-400.0, -300.0), Vec2::new(400.0, 300.0));
        for step in 0..=20 {
            let progress = step as f32 / 20.0;
            let (at, _) = sweep_arc(from, to, progress);
            let (flat, _) = arc(from, to, 0.0, progress);
            assert!(
                at.y - flat.y <= TILE * 1.2 + 1e-3,
                "too high at {step}: {at:?}"
            );
            assert!(at.z > layout::z::WALL, "under the fences at {step}");
        }
    }

    /// Trauma is a pool, not a queue: four raids in one frame must not
    /// throw the camera four times as far, and it has to drain to exactly
    /// zero rather than to a fraction that shakes for ever.
    #[test]
    fn trauma_is_capped_and_drains_away() {
        let mut trauma = Trauma::default();
        for _ in 0..8 {
            trauma.add(0.55);
        }
        assert_eq!(trauma.0, Trauma::MAX, "the pool has a ceiling");
        let thrown = trauma.offset(0.016, 0.4);
        assert!(thrown.length() > 0.0, "a full pool moves the camera");
        assert!(
            thrown.length() <= Trauma::THROW * std::f32::consts::SQRT_2,
            "and never further than the throw allows: {thrown:?}"
        );
        for _ in 0..200 {
            trauma.offset(0.016, 0.4);
        }
        assert_eq!(trauma.0, 0.0, "and it comes to rest");
        assert_eq!(trauma.offset(0.016, 0.4), Vec2::ZERO);
    }
}