ghast_client/engine/behavior.rs
1//! The behaviour contract: the [`Behavior`] trait (with its boxed form), the do-nothing
2//! [`Idle`] behaviour, and a click's ticket and refusal ([`ClickTicket`], [`ClickRefused`]).
3
4use super::*;
5
6/// A bot behaviour: the code that decides what the player does each tick.
7///
8/// Behaviours never see packets or versions: they read a [`TickContext`] and call its
9/// actions. A panic in a behaviour stops that behaviour (its [`Behavior::stop`] is called with
10/// `"panic"`) but not the connection: the player keeps standing and answering the server.
11pub trait Behavior {
12 /// Name for logs.
13 fn name(&self) -> &str {
14 "behavior"
15 }
16
17 /// Optional packet groups this behaviour needs. Read every tick; a change updates the
18 /// packet filter. Everything not asked for is dropped before it is decoded.
19 fn interests(&self) -> Interests {
20 Interests::NONE
21 }
22
23 /// Extra clientbound play packet ids (of `version`) to copy undecoded into
24 /// [`TickEvents::raw`], including packets the core consumes itself (the core's handling
25 /// does not change). Read every tick like [`Behavior::interests`]; a change updates the
26 /// packet filter. Decoding is the behaviour's job (`ghast::protocol::v1_8::play::clientbound`
27 /// / `v1_16_5`). A behaviour made of modules returns the union of their lists
28 /// (`Cow::Owned([a.ids(version), b.ids(version)].concat())`; duplicates are harmless).
29 /// Most needs have typed events now: [`TickEvents::effects`], [`TickEvents::hurt`],
30 /// [`TickEvents::deaths`], [`TickEvents::item_use`], [`TickEvents::entities`],
31 /// [`TickContext::spawn_position`].
32 fn raw_packets(&self, version: GameVersion) -> std::borrow::Cow<'static, [i32]> {
33 let _ = version;
34 std::borrow::Cow::Borrowed(&[])
35 }
36
37 /// Called on the first tick the player is in the world, before that tick's
38 /// [`Behavior::tick`] (both see the same events).
39 fn start(&mut self, ctx: &mut TickContext<'_>) {
40 let _ = ctx;
41 }
42
43 /// Called every tick while the player is in the world and the server is answering.
44 fn tick(&mut self, ctx: &mut TickContext<'_>);
45
46 /// Whether the behaviour still wants ticks. Once it returns `false` the behaviour is done:
47 /// it is not ticked again (the player keeps standing and answering the server) and
48 /// [`Behavior::stop`] still runs when the session ends. Read after every start / tick.
49 fn running(&self) -> bool {
50 true
51 }
52
53 /// Called after every tick's movement step (also while the behaviour is on hold or has
54 /// finished), with a read-only view of what the server now has: the pose sent this tick,
55 /// the world, entities and inventory. For observers (a viewer, a recorder); it cannot act.
56 /// Default: nothing.
57 ///
58 /// ```
59 /// use ghast_client::{Behavior, TickContext, TickView};
60 ///
61 /// /// Logs where the server has the player, once a second.
62 /// struct Tracker;
63 ///
64 /// impl Behavior for Tracker {
65 /// fn tick(&mut self, _ctx: &mut TickContext<'_>) {}
66 ///
67 /// fn after_tick(&mut self, view: &TickView<'_>) {
68 /// if view.tick() % 20 == 0 {
69 /// let p = view.sent();
70 /// println!("{} {:?} in {}", view.tick(), p.pos, view.dimension());
71 /// }
72 /// }
73 /// }
74 /// ```
75 fn after_tick(&mut self, view: &TickView<'_>) {
76 let _ = view;
77 }
78
79 /// Called once when the session ends (or the behaviour panicked).
80 fn stop(&mut self, reason: &str) {
81 let _ = reason;
82 }
83
84 /// 26.1+: a dialog the server shows during the configuration state, before the player is in
85 /// the world (behaviours do not tick there). Called only with [`Interests::DIALOGS`]; the
86 /// client sends the returned answer at once, as vanilla would for that button (see
87 /// [`crate::dialog`]); `None` leaves the dialog open. A dialog the answer opens is offered
88 /// next. Play-state dialogs come through [`TickContext::dialog`] instead. Default: `None`.
89 fn configuration_dialog(
90 &mut self,
91 dialog: &crate::dialog::Dialog,
92 ) -> Option<crate::dialog::DialogAnswer> {
93 let _ = dialog;
94 None
95 }
96}
97
98/// A boxed behaviour is a behaviour (a runner can pick one from its config at run time).
99impl<B: Behavior + ?Sized> Behavior for Box<B> {
100 fn name(&self) -> &str {
101 (**self).name()
102 }
103 fn interests(&self) -> Interests {
104 (**self).interests()
105 }
106 fn raw_packets(&self, version: GameVersion) -> std::borrow::Cow<'static, [i32]> {
107 (**self).raw_packets(version)
108 }
109 fn start(&mut self, ctx: &mut TickContext<'_>) {
110 (**self).start(ctx);
111 }
112 fn tick(&mut self, ctx: &mut TickContext<'_>) {
113 (**self).tick(ctx);
114 }
115 fn running(&self) -> bool {
116 (**self).running()
117 }
118 fn after_tick(&mut self, view: &TickView<'_>) {
119 (**self).after_tick(view);
120 }
121 fn stop(&mut self, reason: &str) {
122 (**self).stop(reason);
123 }
124 fn configuration_dialog(
125 &mut self,
126 dialog: &crate::dialog::Dialog,
127 ) -> Option<crate::dialog::DialogAnswer> {
128 (**self).configuration_dialog(dialog)
129 }
130}
131
132/// Why [`TickContext::click`] (or opening / closing a window) sent nothing.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134#[non_exhaustive]
135pub enum ClickRefused {
136 /// The player is turning: click only while still.
137 Turning,
138 /// The inventory refused it.
139 Inventory(ghast_inventory::ClickError),
140 /// The player is dead (vanilla's death screen takes the input until the respawn).
141 Dead,
142}
143
144impl std::fmt::Display for ClickRefused {
145 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146 match self {
147 ClickRefused::Turning => f.write_str("the player is turning"),
148 ClickRefused::Inventory(e) => write!(f, "{e}"),
149 ClickRefused::Dead => f.write_str("the player is dead"),
150 }
151 }
152}
153
154impl std::error::Error for ClickRefused {}
155
156/// A click that was sent: match it with [`TickEvents::inventory`]'s `clicks` on a later tick
157/// (window id and action number, as the server's confirm carries them).
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
159pub struct ClickTicket {
160 /// Window id the click was sent for; -1 when no [`ghast_inventory::ClickResult`] will
161 /// follow (the 26.x creative inventory screen, whose packets the server applies as sent).
162 pub window_id: i32,
163 /// Its action number.
164 pub action: i16,
165}
166
167impl ClickTicket {
168 /// Whether `r` is the result of this click.
169 #[must_use]
170 pub fn matches(&self, r: &ghast_inventory::ClickResult) -> bool {
171 r.window_id == self.window_id && r.action == self.action
172 }
173}
174
175/// A behaviour that does nothing (the player stands still).
176#[derive(Debug, Clone, Copy, Default)]
177pub struct Idle;
178
179impl Behavior for Idle {
180 fn name(&self) -> &str {
181 "idle"
182 }
183
184 fn tick(&mut self, _ctx: &mut TickContext<'_>) {}
185}