bevy_flora 0.46.0

Parametric, stylized procedural trees and shrubs for Bevy that grow over time: 20 presets, bent and forking branches, CC0 bark and leaf scans, painterly and toon looks, deterministic per seed.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
//! Felling: a cut tree falls, lands with a bounce and leaves a stump.
//!
//! Insert [`FellTree`] on a tree ([`ProceduralTree`], or a [`PooledTree`], which first becomes
//! the `ProceduralTree` of its variant). Once the tree is built, the plugin cuts its wood at
//! `cut_height`: the part below becomes a [`TreeStump`] entity, the part above falls with the
//! tree, and both get a cut face (an end-grain disc). The tree then tips over toward `direction`
//! as a rod hinged at the front of the cut would, comes to rest where its limbs first touch the
//! ground (twigs and leaves give way), and bounces a little; [`TreeLanded`] is sent the moment
//! it hits, and [`Felled`] says how far it has tipped and when it lies still. The ground is flat
//! at the height the tree stands at, unless a [`FloraGround`] resource says otherwise: then the
//! cut is measured from the uphill side of the trunk and the tree lands on the terrain, down a
//! slope or against it.
//!
//! Once it lands a felled tree stops swaying in the wind (its leaves still flutter). It is no
//! longer rebuilt when its [`ProceduralTree`] or [`TreeAge`] changes, and keeps its entity:
//! despawn it, or insert [`BuckTree`] to cut its trunk into [`TreeLog`]s lying on the ground,
//! once it has landed. Its [`TreeShape`](crate::TreeShape) turns with it but is not cut.
//!
//! Before it falls, a tree can be notched: a [`TreeNotch`] carves an axe's wedge out of its
//! trunk, deeper with each blow, and a tree felled with one is cut at the notch's floor.

use std::sync::Arc;

use bevy::asset::{Assets, Handle};
use bevy::camera::visibility::{Visibility, VisibilityRange};
use bevy::ecs::prelude::*;
use bevy::image::Image;
use bevy::math::{Quat, Vec2, Vec3, Vec3Swizzles};
use bevy::mesh::{Mesh, Mesh3d};
use bevy::pbr::{MeshMaterial3d, StandardMaterial};
use bevy::reflect::Reflect;
use bevy::time::Time;
use bevy::transform::components::Transform;

use crate::gpu::GpuGrowth;
use crate::ground::FloraGround;
use crate::mesh::MeshData;
use crate::mesh::cut::{Notch, carve_notch, cut, fell_notched};
use crate::mesh::branch::{bark_tile, prism_sides, skeleton_mesh};
use crate::mesh::trunk::{trunk_mesh_with, trunk_pieces};
use crate::pipeline::{aged_skeleton, build_aged};
use crate::plugin::{CoarseLevel, Growing, Paint, ProceduralTree, TreeAge, TreeRender, paint_child};
use crate::shape::WoodCapsule;
use crate::pool::{PoolColors, PoolRecolors, PooledLook, PooledShapeFilled, PooledTree, PooledTreeSpawned, TreePool};
use crate::recolor::{CutWood, FromPool, TreeColors};
use crate::shading::{FloraMaterial, FloraWindBuffer, SharedFlora, TextureLibrary, TreeShake, TreeShakes};
use crate::params::TreeParams;
use crate::skeleton::{NodeKind, Skeleton, trunk_wobble};
use crate::units::FloraUnits;

/// Fell this tree: insert it on a [`ProceduralTree`] or a [`PooledTree`]. See the
/// [module docs](self).
#[derive(Component, Clone, Copy, Debug, PartialEq, Reflect)]
#[reflect(Component)]
pub struct FellTree {
    /// Which way the tree falls, world x and z; normalised when used. Zero falls along +x.
    pub direction: Vec2,
    /// Where the saw goes in, in metres above the tree's base (at least 5 cm, at most half the
    /// trunk); with a [`FloraGround`], above the ground on the uphill side of the trunk. Metres:
    /// [`FloraUnits`] scales it (and the 5 cm) to the world.
    pub cut_height: f32,
    /// How fast it falls: 1 as a real tree of its height would (a 15 m tree takes about four
    /// seconds from the first lean to the ground), 2 twice as fast.
    pub speed: f32,
    /// Lay it down at once where it would come to rest, with no fall and no landing (no
    /// [`TreeLanded`], no shake, no leaves shed): a tree felled before a save, restored. Its
    /// stump, its cut faces and the ground it lies on are as a fallen tree's; [`BuckTree`] cuts it
    /// into logs as soon as it lies.
    pub lying: bool,
}

impl Default for FellTree {
    fn default() -> Self {
        Self { direction: Vec2::X, cut_height: 0.5, speed: 1.0, lying: false }
    }
}

/// A tree that has been cut, added by the plugin in place of [`FellTree`]: falling, then lying
/// on the ground.
#[derive(Component, Clone, Debug, Reflect)]
#[reflect(Component)]
pub struct Felled {
    /// The stump it left.
    pub stump: Entity,
    /// How far it has tipped from upright, in radians.
    pub angle: f32,
    /// True once it lies still.
    pub at_rest: bool,
    #[reflect(ignore)]
    fall: Fall,
}

impl Felled {
    /// Whether it has hit the ground: its children wear the materials that do not sway.
    pub(crate) fn landed(&self) -> bool {
        self.fall.landed
    }

    /// Change the materials it takes on landing (`trunk` is the entity of its wood; the rest are
    /// leaves), for a recolouring while it still falls.
    pub(crate) fn restyle_still(&mut self, trunk: Entity, wood: &Handle<FloraMaterial>, leaves: &Handle<FloraMaterial>) {
        for (child, material) in &mut self.fall.still {
            *material = if *child == trunk { wood.clone() } else { leaves.clone() };
        }
    }

    /// The height of its cut, in the tree's own space: the wood below it is the stump's.
    pub(crate) fn cut_y(&self) -> f32 {
        self.fall.hinge.y
    }
}

/// The stump a felled tree left: the wood below the cut and its cut face, where the tree stood.
#[derive(Component, Clone, Copy, Debug, PartialEq, Reflect)]
#[reflect(Component)]
pub struct TreeStump {
    /// The tree that was cut from it: `None` for a pooled stump ([`PooledDeadfall`](crate::PooledDeadfall)),
    /// which no tree was cut from.
    pub tree: Option<Entity>,
    /// The stump as a capsule in its own space, from its foot to the middle of its cut, with the
    /// trunk's radius at the cut: a collider for it (`WoodCapsule::to_primitive`), and what
    /// [`FloraIndex::obstacles_within`](crate::FloraIndex::obstacles_within) finds.
    #[reflect(ignore)]
    pub capsule: WoodCapsule,
}

/// Sent the frame a felled tree first hits the ground: the moment for the crash, the dust and
/// the camera shake.
#[derive(Message, Clone, Copy, Debug, PartialEq)]
pub struct TreeLanded {
    /// The tree.
    pub tree: Entity,
    /// Its stump.
    pub stump: Entity,
    /// Where it first touched the ground, in world space.
    pub at: Vec3,
}

/// Buck a felled tree: cut its trunk into logs. Insert it on a tree that is being felled or has
/// been ([`FellTree`], [`Felled`]); once it lies still the plugin replaces it with [`TreeLog`]
/// entities lying on the ground in a row from the stump, the way it fell (on the
/// [`FloraGround`] if there is one), sends [`TreeBucked`], and despawns the tree with its crown.
#[derive(Component, Clone, Copy, Debug, PartialEq, Reflect)]
#[reflect(Component)]
pub struct BuckTree {
    /// The length of each log, metres ([`FloraUnits`] scales it to the world). The trunk above the
    /// last whole log stays with the crown.
    pub log_length: f32,
    /// The thinnest a log's top end may be, metres ([`FloraUnits`] scales it to the world): the
    /// trunk above it is too thin for logs.
    pub min_radius: f32,
}

impl Default for BuckTree {
    fn default() -> Self {
        Self { log_length: 2.0, min_radius: 0.08 }
    }
}

/// A log bucked from a felled tree's trunk: bark around it and end grain at both ends, lying on
/// the ground. Its children are the wood and the two end faces.
#[derive(Component, Clone, Copy, Debug, PartialEq, Reflect)]
#[reflect(Component)]
pub struct TreeLog {
    /// The stump of the tree it was cut from.
    pub stump: Entity,
    /// 0 for the butt log, counting up the trunk.
    pub index: u32,
    /// The log as a capsule in its own space, from the butt end to the top end, with the butt
    /// end's radius: a collider for it (`WoodCapsule::to_primitive`).
    #[reflect(ignore)]
    pub capsule: WoodCapsule,
}

/// Sent the frame a felled tree is bucked: its entity has been despawned and its logs spawned.
#[derive(Message, Clone, Debug, PartialEq)]
pub struct TreeBucked {
    /// The tree, now despawned.
    pub tree: Entity,
    /// Its stump.
    pub stump: Entity,
    /// Its logs, butt first; empty when the trunk above the cut is shorter than a log.
    pub logs: Vec<Entity>,
}

/// The material of every cut face, stumps, felled trees and logs: the end-grain picture, made
/// the first time a tree is cut, and its unlit twin for trees in an unlit look
/// ([`PoolColors::unlit`](crate::PoolColors::unlit)).
#[derive(Resource, Default)]
pub(crate) struct CutFace {
    lit: Option<Handle<StandardMaterial>>,
    unlit: Option<Handle<StandardMaterial>>,
}

impl CutFace {
    pub(crate) fn get(
        &mut self,
        textures: &mut TextureLibrary,
        materials: &mut Assets<StandardMaterial>,
        unlit: bool,
    ) -> Handle<StandardMaterial> {
        let slot = if unlit { &mut self.unlit } else { &mut self.lit };
        slot.get_or_insert_with(|| {
            let grain = textures.end_grain();
            materials.add(StandardMaterial {
                base_color: if grain.is_some() { bevy::color::Color::WHITE } else { END_GRAIN_COLOR },
                base_color_texture: grain,
                perceptual_roughness: 0.85,
                unlit,
                ..Default::default()
            })
        })
        .clone()
    }

    /// Whether `handle` is one of the cut face materials.
    pub(crate) fn is_face(&self, handle: &Handle<StandardMaterial>) -> bool {
        self.lit.as_ref() == Some(handle) || self.unlit.as_ref() == Some(handle)
    }
}

/// An axe's notch in a standing tree: a wedge cut out of its trunk on the side `direction`
/// points to, its floor level `height` above the base and its face rising from the floor at 45°,
/// `depth` of the way through. Insert it on a [`ProceduralTree`] or a [`PooledTree`] (which first
/// becomes the `ProceduralTree` of its variant, as for [`FellTree`]), and deepen it blow by blow:
/// each change of `depth` carves the trunk again. Remove it and the trunk is whole again.
///
/// A notched tree stops growing ([`Growing`] is removed; a change of its [`TreeAge`] or
/// [`ProceduralTree`] rebuilds it, notch and all). With [`TreeLod`](crate::TreeLod) only its
/// nearest level is notched. Fell it ([`FellTree`]) and the saw goes in at the notch's floor,
/// whatever `cut_height` says: the stump keeps the floor, the falling tree the face. A real feller
/// cuts the notch on the side the tree should fall to, a quarter to a third of the way through.
#[derive(Component, Clone, Copy, Debug, PartialEq, Reflect)]
#[reflect(Component)]
pub struct TreeNotch {
    /// The side it is cut from, world x and z; normalised when used. Zero is +x.
    pub direction: Vec2,
    /// The height of its floor, metres above the tree's base (at least 5 cm, at most half the
    /// trunk; [`FloraUnits`] scales it to the world); with a [`FloraGround`], above the ground on
    /// the uphill side of the trunk, as [`FellTree::cut_height`].
    pub height: f32,
    /// How far into the trunk it reaches at its floor, a share of the trunk's width there: 0
    /// cuts nothing, 0.25 is a felling notch, 0.9 the most.
    pub depth: f32,
}

