ghast-client 0.2.2

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9 and 1.16.5)
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
//! The mouse buttons in the world: digging, placing and using items, ported from 1.8.9
//! `MinecraftClient.tick` (`doAttack`, `doUse`, `handleBlockBreaking`) and
//! `ClientPlayerInteractionManager` (`attackBlock`, `updateBlockBreakingProgress`,
//! `cancelBlockBreaking`, `onRightClick`, `interactItem`, `stopUsingItem`), verified against recorded
//! lab packet traces.
//!
//! The hands run once per tick after the behaviour and before the movement step (vanilla's
//! key processing comes after the tick-start event and before the player's update), so their
//! packets precede this tick's movement packet and the server judges them with the previous
//! tick's pose.
//!
//! Version-specific facts (block hardness, tool groups, selection boxes, the held stack) come
//! from the [`BlockQuery`] answers and [`HeldItem`]; the state machine is the 1.8 one for both
//! supported versions (1.9+ attack cooldowns and off-hand are not modelled yet).

use ghast_data::DigMaterial;
use ghast_protocol::BlockPos;

use crate::common::{DigStatus, Face, Outbound, Vec3};

/// Survival block reach (`ClientPlayerInteractionManager.getReachDistance`).
pub const REACH: f64 = 4.5;

/// What the hands need to know about one block state.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct BlockQuery {
    /// The block is air (`Material.AIR`).
    pub air: bool,
    /// The block is water (eyes in it slow digging).
    pub water: bool,
    /// Version block id (1.8 `id`, 1.16 registry id).
    pub block: u16,
    /// Hardness; negative = unbreakable.
    pub hardness: f32,
    /// Tool group for the speed multiplier.
    pub dig_material: Option<DigMaterial>,
    /// Item ids that harvest the block (empty = any).
    pub harvest_tools: &'static [u16],
    /// Selection (ray) box relative to the block, `None` when rays pass through.
    pub selection: Option<[f64; 6]>,
    /// Stairs (1.8): vanilla's eight-pass half-cube ray test; the passes' block-local boxes
    /// (`None` = skipped pass). When set, `selection` is ignored for rays.
    pub stairs: Option<[Option<[f64; 6]>; 8]>,
    /// Right-clicking the block activates it (containers, doors, levers, …).
    pub activates: bool,
}

/// The held stack as far as digging and using need it.
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct HeldItem {
    /// Item id.
    pub id: u16,
    /// Stack size.
    pub count: u8,
    /// Efficiency enchantment level.
    pub efficiency: u8,
    /// The item places a block (`BlockItem`).
    pub places_block: bool,
    /// The item is used by holding right click (food, potion, bow, sword, milk).
    pub usable: bool,
    /// The item is food (eaten only below a full food bar).
    pub food: bool,
    /// Food that can be eaten at any food level (golden apple).
    pub always_edible: bool,
    /// Tool speed multiplier per dig group, filled by the version (`tool_multiplier`).
    pub tool_speed: Option<fn(DigMaterial, u16) -> f32>,
}

impl BlockQuery {
    /// A solid, instantly breakable block with no tool group, no ray box and no activation;
    /// set the rest with the `with_*` methods.
    #[must_use]
    pub const fn new(block: u16) -> Self {
        BlockQuery {
            air: false,
            water: false,
            block,
            hardness: 0.0,
            dig_material: None,
            harvest_tools: &[],
            selection: None,
            stairs: None,
            activates: false,
        }
    }

    /// Air (id 0, no ray box).
    pub const AIR: BlockQuery = BlockQuery::new(0).with_air(true);

    /// The block is air.
    #[must_use]
    pub const fn with_air(mut self, on: bool) -> Self {
        self.air = on;
        self
    }

    /// The block is water.
    #[must_use]
    pub const fn with_water(mut self, on: bool) -> Self {
        self.water = on;
        self
    }

    /// Hardness (negative: unbreakable).
    #[must_use]
    pub const fn with_hardness(mut self, hardness: f32) -> Self {
        self.hardness = hardness;
        self
    }

    /// Tool group.
    #[must_use]
    pub const fn with_dig_material(mut self, m: Option<DigMaterial>) -> Self {
        self.dig_material = m;
        self
    }

    /// Item ids that harvest the block (empty: any).
    #[must_use]
    pub const fn with_harvest_tools(mut self, tools: &'static [u16]) -> Self {
        self.harvest_tools = tools;
        self
    }

    /// Selection (ray) box relative to the block.
    #[must_use]
    pub const fn with_selection(mut self, b: Option<[f64; 6]>) -> Self {
        self.selection = b;
        self
    }

    /// 1.8 stairs ray passes.
    #[must_use]
    pub const fn with_stairs(mut self, passes: Option<[Option<[f64; 6]>; 8]>) -> Self {
        self.stairs = passes;
        self
    }

    /// Right-clicking activates it.
    #[must_use]
    pub const fn with_activates(mut self, on: bool) -> Self {
        self.activates = on;
        self
    }
}

impl HeldItem {
    /// One item of `id` with nothing else known; set the rest with the `with_*` methods.
    #[must_use]
    pub const fn new(id: u16) -> Self {
        HeldItem {
            id,
            count: 1,
            efficiency: 0,
            places_block: false,
            usable: false,
            food: false,
            always_edible: false,
            tool_speed: None,
        }
    }

    /// Stack size.
    #[must_use]
    pub const fn with_count(mut self, count: u8) -> Self {
        self.count = count;
        self
    }

    /// Efficiency level.
    #[must_use]
    pub const fn with_efficiency(mut self, level: u8) -> Self {
        self.efficiency = level;
        self
    }

    /// The item places a block.
    #[must_use]
    pub const fn with_places_block(mut self, on: bool) -> Self {
        self.places_block = on;
        self
    }

    /// The item is used by holding right click.
    #[must_use]
    pub const fn with_usable(mut self, on: bool) -> Self {
        self.usable = on;
        self
    }

    /// Food (and whether it can be eaten at a full food bar).
    #[must_use]
    pub const fn with_food(mut self, food: bool, always_edible: bool) -> Self {
        self.food = food;
        self.always_edible = always_edible;
        self
    }

