ghast-physics 0.5.6

Vanilla-exact, pure and deterministic player movement for the ghast Minecraft Java Edition client library (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3), verified bit for bit against the real game
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
//! The generic non-living entity of the modern core: the parts of vanilla's `Entity` that the
//! projectiles, item entities, experience orbs, primed TNT and falling blocks share — position and
//! box, `Entity.move` with its collision response, the inside-block effects, the fluid update,
//! the entity random, the block clip of a projectile and the rotation helpers.
//!
//! Every side- or version-dependent step reads a [`Side`] and the [`Rules`] row; no step reads
//! the player's state. The player keeps its own copies in `player.rs` (its tick path is tuned for
//! the bench and is not shared).

use super::collide::{Placed, Plain, ShapeCtx, World, collide, make_box, placed_shape};
use super::fluid::kind;
use super::inside::{Movement, Visited, axis_order, for_each_block_between};
use super::math::{V3, approx_equal, bx, deflate, floor, intersects, java_max, java_min, mv};
use super::rules::Rules;
use super::rules::shared::{
    BlockKind, VoxelClass, VoxelShapeRef, block_flags as bf, state_flags as sf,
};
use crate::math::Aabb;
use crate::pick::{BlockHit, Cells, Direction, HitKind};
use crate::world::BlockView;

/// Which game's tick runs: the server's (what really happens) or a client's (what a vanilla
/// client shows between two server updates of the entity).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Side {
    /// The server's tick (`Level.isClientSide()` false; the entity is authoritative there).
    Server,
    /// A client's tick of an entity the server owns.
    Client,
}

// ---------------------------------------------------------------------------------------------
// The entity random

/// `LegacyRandomSource` (the 48-bit linear congruential generator of `java.util.Random`), the
/// random an entity is created with (`RandomSource.create(seed)`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct LegacyRandom {
    seed: i64,
}

const MULTIPLIER: i64 = 0x5_DEEC_E66D;
const MASK: i64 = (1 << 48) - 1;

impl LegacyRandom {
    pub(crate) fn new(seed: i64) -> LegacyRandom {
        LegacyRandom {
            seed: (seed ^ MULTIPLIER) & MASK,
        }
    }

    fn next(&mut self, bits: u32) -> i32 {
        self.seed = self.seed.wrapping_mul(MULTIPLIER).wrapping_add(11) & MASK;
        (self.seed >> (48 - bits)) as i32
    }

    /// `nextFloat()`: 24 bits times `2^-24` in float.
    pub(crate) fn next_float(&mut self) -> f32 {
        self.next(24) as f32 * 5.960_464_5e-8_f32
    }

    /// `nextDouble()`: 53 bits times `2^-53`.
    pub(crate) fn next_double(&mut self) -> f64 {
        let a = i64::from(self.next(26));
        let b = i64::from(self.next(27));
        ((a << 27) + b) as f64 * f64::from(1.110_223e-16_f32)
    }

    /// `triangle(mean, spread)`: `mean + spread * (nextDouble() - nextDouble())`.
    pub(crate) fn triangle(&mut self, mean: f64, spread: f64) -> f64 {
        let a = self.next_double();
        let b = self.next_double();
        mean + spread * (a - b)
    }

    /// The draws of `Entity.doWaterSplashEffect` for a box `width` wide (sound pitch, then the
    /// bubble and splash particles); none of them moves anything.
    pub(crate) fn splash(&mut self, width: f32) {
        self.next_float();
        self.next_float();
        let n = 1.0f32 + width * 20.0;
        let mut i = 0;
        while (i as f32) < n {
            self.next_double();
            self.next_double();
            self.next_double();
            i += 1;
        }
        let mut i = 0;
        while (i as f32) < n {
            self.next_double();
            self.next_double();
            i += 1;
        }
    }
}

// ---------------------------------------------------------------------------------------------
// Rotation

/// The two 257-entry tables of `Mth.atan2` (the same values since 1.8).
#[path = "../v1_8/atan_table.rs"]
#[allow(dead_code, clippy::duplicate_mod)]
mod atan_table;

/// `Mth.atan2` (table-driven, not `Math.atan2`).
pub(crate) fn atan2(mut y: f64, mut x: f64) -> f64 {
    let d = x * x + y * y;
    if d.is_nan() {
        return f64::NAN;
    }
    let neg_y = y < 0.0;
    if neg_y {
        y = -y;
    }
    let neg_x = x < 0.0;
    if neg_x {
        x = -x;
    }
    let steep = y > x;
    if steep {
        core::mem::swap(&mut x, &mut y);
    }
    // Mth.fastInvSqrt
    let half = 0.5 * d;
    let r = f64::from_bits((6_910_469_410_427_058_090_i64 - ((d.to_bits() as i64) >> 1)) as u64);
    let r = r * (1.5 - half * r * r);
    x *= r;
    y *= r;
    let bias = f64::from_bits(4_805_340_802_404_319_232);
    let yp = bias + y;
    let i = yp.to_bits() as i32 as usize;
    let phi = f64::from_bits(atan_table::ARCSINE[i]);
    let c = f64::from_bits(atan_table::COSINE[i]);
    let s = yp - bias;
    let sd = y * c - x * s;
    let dd = (6.0 + sd * sd) * sd * 0.166_666_666_666_666_66;
    let mut t = phi + dd;
    if steep {
        t = core::f64::consts::FRAC_PI_2 - t;
    }
    if neg_x {
        t = core::f64::consts::PI - t;
    }
    if neg_y {
        t = -t;
    }
    t
}

