ghast-client 0.5.3

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, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
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
//! 1.12.2: the `WorldView` and `Sim` implementations — every entry point the engine calls,
//! including the world packets and the player's tick.

use super::records::RECORDED_VEHICLE_PACKETS_12;
use super::*;

impl WorldView for Sim12 {
    world_view_forwards!(age: ticks_alive);

    fn column(&self, chunk_x: i32, chunk_z: i32) -> Option<&ghast_world::Column> {
        self.world.column(chunk_x, chunk_z)
    }

    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
        self.world.block_state(x, y, z).map(|s| u32::from(s.raw()))
    }

    fn block_query(&self, x: i32, y: i32, z: i32) -> Option<BlockQuery> {
        let s = self.world.block_state(x, y, z)?;
        let b = s.block();
        let info = b.info();
        Some(BlockQuery {
            exact: Some(crate::hands::ExactDig::V1_12),
            air: b.material().kind == ghast_data::v1_12::MaterialKind::Air,
            water: matches!(b.id(), 8 | 9),
            block: u16::from(b.id()),
            hardness: info.hardness.unwrap_or(-1.0),
            dig_material: info.material,
            harvest_tools: info.harvest_tools,
            selection: ray_1_12(&self.world, x, y, z),
            stairs: None,
            activates: activates_1_12(b.id()),
        })
    }

    fn crosshair(
        &self,
        eyes: Vec3,
        (yaw, pitch): (f32, f32),
        _look: Vec3,
        reach: f64,
    ) -> Option<crate::BlockHit> {
        // The oracle-verified 1.12 pick (ghast_physics::pick::v1_12: vanilla's ray shapes,
        // Entity.rayTrace with the float look vector).
        use ghast_physics::pick::v1_12 as pick;
        let eye = [eyes.x, eyes.y, eyes.z];
        let hit = pick::pick(&self.world, eye, pick::look_vector(yaw, pitch), reach)?;
        block_hit(&hit, eye)
    }
}

impl Sim for Sim12 {
    fn crosshair_target(&self, q: &PickQuery<'_>) -> Crosshair {
        // The oracle-verified GameRenderer.updateTargetedEntity: block ray at the game
        // mode's reach, then the entity ray.
        use ghast_physics::pick::v1_12 as pick;
        let eye = [q.eyes.x, q.eyes.y, q.eyes.z];
        let look = pick::look_vector(q.rotation.0, q.rotation.1);
        if q.entities.is_empty() {
            // pick_target without entities is its block pick (`target` returns it as is).
            let reach = if q.creative {
                pick::CREATIVE_REACH
            } else {
                pick::REACH
            };
            return Crosshair::Block(
                pick::pick(&self.world, eye, look, reach).and_then(|h| block_hit(&h, eye)),
            );
        }
        let t = pick::pick_target(&self.world, eye, look, q.creative, &q.player_bb, q.entities);
        legacy_crosshair(t, eye)
    }