impl Default for TreeNotch {
    fn default() -> Self {
        Self { direction: Vec2::X, height: 0.5, depth: 0.25 }
    }
}

/// The notch a tree's wood was carved with, and the child drawing its faces.
#[derive(Component)]
pub(crate) struct NotchCarved {
    notch: TreeNotch,
    faces: Option<Entity>,
}

/// How a felled tree moves, in its own (local) space.
#[derive(Clone, Debug, Default)]
struct Fall {
    /// Its transform before it was cut.
    base: Transform,
    /// The front edge of the cut, which it turns about.
    hinge: Vec3,
    /// The axis it turns about (through `hinge`).
    axis: Vec3,
    /// The angle at which it first touches the ground, and the point that touches.
    rest: f32,
    contact: Vec3,
    /// `3 g / 2 L` times the square of the speed: a rod of length `L` hinged at its foot.
    pull: f32,
    /// Angular speed, radians a second.
    spin: f32,
    landed: bool,
    /// Laid down at once ([`FellTree::lying`]).
    lying: bool,
    /// How far the crown reaches from the trunk, for the shake it gives its neighbours.
    crown_radius: f32,
    /// Its wood and leaves, and the materials they take once it lands (they do not sway).
    still: Vec<(Entity, Handle<FloraMaterial>)>,
}

/// How much of its speed a tree keeps when it bounces off the ground.
const RESTITUTION: f32 = 0.25;
/// A bounce that would lift the tree less than this, in radians, is over: it lies still.
const SETTLE_RISE: f32 = 0.004;
/// The push the last stroke of the saw gives a cut tree, radians a second: from upright it
/// leans slowly, then gravity takes it.
const START_SPIN: f32 = 0.08;
/// Integration step, seconds.
const STEP: f32 = 1.0 / 240.0;
/// Gravity, metres per second squared; times [`FloraUnits`] in the world.
const GRAVITY: f32 = 9.81;
/// Limbs at least this share of the trunk's radius at the cut, and at least [`CONTACT_RADIUS`]
/// (metres), stop a falling tree; thinner branches, twigs and the leaves give way and may end
/// below the ground, as a crown crushed into it. A conifer's whorls of thin limbs do not prop it
/// up at a slant.
const CONTACT_SHARE: f32 = 0.15;
const CONTACT_RADIUS: f32 = 0.04;
/// The furthest a felled tree turns, from upright: on flat ground its trunk meets the ground
/// before 105°; down a steep slope it can lie along it, well past 90°.
const REST_LIMIT: f32 = 150.0 * std::f32::consts::PI / 180.0;
/// The gap between bucked logs laid in a row, and between the first and the stump, metres (times
/// [`FloraUnits`] in the world): enough that the row reads as separate logs, and their end grain
/// shows between them.
pub(crate) const LOG_GAP: f32 = 0.15;

/// Start felling every tree with a [`FellTree`] that can be cut: turn a pooled tree into its
/// `ProceduralTree`, move a tree off the GPU growth path, then cut (at its [`TreeNotch`]'s
/// floor, if it has one), spawn the stump and set up the fall.
#[allow(clippy::type_complexity, clippy::too_many_arguments)]
pub(crate) fn start_felling(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut flora: ResMut<Assets<FloraMaterial>>,
    mut shared: ResMut<SharedFlora>,
    mut textures: TextureLibrary,
    wind: Option<Res<FloraWindBuffer>>,
    pools: Option<Res<Assets<TreePool>>>,
    recolors: Res<PoolRecolors>,
    ground: Option<Res<FloraGround>>,
    units: Res<FloraUnits>,
    mut cut_face: ResMut<CutFace>,
    trees: Query<(
        Entity,
        &FellTree,
        &Transform,
        Option<&ProceduralTree>,
        Option<&TreeAge>,
        Option<&TreeRender>,
        Option<&PooledTree>,
        Has<GpuGrowth>,
        Has<Growing>,
        Option<&TreeNotch>,
        Option<&NotchCarved>,
        Option<&PooledLook>,
        Option<&TreeColors>,
        Option<&FromPool>,
    )>,
) {
    for (entity, fell, transform, tree, age, render, pooled, gpu, growing, notch, carved, look, colors, from) in &trees {
        if let Some(pooled) = pooled {
            let Some(pool) = pools.as_deref().and_then(|pools| pools.get(&pooled.pool)) else { continue };
            let (params, colors) = pooled_to_tree(pool, pooled, look, &recolors);
            commands
                .entity(entity)
                .despawn_related::<Children>()
                .remove::<(PooledTree, PooledTreeSpawned, PooledShapeFilled, PooledLook)>()
                .insert((ProceduralTree(params), TreeAge(pool.age), TreeColors(colors), from_pool(pool, pooled, look)));
            continue;
        }
        let Some(tree) = tree else { continue };
        if growing {
            commands.entity(entity).remove::<Growing>();
        }
        if gpu {
            commands.entity(entity).remove::<GpuGrowth>();
            continue;
        }
        // Wait for the tree's meshes, rebuilt on the CPU.
        let Some(render) = render else { continue };
        let Some(paint) = render.paint.cloned_cpu() else { continue };
        let age = age.map_or(f32::INFINITY, |age| age.0);
        let built = build_aged(&render.full, &tree.0, age);
        if built.trunk.is_empty() {
            commands.entity(entity).remove::<FellTree>();
            continue;
        }
        // A tree drawn at levels of detail falls in full: its coarse levels go, and its own
        // children are drawn at every distance.
        if let Some((_, levels)) = &render.lod {
            for child in levels.iter().flat_map(CoarseLevel::children) {
                commands.entity(child).despawn();
            }
            let level0 = render.foliage.iter().chain(&render.flowers).map(|child| child.0);
            for child in std::iter::once(render.trunk).chain(level0) {
                commands.entity(child).remove::<(VisibilityRange, crate::pool::LodBand)>();
            }
        }

        let scale = transform.scale.y.max(1.0e-4);
        // A notched tree is cut at the notch's floor; on a slope the saw goes in above the uphill
        // side of the trunk.
        let notch = notch.and_then(|notch| notch_in(&built.trunk, notch, transform, &tree.0, ground.as_deref(), units.units_per_metre));
        let cut_y = notch
            .map_or_else(|| saw_height(transform, &tree.0, ground.as_deref(), fell.cut_height, units.units_per_metre), |n| n.floor);
        let above = cut(&built.trunk, cut_y, true);
        let below = cut(&built.trunk, cut_y, false);
        let unlit = colors.is_some_and(|colors| colors.0.unlit);
        let painted = colors.map_or_else(|| tree.0.clone(), |colors| colors.0.apply(&tree.0));
        let face = cut_face.get(&mut textures, &mut materials, unlit);

        // The stump: the wood below the cut and its face, where the tree stands.
        let cut_wood = CutWood { params: Arc::new(painted.clone()), unlit, calm: false };
        let (centre, radius) = log_end(&above.outlines).unwrap_or((Vec3::new(0.0, cut_y, 0.0), tree.0.trunk.radius));
        let capsule = WoodCapsule { a: Vec3::new(centre.x, 0.0, centre.z), b: Vec3::new(centre.x, cut_y, centre.z), radius };
        let stump = commands.spawn((*transform, Visibility::Inherited, TreeStump { tree: Some(entity), capsule }, cut_wood)).id();
        if let Some(from) = from {
            commands.entity(stump).insert(*from);
        }
        let mut wood = commands.spawn((Mesh3d(meshes.add(below.kept.into_bevy_mesh())), ChildOf(stump)));
        paint_child(&mut wood, &paint, false);
        if !below.faces.is_empty() {
            commands.spawn((Mesh3d(meshes.add(below.faces.into_bevy_mesh())), MeshMaterial3d(face.clone()), ChildOf(stump)));
        }

        // How it will fall: about the front edge of the cut, until its limbs reach the ground.
        let local_dir = fall_direction(transform, fell.direction);
        let (hinge, trunk_reach) = hinge_point(&above.outlines, cut_y, local_dir);
        let axis = Vec3::Y.cross(local_dir).normalize();
        // How far a point of the tree, in its own space, stands above the ground.
        let clearance = |p: Vec3| match ground.as_deref() {
            None => p.y,
            Some(ground) => {
                let world = transform.transform_point(p);
                (world.y - ground.height(world.xz())) / scale
            }
        };
        // The tree keeps the wood above the cut and gains its faces: with a notch, less the
        // notch's wedge, with its face and the cut behind it.
        let (wood, faces) = match &notch {
            Some(notch) => fell_notched(&above, notch),
            None => (above.kept, above.faces),
        };
        let contact_set = contact_points(&wood, &built.skeleton, &tree.0, cut_y, trunk_reach);
        let (rest, contact) = rest_angle(&contact_set, hinge, axis, clearance);
        let length = wood.positions.iter().map(|p| (*p - hinge).length()).fold(trunk_reach, f32::max) * scale;
        let crown = built.foliage.positions.iter().chain(&built.flowers.positions);
        let crown_radius = crown.map(|p| Vec2::new(p.x, p.z).length()).fold(0.0, f32::max) * scale;
        commands.entity(render.trunk).insert((Mesh3d(meshes.add(wood.into_bevy_mesh())), Visibility::Inherited));
        if !faces.is_empty() {
            commands.spawn((Mesh3d(meshes.add(faces.into_bevy_mesh())), MeshMaterial3d(face), ChildOf(entity)));
        }
        if let Some(carved) = carved {
            if let Some(faces) = carved.faces {
                commands.entity(faces).despawn();
            }
            commands.entity(entity).remove::<NotchCarved>();
        }
        // Materials that do not sway, for when it lies on the ground: while it falls the wind
        // still moves it as it did (a change there would show).
        let mut still = Vec::new();
        if let (Paint::Flora { .. }, Some(wind)) = (&paint, wind.as_deref()) {
            let calm = calm_params(&painted);
            still.push((render.trunk, shared.resolve(&mut flora, &textures.wood(&calm).with_unlit(unlit), wind)));
            if render.foliage.is_some() {
                let leaves = shared.resolve(&mut flora, &textures.leaves(&calm).with_unlit(unlit), wind);
                for (child, _) in render.foliage.iter().chain(&render.flowers) {
                    still.push((*child, leaves.clone()));
                }
            }
        }
        let speed = fell.speed.max(0.01);
        commands.entity(entity).remove::<FellTree>().insert(Felled {
            stump,
            angle: 0.0,
            at_rest: false,
            fall: Fall {
                base: *transform,
                hinge,
                axis,
                rest,
                contact,
                pull: 1.5 * GRAVITY * units.units_per_metre / length.max(0.5 * units.units_per_metre) * speed * speed,
                spin: START_SPIN * speed,
                landed: false,
                lying: fell.lying,
                crown_radius,
                still,
            },
        });
    }
}

