1mod components;
2pub mod effect_events;
3pub mod indexing;
4
5use std::collections::HashSet;
6
7use azalea_block::{BlockState, fluid_state::FluidKind, properties};
8use azalea_core::{
9 entity_id::MinecraftEntityId,
10 game_type::GameMode,
11 position::{BlockPos, ChunkPos},
12 tick::GameTick,
13};
14use azalea_registry::{builtin::BlockKind, tags};
15use azalea_world::{ChunkStorage, WorldName, Worlds};
16use bevy_app::{App, Plugin, PostUpdate, Update};
17use bevy_ecs::prelude::*;
18pub use components::*;
19use derive_more::{Deref, DerefMut};
20use indexing::EntityUuidIndex;
21use tracing::debug;
22
23use crate::{
24 FluidOnEyes, LookDirection, Physics, Pose, Position,
25 dimensions::{EntityDimensions, calculate_dimensions},
26 metadata::{self, Health, Player},
27 plugin::effect_events::{handle_add_effect, handle_remove_effects},
28};
29
30#[derive(Clone, Debug, Eq, Hash, PartialEq, SystemSet)]
32pub enum EntityUpdateSystems {
33 Index,
35 Deindex,
37}
38
39pub struct EntityPlugin;
41impl Plugin for EntityPlugin {
42 fn build(&self, app: &mut App) {
43 app.add_systems(
48 PostUpdate,
49 indexing::remove_despawned_entities_from_indexes.in_set(EntityUpdateSystems::Deindex),
50 )
51 .add_systems(
52 Update,
53 (
54 (
55 indexing::update_entity_chunk_positions,
56 indexing::insert_entity_chunk_position,
57 )
58 .chain()
59 .in_set(EntityUpdateSystems::Index),
60 (
61 debug_new_entity,
62 add_dead,
63 clamp_look_direction,
64 update_on_climbable,
65 (update_dimensions, update_bounding_box).chain(),
66 update_crouching,
67 ),
68 ),
69 )
70 .add_systems(GameTick, (update_in_loaded_chunk, update_fluid_on_eyes))
71 .add_observer(handle_add_effect)
72 .add_observer(handle_remove_effects)
73 .init_resource::<EntityUuidIndex>();
74 }
75}
76
77fn debug_new_entity(query: Query<(Entity, Option<&LocalEntity>), Added<MinecraftEntityId>>) {
78 for (entity, local) in query.iter() {
79 if local.is_some() {
80 debug!("new local entity: {:?}", entity);
81 } else {
82 debug!("new entity: {:?}", entity);
83 }
84 }
85}
86
87pub fn add_dead(mut commands: Commands, query: Query<(Entity, &Health), Changed<Health>>) {
94 for (entity, health) in query.iter() {
95 if **health <= 0.0 {
96 commands.entity(entity).insert(Dead);
97 }
98 }
99}
100
101pub fn update_fluid_on_eyes(
102 mut query: Query<
103 (&mut FluidOnEyes, &Position, &EntityDimensions, &WorldName),
104 With<metadata::AbstractLiving>,
105 >,
106 worlds: Res<Worlds>,
107) {
108 query
109 .par_iter_mut()
110 .for_each(|(mut fluid_on_eyes, position, dimensions, world_name)| {
111 let Some(world) = worlds.get(world_name) else {
112 return;
113 };
114
115 let adjusted_eye_y = position.y + (dimensions.eye_height as f64) - 0.1111111119389534;
116 let eye_block_pos = BlockPos::from(position.with_y(adjusted_eye_y));
117 let fluid_at_eye = world
118 .read()
119 .get_fluid_state(eye_block_pos)
120 .unwrap_or_default();
121 let fluid_cutoff_y = (eye_block_pos.y as f32 + fluid_at_eye.height()) as f64;
122 if fluid_cutoff_y > adjusted_eye_y {
123 **fluid_on_eyes = fluid_at_eye.kind;
124 } else {
125 **fluid_on_eyes = FluidKind::Empty;
126 }
127 });
128}
129
130pub fn update_on_climbable(
131 mut query: Query<(&mut OnClimbable, &Position, &WorldName, &GameMode), With<LocalEntity>>,
132 worlds: Res<Worlds>,
133) {
134 for (mut on_climbable, position, world_name, &game_mode) in query.iter_mut() {
135 if game_mode == GameMode::Spectator {
136 continue;
137 }
138
139 let Some(world) = worlds.get(world_name) else {
140 continue;
141 };
142
143 let world = world.read();
144
145 let block_pos = BlockPos::from(position);
146 let block_at_feet = world.get_block_state(block_pos).unwrap_or_default();
147 let registry_block_at_feet = block_at_feet.as_block_kind();
148
149 **on_climbable = tags::blocks::CLIMBABLE.contains(®istry_block_at_feet)
150 || (tags::blocks::TRAPDOORS.contains(®istry_block_at_feet)
151 && is_trapdoor_usable_as_ladder(block_at_feet, block_pos, &world));
152 }
153}
154
155fn is_trapdoor_usable_as_ladder(
156 block_state: BlockState,
157 block_pos: BlockPos,
158 world: &azalea_world::World,
159) -> bool {
160 if !block_state
162 .property::<properties::Open>()
163 .unwrap_or_default()
164 {
165 return false;
166 }
167
168 let block_below = world.get_block_state(block_pos.down(1)).unwrap_or_default();
170 let registry_block_below = block_below.as_block_kind();
171 if registry_block_below != BlockKind::Ladder {
172 return false;
173 }
174 let ladder_facing = block_below
176 .property::<properties::FacingCardinal>()
177 .expect("ladder block must have facing property");
178 let trapdoor_facing = block_state
179 .property::<properties::FacingCardinal>()
180 .expect("trapdoor block must have facing property");
181 if ladder_facing != trapdoor_facing {
182 return false;
183 }
184
185 true
186}
187
188#[derive(Clone, Component, Deref, DerefMut)]
193pub struct LoadedBy(pub HashSet<Entity>);
194
195pub fn clamp_look_direction(mut query: Query<&mut LookDirection>) {
196 for mut look_direction in &mut query {
197 *look_direction = look_direction.clamped();
198 }
199}
200
201#[allow(clippy::type_complexity)]
210pub fn update_bounding_box(
211 mut query: Query<
212 (&mut Physics, &Position, &EntityDimensions),
213 Or<(Changed<Position>, Changed<EntityDimensions>)>,
214 >,
215) {
216 for (mut physics, position, dimensions) in query.iter_mut() {
217 let bounding_box = dimensions.make_bounding_box(**position);
218 physics.bounding_box = bounding_box;
219 }
220}
221
222#[allow(clippy::type_complexity)]
223pub fn update_dimensions(
224 mut query: Query<
225 (&mut EntityDimensions, &EntityKindComponent, &Pose),
226 Or<(Changed<EntityKindComponent>, Changed<Pose>)>,
227 >,
228) {
229 for (mut dimensions, kind, pose) in query.iter_mut() {
230 *dimensions = calculate_dimensions(**kind, *pose);
231 }
232}
233
234#[allow(clippy::type_complexity)]
235pub fn update_crouching(
236 query: Query<(&mut Crouching, &Pose), (Without<LocalEntity>, With<Player>)>,
237) {
238 for (mut crouching, pose) in query {
239 let new_crouching = *pose == Pose::Crouching;
240 if **crouching != new_crouching {
242 **crouching = new_crouching;
243 }
244 }
245}
246
247#[derive(Clone, Component, Copy, Debug)]
253pub struct InLoadedChunk;
254
255pub fn update_in_loaded_chunk(
257 mut commands: bevy_ecs::system::Commands,
258 query: Query<(Entity, &WorldName, &Position, Option<&InLoadedChunk>)>,
259 worlds: Res<Worlds>,
260) {
261 for (entity, world_name, position, last_in_loaded_chunk) in &query {
262 let player_chunk_pos = ChunkPos::from(position);
263 let Some(world_lock) = worlds.get(world_name) else {
264 commands.entity(entity).remove::<InLoadedChunk>();
265 continue;
266 };
267
268 let in_loaded_chunk = world_lock.read().chunks.get(&player_chunk_pos).is_some();
269 if in_loaded_chunk {
270 if last_in_loaded_chunk.is_none() {
271 commands.entity(entity).insert(InLoadedChunk);
272 }
273 } else {
274 if last_in_loaded_chunk.is_some() {
275 commands.entity(entity).remove::<InLoadedChunk>();
276 }
277 }
278 }
279}
280
281pub fn on_pos_legacy(chunk_storage: &ChunkStorage, position: Position) -> BlockPos {
283 on_pos(0.2, chunk_storage, position)
284}
285
286pub fn on_pos(offset: f32, chunk_storage: &ChunkStorage, pos: Position) -> BlockPos {
299 let x = pos.x.floor() as i32;
300 let y = (pos.y - offset as f64).floor() as i32;
301 let z = pos.z.floor() as i32;
302 let pos = BlockPos { x, y, z };
303
304 let block_pos = pos.down(1);
306 let block_state = chunk_storage.get_block_state(block_pos);
307 if block_state == Some(BlockState::AIR) {
308 let block_pos_below = block_pos.down(1);
309 let block_state_below = chunk_storage.get_block_state(block_pos_below);
310 if let Some(_block_state_below) = block_state_below {
311 }
318 }
319
320 pos
321}
322
323#[cfg(test)]
324mod tests {
325 use azalea_block::{
326 blocks::{Ladder, OakTrapdoor},
327 properties::{FacingCardinal, TopBottom},
328 };
329 use azalea_core::position::{BlockPos, ChunkPos};
330 use azalea_registry::builtin::BlockKind;
331 use azalea_world::{Chunk, ChunkStorage, PartialWorld, World};
332
333 use super::is_trapdoor_usable_as_ladder;
334
335 #[test]
336 fn test_is_trapdoor_useable_as_ladder() {
337 let mut partial_world = PartialWorld::default();
338 let mut chunks = ChunkStorage::default();
339 partial_world.chunks.set(
340 &ChunkPos { x: 0, z: 0 },
341 Some(Chunk::default()),
342 &mut chunks,
343 );
344 partial_world.chunks.set_block_state(
345 BlockPos::new(0, 0, 0),
346 BlockKind::Stone.into(),
347 &chunks,
348 );
349
350 let ladder = Ladder {
351 facing: FacingCardinal::East,
352 waterlogged: false,
353 };
354 partial_world
355 .chunks
356 .set_block_state(BlockPos::new(0, 0, 0), ladder.into(), &chunks);
357
358 let trapdoor = OakTrapdoor {
359 facing: FacingCardinal::East,
360 half: TopBottom::Bottom,
361 open: true,
362 powered: false,
363 waterlogged: false,
364 };
365 partial_world
366 .chunks
367 .set_block_state(BlockPos::new(0, 1, 0), trapdoor.into(), &chunks);
368
369 let world = World::from(chunks);
370 let trapdoor_matches_ladder = is_trapdoor_usable_as_ladder(
371 world
372 .get_block_state(BlockPos::new(0, 1, 0))
373 .unwrap_or_default(),
374 BlockPos::new(0, 1, 0),
375 &world,
376 );
377
378 assert!(trapdoor_matches_ladder);
379 }
380}