    /// Tool speed per dig group.
    #[must_use]
    pub const fn with_tool_speed(mut self, f: Option<fn(DigMaterial, u16) -> f32>) -> Self {
        self.tool_speed = f;
        self
    }
}

impl DigFactors {
    /// On ground.
    #[must_use]
    pub const fn with_on_ground(mut self, on: bool) -> Self {
        self.on_ground = on;
        self
    }

    /// Eyes in water.
    #[must_use]
    pub const fn with_in_water(mut self, on: bool) -> Self {
        self.in_water = on;
        self
    }

    /// Aqua affinity on the helmet.
    #[must_use]
    pub const fn with_aqua_affinity(mut self, on: bool) -> Self {
        self.aqua_affinity = on;
        self
    }

    /// Haste level (amplifier + 1), 0 = none.
    #[must_use]
    pub const fn with_haste(mut self, level: u8) -> Self {
        self.haste = level;
        self
    }

    /// Mining fatigue level (amplifier + 1), 0 = none.
    #[must_use]
    pub const fn with_fatigue(mut self, level: u8) -> Self {
        self.fatigue = level;
        self
    }
}

/// Mining speed modifiers of the player.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct DigFactors {
    /// On ground.
    pub on_ground: bool,
    /// Eyes in water.
    pub in_water: bool,
    /// Aqua affinity on the helmet.
    pub aqua_affinity: bool,
    /// Haste level (amplifier + 1), 0 = none.
    pub haste: u8,
    /// Mining fatigue level (amplifier + 1), 0 = none.
    pub fatigue: u8,
}

/// `Block.calcBlockBreakingData` (float maths): break progress per tick.
#[must_use]
pub fn relative_hardness(b: &BlockQuery, held: Option<&HeldItem>, f: DigFactors) -> f32 {
    let h = b.hardness;
    if h < 0.0 {
        return 0.0;
    }
    let can_harvest =
        b.harvest_tools.is_empty() || held.is_some_and(|i| b.harvest_tools.contains(&i.id));
    // PlayerEntity.getMiningSpeed
    let mut speed = match (held, b.dig_material) {
        (Some(i), Some(m)) => i.tool_speed.map_or(1.0, |t| t(m, i.id)),
        _ => 1.0,
    };
    if speed > 1.0
        && let Some(i) = held
        && i.efficiency > 0
    {
        let e = f32::from(i.efficiency);
        speed += e * e + 1.0;
    }
    if f.haste > 0 {
        speed *= 1.0 + f32::from(f.haste) * 0.2;
    }
    if f.fatigue > 0 {
        speed *= match f.fatigue {
            1 => 0.3,
            2 => 0.09,
            3 => 0.0027,
            _ => 8.1e-4,
        };
    }
    if f.in_water && !f.aqua_affinity {
        speed /= 5.0;
    }
    if !f.on_ground {
        speed /= 5.0;
    }
    if can_harvest {
        speed / h / 30.0
    } else {
        speed / h / 100.0
    }
}

/// `Entity.getRotationVector(pitch, yaw)` with vanilla's float sine table.
#[must_use]
pub fn look_vector(yaw: f32, pitch: f32) -> Vec3 {
    use ghast_physics::math::{cos, sin};
    const RAD: f32 = 0.017_453_292;
    let f = cos(-yaw * RAD - std::f32::consts::PI);
    let f1 = sin(-yaw * RAD - std::f32::consts::PI);
    let f2 = -cos(-pitch * RAD);
    let f3 = sin(-pitch * RAD);
    Vec3::new(f64::from(f1 * f2), f64::from(f3), f64::from(f * f2))
}

/// A block the crosshair is on.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct BlockHit {
    /// The block.
    pub pos: BlockPos,
    /// The face hit.
    pub face: Face,
    /// The point hit (absolute).
    pub hit: Vec3,
    /// Distance from the eyes.
    pub distance: f64,
}

/// Floor of a coordinate as vanilla's `MathHelper.floor`.
fn floor(v: f64) -> i32 {
    let i = v as i32;
    if v < f64::from(i) { i - 1 } else { i }
}

/// `Vec3d.lerpForX` and friends: the point on the segment `a → b` whose `axis`
/// coordinate is `v`, if it lies within the segment.
fn intermediate(a: Vec3, b: Vec3, axis: usize, v: f64) -> Option<Vec3> {
    let d = [b.x - a.x, b.y - a.y, b.z - a.z];
    let o = [a.x, a.y, a.z];
    if d[axis] * d[axis] < 1.0e-7 {
        return None;
    }
    let t = (v - o[axis]) / d[axis];
    (0.0..=1.0)
        .contains(&t)
        .then(|| Vec3::new(a.x + d[0] * t, a.y + d[1] * t, a.z + d[2] * t))
}

fn sq_dist(a: Vec3, b: Vec3) -> f64 {
    let (x, y, z) = (b.x - a.x, b.y - a.y, b.z - a.z);
    x * x + y * y + z * z
}

/// `Block.rayTrace`: the segment against the block's ray bounds, in
/// block-local coordinates; the nearest of the six plane hits (ties go to the earlier plane:
/// west, east, down, up, north, south).
fn block_ray(pos: BlockPos, b: &[f64; 6], start: Vec3, end: Vec3) -> Option<(Vec3, Face)> {
    let off = Vec3::new(f64::from(pos.x), f64::from(pos.y), f64::from(pos.z));
    let s = Vec3::new(start.x - off.x, start.y - off.y, start.z - off.z);
    let e = Vec3::new(end.x - off.x, end.y - off.y, end.z - off.z);
    let in_yz = |v: &Vec3| v.y >= b[1] && v.y <= b[4] && v.z >= b[2] && v.z <= b[5];
    let in_xz = |v: &Vec3| v.x >= b[0] && v.x <= b[3] && v.z >= b[2] && v.z <= b[5];
    let in_xy = |v: &Vec3| v.x >= b[0] && v.x <= b[3] && v.y >= b[1] && v.y <= b[4];
    let candidates = [
        (intermediate(s, e, 0, b[0]).filter(in_yz), Face::West),
        (intermediate(s, e, 0, b[3]).filter(in_yz), Face::East),
        (intermediate(s, e, 1, b[1]).filter(in_xz), Face::Down),
        (intermediate(s, e, 1, b[4]).filter(in_xz), Face::Up),
        (intermediate(s, e, 2, b[2]).filter(in_xy), Face::North),
        (intermediate(s, e, 2, b[5]).filter(in_xy), Face::South),
    ];
    let mut best: Option<(Vec3, Face)> = None;
    for (v, face) in candidates {
        if let Some(v) = v
            && best.is_none_or(|(bv, _)| sq_dist(s, v) < sq_dist(s, bv))
        {
            best = Some((v, face));
        }
    }
    best.map(|(v, f)| (Vec3::new(v.x + off.x, v.y + off.y, v.z + off.z), f))
}