    fn world_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        {
            use ghast_protocol::v1_12_2::play::clientbound::id;
            if raw.id == id::LOGIN
                || (raw.id == id::RESPAWN && dimension_of(Some(raw), id::LOGIN) != self.dimension())
            {
                // a new client world
                *self.maps.get_mut() = 0;
            }
            self.session.note(raw, id::LOGIN, id::RESPAWN);
            // Our entity data always (the shared flags); rocket spawns and removals while
            // gliding can happen.
            if raw.id == id::ENTITY_METADATA
                || (self.glide.watch && matches!(raw.id, id::SPAWN_ENTITY | id::ENTITY_DESTROY))
            {
                self.glide_packet(raw)?;
            }
        }
        if let Some(t) = &mut self.entities
            && t.wants(raw.id)
        {
            t.apply(raw)?;
            if let Some(n) = &mut self.near {
                n.packet(t, raw);
            }
        }
        // After the tracker (entity data too, which a tracker without metadata skips).
        if self.nonliving.is_some() {
            self.nonliving_packet(raw)?;
        }
        if self.rec.is_some() {
            self.record_vehicle_packet(raw);
        }
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        if let Some(n) = self.near.as_deref_mut()
            && (raw.id == cb::id::SPAWN_ENTITY_LIVING
                || (!n.watched.is_empty()
                    && matches!(
                        raw.id,
                        cb::id::ENTITY_TELEPORT
                            | cb::id::REL_ENTITY_MOVE
                            | cb::id::ENTITY_MOVE_LOOK
                            | cb::id::ENTITY_LOOK
                            | cb::id::ENTITY
                            | cb::id::ENTITY_HEAD_ROTATION
                            | cb::id::ENTITY_VELOCITY
                            | cb::id::ENTITY_METADATA
                            | cb::id::ENTITY_DESTROY
                    )))
        {
            let ridden = self.ride.as_ref().map(|r| r.id);
            watched_packet(n, ridden, raw)?;
        }
        if matches!(raw.id, cb::id::SET_PASSENGERS | cb::id::VEHICLE_MOVE) {
            return self.vehicle_packet(raw);
        }
        if raw.id == cb::id::ENTITY_UPDATE_ATTRIBUTES {
            return self.mount_attributes(raw);
        }
        if matches!(
            self.ride.as_deref(),
            Some(Ride12 {
                seat: Seat12::Mount(_),
                ..
            })
        ) && matches!(
            raw.id,
            cb::id::ENTITY_TELEPORT
                | cb::id::REL_ENTITY_MOVE
                | cb::id::ENTITY_MOVE_LOOK
                | cb::id::ENTITY_LOOK
                | cb::id::ENTITY
                | cb::id::ENTITY_HEAD_ROTATION
                | cb::id::ENTITY_VELOCITY
                | cb::id::ENTITY_DESTROY
                | cb::id::ENTITY_METADATA
        ) {
            self.mount_packet(raw)?;
        }
        if matches!(
            raw.id,
            cb::id::ENTITY_TELEPORT
                | cb::id::REL_ENTITY_MOVE
                | cb::id::ENTITY_MOVE_LOOK
                | cb::id::ENTITY_LOOK
                | cb::id::ENTITY
        ) && matches!(
            self.ride.as_deref(),
            Some(Ride12 {
                seat: Seat12::Boat(_),
                ..
            })
        ) {
            self.boat_packet(raw)?;
        }
        if matches!(
            raw.id,
            cb::id::ENTITY_TELEPORT
                | cb::id::REL_ENTITY_MOVE
                | cb::id::ENTITY_MOVE_LOOK
                | cb::id::ENTITY_LOOK
                | cb::id::ENTITY
                | cb::id::ENTITY_DESTROY
        ) && matches!(
            self.ride.as_deref(),
            Some(Ride12 {
                seat: Seat12::Cart(_),
                ..
            })
        ) {
            self.cart_packet(raw)?;
        }
        if raw.id == cb::id::TEAMS {
            if let Some(n) = &mut self.near
                && !n
                    .teams
                    .apply(&raw.body, super::teams::TeamLayout::Legacy1_12)
            {
                log::debug!("bad teams packet ({} B)", raw.body.len());
            }
            return Ok(());
        }
        if let Some(n) = &mut self.near
            && matches!(
                raw.id,
                cb::id::MAP_CHUNK
                    | cb::id::BLOCK_CHANGE
                    | cb::id::MULTI_BLOCK_CHANGE
                    | cb::id::LOGIN
                    | cb::id::RESPAWN
            )
        {
            n.world_version = n.world_version.wrapping_add(1);
        }
        let w = &mut self.world;
        match raw.id {
            cb::id::UPDATE_TIME => {
                // The client world's time (world age), which the piston move limit compares.
                let p: cb::UpdateTime = raw.decode_as()?;
                self.piston_time = p.age;
            }
            cb::id::LOGIN => {
                self.ride = None;
                self.mount_attrs.clear();
                self.pistons.clear();
                self.piston_time = 0;
                let p: cb::Login = raw.decode_as()?;
                // Our entity id (our entity data names us by it).
                self.glide.own_id = p.entity_id;
                w.apply_login(&p);
            }
            cb::id::RESPAWN => {
                self.ride = None;
                self.mount_attrs.clear();
                self.pistons.clear();
                w.apply_respawn(&raw.decode_as()?);
            }
            cb::id::MAP_CHUNK => {
                let p: cb::MapChunk = raw.decode_as()?;
                // A full chunk replaces the column and its block entities.
                if p.ground_up && !self.pistons.is_empty() {
                    self.pistons.chunk_replaced(p.x, p.z);
                }
                w.apply_map_chunk(&p)?;
            }
            cb::id::UNLOAD_CHUNK => {
                let p: cb::UnloadChunk = raw.decode_as()?;
                if !self.pistons.is_empty() {
                    self.pistons.chunk_replaced(p.chunk_x, p.chunk_z);
                }
                w.apply_unload_chunk(&p);
            }
            cb::id::BLOCK_CHANGE => {
                let p: cb::BlockChange = raw.decode_as()?;
                self.updates.push(p.location, p.r#type as u32);
                w.apply_block_change(&p);
                self.prune_pistons();
            }
            cb::id::BLOCK_ACTION => return self.block_action(raw),
            cb::id::MULTI_BLOCK_CHANGE => {
                let p: cb::MultiBlockChange = raw.decode_as()?;
                for r in &p.records {
                    let x = p.chunk_x * 16 + i32::from(r.horizontal_pos >> 4);
                    let z = p.chunk_z * 16 + i32::from(r.horizontal_pos & 15);
                    self.updates
                        .push(BlockPos::new(x, i32::from(r.y), z), r.block_id as u32);
                }
                w.apply_multi_block_change(&p);
                self.prune_pistons();
            }
            cb::id::EXPLOSION => {
                w.apply_explosion(&raw.decode_as()?);
                self.prune_pistons();
            }
            cb::id::WORLD_BORDER => {
                w.apply_world_border(&raw.decode_as()?);
            }
            cb::id::TILE_ENTITY_DATA if self.block_entities => {
                w.apply_tile_entity_data(&raw.decode_as()?);
            }
            _ => {}
        }
        Ok(())
    }

