aboutsummaryrefslogtreecommitdiff
path: root/azalea/src/pathfinder/mod.rs
blob: 8a9d7540e77a9cd7ca42ab903ba410e3b9e43f9c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
mod moves;
mod mtdstarlite;

use crate::{prelude::*, SprintDirection, WalkDirection};
use crate::{Client, Event};
use async_trait::async_trait;
use azalea_core::{BlockPos, CardinalDirection};
use azalea_world::entity::EntityData;
use log::debug;
use mtdstarlite::Edge;
pub use mtdstarlite::MTDStarLite;
use parking_lot::Mutex;
use std::collections::VecDeque;
use std::sync::Arc;

#[derive(Clone, Default)]
pub struct Plugin;
impl crate::Plugin for Plugin {
    type State = State;

    fn build(&self) -> State {
        State::default()
    }
}

#[derive(Default, Clone)]
pub struct State {
    // pathfinder: Option<MTDStarLite<Node, f32>>,
    pub path: Arc<Mutex<VecDeque<Node>>>,
}

#[async_trait]
impl crate::PluginState for State {
    async fn handle(self: Box<Self>, event: Event, mut bot: Client) {
        if let Event::Tick = event {
            let mut path = self.path.lock();

            if !path.is_empty() {
                tick_execute_path(&mut bot, &mut path);
            }
        }
    }
}

pub trait Trait {
    fn goto(&self, goal: impl Goal);
}

impl Trait for azalea_client::Client {
    fn goto(&self, goal: impl Goal) {
        let start = Node {
            pos: BlockPos::from(self.entity().pos()),
            vertical_vel: VerticalVel::None,
        };
        let end = goal.goal_node();
        debug!("start: {start:?}, end: {end:?}");

        let possible_moves: Vec<&dyn moves::Move> = vec![
            &moves::ForwardMove(CardinalDirection::North),
            &moves::ForwardMove(CardinalDirection::East),
            &moves::ForwardMove(CardinalDirection::South),
            &moves::ForwardMove(CardinalDirection::West),
            //
            &moves::AscendMove(CardinalDirection::North),
            &moves::AscendMove(CardinalDirection::East),
            &moves::AscendMove(CardinalDirection::South),
            &moves::AscendMove(CardinalDirection::West),
            //
            &moves::DescendMove(CardinalDirection::North),
            &moves::DescendMove(CardinalDirection::East),
            &moves::DescendMove(CardinalDirection::South),
            &moves::DescendMove(CardinalDirection::West),
            //
            &moves::DiagonalMove(CardinalDirection::North),
            &moves::DiagonalMove(CardinalDirection::East),
            &moves::DiagonalMove(CardinalDirection::South),
            &moves::DiagonalMove(CardinalDirection::West),
        ];

        let successors = |node: &Node| {
            let mut edges = Vec::new();

            let world = self.world.read();
            for possible_move in possible_moves.iter() {
                edges.push(Edge {
                    target: possible_move.next_node(node),
                    cost: possible_move.cost(&world, node),
                });
            }
            edges
        };

        let mut pf = MTDStarLite::new(
            start,
            end,
            |n| goal.heuristic(n),
            successors,
            successors,
            |n| goal.success(n),
        );

        let start = std::time::Instant::now();
        let p = pf.find_path();
        let end = std::time::Instant::now();
        debug!("path: {p:?}");
        debug!("time: {:?}", end - start);

        let state = self
            .plugins
            .get::<State>()
            .expect("Pathfinder plugin not installed!")
            .clone();
        // convert the Option<Vec<Node>> to a VecDeque<Node>
        *state.path.lock() = p.expect("no path").into_iter().collect();
    }
}

fn tick_execute_path(bot: &mut Client, path: &mut VecDeque<Node>) {
    let target = if let Some(target) = path.front() {
        target
    } else {
        return;
    };
    let center = target.pos.center();
    // println!("going to {center:?} (at {pos:?})", pos = bot.entity().pos());
    bot.look_at(&center);
    bot.sprint(SprintDirection::Forward);
    // check if we should jump
    if target.pos.y > bot.entity().pos().y.floor() as i32 {
        bot.jump();
    }

    if target.is_reached(&bot.entity()) {
        // println!("ok target {target:?} reached");
        path.pop_front();
        if path.is_empty() {
            bot.walk(WalkDirection::None);
        }
        // tick again, maybe we already reached the next node!
        tick_execute_path(bot, path);
    }
}

/// Information about our vertical velocity
#[derive(Eq, PartialEq, Hash, Clone, Copy, Debug)]
pub enum VerticalVel {
    None,
    /// No vertical velocity, but we're not on the ground
    NoneMidair,
    // less than 3 blocks (no fall damage)
    FallingLittle,
}

#[derive(Eq, PartialEq, Hash, Clone, Copy, Debug)]
pub struct Node {
    pub pos: BlockPos,
    pub vertical_vel: VerticalVel,
}

pub trait Goal {
    fn heuristic(&self, n: &Node) -> f32;
    fn success(&self, n: &Node) -> bool;
    // TODO: this should be removed and mtdstarlite should stop depending on
    // being given a goal node
    fn goal_node(&self) -> Node;
}

impl Node {
    /// Returns whether the entity is at the node and should start going to the
    /// next node.
    pub fn is_reached(&self, entity: &EntityData) -> bool {
        // println!(
        //     "entity.delta.y: {} {:?}=={:?}, self.vertical_vel={:?}",
        //     entity.delta.y,
        //     BlockPos::from(entity.pos()),
        //     self.pos,
        //     self.vertical_vel
        // );
        BlockPos::from(entity.pos()) == self.pos
            && match self.vertical_vel {
                VerticalVel::NoneMidair => entity.delta.y > -0.1 && entity.delta.y < 0.1,
                VerticalVel::None => entity.on_ground,
                VerticalVel::FallingLittle => entity.delta.y < -0.1,
            }
    }
}

pub struct BlockPosGoal {
    pub pos: BlockPos,
}
impl Goal for BlockPosGoal {
    fn heuristic(&self, n: &Node) -> f32 {
        let dx = (self.pos.x - n.pos.x) as f32;
        let dy = (self.pos.y - n.pos.y) as f32;
        let dz = (self.pos.z - n.pos.z) as f32;
        dx * dx + dy * dy + dz * dz
    }
    fn success(&self, n: &Node) -> bool {
        n.pos == self.pos
    }
    fn goal_node(&self) -> Node {
        Node {
            pos: self.pos,
            vertical_vel: VerticalVel::None,
        }
    }
}

impl From<BlockPos> for BlockPosGoal {
    fn from(pos: BlockPos) -> Self {
        Self { pos }
    }
}