/// What a ray found.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum RayResult {
    /// A block's ray bounds.
    Block(BlockHit),
    /// Nothing; the last block the ray passed that rays go through (vanilla's "miss" result
    /// of the crosshair pick).
    Miss {
        /// That block.
        pos: BlockPos,
        /// The face the ray entered it through.
        face: Face,
        /// The entry point.
        hit: Vec3,
    },
    /// Nothing at all.
    None,
}

/// 1.8 `World.rayTrace(start, end, false, false, return_last)`: walks the blocks from `start`
/// to `end` exactly like vanilla (at most 200 steps; −1e−4 for a −0 plane fraction) and tests
/// each block whose rays collide (`BlockQuery::selection`). Unloaded blocks read as air like
/// the vanilla client's empty chunks.
pub fn ray_trace(
    blocks: &dyn Fn(i32, i32, i32) -> Option<BlockQuery>,
    start: Vec3,
    end: Vec3,
    return_last: bool,
) -> RayResult {
    let nan = |v: Vec3| v.x.is_nan() || v.y.is_nan() || v.z.is_nan();
    if nan(start) || nan(end) {
        return RayResult::None;
    }
    let dist = |hit: Vec3, eyes: Vec3| sq_dist(eyes, hit).sqrt();
    let eyes = start;
    let (ex, ey, ez) = (floor(end.x), floor(end.y), floor(end.z));
    let (mut x, mut y, mut z) = (floor(start.x), floor(start.y), floor(start.z));
    let test = |p: BlockPos, s: Vec3| -> Option<BlockHit> {
        let b = blocks(p.x, p.y, p.z)?;
        let found = if let Some(passes) = &b.stairs {
            // StairsBlock.rayTrace: the pass hit farthest from the ray's end wins (strictly;
            // ties keep the earlier pass).
            let mut best: Option<(Vec3, Face)> = None;
            let mut best_d = 0.0;
            for bounds in passes.iter().flatten() {
                if let Some((hit, face)) = block_ray(p, bounds, s, end) {
                    let d = sq_dist(hit, end);
                    if d > best_d {
                        best = Some((hit, face));
                        best_d = d;
                    }
                }
            }
            best
        } else {
            block_ray(p, &b.selection?, s, end)
        };
        found.map(|(hit, face)| BlockHit {
            pos: p,
            face,
            hit,
            distance: dist(hit, eyes),
        })
    };
    let first = BlockPos::new(x, y, z);
    if let Some(h) = test(first, start) {
        return RayResult::Block(h);
    }
    let mut last = RayResult::None;
    let mut cur = start;
    let mut steps = 200;
    while steps >= 0 {
        steps -= 1;
        if nan(cur) {
            return RayResult::None;
        }
        if x == ex && y == ey && z == ez {
            break;
        }
        let plane = |e: i32, c: i32| {
            if e > c {
                Some(f64::from(c) + 1.0)
            } else if e < c {
                Some(f64::from(c))
            } else {
                None
            }
        };
        let (px, py, pz) = (plane(ex, x), plane(ey, y), plane(ez, z));
        let (dx, dy, dz) = (end.x - cur.x, end.y - cur.y, end.z - cur.z);
        let frac = |p: Option<f64>, o: f64, d: f64| {
            let t = p.map_or(999.0, |p| (p - o) / d);
            // Vanilla's `t == -0.0` also matches +0.0: any zero fraction becomes -1e-4.
            if t == 0.0 { -1.0e-4 } else { t }
        };
        let (tx, ty, tz) = (
            frac(px, cur.x, dx),
            frac(py, cur.y, dy),
            frac(pz, cur.z, dz),
        );
        let face;
        if tx < ty && tx < tz {
            face = if ex > x { Face::West } else { Face::East };
            cur = Vec3::new(px.unwrap_or(999.0), cur.y + dy * tx, cur.z + dz * tx);
        } else if ty < tz {
            face = if ey > y { Face::Down } else { Face::Up };
            cur = Vec3::new(cur.x + dx * ty, py.unwrap_or(999.0), cur.z + dz * ty);
        } else {
            face = if ez > z { Face::North } else { Face::South };
            cur = Vec3::new(cur.x + dx * tz, cur.y + dy * tz, pz.unwrap_or(999.0));
        }
        x = floor(cur.x) - i32::from(face == Face::East);
        y = floor(cur.y) - i32::from(face == Face::Up);
        z = floor(cur.z) - i32::from(face == Face::South);
        let p = BlockPos::new(x, y, z);
        match blocks(x, y, z).filter(|b| b.selection.is_some() || b.stairs.is_some()) {
            Some(_) => {
                if let Some(h) = test(p, cur) {
                    return RayResult::Block(h);
                }
            }
            None => {
                last = RayResult::Miss {
                    pos: p,
                    face,
                    hit: cur,
                }
            }
        }
    }
    if return_last { last } else { RayResult::None }
}

/// The crosshair block: `Entity.rayTrace(reach)` from `eyes` along `look`.
#[must_use]
pub fn pick(
    blocks: &dyn Fn(i32, i32, i32) -> Option<BlockQuery>,
    eyes: Vec3,
    look: Vec3,
    reach: f64,
) -> Option<BlockHit> {
    let end = Vec3::new(
        eyes.x + look.x * reach,
        eyes.y + look.y * reach,
        eyes.z + look.z * reach,
    );
    match ray_trace(blocks, eyes, end, true) {
        RayResult::Block(h) => Some(h),
        _ => None,
    }
}