/// Carve every [`TreeNotch`] into its tree's wood when it changes or the tree is rebuilt (turning
/// a pooled tree into its `ProceduralTree` and moving a tree off the GPU growth path first, as
/// felling does), and make the wood of a tree whose notch was removed whole again.
#[allow(clippy::type_complexity, clippy::too_many_arguments)]
pub(crate) fn carve_notches(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut textures: TextureLibrary,
    pools: Option<Res<Assets<TreePool>>>,
    recolors: Res<PoolRecolors>,
    ground: Option<Res<FloraGround>>,
    units: Res<FloraUnits>,
    mut cut_face: ResMut<CutFace>,
    trees: Query<
        (
            Entity,
            &TreeNotch,
            &Transform,
            Option<&ProceduralTree>,
            Option<Ref<TreeRender>>,
            Option<&PooledTree>,
            Has<GpuGrowth>,
            Has<Growing>,
            Option<&NotchCarved>,
            Option<&PooledLook>,
            Option<&TreeColors>,
        ),
        (Without<Felled>, Without<FellTree>),
    >,
    healed: Query<(Entity, &NotchCarved, &ProceduralTree, &TreeRender), (Without<TreeNotch>, Without<Felled>)>,
) {
    for (entity, notch, transform, tree, render, pooled, gpu, growing, carved, look, colors) in &trees {
        if let Some(pooled) = pooled {
            let Some(pool) = pools.as_deref().and_then(|pools| pools.get(&pooled.pool)) else { continue };
            let (params, colors) = pooled_to_tree(pool, pooled, look, &recolors);
            commands
                .entity(entity)
                .despawn_related::<Children>()
                .remove::<(PooledTree, PooledTreeSpawned, PooledShapeFilled, PooledLook)>()
                .insert((ProceduralTree(params), TreeAge(pool.age), TreeColors(colors), from_pool(pool, pooled, look)));
            continue;
        }
        let Some(tree) = tree else { continue };
        if growing {
            commands.entity(entity).remove::<Growing>();
        }
        if gpu {
            commands.entity(entity).remove::<GpuGrowth>();
            continue;
        }
        // Wait for the tree's meshes, rebuilt on the CPU; carve again when they are rebuilt.
        let Some(render) = render else { continue };
        if render.paint.cloned_cpu().is_none() || (carved.is_some_and(|c| c.notch == *notch) && !render.is_changed()) {
            continue;
        }
        let Some(handle) = &render.trunk_mesh else { continue };
        let wood = skeleton_mesh(&aged_skeleton(&render.full, &tree.0, render.age), &tree.0);
        let (wood, faces) = match notch_in(&wood, notch, transform, &tree.0, ground.as_deref(), units.units_per_metre) {
            Some(cut) => carve_notch(&wood, &cut),
            None => (wood, MeshData::default()),
        };
        if let Some(mut mesh) = meshes.get_mut(handle) {
            *mesh = wood.into_bevy_mesh();
        }
        let mut drawn = carved.and_then(|c| c.faces);
        match (drawn, faces.is_empty()) {
            (Some(child), true) => {
                commands.entity(child).despawn();
                drawn = None;
            }
            (Some(child), false) => {
                commands.entity(child).insert(Mesh3d(meshes.add(faces.into_bevy_mesh())));
            }
            (None, false) => {
                let face = cut_face.get(&mut textures, &mut materials, colors.is_some_and(|colors| colors.0.unlit));
                let mesh = Mesh3d(meshes.add(faces.into_bevy_mesh()));
                drawn = Some(commands.spawn((mesh, MeshMaterial3d(face), ChildOf(entity))).id());
            }
            (None, true) => {}
        }
        commands.entity(entity).insert(NotchCarved { notch: *notch, faces: drawn });
    }
    for (entity, carved, tree, render) in &healed {
        if let Some(mut mesh) = render.trunk_mesh.as_ref().and_then(|handle| meshes.get_mut(handle)) {
            *mesh = skeleton_mesh(&aged_skeleton(&render.full, &tree.0, render.age), &tree.0).into_bevy_mesh();
        }
        if let Some(faces) = carved.faces {
            commands.entity(faces).despawn();
        }
        commands.entity(entity).remove::<NotchCarved>();
    }
}

/// What a pooled tree becomes when it is cut or notched: its variant's parameters painted in the
/// colours of its look as they stand now ([`TreePool::tree_params_for`], then any
/// [`RecolorPool`](crate::RecolorPool) since), and those colours, which the tree keeps as
/// [`TreeColors`] (for an unlit look, and for later rebuilds).
fn pooled_to_tree(
    pool: &TreePool,
    pooled: &PooledTree,
    look: Option<&PooledLook>,
    recolors: &PoolRecolors,
) -> (TreeParams, PoolColors) {
    let look = look.map_or(0, |look| look.0);
    let colors = recolors.colors(pooled.pool.id(), look, pool);
    (colors.apply(&pool.tree_params_for(pooled.variant, look)), colors)
}

/// The pool and look (taken modulo the pool's looks) a pooled tree leaves when it is cut or
/// notched.
fn from_pool(pool: &TreePool, pooled: &PooledTree, look: Option<&PooledLook>) -> FromPool {
    FromPool { pool: pooled.pool.id(), look: look.map_or(0, |look| look.0) % pool.looks.len().max(1) as u32 }
}

/// `params` of a tree that does not sway in the wind: what a felled tree lying on the ground has.
pub(crate) fn calm_params(params: &TreeParams) -> TreeParams {
    TreeParams { wind: crate::WindResponse { sway: 0.0, ..params.wind.clone() }, ..params.clone() }
}

/// How high the saw or the axe goes in, in a tree's own space: `height` metres above its base
/// (at least 5 cm, at most half its trunk), or with `ground` above the ground on the uphill side
/// of its trunk. `units` is the world units to a metre ([`FloraUnits`]): `height` and the 5 cm are
/// metres, the tree's `transform` and the ground are the world's.
pub(crate) fn saw_height(transform: &Transform, params: &TreeParams, ground: Option<&FloraGround>, height: f32, units: f32) -> f32 {
    let scale = transform.scale.y.max(1.0e-4);
    let uphill = ground.map_or(0.0, |ground| {
        let top = ground.top(transform.translation.xz(), params.base_radius() * scale);
        (top - transform.translation.y).max(0.0) / scale
    });
    // A trunk shorter than 0.1 m (the fern) is cut at most half way up, whatever the least cut says.
    let most = params.trunk.height * 0.5;
    (uphill + height * units / scale).clamp((0.05 * units / scale).min(most), most)
}

/// Where `notch` cuts into `wood`, the wood of a tree of `params` standing at `transform`, in its
/// own space; `None` where it cuts nothing (no depth, or no trunk at its floor). `units`: world
/// units to a metre ([`FloraUnits`]).
fn notch_in(
    wood: &MeshData,
    notch: &TreeNotch,
    transform: &Transform,
    params: &TreeParams,
    ground: Option<&FloraGround>,
    units: f32,
) -> Option<Notch> {
    let depth = notch.depth.min(0.9);
    if depth.is_nan() || depth <= 0.0 {
        return None;
    }
    let floor = saw_height(transform, params, ground, notch.height, units);
    let level = cut(wood, floor, false);
    // The trunk's outline: the one round the tree's base, not a hanging limb's.
    let centre_of = |o: &[Vec3]| o.iter().copied().sum::<Vec3>() / o.len() as f32;
    let trunk = level.outlines.iter().min_by(|a, b| centre_of(a).xz().length().total_cmp(&centre_of(b).xz().length()))?;
    let centre = centre_of(trunk);
    let toward = fall_direction(transform, notch.direction);
    let front = trunk.iter().map(|p| (*p - centre).dot(toward)).fold(0.0, f32::max);
    let back = trunk.iter().map(|p| (centre - *p).dot(toward)).fold(0.0, f32::max);
    let inner = front - depth * (front + back);
    // The face rises at 45° and leaves the trunk `front - inner` above the floor; the carving
    // stops well clear of that, above and beyond.
    let rise = front - inner;
    let margin = 0.05 * units / transform.scale.y.max(1.0e-4);
    Some(Notch {
        floor,
        mouth: floor + 1.5 * rise + margin,
        axis: centre.xz(),
        toward: toward.xz(),
        inner,
        outer: front + 0.5 * rise + margin,
        radius: trunk.iter().map(|p| p.distance(centre)).fold(0.0, f32::max),
        slope: 1.0,
    })
}

/// Tip every falling tree over, a few small steps a frame, and settle it where it lands.
pub(crate) fn drive_felling(
    mut commands: Commands,
    time: Res<Time>,
    mut shakes: ResMut<TreeShakes>,
    units: Res<FloraUnits>,
    mut landed: MessageWriter<TreeLanded>,
    mut trees: Query<(Entity, &mut Felled, &mut Transform)>,
) {
    let dt = time.delta_secs();
    for (entity, mut felled, mut transform) in &mut trees {
        if felled.at_rest {
            continue;
        }
        let felled = &mut *felled;
        let fall = &mut felled.fall;
        // A tree restored lying: at once where it would come to rest, on its still materials,
        // with no landing.
        if fall.lying {
            felled.angle = fall.rest;
            fall.landed = true;
            fall.spin = 0.0;
            felled.at_rest = true;
            for (child, material) in fall.still.drain(..) {
                commands.entity(child).insert(MeshMaterial3d(material));
            }
        }
        let mut left = dt;
        while left > 0.0 && !felled.at_rest {
            let h = left.min(STEP);
            left -= h;
            fall.spin += fall.pull * felled.angle.sin() * h;
            felled.angle += fall.spin * h;
            if felled.angle >= fall.rest && fall.spin > 0.0 {
                felled.angle = fall.rest;
                if !fall.landed {
                    fall.landed = true;
                    let resting = fall.base.mul_transform(pivot(fall, fall.rest));
                    let at = resting.transform_point(fall.contact);
                    landed.write(TreeLanded { tree: entity, stump: felled.stump, at });
                    // On the ground it stops swaying with the wind; the crash hides the change.
                    for (child, material) in fall.still.drain(..) {
                        commands.entity(child).insert(MeshMaterial3d(material));
                    }
                    // Its own leaves shake on the ground (it no longer sways), and the crowns it
                    // crashed through swing.
                    let own = TreeShake { at: resting.translation.xz(), radius: 0.5, strength: 2.0, duration: 2.0, ..Default::default() };
                    shakes.shake(own, &time);
                    let crash = TreeShake {
                        at: at.xz(),
                        // A shake's radius is metres; the crown's reach is world units.
                        radius: units.metres(fall.crown_radius).max(2.0),
                        strength: 1.2,
                        duration: 2.5,
                        ..Default::default()
                    };
                    shakes.shake(crash, &time);
                }
                fall.spin *= -RESTITUTION;
                // How far the bounce would lift it back against gravity; a small or quick tree
                // falls back within a step, so its speed alone never gets small.
                let rise = fall.spin * fall.spin / (2.0 * fall.pull * fall.rest.sin().max(0.05));
                if rise < SETTLE_RISE {
                    fall.spin = 0.0;
                    felled.at_rest = true;
                }
            }
        }
        *transform = fall.base.mul_transform(pivot(fall, felled.angle));
    }
}

/// Turning by `angle` about the fall's hinge, in the tree's own space.
fn pivot(fall: &Fall, angle: f32) -> Transform {
    let turn = Quat::from_axis_angle(fall.axis, angle);
    Transform::from_translation(fall.hinge - turn * fall.hinge).with_rotation(turn)
}