/// `(float)(radians * Mth.RAD_TO_DEG)`: the source's `180.0F / (float)Math.PI` is one float
/// constant (`57.295776F`) in the class files.
#[inline]
pub(crate) fn degrees(radians: f64) -> f32 {
    (radians * f64::from(180.0f32 / core::f32::consts::PI)) as f32
}

/// `Projectile.lerpRotation(rotO, rot)`: the old angle brought within 180 of the new one, then
/// `Mth.lerp(0.2F, rotO, rot)`.
pub(crate) fn lerp_rotation(mut o: f32, r: f32) -> f32 {
    while r - o < -180.0 {
        o -= 360.0;
    }
    while r - o >= 180.0 {
        o += 360.0;
    }
    o + 0.2 * (r - o)
}

// ---------------------------------------------------------------------------------------------
// The body

/// Up to this many movements are recorded in a tick (vanilla keeps 100; these entities move at
/// most twice).
const MOVES: usize = 4;

/// The `Entity` fields the non-living modern entities read and write.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Body {
    pub pos: V3,
    /// `xo, yo, zo` (set when the tick starts).
    pub old: V3,
    pub vel: V3,
    pub bb: Aabb,
    pub width: f32,
    pub height: f32,
    pub eye_height: f32,
    /// The box is lowered by this much (a wind charge's 0.15).
    pub box_drop: f32,
    /// `getBlockPosBelowThatAffectsMyMovement` offset (0.500001; items and orbs 0.999999).
    pub below_offset: f32,
    pub yaw: f32,
    pub pitch: f32,
    pub yaw_o: f32,
    pub pitch_o: f32,
    pub on_ground: bool,
    pub hcol: bool,
    pub vcol: bool,
    pub vcol_below: bool,
    pub fall: f64,
    pub stuck: V3,
    /// `wasTouchingWater` (`isInWater()`).
    pub in_water: bool,
    pub water_height: f64,
    pub lava_height: f64,
    pub eye_in_water: bool,
    pub first_tick: bool,
    pub supporting: Option<[i32; 3]>,
    pub no_blocks: bool,
    pub no_physics: bool,
    pub removed: bool,
    pub tick_count: i32,
    pub moves: [Option<Movement>; MOVES],
    /// `finalMovementsThisTick` of the last `applyEffectsFromBlocks`.
    pub last_moves: [Option<Movement>; MOVES + 1],
    pub rng: LegacyRandom,
    /// The old position and rotation the next tick starts from instead of the current ones (a
    /// client copy whose interpolation step moved it after `setOldPosAndRot`).
    pub pending_old: Option<(V3, f32, f32)>,
    /// The movements `Entity.move` made this tick (`recordMovement`; at most [`MOVED`]).
    pub moved: [[f64; 3]; MOVED],
    pub moved_n: u8,
}

/// The most movements of one tick [`Body::moved`] keeps.
pub(crate) const MOVED: usize = 4;

impl Body {
    pub(crate) fn new(pos: V3, vel: V3, width: f32, height: f32, eye_height: f32) -> Body {
        let mut b = Body {
            pos,
            old: pos,
            vel,
            bb: make_box(width, height, pos.x, pos.y, pos.z),
            width,
            height,
            eye_height,
            box_drop: 0.0,
            below_offset: 0.500_001,
            yaw: 0.0,
            pitch: 0.0,
            yaw_o: 0.0,
            pitch_o: 0.0,
            on_ground: false,
            hcol: false,
            vcol: false,
            vcol_below: false,
            fall: 0.0,
            stuck: V3::ZERO,
            in_water: false,
            water_height: 0.0,
            lava_height: 0.0,
            eye_in_water: false,
            first_tick: true,
            supporting: None,
            no_blocks: false,
            no_physics: false,
            removed: false,
            tick_count: 0,
            moves: [None; MOVES],
            last_moves: [None; MOVES + 1],
            rng: LegacyRandom::new(0),
            pending_old: None,
            moved: [[0.0; 3]; MOVED],
            moved_n: 0,
        };
        b.set_pos(pos);
        b
    }

    /// `Entity.setPos`: the position and the box made there.
    pub(crate) fn set_pos(&mut self, p: V3) {
        self.pos = p;
        self.bb = self.box_at(p);
    }

    /// `makeBoundingBox(position)`.
    pub(crate) fn box_at(&self, p: V3) -> Aabb {
        if self.box_drop == 0.0 {
            make_box(self.width, self.height, p.x, p.y, p.z)
        } else {
            let w = f64::from(self.width / 2.0);
            let y = p.y - f64::from(self.box_drop);
            bx(
                p.x - w,
                y,
                p.z - w,
                p.x + w,
                y + f64::from(self.height),
                p.z + w,
            )
        }
    }

    /// `ClientLevel` / `ServerLevel.tickNonPassenger` before the entity's own tick:
    /// `setOldPosAndRot`, `tickCount++`.
    pub(crate) fn start_tick(&mut self) {
        if let Some((p, y, x)) = self.pending_old.take() {
            self.old = p;
            self.yaw_o = y;
            self.pitch_o = x;
        } else {
            self.old = self.pos;
            self.yaw_o = self.yaw;
            self.pitch_o = self.pitch;
        }
        self.moved_n = 0;
        self.tick_count += 1;
    }

