ghast-physics 0.4.8

Vanilla-exact, pure and deterministic player movement for the ghast Minecraft Java Edition client library (1.8.9 first), 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
//! Pistons on the 1.8.9 client: the blocks a piston moves, their collision while they travel,
//! and how they move the player.
//!
//! The client does not wait for the server to move blocks. A block-action packet makes the
//! client run the piston itself: it picks the blocks to move (at most 12, slime blocks drag their
//! side neighbours, fragile blocks are broken), turns every moving block into a moving-piston
//! block (`piston_extension`, id 36) with a [`MovingBlock`] behind it, and ticks those after the
//! player in every client tick. An extending block pushes everything its leading part overlaps
//! by `0.5625`, `0.5625` and, in its final tick, `0.25` (a retracting one only by `0.25` at the
//! end); a pushed slime block sets the velocity instead. While it travels it collides with a box
//! that grows (or shrinks) with its progress.
//!
//! [`Pistons`] holds the moving blocks in vanilla's ticking order. World changes are returned as
//! [`Edits`] (the physics never writes to a world): apply them to the client world in order.
//! [`tick_with_pistons`] replaces [`super::tick_with`] while any block moves; a world without
//! moving blocks takes the plain tick.

use ghast_data::v1_8::{Block, BlockState};

use super::blocks::{is_valid_pos, state_at};
use super::player::{Options, PlayerState, push_move, tick_with_moving};
use crate::input::{Packets, TickInput};
use crate::math::{Aabb, BoxOps, sorted_box};
use crate::world::{BlockView, WorldBorder};

/// Block id of the moving-piston block (`piston_extension`).
pub const MOVING_PISTON: u8 = 36;
const STICKY_PISTON: u8 = 29;
const PISTON: u8 = 33;
const PISTON_HEAD: u8 = 34;
const OBSIDIAN: u8 = 49;
const SLIME: u8 = 165;
/// The piston handler's limit of moved blocks.
const PUSH_LIMIT: usize = 12;

/// A 1.8 direction id: 0 down, 1 up, 2 north, 3 south, 4 west, 5 east.
pub type Facing = u8;

/// Block offset of a direction id.
#[inline]
#[must_use]
pub const fn offset(f: Facing) -> [i32; 3] {
    match f {
        0 => [0, -1, 0],
        1 => [0, 1, 0],
        2 => [0, 0, -1],
        3 => [0, 0, 1],
        4 => [-1, 0, 0],
        _ => [1, 0, 0],
    }
}

#[inline]
const fn opposite(f: Facing) -> Facing {
    f ^ 1
}

#[inline]
const fn axis(f: Facing) -> u8 {
    f >> 1
}

#[inline]
fn step(p: [i32; 3], f: Facing, n: i32) -> [i32; 3] {
    let o = offset(f);
    [p[0] + o[0] * n, p[1] + o[1] * n, p[2] + o[2] * n]
}

/// One moving block (vanilla's piston block entity at a moving-piston block).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MovingBlock {
    /// Where the block entity is (the moving block's destination).
    pub pos: [i32; 3],
    /// The block that is moving; it is placed at `pos` when the move ends.
    pub pushed: BlockState,
    /// The piston's facing.
    pub facing: Facing,
    /// Moving away from the piston (pushed or the head going out).
    pub extending: bool,
    /// The piston base itself (retracting).
    pub source: bool,
    /// Progress `0..=1` after the last tick.
    pub progress: f32,
    /// Progress before the last tick (what the collision box uses).
    pub last_progress: f32,
    removed: bool,
    /// Replaced by `setBlockEntity` (invalidated but still in the tick list, which drops it on
    /// its turn and with it whatever block entity the chunk then holds at its position).
    /// Implies `removed`.
    stale: bool,
}

impl MovingBlock {
    /// The box this block collides with right now (vanilla `getCollisionBox` of a moving
    /// piston block): the pushed block's box cut back on the side it moves towards.
    #[must_use]
    pub fn collision_box(&self) -> Option<Aabb> {
        self.collision_box_with(FULL)
    }

    /// [`MovingBlock::collision_box`] with the piston head block's current shared bounds
    /// ([`Pistons::head_bounds`]).
    #[must_use]
    pub fn collision_box_with(&self, head: [f64; 6]) -> Option<Aabb> {
        let f = if self.extending {
            1.0 - self.last_progress
        } else {
            self.last_progress
        };
        shrunk_box(self.pushed, self.pos, f, self.facing, head)
    }
}