/// Buck every felled tree with a [`BuckTree`] once it lies still: cut its trunk into logs, lay
/// them on the ground in a row from the stump, the way it fell, and clear the tree.
#[allow(clippy::type_complexity, clippy::too_many_arguments)]
pub(crate) fn buck_trees(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut textures: TextureLibrary,
    mut cut_face: ResMut<CutFace>,
    ground: Option<Res<FloraGround>>,
    units: Res<FloraUnits>,
    mut bucked: MessageWriter<TreeBucked>,
    trees: Query<(
        Entity,
        &BuckTree,
        &Felled,
        &Transform,
        &ProceduralTree,
        Option<&TreeAge>,
        &TreeRender,
        Option<&TreeColors>,
        Option<&FromPool>,
    )>,
    flora_wood: Query<&MeshMaterial3d<FloraMaterial>>,
    plain_wood: Query<&MeshMaterial3d<StandardMaterial>>,
) {
    for (entity, buck, felled, lying, tree, age, render, colors, from) in &trees {
        if !felled.at_rest {
            continue;
        }
        let fall = &felled.fall;
        let params = &tree.0;
        // The trunk alone, as the tree had it: the same rings and bark.
        let skeleton = aged_skeleton(&render.full, params, age.map_or(f32::INFINITY, |age| age.0));
        let node = &skeleton.nodes[0];
        let trunk = trunk_alone(params, node);
        let top = trunk.positions.iter().map(|p| p.y).fold(0.0, f32::max);
        let unlit = colors.is_some_and(|colors| colors.0.unlit);
        let face = cut_face.get(&mut textures, &mut materials, unlit);
        let painted = colors.map_or_else(|| tree.0.clone(), |colors| colors.0.apply(&tree.0));
        let cut_wood = CutWood { params: Arc::new(painted), unlit, calm: true };
        let scale = fall.base.scale.y.max(1.0e-4);
        // The ground's height at a point, and how much higher than its radius a log's axis lies
        // there (1 on flat ground, more on a slope).
        let rest = |p: Vec2| match ground.as_deref() {
            None => (fall.base.translation.y, 1.0),
            Some(ground) => (ground.height(p), 1.0 / ground.normal(p).y.max(0.2)),
        };
        // In a row from the stump's front edge, the way the tree fell.
        let up = lying.rotation * Vec3::Y;
        let along = Vec2::new(up.x, up.z).normalize_or(Vec2::X);
        let gap = LOG_GAP * units.units_per_metre;
        let mut at = fall.base.transform_point(fall.hinge).xz() + along * gap;
        let length = units.world(buck.log_length.max(0.1));
        let mut logs = Vec::new();
        let mut y0 = fall.hinge.y;
        while y0 + length / scale <= top {
            let y1 = y0 + length / scale;
            let lower = cut(&trunk, y0, true);
            let piece = cut(&lower.kept, y1, false);
            let (Some((c0, r0)), Some((c1, r1))) = (log_end(&lower.outlines), log_end(&piece.outlines)) else { break };
            if r1 * scale < units.world(buck.min_radius) {
                break;
            }
            // Its ends on the ground, a log's length apart along it.
            let place = lay_log(&fall.base, at, along, length, (c0, r0), (c1, r1), rest);

            let capsule = WoodCapsule { a: c0, b: c1, radius: r0 };
            let mut log = commands.spawn((
                place,
                Visibility::Inherited,
                TreeLog { stump: felled.stump, index: logs.len() as u32, capsule },
                cut_wood.clone(),
            ));
            if let Some(from) = from {
                log.insert(*from);
            }
            let log = log.id();
            let mut wood = commands.spawn((Mesh3d(meshes.add(piece.kept.into_bevy_mesh())), ChildOf(log)));
            if let Ok(material) = flora_wood.get(render.trunk) {
                wood.insert(material.clone());
            } else if let Ok(material) = plain_wood.get(render.trunk) {
                wood.insert(material.clone());
            }
            let mut ends = lower.faces;
            ends.extend(&piece.faces);
            if !ends.is_empty() {
                commands.spawn((Mesh3d(meshes.add(ends.into_bevy_mesh())), MeshMaterial3d(face.clone()), ChildOf(log)));
            }
            logs.push(log);
            // The next starts a gap past where this one ends (its taper turns it a little, so not
            // quite at `far`).
            at = place.transform_point(c1).xz() + along * gap;
            y0 = y1;
        }
        commands.entity(entity).despawn();
        bucked.write(TreeBucked { tree: entity, stump: felled.stump, logs });
    }
}

/// A tree's trunk node alone, as the tree has it: the same rings, wobble and bark, flat-shaded
/// for a prism trunk (no collars, branches or leaves).
pub(crate) fn trunk_alone(params: &TreeParams, node: &crate::skeleton::Node) -> MeshData {
    let mut trunk_params = params.trunk.clone();
    let prism = prism_sides(params);
    if let Some(sides) = prism {
        trunk_params.radial_segments = sides;
    }
    let pieces = trunk_pieces(&trunk_params, node);
    let trunk = trunk_mesh_with(&trunk_params, node, params.seed, pieces, bark_tile(params));
    if prism.is_some() { trunk.flat_shaded() } else { trunk }
}

/// Where a log of a tree standing as `base` (its own space: butt end centre and radius `(c0, r0)`,
/// top end `(c1, r1)`) lies on the ground: its butt end on the ground at `at` (world x, z), a
/// `length` (world metres) along `along` to its top end. `rest(p)` is the ground's height at `p`
/// and how much higher than a log's radius its axis lies there (1 on flat ground). The transform
/// of the log's entity.
pub(crate) fn lay_log(
    base: &Transform,
    at: Vec2,
    along: Vec2,
    length: f32,
    (c0, r0): (Vec3, f32),
    (c1, r1): (Vec3, f32),
    rest: impl Fn(Vec2) -> (f32, f32),
) -> Transform {
    let scale = base.scale.y.max(1.0e-4);
    let (g0, lift0) = rest(at);
    let rise = rest(at + along * length).0 - g0;
    let far = at + along * (length * length / (length * length + rise * rise).sqrt());
    let (g1, lift1) = rest(far);
    let e0 = Vec3::new(at.x, g0 + r0 * scale * lift0, at.y);
    let e1 = Vec3::new(far.x, g1 + r1 * scale * lift1, far.y);
    let axis = (base.rotation * (c1 - c0)).normalize_or(Vec3::Y);
    let rotation = Quat::from_rotation_arc(axis, (e1 - e0).normalize_or(axis)) * base.rotation;
    Transform { translation: e0 - rotation * (c0 * scale), rotation, scale: base.scale }
}

/// The centre of a log's end and the radius it rests on (the trunk's outline at a cut: its
/// centre, and its mean radius to the middle of its sides, so a polygonal log neither floats
/// on its corners nor sinks by more than them).
pub(crate) fn log_end(outlines: &[Vec<Vec3>]) -> Option<(Vec3, f32)> {
    let outline = outlines.iter().max_by_key(|o| o.len()).filter(|o| o.len() >= 3)?;
    // Only its corners: a flat-shaded trunk's cut has a point in the middle of each side too (where
    // the cut crosses the diagonal of the side's two triangles), which would pull the mean in.
    let n = outline.len();
    let corners: Vec<Vec3> = (0..n)
        .filter(|&i| {
            let (before, here, after) = (outline[(i + n - 1) % n], outline[i], outline[(i + 1) % n]);
            let (u, v) = (here - before, after - here);
            u.cross(v).length() > 0.035 * u.length() * v.length()
        })
        .map(|i| outline[i])
        .collect();
    let trunk = if corners.len() >= 3 { &corners } else { outline };
    let centre = trunk.iter().copied().sum::<Vec3>() / trunk.len() as f32;
    let radius = trunk.iter().map(|p| p.distance(centre)).sum::<f32>() / trunk.len() as f32;
    Some((centre, radius * (std::f32::consts::PI / trunk.len() as f32).cos()))
}

/// `direction` (world x, z) in the tree's own horizontal plane, unit length.
pub(crate) fn fall_direction(transform: &Transform, direction: Vec2) -> Vec3 {
    let world = Vec3::new(direction.x, 0.0, direction.y).normalize_or(Vec3::X);
    let local = transform.rotation.inverse() * world;
    Vec3::new(local.x, 0.0, local.z).normalize_or(Vec3::X)
}

/// The front edge of the cut toward `direction`, which a falling tree turns about (the hinge
/// wood of a real felling cut), and how far it is from the trunk's centre.
pub(crate) fn hinge_point(outlines: &[Vec<Vec3>], cut_y: f32, direction: Vec3) -> (Vec3, f32) {
    // The trunk's outline is the one that encloses the most (a limb the cut crosses lengthwise has
    // more points, as a flat-shaded trunk has few, but encloses little).
    let area = |o: &Vec<Vec3>| {
        let twice: f32 = (0..o.len()).map(|i| (o[i].x * o[(i + 1) % o.len()].z) - (o[(i + 1) % o.len()].x * o[i].z)).sum();
        twice.abs()
    };
    let trunk = outlines.iter().max_by(|a, b| area(a).total_cmp(&area(b))).map(Vec::as_slice).unwrap_or(&[]);
    if trunk.is_empty() {
        return (Vec3::new(0.0, cut_y, 0.0), 0.0);
    }
    let centre = trunk.iter().copied().sum::<Vec3>() / trunk.len() as f32;
    let reach = trunk.iter().map(|p| (*p - centre).dot(direction)).fold(0.0, f32::max);
    (Vec3::new(centre.x, cut_y, centre.z) + direction * reach, reach)
}

/// The points of the wood above the cut that can hold a falling tree up: the trunk and leader
/// all along (sampled from `skeleton`), and the vertices of limbs at least [`CONTACT_SHARE`] as
/// thick as the trunk at the cut and [`CONTACT_RADIUS`] (`uv1.x` is a wood vertex's radius,
/// `trunk_radius` the trunk's at the cut, both in the tree's own units).
pub(crate) fn contact_points(wood: &MeshData, skeleton: &Skeleton, params: &TreeParams, cut_y: f32, trunk_radius: f32) -> Vec<Vec3> {
    let least = (trunk_radius * CONTACT_SHARE).max(CONTACT_RADIUS);
    let mut points: Vec<Vec3> =
        wood.positions.iter().zip(&wood.uv1).filter(|(_, uv1)| uv1.x >= least).map(|(p, _)| *p).collect();
    for node in skeleton.nodes.iter().filter(|n| matches!(n.kind, NodeKind::Trunk | NodeKind::Leader)) {
        let (side, up) = node.direction.any_orthonormal_pair();
        for i in 0..=48 {
            let t = i as f32 / 48.0;
            let mut centre = node.start + node.direction * (node.length * t);
            if node.kind == NodeKind::Trunk {
                // The trunk's mesh follows its wobble; the node's axis does not.
                let (x, z) = trunk_wobble(&params.trunk, params.seed, centre.y / params.trunk.height.max(1.0e-4));
                centre += Vec3::new(x, 0.0, z);
            }
            let radius = node.base_radius + (node.tip_radius - node.base_radius) * t;
            for k in 0..12 {
                let (sin, cos) = (k as f32 * std::f32::consts::TAU / 12.0).sin_cos();
                let p = centre + (side * cos + up * sin) * radius;
                if p.y >= cut_y {
                    points.push(p);
                }
            }
        }
    }
    if points.is_empty() { wood.positions.clone() } else { points }
}

/// The smallest angle, turning about `axis` through `hinge`, at which a point of `points` first
/// reaches the ground, and that point; [`REST_LIMIT`] if none does. `clearance(p)` is how far
/// `p` (in the tree's space) stands above the ground; points already below it before the fall
/// (a limb low on the uphill side of a slope) are left out, as they would plough through.
pub(crate) fn rest_angle(points: &[Vec3], hinge: Vec3, axis: Vec3, clearance: impl Fn(Vec3) -> f32) -> (f32, Vec3) {
    let points: Vec<Vec3> = points.iter().copied().filter(|p| clearance(*p) >= 0.0).collect();
    let lowest = |angle: f32, stride: usize| {
        let turn = Quat::from_axis_angle(axis, angle);
        points
            .iter()
            .step_by(stride)
            .map(|p| (*p, clearance(turn * (*p - hinge) + hinge)))
            .fold((hinge, f32::INFINITY), |best, (p, y)| if y < best.1 { (p, y) } else { best })
    };
    let stride = (points.len() / 6000).max(1);
    let step = 0.5f32.to_radians();
    let mut below = None;
    let mut angle = 0.0;
    while angle < REST_LIMIT {
        angle += step;
        if lowest(angle, stride).1 < 0.0 {
            below = Some(angle);
            break;
        }
    }
    let Some(mut high) = below else { return (REST_LIMIT, lowest(REST_LIMIT, 1).0) };
    let mut low = (high - step).max(0.0);
    for _ in 0..14 {
        let mid = 0.5 * (low + high);
        if lowest(mid, 1).1 < 0.0 {
            high = mid;
        } else {
            low = mid;
        }
    }
    (low, lowest(low, 1).0)
}

/// The colour of fresh-cut wood, for a cut face without the end-grain picture.
pub(crate) const END_GRAIN_COLOR: bevy::color::Color = bevy::color::Color::srgb(0.80, 0.66, 0.46);