    fn reset_player(&mut self) {
        let abilities = self.player.abilities;
        let food = self.player.food_level;
        self.player = fresh_player_1_12();
        self.piston_uncertain_at = None;
        self.pistons.reset_player();
        self.player.abilities = abilities;
        self.player.food_level = food;
        // A new client player: not gliding, no rockets, not riding, an empty jump bar.
        self.leave_boat();
        self.rider_jump = ghast_physics::v1_12::RiderJump::default();
        self.ext.fall_flying = false;
        self.ext.sleeping = false;
        self.glide.rockets.clear();
        self.glide.pending.clear();
        self.update_glide();
        self.server_flags = None;
        self.absorption_dirty |= self.absorption != 0.0;
        self.absorption = 0.0;
    }

    fn teleport(&mut self, pose: &mut Pose, t: &Teleport) {
        // The engine keeps the look (its rotation may have moved it since the last tick).
        self.player.yaw = pose.yaw;
        self.player.pitch = pose.pitch;
        let _reply =
            self.player
                .apply_teleport([t.x, t.y, t.z], t.yaw, t.pitch, rel_flags(t.flags));
        if let Some(r) = &mut self.rec {
            let p = &self.player;
            r.teleport(
                [t.x, t.y, t.z],
                t.yaw,
                t.pitch,
                t.flags,
                t.teleport_id,
                p.pos,
                p.yaw,
                p.pitch,
            );
        }
        sync_pose_12(pose, &self.player);
    }

    fn abilities(&mut self, a: Abilities) {
        let a = physics_abilities(a);
        if let Some(r) = &mut self.rec {
            r.abilities(&a);
        }
        self.player.apply_abilities(a);
    }