/// An entity the crosshair is on.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct EntityHit {
    /// The entity id.
    pub id: i32,
    /// The point hit (absolute; the eyes when they are inside the box).
    pub hit: Vec3,
    /// The entity's position (for interact-at offsets).
    pub entity_pos: Vec3,
    /// Distance from the eyes.
    pub distance: f64,
}

/// `Box.method_585` (unnamed in Legacy Yarn): the nearest plane hit of the segment `a → b` on the
/// box (`x` planes, then `y`, then `z`; ties keep the earlier one).
fn box_intercept(b: &[f64; 6], a: Vec3, e: Vec3) -> Option<Vec3> {
    let in_yz = |v: &Vec3| v.y >= b[1] && v.y <= b[4] && v.z >= b[2] && v.z <= b[5];
    let in_xz = |v: &Vec3| v.x >= b[0] && v.x <= b[3] && v.z >= b[2] && v.z <= b[5];
    let in_xy = |v: &Vec3| v.x >= b[0] && v.x <= b[3] && v.y >= b[1] && v.y <= b[4];
    let cands = [
        intermediate(a, e, 0, b[0]).filter(in_yz),
        intermediate(a, e, 0, b[3]).filter(in_yz),
        intermediate(a, e, 1, b[1]).filter(in_xz),
        intermediate(a, e, 1, b[4]).filter(in_xz),
        intermediate(a, e, 2, b[2]).filter(in_xy),
        intermediate(a, e, 2, b[5]).filter(in_xy),
    ];
    let mut best: Option<Vec3> = None;
    for v in cands.into_iter().flatten() {
        if best.is_none_or(|bv| sq_dist(a, v) < sq_dist(a, bv)) {
            best = Some(v);
        }
    }
    best
}

/// Whether the ray from `eyes` along `look` (unit) meets the full cube at `pos` within
/// `reach`, or starts inside it.
#[must_use]
pub(crate) fn ray_hits_cube(eyes: Vec3, look: Vec3, pos: BlockPos, reach: f64) -> bool {
    let (x, y, z) = (f64::from(pos.x), f64::from(pos.y), f64::from(pos.z));
    let b = [x, y, z, x + 1.0, y + 1.0, z + 1.0];
    let inside = eyes.x >= b[0]
        && eyes.x <= b[3]
        && eyes.y >= b[1]
        && eyes.y <= b[4]
        && eyes.z >= b[2]
        && eyes.z <= b[5];
    let end = Vec3::new(
        eyes.x + look.x * reach,
        eyes.y + look.y * reach,
        eyes.z + look.z * reach,
    );
    inside || box_intercept(&b, eyes, end).is_some()
}

/// One pickable entity: id, box (absolute), position.
pub type PickCandidate = (i32, [f64; 6], Vec3);

/// `GameRenderer.updateTargetedEntity`: the entity whose box grown by `border` (1.8:
/// 0.1, 1.9+: 0) the look ray (reach 4.5) hits first, closer than the block hit; dropped
/// beyond 3 blocks (survival). `riding` = the vehicle id (only picked when nothing else is).
#[must_use]
pub fn pick_entity(
    candidates: impl Iterator<Item = PickCandidate>,
    eyes: Vec3,
    look: Vec3,
    block_distance: Option<f64>,
    border: f64,
    riding: Option<i32>,
) -> Option<EntityHit> {
    let d0 = REACH;
    let d1 = block_distance.unwrap_or(d0);
    let end = Vec3::new(
        eyes.x + look.x * d0,
        eyes.y + look.y * d0,
        eyes.z + look.z * d0,
    );
    let mut best: Option<EntityHit> = None;
    let mut d2 = d1;
    for (id, b, pos) in candidates {
        let g = [
            b[0] - border,
            b[1] - border,
            b[2] - border,
            b[3] + border,
            b[4] + border,
            b[5] + border,
        ];
        let hit = box_intercept(&g, eyes, end);
        let inside = eyes.x > g[0]
            && eyes.x < g[3]
            && eyes.y > g[1]
            && eyes.y < g[4]
            && eyes.z > g[2]
            && eyes.z < g[5];
        if inside {
            if d2 >= 0.0 {
                best = Some(EntityHit {
                    id,
                    hit: hit.unwrap_or(eyes),
                    entity_pos: pos,
                    distance: 0.0,
                });
                d2 = 0.0;
            }
        } else if let Some(h) = hit {
            let d3 = sq_dist(eyes, h).sqrt();
            if d3 < d2 || d2 == 0.0 {
                if riding == Some(id) {
                    if d2 == 0.0 {
                        best = Some(EntityHit {
                            id,
                            hit: h,
                            entity_pos: pos,
                            distance: d3,
                        });
                    }
                } else {
                    best = Some(EntityHit {
                        id,
                        hit: h,
                        entity_pos: pos,
                        distance: d3,
                    });
                    d2 = d3;
                }
            }
        }
    }
    let e = best?;
    // Survival: the entity counts only within 3 blocks, and only when closer than the block.
    if sq_dist(eyes, e.hit).sqrt() > 3.0 {
        return None;
    }
    (d2 < d1 || block_distance.is_none()).then_some(e)
}

/// Mouse buttons held in the world (kept until changed; released by a join or respawn).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Buttons {
    /// Left: mine / attack.
    pub left: bool,
    /// Right: use / place.
    pub right: bool,
}

/// What the hands need from the client each tick.
pub(crate) struct HandsIo<'a> {
    /// Block lookup (version-specific facts).
    pub blocks: &'a dyn Fn(i32, i32, i32) -> Option<BlockQuery>,
    /// The crosshair now.
    pub target: Option<BlockHit>,
    /// The held stack's dig / use facts.
    pub held: Option<HeldItem>,
    /// The held stack itself (sent with 1.8 placement packets).
    pub held_stack: Option<ghast_inventory::Stack>,
    /// Food level (food is only eaten below 20 unless always edible).
    pub food: i32,
    /// 1.9+ rules: swing after the click, both hands tried on right click.
    pub modern: bool,
    /// The off-hand stack's facts (1.9+).
    pub off_held: Option<HeldItem>,
    /// The off-hand stack itself.
    pub off_stack: Option<ghast_inventory::Stack>,
    /// Mining speed modifiers.
    pub factors: DigFactors,
    /// Sneaking (skips block activation when holding an item).
    pub sneaking: bool,
    /// The entity the crosshair is on (it wins over `target` when set).
    pub entity: Option<EntityHit>,
    /// Packets out (in order).
    pub out: &'a mut Vec<Outbound>,
    /// Blocks to predict as air (broken on the client).
    pub broken: &'a mut Vec<BlockPos>,
    /// The held stack's count went down by one (a block was placed).
    pub placed: &'a mut bool,
}