/// A block state's box for a moving block (the pushed block's `getCollisionBox(world, pos,
/// state)`, with the world showing the moving block at `pos`). Full cubes, pistons and piston
/// heads are a full cube (a moving head uses the head block's last bounds: the full cube a head
/// collision query leaves behind). Other blocks use their single collision box (not checked
/// against vanilla: their bounds depend on the client's history).
fn base_box(s: BlockState, head: [f64; 6]) -> Option<[f64; 6]> {
    match s.block().id() {
        PISTON | STICKY_PISTON => Some(FULL),
        PISTON_HEAD => Some(head),
        _ => s
            .collision()
            .boxes
            .first()
            .map(|b| [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z]),
    }
}

/// `true` when the moving box of `s` is exact here: vanilla builds it from the block's
/// `getCollisionBox(world, pos, state)`, which for most non-full blocks reads bounds the last
/// collision query or crosshair ray left in the block (or the moving-piston block's state at
/// `pos`). Exact: pistons, heads (their shared bounds are tracked), blocks without a box, full
/// cubes, and blocks whose box depends on the state alone (snow layers, soul sand, farmland,
/// carpets).
#[must_use]
pub fn box_is_tracked(s: BlockState) -> bool {
    match s.block().id() {
        PISTON | STICKY_PISTON | PISTON_HEAD => true,
        // SnowLayerBlock, SoulSandBlock, FarmlandBlock override getCollisionBox with the state;
        // carpets keep constant bounds.
        78 | 88 | 60 | 171 => true,
        _ => {
            let c = s.collision();
            c.boxes.is_empty() || c.is_full_cube()
        }
    }
}

/// `PistonExtensionBlock.getCollisionBox(world, pos, state, progress, direction)`.
fn shrunk_box(
    s: BlockState,
    pos: [i32; 3],
    progress: f32,
    facing: Facing,
    head: [f64; 6],
) -> Option<Aabb> {
    if s.block().id() == MOVING_PISTON || s.is_air() {
        return None;
    }
    let b = base_box(s, head)?;
    let (x, y, z) = (f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2]));
    let mut v = [x + b[0], y + b[1], z + b[2], x + b[3], y + b[4], z + b[5]];
    let o = offset(facing);
    for axis in 0..3 {
        // int * float in float, widened.
        let d = f64::from(o[axis] as f32 * progress);
        if o[axis] < 0 {
            v[axis] -= d;
        } else {
            v[axis + 3] -= d;
        }
    }
    Some(sorted_box(v[0], v[1], v[2], v[3], v[4], v[5]))
}

/// World changes in the order the client makes them: `(position, new state)`.
pub type Edits = Vec<([i32; 3], BlockState)>;

/// The moving blocks of a client world, in vanilla's ticking order.
#[derive(Clone, Debug, PartialEq)]
pub struct Pistons {
    blocks: Vec<MovingBlock>,
    /// The shared bounds of the piston head block: 0..=5 the plate of that facing (a crosshair
    /// ray passed a head), 6 the full cube (any collision query that met a head).
    head: std::cell::Cell<u8>,
}

impl Default for Pistons {
    fn default() -> Pistons {
        Pistons::new()
    }
}

/// The unit cube.
const FULL: [f64; 6] = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
const HEAD_FULL: u8 = 6;

/// The head plate bounds by facing (`PistonHeadBlock.setHeadBoundingBox`).
const HEAD_PLATE: [[f64; 6]; 6] = [
    [0.0, 0.0, 0.0, 1.0, 0.25, 1.0],
    [0.0, 0.75, 0.0, 1.0, 1.0, 1.0],
    [0.0, 0.0, 0.0, 1.0, 1.0, 0.25],
    [0.0, 0.0, 0.75, 1.0, 1.0, 1.0],
    [0.0, 0.0, 0.0, 0.25, 1.0, 1.0],
    [0.75, 0.0, 0.0, 1.0, 1.0, 1.0],
];

impl Pistons {
    /// No moving blocks.
    #[must_use]
    pub const fn new() -> Pistons {
        Pistons {
            blocks: Vec::new(),
            head: std::cell::Cell::new(HEAD_FULL),
        }
    }

    /// The piston head block's shared bounds (block-local): a moving head's box is built from
    /// them. The full cube unless a crosshair ray passed a head since the last collision query
    /// that met one.
    #[must_use]
    pub fn head_bounds(&self) -> [f64; 6] {
        match self.head.get() {
            f @ 0..=5 => HEAD_PLATE[f as usize],
            _ => FULL,
        }
    }