    /// `Entity.recordMovement` (what a 26.3 client's interpolation takes over).
    #[inline]
    fn note_moved(&mut self, m: V3) {
        if usize::from(self.moved_n) < MOVED {
            self.moved[usize::from(self.moved_n)] = m.arr();
            self.moved_n += 1;
        }
    }

    /// The collision context of the entity (`CollisionContext.of(entity)` of a non-living one).
    pub(crate) fn ctx(&self) -> ShapeCtx {
        ShapeCtx {
            feet_y: self.pos.y,
            descending: false,
            fall_distance: self.fall,
            leather_boots: false,
        }
    }

    /// `Entity.applyGravity` with the entity's gravity.
    #[inline]
    pub(crate) fn apply_gravity(&mut self, g: f64) {
        if g != 0.0 {
            self.vel = self.vel.add(V3::new(0.0, -g, 0.0));
        }
    }

    /// `isInLava()`: not on the first tick.
    pub(crate) fn in_lava(&self) -> bool {
        !self.first_tick && self.lava_height > 0.0
    }

    /// `blockPosition()`.
    pub(crate) fn block_pos(&self) -> [i32; 3] {
        [floor(self.pos.x), floor(self.pos.y), floor(self.pos.z)]
    }

    fn record_movement(&mut self, m: Movement) {
        if let Some(slot) = self.moves.iter_mut().find(|m| m.is_none()) {
            *slot = Some(m);
        } else {
            // Merge the first two (vanilla does that at 100).
            let a = self.moves[0].unwrap_or(m);
            let b = self.moves[1].unwrap_or(m);
            self.moves.copy_within(2.., 1);
            self.moves[0] = Some(Movement {
                from: a.from,
                to: b.to,
                axis_dependent: None,
            });
            self.moves[MOVES - 1] = Some(m);
        }
    }
}

/// The world the entity code reads (no other entities; the world border of the view).
pub(crate) type Env<'a, R, W> = World<'a, R, W, Plain>;