impl HandsIo<'_> {
    /// The non-air block at `pos` (`None`: air or not loaded). A block broken earlier in this
    /// tick (by the behaviour's `dig` or the hands) reads as air, like vanilla, which sets it
    /// to air in the world at once: the held button must not start it again in the same tick.
    fn solid(&self, pos: BlockPos) -> Option<BlockQuery> {
        if self.broken.contains(&pos) {
            return None;
        }
        (self.blocks)(pos.x, pos.y, pos.z).filter(|b| !b.air)
    }
}

/// `ClientPlayerInteractionManager` + the `MinecraftClient` click state.
#[derive(Debug, Clone, Default)]
pub struct Hands {
    hitting: bool,
    current: Option<BlockPos>,
    damage: f32,
    hit_item: Option<u16>,
    hit_delay: u32,
    left_click_counter: u32,
    right_click_delay: u32,
    using: bool,
    left_was: bool,
    right_was: bool,
    /// Blocks broken (finish sent).
    pub broken: u64,
    /// 1.9+: ticks since the last swing / attack (`ticksSinceLastSwing`, attack cooldown).
    pub ticks_since_swing: u32,
}

impl Hands {
    /// A new player: nothing held, nothing in progress.
    pub fn reset(&mut self) {
        let broken = self.broken;
        *self = Hands::default();
        self.broken = broken;
    }

    /// The block being broken and its progress 0..1.
    #[must_use]
    pub fn mining(&self) -> Option<(BlockPos, f32)> {
        match (self.hitting, self.current) {
            (true, Some(p)) => Some((p, self.damage.min(1.0))),
            _ => None,
        }
    }

    /// Using the held item (eating, blocking, drawing a bow).
    #[must_use]
    pub fn using_item(&self) -> bool {
        self.using
    }

    /// The server finished our item use (entity status 9) or the held slot changed.
    pub fn stop_using(&mut self) {
        self.using = false;
    }

    /// One tick with the buttons as held now.
    /// 1.9+ attack strength: `clamp((ticks_since_swing + 0.5) / (20 / attack_speed), 0, 1)`
    /// (vanilla `getCooledAttackStrength(0.5F)`; attack speed 4.0 with an empty hand).
    #[must_use]
    pub fn attack_strength(&self, attack_speed: f64) -> f32 {
        let period = (1.0 / attack_speed * 20.0) as f32;
        ((self.ticks_since_swing as f32 + 0.5) / period).clamp(0.0, 1.0)
    }

    /// `PlayerController.attackEntity`: the attack packet (1.16: then the cooldown resets).
    pub(crate) fn attack(&mut self, id: i32, io: &mut HandsIo<'_>) {
        io.out.push(Outbound::UseEntity {
            target: id,
            action: crate::common::EntityUse::Attack,
            off_hand: false,
            sneaking: io.sneaking,
        });
        self.ticks_since_swing = 0;
    }

    /// Right click on an entity: interact-at then interact (both assumed not handled, so the
    /// item use follows like vanilla's fall-through for plain entities).
    fn interact(&mut self, e: EntityHit, off_hand: bool, io: &mut HandsIo<'_>) {
        let rel = Vec3::new(
            e.hit.x - e.entity_pos.x,
            e.hit.y - e.entity_pos.y,
            e.hit.z - e.entity_pos.z,
        );
        io.out.push(Outbound::UseEntity {
            target: e.id,
            action: crate::common::EntityUse::InteractAt(rel),
            off_hand,
            sneaking: io.sneaking,
        });
        io.out.push(Outbound::UseEntity {
            target: e.id,
            action: crate::common::EntityUse::Interact,
            off_hand,
            sneaking: io.sneaking,
        });
    }

    pub(crate) fn tick(&mut self, left: bool, right: bool, io: &mut HandsIo<'_>) {
        self.ticks_since_swing = self.ticks_since_swing.saturating_add(1);
        if self.left_click_counter > 0 {
            self.left_click_counter -= 1;
        }
        if self.right_click_delay > 0 {
            self.right_click_delay -= 1;
        }
        let t = io.target;
        if self.using {
            if !right {
                // stopUsingItem
                io.out.push(Outbound::Dig {
                    status: DigStatus::ReleaseUseItem,
                    pos: BlockPos::new(0, 0, 0),
                    face: Face::Down,
                });
                self.using = false;
            }
        } else {
            if left && !self.left_was {
                self.click_mouse(t, io);
            }
            if right && !self.right_was {
                self.right_click_mouse(t, io);
            }
        }
        if right && self.right_click_delay == 0 && !self.using {
            self.right_click_mouse(t, io);
        }
        self.send_click_block_to_controller(left, t, io);
        self.left_was = left;
        self.right_was = right;
    }

    fn click_mouse(&mut self, t: Option<BlockHit>, io: &mut HandsIo<'_>) {
        if self.left_click_counter > 0 {
            return;
        }
        if let Some(e) = io.entity {
            if io.modern {
                self.attack(e.id, io);
                io.out.push(Outbound::Swing);
            } else {
                io.out.push(Outbound::Swing);
                self.attack(e.id, io);
            }
            return;
        }
        if io.modern {
            // 1.16 MinecraftClient.doAttack: the action, then the swing; a block hit on air falls
            // through to the miss case.
            match t {
                Some(hit) if io.solid(hit.pos).is_some() => {
                    self.click_block(hit.pos, hit.face, io);
                }
                _ => {
                    self.left_click_counter = 10;
                    // resetCooldown on a miss.
                    self.ticks_since_swing = 0;
                }
            }
            io.out.push(Outbound::Swing);
            return;
        }
        io.out.push(Outbound::Swing);
        match t {
            Some(hit) => {
                if io.solid(hit.pos).is_some() {
                    self.click_block(hit.pos, hit.face, io);
                }
            }
            None => self.left_click_counter = 10,
        }
    }