    /// `true` while the head bounds are a plate: the player's ticks must then take
    /// [`tick_with_pistons`] (which tracks the collision queries that reset them) even when
    /// nothing moves.
    #[inline]
    #[must_use]
    pub fn head_bounds_set(&self) -> bool {
        self.head.get() != HEAD_FULL
    }

    /// The crosshair ray of a client tick (`GameRenderer.updateTargetedEntity(1.0F)`, before the
    /// world tick): `Entity.rayTrace(reach, 1.0F)` from `eye` along `look` (1.8: the head yaw,
    /// which is the previous tick's yaw). Every piston head the ray reaches sets the head bounds
    /// to its plate.
    pub fn crosshair<W: BlockView<State = BlockState>>(
        &self,
        world: &W,
        eye: [f64; 3],
        look: [f64; 3],
        reach: f64,
    ) {
        let end = crate::pick::legacy::ray_end(eye, look, reach);
        let mut last = None;
        crate::pick::legacy::trace(eye, end, true, |p| {
            let s = state_at(world, p[0], p[1], p[2]);
            if s.block().id() == PISTON_HEAD && s.meta() & 7 <= 5 {
                last = Some(s.meta() & 7);
            }
            crate::pick::v1_8::shape(world, p, false)
        });
        if let Some(f) = last {
            self.head.set(f);
        }
    }

    /// `true` when a live moving block whose 1.8 box comes from bounds this crate does not track
    /// ([`box_is_tracked`] is false: stairs, slabs, fences, walls, panes, trapdoors, ...) is
    /// within one block of `bb`: the client's push or collision there may differ from this
    /// model. Pistons, heads, full cubes, slime, snow layers, soul sand, farmland and carpets are
    /// tracked exactly.
    #[must_use]
    pub fn untracked_near(&self, bb: &Aabb) -> bool {
        let area = bb.grow(1.0, 1.0, 1.0);
        self.iter().any(|m| {
            !box_is_tracked(m.pushed)
                && area.intersects(&Aabb::new(
                    f64::from(m.pos[0]) - 1.0,
                    f64::from(m.pos[1]) - 1.0,
                    f64::from(m.pos[2]) - 1.0,
                    f64::from(m.pos[0]) + 2.0,
                    f64::from(m.pos[1]) + 2.0,
                    f64::from(m.pos[2]) + 2.0,
                ))
        })
    }

    /// A collision query met a piston head (`PistonHeadBlock.appendCollisionBoxes` leaves the
    /// full cube in the shared bounds).
    #[inline]
    pub(super) fn head_queried(&self) {
        self.head.set(HEAD_FULL);
    }

    /// `true` when nothing moves (the plain tick applies).
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.blocks.is_empty()
    }

    /// The live moving blocks in ticking order.
    pub fn iter(&self) -> impl Iterator<Item = &MovingBlock> {
        self.blocks.iter().filter(|b| !b.removed)
    }

    /// The live moving block at a position (vanilla `getBlockEntity`).
    #[must_use]
    pub fn at(&self, pos: [i32; 3]) -> Option<&MovingBlock> {
        self.blocks.iter().find(|b| !b.removed && b.pos == pos)
    }

    fn index_at(&self, pos: [i32; 3]) -> Option<usize> {
        self.blocks.iter().position(|b| !b.removed && b.pos == pos)
    }

    /// Forgets every moving block (world unload, dimension change).
    pub fn clear(&mut self) {
        self.blocks.clear();
    }

    /// A block at `pos` changed from `old` to `new` in the client world (a block-update packet,
    /// a chunk replaced, …): a moving-piston block replaced by another block drops its moving
    /// block (no final push). Edits returned by this module already did this.
    pub fn block_changed(&mut self, pos: [i32; 3], old: BlockState, new: BlockState) {
        if old.block().id() == MOVING_PISTON
            && new.block().id() != MOVING_PISTON
            && let Some(i) = self.index_at(pos)
        {
            self.blocks.remove(i);
        }
    }

    /// The moving blocks inside chunk column `(cx, cz)` are gone (chunk unloaded or replaced by
    /// a full chunk packet).
    pub fn chunk_replaced(&mut self, cx: i32, cz: i32) {
        self.blocks
            .retain(|b| !(b.pos[0] >> 4 == cx && b.pos[2] >> 4 == cz));
    }

    /// Adds a block entity at `pos` (vanilla `setBlockEntity` outside the tick loop: it ticks in
    /// the next tick loop, and replaces one already there).
    fn add(&mut self, mut b: MovingBlock) {
        if let Some(i) = self.index_at(b.pos) {
            // Chunk.addBlockEntity invalidates the old one; it stays in the tick list.
            self.blocks[i].removed = true;
            self.blocks[i].stale = true;
        }
        b.removed = false;
        self.blocks.push(b);
    }

    /// The block-entity half of a client tick without the player (it rides a vehicle: the
    /// pushes of riders are not modelled): the blocks advance and finished ones are placed.
    pub fn tick_blocks<W: BlockView<State = BlockState>>(&mut self, world: &W, edits: &mut Edits) {
        if !self.is_empty() {
            tick_moving(None, world, &Options::default(), self, edits);
        }
    }

    /// Keeps only the moving blocks for which `keep` is `true` (e.g. those whose world block is
    /// still a moving-piston block after a packet changed blocks).
    pub fn retain(&mut self, mut keep: impl FnMut(&MovingBlock) -> bool) {
        self.blocks.retain(|b| b.stale || (!b.removed && keep(b)));
    }

    fn drop_removed(&mut self) {
        self.blocks.retain(|b| b.stale || !b.removed);
    }

    /// The block-action packet of a piston (`block` = the packet's block id, 29 sticky or 33,
    /// `action` 0 extend / 1 retract, `data` the facing). Runs the client's piston at `pos`
    /// against `world` and appends the world changes to `edits` (apply them in order). Returns
    /// `false` when the client ignores the packet (no piston-like block at `pos`).
    pub fn block_event<W: BlockView<State = BlockState>>(
        &mut self,
        world: &W,
        pos: [i32; 3],
        block: u8,
        action: u8,
        data: u8,
        edits: &mut Edits,
    ) -> bool {
        let start = edits.len();
        let mut ov = Overlay {
            w: world,
            edits,
            start,
            pistons: self,
        };
        let r = ov.on_event(pos, block, action, data);
        self.drop_removed();
        r
    }
}