/// The end-grain picture a cut face wears: pale sapwood, warmer heartwood, growth rings that
/// wander a little, a dark pith and a few checks, RGBA8 sRGB, `size` square.
fn end_grain_pixels(size: u32) -> Vec<u8> {
    let mut data = Vec::with_capacity((size * size * 4) as usize);
    let half = size as f32 / 2.0;
    for y in 0..size {
        for x in 0..size {
            let dx = (x as f32 + 0.5 - half) / half;
            let dz = (y as f32 + 0.5 - half) / half;
            let r = (dx * dx + dz * dz).sqrt();
            let theta = dz.atan2(dx);
            let wander = 0.012 * (3.0 * theta + 1.3).sin() + 0.008 * (7.0 * theta + 0.4).sin();
            let ring = ((r + wander) * 17.0).fract();
            let late = smoothstep(0.78, 0.95, ring) * (1.0 - smoothstep(0.95, 1.0, ring));
            let sapwood = Vec3::new(225.0, 199.0, 152.0);
            let heartwood = Vec3::new(201.0, 156.0, 104.0);
            let mut colour = heartwood.lerp(sapwood, smoothstep(0.45, 0.7, r));
            colour *= 1.0 - 0.18 * late;
            // The pith, and a few checks running out from it.
            colour *= 0.55 + 0.45 * smoothstep(0.02, 0.06, r);
            let check = [0.4f32, 2.3, 4.4]
                .iter()
                .map(|&a| {
                    let off = (theta - a).sin().abs() * r;
                    let facing = if (theta - a).cos() > 0.0 { 1.0 } else { 0.0 };
                    facing * (1.0 - smoothstep(0.0, 0.012, off)) * (1.0 - smoothstep(0.25, 0.55, r))
                })
                .fold(0.0, f32::max);
            colour *= 1.0 - 0.55 * check;
            // The cambium, darker, where the bark begins.
            colour *= 1.0 - 0.35 * smoothstep(0.93, 1.0, r);
            data.extend([colour.x, colour.y, colour.z].map(|c| c.clamp(0.0, 255.0) as u8));
            data.push(255);
        }
    }
    data
}

fn smoothstep(edge0: f32, edge1: f32, x: f32) -> f32 {
    let t = ((x - edge0) / (edge1 - edge0)).clamp(0.0, 1.0);
    t * t * (3.0 - 2.0 * t)
}

/// The end-grain image with its mip chain, for [`TextureLibrary::end_grain`].
pub(crate) fn end_grain_image() -> Image {
    use bevy::asset::RenderAssetUsages;
    use bevy::render::render_resource::{Extent3d, TextureDimension, TextureFormat};
    const SIZE: u32 = 256;
    let base = end_grain_pixels(SIZE);
    // `Image::new` takes the base level alone (debug builds check its length); the chain
    // replaces the data afterwards.
    let mut image = Image::new(
        Extent3d { width: SIZE, height: SIZE, depth_or_array_layers: 1 },
        TextureDimension::D2,
        base.clone(),
        TextureFormat::Rgba8UnormSrgb,
        RenderAssetUsages::RENDER_WORLD,
    );
    image.data = Some(crate::impostor::with_mip_chain(&base, SIZE, SIZE));
    image.texture_descriptor.mip_level_count = crate::impostor::MIP_LEVELS;
    image
}