    fn send_click_block_to_controller(
        &mut self,
        left: bool,
        t: Option<BlockHit>,
        io: &mut HandsIo<'_>,
    ) {
        if !left {
            self.left_click_counter = 0;
        }
        if self.left_click_counter > 0 || self.using {
            return;
        }
        match t.filter(|_| io.entity.is_none()) {
            Some(hit) if left => {
                let solid = io.solid(hit.pos).is_some();
                if solid && self.damage_block(hit.pos, hit.face, io) {
                    io.out.push(Outbound::Swing);
                }
            }
            _ => self.reset_block_removing(io),
        }
    }

    fn hitting_position(&self, pos: BlockPos, io: &HandsIo<'_>) -> bool {
        self.hitting && self.current == Some(pos) && self.hit_item == io.held.map(|h| h.id)
    }

    /// `attackBlock`: START (aborting a previous block), instant break when fast enough.
    pub(crate) fn click_block(&mut self, pos: BlockPos, face: Face, io: &mut HandsIo<'_>) {
        if self.hitting && self.hitting_position(pos, io) {
            return;
        }
        if self.hitting
            && let Some(cur) = self.current
        {
            io.out.push(Outbound::Dig {
                status: DigStatus::Abort,
                pos: cur,
                face,
            });
        }
        io.out.push(Outbound::Dig {
            status: DigStatus::Start,
            pos,
            face,
        });
        if let Some(b) = io.solid(pos)
            && relative_hardness(&b, io.held.as_ref(), io.factors) >= 1.0
        {
            self.destroyed(pos, io);
            return;
        }
        self.hitting = true;
        self.current = Some(pos);
        self.hit_item = io.held.map(|h| h.id);
        self.damage = 0.0;
    }

    /// `updateBlockBreakingProgress`.
    fn damage_block(&mut self, pos: BlockPos, face: Face, io: &mut HandsIo<'_>) -> bool {
        if self.hit_delay > 0 {
            self.hit_delay -= 1;
            return true;
        }
        if !self.hitting_position(pos, io) {
            self.click_block(pos, face, io);
            return true;
        }
        let Some(b) = io.solid(pos) else {
            self.hitting = false;
            return false;
        };
        self.damage += relative_hardness(&b, io.held.as_ref(), io.factors);
        if self.damage >= 1.0 {
            self.hitting = false;
            io.out.push(Outbound::Dig {
                status: DigStatus::Finish,
                pos,
                face,
            });
            self.destroyed(pos, io);
            self.damage = 0.0;
            self.hit_delay = 5;
        }
        true
    }

    /// `breakBlock`: air on the client; the current block moves to y = −1.
    fn destroyed(&mut self, pos: BlockPos, io: &mut HandsIo<'_>) {
        io.broken.push(pos);
        if let Some(c) = self.current {
            self.current = Some(BlockPos::new(c.x, -1, c.z));
        }
        self.broken += 1;
    }

    /// `cancelBlockBreaking`.
    pub(crate) fn reset_block_removing(&mut self, io: &mut HandsIo<'_>) {
        if !self.hitting {
            return;
        }
        if let Some(cur) = self.current {
            io.out.push(Outbound::Dig {
                status: DigStatus::Abort,
                pos: cur,
                face: Face::Down,
            });
        }
        self.hitting = false;
        self.damage = 0.0;
    }

    /// `doUse` (nothing while a block is being hit).
    fn right_click_mouse(&mut self, t: Option<BlockHit>, io: &mut HandsIo<'_>) {
        if self.hitting {
            return;
        }
        self.right_click_delay = 4;
        if io.modern {
            self.right_click_modern(t, io);
            return;
        }
        if let Some(e) = io.entity {
            // 1.8: interact-at, interact; not handled -> the item is used.
            self.interact(e, false, io);
            if let Some(h) = io.held {
                io.out.push(Outbound::UseItem {
                    held: io.held_stack.clone(),
                    off_hand: false,
                });
                if h.usable && (!h.food || h.always_edible || io.food < 20) {
                    self.using = true;
                }
            }
            return;
        }
        let mut fall_through = true;
        if let Some(hit) = t
            && let Some(b) = io.solid(hit.pos)
        {
            if self.right_click_block(hit, &b, io) {
                fall_through = false;
                io.out.push(Outbound::Swing);
            }
            if io.held.is_none() {
                return;
            }
        }
        if fall_through && let Some(h) = io.held {
            // interactItem: the item itself (position -1, face 255).
            io.out.push(Outbound::UseItem {
                held: io.held_stack.clone(),
                off_hand: false,
            });
            // FoodItem.onStartUse: only when the player can eat.
            if h.usable && (!h.food || h.always_edible || io.food < 20) {
                self.using = true;
            }
        }
    }

    /// 1.9+ `doItemUse` (1.16.5 Yarn): main hand, then off hand; per hand the block (activation, then
    /// the item on the block), then the item itself; the first success / consume ends it.
    fn right_click_modern(&mut self, t: Option<BlockHit>, io: &mut HandsIo<'_>) {
        let any_item = io.held.is_some() || io.off_held.is_some();
        for off_hand in [false, true] {
            let (held, stack) = if off_hand {
                (io.off_held, io.off_stack.clone())
            } else {
                (io.held, io.held_stack.clone())
            };
            let swing = if off_hand {
                Outbound::SwingOffHand
            } else {
                Outbound::Swing
            };
            if let Some(e) = io.entity {
                self.interact(e, off_hand, io);
            } else if let Some(hit) = t
                && let Some(b) = io.solid(hit.pos)
            {
                let cursor = Vec3::new(
                    hit.hit.x - f64::from(hit.pos.x),
                    hit.hit.y - f64::from(hit.pos.y),
                    hit.hit.z - f64::from(hit.pos.z),
                );
                io.out.push(Outbound::Place {
                    pos: hit.pos,
                    face: hit.face,
                    cursor,
                    held: stack.clone(),
                    off_hand,
                });
                // Sneaking with something in either hand skips the block's activation.
                if b.activates && !(io.sneaking && any_item) {
                    io.out.push(swing);
                    return;
                }
                if let Some(h) = held
                    && h.places_block
                    && h.count > 0
                {
                    if !off_hand {
                        *io.placed = true;
                    }
                    io.out.push(swing);
                    return;
                }
            }
            if let Some(h) = held {
                io.out.push(Outbound::UseItem {
                    held: stack,
                    off_hand,
                });
                if h.usable && (!h.food || h.always_edible || io.food < 20) {
                    self.using = true;
                    return;
                }
            }
        }
    }