/// A world view with changes not yet applied on top (later changes win).
struct Layered<'a, W> {
    w: &'a W,
    edits: &'a [([i32; 3], BlockState)],
}

impl<W: BlockView<State = BlockState>> BlockView for Layered<'_, W> {
    type State = BlockState;

    #[inline]
    fn block(&self, x: i32, y: i32, z: i32) -> BlockState {
        for (p, s) in self.edits.iter().rev() {
            if *p == [x, y, z] {
                return *s;
            }
        }
        self.w.block(x, y, z)
    }

    #[inline]
    fn is_chunk_loaded(&self, cx: i32, cz: i32) -> bool {
        self.w.is_chunk_loaded(cx, cz)
    }

    #[inline]
    fn world_border(&self) -> WorldBorder {
        self.w.world_border()
    }
}

/// The world with the changes made since `start` on top (reads see earlier writes), recording
/// changes and keeping the moving blocks in step with the client world's rules.
struct Overlay<'a, W> {
    w: &'a W,
    edits: &'a mut Edits,
    start: usize,
    pistons: &'a mut Pistons,
}

/// The piston handler's view of a block (oracle `piston_facts.jsonl.gz`).
#[derive(Clone, Copy, PartialEq, Eq)]
enum Behaviour {
    Normal,
    Destroy,
    Block,
}

fn behaviour(id: u8) -> Behaviour {
    match id {
        6
        | 8..=11
        | 18
        | 26
        | 30..=32
        | 37..=40
        | 50
        | 51
        | 55
        | 59
        | 64
        | 65
        | 69..=72
        | 75..=78
        | 81
        | 83
        | 86
        | 91..=94
        | 103..=106
        | 111
        | 115
        | 122
        | 127
        | 131
        | 132
        | 140..=144
        | 147..=150
        | 161
        | 175
        | 193..=197 => Behaviour::Destroy,
        29 | 33 | 34 | 36 | 90 | 119 | 145 | 166 => Behaviour::Block,
        _ => Behaviour::Normal,
    }
}

/// Strength -1 (bedrock, moving piston, portals, end portal frame, command block, barrier).
fn unbreakable(id: u8) -> bool {
    matches!(id, 7 | 36 | 90 | 119 | 120 | 137 | 166)
}

/// Blocks with a block entity.
fn has_block_entity(id: u8) -> bool {
    matches!(
        id,
        23 | 25
            | 36
            | 52
            | 54
            | 61..=63
            | 68
            | 84
            | 116
            | 117
            | 119
            | 130
            | 137
            | 138
            | 140
            | 144
            | 146
            | 149
            | 150
            | 151
            | 154
            | 158
            | 176..=178
    )
}