/// Builds the entity world over a block view and calls `f` with it.
pub(crate) fn with_env<R: Rules, W: BlockView<State = R::State>, T>(
    world: &W,
    f: impl FnOnce(&Env<'_, R, W>) -> T,
) -> T {
    let border = super::collide::Border::new(&world.world_border());
    let w = World::<R, W, Plain> {
        w: world,
        border: &border,
        min_y: -64,
        max_y: 319,
        ext: Plain,
        _r: core::marker::PhantomData,
    };
    f(&w)
}

// ---------------------------------------------------------------------------------------------
// Fluids

/// `Entity.updateFluidInteraction`: the fluid sweep, the water flag (splash draws when entering),
/// and the currents when the entity is pushed by fluids.
pub(crate) fn update_fluids<R: Rules, W: BlockView<State = R::State>>(
    b: &mut Body,
    w: &Env<'_, R, W>,
    pushed: bool,
    splash: bool,
) {
    let fi = w.fluid_interaction(
        &b.bb,
        [floor(b.pos.x), floor(b.pos.z)],
        b.pos.y + f64::from(b.eye_height),
        !pushed,
    );
    b.water_height = fi.water.height;
    b.lava_height = fi.lava.height;
    b.eye_in_water = fi.water.eyes_inside;
    let in_water = fi.water.height > 0.0;
    let in_lava = fi.lava.height > 0.0;
    if in_water {
        b.fall = 0.0;
        if !b.in_water && !b.first_tick && splash {
            b.rng.splash(b.width);
        }
    }
    b.in_water = in_water;
    if pushed {
        if in_water && let Some(imp) = fi.water.current_impulse_entity(b.vel, 0.014) {
            b.vel = b.vel.add(imp);
        }
        if in_lava
            && let Some(imp) = fi
                .lava
                .current_impulse_entity(b.vel, 0.002_333_333_333_333_333_5)
        {
            b.vel = b.vel.add(imp);
        }
    }
}

/// `Entity.baseTick` of these entities: the fluid update, the lava halving of the fall distance,
/// the removal far below the world, and the end of the first tick.
pub(crate) fn base_tick<R: Rules, W: BlockView<State = R::State>>(
    b: &mut Body,
    w: &Env<'_, R, W>,
    pushed: bool,
    splash: bool,
) {
    update_fluids::<R, W>(b, w, pushed, splash);
    if b.in_lava() {
        b.fall *= 0.5;
    }
    // checkBelowWorld: 64 blocks under the build height the entity is removed.
    if b.pos.y < f64::from(w.min_y - 64) {
        b.removed = true;
    }
    b.first_tick = false;
}

// ---------------------------------------------------------------------------------------------
// Entity.move

/// How the side and the version decide the collision response of one entity.
#[derive(Clone, Copy, Debug)]
pub(crate) struct MoveRules {
    /// `isLocalInstanceAuthoritative()` (the server, for these entities).
    pub authoritative: bool,
    /// `canSimulateMovement()`.
    pub simulate: bool,
    /// `getEffectiveGravity()` (26.2 restitution).
    pub gravity: f64,
    /// `getAirDrag()` (26.2 restitution).
    pub air_drag: f32,
}

/// `Entity.move(SELF, delta)` of a non-living entity (no step height, no edge back-off).
pub(crate) fn entity_move<R: Rules, W: BlockView<State = R::State>>(
    b: &mut Body,
    w: &Env<'_, R, W>,
    delta: V3,
    mr: MoveRules,
) {
    if b.no_physics {
        let p = b.pos.add(delta);
        b.set_pos(p);
        b.note_moved(delta);
        b.hcol = false;
        b.vcol = false;
        b.vcol_below = false;
        return;
    }
    let mut delta = delta;
    if b.stuck.length_sqr() > 1.0e-7 {
        delta = delta.mul(b.stuck.x, b.stuck.y, b.stuck.z);
        b.stuck = V3::ZERO;
        b.vel = V3::ZERO;
    }
    let ctx = b.ctx();
    let movement = collide::<R, _, Plain>(w, b.pos.arr(), &b.bb, delta, b.on_ground, 0.0, &ctx);
    let len = movement.length_sqr();
    if len > 1.0e-7 || delta.length_sqr() - len < 1.0e-7 {
        if b.fall != 0.0 && len >= 1.0 && fall_reset_clip::<R, W>(b, w, movement) {
            b.fall = 0.0;
        }
        let from = b.pos;
        let to = from.add(movement);
        b.record_movement(Movement {
            from,
            to,
            axis_dependent: Some(delta),
        });
        b.set_pos(to);
        b.note_moved(movement);
    }
    let xc = !approx_equal(delta.x, movement.x);
    let zc = !approx_equal(delta.z, movement.z);
    b.hcol = xc || zc;
    let moved_vertically = delta.y.abs() > 0.0;
    if moved_vertically || mr.authoritative {
        b.vcol = delta.y != movement.y;
        b.vcol_below = b.vcol && delta.y < 0.0;
        b.on_ground = b.vcol_below;
        check_supporting_block::<R, W>(b, w, b.on_ground, Some(movement));
    }
    let ep = on_pos::<R, W>(b, w, 0.2);
    let effect = w.state(ep[0], ep[1], ep[2]);
    if mr.authoritative {
        // checkFallDamage: no block's fallOn moves a non-living entity.
        if !b.in_water && movement.y < 0.0 {
            b.fall -= f64::from(movement.y as f32);
        }
        if b.on_ground {
            b.fall = 0.0;
        }
    }
    if b.removed {
        return;
    }
    if R::RESTITUTION {
        if mr.simulate && (moved_vertically && b.vcol || b.hcol) {
            restitute::<R>(b, effect, xc, zc, movement, mr);
        }
    } else {
        if b.hcol {
            b.vel = V3::new(
                if xc { 0.0 } else { b.vel.x },
                b.vel.y,
                if zc { 0.0 } else { b.vel.z },
            );
        }
        if mr.simulate && delta.y != movement.y {
            after_fall_on::<R>(b, effect);
        }
    }
    let k = f64::from(block_speed_factor::<R, W>(b, w));
    b.vel = V3::new(b.vel.x * k, b.vel.y, b.vel.z * k);
}

/// The fall-distance reset of a long move: a clip from the position along the move (at most 8
/// blocks) against fall-damage-resetting blocks (as full cubes) and water.
fn fall_reset_clip<R: Rules, W: BlockView<State = R::State>>(
    b: &Body,
    w: &Env<'_, R, W>,
    movement: V3,
) -> bool {
    let d = java_min(movement.length(), 8.0);
    let to = b.pos.add(movement.normalize().scale(d));
    let full = R::voxel(R::FULL_CUBE_VOXEL);
    crate::pick::traverse(b.pos.arr(), to.arr(), |p| {
        let s = w.state(p[0], p[1], p[2]);
        let block = if R::block_flags(s) & bf::FALL_DAMAGE_RESETTING != 0 {
            clip_voxel(full, None, b.pos.arr(), to.arr(), p)
        } else {
            None
        };
        let f = R::phys(s).fluid();
        let liquid = if kind(f) == 1 {
            let h = f64::from(w.fluid_height(p[0], p[1], p[2], f));
            let fluid_box = [Aabb::new(0.0, 0.0, 0.0, 1.0, h, 1.0)];
            fluid_clip(&fluid_box, b.pos.arr(), to.arr(), p)
        } else {
            None
        };
        let dist = |h: &Option<BlockHit>| {
            h.map_or(f64::MAX, |h| {
                crate::pick::length_sqr(h.location, b.pos.arr())
            })
        };
        if dist(&block) <= dist(&liquid) {
            block
        } else {
            liquid
        }
    })
    .is_some()
}

/// A fluid shape (one box of the fluid's height) against the segment.
fn fluid_clip(boxes: &[Aabb], from: [f64; 3], to: [f64; 3], pos: [i32; 3]) -> Option<BlockHit> {
    if boxes[0].max_y <= 0.0 {
        return None;
    }
    let cells = Cells {
        cube: false,
        sizes: [1, 1, 1],
        xs: &[0.0, 1.0],
        ys: &[0.0, boxes[0].max_y],
        zs: &[0.0, 1.0],
        cells: &[1],
        empty: false,
        boxes,
    };
    crate::pick::clip_cells(&cells, None, from, to, pos)
}

/// `checkSupportingBlock(onGround, movement)`.
pub(crate) fn check_supporting_block<R: Rules, W: BlockView<State = R::State>>(
    b: &mut Body,
    w: &Env<'_, R, W>,
    on_ground: bool,
    movement: Option<V3>,
) {
    if !on_ground {
        b.no_blocks = false;
        b.supporting = None;
        return;
    }
    let bb = b.bb;
    let test = bx(
        bb.min_x,
        bb.min_y - 1.0e-6,
        bb.min_z,
        bb.max_x,
        bb.min_y,
        bb.max_z,
    );
    let ctx = b.ctx();
    let mut s = w.supporting_block(b.pos.arr(), &test, &ctx);
    if s.is_some() || b.no_blocks {
        b.supporting = s;
    } else if let Some(m) = movement {
        let t2 = mv(&test, -m.x, 0.0, -m.z);
        s = w.supporting_block(b.pos.arr(), &t2, &ctx);
        b.supporting = s;
    }
    b.no_blocks = s.is_none();
}

/// `getOnPos(offset)`.
pub(crate) fn on_pos<R: Rules, W: BlockView<State = R::State>>(
    b: &Body,
    w: &Env<'_, R, W>,
    offset: f32,
) -> [i32; 3] {
    if let Some(p) = b.supporting {
        if offset <= 1.0e-5 {
            return p;
        }
        let below = w.state(p[0], p[1], p[2]);
        let flags = R::block_flags(below);
        let keep = (offset <= 0.5 && flags & bf::FENCES != 0)
            || flags & bf::WALLS != 0
            || flags & bf::FENCE_GATE != 0;
        if keep {
            p
        } else {
            [p[0], floor(b.pos.y - f64::from(offset)), p[2]]
        }
    } else {
        [
            floor(b.pos.x),
            floor(b.pos.y - f64::from(offset)),
            floor(b.pos.z),
        ]
    }
}

/// `getBlockSpeedFactor()`.
fn block_speed_factor<R: Rules, W: BlockView<State = R::State>>(
    b: &Body,
    w: &Env<'_, R, W>,
) -> f32 {
    let bp = b.block_pos();
    let s = w.state(bp[0], bp[1], bp[2]);
    let here = R::speed_factor(s);
    let k = R::phys(s).kind();
    if k == BlockKind::Water as u8 || k == BlockKind::BubbleColumn as u8 {
        return here;
    }
    if here == 1.0 {
        let p = on_pos::<R, W>(b, w, b.below_offset);
        R::speed_factor(w.state(p[0], p[1], p[2]))
    } else {
        here
    }
}

/// `Block.updateEntityMovementAfterFallOn` for a non-living entity (26.1).
fn after_fall_on<R: Rules>(b: &mut Body, s: R::State) {
    let v = b.vel;
    if R::phys(s).kind() == BlockKind::SlimeBlock as u8 {
        if v.y < 0.0 {
            b.vel = V3::new(v.x, -v.y * 0.8, v.z);
        }
    } else if R::block_flags(s) & bf::BED != 0 {
        if v.y < 0.0 {
            b.vel = V3::new(v.x, -v.y * f64::from(0.66f32) * 0.8, v.z);
        }
    } else {
        b.vel = V3::new(v.x, v.y * 0.0, v.z);
    }
}

/// 26.2 `Entity.restituteMovementAfterCollisions` for a non-living entity (no bounciness of its
/// own, never suppressing the bounce, the block's restitution times 0.8).
fn restitute<R: Rules>(
    b: &mut Body,
    effect: R::State,
    xc: bool,
    zc: bool,
    movement: V3,
    mr: MoveRules,
) {
    let c = b.vel;
    let mut o = c;
    let mut r = 0.0;
    if xc {
        o.x = -c.x * r;
    }
    if zc {
        o.z = -c.z * r;
    }
    if b.vcol {
        let g = mr.gravity;
        if b.vcol_below {
            let fast = if R::BOUNCE_ABOVE_GRAVITY {
                -c.y > g
            } else {
                -c.y >= g || (-c.y).is_nan()
            };
            r = if fast && R::phys(effect).kind() != BlockKind::HoneyBlock as u8 {
                java_max(r, f64::from(R::bounce_restitution(effect) * 0.8f32))
            } else {
                0.0
            };
        }
        let (gc, drag) = if r > 0.0 {
            let portion = movement.y / c.y;
            (
                portion * g,
                super::math::lerp(portion, 1.0, f64::from(mr.air_drag)),
            )
        } else {
            (0.0, 1.0)
        };
        o.y = (gc - c.y) * drag * r;
    }
    b.vel = o;
}

// ---------------------------------------------------------------------------------------------
// Inside-block effects

/// How an entity answers the movement effects of the blocks it is inside.
#[derive(Clone, Copy, Debug)]
pub(crate) struct InsideRules {
    /// `Projectile.onAboveBubbleColumn` / `onInsideBubbleColumn` (unclamped additions) instead
    /// of the clamped ones of `Entity`.
    pub projectile_bubbles: bool,
    /// An arrow in the ground ignores bubble columns.
    pub no_bubbles: bool,
}

/// `Entity.applyEffectsFromBlocks()`: the tick's recorded movements (or old position to
/// position), then the effects.
pub(crate) fn apply_effects_from_blocks<R: Rules, W: BlockView<State = R::State>>(
    b: &mut Body,
    w: &Env<'_, R, W>,
    ir: InsideRules,
) {
    let mut list = [None; MOVES + 1];
    let mut n = 0;
    for m in b.moves.iter().flatten() {
        list[n] = Some(*m);
        n += 1;
    }
    b.moves = [None; MOVES];
    if n == 0 {
        list[0] = Some(Movement {
            from: b.old,
            to: b.pos,
            axis_dependent: None,
        });
    } else if list[n - 1].is_some_and(|l| l.to.dist_sqr(b.pos) > f64::from(9.999_999_4e-11f32)) {
        let last = list[n - 1].map_or(b.pos, |l| l.to);
        list[n] = Some(Movement {
            from: last,
            to: b.pos,
            axis_dependent: None,
        });
    }
    b.last_moves = list;
    apply_effects_of::<R, W>(b, w, &list, ir);
}

/// `applyEffectsFromBlocksForLastMovements()`.
pub(crate) fn apply_effects_last<R: Rules, W: BlockView<State = R::State>>(
    b: &mut Body,
    w: &Env<'_, R, W>,
    ir: InsideRules,
) {
    let list = b.last_moves;
    apply_effects_of::<R, W>(b, w, &list, ir);
}

/// `applyEffectsFromBlocks(from, to)`.
pub(crate) fn apply_effects_between<R: Rules, W: BlockView<State = R::State>>(
    b: &mut Body,
    w: &Env<'_, R, W>,
    from: V3,
    to: V3,
    ir: InsideRules,
) {
    let mut list = [None; MOVES + 1];
    list[0] = Some(Movement {
        from,
        to,
        axis_dependent: None,
    });
    apply_effects_of::<R, W>(b, w, &list, ir);
}

fn apply_effects_of<R: Rules, W: BlockView<State = R::State>>(
    b: &mut Body,
    w: &Env<'_, R, W>,
    list: &[Option<Movement>],
    ir: InsideRules,
) {
    if b.removed || b.no_physics {
        return;
    }
    // onGround: Block.stepOn (slime: a non-living entity is slowed too).
    if b.on_ground {
        let ep = on_pos::<R, W>(b, w, 0.2);
        let s = w.state(ep[0], ep[1], ep[2]);
        if R::phys(s).kind() == BlockKind::SlimeBlock as u8 {
            let v = b.vel;
            let ad = v.y.abs();
            if ad < 0.1 {
                let k = 0.4 + ad * 0.2;
                b.vel = V3::new(v.x * k, v.y, v.z * k);
            }
        }
    }
    let mut visited = Visited::default();
    for m in list.iter().flatten() {
        let mut budget = 16i32;
        let delta = m.to.sub(m.from);
        match m.axis_dependent {
            Some(orig) if delta.length_sqr() > 0.0 => {
                let mut pos = m.from;
                for axis in axis_order(orig) {
                    let am = delta.get(axis);
                    if am != 0.0 {
                        let to = pos.with(axis, pos.get(axis) + am);
                        budget -= check_inside::<R, W>(b, w, pos, to, &mut visited, budget, ir);
                        pos = to;
                    }
                }
            }
            _ => budget -= check_inside::<R, W>(b, w, m.from, m.to, &mut visited, 16, ir),
        }
        if budget <= 0 {
            check_inside::<R, W>(b, w, m.to, m.to, &mut visited, 1, ir);
        }
    }
}

/// One `checkInsideBlocks(from, to, ..., maxIterations)`; returns `iterations + 1`.
fn check_inside<R: Rules, W: BlockView<State = R::State>>(
    b: &mut Body,
    w: &Env<'_, R, W>,
    from: V3,
    to: V3,
    visited: &mut Visited,
    max: i32,
    ir: InsideRules,
) -> i32 {
    let at_target = deflate(&b.box_at(to), f64::from(1.0e-5f32));
    let far = from.dist_sqr(to) > 0.999_990_000_000_252_6 * 0.999_990_000_000_252_6;
    let mut last_iter = 0;
    for_each_block_between(from, to, &at_target, |pos, it| {
        if it >= max {
            return false;
        }
        last_iter = it;
        let s = w.state(pos[0], pos[1], pos[2]);
        let ph = R::phys(s);
        if ph.flags() & sf::AIR != 0 {
            return true;
        }
        let k = ph.kind();
        let effect_kind = k == BlockKind::Cobweb as u8
            || k == BlockKind::PowderSnow as u8
            || k == BlockKind::HoneyBlock as u8
            || k == BlockKind::BubbleColumn as u8;
        if !effect_kind
            || (k == BlockKind::PowderSnow as u8
                && !inside_powder_snow::<R, W>(b, w, pos, s, from, to))
            || !visited.add(pos)
        {
            return true;
        }
        let precise = far
            || intersects(
                &at_target,
                f64::from(pos[0]),
                f64::from(pos[1]),
                f64::from(pos[2]),
                f64::from(pos[0]) + 1.0,
                f64::from(pos[1]) + 1.0,
                f64::from(pos[2]) + 1.0,
            );
        entity_inside::<R, W>(b, w, pos, s, precise, ir);
        true
    });
    last_iter + 1
}

/// `getEntityInsideCollisionShape` of powder snow swept from `from` to `to`.
fn inside_powder_snow<R: Rules, W: BlockView<State = R::State>>(
    b: &Body,
    w: &Env<'_, R, W>,
    pos: [i32; 3],
    s: R::State,
    from: V3,
    to: V3,
) -> bool {
    let ctx = b.ctx();
    match w.shape_of_state(s, pos[0], pos[1], pos[2], Some(&ctx)) {
        None | Some(Placed::Cube(_)) => true,
        Some(sh @ Placed::Shape(..)) => {
            let at_from = b.box_at(from);
            let mut boxes = [Aabb::new(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); 8];
            let mut n = 0;
            sh.for_boxes(|bb| {
                if n < boxes.len() {
                    boxes[n] = bb;
                    n += 1;
                }
                true
            });
            super::math::collided_along(&at_from, to.sub(from), boxes[..n].iter().copied())
        }
        Some(Placed::Border) => false,
        Some(Placed::Moving(n, _)) => match n {},
    }
}

/// `entityInside` of the movement-relevant blocks for a non-living entity.
fn entity_inside<R: Rules, W: BlockView<State = R::State>>(
    b: &mut Body,
    w: &Env<'_, R, W>,
    pos: [i32; 3],
    s: R::State,
    precise: bool,
    ir: InsideRules,
) {
    let ph = R::phys(s);
    let k = ph.kind();
    if k == BlockKind::Cobweb as u8 {
        b.fall = 0.0;
        b.stuck = V3::new(0.25, f64::from(0.05f32), 0.25);
    } else if k == BlockKind::PowderSnow as u8 {
        // Non-living entities are always stuck in it.
        b.fall = 0.0;
        b.stuck = V3::new(f64::from(0.9f32), 1.5, f64::from(0.9f32));
    } else if k == BlockKind::HoneyBlock as u8 {
        if honey_sliding(b, pos) {
            let v = b.vel;
            let old = v.y / f64::from(0.98f32) + 0.08;
            let new_y = (-0.05 - 0.08) * f64::from(0.98f32);
            if old < -0.13 {
                let r = -0.05 / old;
                b.vel = V3::new(v.x * r, new_y, v.z * r);
            } else {
                b.vel = V3::new(v.x, new_y, v.z);
            }
            b.fall = 0.0;
        }
    } else if k == BlockKind::BubbleColumn as u8 && precise && !ir.no_bubbles {
        let above = R::phys(w.state(pos[0], pos[1] + 1, pos[2]));
        let nothing_above = (above.flags() & sf::EMPTY != 0 && above.flags() & sf::CONTEXT == 0
            || above.flags() & sf::CONTEXT != 0 && above.kind() == BlockKind::PowderSnow as u8)
            && kind(above.fluid()) == 0;
        bubble_column(b, ph.aux() & 1 != 0, nothing_above, ir);
    }
}

/// The bubble column's push (`onAboveBubbleColumn` / `onInsideBubbleColumn`).
pub(crate) fn bubble_column(b: &mut Body, drag: bool, above: bool, ir: InsideRules) {
    let v = b.vel;
    if ir.projectile_bubbles {
        let yd = match (above, drag) {
            (true, true) | (false, true) => -0.03,
            (true, false) => 0.1,
            (false, false) => 0.06,
        };
        b.vel = v.add(V3::new(0.0, yd, 0.0));
        if !above {
            b.fall = 0.0;
        }
        return;
    }
    let y = match (above, drag) {
        (true, true) => java_max(-0.9, v.y - 0.03),
        (true, false) => java_min(1.8, v.y + 0.1),
        (false, true) => java_max(-0.3, v.y - 0.03),
        (false, false) => java_min(0.7, v.y + 0.06),
    };
    b.vel = V3::new(v.x, y, v.z);
    if !above {
        b.fall = 0.0;
    }
}

/// `HoneyBlock.isSlidingDown`.
fn honey_sliding(b: &Body, pos: [i32; 3]) -> bool {
    if b.on_ground {
        return false;
    }
    if b.pos.y > f64::from(pos[1]) + 0.9375 - 1.0e-7 {
        return false;
    }
    if b.vel.y / f64::from(0.98f32) + 0.08 >= -0.08 {
        return false;
    }
    let dx = (f64::from(pos[0]) + 0.5 - b.pos.x).abs();
    let dz = (f64::from(pos[2]) + 0.5 - b.pos.z).abs();
    let o = 0.4375 + f64::from(b.width / 2.0);
    dx + 1.0e-7 > o || dz + 1.0e-7 > o
}

// ---------------------------------------------------------------------------------------------
// Collision queries

/// `level.noCollision(box)` with no entity (the empty collision context, no border).
pub(crate) fn no_collision_empty<R: Rules, W: BlockView<State = R::State>>(
    w: &Env<'_, R, W>,
    query: &Aabb,
) -> bool {
    let mut empty = true;
    w.each_collision(query, None, false, |_, _, _, _| {
        empty = false;
        false
    });
    empty
}

/// `BlockState.isCollisionShapeFullBlock` (the empty-context collision shape is the full cube).
pub(crate) fn full_block<R: Rules>(s: R::State) -> bool {
    match placed_shape::<R>(s, 0, 0, 0, None) {
        Some(Placed::Cube(_)) => true,
        Some(Placed::Shape(r, None, _)) => {
            r.boxes.len() == 1 && {
                let a = r.boxes[0];
                a.min_x == 0.0
                    && a.min_y == 0.0
                    && a.min_z == 0.0
                    && a.max_x == 1.0
                    && a.max_y == 1.0
                    && a.max_z == 1.0
            }
        }
        _ => false,
    }
}

/// `Entity.moveTowardsClosestSpace(x, y, z)` (one random draw).
pub(crate) fn move_towards_closest_space<R: Rules, W: BlockView<State = R::State>>(
    b: &mut Body,
    w: &Env<'_, R, W>,
    x: f64,
    y: f64,
    z: f64,
) {
    let p = [floor(x), floor(y), floor(z)];
    let d = [
        x - f64::from(p[0]),
        y - f64::from(p[1]),
        z - f64::from(p[2]),
    ];
    // North, south, west, east, up: (axis, positive).
    const DIRS: [(usize, bool, [i32; 3]); 5] = [
        (2, false, [0, 0, -1]),
        (2, true, [0, 0, 1]),
        (0, false, [-1, 0, 0]),
        (0, true, [1, 0, 0]),
        (1, true, [0, 1, 0]),
    ];
    let mut best = (1, true);
    let mut closest = f64::MAX;
    for (axis, positive, o) in DIRS {
        let n = w.state(p[0] + o[0], p[1] + o[1], p[2] + o[2]);
        if !full_block::<R>(n) {
            let v = d[axis];
            let oriented = if positive { 1.0 - v } else { v };
            if oriented < closest {
                closest = oriented;
                best = (axis, positive);
            }
        }
    }
    let speed = b.rng.next_float() * 0.2 + 0.1;
    let step = if best.1 { 1.0f32 } else { -1.0 };
    let s = b.vel.scale(0.75);
    let v = f64::from(step * speed);
    b.vel = match best.0 {
        0 => V3::new(v, s.y, s.z),
        1 => V3::new(s.x, v, s.z),
        _ => V3::new(s.x, s.y, v),
    };
}

// ---------------------------------------------------------------------------------------------
// The projectile clip

/// A full collision table entry as a clip grid.
fn voxel_cells(r: &'static VoxelShapeRef) -> Cells<'static> {
    Cells {
        cube: r.class == VoxelClass::Simple,
        sizes: r.sizes,
        xs: r.xs,
        ys: r.ys,
        zs: r.zs,
        cells: r.cells,
        empty: r.empty,
        boxes: r.boxes,
    }
}

fn clip_voxel(
    r: &'static VoxelShapeRef,
    shift: Option<[f64; 3]>,
    from: [f64; 3],
    to: [f64; 3],
    pos: [i32; 3],
) -> Option<BlockHit> {
    crate::pick::clip_cells(&voxel_cells(r), shift, from, to, pos)
}

/// `Level.clipIncludingBorder(new ClipContext(from, to, COLLIDER, NONE, entity))`: the first
/// block whose collision shape (in the entity's context) the segment hits, re-faced by a nearer
/// interaction-shape hit; else a miss at `to`. A segment that leaves the world border from inside
/// is cut at the border (`border` set on the result).
pub(crate) fn clip<R: Rules, W: BlockView<State = R::State>>(
    w: &Env<'_, R, W>,
    from: V3,
    to: V3,
    ctx: &ShapeCtx,
) -> (BlockHit, bool) {
    let (f, t) = (from.arr(), to.arr());
    let hit = crate::pick::traverse(f, t, |p| {
        let s = w.state(p[0], p[1], p[2]);
        let (r, shift) = match placed_shape::<R>(s, p[0], p[1], p[2], Some(ctx))? {
            Placed::Cube(_) => (R::voxel(R::FULL_CUBE_VOXEL), None),
            Placed::Shape(r, shift, _) => (r, shift),
            Placed::Border | Placed::Moving(..) => return None,
        };
        let mut hit = clip_voxel(r, shift, f, t, p)?;
        let inter = crate::pick::PlacedShape::fixed(R::interaction_shape(s));
        if let Some(o) = crate::pick::clip_shape(&inter, f, t, p)
            && crate::pick::length_sqr(o.location, f) < crate::pick::length_sqr(hit.location, f)
        {
            hit.face = o.face;
        }
        Some(hit)
    })
    .unwrap_or_else(|| {
        BlockHit::miss(
            t,
            Direction::approximate_nearest(f[0] - t[0], f[1] - t[1], f[2] - t[2]),
        )
    });
    // The world border.
    let wb = w.w.world_border();
    let max = 29_999_984.0;
    let c = |v: f64| v.clamp(-max, max);
    let (min_x, max_x) = (
        c(wb.center_x - wb.size / 2.0),
        c(wb.center_x + wb.size / 2.0),
    );
    let (min_z, max_z) = (
        c(wb.center_z - wb.size / 2.0),
        c(wb.center_z + wb.size / 2.0),
    );
    let within = |x: f64, z: f64| x >= min_x && x < max_x && z >= min_z && z < max_z;
    if within(f[0], f[2]) && !within(hit.location[0], hit.location[2]) {
        let l = hit.location;
        let d = [l[0] - f[0], l[1] - f[1], l[2] - f[2]];
        let face = Direction::approximate_nearest(d[0], d[1], d[2]);
        let eps = f64::from(1.0e-5f32);
        let at = [
            super::math::clamp(l[0], min_x, max_x - eps),
            l[1],
            super::math::clamp(l[2], min_z, max_z - eps),
        ];
        let hit = BlockHit {
            kind: HitKind::Block,
            pos: at.map(floor),
            face,
            location: at,
            inside: false,
        };
        return (hit, true);
    }
    (hit, false)
}