    fn sleep_at(&mut self, pose: &mut Pose, bed: ghast_protocol::BlockPos) {
        // trySleep: setBounds(0.2, 0.2) (shrinking: centred), 0.5 + facing * 0.4,
        // updatePosition, velocity zeroed; updateSize keeps the size while asleep (the tick
        // with the extension state)
        let meta = self
            .world
            .block_state(bed.x, bed.y, bed.z)
            .filter(|s| s.block().id() == 26)
            .map(|s| s.meta());
        let [x, y, z] = super::legacy_bed_position(bed, meta, true);
        self.player.width = ghast_physics::v1_12::SLEEP_SIZE;
        self.player.height = ghast_physics::v1_12::SLEEP_SIZE;
        self.player.set_position(x, y, z);
        self.player.vel = [0.0; 3];
        self.ext.sleeping = true;
        self.update_glide();
        pose.pos = Vec3::new(x, y, z);
    }

    fn wake_up(&mut self) {
        self.wake_up_legacy();
    }

    fn food(&mut self, food: i32) {
        self.player.food_level = food;
    }

    fn velocity(&mut self, v: Vec3, add: bool) {
        if let Some(r) = &mut self.rec {
            if add {
                r.note("explosion push not representable");
            } else {
                r.velocity([
                    (v.x * 8000.0).round() as i32,
                    (v.y * 8000.0).round() as i32,
                    (v.z * 8000.0).round() as i32,
                ]);
            }
        }
        let p = &mut self.player;
        if add {
            p.vel[0] += v.x;
            p.vel[1] += v.y;
            p.vel[2] += v.z;
        } else {
            p.vel = [v.x, v.y, v.z];
        }
    }

    fn movement_speed(&mut self, base: f64, modifiers: &[(u128, f64, u8)]) {
        if let Some(r) = &mut self.rec {
            r.speed_attribute(base, modifiers);
        }
        self.player.apply_speed_attribute(base, modifiers);
    }

    fn status_effects(&mut self, effects: &std::collections::BTreeMap<i8, i8>) {
        if let Some(r) = &mut self.rec {
            r.effects(effects);
        }
        let e = &mut self.player.effects;
        e.jump_boost = effects.get(&8).map(|a| i32::from(*a));
        e.blindness = effects.contains_key(&15);
        e.levitation = effects.get(&25).map(|a| i32::from(*a));
    }

    fn boots(&mut self, depth_strider: u8, _soul_speed: u8) {
        // Soul speed does not exist in 1.12.
        self.player.depth_strider = depth_strider;
    }

    fn spectator(&mut self, on: bool) {
        self.player.spectator = on;
    }

    fn set_flying(&mut self, flying: bool, out: &mut Vec<Outbound>) {
        let a = &mut self.player.abilities;
        if a.flying == flying || (flying && !a.allow_flying) {
            return;
        }
        a.flying = flying;
        let a = *a;
        out.push(Outbound::Abilities {
            flags: abilities_flags(&a),
            flying_speed: a.fly_speed,
            walking_speed: a.walk_speed,
        });
    }

    fn collect_block_updates(&mut self, on: bool) {
        self.updates.on = on;
        if !on {
            self.updates.list.clear();
        }
    }

    fn drain_block_updates(&mut self, out: &mut Vec<(BlockPos, u32)>) -> usize {
        out.append(&mut self.updates.list);
        std::mem::take(&mut self.updates.dropped)
    }

    fn world_packet_ids(&self) -> Vec<i32> {
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        let mut ids: Vec<i32> = self.world.packet_ids().collect();
        // Riding: boarding and the server's boat corrections. Our entity data: the shared
        // flags (sprinting, fall flying).
        ids.extend([
            cb::id::SET_PASSENGERS,
            cb::id::VEHICLE_MOVE,
            cb::id::ENTITY_METADATA,
            // The living mounts' movement speed and jump strength.
            cb::id::ENTITY_UPDATE_ATTRIBUTES,
            // Pistons: the client moves the blocks itself.
            cb::id::BLOCK_ACTION,
        ]);
        if self.glide.watch {
            // Gliding: the rockets the server attaches to us.
            ids.extend([cb::id::SPAWN_ENTITY, cb::id::ENTITY_DESTROY]);
        }
        // A recording: every packet of a living mount ([`Sim12::record_vehicle_packet`]).
        if self.rec.is_some() {
            ids.extend(RECORDED_VEHICLE_PACKETS_12);
        }
        ids
    }