#[inline]
fn is_piston(id: u8) -> bool {
    id == PISTON || id == STICKY_PISTON
}

/// The facing a block action reads from the world state (`state.get(FACING)`): pistons, piston
/// heads and moving pistons. Other blocks: the client drops the action.
fn facing_of(s: BlockState) -> Option<Facing> {
    match s.block().id() {
        PISTON | STICKY_PISTON | PISTON_HEAD | MOVING_PISTON => {
            let f = s.meta() & 7;
            (f <= 5).then_some(f)
        }
        _ => None,
    }
}

impl<W: BlockView<State = BlockState>> Overlay<'_, W> {
    #[inline]
    fn get(&self, p: [i32; 3]) -> BlockState {
        let v = Layered {
            w: self.w,
            edits: &self.edits[self.start..],
        };
        state_at(&v, p[0], p[1], p[2])
    }

    /// The client world's `setBlockState`: nothing outside the world or in an unloaded column,
    /// the same state is no change, a moving-piston block replaced drops its block entity.
    fn set(&mut self, p: [i32; 3], s: BlockState) {
        if !is_valid_pos(p[0], p[1], p[2]) || !self.w.is_chunk_loaded(p[0] >> 4, p[2] >> 4) {
            return;
        }
        let old = self.get(p);
        if old == s {
            return;
        }
        if old.block().id() == MOVING_PISTON
            && s.block().id() != MOVING_PISTON
            && let Some(i) = self.pistons.index_at(p)
        {
            self.pistons.blocks[i].removed = true;
        }
        self.edits.push((p, s));
    }

    /// `setBlockEntity` right after the moving-piston block was placed.
    fn add_moving(
        &mut self,
        pos: [i32; 3],
        pushed: BlockState,
        facing: Facing,
        extending: bool,
        source: bool,
    ) {
        if !is_valid_pos(pos[0], pos[1], pos[2])
            || !self.w.is_chunk_loaded(pos[0] >> 4, pos[2] >> 4)
        {
            // The block entity would sit in the tick list without a world position: inert.
            return;
        }
        self.pistons.add(MovingBlock {
            pos,
            pushed,
            facing,
            extending,
            source,
            progress: 0.0,
            last_progress: 0.0,
            removed: false,
            stale: false,
        });
    }

    /// `PistonBlockEntity.finish`: jump to the end without pushing.
    fn finish(&mut self, i: usize) {
        let b = self.pistons.blocks[i];
        if b.last_progress < 1.0 {
            let m = &mut self.pistons.blocks[i];
            m.progress = 1.0;
            m.last_progress = 1.0;
            m.removed = true;
            if self.get(b.pos).block().id() == MOVING_PISTON {
                self.set(b.pos, b.pushed);
            }
        }
    }

    fn on_event(&mut self, pos: [i32; 3], block: u8, action: u8, data: u8) -> bool {
        let state = self.get(pos);
        let Some(facing) = facing_of(state) else {
            return false;
        };
        let sticky = block == STICKY_PISTON;
        match action {
            0 => {
                if !self.move_blocks(pos, facing, true, sticky) {
                    return true;
                }
                // `state.with(EXTENDED, true)`: only a piston state has the property (others
                // throw here, after the move).
                if is_piston(state.block().id()) {
                    self.set(pos, BlockState::new(state.block(), state.meta() | 8));
                }
            }
            1 => {
                if let Some(i) = self.pistons.index_at(step(pos, facing, 1)) {
                    self.finish(i);
                }
                let moving = Block::from_id(MOVING_PISTON).expect("moving piston");
                self.set(
                    pos,
                    BlockState::new(moving, facing | if sticky { 8 } else { 0 }),
                );
                let base = Block::from_id(block).unwrap_or(state.block());
                self.add_moving(pos, BlockState::new(base, data & 15), facing, false, true);
                if sticky {
                    let p2 = step(pos, facing, 2);
                    let b = self.get(p2);
                    let mut finished = false;
                    if b.block().id() == MOVING_PISTON
                        && let Some(i) = self.pistons.index_at(p2)
                        && self.pistons.blocks[i].facing == facing
                        && self.pistons.blocks[i].extending
                    {
                        self.finish(i);
                        finished = true;
                    }
                    let id = b.block().id();
                    if !finished
                        && !b.is_air()
                        && self.movable(b, p2, opposite(facing), false)
                        && (behaviour(id) == Behaviour::Normal || is_piston(id))
                    {
                        self.move_blocks(pos, facing, false, sticky);
                    }
                } else {
                    self.set(step(pos, facing, 1), BlockState::AIR);
                }
            }
            _ => {}
        }
        true
    }

    /// `PistonBlock.isMovable`.
    fn movable(&self, b: BlockState, p: [i32; 3], dir: Facing, can_break: bool) -> bool {
        let id = b.block().id();
        if id == OBSIDIAN {
            return false;
        }
        if !self.w.world_border().contains_block(p[0], p[2]) {
            return false;
        }
        if p[1] < 0 || (dir == 0 && p[1] == 0) || p[1] > 255 || (dir == 1 && p[1] == 255) {
            return false;
        }
        if is_piston(id) {
            if self.get(p).meta() & 8 != 0 {
                return false;
            }
        } else {
            if unbreakable(id) {
                return false;
            }
            match behaviour(id) {
                Behaviour::Block => return false,
                Behaviour::Destroy => return can_break,
                Behaviour::Normal => {}
            }
        }
        !has_block_entity(id)
    }

    /// `PistonBlock.move`: `extend` pushes away from the piston, otherwise a sticky piston
    /// pulls the block two in front of it.
    fn move_blocks(&mut self, pos: [i32; 3], facing: Facing, extend: bool, sticky: bool) -> bool {
        if !extend {
            self.set(step(pos, facing, 1), BlockState::AIR);
        }
        let mut h = Handler::new(pos, facing, extend);
        if !h.calculate(self) {
            return false;
        }
        let push = if extend { facing } else { opposite(facing) };
        for &b in h.broken.iter().rev() {
            self.set(b, BlockState::AIR);
        }
        let moving = Block::from_id(MOVING_PISTON).expect("moving piston");
        for &m in h.moved.iter().rev() {
            let s = self.get(m);
            self.set(m, BlockState::AIR);
            let dst = step(m, push, 1);
            self.set(dst, BlockState::new(moving, facing));
            self.add_moving(dst, s, facing, extend, false);
        }
        if extend {
            let head_pos = step(pos, facing, 1);
            let t = if sticky { 8 } else { 0 };
            let head = Block::from_id(PISTON_HEAD).expect("piston head");
            self.set(head_pos, BlockState::new(moving, facing | t));
            self.add_moving(
                head_pos,
                BlockState::new(head, facing | t),
                facing,
                true,
                false,
            );
        }
        true
    }
}

