Skip to main content

azalea/pathfinder/
simulation.rs

1//! Simulate the Minecraft world, currently only used for tests.
2
3use std::sync::Arc;
4
5use azalea_client::{
6    ClientMovementState, interact::BlockStatePredictionHandler, local_player::PreviousGameMode,
7    mining::MineBundle,
8};
9use azalea_core::{
10    entity_id::MinecraftEntityId, game_type::GameMode, position::Vec3, tick::GameTick,
11};
12use azalea_entity::{
13    Attributes, LookDirection, Physics, Position, dimensions::EntityDimensions,
14    inventory::Inventory,
15};
16use azalea_registry::builtin::EntityKind;
17use azalea_world::{ChunkStorage, PartialWorld, World, WorldName, Worlds};
18use bevy_app::App;
19use bevy_ecs::{prelude::*, schedule::SingleThreadedExecutor};
20use parking_lot::RwLock;
21use uuid::Uuid;
22
23#[derive(Bundle, Clone)]
24pub struct SimulatedPlayerBundle {
25    pub position: Position,
26    pub physics: Physics,
27    pub physics_state: ClientMovementState,
28    pub look_direction: LookDirection,
29    pub attributes: Attributes,
30    pub inventory: Inventory,
31}
32
33impl SimulatedPlayerBundle {
34    pub fn new(position: Vec3) -> Self {
35        let dimensions = EntityDimensions::from(EntityKind::Player);
36
37        SimulatedPlayerBundle {
38            position: Position::new(position),
39            physics: Physics::new(&dimensions, position),
40            physics_state: ClientMovementState::default(),
41            look_direction: LookDirection::default(),
42            attributes: Attributes::new(EntityKind::Player),
43            inventory: Inventory::default(),
44        }
45    }
46}
47
48fn simulation_world_name() -> WorldName {
49    WorldName::new("azalea:simulation")
50}
51
52fn create_simulation_world(chunks: ChunkStorage) -> (App, Arc<RwLock<World>>) {
53    let world_name = simulation_world_name();
54
55    let world = Arc::new(RwLock::new(World {
56        chunks,
57        ..Default::default()
58    }));
59
60    let mut app = App::new();
61    // we don't use all the default azalea plugins because we don't need all of
62    // them
63    app.add_plugins((
64        azalea_physics::PhysicsPlugin,
65        azalea_entity::EntityPlugin,
66        azalea_client::movement::MovementPlugin,
67        super::PathfinderPlugin,
68        crate::bot::BotPlugin,
69        azalea_client::task_pool::TaskPoolPlugin::default(),
70        // for mining
71        azalea_client::client_inventory::InventoryPlugin,
72        azalea_client::mining::MiningPlugin,
73        azalea_client::interact::InteractPlugin,
74        azalea_client::loading::PlayerLoadedPlugin,
75    ))
76    .insert_resource(Worlds {
77        map: [(world_name.clone(), Arc::downgrade(&world.clone()))]
78            .iter()
79            .cloned()
80            .collect(),
81    });
82
83    app.edit_schedule(bevy_app::Main, |schedule| {
84        schedule.set_executor(SingleThreadedExecutor::new());
85    });
86
87    app.finish();
88
89    (app, world)
90}
91
92fn create_simulation_player_complete_bundle(
93    world: Arc<RwLock<World>>,
94    player: &SimulatedPlayerBundle,
95) -> impl Bundle {
96    let world_name = simulation_world_name();
97
98    (
99        azalea_entity::LocalEntity,
100        azalea_entity::metadata::PlayerMetadataBundle::default(),
101        azalea_entity::EntityBundle::new(
102            Uuid::nil(),
103            MinecraftEntityId(0),
104            *player.position,
105            EntityKind::Player,
106            world_name,
107        ),
108        azalea_client::local_player::WorldHolder {
109            // the partial world is never actually used by the pathfinder, so we
110            // can leave it empty
111            partial: Arc::new(RwLock::new(PartialWorld::default())),
112            shared: world.clone(),
113        },
114        Inventory::default(),
115        GameMode::Survival,
116        PreviousGameMode(None),
117        MineBundle::default(),
118        BlockStatePredictionHandler::default(),
119        azalea_client::local_player::PermissionLevel::default(),
120        azalea_entity::PlayerAbilities::default(),
121    )
122}
123
124pub fn create_simulation_player(
125    ecs: &mut bevy_ecs::world::World,
126    world: Arc<RwLock<World>>,
127    player: SimulatedPlayerBundle,
128) -> Entity {
129    let mut entity = ecs.spawn(create_simulation_player_complete_bundle(world, &player));
130    entity.insert(player);
131    entity.id()
132}
133
134/// Simulate the Minecraft world to see if certain movements would be possible.
135pub struct Simulation {
136    pub app: App,
137    pub entity: Entity,
138    pub world: Arc<RwLock<World>>,
139}
140
141impl Simulation {
142    pub fn new(chunks: ChunkStorage, player: SimulatedPlayerBundle) -> Self {
143        let (mut app, world) = create_simulation_world(chunks);
144        let entity = create_simulation_player(app.world_mut(), world.clone(), player);
145        Self { app, entity, world }
146    }
147
148    /// Despawn the old simulated player and create a new one.
149    ///
150    /// This is cheaper than creating a new [`Simulation`] from scratch.
151    pub fn reset(&mut self, player: SimulatedPlayerBundle) {
152        self.app.world_mut().despawn(self.entity);
153        let entity = create_simulation_player(self.app.world_mut(), self.world.clone(), player);
154        self.entity = entity;
155    }
156
157    pub fn tick(&mut self) {
158        self.run_update_schedule();
159        self.run_gametick_schedule();
160    }
161
162    pub fn run_update_schedule(&mut self) {
163        self.app.update();
164    }
165    pub fn run_gametick_schedule(&mut self) {
166        self.app.world_mut().run_schedule(GameTick);
167    }
168
169    pub fn component<T: Component + Clone>(&self) -> T {
170        self.app.world().get::<T>(self.entity).unwrap().clone()
171    }
172    pub fn get_component<T: Component + Clone>(&self) -> Option<T> {
173        self.app.world().get::<T>(self.entity).cloned()
174    }
175    pub fn position(&self) -> Vec3 {
176        *self.component::<Position>()
177    }
178    pub fn physics(&self) -> Physics {
179        self.component::<Physics>().clone()
180    }
181    pub fn is_mining(&self) -> bool {
182        // return true if the component is present and Some
183        self.get_component::<azalea_client::mining::MineBlockPos>()
184            .and_then(|c| *c)
185            .is_some()
186    }
187}
188
189/// A set of simulations, useful for efficiently doing multiple simulations.
190pub struct SimulationSet {
191    pub app: App,
192    world: Arc<RwLock<World>>,
193}
194impl SimulationSet {
195    pub fn new(chunks: ChunkStorage) -> Self {
196        let (app, world) = create_simulation_world(chunks);
197        Self { app, world }
198    }
199    pub fn tick(&mut self) {
200        self.app.update();
201        self.app.world_mut().run_schedule(GameTick);
202    }
203
204    pub fn spawn(&mut self, player: SimulatedPlayerBundle) -> Entity {
205        create_simulation_player(self.app.world_mut(), self.world.clone(), player)
206    }
207    pub fn despawn(&mut self, entity: Entity) {
208        self.app.world_mut().despawn(entity);
209    }
210
211    pub fn position(&self, entity: Entity) -> Vec3 {
212        **self.app.world().get::<Position>(entity).unwrap()
213    }
214}