1use std::panic::{AssertUnwindSafe, catch_unwind};
25use std::sync::Arc;
26use std::time::{Duration, Instant};
27
28use crate::common::{
29 Abilities, ChatMessage, ClientSettings, Controls, GameMode, Health, Inbound, MovePacket,
30 Outbound, Pose, Vec3,
31};
32use crate::hands::{self, BlockHit, Buttons, DigFactors, Hands, HandsIo};
33use crate::interest::Interests;
34use crate::rotation::Rotation;
35use crate::sim::{Crosshair, PickQuery, Sim, WorldView};
36use crate::version::{Capabilities, GameVersion};
37
38const MAX_PENDING_CHAT: usize = 512;
41
42pub trait Behavior {
48 fn name(&self) -> &str {
50 "behavior"
51 }
52
53 fn interests(&self) -> Interests {
56 Interests::NONE
57 }
58
59 fn raw_packets(&self, version: GameVersion) -> std::borrow::Cow<'static, [i32]> {
65 let _ = version;
66 std::borrow::Cow::Borrowed(&[])
67 }
68
69 fn start(&mut self, ctx: &mut TickContext<'_>) {
72 let _ = ctx;
73 }
74
75 fn tick(&mut self, ctx: &mut TickContext<'_>);
77
78 fn running(&self) -> bool {
82 true
83 }
84
85 fn after_tick(&mut self, view: &TickView<'_>) {
108 let _ = view;
109 }
110
111 fn stop(&mut self, reason: &str) {
113 let _ = reason;
114 }
115
116 fn configuration_dialog(
122 &mut self,
123 dialog: &crate::dialog::Dialog,
124 ) -> Option<crate::dialog::DialogAnswer> {
125 let _ = dialog;
126 None
127 }
128}
129
130impl<B: Behavior + ?Sized> Behavior for Box<B> {
132 fn name(&self) -> &str {
133 (**self).name()
134 }
135 fn interests(&self) -> Interests {
136 (**self).interests()
137 }
138 fn raw_packets(&self, version: GameVersion) -> std::borrow::Cow<'static, [i32]> {
139 (**self).raw_packets(version)
140 }
141 fn start(&mut self, ctx: &mut TickContext<'_>) {
142 (**self).start(ctx);
143 }
144 fn tick(&mut self, ctx: &mut TickContext<'_>) {
145 (**self).tick(ctx);
146 }
147 fn running(&self) -> bool {
148 (**self).running()
149 }
150 fn after_tick(&mut self, view: &TickView<'_>) {
151 (**self).after_tick(view);
152 }
153 fn stop(&mut self, reason: &str) {
154 (**self).stop(reason);
155 }
156 fn configuration_dialog(
157 &mut self,
158 dialog: &crate::dialog::Dialog,
159 ) -> Option<crate::dialog::DialogAnswer> {
160 (**self).configuration_dialog(dialog)
161 }
162}
163
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166#[non_exhaustive]
167pub enum ClickRefused {
168 Turning,
170 Inventory(ghast_inventory::ClickError),
172}
173
174impl std::fmt::Display for ClickRefused {
175 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176 match self {
177 ClickRefused::Turning => f.write_str("the player is turning"),
178 ClickRefused::Inventory(e) => write!(f, "{e}"),
179 }
180 }
181}
182
183impl std::error::Error for ClickRefused {}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
188pub struct ClickTicket {
189 pub window_id: i32,
191 pub action: i16,
193}
194
195impl ClickTicket {
196 #[must_use]
198 pub fn matches(&self, r: &ghast_inventory::ClickResult) -> bool {
199 r.window_id == self.window_id && r.action == self.action
200 }
201}
202
203#[derive(Debug, Clone, Copy, Default)]
205pub struct Idle;
206
207impl Behavior for Idle {
208 fn name(&self) -> &str {
209 "idle"
210 }
211
212 fn tick(&mut self, _ctx: &mut TickContext<'_>) {}
213}
214
215#[derive(Debug, Clone, PartialEq, Eq)]
217#[non_exhaustive]
218pub struct RawInbound {
219 pub id: i32,
221 pub body: bytes::Bytes,
223 pub at: Instant,
225}
226
227#[derive(Debug, Clone, Copy, PartialEq)]
229#[non_exhaustive]
230pub struct TeleportEvent {
231 pub teleport: crate::common::Teleport,
234 pub sent_before: Pose,
237 pub pose_before: Pose,
239 pub after: Pose,
241}
242
243const MAX_PENDING_TELEPORTS: usize = 64;
245
246const MAX_PENDING_RAW: usize = 4096;
248const MAX_PENDING_DIALOGS: usize = 64;
250
251#[derive(Debug, Clone, Default, PartialEq)]
253#[non_exhaustive]
254pub struct TickEvents {
255 pub chat: Vec<ChatMessage>,
257 pub chat_dropped: usize,
259 pub teleported: bool,
261 pub teleports: Vec<TeleportEvent>,
263 pub joined: bool,
265 pub respawned: bool,
267 pub died: bool,
269 pub health_changed: bool,
271 pub game_mode_changed: bool,
273 pub inventory: ghast_inventory::Events,
275 pub block_updates: Vec<(ghast_protocol::BlockPos, u32)>,
279 pub block_updates_dropped: usize,
281 pub raw: Vec<RawInbound>,
284 pub raw_dropped: usize,
286}
287
288impl TickEvents {
289 fn clear(&mut self) {
290 self.chat.clear();
291 self.chat_dropped = 0;
292 self.teleported = false;
293 self.teleports.clear();
294 self.joined = false;
295 self.respawned = false;
296 self.died = false;
297 self.health_changed = false;
298 self.game_mode_changed = false;
299 self.inventory = ghast_inventory::Events::default();
300 self.block_updates.clear();
301 self.block_updates_dropped = 0;
302 self.raw.clear();
303 self.raw_dropped = 0;
304 }
305}
306
307#[derive(Debug, Clone)]
309pub(crate) struct CoreOptions {
310 pub name: Arc<str>,
311 pub caps: &'static Capabilities,
313 pub settings: ClientSettings,
314 pub brand: Option<String>,
315 pub sensitivity: f32,
316 pub silent_hold: Duration,
317 pub inventory: ghast_inventory::Version,
318 pub hold_turn_on_action: bool,
321 pub accept_required_packs: bool,
323 pub entity_push: bool,
326}
327
328#[derive(Debug)]
330pub(crate) struct Core {
331 opts: CoreOptions,
332 tick: u64,
333 entity_id: i32,
334 joined: bool,
335 teleported_once: bool,
336 ready: bool,
337 pose: Pose,
338 sent: Pose,
339 rotation: Rotation,
340 aimed: bool,
341 controls: Controls,
342 health: Health,
343 dead: bool,
344 abilities: Abilities,
345 game_mode: GameMode,
346 held_slot: u8,
347 sent_slot: u8,
348 open_window: i32,
349 dimension: String,
350 respawn_screen: bool,
351 pending: TickEvents,
352 current: TickEvents,
353 out: Vec<Outbound>,
354 last_inbound: Option<Instant>,
355 silent: bool,
356 quit: Option<String>,
357 status: String,
358 hands: Hands,
359 buttons: Buttons,
360 inv: ghast_inventory::Inventory,
362 turned: bool,
364 effects: std::collections::BTreeMap<i8, i8>,
366 aqua_affinity: bool,
368 broken_now: Vec<ghast_protocol::BlockPos>,
370 pick: PickList,
372 want_flying: Option<bool>,
374 held_turns: u64,
376 swings: u64,
378 level_load_started: bool,
380 client_loaded: bool,
382 chat_session_due: bool,
384 gate_tick: bool,
386 #[cfg(test)]
388 test_gate: Option<(bool, bool)>,
389 load_wait: u32,
391 near_loaded: u8,
394 origin: Instant,
396 entity_push: bool,
398 entity_push_sim: bool,
400 dialog: Option<Arc<crate::dialog::Dialog>>,
402 dialogs_pending: Vec<crate::dialog::DialogEvent>,
405 dialogs: Vec<crate::dialog::DialogEvent>,
406 sequence: Option<i32>,
408 #[cfg(test)]
410 forced_look: Option<(f32, f32)>,
411}
412
413#[derive(Debug, Default)]
415struct BehaviorState {
416 started: bool,
417 failed: bool,
418 done: bool,
420}
421
422#[derive(Debug)]
424pub(crate) struct Engine<S> {
425 pub core: Core,
426 pub sim: S,
427 state: BehaviorState,
428}
429
430impl Core {
431 fn new(opts: CoreOptions) -> Self {
432 let rotation = Rotation::new(opts.sensitivity);
433 let inv = ghast_inventory::Inventory::new(opts.inventory)
435 .expect("the version's feature enables its ghast-inventory feature");
436 let entity_push = opts.entity_push;
437 Core {
438 opts,
439 tick: 0,
440 entity_id: 0,
441 joined: false,
442 teleported_once: false,
443 ready: false,
444 pose: Pose::default(),
445 sent: Pose::default(),
446 rotation,
447 aimed: false,
448 controls: Controls::default(),
449 health: Health::default(),
450 dead: false,
451 abilities: Abilities::default(),
452 game_mode: GameMode::default(),
453 held_slot: 0,
454 sent_slot: 0,
455 open_window: 0,
456 dimension: String::new(),
457 respawn_screen: true,
458 pending: TickEvents::default(),
459 current: TickEvents::default(),
460 out: Vec::with_capacity(16),
461 last_inbound: None,
462 silent: false,
463 quit: None,
464 status: String::new(),
465 hands: Hands::default(),
466 buttons: Buttons::default(),
467 inv,
468 turned: false,
469 effects: std::collections::BTreeMap::new(),
470 aqua_affinity: false,
471 broken_now: Vec::new(),
472 pick: PickList::default(),
473 want_flying: None,
474 held_turns: 0,
475 swings: 0,
476 level_load_started: false,
477 client_loaded: false,
478 chat_session_due: false,
479 gate_tick: false,
480 #[cfg(test)]
481 test_gate: None,
482 load_wait: 0,
483 near_loaded: 0,
484 origin: Instant::now(),
485 entity_push,
486 entity_push_sim: entity_push,
487 dialog: None,
488 dialogs_pending: Vec::new(),
489 dialogs: Vec::new(),
490 sequence: None,
491 #[cfg(test)]
492 forced_look: None,
493 }
494 }
495
496 fn reset_player(&mut self, why: &str) {
499 self.teleported_once = false;
500 self.ready = false;
501 self.pose = Pose::default();
502 self.sent = Pose::default();
503 self.controls = Controls::default();
504 self.aimed = false;
505 self.open_window = 0;
506 self.dead = false;
507 self.hands.reset();
508 self.buttons = Buttons::default();
509 self.effects.clear();
510 self.level_load_started = false;
512 self.client_loaded = false;
513 self.load_wait = 0;
514 self.near_loaded = 0;
515 log::debug!(
516 "[{}] t{} {why}: waiting for the server position",
517 self.opts.name,
518 self.tick
519 );
520 }
521
522 fn now_nanos(&self) -> i64 {
524 self.last_inbound.map_or(0, |t| {
525 t.saturating_duration_since(self.origin).as_nanos() as i64
526 })
527 }
528
529 fn column_loaded(&self, world: &dyn WorldView) -> bool {
530 let cx = (self.pose.pos.x.floor() as i64 >> 4) as i32;
532 let cz = (self.pose.pos.z.floor() as i64 >> 4) as i32;
533 world.is_column_loaded(cx, cz)
534 }
535
536 fn neighbourhood_loaded(&self, world: &dyn WorldView) -> bool {
539 let cx = (self.pose.pos.x.floor() as i64 >> 4) as i32;
540 let cz = (self.pose.pos.z.floor() as i64 >> 4) as i32;
541 (-1..=1).all(|dx| (-1..=1).all(|dz| world.is_column_loaded(cx + dx, cz + dz)))
542 }
543}
544
545fn held_item<W: Sim + ?Sized>(
547 inv: &ghast_inventory::Inventory,
548 sim: &W,
549) -> Option<hands::HeldItem> {
550 let s = inv.held()?;
551 let id = u16::try_from(s.id()).ok()?;
552 let count = u8::try_from(s.count().clamp(0, 255)).unwrap_or(0);
553 Some(sim.item_use_facts(s, false, sim.held_item(id, count, efficiency(s))))
554}
555
556fn collidable(e: &ghast_entity::Entity) -> bool {
560 use ghast_entity::{EntityClass, EntityType};
561 match e.class() {
562 EntityClass::Player | EntityClass::Mob | EntityClass::Painting => true,
563 EntityClass::Item | EntityClass::ExperienceOrb => false,
564 EntityClass::Object => match e.entity_type() {
565 EntityType::LegacyObject(t) => {
568 matches!(t, 1 | 10 | 50 | 51 | 63 | 70 | 71 | 77 | 78)
569 }
570 #[cfg(feature = "v1_16_5")]
571 EntityType::Registry(_) => {
572 ghast_entity::v1_16_5::info(e.entity_type()).is_some_and(|i| {
573 matches!(
574 i.name,
575 "boat"
576 | "fireball"
577 | "tnt"
578 | "end_crystal"
579 | "falling_block"
580 | "item_frame"
581 | "leash_knot"
582 | "armor_stand"
583 | "shulker_bullet"
584 ) || i.name.contains("minecart")
585 })
586 }
587 _ => false,
588 },
589 _ => false,
591 }
592}
593
594pub(crate) fn legacy_pick_margin(
597 ents: &ghast_entity::Entities,
598 e: &ghast_entity::Entity,
599) -> Option<f32> {
600 let spectator = e.is_player()
601 && ents
602 .player_info(&e.uuid())
603 .is_some_and(|p| p.game_mode == 3);
604 (collidable(e) && !spectator).then(|| e.targeting_margin())
605}
606
607#[derive(Debug, Default)]
610struct PickList {
611 entities: Vec<ghast_physics::pick::PickEntity>,
612 ids: Vec<(i32, Vec3)>,
613}
614
615impl PickList {
616 fn fill(&mut self, w: &(impl Sim + ?Sized), caps: &Capabilities, eyes: Vec3) {
620 self.entities.clear();
621 self.ids.clear();
622 if let Some(ents) = w.entities() {
623 self.fill_from(w, ents, caps, eyes);
624 }
625 }
626
627 #[inline(never)]
628 fn fill_from(
629 &mut self,
630 w: &(impl Sim + ?Sized),
631 ents: &ghast_entity::Entities,
632 caps: &Capabilities,
633 eyes: Vec3,
634 ) {
635 use ghast_entity::Entity;
636 let me = ents.self_id();
637 let root = |mut id: i32| {
638 for _ in 0..16 {
639 match ents.get(id).and_then(Entity::vehicle) {
640 Some(v) => id = v,
641 None => break,
642 }
643 }
644 id
645 };
646 let riding = ents.me().and_then(Entity::vehicle);
647 let my_root = me.map(root);
648 for e in ents.within([eyes.x, eyes.y, eyes.z], 16.0) {
649 if Some(e.id()) == me {
650 continue;
651 }
652 let Some(pick_radius) = w.pick_margin(e) else {
653 continue;
654 };
655 let Some(b) = e.bounding_box() else {
656 continue;
657 };
658 let same_root_vehicle = if caps.entity_pick_root_vehicle {
660 my_root.is_some_and(|r| root(e.id()) == r)
661 } else {
662 riding == Some(e.id())
663 };
664 self.entities.push(ghast_physics::pick::PickEntity {
665 bb: ghast_physics::math::Aabb::new(b[0], b[1], b[2], b[3], b[4], b[5]),
666 pick_radius,
667 same_root_vehicle,
668 });
669 let p = e.position();
670 self.ids.push((e.id(), Vec3::new(p[0], p[1], p[2])));
671 }
672 }
673
674 fn split(&self, t: Crosshair, eyes: Vec3) -> (Option<BlockHit>, Option<hands::EntityHit>) {
677 match t {
678 Crosshair::Block(b) => (b, None),
679 Crosshair::Entity { index, hit } => {
680 let (id, entity_pos) = self.ids[index];
681 let d = [hit.x - eyes.x, hit.y - eyes.y, hit.z - eyes.z];
682 let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
683 (
684 None,
685 Some(hands::EntityHit {
686 id,
687 hit,
688 entity_pos,
689 distance,
690 }),
691 )
692 }
693 }
694 }
695}
696
697fn pick_box(pos: Vec3) -> ghast_physics::math::Aabb {
700 let h = f64::from(0.6f32 / 2.0);
701 ghast_physics::math::Aabb::new(
702 pos.x - h,
703 pos.y,
704 pos.z - h,
705 pos.x + h,
706 pos.y + f64::from(1.8f32),
707 pos.z + h,
708 )
709}
710
711fn off_held_item<W: Sim + ?Sized>(
713 inv: &ghast_inventory::Inventory,
714 sim: &W,
715) -> Option<hands::HeldItem> {
716 let s = inv.offhand()?;
717 let id = u16::try_from(s.id()).ok()?;
718 let count = u8::try_from(s.count().clamp(0, 255)).unwrap_or(0);
719 Some(sim.item_use_facts(s, true, sim.held_item(id, count, 0)))
720}
721
722fn efficiency(s: &ghast_inventory::Stack) -> u8 {
724 enchant_level(s, 32, "minecraft:efficiency")
725}
726
727fn enchant_level(s: &ghast_inventory::Stack, id_1_8: i32, name: &str) -> u8 {
730 use ghast_protocol::nbt::Tag;
731 let Some(root) = s.nbt().and_then(|n| n.parse().ok().flatten()) else {
732 return 0;
733 };
734 let Some(c) = root.tag.as_compound() else {
735 return 0;
736 };
737 let num = |t: Option<&Tag>| match t {
738 Some(Tag::Short(v)) => i32::from(*v),
739 Some(Tag::Int(v)) => *v,
740 Some(Tag::Byte(v)) => i32::from(*v),
741 _ => -1,
742 };
743 for key in ["ench", "Enchantments"] {
744 if let Some(Tag::List(l)) = c.get(key) {
745 for e in l.items.iter().filter_map(Tag::as_compound) {
746 let hit = match e.get("id") {
747 Some(Tag::String(n)) => n == name,
748 other => num(other) == id_1_8,
749 };
750 if hit {
751 return u8::try_from(num(e.get("lvl")).clamp(0, 255)).unwrap_or(0);
752 }
753 }
754 }
755 }
756 0
757}
758
759impl<S: Sim> Engine<S> {
760 pub(crate) fn new(opts: CoreOptions, mut sim: S) -> Self {
761 sim.set_entity_push(opts.entity_push);
762 Engine {
763 core: Core::new(opts),
764 sim,
765 state: BehaviorState::default(),
766 }
767 }
768
769 pub(crate) fn request_chat_session(&mut self) {
772 self.core.chat_session_due = true;
773 }
774
775 pub(crate) fn joined(&self) -> bool {
777 self.core.joined
778 }
779
780 pub(crate) fn note_inbound(&mut self, now: Instant) {
782 self.core.last_inbound = Some(now);
783 }
784
785 pub(crate) fn last_inbound(&self) -> Option<Instant> {
787 self.core.last_inbound
788 }
789
790 pub(crate) fn note_sequence(&mut self, sequence: Option<i32>) {
792 self.core.sequence = sequence;
793 }
794
795 pub(crate) fn name(&self) -> &str {
797 &self.core.opts.name
798 }
799
800 pub(crate) fn push_raw(&mut self, p: RawInbound) {
802 let ev = &mut self.core.pending;
803 if ev.raw.len() < MAX_PENDING_RAW {
804 ev.raw.push(p);
805 } else {
806 ev.raw_dropped += 1;
807 }
808 }
809
810 pub(crate) fn raw_packets<B: Behavior>(&self, b: &B) -> std::borrow::Cow<'static, [i32]> {
812 if self.state.failed || self.state.done {
813 std::borrow::Cow::Borrowed(&[])
814 } else {
815 b.raw_packets(self.core.opts.caps.version)
816 }
817 }
818
819 pub(crate) fn inventory_mut(&mut self) -> &mut ghast_inventory::Inventory {
821 &mut self.core.inv
822 }
823
824 pub(crate) fn outbound(&mut self) -> &mut Vec<Outbound> {
826 &mut self.core.out
827 }
828
829 pub(crate) fn quit_requested(&self) -> Option<&str> {
831 self.core.quit.as_deref()
832 }
833
834 pub(crate) fn core_name(&self) -> &str {
835 &self.core.opts.name
836 }
837
838 pub(crate) fn tick_count(&self) -> u64 {
839 self.core.tick
840 }
841
842 pub(crate) fn handle(&mut self, p: Inbound) {
845 let c = &mut self.core;
846 let sim = &mut self.sim;
847 match p {
848 Inbound::KeepAlive(id) => c.out.push(Outbound::KeepAlive(id)),
849 Inbound::JoinGame(j) => {
850 c.entity_id = j.entity_id;
851 sim.set_main_arm_left(c.opts.settings.main_hand == 0);
853 c.game_mode = j.game_mode;
854 c.respawn_screen = j.respawn_screen;
855 c.dimension = j.dimension;
858 c.joined = true;
859 c.pending.joined = true;
860 c.dialog = None;
862 c.health = Health::default();
863 c.abilities = Abilities::default();
864 c.reset_player("join game");
865 sim.reset_player();
866 sim.spectator(c.game_mode == GameMode::Spectator);
867 if !c.opts.caps.configuration_state {
870 c.out.push(Outbound::Settings(c.opts.settings.clone()));
871 if let Some(brand) = &c.opts.brand {
872 c.out.push(Outbound::Brand(brand.clone()));
873 }
874 }
875 log::info!(
876 "[{}] joined: entity {} {:?} dimension {}",
877 c.opts.name,
878 c.entity_id,
879 c.game_mode,
880 c.dimension
881 );
882 }
883 Inbound::Respawn {
884 dimension,
885 game_mode,
886 keep,
887 } => {
888 if dimension != c.dimension {
889 c.dimension = dimension;
890 }
891 c.game_mode = game_mode;
892 c.pending.respawned = true;
893 c.reset_player("respawn");
894 sim.respawn_player(keep);
895 sim.spectator(c.game_mode == GameMode::Spectator);
896 }
897 Inbound::Teleport(t) => {
898 if c.teleported_once {
899 log::debug!(
900 "[{}] t{} teleport {:?} {:?} {:?} yaw {:?} pitch {:?} flags {}; we had sent \
901 {:?} {:?} {:?} yaw {:?} pitch {:?} ground {}",
902 c.opts.name,
903 c.tick,
904 t.x,
905 t.y,
906 t.z,
907 t.yaw,
908 t.pitch,
909 t.flags,
910 c.sent.pos.x,
911 c.sent.pos.y,
912 c.sent.pos.z,
913 c.sent.yaw,
914 c.sent.pitch,
915 c.sent.on_ground
916 );
917 }
918 let (sent_before, pose_before) = (c.sent, c.pose);
919 sim.teleport(&mut c.pose, &t);
920 if c.pending.teleports.len() < MAX_PENDING_TELEPORTS {
921 c.pending.teleports.push(TeleportEvent {
922 teleport: t,
923 sent_before,
924 pose_before,
925 after: c.pose,
926 });
927 }
928 if let Some(id) = t.teleport_id {
929 c.out.push(Outbound::TeleportConfirm(id));
930 }
931 c.out.push(Outbound::Move(MovePacket::PositionLook {
932 horizontal_collision: false,
933 pos: c.pose.pos,
934 yaw: c.pose.yaw,
935 pitch: c.pose.pitch,
936 on_ground: false,
937 }));
938 c.sent = Pose {
940 on_ground: false,
941 ..c.pose
942 };
943 if !c.teleported_once {
944 log::debug!(
945 "[{}] t{} spawn position {:.3} {:.3} {:.3}",
946 c.opts.name,
947 c.tick,
948 c.pose.pos.x,
949 c.pose.pos.y,
950 c.pose.pos.z
951 );
952 }
953 c.teleported_once = true;
954 c.pending.teleported = true;
955 }
956 Inbound::Chat(m) => {
957 if c.pending.chat.len() < MAX_PENDING_CHAT {
958 c.pending.chat.push(m);
959 } else {
960 c.pending.chat_dropped += 1;
961 }
962 }
963 Inbound::Health(h) => {
964 let was_dead = c.dead;
965 c.health = h;
966 sim.food(h.food);
967 sim.player_alive(h.health > 0.0);
969 c.pending.health_changed = true;
970 if h.health <= 0.0 && !was_dead {
971 c.dead = true;
972 c.pending.died = true;
973 log::info!("[{}] t{} died", c.opts.name, c.tick);
974 }
975 }
976 Inbound::Died { entity_id } => {
977 if entity_id == c.entity_id && !c.respawn_screen {
978 c.out.push(Outbound::Respawn);
980 }
981 }
982 Inbound::Abilities(a) => {
983 c.abilities = a;
984 c.pose.flying = a.flying();
985 sim.abilities(a);
986 }
987 Inbound::HeldSlot(s) => {
988 if (0..9).contains(&s) {
989 if c.held_slot != s as u8 {
992 c.hands.stop_using();
993 }
994 c.held_slot = s as u8;
995 }
996 }
997 Inbound::GameState { reason, value } => match reason {
998 1 | 2 | 7 => sim.weather(reason, value),
1000 3 => {
1001 c.game_mode = GameMode::from_wire(value as u8);
1002 sim.spectator(c.game_mode == GameMode::Spectator);
1003 if c.game_mode == GameMode::Spectator {
1004 c.hands.stop_using();
1006 }
1007 c.pending.game_mode_changed = true;
1008 }
1009 11 if c.opts.caps.immediate_respawn_rule => c.respawn_screen = value == 0.0,
1011 13 if c.opts.caps.player_loaded_gate => {
1013 c.level_load_started = true;
1014 sim.level_load_start();
1015 }
1016 _ => {}
1017 },
1018 Inbound::Transaction { .. } => {}
1020 Inbound::OpenWindow(id) => c.open_window = id,
1021 Inbound::CloseWindow(_) => c.open_window = 0,
1022 Inbound::Velocity { entity_id, motion } => {
1023 if entity_id == c.entity_id {
1024 sim.velocity(motion, false);
1025 }
1026 }
1027 Inbound::ExplosionPush(motion) => sim.velocity(motion, true),
1028 Inbound::MovementSpeed {
1029 entity_id,
1030 base,
1031 modifiers,
1032 } => {
1033 if entity_id == c.entity_id {
1034 log::debug!(
1035 "[{}] t{} movement speed base {base:?} modifiers {modifiers:?}",
1036 c.opts.name,
1037 c.tick
1038 );
1039 let mods: Vec<(u128, f64, u8)> = modifiers
1040 .iter()
1041 .map(|&(id, amount, op)| (id.as_u128(), amount, op as u8))
1042 .collect();
1043 sim.movement_speed(base, &mods);
1044 }
1045 }
1046 Inbound::Effect {
1047 entity_id,
1048 id,
1049 amplifier,
1050 } => {
1051 if entity_id == c.entity_id {
1052 c.effects.insert(id, amplifier);
1053 sim.status_effects(&c.effects);
1054 }
1055 }
1056 Inbound::EffectRemoved { entity_id, id } => {
1057 if entity_id == c.entity_id {
1058 c.effects.remove(&id);
1059 sim.status_effects(&c.effects);
1060 }
1061 }
1062 Inbound::EntityStatus { entity_id, status } => {
1063 if entity_id == c.entity_id && status == 9 {
1065 c.hands.stop_using();
1066 }
1067 }
1068 Inbound::Attributes {
1069 entity_id,
1070 attributes,
1071 } => {
1072 if entity_id == c.entity_id {
1073 sim.attributes(&attributes);
1074 }
1075 }
1076 Inbound::Ping(id) => c.out.push(Outbound::Pong(id)),
1077 Inbound::ChunkBatchStart => sim.chunk_batch_start(c.now_nanos()),
1078 Inbound::ChunkBatchFinished(size) => {
1079 let per_tick = sim.chunk_batch_finished(size, c.now_nanos());
1080 c.out.push(Outbound::ChunkBatchReceived(per_tick));
1081 }
1082 Inbound::StartConfiguration => {
1083 c.joined = false;
1085 c.dialog = None;
1086 c.reset_player("reconfiguration");
1087 sim.drop_level();
1088 }
1089 Inbound::ResourcePackPush { id, required } => {
1090 if required && c.opts.accept_required_packs {
1094 for result in [3, 4, 0] {
1095 c.out.push(Outbound::ResourcePackStatus { id, result });
1096 }
1097 } else {
1098 c.out.push(Outbound::ResourcePackStatus { id, result: 1 });
1099 }
1100 }
1101 Inbound::CookieRequest(key) => {
1102 c.out.push(Outbound::CookieResponse { key, value: None });
1104 }
1105 Inbound::StoreCookie { .. } => {}
1106 Inbound::Transfer { .. } => {}
1108 Inbound::Rotate {
1109 yaw,
1110 pitch,
1111 relative_yaw,
1112 relative_pitch,
1113 } => {
1114 let yaw = if relative_yaw { c.pose.yaw + yaw } else { yaw };
1116 let pitch = if relative_pitch {
1117 c.pose.pitch + pitch
1118 } else {
1119 pitch
1120 };
1121 c.pose.yaw = yaw;
1122 c.pose.pitch = pitch.clamp(-90.0, 90.0);
1123 c.rotation.reset(c.pose.yaw, c.pose.pitch);
1124 c.out.push(Outbound::LookAnswer {
1125 yaw: c.pose.yaw,
1126 pitch: c.pose.pitch,
1127 });
1128 c.sent.yaw = c.pose.yaw;
1129 c.sent.pitch = c.pose.pitch;
1130 }
1131 Inbound::ShowDialog(d) => {
1132 log::debug!("[{}] t{} dialog \"{}\"", c.opts.name, c.tick, d.title);
1133 c.dialog = Some(d.clone());
1134 if c.dialogs_pending.len() < MAX_PENDING_DIALOGS {
1135 c.dialogs_pending.push(crate::dialog::DialogEvent::Shown(d));
1136 }
1137 }
1138 Inbound::ClearDialog => {
1139 if c.dialog.take().is_some() && c.dialogs_pending.len() < MAX_PENDING_DIALOGS {
1140 c.dialogs_pending.push(crate::dialog::DialogEvent::Cleared);
1141 }
1142 }
1143 Inbound::Disconnect(_) | Inbound::SetCompression(_) => {}
1144 }
1145 }
1146
1147 pub(crate) fn interests<B: Behavior>(&self, b: &B) -> Interests {
1149 if self.state.failed {
1150 Interests::NONE
1151 } else {
1152 b.interests()
1153 }
1154 }
1155
1156 pub(crate) fn stop<B: Behavior>(&mut self, b: &mut B, reason: &str) {
1158 if self.state.started && !self.state.failed {
1159 self.state.failed = true;
1160 let name = self.core.opts.name.clone();
1161 if catch_unwind(AssertUnwindSafe(|| b.stop(reason))).is_err() {
1162 log::error!("[{name}] behaviour {} panicked in stop", b.name());
1163 }
1164 }
1165 }
1166
1167 #[cfg(test)]
1169 #[allow(dead_code, reason = "the engine tests need every version feature")]
1170 pub(crate) fn tick<B: Behavior>(&mut self, b: &mut B, now: Instant) {
1171 self.tick_with(b, now, &|_| crate::dialog::CommandCheck::ParseErrors);
1172 }
1173
1174 pub(crate) fn tick_with<B: Behavior>(
1177 &mut self,
1178 b: &mut B,
1179 now: Instant,
1180 commands: &dyn Fn(&str) -> crate::dialog::CommandCheck,
1181 ) {
1182 let c = &mut self.core;
1183 c.tick += 1;
1184 c.inv.tick();
1186 let was_ready = c.ready;
1187 c.ready = c.teleported_once
1190 && ((c.opts.caps.player_loaded_gate && c.client_loaded) || c.column_loaded(&self.sim));
1191 if c.ready != was_ready {
1192 if c.ready {
1193 log::info!(
1194 "[{}] t{} in the world at {:.3} {:.3} {:.3}",
1195 c.opts.name,
1196 c.tick,
1197 c.pose.pos.x,
1198 c.pose.pos.y,
1199 c.pose.pos.z
1200 );
1201 } else {
1202 log::debug!(
1203 "[{}] t{} player column not loaded: not ticking",
1204 c.opts.name,
1205 c.tick
1206 );
1207 }
1208 }
1209 if c.chat_session_due && c.joined {
1210 c.chat_session_due = false;
1213 c.out.push(Outbound::ChatSessionUpdate);
1214 }
1215 if c.opts.caps.player_loaded_gate && c.joined && !c.client_loaded {
1216 c.load_wait += 1;
1225 let near = c.neighbourhood_loaded(&self.sim);
1226 c.near_loaded = if near {
1227 c.near_loaded.saturating_add(1)
1228 } else {
1229 0
1230 };
1231 let (compiled, timed_out) = (c.ready && c.near_loaded >= 2, c.load_wait >= 600);
1235 #[cfg(test)]
1236 let (compiled, timed_out) = c.test_gate.unwrap_or((compiled, timed_out));
1237 if self.sim.load_gate_tick(compiled, timed_out) {
1238 c.client_loaded = true;
1239 c.gate_tick = true;
1240 c.out.push(Outbound::PlayerLoaded);
1241 log::debug!("[{}] t{} player loaded", c.opts.name, c.tick);
1242 }
1243 }
1244 if !c.ready || (c.opts.caps.player_loaded_gate && !c.client_loaded) {
1245 if c.opts.caps.sends_tick_end && c.joined {
1248 c.out.push(Outbound::TickEnd);
1249 }
1250 if c.opts.caps.player_loaded_gate && c.joined && !c.client_loaded {
1252 self.sim.tick_unloaded();
1253 }
1254 self.sim.tick_entities(&mut c.pose);
1255 return;
1256 }
1257
1258 let silent_for = c.last_inbound.map(|t| now.saturating_duration_since(t));
1259 let silent = silent_for.is_some_and(|d| d > c.opts.silent_hold);
1260 if silent != c.silent {
1261 c.silent = silent;
1262 if silent {
1263 log::warn!(
1264 "[{}] t{} server silent for {} ms: behaviour on hold",
1265 c.opts.name,
1266 c.tick,
1267 silent_for.unwrap_or_default().as_millis()
1268 );
1269 } else {
1270 log::info!(
1271 "[{}] t{} server answering again: behaviour resumes",
1272 c.opts.name,
1273 c.tick
1274 );
1275 }
1276 }
1277
1278 if silent {
1279 c.controls = Controls::default();
1281 c.aimed = false;
1282 } else if !self.state.failed && !self.state.done {
1283 std::mem::swap(&mut c.pending, &mut c.current);
1284 c.pending.clear();
1285 if !c.dialogs.is_empty() || !c.dialogs_pending.is_empty() {
1286 c.dialogs.clear();
1287 std::mem::swap(&mut c.dialogs, &mut c.dialogs_pending);
1288 }
1289 c.current.inventory = c.inv.drain_events();
1290 c.current.block_updates_dropped =
1291 self.sim.drain_block_updates(&mut c.current.block_updates);
1292 if c.current.inventory.player_changed {
1293 let ench = |a: usize, id: i32, name: &str| {
1295 c.inv.armor(a).map_or(0, |s| enchant_level(s, id, name))
1296 };
1297 let depth = ench(3, 8, "minecraft:depth_strider");
1298 let soul = ench(3, -1, "minecraft:soul_speed");
1299 c.aqua_affinity = ench(0, 6, "minecraft:aqua_affinity") > 0;
1300 self.sim.boots(depth, soul);
1301 self.sim.feet_item(c.inv.armor(3).map(|s| s.id()));
1302 }
1303 let started = self.state.started;
1304 self.state.started = true;
1305 if !started {
1306 c.rotation.reset(c.pose.yaw, c.pose.pitch);
1307 }
1308 let name = c.opts.name.clone();
1309 let result = catch_unwind(AssertUnwindSafe(|| {
1310 let held = held_item(&c.inv, &self.sim);
1311 let mut ctx = TickContext {
1312 core: c,
1313 world: &self.sim,
1314 held,
1315 crosshair: std::cell::OnceCell::new(),
1316 commands,
1317 };
1318 if !started {
1319 b.start(&mut ctx);
1320 }
1321 b.tick(&mut ctx);
1322 b.running()
1323 }));
1324 match result {
1325 Ok(true) => {}
1326 Ok(false) => {
1327 self.state.done = true;
1328 log::info!("[{name}] behaviour {} finished", b.name());
1329 }
1330 Err(_) => {
1331 log::error!("[{name}] behaviour {} panicked: stopped", b.name());
1332 self.stop(b, "panic");
1333 }
1334 }
1335 }
1336
1337 let c = &mut self.core;
1338 if c.entity_push != c.entity_push_sim {
1340 c.entity_push_sim = c.entity_push;
1341 self.sim.set_entity_push(c.entity_push);
1342 }
1343 if c.held_slot != c.sent_slot {
1346 c.sent_slot = c.held_slot;
1347 c.out.push(Outbound::HeldSlot(i16::from(c.sent_slot)));
1348 }
1349 {
1351 let gui = c.inv.gui_open();
1354 if self.sim.modern_inputs() && ((c.buttons.right && !gui) || c.hands.using_item()) {
1356 self.sim.held_use_inputs(&mut c.inv);
1357 }
1358 let eye = if c.pose.sneaking {
1359 c.opts.caps.sneak_eye_height
1360 } else {
1361 c.opts.caps.eye_height
1362 };
1363 let eyes = Vec3::new(c.pose.pos.x, c.pose.pos.y + eye, c.pose.pos.z);
1364 let sim = &self.sim;
1365 let blocks = |x: i32, y: i32, z: i32| sim.block_query(x, y, z);
1366 let look = hands::look_vector(c.pose.yaw, c.pose.pitch);
1367 let held_id = c.inv.held().and_then(|s| u16::try_from(s.id()).ok());
1368 let (left, right) = (c.buttons.left && !gui, c.buttons.right && !gui);
1369 let (target, entity) = if left || right {
1374 c.pick.fill(sim, c.opts.caps, eyes);
1375 let crosshair = sim.crosshair_target(&PickQuery {
1376 eyes,
1377 rotation: (c.pose.yaw, c.pose.pitch),
1378 look,
1379 held: held_id,
1380 now: true,
1381 creative: c.game_mode == GameMode::Creative,
1382 player_bb: pick_box(c.pose.pos),
1383 entities: &c.pick.entities,
1384 });
1385 c.pick.split(crosshair, eyes)
1386 } else {
1387 (None, None)
1388 };
1389 let in_water = blocks(
1390 eyes.x.floor() as i32,
1391 eyes.y.floor() as i32,
1392 eyes.z.floor() as i32,
1393 )
1394 .is_some_and(|b| b.water);
1395 let held = held_item(&c.inv, sim);
1396 let mut placed = false;
1397 let first = c.out.len();
1398 let mut io = HandsIo {
1399 blocks: &blocks,
1400 target,
1401 held,
1402 held_stack: c.inv.held().cloned(),
1403 food: c.health.food,
1404 modern: c.opts.caps.combat_1_9,
1405 off_held: off_held_item(&c.inv, sim),
1406 off_stack: c.inv.offhand().cloned(),
1407 entity,
1408 factors: DigFactors {
1409 on_ground: c.pose.on_ground,
1410 in_water,
1411 aqua_affinity: c.aqua_affinity,
1412 haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
1413 fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
1414 },
1415 sneaking: c.pose.sneaking,
1416 out: &mut c.out,
1417 broken: &mut c.broken_now,
1418 placed: &mut placed,
1419 spectator: c.game_mode == GameMode::Spectator,
1420 };
1421 c.hands.tick(left, right, &mut io);
1422 let _ = placed;
1424 predict_planting(c, sim, first);
1425 }
1426 for p in c.broken_now.drain(..) {
1427 self.sim.predict_air(p.x, p.y, p.z);
1428 }
1429 if let Some(f) = c.want_flying.take() {
1431 let first = c.out.len();
1432 self.sim.set_flying(f, &mut c.out);
1433 if c.out.len() > first {
1434 c.pose.flying = f;
1435 } else if f && !c.pose.flying {
1436 log::debug!(
1437 "[{}] t{} set_flying(true) refused: flight not allowed",
1438 c.opts.name,
1439 c.tick
1440 );
1441 }
1442 }
1443 c.turned = false;
1445 #[cfg(test)]
1446 if let Some((yaw, pitch)) = c.forced_look.take() {
1447 c.turned = yaw != c.pose.yaw || pitch != c.pose.pitch;
1448 c.pose.yaw = yaw;
1449 c.pose.pitch = pitch;
1450 c.aimed = false;
1451 }
1452 let gate_tick = std::mem::take(&mut c.gate_tick);
1455 if c.aimed && !gate_tick {
1456 let (yaw, pitch) = c.rotation.step(c.pose.yaw, c.pose.pitch);
1457 if c.opts.hold_turn_on_action && !post_look_ok(c, yaw, pitch) {
1458 c.held_turns += 1;
1461 } else {
1462 c.turned = yaw != c.pose.yaw || pitch != c.pose.pitch;
1463 c.pose.yaw = yaw;
1464 c.pose.pitch = pitch;
1465 }
1466 c.aimed = false;
1467 }
1468 let first = c.out.len();
1469 if self.sim.modern_inputs()
1474 && (c.hands.using_item()
1475 || c.hands.released_use().is_some()
1476 || c.controls.jump
1477 || self.sim.pre_tick_wanted())
1478 {
1479 let pre = crate::sim::PreTick {
1480 using: c.hands.use_item(),
1481 released: c.hands.released_use(),
1482 controls: c.controls,
1483 look: (c.pose.yaw, c.pose.pitch),
1484 };
1485 if !self.sim.pre_tick(&c.inv, &pre) {
1486 c.hands.stop_using();
1487 }
1488 }
1489 let using = c.hands.using_item();
1490 self.sim
1491 .step(&mut c.pose, c.controls, using, c.entity_id, &mut c.out);
1492 self.sim.tick_entities(&mut c.pose);
1496 c.hands.count_use_tick();
1497 for o in &c.out[first..] {
1498 let Outbound::Move(m) = o else { continue };
1499 match *m {
1500 MovePacket::Position { pos, .. } => c.sent.pos = pos,
1501 MovePacket::Look { yaw, pitch, .. } => {
1502 c.sent.yaw = yaw;
1503 c.sent.pitch = pitch;
1504 }
1505 MovePacket::PositionLook {
1506 pos, yaw, pitch, ..
1507 } => {
1508 c.sent.pos = pos;
1509 c.sent.yaw = yaw;
1510 c.sent.pitch = pitch;
1511 }
1512 MovePacket::Flying { .. } => {}
1513 }
1514 if matches!(
1515 m,
1516 MovePacket::Position { .. } | MovePacket::PositionLook { .. }
1517 ) {
1518 c.sent.motion = c.pose.motion;
1519 }
1520 }
1521 c.sent.on_ground = c.pose.on_ground;
1522 c.sent.sneaking = c.pose.sneaking;
1523 c.sent.sprinting = c.pose.sprinting;
1524 c.sent.flying = c.pose.flying;
1525 c.swings += count_swings(&c.out);
1526 if c.opts.caps.sends_tick_end {
1528 c.out.push(Outbound::TickEnd);
1529 }
1530
1531 if self.state.started && !self.state.failed {
1532 let name = c.opts.name.clone();
1533 let view = TickView {
1534 core: &self.core,
1535 world: &self.sim,
1536 };
1537 if catch_unwind(AssertUnwindSafe(|| b.after_tick(&view))).is_err() {
1538 log::error!(
1539 "[{name}] behaviour {} panicked in after_tick: stopped",
1540 b.name()
1541 );
1542 self.stop(b, "panic");
1543 }
1544 }
1545 }
1546}
1547
1548fn count_swings(out: &[Outbound]) -> u64 {
1550 out.iter()
1551 .filter(|o| matches!(o, Outbound::Swing | Outbound::SwingOffHand))
1552 .count() as u64
1553}
1554
1555pub struct TickView<'a> {
1557 core: &'a Core,
1558 world: &'a dyn WorldView,
1559}
1560
1561impl std::fmt::Debug for TickView<'_> {
1562 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1563 f.debug_struct("TickView")
1564 .field("tick", &self.core.tick)
1565 .field("sent", &self.core.sent)
1566 .finish_non_exhaustive()
1567 }
1568}
1569
1570impl TickView<'_> {
1571 #[must_use]
1573 pub fn tick(&self) -> u64 {
1574 self.core.tick
1575 }
1576
1577 #[must_use]
1579 pub fn version(&self) -> GameVersion {
1580 self.core.opts.caps.version
1581 }
1582
1583 #[must_use]
1585 pub fn pose(&self) -> &Pose {
1586 &self.core.pose
1587 }
1588
1589 #[must_use]
1591 pub fn sent(&self) -> &Pose {
1592 &self.core.sent
1593 }
1594
1595 #[must_use]
1597 pub fn world(&self) -> &dyn WorldView {
1598 self.world
1599 }
1600
1601 #[must_use]
1603 pub fn entities(&self) -> Option<&ghast_entity::Entities> {
1604 self.world.entities()
1605 }
1606
1607 #[must_use]
1609 pub fn inventory(&self) -> &ghast_inventory::Inventory {
1610 &self.core.inv
1611 }
1612
1613 #[must_use]
1615 pub fn events(&self) -> &TickEvents {
1616 &self.core.current
1617 }
1618
1619 #[must_use]
1621 pub fn entity_id(&self) -> i32 {
1622 self.core.entity_id
1623 }
1624
1625 #[must_use]
1627 pub fn health(&self) -> Health {
1628 self.core.health
1629 }
1630
1631 #[must_use]
1633 pub fn game_mode(&self) -> GameMode {
1634 self.core.game_mode
1635 }
1636
1637 #[must_use]
1639 pub fn held_slot(&self) -> u8 {
1640 self.core.held_slot
1641 }
1642
1643 #[must_use]
1645 pub fn mining(&self) -> Option<(ghast_protocol::BlockPos, f32)> {
1646 self.core.hands.mining()
1647 }
1648
1649 #[must_use]
1651 pub fn swings(&self) -> u64 {
1652 self.core.swings
1653 }
1654
1655 #[must_use]
1657 pub fn broken(&self) -> u64 {
1658 self.core.hands.broken
1659 }
1660
1661 #[must_use]
1664 pub fn dimension(&self) -> &str {
1665 &self.core.dimension
1666 }
1667
1668 #[must_use]
1671 pub fn using_item(&self) -> bool {
1672 self.core.hands.using_item()
1673 }
1674
1675 #[must_use]
1682 pub fn outbound(&self) -> &[Outbound] {
1683 &self.core.out
1684 }
1685
1686 #[must_use]
1688 pub fn prediction_sequence(&self) -> Option<i32> {
1689 self.core.sequence
1690 }
1691}
1692
1693#[cfg(all(test, feature = "v1_8"))]
1694impl Core {
1695 pub(crate) fn test_set_slot(&mut self, slot: u8) {
1697 self.held_slot = slot;
1698 self.sent_slot = slot;
1699 self.inv.select(slot);
1700 }
1701
1702 pub(crate) fn test_poses(&mut self) -> (&mut Pose, &mut Pose) {
1704 (&mut self.pose, &mut self.sent)
1705 }
1706
1707 pub(crate) fn test_held_turns(&self) -> u64 {
1709 self.held_turns
1710 }
1711}
1712
1713#[cfg(all(test, feature = "v1_8"))]
1714impl TickContext<'_> {
1715 pub(crate) fn test_force_look(&mut self, yaw: f32, pitch: f32) {
1717 self.core.forced_look = Some((yaw, pitch));
1718 }
1719
1720 pub(crate) fn test_rotation(&self) -> Rotation {
1722 self.core.rotation
1723 }
1724}
1725
1726fn predict_planting(c: &mut Core, world: &dyn WorldView, first: usize) {
1732 if !c.opts.caps.seed_planting_prediction || c.game_mode == GameMode::Creative {
1733 return;
1734 }
1735 let mut uses = 0u8;
1736 for o in &c.out[first..] {
1737 let Outbound::Place {
1738 pos,
1739 face: crate::common::Face::Up,
1740 held: Some(held),
1741 off_hand: false,
1742 ..
1743 } = o
1744 else {
1745 continue;
1746 };
1747 let soil = match held.id() {
1750 295 | 361 | 362 | 391 | 392 => 60,
1751 372 => 88,
1752 _ => continue,
1753 };
1754 let id = |y: i32| world.raw_block(pos.x, y, pos.z).map(|s| s >> 4);
1755 if held.count() > i32::from(uses) && id(pos.y) == Some(soil) && id(pos.y + 1) == Some(0) {
1756 uses += 1;
1757 }
1758 }
1759 if uses > 0 {
1760 c.inv.consume_held(uses);
1761 }
1762}
1763
1764fn post_look_ok(c: &Core, yaw: f32, pitch: f32) -> bool {
1768 let looks = [
1769 hands::look_vector(c.pose.yaw, pitch),
1770 hands::look_vector(yaw, pitch),
1771 ];
1772 let heights = [c.opts.caps.eye_height, c.opts.caps.sneak_eye_height];
1773 c.out
1774 .iter()
1775 .filter_map(|o| match o {
1776 Outbound::Dig {
1777 status: crate::common::DigStatus::Start | crate::common::DigStatus::Finish,
1778 pos,
1779 ..
1780 }
1781 | Outbound::Place { pos, .. } => Some(*pos),
1782 _ => None,
1783 })
1784 .all(|t| {
1785 [c.sent.pos, c.pose.pos].iter().all(|o| {
1786 heights.iter().any(|h| {
1787 let eyes = Vec3::new(o.x, o.y + *h, o.z);
1788 looks
1789 .iter()
1790 .any(|l| hands::ray_hits_cube(eyes, *l, t, ACTION_LOOK_REACH))
1791 })
1792 })
1793 })
1794}
1795
1796const ACTION_LOOK_REACH: f64 = 6.0;
1798
1799pub struct TickContext<'a> {
1804 core: &'a mut Core,
1805 world: &'a dyn Sim,
1806 held: Option<hands::HeldItem>,
1807 crosshair: std::cell::OnceCell<(Option<BlockHit>, Option<hands::EntityHit>)>,
1810 commands: &'a dyn Fn(&str) -> crate::dialog::CommandCheck,
1812}
1813
1814impl std::fmt::Debug for TickContext<'_> {
1815 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1816 f.debug_struct("TickContext")
1817 .field("tick", &self.core.tick)
1818 .field("pose", &self.core.pose)
1819 .finish_non_exhaustive()
1820 }
1821}
1822
1823impl TickContext<'_> {
1824 #[must_use]
1826 pub fn tick(&self) -> u64 {
1827 self.core.tick
1828 }
1829
1830 #[must_use]
1832 pub fn version(&self) -> GameVersion {
1833 self.core.opts.caps.version
1834 }
1835
1836 #[must_use]
1838 pub fn pose(&self) -> &Pose {
1839 &self.core.pose
1840 }
1841
1842 #[must_use]
1844 pub fn sent(&self) -> &Pose {
1845 &self.core.sent
1846 }
1847
1848 #[must_use]
1850 pub fn eyes(&self, pose: &Pose) -> Vec3 {
1851 let v = self.core.opts.caps;
1852 pose.eyes(if pose.sneaking {
1853 v.sneak_eye_height
1854 } else {
1855 v.eye_height
1856 })
1857 }
1858
1859 #[must_use]
1861 pub fn world(&self) -> &dyn WorldView {
1862 self.world
1863 }
1864
1865 #[cfg(ghast_modern)]
1870 #[must_use]
1871 pub fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
1872 self.world.modern_player()
1873 }
1874
1875 #[must_use]
1877 pub fn events(&self) -> &TickEvents {
1878 &self.core.current
1879 }
1880
1881 #[must_use]
1883 pub fn entity_id(&self) -> i32 {
1884 self.core.entity_id
1885 }
1886
1887 #[must_use]
1891 pub fn swings(&self) -> u64 {
1892 self.core.swings + count_swings(&self.core.out)
1893 }
1894
1895 #[must_use]
1897 pub fn health(&self) -> Health {
1898 self.core.health
1899 }
1900
1901 #[must_use]
1903 pub fn is_dead(&self) -> bool {
1904 self.core.dead
1905 }
1906
1907 #[must_use]
1909 pub fn game_mode(&self) -> GameMode {
1910 self.core.game_mode
1911 }
1912
1913 #[must_use]
1915 pub fn abilities(&self) -> Abilities {
1916 self.core.abilities
1917 }
1918
1919 #[must_use]
1921 pub fn can_fly(&self) -> bool {
1922 self.core.abilities.may_fly()
1923 }
1924
1925 #[must_use]
1927 pub fn held_slot(&self) -> u8 {
1928 self.core.held_slot
1929 }
1930
1931 #[must_use]
1933 pub fn open_window(&self) -> Option<i32> {
1934 (self.core.open_window != 0).then_some(self.core.open_window)
1935 }
1936
1937 #[must_use]
1939 pub fn dimension(&self) -> &str {
1940 &self.core.dimension
1941 }
1942
1943 #[must_use]
1945 pub fn controls(&self) -> Controls {
1946 self.core.controls
1947 }
1948
1949 #[must_use]
1951 pub fn aim(&self) -> (f32, f32) {
1952 self.core.rotation.target()
1953 }
1954
1955 pub fn chat(&mut self, text: impl Into<String>) {
1960 self.core.out.push(Outbound::Chat(text.into()));
1961 }
1962
1963 pub fn respawn(&mut self) -> bool {
1965 if self.core.dead {
1966 self.core.out.push(Outbound::Respawn);
1967 true
1968 } else {
1969 false
1970 }
1971 }
1972
1973 pub fn select_slot(&mut self, slot: u8) {
1976 if slot < 9 {
1977 if self.core.held_slot != slot {
1978 self.core.hands.stop_using();
1979 self.core.hands.ticks_since_swing = 0;
1980 }
1981 self.core.held_slot = slot;
1982 self.core.inv.select(slot);
1983 if self.core.sent_slot != slot {
1984 self.core.sent_slot = slot;
1985 self.core.out.push(Outbound::HeldSlot(i16::from(slot)));
1986 }
1987 }
1988 }
1989
1990 pub fn swing(&mut self) {
1992 self.core.out.push(Outbound::Swing);
1993 }
1994
1995 pub fn send_raw(&mut self, id: i32, body: impl Into<bytes::Bytes>) {
2002 self.core
2003 .out
2004 .push(Outbound::Raw(ghast_protocol::RawPacket::new(
2005 id,
2006 body.into(),
2007 )));
2008 }
2009
2010 pub fn send_packet<P: ghast_protocol::Packet>(
2014 &mut self,
2015 packet: &P,
2016 ) -> Result<(), ghast_protocol::EncodeError> {
2017 if P::STATE != ghast_protocol::State::Play
2018 || P::DIRECTION != ghast_protocol::Direction::Serverbound
2019 {
2020 return Err(ghast_protocol::EncodeError::Invalid(
2021 "not a serverbound play packet",
2022 ));
2023 }
2024 let mut body = bytes::BytesMut::new();
2025 packet.encode(&mut body)?;
2026 self.send_raw(P::ID, body.freeze());
2027 Ok(())
2028 }
2029
2030 pub fn disconnect(&mut self, reason: impl Into<String>) {
2032 self.core.quit = Some(reason.into());
2033 }
2034
2035 pub fn set_aim(&mut self, yaw: f32, pitch: f32) {
2040 self.core.rotation.set_target(yaw, pitch);
2041 self.core.aimed = true;
2042 }
2043
2044 pub fn set_controls(&mut self, controls: Controls) {
2047 self.core.controls = controls;
2048 }
2049
2050 #[must_use]
2052 pub fn inventory(&self) -> &ghast_inventory::Inventory {
2053 &self.core.inv
2054 }
2055
2056 pub fn click(&mut self, click: ghast_inventory::Click) -> Result<ClickTicket, ClickRefused> {
2062 if self.core.turned || self.core.aimed {
2063 return Err(ClickRefused::Turning);
2064 }
2065 let o = self
2066 .core
2067 .inv
2068 .click(click)
2069 .map_err(ClickRefused::Inventory)?;
2070 let ticket = match &o {
2071 ghast_inventory::Outgoing::Click(p) => ClickTicket {
2072 window_id: i32::from(p.window_id),
2073 action: p.action,
2074 },
2075 _ => ClickTicket {
2076 window_id: -1,
2077 action: -1,
2078 },
2079 };
2080 self.core.out.push(Outbound::Inventory(o));
2081 Ok(ticket)
2082 }
2083
2084 pub fn anvil_rename(&mut self, name: &str) -> Result<(), ClickRefused> {
2088 #[cfg(ghast_modern)]
2089 if let Some(o) = self
2090 .core
2091 .inv
2092 .anvil_rename_modern(name)
2093 .map_err(ClickRefused::Inventory)?
2094 {
2095 self.core.out.push(Outbound::Inventory(o));
2096 }
2097 #[cfg(not(ghast_modern))]
2098 let _ = name;
2099 Ok(())
2100 }
2101
2102 pub fn select_loom_pattern(&mut self, index: i32) -> Result<(), ClickRefused> {
2105 #[cfg(ghast_modern)]
2106 if let Some(o) = self
2107 .core
2108 .inv
2109 .select_loom_pattern_modern(index)
2110 .map_err(ClickRefused::Inventory)?
2111 {
2112 self.core.out.push(Outbound::Inventory(o));
2113 }
2114 #[cfg(not(ghast_modern))]
2115 let _ = index;
2116 Ok(())
2117 }
2118
2119 pub fn select_trade(&mut self, index: i32) -> Result<(), ClickRefused> {
2122 #[cfg(ghast_modern)]
2123 {
2124 let o = self
2125 .core
2126 .inv
2127 .select_trade_modern(index)
2128 .map_err(ClickRefused::Inventory)?;
2129 self.core.out.push(Outbound::Inventory(o));
2130 }
2131 #[cfg(not(ghast_modern))]
2132 let _ = index;
2133 Ok(())
2134 }
2135
2136 pub fn open_inventory(&mut self) -> Result<(), ClickRefused> {
2139 if let Some(o) = self
2140 .core
2141 .inv
2142 .open_inventory()
2143 .map_err(ClickRefused::Inventory)?
2144 {
2145 self.core.out.push(Outbound::Inventory(o));
2146 }
2147 Ok(())
2148 }
2149
2150 pub fn close_window(&mut self) -> Result<(), ClickRefused> {
2152 let o = self.core.inv.close().map_err(ClickRefused::Inventory)?;
2153 self.core.out.push(Outbound::Inventory(o));
2154 self.core.open_window = 0;
2156 Ok(())
2157 }
2158
2159 pub fn set_buttons(&mut self, buttons: Buttons) {
2167 self.core.buttons = buttons;
2168 }
2169
2170 pub fn set_entity_push(&mut self, on: bool) {
2174 self.core.entity_push = on;
2175 }
2176
2177 #[must_use]
2179 pub fn entity_push(&self) -> bool {
2180 self.core.entity_push
2181 }
2182
2183 #[must_use]
2186 pub fn dialog(&self) -> Option<&crate::dialog::Dialog> {
2187 self.core.dialog.as_deref()
2188 }
2189
2190 #[must_use]
2194 pub fn dialog_events(&self) -> &[crate::dialog::DialogEvent] {
2195 &self.core.dialogs
2196 }
2197
2198 pub fn answer_dialog(
2204 &mut self,
2205 answer: &crate::dialog::DialogAnswer,
2206 ) -> Result<crate::dialog::DialogOutcome, crate::dialog::DialogRefused> {
2207 use crate::dialog::{CommandCheck, DialogOutcome, DialogRefused, DialogSent, Effect, Next};
2208 let d = self.core.dialog.clone().ok_or(DialogRefused::NoDialog)?;
2209 let (effect, mut next) = crate::dialog::resolve(&d, answer)?;
2210 let sent = match effect {
2211 Effect::Nothing => DialogSent::Nothing,
2212 Effect::Custom { id, payload } => {
2213 self.core.out.push(Outbound::CustomClickAction {
2214 id: id.clone(),
2215 payload: crate::dialog::payload_nbt(payload.as_ref()),
2216 });
2217 DialogSent::Custom(id)
2218 }
2219 Effect::Command(command) => match ((self.commands)(&command), answer.confirms()) {
2220 (CommandCheck::NoIssues, _)
2221 | (CommandCheck::ParseErrors | CommandCheck::PermissionsRequired, true) => {
2222 self.core.out.push(Outbound::DialogCommand(command.clone()));
2223 DialogSent::Command(command)
2224 }
2225 (CommandCheck::SignatureRequired, true) => {
2226 self.core.out.push(Outbound::Chat(format!("/{command}")));
2228 DialogSent::Command(command)
2229 }
2230 (check, _) => {
2231 next = Next::Stay;
2233 DialogSent::CommandHeld { command, check }
2234 }
2235 },
2236 };
2237 let (open, waiting) = match next {
2238 Next::Stay => (Some(d.clone()), false),
2239 Next::Closed => (None, false),
2240 Next::Waiting => (None, true),
2241 Next::Open(n) => (Some(n), false),
2242 };
2243 if let Some(n) = &open
2244 && !Arc::ptr_eq(n, &d)
2245 {
2246 self.core
2247 .dialogs_pending
2248 .push(crate::dialog::DialogEvent::Shown(n.clone()));
2249 }
2250 self.core.dialog = open.clone();
2251 Ok(DialogOutcome {
2252 sent,
2253 open,
2254 waiting,
2255 })
2256 }
2257
2258 #[must_use]
2260 pub fn buttons(&self) -> Buttons {
2261 self.core.buttons
2262 }
2263
2264 fn sent_crosshair(&self) -> (Option<BlockHit>, Option<hands::EntityHit>) {
2267 *self.crosshair.get_or_init(|| self.pick_sent())
2268 }
2269
2270 fn pick_sent(&self) -> (Option<BlockHit>, Option<hands::EntityHit>) {
2271 let s = &self.core.sent;
2272 let v = self.core.opts.caps;
2273 let eye = if s.sneaking {
2274 v.sneak_eye_height
2275 } else {
2276 v.eye_height
2277 };
2278 let eyes = Vec3::new(s.pos.x, s.pos.y + eye, s.pos.z);
2279 let mut list = PickList::default();
2280 list.fill(self.world, v, eyes);
2281 let t = self.world.crosshair_target(&PickQuery {
2282 eyes,
2283 rotation: (s.yaw, s.pitch),
2284 look: hands::look_vector(s.yaw, s.pitch),
2285 held: None,
2286 now: false,
2287 creative: self.core.game_mode == GameMode::Creative,
2288 player_bb: pick_box(s.pos),
2289 entities: &list.entities,
2290 });
2291 list.split(t, eyes)
2292 }
2293
2294 #[must_use]
2300 pub fn target(&self) -> Option<BlockHit> {
2301 self.sent_crosshair().0
2302 }
2303
2304 #[must_use]
2306 pub fn entities(&self) -> Option<&ghast_entity::Entities> {
2307 self.world.entities()
2308 }
2309
2310 #[must_use]
2314 pub fn target_entity(&self) -> Option<hands::EntityHit> {
2315 self.sent_crosshair().1
2316 }
2317
2318 pub fn attack(&mut self, entity: i32) -> bool {
2322 if self.target_entity().is_none_or(|e| e.id != entity) {
2323 return false;
2324 }
2325 let world = self.world;
2326 let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
2327 let c = &mut *self.core;
2328 let modern = c.opts.caps.combat_1_9;
2329 let mut placed = false;
2330 let mut io = HandsIo {
2331 blocks: &blocks,
2332 target: None,
2333 held: self.held,
2334 held_stack: None,
2335 food: c.health.food,
2336 modern,
2337 off_held: None,
2338 off_stack: None,
2339 entity: None,
2340 factors: DigFactors::default(),
2341 sneaking: c.pose.sneaking,
2342 out: &mut c.out,
2343 broken: &mut c.broken_now,
2344 placed: &mut placed,
2345 spectator: c.game_mode == GameMode::Spectator,
2346 };
2347 if !modern {
2348 io.out.push(Outbound::Swing);
2349 }
2350 c.hands.attack(entity, &mut io);
2351 if modern {
2352 c.out.push(Outbound::Swing);
2353 }
2354 true
2355 }
2356
2357 #[must_use]
2360 pub fn attack_strength(&self, attack_speed: f64) -> f32 {
2361 if self.core.opts.caps.combat_1_9 {
2362 self.core.hands.attack_strength(attack_speed)
2363 } else {
2364 1.0
2365 }
2366 }
2367
2368 #[must_use]
2370 pub fn mining(&self) -> Option<(ghast_protocol::BlockPos, f32)> {
2371 self.core.hands.mining()
2372 }
2373
2374 #[must_use]
2376 pub fn broken(&self) -> u64 {
2377 self.core.hands.broken
2378 }
2379
2380 #[must_use]
2382 pub fn using_item(&self) -> bool {
2383 self.core.hands.using_item()
2384 }
2385
2386 #[must_use]
2392 pub fn prediction_sequence(&self) -> Option<i32> {
2393 self.core.sequence
2394 }
2395
2396 #[must_use]
2401 pub fn vehicle(&self) -> Option<crate::common::Vehicle> {
2402 self.world.vehicle()
2403 }
2404
2405 #[must_use]
2407 pub fn is_riding(&self) -> bool {
2408 self.world.vehicle().is_some()
2409 }
2410
2411 #[must_use]
2414 pub fn is_gliding(&self) -> bool {
2415 self.world.gliding()
2416 }
2417
2418 pub fn start_gliding(&mut self) {
2425 self.core.controls.jump = true;
2426 }
2427
2428 #[must_use]
2439 pub fn item_facts(&self, stack: &ghast_inventory::Stack) -> Option<hands::HeldItem> {
2440 let id = u16::try_from(stack.id()).ok()?;
2441 let count = u8::try_from(stack.count().clamp(0, 255)).unwrap_or(0);
2442 Some(crate::sim::held_item_facts(
2443 self.core.opts.caps.data,
2444 id,
2445 count,
2446 efficiency(stack),
2447 ))
2448 }
2449
2450 #[must_use]
2467 pub fn dig_speed(
2468 &self,
2469 pos: ghast_protocol::BlockPos,
2470 stack: Option<&ghast_inventory::Stack>,
2471 ) -> Option<f32> {
2472 let b = self.world.block_query(pos.x, pos.y, pos.z)?;
2473 if b.air {
2474 return Some(0.0);
2475 }
2476 let c = &*self.core;
2477 let eyes = self.eyes(&c.pose);
2478 let in_water = self
2479 .world
2480 .block_query(
2481 eyes.x.floor() as i32,
2482 eyes.y.floor() as i32,
2483 eyes.z.floor() as i32,
2484 )
2485 .is_some_and(|b| b.water);
2486 let held = stack.and_then(|s| self.item_facts(s));
2487 let factors = DigFactors {
2488 on_ground: c.pose.on_ground,
2489 in_water,
2490 aqua_affinity: c.aqua_affinity,
2491 haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
2492 fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
2493 };
2494 Some(hands::relative_hardness(&b, held.as_ref(), factors))
2495 }
2496
2497 pub fn dig(&mut self, pos: ghast_protocol::BlockPos, face: crate::common::Face) -> bool {
2501 if !self
2502 .target()
2503 .is_some_and(|t| t.pos == pos && t.face == face)
2504 {
2505 return false;
2506 }
2507 let world = self.world;
2508 let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
2509 let c = &mut *self.core;
2510 let mut placed = false;
2511 let mut io = HandsIo {
2512 blocks: &blocks,
2513 target: None,
2514 held: self.held,
2515 held_stack: c.inv.held().cloned(),
2516 food: c.health.food,
2517 modern: c.opts.caps.combat_1_9,
2518 off_held: None,
2519 off_stack: None,
2520 entity: None,
2521 factors: DigFactors {
2522 on_ground: c.pose.on_ground,
2523 in_water: false,
2524 aqua_affinity: c.aqua_affinity,
2525 haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
2526 fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
2527 },
2528 sneaking: c.pose.sneaking,
2529 out: &mut c.out,
2530 broken: &mut c.broken_now,
2531 placed: &mut placed,
2532 spectator: c.game_mode == GameMode::Spectator,
2533 };
2534 c.hands.click_block(pos, face, &mut io);
2535 c.out.push(Outbound::Swing);
2536 true
2537 }
2538
2539 pub fn place(
2543 &mut self,
2544 support: ghast_protocol::BlockPos,
2545 face: crate::common::Face,
2546 hit: Vec3,
2547 ) -> bool {
2548 let Some(t) = self.target().filter(|t| t.pos == support && t.face == face) else {
2549 return false;
2550 };
2551 let world = self.world;
2552 let Some(b) = world.block_query(support.x, support.y, support.z) else {
2553 return false;
2554 };
2555 let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
2556 let c = &mut *self.core;
2557 let mut placed = false;
2558 let first = c.out.len();
2559 let mut io = HandsIo {
2560 blocks: &blocks,
2561 target: None,
2562 held: self.held,
2563 held_stack: c.inv.held().cloned(),
2564 food: c.health.food,
2565 modern: c.opts.caps.combat_1_9,
2566 off_held: None,
2567 off_stack: None,
2568 entity: None,
2569 factors: DigFactors::default(),
2570 sneaking: c.pose.sneaking,
2571 out: &mut c.out,
2572 broken: &mut c.broken_now,
2573 placed: &mut placed,
2574 spectator: c.game_mode == GameMode::Spectator,
2575 };
2576 c.hands
2577 .right_click_block(BlockHit { hit, ..t }, &b, &mut io);
2578 let _ = placed;
2579 predict_planting(c, world, first);
2580 c.out.push(Outbound::Swing);
2581 true
2582 }
2583
2584 #[must_use]
2586 pub fn last_inbound(&self) -> Option<Instant> {
2587 self.core.last_inbound
2588 }
2589
2590 #[must_use]
2596 pub fn planned_look(&self) -> (f32, f32) {
2597 let c = &*self.core;
2598 let now = (c.pose.yaw, c.pose.pitch);
2599 #[cfg(test)]
2600 if let Some(l) = c.forced_look {
2601 return l;
2602 }
2603 if !c.aimed {
2604 return now;
2605 }
2606 let mut r = c.rotation;
2607 let (yaw, pitch) = r.step(c.pose.yaw, c.pose.pitch);
2608 if c.opts.hold_turn_on_action && !post_look_ok(c, yaw, pitch) {
2609 now
2610 } else {
2611 (yaw, pitch)
2612 }
2613 }
2614
2615 pub fn set_flying(&mut self, flying: bool) {
2619 self.core.want_flying = Some(flying);
2620 }
2621
2622 #[must_use]
2625 pub fn held_turns(&self) -> u64 {
2626 self.core.held_turns
2627 }
2628
2629 pub fn status(&mut self, text: &str) {
2631 if self.core.status != text {
2632 text.clone_into(&mut self.core.status);
2633 log::info!(
2634 "[{}] t{} status: {text}",
2635 self.core.opts.name,
2636 self.core.tick
2637 );
2638 }
2639 }
2640}
2641
2642#[cfg(all(
2645 test,
2646 feature = "v1_8",
2647 feature = "v1_12_2",
2648 feature = "v1_16_5",
2649 feature = "v26_1"
2650))]
2651#[path = "engine_tests_26_1.rs"]
2652mod tests_26_1;
2653
2654#[cfg(all(
2655 test,
2656 feature = "v1_8",
2657 feature = "v1_12_2",
2658 feature = "v1_16_5",
2659 feature = "v26_1",
2660 feature = "v26_2"
2661))]
2662#[path = "engine_tests_26_2.rs"]
2663mod tests_26_2;
2664
2665#[cfg(all(
2666 test,
2667 feature = "v1_8",
2668 feature = "v1_12_2",
2669 feature = "v1_16_5",
2670 feature = "v26_1"
2671))]
2672mod tests {
2673 use super::*;
2674 use crate::common::Teleport;
2675 use crate::common::{ChatPosition, EntityAction, JoinGame};
2676 use ghast_protocol::RawPacket;
2677
2678 pub(super) fn opts(version: GameVersion) -> CoreOptions {
2679 CoreOptions {
2680 name: "test".into(),
2681 caps: version.caps(),
2682 settings: ClientSettings::default(),
2683 brand: Some("vanilla".into()),
2684 sensitivity: 0.5,
2685 silent_hold: Duration::from_millis(1500),
2686 hold_turn_on_action: true,
2687 accept_required_packs: true,
2688 entity_push: true,
2689 inventory: match version {
2690 GameVersion::V1_8_9 => ghast_inventory::Version::V1_8,
2691 GameVersion::V1_12_2 => ghast_inventory::Version::V1_12,
2692 _ => ghast_inventory::Version::V1_16_5,
2693 },
2694 }
2695 }
2696
2697 pub(super) fn engine(version: GameVersion) -> Engine<Box<dyn Sim>> {
2699 let sim: Box<dyn Sim> = match version {
2700 GameVersion::V1_8_9 => Box::new(crate::sim::Sim18::new()),
2701 GameVersion::V1_12_2 => Box::new(crate::sim::Sim12::new()),
2702 GameVersion::V26_1 => Box::new(crate::sim::Sim26::test_overworld()),
2703 #[cfg(feature = "v26_2")]
2704 GameVersion::V26_2 => Box::new(crate::sim::Sim262::test_overworld()),
2705 _ => Box::new(crate::sim::Sim16::new()),
2706 };
2707 Engine::new(opts(version), sim)
2708 }
2709
2710 pub(super) fn load(e: &mut Engine<Box<dyn Sim>>, x: i32, z: i32) {
2712 let raw = match e.core.opts.caps.version {
2713 GameVersion::V1_8_9 => crate::sim::test_chunks::v1_8(x, z),
2714 GameVersion::V1_12_2 => crate::sim::test_chunks::v1_12_2(x, z),
2715 GameVersion::V26_1 => crate::sim::test_chunks::v26_1(x, z),
2716 #[cfg(feature = "v26_2")]
2717 GameVersion::V26_2 => crate::sim::test_chunks::v26_2(x, z),
2718 _ => crate::sim::test_chunks::v1_16_5(x, z),
2719 };
2720 e.sim.world_packet(&raw).unwrap();
2721 }
2722
2723 pub(super) fn join(e: &mut Engine<Box<dyn Sim>>) {
2724 e.handle(Inbound::JoinGame(JoinGame {
2725 entity_id: 7,
2726 game_mode: GameMode::Survival,
2727 dimension: "0".into(),
2728 hardcore: false,
2729 dimension_nbt: None,
2730 respawn_screen: true,
2731 }));
2732 for x in -1..=1 {
2734 for z in -1..=1 {
2735 load(e, x, z);
2736 }
2737 }
2738 e.handle(Inbound::Teleport(Teleport {
2739 x: 8.5,
2740 y: 64.0,
2741 z: 8.5,
2742 yaw: 90.0,
2743 pitch: 0.0,
2744 flags: 0,
2745 teleport_id: None,
2746 ..Default::default()
2747 }));
2748 e.handle(Inbound::GameState {
2750 reason: 13,
2751 value: 0.0,
2752 });
2753 e.core.near_loaded = 1;
2755 e.outbound().clear();
2756 }
2757
2758 pub(super) fn names(out: &mut Vec<Outbound>) -> Vec<&'static str> {
2760 let v = out
2761 .iter()
2762 .map(|o| match o {
2763 Outbound::Move(m) => m.trace_id(),
2764 Outbound::Chat(_) => "chat",
2765 Outbound::HeldSlot(_) => "held_slot",
2766 Outbound::Swing => "swing",
2767 Outbound::EntityAction { .. } => "entity_action",
2768 Outbound::KeepAlive(_) => "keep_alive",
2769 Outbound::Transaction { .. } => "transaction",
2770 Outbound::TeleportConfirm(_) => "teleport_confirm",
2771 Outbound::Respawn => "respawn",
2772 Outbound::Settings(_) => "settings",
2773 Outbound::Brand(_) => "brand",
2774 Outbound::Abilities { .. } => "abilities",
2775 Outbound::Dig { .. } => "block_dig",
2776 Outbound::Place { .. } | Outbound::UseItem { .. } => "block_place",
2777 Outbound::SwingOffHand => "swing_off",
2778 Outbound::UseEntity { .. } => "use_entity",
2779 Outbound::Inventory(_) => "inventory",
2780 Outbound::PlayerInput(_) => "player_input",
2781 Outbound::TickEnd => "tick_end",
2782 Outbound::PlayerLoaded => "player_loaded",
2783 Outbound::ChatSessionUpdate => "chat_session_update",
2784 Outbound::ChunkBatchReceived(_) => "chunk_batch_received",
2785 Outbound::Pong(_) => "pong",
2786 Outbound::ResourcePackStatus { .. } => "resource_pack",
2787 Outbound::CookieResponse { .. } => "cookie_response",
2788 Outbound::LookAnswer { .. } => "C05",
2789 Outbound::VehicleMove { .. } => "vehicle_move",
2790 Outbound::SteerBoat { .. } => "steer_boat",
2791 Outbound::CustomClickAction { .. } => "custom_click_action",
2792 Outbound::DialogCommand(_) => "chat_command",
2793 Outbound::Raw(_) => "raw",
2794 })
2795 .collect();
2796 out.clear();
2797 v
2798 }
2799
2800 pub(super) struct Script<F: FnMut(&mut TickContext<'_>)>(pub(super) F);
2801 impl<F: FnMut(&mut TickContext<'_>)> Behavior for Script<F> {
2802 fn tick(&mut self, ctx: &mut TickContext<'_>) {
2803 (self.0)(ctx);
2804 }
2805 }
2806
2807 #[test]
2808 fn join_sends_settings_then_brand() {
2809 let mut e = engine(GameVersion::V1_8_9);
2810 e.handle(Inbound::JoinGame(JoinGame {
2811 entity_id: 1,
2812 game_mode: GameMode::Creative,
2813 dimension: "0".into(),
2814 hardcore: false,
2815 dimension_nbt: None,
2816 respawn_screen: true,
2817 }));
2818 assert_eq!(names(e.outbound()), ["settings", "brand"]);
2819 }
2820
2821 #[test]
2822 fn nothing_before_the_first_teleport() {
2823 let mut e = engine(GameVersion::V1_8_9);
2824 let mut b = Idle;
2825 let t0 = Instant::now();
2826 load(&mut e, 0, 0);
2827 e.outbound().clear();
2828 for i in 0..5 {
2829 e.tick(&mut b, t0 + Duration::from_millis(50 * i));
2830 }
2831 assert!(e.outbound().is_empty());
2832 }
2833
2834 #[test]
2835 fn teleport_reply_per_version() {
2836 let mut e = engine(GameVersion::V1_16_5);
2837 e.handle(Inbound::Teleport(Teleport {
2838 x: 1.0,
2839 y: 2.0,
2840 z: 3.0,
2841 yaw: 450.0,
2842 pitch: 100.0,
2843 flags: 0,
2844 teleport_id: Some(5),
2845 ..Default::default()
2846 }));
2847 let out = std::mem::take(e.outbound());
2848 assert_eq!(out[0], Outbound::TeleportConfirm(5));
2849 match out[1] {
2850 Outbound::Move(MovePacket::PositionLook {
2851 yaw,
2852 pitch,
2853 on_ground,
2854 ..
2855 }) => {
2856 assert_eq!((yaw, pitch, on_ground), (90.0, 90.0, false));
2857 }
2858 ref o => panic!("unexpected {o:?}"),
2859 }
2860 let mut e = engine(GameVersion::V1_8_9);
2861 e.handle(Inbound::Teleport(Teleport {
2862 x: 1.0,
2863 y: 2.0,
2864 z: 3.0,
2865 yaw: 450.0,
2866 pitch: 100.0,
2867 flags: 0,
2868 teleport_id: None,
2869 ..Default::default()
2870 }));
2871 let out = std::mem::take(e.outbound());
2872 assert_eq!(out.len(), 1);
2873 assert!(matches!(
2875 out[0],
2876 Outbound::Move(MovePacket::PositionLook {
2877 yaw: 90.0,
2878 pitch: 100.0,
2879 ..
2880 })
2881 ));
2882 }
2883
2884 #[test]
2889 fn entity_pick_uses_the_tracker_and_the_proven_pick() {
2890 use ghast_protocol::v1_8::play::clientbound::id;
2891 use std::cell::Cell;
2892 let raw = |id: i32, b: Vec<u8>| RawPacket {
2893 id,
2894 body: bytes::Bytes::from(b),
2895 };
2896 let zombie = |eid: u8, x: f64| {
2897 let mut b = vec![eid, 54];
2898 for v in [x, 64.0, 8.5] {
2899 b.extend(((v * 32.0) as i32).to_be_bytes());
2900 }
2901 b.extend([0, 0, 0, 0, 0, 0, 0, 0, 0, 0x7f]);
2902 raw(id::SPAWN_ENTITY_LIVING, b)
2903 };
2904 let mut e = engine(GameVersion::V1_8_9);
2905 let mut login = 7i32.to_be_bytes().to_vec();
2906 login.extend([0, 0, 2, 20, 7]);
2907 login.extend(b"default");
2908 login.push(0);
2909 e.sim.world_packet(&raw(id::LOGIN, login)).unwrap();
2910 e.sim.set_entities(Some(ghast_entity::Config::default()));
2911 join(&mut e);
2912 let pos: i64 = (4 << 38) | (65 << 26) | 8;
2915 let mut b = pos.to_be_bytes().to_vec();
2916 b.push(1 << 4);
2917 e.sim.world_packet(&raw(id::BLOCK_CHANGE, b)).unwrap();
2918 let t0 = Instant::now();
2919 e.note_inbound(t0);
2920 let seen = Cell::new((None, None));
2921 let look = |e: &mut Engine<Box<dyn Sim>>| {
2922 let mut b = Script(|ctx: &mut TickContext<'_>| {
2923 seen.set((
2924 ctx.target_entity().map(|h| (h.id, h.distance)),
2925 ctx.target().map(|t| (t.pos, t.face)),
2926 ));
2927 });
2928 e.tick(&mut b, t0);
2929 seen.get()
2930 };
2931 assert_eq!(
2932 look(&mut e),
2933 (
2934 None,
2935 Some((ghast_protocol::BlockPos::new(4, 65, 8), crate::Face::East))
2936 )
2937 );
2938 e.sim.world_packet(&zombie(50, 6.5)).unwrap();
2941 let (ent, block) = look(&mut e);
2942 let (eid, d) = ent.unwrap();
2943 assert_eq!(eid, 50);
2944 assert!((d - 1.6).abs() < 1e-6, "{d}");
2945 assert_eq!(block, None);
2946 e.sim
2948 .world_packet(&raw(id::ENTITY_DESTROY, vec![1, 50]))
2949 .unwrap();
2950 e.sim.world_packet(&zombie(51, 5.0)).unwrap();
2951 assert_eq!(look(&mut e), (None, None));
2952 }
2953
2954 #[test]
2955 fn actions_precede_the_single_movement_packet() {
2956 let mut e = engine(GameVersion::V1_8_9);
2957 join(&mut e);
2958 let t0 = Instant::now();
2959 e.note_inbound(t0);
2960 let mut b = Script(|ctx: &mut TickContext<'_>| {
2961 if ctx.tick() == 2 {
2962 ctx.select_slot(3);
2963 ctx.chat("hello");
2964 ctx.swing();
2965 ctx.set_controls(Controls {
2966 sneak: true,
2967 ..Controls::default()
2968 });
2969 }
2970 });
2971 e.tick(&mut b, t0);
2972 assert_eq!(names(e.outbound()), ["C06"]);
2973 e.tick(&mut b, t0);
2974 assert_eq!(
2975 names(e.outbound()),
2976 ["held_slot", "chat", "swing", "entity_action", "C03"]
2977 );
2978 for _ in 0..100 {
2979 e.tick(&mut b, t0);
2980 let n = names(e.outbound());
2981 assert_eq!(n.len(), 1, "one movement packet per tick: {n:?}");
2982 }
2983 }
2984
2985 #[test]
2988 fn raw_packets_keep_the_call_order() {
2989 use crate::version::ClientVersion;
2990 for v in [GameVersion::V1_8_9, GameVersion::V26_1] {
2991 let mut e = engine(v);
2992 join(&mut e);
2993 let t0 = Instant::now();
2994 e.note_inbound(t0);
2995 let mut refused = None;
2996 let mut b = Script(|ctx: &mut TickContext<'_>| {
2997 if ctx.tick() == 3 {
2998 ctx.swing();
2999 ctx.send_raw(0x7f, vec![1, 2, 3]);
3000 ctx.send_packet(&ghast_protocol::v26_1::play::serverbound::ArmAnimation {
3001 hand: ghast_protocol::v26_1::play::serverbound::ArmAnimationHand::OFF_HAND,
3002 })
3003 .unwrap();
3004 refused = Some(ctx.send_packet(
3005 &ghast_protocol::v26_1::play::clientbound::KeepAlive { keep_alive_id: 1 },
3006 ));
3007 ctx.chat("after");
3008 }
3009 });
3010 for _ in 0..2 {
3011 e.tick(&mut b, t0);
3012 }
3013 e.outbound().clear();
3014 e.tick(&mut b, t0);
3015 let out = e.outbound().clone();
3016 let n = names(e.outbound());
3017 assert_eq!(n[..4], ["swing", "raw", "raw", "chat"], "{v:?} {n:?}");
3018 let movement = n.iter().position(|x| {
3019 x.starts_with('C') || x.contains("position") || *x == "flying" || *x == "look"
3020 });
3021 assert!(movement.is_none_or(|m| m > 3), "{v:?} {n:?}");
3022 assert!(refused.unwrap().is_err());
3023 let typed = ghast_protocol::v26_1::play::serverbound::ArmAnimation {
3025 hand: ghast_protocol::v26_1::play::serverbound::ArmAnimationHand::OFF_HAND,
3026 };
3027 let mut want = ghast_protocol::FrameEncoder::new();
3028 want.write_packet(&typed).unwrap();
3029 let mut got = ghast_protocol::FrameEncoder::new();
3030 let mut wire = crate::version::Wire26_1::default();
3031 crate::version::V26_1::write_play(&mut got, &out[2], &mut wire).unwrap();
3032 assert_eq!(got.take(), want.take());
3033 }
3034 }
3035
3036 #[test]
3037 fn standing_bot_packets() {
3038 let mut e = engine(GameVersion::V1_8_9);
3039 join(&mut e);
3040 let mut b = Idle;
3041 let t0 = Instant::now();
3042 e.note_inbound(t0);
3043 e.tick(&mut b, t0);
3045 let out = std::mem::take(e.outbound());
3046 assert!(matches!(
3047 out[..],
3048 [Outbound::Move(MovePacket::PositionLook {
3049 on_ground: false,
3050 ..
3051 })]
3052 ));
3053 let mut kinds = Vec::new();
3055 for _ in 0..42 {
3056 e.tick(&mut b, t0);
3057 kinds.extend(names(e.outbound()));
3058 }
3059 assert_eq!(kinds.iter().filter(|k| **k == "C04").count(), 2);
3060 assert_eq!(kinds.iter().filter(|k| **k == "C03").count(), 40);
3061 assert_eq!((kinds[20], kinds[41]), ("C04", "C04"));
3062 assert!(e.core.sent.on_ground);
3063 }
3064
3065 #[test]
3066 fn silent_server_freezes_behaviour() {
3067 let mut e = engine(GameVersion::V1_8_9);
3068 join(&mut e);
3069 let t0 = Instant::now();
3070 e.note_inbound(t0);
3071 let mut ticks = 0;
3072 let mut b = Script(|ctx: &mut TickContext<'_>| {
3073 ticks += 1;
3074 ctx.set_controls(Controls {
3075 sneak: true,
3076 ..Controls::default()
3077 });
3078 });
3079 e.tick(&mut b, t0 + Duration::from_millis(100));
3080 e.tick(&mut b, t0 + Duration::from_millis(1600));
3081 let n = names(e.outbound());
3083 assert_eq!(n, ["entity_action", "C06", "entity_action", "C03"]);
3084 e.note_inbound(t0 + Duration::from_millis(1700));
3085 e.tick(&mut b, t0 + Duration::from_millis(1700));
3086 let _ = b;
3087 assert_eq!(ticks, 2);
3088 }
3089
3090 #[test]
3091 fn keepalive_answered_transactions_left_to_the_inventory() {
3092 let mut e = engine(GameVersion::V1_8_9);
3093 join(&mut e);
3094 e.handle(Inbound::KeepAlive(42));
3095 e.handle(Inbound::Transaction {
3098 window_id: 0,
3099 action: -5,
3100 accepted: false,
3101 });
3102 assert_eq!(std::mem::take(e.outbound()), [Outbound::KeepAlive(42)]);
3103 }
3104
3105 #[test]
3106 fn panicking_behaviour_does_not_stop_the_tick() {
3107 let mut e = engine(GameVersion::V1_8_9);
3108 join(&mut e);
3109 let t0 = Instant::now();
3110 let mut b = Script(|ctx: &mut TickContext<'_>| {
3111 if ctx.tick() == 2 {
3112 panic!("boom");
3113 }
3114 });
3115 let hook = std::panic::take_hook();
3116 std::panic::set_hook(Box::new(|_| {}));
3117 for _ in 0..5 {
3118 e.tick(&mut b, t0);
3119 }
3120 std::panic::set_hook(hook);
3121 assert!(e.state.failed);
3122 assert_eq!(names(e.outbound()).len(), 5);
3123 }
3124
3125 #[test]
3126 fn chat_events_reach_the_behaviour_once() {
3127 let mut e = engine(GameVersion::V1_16_5);
3128 join(&mut e);
3129 e.handle(Inbound::Chat(ChatMessage {
3130 rendered: None,
3131 json: r#"{"text":"hi"}"#.into(),
3132 position: ChatPosition::System,
3133 sender: None,
3134 }));
3135 let mut seen = Vec::new();
3136 let mut b = Script(|ctx: &mut TickContext<'_>| {
3137 seen.extend(ctx.events().chat.iter().map(ChatMessage::plain));
3138 });
3139 let t0 = Instant::now();
3140 e.tick(&mut b, t0);
3141 e.tick(&mut b, t0);
3142 let _ = b;
3143 assert_eq!(seen, ["hi"]);
3144 }
3145
3146 #[test]
3147 fn immediate_respawn_1_16() {
3148 let mut e = engine(GameVersion::V1_16_5);
3149 join(&mut e);
3150 e.handle(Inbound::GameState {
3151 reason: 11,
3152 value: 1.0,
3153 });
3154 e.handle(Inbound::Died { entity_id: 7 });
3155 assert_eq!(e.outbound().as_slice(), [Outbound::Respawn]);
3156 }
3157
3158 #[test]
3161 fn dig_with_the_left_button() {
3162 let mut e = engine(GameVersion::V1_8_9);
3163 join(&mut e);
3164 let t0 = Instant::now();
3165 e.note_inbound(t0);
3166 let mut b = Script(|ctx: &mut TickContext<'_>| {
3167 ctx.set_aim(90.0, 89.5);
3168 let down = ctx.target().is_some_and(|t| {
3169 t.pos == ghast_protocol::BlockPos::new(8, 63, 8) && t.face == crate::Face::Up
3170 });
3171 ctx.set_buttons(Buttons {
3172 left: down,
3173 right: false,
3174 });
3175 });
3176 let mut ticks = Vec::new();
3177 for _ in 0..200 {
3178 e.tick(&mut b, t0);
3179 let n = names(e.outbound());
3180 assert_eq!(n.iter().filter(|x| x.starts_with('C')).count(), 1, "{n:?}");
3181 assert!(n.last().unwrap().starts_with('C'), "movement last: {n:?}");
3182 ticks.push(n);
3183 }
3184 let flat: Vec<&str> = ticks.iter().flatten().copied().collect();
3185 assert_eq!(
3186 flat.iter().filter(|x| **x == "block_dig").count(),
3187 2,
3188 "start + finish"
3189 );
3190 assert!(e.core.hands.broken == 1);
3191 let start = ticks.iter().position(|t| t.contains(&"block_dig")).unwrap();
3193 let finish = ticks
3194 .iter()
3195 .rposition(|t| t.contains(&"block_dig"))
3196 .unwrap();
3197 assert_eq!(finish - start, 150);
3198 assert!(e.sim.block_query(8, 63, 8).unwrap().air);
3199 assert!(
3200 e.core.pose.pos.y < 64.0,
3201 "falls into the hole: {:?}",
3202 e.core.pose.pos
3203 );
3204 }
3205
3206 #[test]
3210 fn outbound_visible_to_the_behaviour() {
3211 use crate::version::ClientVersion;
3212 struct Watch {
3213 seen: Vec<Vec<Outbound>>,
3214 seq: Vec<Option<i32>>,
3215 }
3216 impl Behavior for Watch {
3217 fn tick(&mut self, ctx: &mut TickContext<'_>) {
3218 self.seq.push(ctx.prediction_sequence());
3219 ctx.set_aim(90.0, 89.5);
3220 let down = ctx.target().is_some_and(|t| t.face == crate::Face::Up);
3221 ctx.set_buttons(Buttons {
3222 left: down,
3223 right: false,
3224 });
3225 }
3226 fn after_tick(&mut self, view: &TickView<'_>) {
3227 self.seen.push(view.outbound().to_vec());
3228 assert_eq!(view.prediction_sequence(), *self.seq.last().unwrap());
3229 }
3230 }
3231 let mut e = engine(GameVersion::V1_8_9);
3232 join(&mut e);
3233 let t0 = Instant::now();
3234 e.note_inbound(t0);
3235 let mut b = Watch {
3236 seen: Vec::new(),
3237 seq: Vec::new(),
3238 };
3239 for t in 0..20 {
3240 e.note_sequence(Some(t));
3241 e.tick(&mut b, t0);
3242 assert_eq!(*e.outbound(), *b.seen.last().unwrap());
3243 e.outbound().clear();
3244 }
3245 assert_eq!(b.seq.last(), Some(&Some(19)));
3246 let dig = b
3247 .seen
3248 .iter()
3249 .find(|o| o.iter().any(|p| matches!(p, Outbound::Dig { .. })))
3250 .expect("a dig start");
3251 assert!(matches!(
3252 dig.iter()
3253 .find(|p| matches!(p, Outbound::Dig { .. }))
3254 .unwrap(),
3255 Outbound::Dig {
3256 status: crate::common::DigStatus::Start,
3257 face: crate::Face::Up,
3258 ..
3259 }
3260 ));
3261 assert!(matches!(dig.last(), Some(Outbound::Move(_))));
3262 let mut wire = crate::version::Wire26_1::default();
3264 let mut enc = ghast_protocol::FrameEncoder::new();
3265 let dig = |status| Outbound::Dig {
3266 status,
3267 pos: ghast_protocol::BlockPos::new(1, 2, 3),
3268 face: crate::Face::Up,
3269 };
3270 use crate::common::DigStatus;
3271 assert_eq!(crate::version::V26_1::prediction_sequence(&wire), Some(0));
3272 for (s, want) in [
3273 (DigStatus::Start, 1),
3274 (DigStatus::Abort, 1),
3275 (DigStatus::Start, 2),
3276 (DigStatus::Finish, 3),
3277 ] {
3278 crate::version::V26_1::write_play(&mut enc, &dig(s), &mut wire).unwrap();
3279 assert_eq!(
3280 crate::version::V26_1::prediction_sequence(&wire),
3281 Some(want)
3282 );
3283 }
3284 assert_eq!(crate::version::V1_8::prediction_sequence(&()), None);
3285 }
3286
3287 #[test]
3289 fn dig_speed_and_item_facts() {
3290 let mut e = engine(GameVersion::V1_16_5);
3292 join(&mut e);
3293 let t0 = Instant::now();
3294 e.note_inbound(t0);
3295 let mut b = Script(|ctx: &mut TickContext<'_>| {
3296 let id = |n: &str| i32::from(ghast_data::v1_16_5::Item::from_name(n).unwrap().id());
3297 let bread = ctx.item_facts(&ghast_inventory::Stack::new(id("bread"), 3, 0));
3298 assert!(bread.is_some_and(|f| f.food && f.usable && !f.places_block && f.count == 3));
3299 let dirt = ctx.item_facts(&ghast_inventory::Stack::new(id("dirt"), 1, 0));
3300 assert!(dirt.is_some_and(|f| f.places_block && !f.food));
3301 });
3302 e.tick(&mut b, t0);
3303
3304 let mut e = engine(GameVersion::V1_8_9);
3305 join(&mut e);
3306 e.note_inbound(t0);
3307 let got = std::cell::Cell::new(None);
3308 let mut b = Script(|ctx: &mut TickContext<'_>| {
3309 let stone = ghast_protocol::BlockPos::new(8, 63, 8);
3310 let pick = ghast_inventory::Stack::new(278, 1, 0);
3311 let facts = ctx.item_facts(&pick).unwrap();
3312 assert!(!facts.places_block && !facts.food);
3313 got.set(Some((
3314 ctx.dig_speed(stone, None),
3315 ctx.dig_speed(stone, Some(&pick)),
3316 ctx.dig_speed(ghast_protocol::BlockPos::new(8, 64, 8), None),
3317 ctx.dig_speed(ghast_protocol::BlockPos::new(500, 63, 8), None),
3318 )));
3319 });
3320 for _ in 0..40 {
3322 e.tick(&mut b, t0);
3323 }
3324 assert!(e.core.pose.on_ground, "{:?}", e.core.pose);
3325 let (hand, pick, air, unloaded) = got.get().expect("ticked");
3326 assert_eq!(hand, Some(1.0 / 1.5 / 100.0));
3329 assert_eq!(pick, Some(8.0 / 1.5 / 30.0));
3331 assert_eq!(air, Some(0.0));
3332 assert_eq!(unloaded, None);
3333 }
3334
3335 #[test]
3338 fn place_needs_the_sent_look() {
3339 let mut e = engine(GameVersion::V1_8_9);
3340 join(&mut e);
3341 let t0 = Instant::now();
3342 e.note_inbound(t0);
3343 let floor = ghast_protocol::BlockPos::new(8, 63, 8);
3344 let mut results = Vec::new();
3345 let mut b = Script(|ctx: &mut TickContext<'_>| {
3346 ctx.set_aim(90.0, 89.5);
3347 results.push(ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)));
3348 });
3349 e.core
3351 .inv
3352 .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(1, 64, 0)));
3353 let mut placed_tick = None;
3354 for i in 0..20 {
3355 e.tick(&mut b, t0);
3356 let n = names(e.outbound());
3357 if n.contains(&"block_place") {
3358 assert_eq!(n[..2], ["block_place", "swing"], "{n:?}");
3359 placed_tick.get_or_insert(i);
3360 }
3361 }
3362 let _ = b;
3363 let first = results.iter().position(|r| *r).unwrap();
3364 assert!(first > 3, "refused while still turning");
3365 assert_eq!(placed_tick, Some(first));
3366 assert_eq!(e.core.inv.held().map(|s| s.id()), Some(1));
3367 }
3368
3369 #[test]
3370 fn sneak_action_order() {
3371 let mut e = engine(GameVersion::V1_8_9);
3372 join(&mut e);
3373 let mut b = Script(|ctx: &mut TickContext<'_>| {
3374 ctx.set_controls(Controls {
3375 sneak: true,
3376 ..Controls::default()
3377 });
3378 });
3379 e.tick(&mut b, Instant::now());
3380 let out = std::mem::take(e.outbound());
3381 assert_eq!(
3382 out[0],
3383 Outbound::EntityAction {
3384 entity_id: 7,
3385 action: EntityAction::StartSneaking
3386 }
3387 );
3388 assert!(matches!(out[1], Outbound::Move(_)));
3389 }
3390
3391 #[test]
3393 fn block_updates_per_version() {
3394 use ghast_protocol::BlockPos;
3395 for &v in GameVersion::ALL {
3396 let mut e = engine(v);
3397 join(&mut e);
3398 e.sim.collect_block_updates(true);
3399 let t0 = Instant::now();
3400 e.note_inbound(t0);
3401 let raws = match v {
3402 GameVersion::V1_8_9 => {
3403 use ghast_protocol::v1_8::play::clientbound as cb;
3404 vec![
3405 RawPacket::from_packet(&cb::BlockChange {
3406 location: BlockPos::new(3, 63, 4),
3407 r#type: 59 << 4 | 7,
3408 })
3409 .unwrap(),
3410 RawPacket::from_packet(&cb::MultiBlockChange {
3411 chunk_x: 0,
3412 chunk_z: 0,
3413 records: vec![cb::MultiBlockChangeRecords {
3414 horizontal_pos: 5 << 4 | 6,
3415 y: 62,
3416 block_id: 60 << 4 | 7,
3417 }],
3418 })
3419 .unwrap(),
3420 ]
3421 }
3422 GameVersion::V1_12_2 => {
3423 use ghast_protocol::v1_12_2::play::clientbound as cb;
3424 vec![
3425 RawPacket::from_packet(&cb::BlockChange {
3426 location: BlockPos::new(3, 63, 4),
3427 r#type: 59 << 4 | 7,
3428 })
3429 .unwrap(),
3430 RawPacket::from_packet(&cb::MultiBlockChange {
3431 chunk_x: 0,
3432 chunk_z: 0,
3433 records: vec![cb::MultiBlockChangeRecords {
3434 horizontal_pos: 5 << 4 | 6,
3435 y: 62,
3436 block_id: 60 << 4 | 7,
3437 }],
3438 })
3439 .unwrap(),
3440 ]
3441 }
3442 GameVersion::V26_1 => {
3443 use ghast_protocol::v26_1::play::clientbound as cb;
3444 let local = (5 << 8 | 6 << 4 | 14) as i64;
3446 vec![
3447 RawPacket::from_packet(&cb::BlockChange {
3448 location: BlockPos::new(3, 63, 4),
3449 r#type: 1,
3450 })
3451 .unwrap(),
3452 RawPacket::from_packet(&cb::MultiBlockChange {
3453 chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
3454 x: 0,
3455 z: 0,
3456 y: -1,
3457 },
3458 records: vec![9 << 12 | local],
3459 })
3460 .unwrap(),
3461 ]
3462 }
3463 #[cfg(feature = "v26_2")]
3464 GameVersion::V26_2 => {
3465 use ghast_protocol::v26_2::play::clientbound as cb;
3466 let local = (5 << 8 | 6 << 4 | 14) as i64;
3468 vec![
3469 RawPacket::from_packet(&cb::BlockChange {
3470 location: BlockPos::new(3, 63, 4),
3471 r#type: 1,
3472 })
3473 .unwrap(),
3474 RawPacket::from_packet(&cb::MultiBlockChange {
3475 chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
3476 x: 0,
3477 z: 0,
3478 y: -1,
3479 },
3480 records: vec![9 << 12 | local],
3481 })
3482 .unwrap(),
3483 ]
3484 }
3485 _ => {
3486 use ghast_protocol::v1_16_5::play::clientbound as cb;
3487 let local = (5 << 8 | 6 << 4 | 14) as i64;
3489 vec![
3490 RawPacket::from_packet(&cb::BlockChange {
3491 location: BlockPos::new(3, 63, 4),
3492 r#type: 1,
3493 })
3494 .unwrap(),
3495 RawPacket::from_packet(&cb::MultiBlockChange {
3496 chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
3497 x: 0,
3498 z: 0,
3499 y: 0xF_FFFF,
3500 },
3501 not_trust_edges: false,
3502 records: vec![9 << 12 | local],
3503 })
3504 .unwrap(),
3505 ]
3506 }
3507 };
3508 for raw in &raws {
3509 e.sim.world_packet(raw).unwrap();
3510 }
3511 let mut seen = Vec::new();
3512 let mut b = Script(|ctx: &mut TickContext<'_>| {
3513 seen.push(ctx.events().block_updates.clone());
3514 });
3515 e.tick(&mut b, t0);
3516 e.tick(&mut b, t0);
3517 let _ = b;
3518 let want = match v {
3519 GameVersion::V1_8_9 | GameVersion::V1_12_2 => vec![
3520 (BlockPos::new(3, 63, 4), 59 << 4 | 7),
3521 (BlockPos::new(5, 62, 6), 60 << 4 | 7),
3522 ],
3523 _ => vec![(BlockPos::new(3, 63, 4), 1), (BlockPos::new(5, -2, 6), 9)],
3524 };
3525 assert_eq!(seen, [want, Vec::new()], "{v:?}");
3526
3527 e.sim.collect_block_updates(false);
3529 e.sim.world_packet(&raws[0]).unwrap();
3530 let mut n = usize::MAX;
3531 let mut b = Script(|ctx: &mut TickContext<'_>| n = ctx.events().block_updates.len());
3532 e.tick(&mut b, t0);
3533 let _ = b;
3534 assert_eq!(n, 0);
3535 }
3536 }
3537
3538 #[test]
3540 fn set_flying_needs_may_fly() {
3541 for &v in GameVersion::ALL {
3542 let mut e = engine(v);
3543 join(&mut e);
3544 let t0 = Instant::now();
3545 e.note_inbound(t0);
3546 e.handle(Inbound::Teleport(Teleport {
3548 x: 8.5,
3549 y: 70.0,
3550 z: 8.5,
3551 yaw: 90.0,
3552 pitch: 0.0,
3553 flags: 0,
3554 teleport_id: Some(2),
3555 ..Default::default()
3556 }));
3557 e.outbound().clear();
3558 let mut b = Script(|ctx: &mut TickContext<'_>| ctx.set_flying(true));
3559 e.tick(&mut b, t0);
3560 assert!(!names(e.outbound()).contains(&"abilities"), "{v:?}");
3561 assert!(!e.core.pose.flying);
3562 e.handle(Inbound::Abilities(Abilities {
3563 flags: 4,
3564 ..Abilities::default()
3565 }));
3566 e.tick(&mut b, t0);
3567 let out = std::mem::take(e.outbound());
3568 assert_eq!(
3569 out[0],
3570 Outbound::Abilities {
3571 flags: 6,
3572 flying_speed: 0.05,
3573 walking_speed: 0.1
3574 },
3575 "{v:?}"
3576 );
3577 assert!(matches!(out[1], Outbound::Move(_)), "{out:?}");
3578 assert!(e.core.pose.flying && e.core.sent.flying);
3579 e.tick(&mut b, t0);
3581 assert!(!names(e.outbound()).contains(&"abilities"));
3582 let _ = b;
3583 }
3584 }
3585
3586 #[test]
3590 fn v1_12_2_walks_with_physics() {
3591 let mut e = engine(GameVersion::V1_12_2);
3592 join(&mut e);
3593 let t0 = Instant::now();
3594 e.note_inbound(t0);
3595 let mut idle = Script(|_: &mut TickContext<'_>| {});
3596 e.tick(&mut idle, t0);
3597 assert!(
3598 !names(e.outbound())
3599 .iter()
3600 .any(|n| matches!(*n, "C04" | "C06"))
3601 );
3602 for _ in 0..5 {
3603 e.tick(&mut idle, t0);
3604 }
3605 e.outbound().clear();
3606 let start = e.core.pose.pos;
3607 assert!(e.core.pose.on_ground, "{:?}", e.core.pose);
3608 let mut walk = Script(|ctx: &mut TickContext<'_>| {
3609 ctx.set_controls(crate::common::Controls {
3610 forward: true,
3611 ..Default::default()
3612 });
3613 });
3614 for _ in 0..10 {
3615 e.tick(&mut walk, t0);
3616 }
3617 let _ = walk;
3618 let moved = names(e.outbound());
3619 assert!(
3620 moved.iter().any(|n| matches!(*n, "C04" | "C06")),
3621 "{moved:?}"
3622 );
3623 assert!(e.core.pose.pos.x < start.x - 0.5, "{:?}", e.core.pose.pos);
3625 assert_eq!(e.core.pose.pos.y, 64.0);
3626 let mut stop = Script(|ctx: &mut TickContext<'_>| {
3627 ctx.set_controls(crate::common::Controls::default());
3628 });
3629 for _ in 0..30 {
3630 e.tick(&mut stop, t0);
3631 }
3632 e.outbound().clear();
3633 for _ in 0..5 {
3634 e.tick(&mut stop, t0);
3635 }
3636 let _ = (idle, stop);
3637 let still = names(e.outbound());
3639 assert!(still.len() <= 1 && !still.contains(&"C03"), "{still:?}");
3640 }
3641
3642 #[test]
3644 fn finished_behaviour_is_not_ticked() {
3645 struct Three(std::rc::Rc<std::cell::Cell<u32>>);
3646 impl Behavior for Three {
3647 fn tick(&mut self, _ctx: &mut TickContext<'_>) {
3648 self.0.set(self.0.get() + 1);
3649 }
3650 fn running(&self) -> bool {
3651 self.0.get() < 3
3652 }
3653 }
3654 let ticks = std::rc::Rc::new(std::cell::Cell::new(0));
3655 let mut e = engine(GameVersion::V1_8_9);
3656 join(&mut e);
3657 let t0 = Instant::now();
3658 e.note_inbound(t0);
3659 let mut b: Box<dyn Behavior> = Box::new(Three(ticks.clone()));
3660 for _ in 0..10 {
3661 e.tick(&mut b, t0);
3662 let out = std::mem::take(e.outbound());
3664 assert!(
3665 out.iter().any(|o| matches!(o, Outbound::Move(_))),
3666 "{out:?}"
3667 );
3668 }
3669 assert_eq!(
3670 ticks.get(),
3671 3,
3672 "not ticked after running() == false (through the Box)"
3673 );
3674 }
3675
3676 #[test]
3678 fn turn_held_on_a_place_tick() {
3679 let mut e = engine(GameVersion::V1_8_9);
3680 join(&mut e);
3681 let t0 = Instant::now();
3682 e.note_inbound(t0);
3683 e.core
3684 .inv
3685 .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(1, 64, 0)));
3686 let floor = ghast_protocol::BlockPos::new(8, 63, 8);
3687 let mut tick = 0;
3688 let mut placed_at = None;
3689 let mut pitches = Vec::new();
3690 let mut b = Script(|ctx: &mut TickContext<'_>| {
3691 tick += 1;
3692 if placed_at.is_none() {
3693 ctx.set_aim(90.0, 89.5);
3694 if ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)) {
3695 placed_at = Some(tick);
3696 ctx.set_aim(90.0, -60.0);
3698 }
3699 } else {
3700 ctx.set_aim(90.0, -60.0);
3701 }
3702 pitches.push(ctx.pose().pitch);
3703 });
3704 for _ in 0..30 {
3705 e.tick(&mut b, t0);
3706 e.outbound().clear();
3707 }
3708 let _ = b;
3709 let p = placed_at.expect("placed");
3710 assert_eq!(e.core.held_turns, 1);
3711 assert_eq!(pitches[p], pitches[p - 1], "{pitches:?}");
3713 assert!(pitches[p + 1] < pitches[p], "{pitches:?}");
3714 }
3715
3716 #[test]
3718 fn click_ticket_matches_the_confirm() {
3719 let mut e = engine(GameVersion::V1_8_9);
3720 join(&mut e);
3721 let t0 = Instant::now();
3722 e.note_inbound(t0);
3723 e.core
3724 .inv
3725 .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(1, 64, 0)));
3726 let mut ticket = None;
3727 let mut n = 0;
3728 let mut b = Script(|ctx: &mut TickContext<'_>| {
3729 n += 1;
3730 if n == 1 {
3731 ctx.open_inventory().unwrap();
3732 } else if ticket.is_none() {
3733 ticket = ctx
3734 .click(ghast_inventory::Click::Pickup {
3735 slot: 36,
3736 right: false,
3737 })
3738 .ok();
3739 }
3740 });
3741 for _ in 0..3 {
3742 e.tick(&mut b, t0);
3743 }
3744 let _ = b;
3745 let t = ticket.expect("click sent");
3746 assert_eq!(t.window_id, 0);
3747 assert!(t.matches(&ghast_inventory::ClickResult::new(
3748 0,
3749 t.action,
3750 ghast_inventory::ClickOutcome::Accepted,
3751 )));
3752 }
3753
3754 #[test]
3757 fn planting_uses_the_seed_at_once() {
3758 use ghast_protocol::v1_8::play::clientbound as cb;
3759 for (soil, item, used) in [
3760 (60 << 4 | 7, 295, true),
3761 (1 << 4, 295, false),
3762 (60 << 4, 1, false),
3763 ] {
3764 let mut e = engine(GameVersion::V1_8_9);
3765 join(&mut e);
3766 let t0 = Instant::now();
3767 e.note_inbound(t0);
3768 let floor = ghast_protocol::BlockPos::new(8, 63, 8);
3769 let raw = RawPacket::from_packet(&cb::BlockChange {
3770 location: floor,
3771 r#type: soil,
3772 })
3773 .unwrap();
3774 e.sim.world_packet(&raw).unwrap();
3775 e.core
3776 .inv
3777 .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(item, 64, 0)));
3778 let mut done = false;
3779 let mut b = Script(|ctx: &mut TickContext<'_>| {
3780 ctx.set_aim(90.0, 89.5);
3781 if !done {
3782 done = ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5));
3783 }
3784 });
3785 let mut sent = None;
3786 for _ in 0..20 {
3787 e.tick(&mut b, t0);
3788 for o in e.outbound().drain(..) {
3789 if let Outbound::Place { held, .. } = o {
3790 sent = held.map(|h| h.count());
3791 }
3792 }
3793 }
3794 let _ = b;
3795 assert_eq!(sent, Some(64), "the packet carries the stack before use");
3796 let left = e.core.inv.held().map(|s| s.count());
3797 assert_eq!(
3798 left,
3799 Some(if used { 63 } else { 64 }),
3800 "soil {soil} item {item}"
3801 );
3802 }
3803 }
3804
3805 #[test]
3808 fn planned_look_is_the_next_look() {
3809 let mut e = engine(GameVersion::V1_8_9);
3810 join(&mut e);
3811 let t0 = Instant::now();
3812 e.note_inbound(t0);
3813 e.core
3814 .inv
3815 .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(1, 64, 0)));
3816 let floor = ghast_protocol::BlockPos::new(8, 63, 8);
3817 let mut n = 0;
3818 let mut placed = false;
3819 let mut plans: Vec<(f32, f32)> = Vec::new();
3820 let mut b = Script(|ctx: &mut TickContext<'_>| {
3821 n += 1;
3822 if n % 5 == 0 {
3823 } else if !placed {
3825 ctx.set_aim(90.0, 89.5);
3826 if ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)) {
3827 placed = true;
3828 ctx.set_aim(90.0, -60.0);
3829 }
3830 } else {
3831 ctx.set_aim(150.0, -60.0);
3832 }
3833 let p = ctx.planned_look();
3835 assert_eq!(p, ctx.planned_look());
3836 plans.push(p);
3837 });
3838 let mut looks = Vec::new();
3839 for _ in 0..40 {
3840 e.tick(&mut b, t0);
3841 e.outbound().clear();
3842 looks.push((e.core.pose.yaw, e.core.pose.pitch));
3843 }
3844 let _ = b;
3845 assert!(placed);
3846 assert_eq!(e.core.test_held_turns(), 1);
3847 assert_eq!(plans, looks);
3848 }
3849
3850 #[test]
3853 fn teleport_event_has_the_sent_pose_before() {
3854 for &v in GameVersion::ALL {
3855 let mut e = engine(v);
3856 join(&mut e);
3857 let t0 = Instant::now();
3858 e.note_inbound(t0);
3859 let mut seen = Vec::new();
3860 let mut b = Script(|ctx: &mut TickContext<'_>| {
3861 seen.extend(ctx.events().teleports.iter().copied());
3862 });
3863 e.tick(&mut b, t0);
3864 let sent = e.core.sent;
3865 let tp = Teleport {
3867 x: 10.5,
3868 y: 64.0,
3869 z: 8.5,
3870 yaw: 30.0,
3871 pitch: 0.0,
3872 flags: crate::common::teleport_flags::YAW,
3873 teleport_id: Some(9),
3874 relative: crate::common::teleport_flags::YAW as u32,
3875 ..Default::default()
3876 };
3877 e.handle(Inbound::Teleport(tp));
3878 e.tick(&mut b, t0);
3879 e.tick(&mut b, t0);
3880 let _ = b;
3881 assert_eq!(seen.len(), 2, "{v:?}");
3883 let ev = seen[1];
3884 assert_eq!(ev.teleport, tp);
3885 assert_eq!(ev.sent_before, sent);
3886 assert_eq!(ev.after.pos, Vec3::new(10.5, 64.0, 8.5));
3887 assert_eq!(ev.after.yaw, sent.yaw + 30.0, "{v:?}");
3888 }
3889 }
3890
3891 #[test]
3895 fn closed_window_frees_the_buttons() {
3896 for &v in GameVersion::ALL {
3897 let mut e = engine(v);
3898 join(&mut e);
3899 let t0 = Instant::now();
3900 e.note_inbound(t0);
3901 if v == GameVersion::V1_16_5 {
3902 use ghast_protocol::v1_16_5::play::clientbound as cb;
3904 let raw = RawPacket::from_packet(&cb::BlockChange {
3905 location: ghast_protocol::BlockPos::new(8, 63, 8),
3906 r#type: 1,
3907 })
3908 .unwrap();
3909 e.sim.world_packet(&raw).unwrap();
3910 }
3911 e.core.inv.on_open_window(
3912 5,
3913 Some(ghast_inventory::WindowKind::Chest { rows: 3 }),
3914 "Vault".into(),
3915 );
3916 e.handle(Inbound::OpenWindow(5));
3917 e.core
3920 .inv
3921 .on_set_slot(-1, -1, Some(ghast_inventory::Stack::new(1, 3, 0)));
3922 let mut n = 0;
3923 let mut closed_at = None;
3924 let mut b = Script(|ctx: &mut TickContext<'_>| {
3925 n += 1;
3926 ctx.set_aim(90.0, 89.5);
3927 ctx.set_buttons(Buttons {
3928 left: true,
3929 right: false,
3930 });
3931 if n == 15 {
3932 assert!(ctx.inventory().cursor().is_some());
3933 ctx.close_window().unwrap();
3934 assert_eq!(ctx.open_window(), None);
3935 let inv = ctx.inventory();
3936 assert!(!inv.gui_open() && inv.window().is_none() && inv.cursor().is_none());
3937 closed_at = Some(n);
3938 }
3939 });
3940 let mut first_dig = None;
3941 for i in 1..=30 {
3942 e.tick(&mut b, t0);
3943 let out = std::mem::take(e.outbound());
3944 if first_dig.is_none()
3945 && out.iter().any(|o| {
3946 matches!(
3947 o,
3948 Outbound::Dig {
3949 status: crate::common::DigStatus::Start,
3950 ..
3951 }
3952 )
3953 })
3954 {
3955 first_dig = Some(i);
3956 }
3957 }
3958 let _ = b;
3959 assert_eq!(closed_at, Some(15));
3960 let d = first_dig.unwrap_or_else(|| panic!("{v:?}: no dig after the close"));
3961 assert!(d >= 15, "{v:?}: dug at tick {d} with the window open");
3963 }
3964 }
3965
3966 #[test]
3968 fn swings_count_every_arm_swing() {
3969 let mut e = engine(GameVersion::V1_8_9);
3970 join(&mut e);
3971 let t0 = Instant::now();
3972 e.note_inbound(t0);
3973 let mut n = 0;
3974 let mut seen = Vec::new();
3975 let mut b = Script(|ctx: &mut TickContext<'_>| {
3976 n += 1;
3977 ctx.set_aim(90.0, 89.5);
3978 if n == 1 {
3979 ctx.swing();
3980 ctx.swing();
3981 }
3982 if n == 20 {
3983 ctx.set_buttons(Buttons {
3985 left: true,
3986 right: false,
3987 });
3988 }
3989 seen.push(ctx.swings());
3990 });
3991 let mut sent = 0u64;
3992 for _ in 0..30 {
3993 e.tick(&mut b, t0);
3994 sent += count_swings(&std::mem::take(e.outbound()));
3995 }
3996 let _ = b;
3997 assert_eq!(seen[0], 2, "this tick's own swings count at once");
3998 assert!(sent > 10, "the held button swings: {sent}");
3999 assert_eq!(*seen.last().unwrap() + 1, sent);
4001 assert_eq!(e.core.swings, sent);
4002 }
4003
4004 #[test]
4006 fn column_view_and_world_config() {
4007 for config in [
4008 None,
4009 Some(
4010 ghast_world::WorldConfig::default()
4011 .with_biomes(true)
4012 .with_light(true),
4013 ),
4014 ] {
4015 let sim = crate::sim::Sim18::with(&crate::sim::SimOptions {
4016 world: config,
4017 ..crate::sim::SimOptions::default()
4018 });
4019 let mut e = Engine::new(opts(GameVersion::V1_8_9), Box::new(sim) as Box<dyn Sim>);
4020 join(&mut e);
4021 let w: &dyn WorldView = &e.sim;
4022 let col = w.column(0, 0).expect("loaded");
4023 assert_eq!(u32::from(col.raw(8, 63, 8)), w.raw_block(8, 63, 8).unwrap());
4024 assert_eq!(col.raw(8, 63, 8), 1 << 4);
4025 assert!(w.column(5, 5).is_none());
4026 let light = col.sky_light(8, 63, 8);
4027 assert_eq!(light.is_some(), config.is_some(), "{config:?}");
4028 let biomes = !matches!(col.biomes(), ghast_world::Biomes::None);
4029 assert_eq!(biomes, config.is_some(), "{config:?}");
4030 }
4031 }
4032
4033 #[test]
4036 fn after_tick_sees_the_sent_pose() {
4037 struct Obs {
4038 n: u32,
4039 views: Vec<(u64, Pose, u64)>,
4040 }
4041 impl Behavior for Obs {
4042 fn tick(&mut self, ctx: &mut TickContext<'_>) {
4043 self.n += 1;
4044 ctx.set_aim(150.0, 10.0);
4045 ctx.set_controls(Controls {
4046 forward: true,
4047 ..Controls::default()
4048 });
4049 }
4050 fn running(&self) -> bool {
4051 self.n < 5
4052 }
4053 fn after_tick(&mut self, view: &TickView<'_>) {
4054 self.views.push((view.tick(), *view.sent(), view.swings()));
4055 assert!(view.world().is_column_loaded(0, 0));
4056 assert_eq!(view.version(), GameVersion::V1_8_9);
4057 }
4058 }
4059 let mut e = engine(GameVersion::V1_8_9);
4060 join(&mut e);
4061 let t0 = Instant::now();
4062 e.note_inbound(t0);
4063 let mut b = Obs {
4064 n: 0,
4065 views: Vec::new(),
4066 };
4067 let mut sent = Vec::new();
4068 for _ in 0..10 {
4069 e.tick(&mut b, t0);
4070 e.outbound().clear();
4071 sent.push(e.core.sent);
4072 }
4073 assert_eq!(b.n, 5);
4074 assert_eq!(b.views.len(), 10, "also after the behaviour finished");
4075 for (i, (_, p, _)) in b.views.iter().enumerate() {
4076 assert_eq!(*p, sent[i]);
4077 }
4078 assert_ne!(
4079 b.views[0].1.yaw, b.views[4].1.yaw,
4080 "the view follows the turn"
4081 );
4082 }
4083
4084 #[test]
4087 fn block_entities_follow_the_world_config() {
4088 use ghast_protocol::v1_8::play::clientbound as cb;
4089 for on in [false, true] {
4090 let sim = crate::sim::Sim18::with(&crate::sim::SimOptions {
4091 world: on.then(|| ghast_world::WorldConfig::default().with_block_entities(true)),
4092 ..crate::sim::SimOptions::default()
4093 });
4094 assert_eq!(sim.world_packet_ids().contains(&cb::id::UPDATE_SIGN), on);
4095 let mut e = Engine::new(opts(GameVersion::V1_8_9), Box::new(sim) as Box<dyn Sim>);
4096 join(&mut e);
4097 let raw = RawPacket::from_packet(&cb::UpdateSign {
4098 location: ghast_protocol::BlockPos::new(3, 64, 4),
4099 text1: "\"Hello\"".into(),
4100 text2: "\"\"".into(),
4101 text3: "\"\"".into(),
4102 text4: "\"\"".into(),
4103 })
4104 .unwrap();
4105 e.sim.world_packet(&raw).unwrap();
4106 let w: &dyn WorldView = &e.sim;
4107 let be = w.column(0, 0).unwrap().block_entity(3, 64, 4);
4108 assert_eq!(be.is_some(), on, "{be:?}");
4109 }
4110 }
4111}