/// `PistonHandler`: the blocks a piston moves and breaks.
struct Handler {
    from: [i32; 3],
    to: [i32; 3],
    dir: Facing,
    moved: Vec<[i32; 3]>,
    broken: Vec<[i32; 3]>,
}

impl Handler {
    fn new(pos: [i32; 3], facing: Facing, extend: bool) -> Handler {
        let (dir, to) = if extend {
            (facing, step(pos, facing, 1))
        } else {
            (opposite(facing), step(pos, facing, 2))
        };
        Handler {
            from: pos,
            to,
            dir,
            moved: Vec::new(),
            broken: Vec::new(),
        }
    }

    fn calculate<W: BlockView<State = BlockState>>(&mut self, ov: &Overlay<'_, W>) -> bool {
        self.moved.clear();
        self.broken.clear();
        let b = ov.get(self.to);
        if !ov.movable(b, self.to, self.dir, false) {
            if behaviour(b.block().id()) != Behaviour::Destroy {
                return false;
            }
            self.broken.push(self.to);
            return true;
        }
        if !self.try_move(ov, self.to) {
            return false;
        }
        let mut i = 0;
        while i < self.moved.len() {
            let p = self.moved[i];
            if ov.get(p).block().id() == SLIME && !self.move_adjacent(ov, p) {
                return false;
            }
            i += 1;
        }
        true
    }