/// Messages, reflection and the cut faces' material; the systems are in the plugin's chain.
pub(crate) fn build(app: &mut bevy::app::App) {
    app.add_message::<TreeLanded>()
        .add_message::<TreeBucked>()
        .init_resource::<CutFace>()
        .register_type::<FellTree>()
        .register_type::<Felled>()
        .register_type::<TreeStump>()
        .register_type::<BuckTree>()
        .register_type::<TreeLog>()
        .register_type::<TreeNotch>();
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{TreePreset, build_tree};

    #[test]
    fn a_felled_tree_rests_on_its_limbs_without_sinking_into_the_ground() {
        for preset in [
            TreePreset::Oak,
            TreePreset::Pine,
            TreePreset::Willow,
            TreePreset::Birch,
            TreePreset::Maple,
            TreePreset::Spruce,
            TreePreset::Redwood,
        ] {
            let params = preset.params();
            let tree = build_tree(&params, f32::INFINITY);
            let above = cut(&tree.trunk, 0.5, true);
            let direction = Vec3::X;
            let (hinge, reach) = hinge_point(&above.outlines, 0.5, direction);
            let points = contact_points(&above.kept, &tree.skeleton, &params, 0.5, reach);
            let axis = Vec3::Y.cross(direction).normalize();
            let (rest, contact) = rest_angle(&points, hinge, axis, |p| p.y);
            assert!(
                rest > 45f32.to_radians() && rest < 105f32.to_radians(),
                "{preset:?}: rests at {}°",
                rest.to_degrees()
            );
            let turn = Quat::from_axis_angle(axis, rest);
            let lowest = points.iter().map(|p| (turn * (*p - hinge) + hinge).y).fold(f32::INFINITY, f32::min);
            assert!(lowest > -0.005, "{preset:?}: its limbs sink {lowest} m into the ground at rest");
            assert!(lowest < 0.05, "{preset:?}: floats {lowest} m above the ground at rest");
            assert!((turn * (contact - hinge) + hinge).y < 0.05, "{preset:?}: the contact point is not on the ground");
            // It falls toward +x: the top of the trunk ends on that side.
            let top = points.iter().copied().max_by(|a, b| a.y.total_cmp(&b.y)).unwrap();
            assert!((turn * (top - hinge) + hinge).x > hinge.x, "{preset:?}: fell the wrong way");
        }
    }

    fn app() -> bevy::app::App {
        use bevy::asset::{AssetApp, AssetPlugin};
        use bevy::time::TimeUpdateStrategy;
        let mut app = bevy::app::App::new();
        app.add_plugins((bevy::MinimalPlugins, AssetPlugin::default()));
        app.init_asset::<Mesh>();
        app.init_asset::<StandardMaterial>();
        app.add_plugins(crate::FloraPlugin);
        app.insert_resource(TimeUpdateStrategy::ManualDuration(std::time::Duration::from_secs_f32(1.0 / 30.0)));
        app
    }

    /// Run updates until every felled tree lies still (at most `frames`), counting landings.
    fn settle(app: &mut bevy::app::App, frames: u32) -> usize {
        let mut cursor = app.world().resource::<bevy::ecs::message::Messages<TreeLanded>>().get_cursor_current();
        let mut landings = 0;
        for _ in 0..frames {
            app.update();
            landings += cursor.read(app.world().resource::<bevy::ecs::message::Messages<TreeLanded>>()).count();
            let mut query = app.world_mut().query::<&Felled>();
            let felled: Vec<bool> = query.iter(app.world()).map(|f| f.at_rest).collect();
            if !felled.is_empty() && felled.iter().all(|&rest| rest) {
                break;
            }
        }
        landings
    }

    #[test]
    fn a_tree_restored_lying_lies_at_once_where_a_felled_one_comes_to_rest() {
        let params = TreePreset::Oak.params();
        let lay = |lying: bool| {
            let mut app = app();
            let tree = app.world_mut().spawn((ProceduralTree(params.clone()), Transform::from_xyz(2.0, 0.0, -1.0))).id();
            app.update();
            app.world_mut().entity_mut(tree).insert(FellTree { direction: Vec2::new(1.0, 1.0), lying, ..Default::default() });
            app.update();
            let at_once = app.world().get::<Felled>(tree).map(|felled| felled.at_rest);
            let landings = settle(&mut app, 900);
            let lying_at = *app.world().get::<Transform>(tree).unwrap();
            (app, tree, at_once, landings, lying_at)
        };
        let (_, _, fell_at_once, fell_landings, fell_at) = lay(false);
        let (mut app, tree, at_once, landings, at) = lay(true);
        assert_eq!((fell_at_once, fell_landings), (Some(false), 1));
        assert_eq!(at_once, Some(true), "a tree restored lying fell first");
        assert_eq!(landings, 0, "a tree restored lying landed");
        assert!(at.translation.distance(fell_at.translation) < 1e-3, "{at:?} against {fell_at:?}");
        assert!(at.rotation.angle_between(fell_at.rotation) < 1e-3, "{at:?} against {fell_at:?}");
        // Bucked as soon as it lies.
        app.world_mut().entity_mut(tree).insert(BuckTree::default());
        app.update();
        app.update();
        assert!(app.world_mut().query::<&TreeLog>().iter(app.world()).count() > 0, "no logs");
    }

    #[test]
    fn a_felled_tree_falls_the_way_it_was_sent_lands_once_and_leaves_a_stump() {
        let mut app = app();
        let tree = app
            .world_mut()
            .spawn((ProceduralTree(TreePreset::Oak.params()), Transform::from_xyz(3.0, 0.0, -2.0)))
            .id();
        app.update();
        let fell = FellTree { direction: Vec2::new(0.0, 1.0), speed: 3.0, ..Default::default() };
        app.world_mut().entity_mut(tree).insert(fell);
        assert_eq!(settle(&mut app, 600), 1, "the tree did not land exactly once");

        let felled = app.world().get::<Felled>(tree).expect("the tree was not felled").clone();
        assert!(felled.at_rest, "the tree is still moving");
        let up = app.world().get::<Transform>(tree).unwrap().rotation * Vec3::Y;
        assert!(up.z > 0.6 && up.y < 0.6, "it fell along {up}, not toward +z");
        let stump = app.world().get::<TreeStump>(felled.stump).expect("no stump");
        assert_eq!(stump.tree, Some(tree));
        assert_eq!(app.world().get::<Transform>(felled.stump).unwrap().translation, Vec3::new(3.0, 0.0, -2.0));
        let pieces = app.world().get::<Children>(felled.stump).map_or(0, |c| c.len());
        assert_eq!(pieces, 2, "the stump should be its wood and its cut face");

        // It is cut for good: ageing it rebuilds nothing.
        let mut generated =
            app.world().resource::<bevy::ecs::message::Messages<crate::TreeGenerated>>().get_cursor_current();
        app.world_mut().get_mut::<TreeAge>(tree).unwrap().0 = 3.0;
        app.update();
        app.update();
        let rebuilt = generated.read(app.world().resource::<bevy::ecs::message::Messages<crate::TreeGenerated>>());
        assert_eq!(rebuilt.filter(|g| g.entity == tree).count(), 0, "a felled tree was rebuilt");
    }

    #[test]
    fn a_pooled_tree_is_felled_as_the_tree_of_its_variant() {
        let mut app = app();
        let pool = crate::build_pool(
            &TreePreset::Birch.params(),
            3,
            f32::INFINITY,
            &crate::LodSettings::default(),
            &mut app.world_mut().resource_mut::<Assets<Mesh>>(),
        );
        let expected = pool.tree_params(4);
        let pool = app.world_mut().resource_mut::<Assets<TreePool>>().add(pool);
        let tree = app.world_mut().spawn((PooledTree { pool, variant: 4 }, Transform::default())).id();
        app.update();
        app.world_mut().entity_mut(tree).insert(FellTree { speed: 4.0, ..Default::default() });
        assert_eq!(settle(&mut app, 600), 1);
        assert!(app.world().get::<PooledTree>(tree).is_none(), "it is still pooled");
        assert_eq!(app.world().get::<ProceduralTree>(tree), Some(&ProceduralTree(expected)));
        assert!(app.world().get::<Felled>(tree).is_some_and(|f| f.at_rest));
    }

    #[test]
    fn on_a_slope_a_tree_is_cut_above_its_uphill_side_and_lands_on_the_terrain() {
        // The ground falls 0.4 m a metre toward +x, 22°.
        let slope = FloraGround::new(|at: Vec2| 3.0 - 0.4 * at.x);
        let params = TreePreset::Oak.params();
        let at = Vec2::new(2.0, 1.0);
        let fell = |ground: Option<&FloraGround>, direction: Vec2| {
            let mut app = app();
            let y = ground.map_or(0.0, |ground| ground.footing(at, params.base_radius()));
            if let Some(ground) = ground {
                app.insert_resource(ground.clone());
            }
            let base = Transform::from_xyz(at.x, y, at.y);
            let tree = app.world_mut().spawn((ProceduralTree(params.clone()), base)).id();
            app.update();
            app.world_mut().entity_mut(tree).insert(FellTree { direction, speed: 4.0, ..Default::default() });
            assert_eq!(settle(&mut app, 900), 1, "it did not land exactly once");
            let felled = app.world().get::<Felled>(tree).unwrap().clone();
            assert!(felled.at_rest, "it is still moving");
            (base, *app.world().get::<Transform>(tree).unwrap(), felled)
        };
        let (_, _, flat) = fell(None, Vec2::X);
        for (direction, downhill) in [(Vec2::X, true), (Vec2::NEG_X, false)] {
            let (base, lying, felled) = fell(Some(&slope), direction);
            // The saw went in half a metre above the ground on the trunk's uphill side.
            let cut = base.translation.y + felled.fall.hinge.y;
            let uphill = slope.top(at, params.base_radius());
            assert!((cut - uphill - 0.5).abs() < 1.0e-3, "cut at {cut}, the uphill ground at {uphill}");
            // Down the slope it turns further than on flat ground, up it less.
            let (angle, on_flat) = (felled.angle.to_degrees(), flat.angle.to_degrees());
            let turned = if downhill { angle > on_flat + 8.0 } else { angle < on_flat - 8.0 };
            assert!(turned, "downhill {downhill}: rests at {angle}°, {on_flat}° on flat ground");
            // And it lies on the terrain.
            let contact = lying.transform_point(felled.fall.contact);
            let gap = contact.y - slope.height(contact.xz());
            assert!(gap.abs() < 0.03, "downhill {downhill}: it touches the ground {gap} m off it");
        }
    }

    #[test]
    fn every_preset_felled_on_a_slope_lands_once_and_lies_on_it() {
        // 27°, falling toward +x.
        let slope = FloraGround::new(|at: Vec2| -0.5 * at.x);
        for preset in TreePreset::ALL {
            let params = preset.params();
            for direction in [Vec2::X, Vec2::NEG_X, Vec2::Y] {
                let mut app = app();
                app.insert_resource(slope.clone());
                let base = Transform::from_xyz(0.0, slope.footing(Vec2::ZERO, params.base_radius()), 0.0);
                let tree = app.world_mut().spawn((ProceduralTree(params.clone()), base)).id();
                app.update();
                app.world_mut().entity_mut(tree).insert(FellTree { direction, speed: 4.0, ..Default::default() });
                let landings = settle(&mut app, 900);
                let felled = app.world().get::<Felled>(tree).unwrap().clone();
                let lying = *app.world().get::<Transform>(tree).unwrap();
                let contact = lying.transform_point(felled.fall.contact);
                let gap = contact.y - slope.height(contact.xz());
                assert!(
                    felled.at_rest && landings == 1 && gap.abs() < 0.05,
                    "{preset:?} toward {direction}: landed {landings} times, at rest {}, at {}°, {gap} m off the ground",
                    felled.at_rest,
                    felled.angle.to_degrees()
                );
            }
        }
    }

    /// Fell a tree of `params` standing at `at` toward `direction` and buck it into logs of the
    /// default length; the `TreeBucked` message.
    fn fell_and_buck(app: &mut bevy::app::App, params: &TreeParams, at: Vec3, direction: Vec2) -> TreeBucked {
        fell_and_buck_as(app, params, Transform::from_translation(at), direction)
    }

    /// As [`fell_and_buck`], the tree placed with `transform` (scaled, in a world of other units).
    fn fell_and_buck_as(app: &mut bevy::app::App, params: &TreeParams, transform: Transform, direction: Vec2) -> TreeBucked {
        use bevy::ecs::message::Messages;
        let tree = app.world_mut().spawn((ProceduralTree(params.clone()), transform)).id();
        app.update();
        let fell = FellTree { direction, speed: 4.0, ..Default::default() };
        app.world_mut().entity_mut(tree).insert((fell, BuckTree::default()));
        let mut cursor = app.world().resource::<Messages<TreeBucked>>().get_cursor_current();
        for _ in 0..900 {
            app.update();
            let bucked: Vec<TreeBucked> = cursor.read(app.world().resource::<Messages<TreeBucked>>()).cloned().collect();
            if let Some(bucked) = bucked.into_iter().next() {
                assert_eq!(bucked.tree, tree);
                assert!(app.world().get_entity(tree).is_err(), "the bucked tree is still there");
                return bucked;
            }
        }
        panic!("the tree was never bucked");
    }

    #[test]
    fn a_bucked_tree_becomes_logs_lying_on_the_ground_in_a_row_from_its_stump() {
        let params = TreePreset::Oak.params();
        // Flat, and falling 0.3 m a metre toward +x (17°).
        for slope in [None, Some(FloraGround::new(|at: Vec2| 1.0 - 0.3 * at.x))] {
            let ground = slope.clone().unwrap_or_default();
            for direction in [Vec2::X, Vec2::NEG_X] {
                let mut app = app();
                if let Some(slope) = &slope {
                    app.insert_resource(slope.clone());
                }
                let at = Vec3::new(0.0, ground.footing(Vec2::ZERO, params.base_radius()), 0.0);
                let bucked = fell_and_buck(&mut app, &params, at, direction);
                let what = format!("slope {}, toward {direction}", slope.is_some());
                assert!(bucked.logs.len() >= 2, "{what}: {} logs", bucked.logs.len());
                let lift = |p: Vec3| 1.0 / ground.normal(p.xz()).y;
                let mut reached = 0.0;
                for (index, &entity) in bucked.logs.iter().enumerate() {
                    let log = *app.world().get::<TreeLog>(entity).unwrap();
                    assert_eq!((log.index, log.stump), (index as u32, bucked.stump));
                    let place = app.world().get::<Transform>(entity).unwrap();
                    let (a, b) = (place.transform_point(log.capsule.a), place.transform_point(log.capsule.b));
                    assert!((a.distance(b) - 2.0).abs() < 0.04, "{what}: log {index} is {} m long", a.distance(b));
                    // Its butt end lies on the ground; its thinner top end too, a little lower.
                    let butt = a.y - ground.height(a.xz()) - log.capsule.radius * lift(a);
                    let top = b.y - ground.height(b.xz());
                    assert!(butt.abs() < 0.03, "{what}: log {index}'s butt end is {butt} m off the ground");
                    assert!(top > 0.0 && top < log.capsule.radius * lift(b) + 0.03, "{what}: its top end {top} m up");
                    // In a row from the stump, the way the tree fell, apart.
                    let (from, to) = (a.xz().dot(direction), b.xz().dot(direction));
                    assert!(from > reached + 0.02 && to > from, "{what}: log {index} from {from} to {to}, after {reached}");
                    reached = to;
                    let pieces = app.world().get::<Children>(entity).map_or(0, |c| c.len());
                    assert_eq!(pieces, 2, "{what}: a log is its wood and its end faces");
                }
            }
        }
    }

    #[test]
    fn a_bucked_trees_stump_and_logs_are_found_as_obstacles_where_they_lie() {
        use crate::index::{FloraIndex, ObstacleKind};
        use bevy::transform::components::GlobalTransform;
        let params = TreePreset::Oak.params();
        // Where things are in the world: the obstacles are kept from their global transforms.
        let mut app = app();
        app.add_plugins(bevy::transform::TransformPlugin);
        let at = Vec3::new(3.0, 0.0, -2.0);
        let bucked = fell_and_buck(&mut app, &params, at, Vec2::X);
        app.update();
        // The stump: from its foot to its cut, the trunk's radius there.
        let stump = *app.world().get::<TreeStump>(bucked.stump).unwrap();
        let cut_height = FellTree::default().cut_height;
        assert!(stump.capsule.a.y.abs() < 1.0e-6 && (stump.capsule.b.y - cut_height).abs() < 0.15, "{stump:?}");
        let (top, foot) = (params.trunk.radius * params.trunk.taper, params.base_radius());
        assert!(stump.capsule.radius > top && stump.capsule.radius < foot * 1.1, "{stump:?}: between {top} and {foot}");
        {
            let index = app.world().resource::<FloraIndex>();
            let near = |p: Vec2, kind: ObstacleKind| -> Vec<Entity> {
                index.obstacles_within(p, 0.05).filter(|o| o.kind == kind).map(|o| o.entity).collect()
            };
            assert_eq!(near(at.xz(), ObstacleKind::Stump), vec![bucked.stump]);
            for &log in &bucked.logs {
                let capsule = app.world().get::<TreeLog>(log).unwrap().capsule;
                let place = app.world().get::<GlobalTransform>(log).unwrap();
                let middle = place.transform_point((capsule.a + capsule.b) * 0.5).xz();
                assert!(near(middle, ObstacleKind::Log).contains(&log), "log {log:?} is not found where it lies");
            }
            assert_eq!(index.obstacles().count(), 1 + bucked.logs.len());
            assert!(index.within(at.xz(), 1.0).next().is_none(), "the tree no longer stands");
        }
        // Gone with its entity.
        app.world_mut().despawn(bucked.stump);
        app.update();
        assert!(app.world().resource::<FloraIndex>().obstacles().all(|o| o.entity != bucked.stump));
    }

    #[test]
    fn a_felled_tree_with_a_shape_is_an_obstacle_once_it_lies_still() {
        use crate::index::{FloraIndex, ObstacleKind};
        use crate::shape::TreeShape;
        let mut app = app();
        app.add_plugins(bevy::transform::TransformPlugin);
        let tree = app.world_mut().spawn((ProceduralTree(TreePreset::Oak.params()), TreeShape::default(), Transform::default())).id();
        app.update();
        app.world_mut().entity_mut(tree).insert(FellTree { direction: Vec2::X, speed: 4.0, ..Default::default() });
        let lying = |app: &bevy::app::App| -> Vec<WoodCapsule> {
            let index = app.world().resource::<FloraIndex>();
            index.obstacles().filter(|o| o.kind == ObstacleKind::Lying && o.entity == tree).map(|o| o.capsule).collect()
        };
        let mut falling = 0;
        for _ in 0..900 {
            app.update();
            if app.world().get::<Felled>(tree).is_some_and(|felled| felled.at_rest) {
                break;
            }
            assert!(lying(&app).is_empty(), "a falling tree is no obstacle yet");
            falling += 1;
        }
        assert!(falling > 3, "it fell over {falling} frames");
        let wood = lying(&app);
        assert!(!wood.is_empty(), "the tree lies still and is an obstacle");
        // All of it lies the way it fell: the wood below the cut, the stump's, is not part of it.
        for capsule in &wood {
            assert!(capsule.a.x > -0.3 && capsule.b.x > -0.3, "{capsule:?} reaches behind the stump");
        }
    }

    #[test]
    fn every_preset_can_be_bucked() {
        for preset in TreePreset::ALL {
            let mut app = app();
            let bucked = fell_and_buck(&mut app, &preset.params(), Vec3::ZERO, Vec2::Y);
            for &entity in &bucked.logs {
                let log = app.world().get::<TreeLog>(entity).unwrap();
                let length = log.capsule.a.distance(log.capsule.b);
                assert!((length - 2.0).abs() < 0.04 && log.capsule.radius >= 0.08, "{preset:?}: {log:?}");
            }
        }
    }

    #[test]
    fn every_preset_falls_and_lies_still() {
        for preset in TreePreset::ALL {
            for seed in [42, 1, 2] {
                let mut app = app();
                let tree = app.world_mut().spawn(ProceduralTree(TreeParams { seed, ..preset.params() })).id();
                app.update();
                app.world_mut().entity_mut(tree).insert(FellTree { speed: 4.0, ..Default::default() });
                let landings = settle(&mut app, 900);
                let felled = app.world().get::<Felled>(tree).unwrap_or_else(|| panic!("{preset:?} was not felled"));
                assert!(
                    felled.at_rest && landings == 1,
                    "{preset:?} seed {seed}: landed {landings} times, at rest: {}, angle {}° of {}°, spin {}",
                    felled.at_rest,
                    felled.angle.to_degrees(),
                    felled.fall.rest.to_degrees(),
                    felled.fall.spin
                );
            }
        }
    }

    /// The positions of a tree's wood as drawn.
    fn drawn_wood(app: &bevy::app::App, tree: Entity) -> Vec<Vec3> {
        let handle = app.world().get::<TreeRender>(tree).unwrap().trunk_mesh.clone().unwrap();
        let mesh = app.world().resource::<Assets<Mesh>>().get(&handle).unwrap();
        let positions = mesh.attribute(Mesh::ATTRIBUTE_POSITION).unwrap().as_float3().unwrap();
        positions.iter().map(|p| Vec3::from_array(*p)).collect()
    }

    /// The positions and normals of the mesh `entity` draws.
    fn drawn(app: &bevy::app::App, entity: Entity) -> (Vec<Vec3>, Vec<Vec3>) {
        let handle = &app.world().get::<Mesh3d>(entity).unwrap().0;
        let mesh = app.world().resource::<Assets<Mesh>>().get(handle).unwrap();
        let read = |attribute| -> Vec<Vec3> {
            let values = mesh.attribute(attribute).unwrap().as_float3().unwrap();
            values.iter().map(|p| Vec3::from_array(*p)).collect()
        };
        (read(Mesh::ATTRIBUTE_POSITION), read(Mesh::ATTRIBUTE_NORMAL))
    }

    #[test]
    fn a_notch_is_carved_into_a_standing_tree_deepens_with_each_blow_and_heals() {
        let mut app = app();
        let params = TreePreset::Oak.params();
        let tree = app.world_mut().spawn((ProceduralTree(params.clone()), Transform::default())).id();
        app.update();
        let whole = drawn_wood(&app, tree);
        let wood = build_tree(&params, f32::INFINITY).trunk;
        // The trunk's width along -z (the side cut from) at the notch's floor, from the wood itself.
        let level = cut(&wood, 0.6, false);
        let ring = level.outlines.iter().max_by_key(|o| o.len()).unwrap();
        let front = ring.iter().map(|p| -p.z).fold(f32::NEG_INFINITY, f32::max);
        let width = front - ring.iter().map(|p| -p.z).fold(f32::INFINITY, f32::min);
        for depth in [0.1, 0.2, 0.3] {
            let notch = TreeNotch { direction: Vec2::new(0.0, -1.0), height: 0.6, depth };
            app.world_mut().entity_mut(tree).insert(notch);
            app.update();
            let wedge = notch_in(&wood, &notch, &Transform::default(), &params, None, 1.0).unwrap();
            let face = wedge.face();
            let inside = drawn_wood(&app, tree)
                .into_iter()
                .filter(|p| p.y > wedge.floor + 1e-3 && p.y < wedge.mouth - 1e-3 && face.distance(*p) < -1e-3);
            assert_eq!(inside.count(), 0, "depth {depth}: wood left in the notch");
            // Its faces reach `depth` of the way through the trunk, from the front.
            let faces = app.world().get::<NotchCarved>(tree).unwrap().faces.expect("no faces drawn");
            let (positions, _) = drawn(&app, faces);
            let reached = front - positions.iter().map(|p| -p.z).fold(f32::INFINITY, f32::min);
            assert!((reached / width - depth).abs() < 0.03, "depth {depth}: the notch reaches {} of the way", reached / width);
        }
        let faces = app.world().get::<NotchCarved>(tree).unwrap().faces.unwrap();
        app.world_mut().entity_mut(tree).remove::<TreeNotch>();
        app.update();
        assert_eq!(drawn_wood(&app, tree), whole, "the trunk is not whole again");
        assert!(app.world().get_entity(faces).is_err(), "the notch's faces are still drawn");
    }

    #[test]
    fn a_notched_tree_is_felled_at_its_notch_and_falls_with_its_face() {
        let mut app = app();
        let tree = app.world_mut().spawn((ProceduralTree(TreePreset::Oak.params()), Transform::default())).id();
        app.update();
        app.world_mut().entity_mut(tree).insert(TreeNotch { direction: Vec2::X, height: 0.8, depth: 0.3 });
        app.update();
        let standing = app.world().get::<NotchCarved>(tree).unwrap().faces.unwrap();
        app.world_mut().entity_mut(tree).insert(FellTree { direction: Vec2::X, cut_height: 0.3, speed: 4.0, ..Default::default() });
        assert_eq!(settle(&mut app, 900), 1, "it did not land exactly once");
        let felled = app.world().get::<Felled>(tree).unwrap().clone();
        assert!((felled.fall.hinge.y - 0.8).abs() < 1e-4, "cut at {}, not at the notch's floor", felled.fall.hinge.y);
        assert!(app.world().get_entity(standing).is_err(), "the standing notch's faces are still drawn");
        assert!(app.world().get::<NotchCarved>(tree).is_none());
        // The fallen tree's faces: the notch's face (out of the trunk and down) and the cut behind
        // it (down); the floor stays on the stump.
        let cut_face = app.world().resource::<CutFace>().lit.clone().unwrap();
        let children: Vec<Entity> = app.world().get::<Children>(tree).unwrap().iter().collect();
        let faces = children
            .into_iter()
            .find(|&c| app.world().get::<MeshMaterial3d<StandardMaterial>>(c).is_some_and(|m| m.0 == cut_face))
            .expect("the fallen tree has no cut faces");
        let (_, normals) = drawn(&app, faces);
        assert!(normals.iter().any(|n| n.x > 0.5 && n.y < -0.5), "the fallen tree has no notch face");
        assert!(normals.iter().any(|n| n.y < -0.99), "the fallen tree has no cut behind its notch");
        assert!(!normals.iter().any(|n| n.y > 0.0), "the fallen tree carries the notch's floor");
    }

    #[test]
    fn a_prism_trunk_can_be_notched_felled_and_bucked() {
        use crate::params::TrunkStyle;
        let params = crate::crown_hull::hull_spruce();

        // Notched: its faces are drawn, and the notch is felled at its floor.
        for (floor, cut_height) in [(0.8, 0.3), (0.6, 0.5)] {
            let mut app = app();
            let tree = app.world_mut().spawn((ProceduralTree(params.clone()), Transform::default())).id();
            app.update();
            app.world_mut().entity_mut(tree).insert(TreeNotch { direction: Vec2::X, height: floor, depth: 0.3 });
            app.update();
            let faces = app.world().get::<NotchCarved>(tree).and_then(|carved| carved.faces);
            assert!(faces.is_some(), "a prism trunk's notch has no faces");
            app.world_mut().entity_mut(tree).insert(FellTree { direction: Vec2::X, cut_height, speed: 4.0, ..Default::default() });
            assert_eq!(settle(&mut app, 900), 1, "the notched prism (floor {floor}) did not land exactly once");
            let felled = app.world().get::<Felled>(tree).unwrap().clone();
            assert!(felled.at_rest && (felled.fall.hinge.y - floor).abs() < 1e-4, "cut at {}, floor {floor}", felled.fall.hinge.y);
        }

        // Bucked: logs a length long, as thick as the round trunk's (a flat trunk's cut has a point
        // in the middle of each side, which must not pull the log's radius in).
        let (mut app, mut round_app) = (self::app(), self::app());
        let bucked = fell_and_buck(&mut app, &params, Vec3::ZERO, Vec2::Y);
        let round = TreeParams { trunk_style: TrunkStyle::Round, ..params.clone() };
        let round_logs = fell_and_buck(&mut round_app, &round, Vec3::ZERO, Vec2::Y);
        assert!(!bucked.logs.is_empty(), "the prism trunk made no logs");
        let radius = |app: &bevy::app::App, bucked: &TreeBucked| app.world().get::<TreeLog>(bucked.logs[0]).unwrap().capsule.radius;
        for &entity in &bucked.logs {
            let log = app.world().get::<TreeLog>(entity).unwrap();
            let length = log.capsule.a.distance(log.capsule.b);
            assert!((length - 2.0).abs() < 0.04 && log.capsule.radius >= 0.08, "{log:?}");
        }
        let (flat, smooth) = (radius(&app, &bucked), radius(&round_app, &round_logs));
        assert!((0.7..=1.1).contains(&(flat / smooth)), "the prism log is {flat} thick, the round one {smooth}");
    }

    const BLUE: PoolColors =
        PoolColors { wood: bevy::color::Color::srgb(0.10, 0.20, 0.60), leaves: bevy::color::Color::srgb(0.30, 0.55, 0.95), unlit: true };
    const RUST: PoolColors =
        PoolColors { wood: bevy::color::Color::srgb(0.45, 0.20, 0.08), leaves: bevy::color::Color::srgb(0.75, 0.35, 0.10), unlit: false };

    fn flora_app() -> bevy::app::App {
        let mut app = app();
        app.insert_resource(crate::FloraMaterialSupport);
        app
    }

    fn recolor(app: &mut bevy::app::App, tree: Entity, colors: PoolColors) {
        let message = crate::RecolorTree { tree, colors };
        app.world_mut().resource_mut::<bevy::ecs::message::Messages<crate::RecolorTree>>().write(message);
    }

    fn flora_of(app: &bevy::app::App, entity: Entity) -> FloraMaterial {
        let handle = &app.world().get::<MeshMaterial3d<FloraMaterial>>(entity).expect("a flora material").0;
        app.world().resource::<Assets<FloraMaterial>>().get(handle).unwrap().clone()
    }

    fn plain_of(app: &bevy::app::App, entity: Entity) -> StandardMaterial {
        let handle = &app.world().get::<MeshMaterial3d<StandardMaterial>>(entity).expect("a plain material").0;
        app.world().resource::<Assets<StandardMaterial>>().get(handle).unwrap().clone()
    }

    fn children_of(app: &bevy::app::App, entity: Entity) -> Vec<Entity> {
        app.world().get::<Children>(entity).map_or_else(Vec::new, |children| children.iter().collect())
    }

    /// Every child of `entity` with a flora material wears `colors`: the wood's colour for wood, the
    /// leaves' for leaves; returns how many there are.
    fn assert_dressed(app: &bevy::app::App, entity: Entity, colors: PoolColors, calm: bool) -> usize {
        let mut seen = 0;
        for child in children_of(app, entity) {
            if app.world().get::<MeshMaterial3d<FloraMaterial>>(child).is_none() {
                continue;
            }
            let material = flora_of(app, child);
            let wanted = if material.extension.leaf { colors.leaves } else { colors.wood };
            assert_eq!(material.base.base_color, wanted, "leaf: {}", material.extension.leaf);
            assert_eq!(material.base.unlit, colors.unlit);
            if calm {
                assert_eq!(material.extension.flora.response.x, 0.0, "a tree on the ground does not sway");
            }
            seen += 1;
        }
        seen
    }

    #[test]
    fn recolouring_a_standing_tree_swaps_its_materials_without_rebuilding_and_the_colours_outlast_a_rebuild() {
        let mut app = flora_app();
        let tree = app
            .world_mut()
            .spawn((ProceduralTree(TreePreset::Oak.params()), crate::lod::TreeLod::default(), Transform::default()))
            .id();
        app.update();
        app.update();
        let meshes = |app: &bevy::app::App| -> Vec<_> {
            children_of(app, tree).into_iter().map(|c| app.world().get::<Mesh3d>(c).unwrap().0.id()).collect()
        };
        let before = meshes(&app);
        let mut generated =
            app.world().resource::<bevy::ecs::message::Messages<crate::TreeGenerated>>().get_cursor_current();

        recolor(&mut app, tree, BLUE);
        app.update();
        assert!(assert_dressed(&app, tree, BLUE, false) >= 6, "every level of detail is recoloured");
        assert_eq!(meshes(&app), before, "no mesh was rebuilt");
        let messages = app.world().resource::<bevy::ecs::message::Messages<crate::TreeGenerated>>();
        assert_eq!(generated.read(messages).count(), 0);

        // A rebuild is drawn in the colours the tree was given, not the parameters'.
        app.world_mut().get_mut::<ProceduralTree>(tree).unwrap().0.seed = 9;
        app.update();
        app.update();
        let messages = app.world().resource::<bevy::ecs::message::Messages<crate::TreeGenerated>>();
        assert_eq!(generated.read(messages).count(), 1, "the tree was rebuilt");
        assert!(assert_dressed(&app, tree, BLUE, false) >= 6);

        recolor(&mut app, tree, RUST);
        app.update();
        assert!(assert_dressed(&app, tree, RUST, false) >= 6, "back to lit");
    }

    #[test]
    fn a_tree_drawn_with_plain_materials_is_recoloured_in_place() {
        let mut app = app();
        let tree = app.world_mut().spawn((ProceduralTree(TreePreset::Oak.params()), Transform::default())).id();
        app.update();
        recolor(&mut app, tree, BLUE);
        app.update();
        let render = app.world().get::<TreeRender>(tree).unwrap();
        let (trunk, foliage) = (render.trunk_entity(), render.foliage_entity().unwrap());
        for (child, color) in [(trunk, BLUE.wood), (foliage, BLUE.leaves)] {
            let material = plain_of(&app, child);
            assert_eq!((material.base_color, material.unlit), (color, true));
        }
    }

    #[test]
    fn a_tree_recoloured_while_it_falls_lands_and_lies_in_the_new_colours_still_with_unlit_cut_faces() {
        let mut app = flora_app();
        let tree = app.world_mut().spawn((ProceduralTree(TreePreset::Oak.params()), Transform::default())).id();
        app.update();
        app.update();
        app.world_mut().entity_mut(tree).insert(FellTree { speed: 4.0, ..Default::default() });
        app.update();
        assert!(!app.world().get::<Felled>(tree).expect("falling").landed());

        recolor(&mut app, tree, BLUE);
        app.update();
        assert!(assert_dressed(&app, tree, BLUE, false) >= 2, "falling, it still sways");
        assert_eq!(settle(&mut app, 900), 1);
        assert!(app.world().get::<Felled>(tree).unwrap().landed());
        assert!(assert_dressed(&app, tree, BLUE, true) >= 2, "lying, it does not");

        // Its stump and every cut face: the unlit twin of the end grain.
        let stump = app.world().get::<Felled>(tree).unwrap().stump;
        assert!(assert_dressed(&app, stump, BLUE, false) >= 1);
        let faces: Vec<Entity> = [tree, stump]
            .into_iter()
            .flat_map(|e| children_of(&app, e))
            .filter(|&c| app.world().get::<MeshMaterial3d<StandardMaterial>>(c).is_some())
            .collect();
        assert!(faces.len() >= 2, "the tree and its stump have cut faces");
        assert!(faces.iter().all(|&face| plain_of(&app, face).unlit));

        // Lying on the ground it is recoloured again: still still, and lit.
        recolor(&mut app, tree, RUST);
        app.update();
        assert!(assert_dressed(&app, tree, RUST, true) >= 2);
        assert!(assert_dressed(&app, stump, RUST, false) >= 1);
        assert!(faces.iter().all(|&face| !plain_of(&app, face).unlit));

        // Bucked, the stump and each log are recoloured by their own message.
        app.world_mut().entity_mut(tree).insert(BuckTree::default());
        app.update();
        let mut logs = app.world_mut().query::<(Entity, &TreeLog)>();
        let logs: Vec<Entity> = logs.iter(app.world()).map(|(log, _)| log).collect();
        assert!(!logs.is_empty(), "the tree was not bucked");
        recolor(&mut app, stump, BLUE);
        for &log in &logs {
            recolor(&mut app, log, BLUE);
        }
        app.update();
        assert!(assert_dressed(&app, stump, BLUE, false) >= 1);
        for &log in &logs {
            assert!(assert_dressed(&app, log, BLUE, true) >= 1, "a log's wood does not sway");
            let ends: Vec<Entity> = children_of(&app, log)
                .into_iter()
                .filter(|&c| app.world().get::<MeshMaterial3d<StandardMaterial>>(c).is_some())
                .collect();
            assert!(!ends.is_empty() && ends.iter().all(|&end| plain_of(&app, end).unlit), "the logs' end grain is unlit");
        }
    }

    /// An oak felled toward +x at the default speed (as a real one, a few seconds) in a world of
    /// `units` world units to the metre, the tree scaled by `scale` as a game scales its trees, and
    /// notched at `notch` metres when given: the update the first `TreeLanded` came on, the height
    /// of the cut in the tree's own space and the angle it came to rest at.
    fn fell_in_a_world_of(units: f32, scale: f32, notch: Option<f32>) -> (usize, f32, f32) {
        use bevy::ecs::message::Messages;
        let mut app = app();
        app.insert_resource(FloraUnits { units_per_metre: units });
        let at = Transform::from_xyz(2.0 * scale, 0.0, -scale).with_scale(Vec3::splat(scale));
        let tree = app.world_mut().spawn((ProceduralTree(TreePreset::Oak.params()), at)).id();
        app.update();
        if let Some(height) = notch {
            app.world_mut().entity_mut(tree).insert(TreeNotch { direction: Vec2::X, height, depth: 0.3 });
            app.update();
        }
        app.world_mut().entity_mut(tree).insert(FellTree { direction: Vec2::X, ..Default::default() });
        let mut cursor = app.world().resource::<Messages<TreeLanded>>().get_cursor_current();
        for step in 0..900 {
            app.update();
            if cursor.read(app.world().resource::<Messages<TreeLanded>>()).next().is_some() {
                let felled = app.world().get::<Felled>(tree).expect("a landed tree is felled");
                return (step, felled.fall.hinge.y, felled.fall.rest);
            }
        }
        panic!("the oak never landed ({units} units to the metre)");
    }

    #[test]
    fn a_tree_felled_in_a_world_in_feet_lands_on_the_step_it_does_in_metres() {
        const FEET: f32 = 3.2808;
        let metres = fell_in_a_world_of(1.0, 1.0, None);
        let feet = fell_in_a_world_of(FEET, FEET, None);
        assert!(metres.0 > 20, "it landed after {} updates: not a tree of its size falling", metres.0);
        assert!(metres.0.abs_diff(feet.0) <= 1, "landed on update {} in metres, {} in feet", metres.0, feet.0);
        // The cut is half a metre up in either world, and it comes to rest at the same angle.
        assert!((metres.1 - 0.5).abs() < 1.0e-4 && (feet.1 - 0.5).abs() < 1.0e-4, "cut at {} and {}", metres.1, feet.1);
        assert!((metres.2 - feet.2).abs() < 1.0e-3, "rests at {} and {} rad", metres.2, feet.2);
        // Without the units the feet world's tree is three times as long under the same gravity
        // and takes much longer: what the test would otherwise not tell.
        let unscaled = fell_in_a_world_of(1.0, FEET, None);
        assert!(unscaled.0 * 2 > metres.0 * 3, "an unscaled world landed on update {} against {}", unscaled.0, metres.0);
    }

    #[test]
    fn a_notch_is_cut_at_the_same_metres_in_a_world_in_feet() {
        let metres = fell_in_a_world_of(1.0, 1.0, Some(0.8));
        let feet = fell_in_a_world_of(3.2808, 3.2808, Some(0.8));
        assert!((metres.1 - 0.8).abs() < 1.0e-4 && (feet.1 - 0.8).abs() < 1.0e-4, "cut at {} and {} m", metres.1, feet.1);
        assert!(metres.0.abs_diff(feet.0) <= 1, "landed on update {} in metres, {} in feet", metres.0, feet.0);
    }

    #[test]
    fn logs_bucked_in_a_world_in_feet_are_the_same_logs_the_same_gap_apart() {
        const FEET: f32 = 3.2808;
        let params = TreePreset::Oak.params();
        let lay = |units: f32| {
            let mut app = app();
            app.insert_resource(FloraUnits { units_per_metre: units });
            let bucked = fell_and_buck_as(&mut app, &params, Transform::from_scale(Vec3::splat(units)), Vec2::X);
            // Each log's two ends in world space, and its butt radius in the tree's own space.
            bucked
                .logs
                .iter()
                .map(|&log| {
                    let capsule = app.world().get::<TreeLog>(log).unwrap().capsule;
                    let place = app.world().get::<Transform>(log).unwrap();
                    (place.transform_point(capsule.a), place.transform_point(capsule.b), capsule.radius)
                })
                .collect::<Vec<(Vec3, Vec3, f32)>>()
        };
        let (metres, feet) = (lay(1.0), lay(FEET));
        assert!(metres.len() >= 2, "{} logs", metres.len());
        assert_eq!(metres.len(), feet.len(), "a different number of logs in feet");
        for (m, f) in metres.iter().zip(&feet) {
            assert!((m.0.distance(m.1) - 2.0).abs() < 0.04, "a log {} m long", m.0.distance(m.1));
            assert!((f.0.distance(f.1) - 2.0 * FEET).abs() < 0.04 * FEET, "a log {} ft long", f.0.distance(f.1));
            assert!((m.2 - f.2).abs() < 1.0e-4, "radius {} and {}", m.2, f.2);
        }
        // 15 cm apart along the ground, in a row from the stump: 15 cm of feet in the other world.
        for (row, gap) in [(&metres, 0.15), (&feet, 0.15 * FEET)] {
            for pair in row.windows(2) {
                let apart = (pair[1].0.xz() - pair[0].1.xz()).length();
                assert!((apart - gap).abs() < 0.01 * gap, "{apart} between logs, not {gap}");
            }
        }
    }

    #[test]
    fn a_hull_spruce_notched_and_felled_in_one_frame_falls_like_a_round_one() {
        use crate::params::TrunkStyle;
        let hull = crate::crown_hull::hull_spruce();
        let round = TreeParams { trunk_style: TrunkStyle::Round, crown: crate::params::CrownStyle::Leaves, ..hull.clone() };
        let crown = |trunk_only| crate::params::CrownStyle::Hull { tiers: 5, sides: 7, lift: 0.2, jitter: 1.0, trunk_only };
        let branchy = TreeParams { crown: crown(false), ..hull.clone() };
        for (what, params) in [("round", round), ("hull, trunk only", hull), ("hull with every branch", branchy)] {
            let mut app = app();
            // Spawned with the notch and the fall already on it, as `inspect` does.
            let tree = app
                .world_mut()
                .spawn((
                    ProceduralTree(params),
                    TreeAge(f32::INFINITY),
                    Transform::default(),
                    TreeNotch { direction: Vec2::X, height: 0.6, depth: 0.3 },
                    FellTree { direction: Vec2::X, speed: 4.0, ..Default::default() },
                ))
                .id();
            assert_eq!(settle(&mut app, 900), 1, "{what}: did not land exactly once");
            let felled = app.world().get::<Felled>(tree).unwrap().clone();
            // Inspect photographed it standing at a tilt of 12 degrees, taken for lying: a prism
            // tree's hinge was a limb's cut, not the trunk's.
            assert!(felled.at_rest && felled.fall.rest > 45f32.to_radians(), "{what}: at rest {} at {} degrees", felled.at_rest, felled.fall.rest.to_degrees());
        }
    }

    #[test]
    fn a_felled_prism_tree_still_rests_on_its_limbs_and_not_on_its_own_trunk() {
        use crate::params::TrunkStyle;
        for (what, style) in [("round", TrunkStyle::Round), ("prism", TrunkStyle::Prism { sides: 5 })] {
            let params = TreeParams { trunk_style: style, ..TreePreset::Spruce.params() };
            let tree = build_tree(&params, f32::INFINITY);
            let above = cut(&tree.trunk, 0.6, true);
            let (hinge, reach) = hinge_point(&above.outlines, 0.6, Vec3::X);
            let points = contact_points(&above.kept, &tree.skeleton, &params, 0.6, reach);
            let axis = Vec3::Y.cross(Vec3::X).normalize();
            let (rest, contact) = rest_angle(&points, hinge, axis, |p| p.y);
            assert!(rest > 45f32.to_radians(), "{what}: rests at {}° on {contact} ({} points, hinge {hinge})", rest.to_degrees(), points.len());
        }
    }
}