    /// `onRightClick`: the placement packet; returns whether something was activated or
    /// placed (the caller swings).
    pub(crate) fn right_click_block(
        &mut self,
        hit: BlockHit,
        b: &BlockQuery,
        io: &mut HandsIo<'_>,
    ) -> bool {
        let cursor = Vec3::new(
            f64::from((hit.hit.x - f64::from(hit.pos.x)) as f32),
            f64::from((hit.hit.y - f64::from(hit.pos.y)) as f32),
            f64::from((hit.hit.z - f64::from(hit.pos.z)) as f32),
        );
        let activated = b.activates && (!io.sneaking || io.held.is_none());
        io.out.push(Outbound::Place {
            pos: hit.pos,
            face: hit.face,
            cursor,
            held: io.held_stack.clone(),
            off_hand: false,
        });
        if activated {
            return true;
        }
        match io.held {
            Some(h) if h.places_block && h.count > 0 => {
                *io.placed = true;
                true
            }
            _ => false,
        }
    }
}

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

    fn stone() -> BlockQuery {
        BlockQuery {
            air: false,
            water: false,
            block: 1,
            hardness: 1.5,
            dig_material: Some(DigMaterial::Rock),
            harvest_tools: &[270, 274],
            selection: Some([0.0, 0.0, 0.0, 1.0, 1.0, 1.0]),
            stairs: None,
            activates: false,
        }
    }

    #[test]
    fn hand_stone_time() {
        // Stone by hand, on ground: 1 / 1.5 / 100 per tick; the f32 sum (as vanilla's
        // currentBreakingProgress) reaches 1 on the 151st tick, not the 150th.
        let f = DigFactors {
            on_ground: true,
            ..DigFactors::default()
        };
        let per_tick = relative_hardness(&stone(), None, f);
        let mut d = 0.0_f32;
        let mut n = 0;
        while d < 1.0 {
            d += per_tick;
            n += 1;
        }
        assert_eq!(n, 151);
    }

    #[test]
    fn look_south_hits_block() {
        let look = look_vector(0.0, 0.0);
        assert!(look.z > 0.99 && look.x.abs() < 1e-3);
        let blocks = |x: i32, y: i32, z: i32| {
            Some(if (x, y, z) == (0, 1, 2) {
                stone()
            } else {
                BlockQuery {
                    air: true,
                    selection: None,
                    ..stone()
                }
            })
        };
        let hit = pick(&blocks, Vec3::new(0.5, 1.62, 0.5), look, REACH).unwrap();
        assert_eq!(hit.pos, BlockPos::new(0, 1, 2));
        assert_eq!(hit.face, Face::North);
        assert!((hit.distance - 1.5).abs() < 1e-3);
    }

    fn io_blocks(x: i32, y: i32, z: i32) -> Option<BlockQuery> {
        Some(if (x, y, z) == (0, 0, 0) {
            stone()
        } else {
            BlockQuery {
                air: true,
                selection: None,
                ..stone()
            }
        })
    }

    fn kinds(out: &[Outbound]) -> Vec<&'static str> {
        out.iter()
            .map(|o| match o {
                Outbound::Place {
                    off_hand: false, ..
                } => "place_main",
                Outbound::Place { off_hand: true, .. } => "place_off",
                Outbound::UseItem {
                    off_hand: false, ..
                } => "use_main",
                Outbound::UseItem { off_hand: true, .. } => "use_off",
                Outbound::Swing => "swing",
                Outbound::SwingOffHand => "swing_off",
                Outbound::Dig { .. } => "dig",
                _ => "other",
            })
            .collect()
    }

    /// 1.16 right click: empty hands try both hands on the block; a block item places with
    /// the main hand and swings.
    #[test]
    fn modern_right_click_hands() {
        let hit = Some(BlockHit {
            pos: BlockPos::new(0, 0, 0),
            face: Face::Up,
            hit: Vec3::new(0.5, 1.0, 0.5),
            distance: 1.6,
        });
        let run = |held: Option<HeldItem>| {
            let mut h = Hands::default();
            let (mut out, mut broken, mut placed) = (Vec::new(), Vec::new(), false);
            let mut io = HandsIo {
                blocks: &io_blocks,
                target: hit,
                held,
                held_stack: None,
                food: 20,
                modern: true,
                off_held: None,
                off_stack: None,
                entity: None,
                factors: DigFactors::default(),
                sneaking: false,
                out: &mut out,
                broken: &mut broken,
                placed: &mut placed,
            };
            h.tick(false, true, &mut io);
            kinds(&out)
        };
        assert_eq!(run(None), ["place_main", "place_off"]);
        let dirt = HeldItem {
            id: 3,
            count: 10,
            places_block: true,
            ..HeldItem::default()
        };
        assert_eq!(run(Some(dirt)), ["place_main", "swing"]);
        // An item that is neither a block nor usable: place on the block, then use it.
        let stick = HeldItem {
            id: 280,
            count: 1,
            ..HeldItem::default()
        };
        assert_eq!(run(Some(stick)), ["place_main", "use_main", "place_off"]);
    }

    /// Pressing the left button on an instant-break block sends one START: the held-button
    /// pass of the same tick sees the block as air (vanilla breaks it in the world at once),
    /// for 1.8 and 1.16 alike. Also with a block the behaviour broke earlier in the tick.
    #[test]
    fn instant_break_press_starts_once() {
        fn instant(x: i32, y: i32, z: i32) -> Option<BlockQuery> {
            Some(if (x, y, z) == (0, 0, 0) {
                BlockQuery {
                    hardness: 0.0,
                    ..stone()
                }
            } else {
                BlockQuery {
                    air: true,
                    selection: None,
                    ..stone()
                }
            })
        }
        let hit = Some(BlockHit {
            pos: BlockPos::new(0, 0, 0),
            face: Face::Up,
            hit: Vec3::new(0.5, 1.0, 0.5),
            distance: 1.6,
        });
        for modern in [false, true] {
            for pre_broken in [false, true] {
                let mut h = Hands::default();
                let (mut out, mut placed) = (Vec::new(), false);
                let mut broken = if pre_broken {
                    vec![BlockPos::new(0, 0, 0)]
                } else {
                    Vec::new()
                };
                let mut io = HandsIo {
                    blocks: &instant,
                    target: hit,
                    held: None,
                    held_stack: None,
                    food: 20,
                    modern,
                    off_held: None,
                    off_stack: None,
                    entity: None,
                    factors: DigFactors::default(),
                    sneaking: false,
                    out: &mut out,
                    broken: &mut broken,
                    placed: &mut placed,
                };
                h.tick(true, false, &mut io);
                let starts = out
                    .iter()
                    .filter(|o| {
                        matches!(
                            o,
                            Outbound::Dig {
                                status: DigStatus::Start,
                                ..
                            }
                        )
                    })
                    .count();
                let want = usize::from(!pre_broken);
                assert_eq!(
                    starts, want,
                    "modern {modern} pre_broken {pre_broken}: {out:?}"
                );
                assert_eq!(h.broken, want as u64);
            }
        }
    }

    #[test]
    fn entity_pick_rules() {
        let eyes = Vec3::new(0.5, 1.62, 0.5);
        let look = look_vector(0.0, 0.0); // +z
        let at = |z: f64| {
            (
                7,
                [0.2, 1.0, z, 0.8, 2.0, z + 0.6],
                Vec3::new(0.5, 1.0, z + 0.3),
            )
        };
        // 2 blocks ahead: hit on the north face, grown by the 1.8 border.
        let hit = pick_entity([at(2.5)].into_iter(), eyes, look, None, 0.1, None).unwrap();
        assert_eq!(hit.id, 7);
        assert!((hit.hit.z - 2.4).abs() < 1e-9, "{hit:?}");
        // Behind a block hit at 1.5: not picked.
        assert!(pick_entity([at(2.5)].into_iter(), eyes, look, Some(1.5), 0.1, None).is_none());
        // Beyond 3 blocks: not picked (survival).
        assert!(pick_entity([at(3.6)].into_iter(), eyes, look, None, 0.0, None).is_none());
        // Eyes inside the box: picked at distance 0.
        let inside = (8, [0.0, 1.0, 0.0, 1.0, 2.0, 1.0], Vec3::new(0.5, 1.0, 0.5));
        assert_eq!(
            pick_entity([inside].into_iter(), eyes, look, None, 0.0, None).map(|h| h.distance),
            Some(0.0)
        );
    }

    /// 1.16 left click: block_dig start, then the swing (1.8: swing first).
    #[test]
    fn modern_left_click_order() {
        let hit = Some(BlockHit {
            pos: BlockPos::new(0, 0, 0),
            face: Face::Up,
            hit: Vec3::new(0.5, 1.0, 0.5),
            distance: 1.6,
        });
        for (modern, want) in [(true, ["dig", "swing"]), (false, ["swing", "dig"])] {
            let mut h = Hands::default();
            let (mut out, mut broken, mut placed) = (Vec::new(), Vec::new(), false);
            let mut io = HandsIo {
                blocks: &io_blocks,
                target: hit,
                held: None,
                held_stack: None,
                food: 20,
                modern,
                off_held: None,
                off_stack: None,
                entity: None,
                factors: DigFactors::default(),
                sneaking: false,
                out: &mut out,
                broken: &mut broken,
                placed: &mut placed,
            };
            h.click_mouse(hit, &mut io);
            assert_eq!(kinds(&out)[..2], want);
        }
    }

    #[test]
    fn dig_sequence() {
        let blocks = |x: i32, y: i32, z: i32| {
            Some(if (x, y, z) == (0, 0, 0) {
                BlockQuery {
                    hardness: 0.6,
                    ..stone()
                }
            } else {
                BlockQuery {
                    air: true,
                    selection: None,
                    ..stone()
                }
            })
        };
        let target = Some(BlockHit {
            pos: BlockPos::new(0, 0, 0),
            face: Face::Up,
            hit: Vec3::new(0.5, 1.0, 0.5),
            distance: 1.6,
        });
        let mut h = Hands::default();
        let mut out = Vec::new();
        let mut broken = Vec::new();
        let mut placed = false;
        let mut ticks = 0;
        while broken.is_empty() && ticks < 200 {
            let mut io = HandsIo {
                blocks: &blocks,
                target,
                held: None,
                held_stack: None,
                food: 20,
                modern: false,
                off_held: None,
                off_stack: None,
                entity: None,
                factors: DigFactors {
                    on_ground: true,
                    ..DigFactors::default()
                },
                sneaking: false,
                out: &mut out,
                broken: &mut broken,
                placed: &mut placed,
            };
            h.tick(true, false, &mut io);
            ticks += 1;
        }
        // 0.6 hardness, not harvestable by hand: 1/0.6/100 per tick; the f32 sum reaches 1 on
        // the 61st tick (damage is added from the START tick on).
        assert_eq!(broken, [BlockPos::new(0, 0, 0)]);
        let digs: Vec<_> = out
            .iter()
            .filter_map(|o| match o {
                Outbound::Dig { status, .. } => Some(*status),
                _ => None,
            })
            .collect();
        assert_eq!(digs, [DigStatus::Start, DigStatus::Finish]);
        assert_eq!(ticks, 61);
        // The click swings, and every damage tick swings (two on the first tick).
        assert_eq!(
            out.iter().filter(|o| matches!(o, Outbound::Swing)).count(),
            62
        );
    }
}