    fn try_move<W: BlockView<State = BlockState>>(
        &mut self,
        ov: &Overlay<'_, W>,
        pos: [i32; 3],
    ) -> bool {
        let mut b = ov.get(pos);
        if b.is_air()
            || !ov.movable(b, pos, self.dir, false)
            || pos == self.from
            || self.moved.contains(&pos)
        {
            return true;
        }
        let back = opposite(self.dir);
        let mut i = 1usize;
        if i + self.moved.len() > PUSH_LIMIT {
            return false;
        }
        while b.block().id() == SLIME {
            let bp = step(pos, back, i as i32);
            b = ov.get(bp);
            if b.is_air() || !ov.movable(b, bp, self.dir, false) || bp == self.from {
                break;
            }
            i += 1;
            if i + self.moved.len() > PUSH_LIMIT {
                return false;
            }
        }
        let mut j = 0usize;
        for k in (0..i).rev() {
            self.moved.push(step(pos, back, k as i32));
            j += 1;
        }
        let mut l = 1;
        loop {
            let bp = step(pos, self.dir, l);
            if let Some(m) = self.moved.iter().position(|&p| p == bp) {
                self.reorder(j, m);
                for n in 0..=m + j {
                    let p = self.moved[n];
                    if ov.get(p).block().id() == SLIME && !self.move_adjacent(ov, p) {
                        return false;
                    }
                }
                return true;
            }
            let b = ov.get(bp);
            if b.is_air() {
                return true;
            }
            if !ov.movable(b, bp, self.dir, true) || bp == self.from {
                return false;
            }
            if behaviour(b.block().id()) == Behaviour::Destroy {
                self.broken.push(bp);
                return true;
            }
            if self.moved.len() >= PUSH_LIMIT {
                return false;
            }
            self.moved.push(bp);
            j += 1;
            l += 1;
        }
    }

    /// `setMovedBlocks(from, to)`: the last `from` entries move in front of entry `to`.
    fn reorder(&mut self, from: usize, to: usize) {
        let n = self.moved.len();
        let mut v = Vec::with_capacity(n);
        v.extend_from_slice(&self.moved[..to]);
        v.extend_from_slice(&self.moved[n - from..]);
        v.extend_from_slice(&self.moved[to..n - from]);
        self.moved = v;
    }

    fn move_adjacent<W: BlockView<State = BlockState>>(
        &mut self,
        ov: &Overlay<'_, W>,
        pos: [i32; 3],
    ) -> bool {
        for d in 0..6 {
            if axis(d) != axis(self.dir) && !self.try_move(ov, step(pos, d, 1)) {
                return false;
            }
        }
        true
    }
}

/// One client tick with moving blocks: the player's tick (moving blocks collide with their
/// current box), then every moving block ticks in order and pushes the player; blocks that
/// finish are placed (appended to `edits`). With no moving blocks the result equals
/// [`super::tick_with`]'s; call that one then (it is the faster path).
pub fn tick_with_pistons<W: BlockView<State = BlockState>>(
    p: &mut PlayerState,
    input: &TickInput,
    world: &W,
    options: &Options,
    pistons: &mut Pistons,
    out: &mut Packets,
    edits: &mut Edits,
) {
    // A distinct world type: the moving tick's code is its own copy, so the plain tick's helpers
    // keep a single caller each and stay inlined there (measured: +4 % instructions otherwise).
    let view = Distinct(world);
    tick_with_moving(p, input, &view, options, pistons, out);
    tick_moving(Some(p), world, options, pistons, edits);
}

/// The world seen through another type (see [`tick_with_pistons`]).
struct Distinct<'a, W>(&'a W);

impl<W: BlockView<State = BlockState>> BlockView for Distinct<'_, W> {
    type State = BlockState;

    #[inline(always)]
    fn block(&self, x: i32, y: i32, z: i32) -> BlockState {
        self.0.block(x, y, z)
    }

    #[inline(always)]
    fn is_chunk_loaded(&self, cx: i32, cz: i32) -> bool {
        self.0.is_chunk_loaded(cx, cz)
    }

    #[inline(always)]
    fn world_border(&self) -> WorldBorder {
        self.0.world_border()
    }
}

/// The block-entity half of the tick (`World.tickEntities` after the entities).
fn tick_moving<W: BlockView<State = BlockState>>(
    mut p: Option<&mut PlayerState>,
    world: &W,
    options: &Options,
    pistons: &mut Pistons,
    edits: &mut Edits,
) {
    let border = world.world_border();
    let start = edits.len();
    let mut i = 0;
    while i < pistons.blocks.len() {
        let b = pistons.blocks[i];
        i += 1;
        if b.stale {
            // The tick loop drops an invalid block entity and removes the chunk's block entity
            // at its position (the one that replaced it, which then never ticks).
            pistons.blocks[i - 1].stale = false;
            if let Some(j) = pistons.index_at(b.pos) {
                pistons.blocks[j].removed = true;
            }
            continue;
        }
        if b.removed || !(0..256).contains(&b.pos[1]) || !border.contains_block(b.pos[0], b.pos[2])
        {
            continue;
        }
        let m = &mut pistons.blocks[i - 1];
        m.last_progress = m.progress;
        if m.last_progress >= 1.0 {
            let m = *m;
            if let Some(p) = p.as_deref_mut() {
                push(p, world, options, pistons, &edits[start..], &m, 1.0, 0.25);
            }
            pistons.blocks[i - 1].removed = true;
            let mut ov = Overlay {
                w: world,
                edits,
                start,
                pistons,
            };
            if ov.get(m.pos).block().id() == MOVING_PISTON {
                ov.set(m.pos, m.pushed);
            }
        } else {
            m.progress += 0.5;
            if m.progress >= 1.0 {
                m.progress = 1.0;
            }
            let m = *m;
            if m.extending
                && let Some(p) = p.as_deref_mut()
            {
                let distance = m.progress - m.last_progress + 0.0625;
                push(
                    p,
                    world,
                    options,
                    pistons,
                    &edits[start..],
                    &m,
                    m.progress,
                    distance,
                );
            }
        }
    }
    pistons.drop_removed();
}

