Skip to main content

ghast_viewer/
watch.rs

1//! The behaviour wrapper that feeds a viewer from the bot's tick.
2
3use std::borrow::Cow;
4
5use ghast_client::{
6    Behavior, GameVersion, Health, Interests, Pose, RawInbound, TickContext, TickView,
7};
8use ghast_entity::Entities;
9use ghast_inventory::Stack;
10use ghast_protocol::BlockPos;
11
12use crate::Viewer;
13use crate::feed::{BotView, RAW_ALWAYS_1_8, RAW_WATCHED_1_8};
14
15/// A behaviour that also feeds a [`Viewer`]. It only reads the tick context: it never writes to
16/// the connection and does not change the bot's timing. While nobody watches it adds a handful
17/// of rare packets to the filter (weather, experience, block entities) and does nothing else.
18///
19/// Side effects on the wrapped behaviour: while a page is open, `TickEvents::block_updates` and
20/// `TickEvents::raw` may hold entries it did not ask for (filter `raw` by packet id), and with
21/// [`crate::ViewerConfig::entities`] on, entity tracking (and the tab list) is enabled for the
22/// session. A wrapped behaviour that finishes stops being ticked, but the viewer keeps showing
23/// the bot standing there.
24///
25/// The viewer reads the bot in [`Behavior::after_tick`] (the pose after the movement step). For
26/// light, biomes and block entities (sign text, skulls …) the client must keep them: build it
27/// with `Client::world_config(ghast_viewer::world_config())`.
28pub struct Watched<B> {
29    inner: B,
30    viewer: Viewer,
31    inner_done: bool,
32}
33
34impl<B> Watched<B> {
35    pub(crate) fn new(inner: B, viewer: Viewer) -> Self {
36        Watched {
37            inner,
38            viewer,
39            inner_done: false,
40        }
41    }
42
43    /// The wrapped behaviour.
44    pub fn inner(&self) -> &B {
45        &self.inner
46    }
47
48    /// The wrapped behaviour.
49    pub fn inner_mut(&mut self) -> &mut B {
50        &mut self.inner
51    }
52
53    /// Unwraps.
54    pub fn into_inner(self) -> B {
55        self.inner
56    }
57}
58
59impl<B: Behavior> Behavior for Watched<B> {
60    fn name(&self) -> &str {
61        self.inner.name()
62    }
63
64    fn interests(&self) -> Interests {
65        let mut i = if self.inner_done {
66            Interests::NONE
67        } else {
68            self.inner.interests()
69        };
70        let watched = self.viewer.hub().active();
71        match self.viewer.config().entities {
72            crate::EntityTracking::Always => {
73                i |= Interests::ENTITIES | Interests::PLAYER_LIST | Interests::PLAYER_SKINS;
74            }
75            crate::EntityTracking::WhileWatched if watched => {
76                i |= Interests::ENTITIES | Interests::PLAYER_LIST | Interests::PLAYER_SKINS;
77            }
78            _ => {}
79        }
80        if self.viewer.hub().active() {
81            i |= Interests::BLOCK_UPDATES;
82        }
83        i
84    }
85
86    fn raw_packets(&self, version: GameVersion) -> Cow<'static, [i32]> {
87        let inner = if self.inner_done {
88            Cow::Borrowed(&[][..])
89        } else {
90            self.inner.raw_packets(version)
91        };
92        if version != GameVersion::V1_8_9 {
93            return inner;
94        }
95        let ours = if self.viewer.hub().active() {
96            RAW_WATCHED_1_8
97        } else {
98            RAW_ALWAYS_1_8
99        };
100        if inner.is_empty() {
101            return Cow::Borrowed(ours);
102        }
103        let mut all: Vec<i32> = inner.into_owned();
104        all.extend_from_slice(ours);
105        all.sort_unstable();
106        all.dedup();
107        Cow::Owned(all)
108    }
109
110    fn start(&mut self, ctx: &mut TickContext<'_>) {
111        self.inner.start(ctx);
112        self.inner_done = !self.inner.running();
113    }
114
115    fn tick(&mut self, ctx: &mut TickContext<'_>) {
116        if !self.inner_done {
117            self.inner.tick(ctx);
118            self.inner_done = !self.inner.running();
119        }
120    }
121
122    fn after_tick(&mut self, view: &TickView<'_>) {
123        // the engine calls this also once the inner behaviour has finished, like for any behaviour
124        self.inner.after_tick(view);
125        self.viewer.hub().tick(&View(view));
126    }
127
128    fn running(&self) -> bool {
129        // a finished behaviour is not ticked any more, but the viewer keeps its packets
130        true
131    }
132
133    fn stop(&mut self, reason: &str) {
134        self.inner.stop(reason);
135        self.viewer
136            .hub()
137            .session_ended(&format!("The bot left the game ({reason})"));
138    }
139}
140
141/// [`BotView`] over ghast's after-tick view (the pose after this tick's movement step).
142struct View<'a, 'b>(&'a TickView<'b>);
143
144impl BotView for View<'_, '_> {
145    fn tick(&self) -> u64 {
146        self.0.tick()
147    }
148    fn version(&self) -> GameVersion {
149        self.0.version()
150    }
151    fn pose(&self) -> Pose {
152        *self.0.pose()
153    }
154    fn entity_id(&self) -> i32 {
155        self.0.entity_id()
156    }
157    fn health(&self) -> Health {
158        self.0.health()
159    }
160    fn held_slot(&self) -> u8 {
161        self.0.held_slot()
162    }
163    fn hotbar(&self, k: usize) -> Option<&Stack> {
164        self.0.inventory().hotbar(k)
165    }
166    fn armor(&self, a: usize) -> Option<&Stack> {
167        self.0.inventory().armor(a)
168    }
169    fn mining(&self) -> Option<(BlockPos, f32)> {
170        self.0.mining()
171    }
172    fn broken(&self) -> u64 {
173        self.0.broken()
174    }
175    fn swings(&self) -> Option<u64> {
176        Some(self.0.swings())
177    }
178    fn using_item(&self) -> bool {
179        self.0.using_item()
180    }
181    fn dimension(&self) -> &str {
182        self.0.dimension()
183    }
184    fn is_column_loaded(&self, cx: i32, cz: i32) -> bool {
185        self.0.world().is_column_loaded(cx, cz)
186    }
187    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
188        self.0.world().raw_block(x, y, z)
189    }
190    fn column(&self, cx: i32, cz: i32) -> Option<&ghast_world::Column> {
191        self.0.world().column(cx, cz)
192    }
193    fn entities(&self) -> Option<&Entities> {
194        self.0.entities()
195    }
196    fn block_updates(&self) -> &[(BlockPos, u32)] {
197        &self.0.events().block_updates
198    }
199    fn raw(&self) -> &[RawInbound] {
200        &self.0.events().raw
201    }
202    fn joined(&self) -> bool {
203        self.0.events().joined
204    }
205    fn respawned(&self) -> bool {
206        self.0.events().respawned
207    }
208    fn build_height(&self) -> Option<(i32, i32)> {
209        self.0.world().build_height()
210    }
211    #[cfg(any(feature = "v26_1", feature = "v26_2"))]
212    fn enchantment_name(&self, id: i32) -> Option<&str> {
213        self.0.inventory().enchantment_name_modern(id)
214    }
215}