    fn take_filter_dirty(&mut self) -> bool {
        std::mem::take(&mut self.glide.filter_dirty)
    }

    #[cfg(all(test, ghast_modern, feature = "v1_8", feature = "v1_16_5"))]
    fn test_set_own_id(&mut self, id: i32) {
        self.glide.own_id = id;
    }

    fn eye_height(&self) -> Option<f64> {
        // PlayerEntity.getEyeHeight: sneaking (or 1.65 high) 1.62 - 0.08, gliding (or 0.6
        // high) 0.4.
        let p = &self.player;
        let f: f32 = if self.ext.sleeping {
            0.2
        } else if p.sneaking() || p.height == 1.65 {
            1.62 - 0.08
        } else if self.ext.fall_flying || p.height == 0.6 {
            0.4
        } else {
            1.62
        };
        Some(f64::from(f))
    }

    fn attack_hurts(&self, e: &ghast_entity::Entity) -> bool {
        use ghast_entity::EntityType as T;
        // 1.12.2 `damage` on the client: `OtherClientPlayerEntity` always, boats and minecarts
        // (`world.isClient` → true), the end crystal, the ghast fireball (an attacker given),
        // the shulker bullet. LivingEntity is false on the client; paintings / item frames
        // are skipped by `handleAttack`; small / dragon fireballs and wither skulls are never
        // damaged.
        match e.entity_type() {
            T::Player => true,
            T::LegacyObject(t) => matches!(t, 1 | 10 | 51 | 63 | 67),
            _ => false,
        }
    }

    fn attack_slow(&mut self, _target: i32, _yaw: f32, knockback: i32, sprint_bonus: bool) {
        let p = &mut self.player;
        if super::attack_knockback_applies(knockback, p.sprinting, sprint_bonus) {
            p.vel[0] *= 0.6;
            p.vel[2] *= 0.6;
            p.set_sprinting(false);
            if let Some(r) = &mut self.rec {
                r.note("attack slow-down not representable");
            }
        }
    }

    fn server_flags(&self) -> Option<u8> {
        self.server_flags
    }

    #[inline]
    fn take_absorption(&mut self) -> Option<f32> {
        std::mem::take(&mut self.absorption_dirty).then_some(self.absorption)
    }

    #[inline]
    fn take_living_flags(&mut self) -> Option<u8> {
        self.living_flags.take()
    }

    fn velocity_now(&self) -> Vec3 {
        let v = self.player.vel;
        Vec3::new(v[0], v[1], v[2])
    }

    fn mount_rules(&self, entity_id: i32) -> Option<ghast_inventory::MountRules> {
        // HorseScreenHandler: the saddle slot asks canBeSaddled (every mount but llamas), the
        // armor slot isArmor (horse armor for horses, carpets for llamas): the type decides.
        use ghast_inventory::{MountArmor, MountRules};
        let e = self.entities.as_ref()?.get(entity_id)?;
        Some(match ghast_entity::v1_12::info(e.entity_type())?.name {
            "horse" => MountRules::new(true, MountArmor::HorseArmor),
            "donkey" | "mule" | "zombie_horse" | "skeleton_horse" => {
                MountRules::new(true, MountArmor::None)
            }
            "llama" => MountRules::new(false, MountArmor::Carpet),
            _ => return None,
        })
    }

    fn take_reply(&mut self) -> Option<Outbound> {
        self.reply.take()
    }

    fn vehicle(&self) -> Option<crate::common::Vehicle> {
        let r = self.ride.as_deref()?;
        let b = match &r.seat {
            Seat12::Boat(b) => b,
            Seat12::Mount(m) => {
                let p = m.pos();
                return Some(crate::common::Vehicle {
                    entity_id: r.id,
                    pos: Vec3::new(p[0], p[1], p[2]),
                    yaw: m.yaw(),
                    pitch: m.pitch(),
                    on_ground: m.on_ground(),
                    controlled: m.steered(),
                });
            }
            Seat12::Cart(c) => {
                return Some(crate::common::Vehicle {
                    entity_id: r.id,
                    pos: Vec3::new(c.pos[0], c.pos[1], c.pos[2]),
                    yaw: c.yaw,
                    pitch: c.pitch,
                    on_ground: false,
                    controlled: false,
                });
            }
        };
        Some(crate::common::Vehicle {
            entity_id: r.id,
            pos: Vec3::new(b.pos[0], b.pos[1], b.pos[2]),
            yaw: b.yaw,
            pitch: b.pitch,
            on_ground: b.on_ground,
            controlled: true,
        })
    }