/// `pushEntities(progress, distance)` for the player.
#[allow(clippy::too_many_arguments)]
fn push<W: BlockView<State = BlockState>>(
    p: &mut PlayerState,
    world: &W,
    options: &Options,
    pistons: &Pistons,
    edits: &[([i32; 3], BlockState)],
    m: &MovingBlock,
    progress: f32,
    distance: f32,
) {
    let progress = if m.extending {
        1.0 - progress
    } else {
        progress - 1.0
    };
    let Some(bx) = shrunk_box(m.pushed, m.pos, progress, m.facing, pistons.head_bounds()) else {
        return;
    };
    // Spectators are not pushed (the entity query skips them).
    if p.spectator || !p.bb.intersects(&bx) {
        return;
    }
    let o = offset(m.facing);
    if m.pushed.block().id() == SLIME && m.extending {
        let axis = axis(m.facing) as usize;
        // Direction axes: 0 = y, 1 = z, 2 = x.
        let i = [1, 2, 0][axis];
        p.vel[i] = f64::from(o[i]);
    } else {
        let d = [
            f64::from(distance * o[0] as f32),
            f64::from(distance * o[1] as f32),
            f64::from(distance * o[2] as f32),
        ];
        let view = Layered { w: world, edits };
        push_move(p, &view, options, pistons, d);
    }
}

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

    /// The handler's block tables equal the oracle's dump (`piston_facts.jsonl.gz`).
    #[test]
    fn facts_match_oracle_dump() {
        let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/golden/1.8.9/piston_facts.jsonl.gz");
        let mut text = String::new();
        flate2::read::GzDecoder::new(std::fs::File::open(path).expect("facts"))
            .read_to_string(&mut text)
            .expect("gzip");
        let mut n = 0;
        for line in text.lines() {
            let v: serde_json::Value = serde_json::from_str(line).unwrap();
            let id = v["id"].as_u64().unwrap() as u8;
            let b = match v["piston"].as_u64().unwrap() {
                0 => Behaviour::Normal,
                1 => Behaviour::Destroy,
                _ => Behaviour::Block,
            };
            assert!(behaviour(id) == b, "behaviour of {id}");
            assert_eq!(
                unbreakable(id),
                v["unbreakable"].as_bool().unwrap(),
                "strength of {id}"
            );
            assert_eq!(
                has_block_entity(id),
                v["block_entity"].as_bool().unwrap(),
                "block entity of {id}"
            );
            let air = Block::from_id(id).is_some_and(|b| b.default_state().is_air());
            assert_eq!(air, v["air"].as_bool().unwrap(), "air of {id}");
            n += 1;
        }
        assert_eq!(n, 198);
    }

    #[test]
    fn empty_pistons_take_the_plain_tick() {
        let mut w = super::super::memory_world();
        w.load_chunks(-1, -1, 0, 0);
        w.fill_raw([-4, 63, -4], [4, 63, 4], 1 << 4);
        let mut a = PlayerState::new([0.5, 64.0, 0.5], 0.0, 0.0);
        let mut b = a;
        let input = TickInput::default();
        let (mut oa, mut ob) = (Packets::new(), Packets::new());
        let mut edits = Edits::new();
        for _ in 0..20 {
            oa.clear();
            ob.clear();
            super::super::tick_with(&mut a, &input, &w, &Options::default(), &mut oa);
            tick_with_pistons(
                &mut b,
                &input,
                &w,
                &Options::default(),
                &mut Pistons::new(),
                &mut ob,
                &mut edits,
            );
            assert_eq!(a, b);
            assert_eq!(oa.as_slice(), ob.as_slice());
        }
        assert!(edits.is_empty());
    }
}