    #[inline(always)]
    fn modern_inputs(&self) -> bool {
        // The elytra is read on jump presses in the air (the request needs that); a pig we ride
        // reads the hands every tick.
        !self.player.on_ground || self.pig_ride()
    }

    fn pre_tick_wanted(&self) -> bool {
        self.pig_ride()
    }

    fn hand_items(&mut self, inv: &mut ghast_inventory::Inventory) {
        if self.rec.is_some() {
            self.record_hands(inv);
        }
    }

    fn hands_at_packet(&mut self, inv: &ghast_inventory::Inventory) {
        // PigEntity.canBeControlledByRider reads the hands whenever it is asked: by each move
        // packet of the pig too (`onEntityUpdate` / `onEntityPosition`).
        if self.pig_ride() {
            let carrot = |s: Option<&ghast_inventory::Stack>| {
                s.is_some_and(|s| s.id() == CARROT_ON_A_STICK_12)
            };
            self.set_carrot(carrot(inv.held()) || carrot(inv.offhand()));
        }
    }

    #[inline]
    fn pre_tick(&mut self, inv: &ghast_inventory::Inventory, t: &crate::sim::PreTick) -> bool {
        if self.pig_ride() {
            // PigEntity.canBeControlledByRider: a carrot on a stick in either hand.
            let carrot = |s: Option<&ghast_inventory::Stack>| {
                s.is_some_and(|s| s.id() == CARROT_ON_A_STICK_12)
            };
            self.set_carrot(carrot(inv.held()) || carrot(inv.offhand()));
        }
        if t.controls.jump {
            // ElytraItem.isUsable: damage below 431 (elytra, item 443).
            self.ext.elytra = inv.armor(1).is_some_and(|s| {
                s.id() == 443 && s.damage_value(ghast_inventory::Version::V1_12) < 432 - 1
            });
            if self.ext.elytra && !self.glide.watch {
                self.glide.watch = true;
                self.glide.filter_dirty = true;
            }
            self.update_glide();
        }
        true
    }

    fn gliding(&self) -> bool {
        self.ext.fall_flying
    }

    fn entity_config(&self) -> Option<ghast_entity::Config> {
        self.entities.as_ref().map(|t| t.config())
    }

    fn set_entities(&mut self, config: Option<ghast_entity::Config>) {
        if self.entity_config() == config {
            return;
        }
        self.entities = config.map(|c| {
            let mut t = ghast_entity::v1_12::Tracker::new(c);
            self.session.replay(|r| {
                if let Err(e) = t.apply(r) {
                    log::debug!("entity tracker: session packet 0x{:02x}: {e}", r.id);
                }
            });
            t
        });
        // The tracker starts empty (entities spawned before are known once the server resends
        // them), and teams sent before are not known (all pushes allowed).
        self.near = self.entities.is_some().then(Box::default);
        // A new tracker starts empty: so do the simulated entities.
        if let Some(n) = &mut self.nonliving {
            n.clear();
        }
    }

    fn entity_packet_ids(&self) -> Vec<i32> {
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        // The simulated entities read entity data even when the tracker does not.
        let data: &[i32] = if self.nonliving.is_some() {
            &[cb::id::ENTITY_METADATA]
        } else {
            &[]
        };
        self.entities
            .as_ref()
            .map(|t| {
                t.packet_ids()
                    .chain([cb::id::TEAMS])
                    .chain(data.iter().copied())
                    .collect()
            })
            .unwrap_or_default()
    }

    fn tick_entities(&mut self, pose: &mut Pose) {
        if self.near.is_some() {
            self.tick_near(pose);
        }
        if self.glide_on && !self.glide.rockets.is_empty() {
            self.tick_rockets(pose);
        }
        // The other entities' interpolation steps (what the next tick's pick sees).
        if let Some(t) = &mut self.entities {
            t.tick_client();
        }
        // Each non-living entity's own client tick.
        if self.nonliving.is_some() {
            self.tick_nonliving();
        }
        // The block entities tick last; then ClientWorld.tick advances the world time.
        if !self.pistons.is_empty() {
            self.tick_piston_phase(pose);
        }
        self.piston_time = self.piston_time.wrapping_add(1);
    }

    fn entities_mut(&mut self) -> Option<&mut ghast_entity::Entities> {
        self.entities.as_mut().map(|t| t.store_mut())
    }

    fn set_entity_push(&mut self, on: bool) {
        self.entity_push = on;
    }

    fn set_entity_physics(&mut self, on: bool) {
        self.set_nonliving(on);
    }

    fn predict_air(&mut self, x: i32, y: i32, z: i32) {
        self.world
            .set_block_state(x, y, z, ghast_data::v1_12::BlockState::AIR);
    }

    fn place_rules(
        &self,
        q: &crate::sim::predict::PlaceQuery<'_>,
    ) -> crate::sim::predict::PlaceRules {
        crate::sim::place112::rules(&self.world, &self.player.bb, q)
    }

    fn air_use(&self, q: &crate::sim::predict::AirQuery<'_>) -> crate::sim::predict::AirAnswer {
        let p = &self.player;
        crate::sim::use112::air_use(
            &crate::sim::use112::Ctx {
                world: &self.world,
                bb: p.bb,
                climbing: ghast_physics::v1_12::is_climbing(p, &self.world),
                fall_flying: self.ext.fall_flying,
                nether: self.dimension() == Some(-1),
                entities: self.entities.as_deref(),
                own_id: self.own_id(),
                maps: &self.maps,
            },
            q,
        )
    }

    fn air_use_sent(&mut self, blocks: &[(BlockPos, u32)]) {
        for &(p, raw) in blocks {
            let s = ghast_data::v1_12::BlockState::from_raw_vanilla(raw as u16);
            log::debug!("item use set {} at {p:?}", s.block().name());
            self.world.set_block_state(p.x, p.y, p.z, s);
        }
    }

    fn place_sent(&mut self, p: &crate::sim::predict::PlaceSent<'_>) -> bool {
        // 1.12.2: the oracle-proven rules (`ghast_data::v1_12::place`), for the hand that
        // placed; what they do not decide is the server's block update
        let player = self.player.bb;
        let used = crate::sim::place112::sent(&mut self.world, &player, p);
        log::debug!("place at {:?}: item used {used}", p.pos);
        used
    }

    fn place_suppressed(&self, pos: BlockPos, face: crate::common::Face, held: u16) -> bool {
        use ghast_data::v1_12::{Block, BlockState};
        // Anvils and slab items (stone, wooden, red sandstone, purpur): not decided.
        const UNDECIDED: &[u16] = &[44, 126, 145, 182, 205];
        let w = &self.world;
        let unit = ghast_data::Aabb {
            min_x: 0.0,
            min_y: 0.0,
            min_z: 0.0,
            max_x: 1.0,
            max_y: 1.0,
            max_z: 1.0,
        };
        crate::sim::predict::legacy_place_suppressed(
            pos,
            face,
            held,
            UNDECIDED,
            |q| w.block_state(q.x, q.y, q.z).map(BlockState::raw),
            |id| {
                u8::try_from(id)
                    .ok()
                    .and_then(Block::from_id)
                    .is_some_and(|b| b.material().replaceable)
            },
            |id| {
                let Some(b) = u8::try_from(id).ok().and_then(Block::from_id) else {
                    return false;
                };
                b.shape_dependency() == ghast_data::ShapeDependency::None
                    && (0..16u8).all(|m| {
                        let s = BlockState::new(b, m);
                        !s.is_registered() || s.shape() == [unit]
                    })
            },
            &self.player.bb,
            // World.hasEntityIn (spectators left out by getEntitiesIn): the entities whose
            // client position the sim keeps (with entity tracking). Not decided: the others
            // (minecarts, armor stands, bats, parrots, TNT, falling blocks, riders).
            |cube| match (self.near.as_deref(), self.entities.as_ref()) {
                (Some(n), Some(t)) => n.blocks_building(t, &self.world, cube),
                _ => false,
            },
        )
    }

    #[cfg(test)]
    fn set_player_pos(&mut self, p: Vec3) {
        self.player.set_position(p.x, p.y, p.z);
    }

    fn held_item(&self, id: u16, count: u8, efficiency: u8) -> HeldItem {
        held_item_facts(DataSet::V1_12, id, count, efficiency)
    }

    fn step(
        &mut self,
        pose: &mut Pose,
        controls: Controls,
        using_item: bool,
        entity_id: i32,
        out: &mut Vec<Outbound>,
    ) {
        self.packets.clear();
        if let Some(r) = &mut self.rec {
            // From the first tick the player really ticks: until its column is there it is not
            // added to the world (no move, no packet), which the replay's setup cannot express.
            if !r.started() && self.player.added_to_chunk {
                let own = self
                    .entities
                    .as_ref()
                    .and_then(|t| t.self_id())
                    .unwrap_or(self.glide.own_id);
                r.entity_id = Some(own);
                r.start_1_12(&self.player);
            }
            let w = &self.world;
            r.observe(self.player.pos, |x, y, z| {
                w.is_column_loaded(x >> 4, z >> 4)
                    .then(|| w.block_state(x, y, z).map_or(0, |s| u32::from(s.raw())))
            });
            match self.ride.as_deref() {
                Some(Ride12 {
                    seat: Seat12::Mount(_),
                    id,
                    ..
                }) if r.vehicles.contains(id) => {}
                Some(Ride12 {
                    seat: Seat12::Mount(_),
                    ..
                }) => r.note_once("riding a mount whose spawn was not recorded: not representable"),
                Some(_) => r.note_once("riding a boat or minecart not representable"),
                None if self.glide_on => r.note_once("gliding not representable"),
                None if self
                    .near
                    .as_deref()
                    .is_some_and(|n| !n.idle() && !n.only(&r.vehicles)) =>
                {
                    r.note_once("entity pushes and collisions not representable");
                }
                None => {}
            }
        }
        let riding = self.ride.is_some();
        if !riding && !self.pistons.is_empty() {
            self.step_pistons(pose, controls, using_item);
        } else if riding {
            match self.ride.as_deref().map(|r| &r.seat) {
                Some(Seat12::Cart(_)) => self.step_cart(pose, controls),
                Some(Seat12::Mount(_)) => self.step_mount(pose, controls),
                _ => self.step_ride(pose, controls),
            }
        } else if self.glide_on {
            self.step_ext(pose, controls, using_item);
        } else if self.near.as_deref().is_some_and(|n| !n.idle()) {
            self.step_near(pose, controls, using_item);
        } else {
            let input = ghast_physics::TickInput {
                keys: keys(controls),
                yaw: pose.yaw,
                pitch: pose.pitch,
                using_item,
            };
            ghast_physics::v1_12::tick(&mut self.player, &input, &self.world, &mut self.packets);
        }
        if self.force_step_position != ForceStepPosition::Off && !riding {
            let p = &mut self.player;
            let cur = [p.pos[0], p.bb.min_y, p.pos[2]];
            force_position(
                &mut self.packets,
                cur,
                &mut p.sent.pos,
                &mut p.sent.ticks_since_pos,
                self.force_step_position,
            );
        }
        if let Some(r) = &mut self.rec {
            let input = ghast_physics::TickInput {
                keys: keys(controls),
                yaw: pose.yaw,
                pitch: pose.pitch,
                using_item,
            };
            r.tick(
                &input,
                &crate::record::state_1_12(&self.player),
                &self.packets,
            );
        }
        push_packets(&self.packets, entity_id, out);
        sync_pose_12(pose, &self.player);
        // A moving world border advances with the client's clock.
        self.world.advance_time(50);
    }
}