1use azalea_core::{
2 entity_id::MinecraftEntityId,
3 game_type::GameMode,
4 position::{Vec2, Vec3},
5 tick::GameTick,
6};
7use azalea_entity::{
8 ActiveEffects, Attributes, Crouching, EntityGeometryUpdateSystems, HasClientLoaded, Jumping,
9 LastSentPosition, LocalEntity, LookDirection, OnClimbable, Physics, PlayerAbilities, Pose,
10 Position,
11 dimensions::calculate_dimensions,
12 inventory::Inventory,
13 metadata::{self, FallFlying, Sprinting},
14 update_bounding_box,
15};
16use azalea_physics::{
17 PhysicsSystems, ai_step,
18 client_movement::{ClientMovementState, SprintDirection, WalkDirection},
19 collision::entity_collisions::{AabbQuery, CollidableEntityQuery, update_last_bounding_box},
20 travel::{no_collision, travel},
21};
22use azalea_protocol::{
23 common::movements::MoveFlags,
24 packets::{
25 Packet,
26 game::{
27 ServerboundPlayerCommand, ServerboundPlayerInput,
28 s_move_player_pos::ServerboundMovePlayerPos,
29 s_move_player_pos_rot::ServerboundMovePlayerPosRot,
30 s_move_player_rot::ServerboundMovePlayerRot,
31 s_move_player_status_only::ServerboundMovePlayerStatusOnly, s_player_command,
32 },
33 },
34};
35use azalea_registry::{
36 builtin::{EntityKind, MobEffect},
37 item::{
38 ItemStack,
39 components::{self, EquipmentSlot},
40 },
41};
42use azalea_world::World;
43use bevy_app::{App, Plugin, Update};
44use bevy_ecs::prelude::*;
45
46use crate::{
47 local_player::{Hunger, WorldHolder},
48 packet::game::SendGamePacketEvent,
49};
50
51pub struct MovementPlugin;
52
53impl Plugin for MovementPlugin {
54 fn build(&self, app: &mut App) {
55 app.add_message::<StartWalkEvent>()
56 .add_message::<StartSprintEvent>()
57 .add_systems(
58 Update,
59 (handle_sprint, handle_walk)
60 .chain()
61 .in_set(MoveEventsSystems)
62 .after(update_bounding_box)
63 .after(update_last_bounding_box),
64 )
65 .add_systems(
66 GameTick,
67 (
68 (
69 tick_controls,
70 local_player_ai_step,
71 process_fall_flying_activation,
72 )
73 .chain()
74 .in_set(PhysicsSystems)
75 .before(ai_step)
76 .before(azalea_physics::fluids::update_in_water_state_and_do_fluid_pushing),
77 send_player_input_packet,
78 update_pose.before(EntityGeometryUpdateSystems),
79 send_sprinting_if_needed
80 .after(azalea_entity::update_in_loaded_chunk)
81 .after(travel)
82 .after(EntityGeometryUpdateSystems),
83 send_position,
84 )
85 .chain(),
86 )
87 .add_observer(handle_knockback);
88 }
89}
90
91#[derive(Clone, Debug, Eq, Hash, PartialEq, SystemSet)]
92pub struct MoveEventsSystems;
93
94#[derive(Clone, Component, Debug, Default)]
97pub struct LastSentLookDirection {
98 pub x_rot: f32,
99 pub y_rot: f32,
100}
101
102#[allow(clippy::type_complexity)]
103pub fn send_position(
104 mut query: Query<
105 (
106 Entity,
107 &Position,
108 &LookDirection,
109 &mut ClientMovementState,
110 &mut LastSentPosition,
111 &mut Physics,
112 &mut LastSentLookDirection,
113 ),
114 With<HasClientLoaded>,
115 >,
116 mut commands: Commands,
117) {
118 for (
119 entity,
120 position,
121 direction,
122 mut physics_state,
123 mut last_sent_position,
124 mut physics,
125 mut last_direction,
126 ) in query.iter_mut()
127 {
128 let packet = {
129 let x_delta = position.x - last_sent_position.x;
135 let y_delta = position.y - last_sent_position.y;
136 let z_delta = position.z - last_sent_position.z;
137 let y_rot_delta = (direction.y_rot() - last_direction.y_rot) as f64;
138 let x_rot_delta = (direction.x_rot() - last_direction.x_rot) as f64;
139
140 physics_state.position_remainder += 1;
141
142 let is_delta_large_enough =
146 (x_delta.powi(2) + y_delta.powi(2) + z_delta.powi(2)) > 2.0e-4f64.powi(2);
147 let sending_position = is_delta_large_enough || physics_state.position_remainder >= 20;
148 let sending_direction = y_rot_delta != 0.0 || x_rot_delta != 0.0;
149
150 let flags = MoveFlags {
154 on_ground: physics.on_ground(),
155 horizontal_collision: physics.horizontal_collision,
156 };
157 let packet = if sending_position && sending_direction {
158 Some(
159 ServerboundMovePlayerPosRot {
160 pos: **position,
161 look_direction: *direction,
162 flags,
163 }
164 .into_variant(),
165 )
166 } else if sending_position {
167 Some(
168 ServerboundMovePlayerPos {
169 pos: **position,
170 flags,
171 }
172 .into_variant(),
173 )
174 } else if sending_direction {
175 Some(
176 ServerboundMovePlayerRot {
177 look_direction: *direction,
178 flags,
179 }
180 .into_variant(),
181 )
182 } else if physics.last_on_ground() != physics.on_ground() {
183 Some(ServerboundMovePlayerStatusOnly { flags }.into_variant())
184 } else {
185 None
186 };
187
188 if sending_position {
189 **last_sent_position = **position;
190 physics_state.position_remainder = 0;
191 }
192 if sending_direction {
193 last_direction.y_rot = direction.y_rot();
194 last_direction.x_rot = direction.x_rot();
195 }
196
197 let on_ground = physics.on_ground();
198 physics.set_last_on_ground(on_ground);
199 packet
202 };
203
204 if let Some(packet) = packet {
205 commands.trigger(SendGamePacketEvent {
206 sent_by: entity,
207 packet,
208 });
209 }
210 }
211}
212
213#[derive(Clone, Component, Debug, Default, Eq, PartialEq)]
214pub struct LastSentInput(pub ServerboundPlayerInput);
215pub fn send_player_input_packet(
216 mut query: Query<(
217 Entity,
218 &ClientMovementState,
219 &Jumping,
220 Option<&LastSentInput>,
221 )>,
222 mut commands: Commands,
223) {
224 for (entity, physics_state, jumping, last_sent_input) in query.iter_mut() {
225 let dir = physics_state.move_direction;
226 let input = ServerboundPlayerInput {
227 forward: dir.forward(),
228 backward: dir.backward(),
229 left: dir.left(),
230 right: dir.right(),
231 jump: **jumping,
232 shift: physics_state.trying_to_crouch,
233 sprint: physics_state.trying_to_sprint,
234 };
235
236 let last_sent_input = last_sent_input.cloned().unwrap_or_default();
239
240 if input != last_sent_input.0 {
241 commands.trigger(SendGamePacketEvent {
242 sent_by: entity,
243 packet: input.clone().into_variant(),
244 });
245 commands.entity(entity).insert(LastSentInput(input));
246 }
247 }
248}
249
250pub fn send_sprinting_if_needed(
251 mut query: Query<(
252 Entity,
253 &MinecraftEntityId,
254 &Sprinting,
255 &mut ClientMovementState,
256 )>,
257 mut commands: Commands,
258) {
259 for (entity, minecraft_entity_id, sprinting, mut physics_state) in query.iter_mut() {
260 let was_sprinting = physics_state.was_sprinting;
261 if **sprinting != was_sprinting {
262 let sprinting_action = if **sprinting {
263 s_player_command::Action::StartSprinting
264 } else {
265 s_player_command::Action::StopSprinting
266 };
267 commands.trigger(SendGamePacketEvent::new(
268 entity,
269 ServerboundPlayerCommand {
270 id: *minecraft_entity_id,
271 action: sprinting_action,
272 data: 0,
273 },
274 ));
275 physics_state.was_sprinting = **sprinting;
276 }
277 }
278}
279
280pub(crate) fn tick_controls(mut query: Query<&mut ClientMovementState>) {
283 for mut physics_state in query.iter_mut() {
284 let mut forward_impulse: f32 = 0.;
285 let mut left_impulse: f32 = 0.;
286 let move_direction = physics_state.move_direction;
287
288 if move_direction.forward() {
289 forward_impulse += 1.;
290 } else if move_direction.backward() {
291 forward_impulse -= 1.;
292 }
293
294 if move_direction.left() {
295 left_impulse += 1.;
296 } else if move_direction.right() {
297 left_impulse -= 1.;
298 }
299
300 let move_vector = Vec2::new(left_impulse, forward_impulse).normalized();
301 physics_state.move_vector = move_vector;
302 }
303}
304
305#[allow(clippy::type_complexity)]
309pub fn local_player_ai_step(
310 mut query: Query<
311 (
312 Entity,
313 &ClientMovementState,
314 &PlayerAbilities,
315 &metadata::Swimming,
316 &metadata::SleepingPos,
317 &WorldHolder,
318 &Position,
319 Option<&Hunger>,
320 Option<&LastSentInput>,
321 &FallFlying,
322 &Pose,
323 &mut Physics,
324 &mut Sprinting,
325 &mut Crouching,
326 &mut Attributes,
327 ),
328 (With<HasClientLoaded>, With<LocalEntity>),
329 >,
330 aabb_query: AabbQuery,
331 collidable_entity_query: CollidableEntityQuery,
332) {
333 for (
334 entity,
335 physics_state,
336 abilities,
337 swimming,
338 sleeping_pos,
339 world_holder,
340 position,
341 hunger,
342 last_sent_input,
343 fall_flying,
344 pose,
345 mut physics,
346 mut sprinting,
347 mut crouching,
348 mut attributes,
349 ) in query.iter_mut()
350 {
351 let is_swimming = **swimming;
354 let is_passenger = false;
356 let is_sleeping = sleeping_pos.is_some();
357
358 let world = world_holder.shared.read();
359 let ctx = CanPlayerFitCtx {
360 world: &world,
361 entity,
362 position: *position,
363 aabb_query: &aabb_query,
364 collidable_entity_query: &collidable_entity_query,
365 physics: &physics,
366 };
367
368 let new_crouching = !abilities.flying
369 && !is_swimming
370 && !is_passenger
371 && (last_sent_input.is_some_and(|i| i.0.shift)
372 || !is_sleeping
373 && !can_player_fit_within_blocks_and_entities_when(&ctx, Pose::Standing))
374 && can_player_fit_within_blocks_and_entities_when(&ctx, Pose::Crouching);
375 if **crouching != new_crouching {
376 **crouching = new_crouching;
377 }
378
379 let has_enough_food_to_sprint = hunger.is_none_or(Hunger::is_enough_to_sprint);
383
384 let trying_to_sprint = physics_state.trying_to_sprint;
387
388 let is_underwater = false;
390 let is_in_water = physics.is_in_water();
391
392 let is_fall_flying = **fall_flying;
393 let is_passenger = false;
395 let using_item = false;
397 let has_blindness = false;
399
400 let has_enough_impulse = has_enough_impulse_to_start_sprinting(physics_state);
401
402 let can_start_sprinting = !**sprinting
404 && has_enough_impulse
405 && has_enough_food_to_sprint
406 && !using_item
407 && !has_blindness
408 && (!is_passenger || is_underwater)
409 && (!is_fall_flying || is_underwater)
410 && (!is_moving_slowly(&crouching, fall_flying, pose, is_in_water) || is_underwater)
411 && (!is_in_water || is_underwater);
412 if trying_to_sprint && can_start_sprinting {
413 set_sprinting(true, &mut sprinting, &mut attributes);
414 }
415
416 if **sprinting {
417 let vehicle_can_sprint = false;
420 let should_stop_sprinting = has_blindness
422 || (is_passenger && !vehicle_can_sprint)
423 || !has_enough_impulse
424 || !has_enough_food_to_sprint
425 || (physics.horizontal_collision && !physics.minor_horizontal_collision)
426 || (is_in_water && !is_underwater);
427 if should_stop_sprinting {
428 set_sprinting(false, &mut sprinting, &mut attributes);
429 }
430 }
431
432 let move_vector = modify_input(
435 physics_state.move_vector,
436 false,
437 false,
438 is_moving_slowly(&crouching, fall_flying, pose, is_in_water),
439 &attributes,
440 );
441 physics.x_acceleration = move_vector.x;
442 physics.z_acceleration = move_vector.y;
443 }
444}
445
446pub fn process_fall_flying_activation(
451 mut query: Query<
452 (
453 Entity,
454 &MinecraftEntityId,
455 &PlayerAbilities,
456 Option<&LastSentInput>,
457 &Jumping,
458 &Inventory,
459 &Physics,
460 &ActiveEffects,
461 &OnClimbable,
462 &mut FallFlying,
463 ),
464 (With<HasClientLoaded>, With<LocalEntity>),
465 >,
466 mut commands: Commands,
467) {
468 for (
469 entity,
470 minecraft_entity_id,
471 abilities,
472 last_sent_input,
473 jumping,
474 inv,
475 physics,
476 active_effects,
477 onclimbable,
478 mut fall_flying,
479 ) in query.iter_mut()
480 {
481 let creative_flight_toggled = false;
483
484 if **jumping
485 && !creative_flight_toggled
486 && last_sent_input.is_some_and(|input| !input.0.jump)
487 && !**onclimbable
488 && can_start_fall_flying(&fall_flying, abilities, inv, physics, active_effects)
489 {
490 **fall_flying = true; commands.trigger(SendGamePacketEvent::new(
493 entity,
494 s_player_command::ServerboundPlayerCommand {
495 id: *minecraft_entity_id,
496 action: s_player_command::Action::StartFallFlying,
497 data: 0,
498 },
499 ));
500 }
501 }
502}
503
504fn can_start_fall_flying(
506 already_fall_flying: &FallFlying,
507 abilities: &PlayerAbilities,
508 inv: &Inventory,
509 physics: &Physics,
510 active_effects: &ActiveEffects,
511) -> bool {
512 (!**already_fall_flying)
513 && (!abilities.flying)
514
515 && !physics.on_ground()
517 && !active_effects.0.contains_key(&MobEffect::Levitation)
519 && EquipmentSlot::values().iter().any(|slot| {
520 inv.get_equipment(*slot).is_some_and(|stack| {
521 stack.get_component::<components::Glider>().is_some()
523 && stack.get_component::<components::Equippable>().is_some_and(
524 |equippable| equippable.slot == *slot
525 )
526 && !next_damage_will_break(stack)
527 })
528 })
529
530 && !physics.is_in_water()
531}
532
533fn next_damage_will_break(stack: &ItemStack) -> bool {
535 let Some(max_damage) = stack.get_component::<components::MaxDamage>() else {
536 return false;
537 };
538 let Some(damage) = stack.get_component::<components::Damage>() else {
539 return false;
540 };
541 if stack.get_component::<components::Unbreakable>().is_some() {
543 return false;
544 }
545 damage.amount >= max_damage.amount - 1
546}
547
548fn is_moving_slowly(
550 crouching: &Crouching,
551 fall_flying: &FallFlying,
552 pose: &Pose,
553 is_in_water: bool,
554) -> bool {
555 if **crouching {
556 return true;
557 }
558
559 if is_in_water {
561 return false;
562 }
563
564 match *pose {
566 Pose::Swimming => true,
567 Pose::FallFlying => !**fall_flying,
568 _ => false,
572 }
573}
574
575fn modify_input(
577 mut move_vector: Vec2,
578 is_using_item: bool,
579 is_passenger: bool,
580 moving_slowly: bool,
581 attributes: &Attributes,
582) -> Vec2 {
583 if move_vector.length_squared() == 0. {
584 return move_vector;
585 }
586
587 move_vector *= 0.98;
588 if is_using_item && !is_passenger {
589 move_vector *= 0.2;
590 }
591
592 if moving_slowly {
593 let sneaking_speed = attributes.sneaking_speed.calculate() as f32;
594 move_vector *= sneaking_speed;
595 }
596
597 modify_input_speed_for_square_movement(move_vector)
598}
599fn modify_input_speed_for_square_movement(move_vector: Vec2) -> Vec2 {
600 let length = move_vector.length();
601 if length == 0. {
602 return move_vector;
603 }
604 let scaled_to_inverse_length = move_vector * (1. / length);
605 let dist = distance_to_unit_square(scaled_to_inverse_length);
606 let scale = (length * dist).min(1.);
607 scaled_to_inverse_length * scale
608}
609fn distance_to_unit_square(v: Vec2) -> f32 {
610 let x = v.x.abs();
611 let y = v.y.abs();
612 let ratio = if y > x { x / y } else { y / x };
613 (1. + ratio * ratio).sqrt()
614}
615
616#[derive(Debug, Message)]
622pub struct StartWalkEvent {
623 pub entity: Entity,
624 pub direction: WalkDirection,
625}
626
627pub fn handle_walk(
630 mut events: MessageReader<StartWalkEvent>,
631 mut query: Query<(&mut ClientMovementState, &mut Sprinting, &mut Attributes)>,
632) {
633 for event in events.read() {
634 if let Ok((mut physics_state, mut sprinting, mut attributes)) = query.get_mut(event.entity)
635 {
636 physics_state.move_direction = event.direction;
637 physics_state.trying_to_sprint = false;
638 set_sprinting(false, &mut sprinting, &mut attributes);
639 }
640 }
641}
642
643#[derive(Message)]
647pub struct StartSprintEvent {
648 pub entity: Entity,
649 pub direction: SprintDirection,
650}
651pub fn handle_sprint(
654 mut query: Query<&mut ClientMovementState>,
655 mut events: MessageReader<StartSprintEvent>,
656) {
657 for event in events.read() {
658 if let Ok(mut physics_state) = query.get_mut(event.entity) {
659 physics_state.move_direction = WalkDirection::from(event.direction);
660 physics_state.trying_to_sprint = true;
661 }
662 }
663}
664
665fn set_sprinting(
673 sprinting: bool,
674 currently_sprinting: &mut Sprinting,
675 attributes: &mut Attributes,
676) -> bool {
677 **currently_sprinting = sprinting;
678 if sprinting {
679 attributes
680 .movement_speed
681 .try_insert(azalea_entity::attributes::sprinting_modifier())
682 .is_ok()
683 } else {
684 attributes
685 .movement_speed
686 .remove(&azalea_entity::attributes::sprinting_modifier().id)
687 .is_none()
688 }
689}
690
691fn has_enough_impulse_to_start_sprinting(physics_state: &ClientMovementState) -> bool {
693 physics_state.move_vector.y > 0.8
697 }
699
700#[derive(EntityEvent, Debug, Clone)]
706pub struct KnockbackEvent {
707 pub entity: Entity,
708 pub data: KnockbackData,
709}
710
711#[derive(Debug, Clone)]
712pub enum KnockbackData {
713 Set(Vec3),
714 Add(Vec3),
715}
716
717pub fn handle_knockback(knockback: On<KnockbackEvent>, mut query: Query<&mut Physics>) {
718 if let Ok(mut physics) = query.get_mut(knockback.entity) {
719 match knockback.data {
720 KnockbackData::Set(velocity) => {
721 physics.velocity = velocity;
722 }
723 KnockbackData::Add(velocity) => {
724 physics.velocity += velocity;
725 }
726 }
727 }
728}
729
730pub fn update_pose(
731 mut query: Query<(
732 Entity,
733 &mut Pose,
734 &Physics,
735 &ClientMovementState,
736 &FallFlying,
737 &GameMode,
738 &WorldHolder,
739 &Position,
740 )>,
741 aabb_query: AabbQuery,
742 collidable_entity_query: CollidableEntityQuery,
743) {
744 for (
745 entity,
746 mut pose,
747 physics,
748 physics_state,
749 fall_flying,
750 &game_mode,
751 world_holder,
752 position,
753 ) in query.iter_mut()
754 {
755 let world = world_holder.shared.read();
756 let world = &*world;
757 let ctx = CanPlayerFitCtx {
758 world,
759 entity,
760 position: *position,
761 aabb_query: &aabb_query,
762 collidable_entity_query: &collidable_entity_query,
763 physics,
764 };
765
766 if !can_player_fit_within_blocks_and_entities_when(&ctx, Pose::Swimming) {
767 continue;
768 }
769
770 let desired_pose = if physics_state.trying_to_crouch {
773 Pose::Crouching
774 } else if **fall_flying {
775 Pose::FallFlying
776 } else {
777 Pose::Standing
778 };
779
780 let is_passenger = false;
782
783 let new_pose = if game_mode == GameMode::Spectator
785 || is_passenger
786 || can_player_fit_within_blocks_and_entities_when(&ctx, desired_pose)
787 {
788 desired_pose
789 } else if can_player_fit_within_blocks_and_entities_when(&ctx, Pose::Crouching) {
790 Pose::Crouching
791 } else {
792 Pose::Swimming
793 };
794
795 if new_pose != *pose {
797 *pose = new_pose;
798 }
799 }
800}
801
802struct CanPlayerFitCtx<'world, 'state, 'a, 'b> {
803 world: &'a World,
804 entity: Entity,
805 position: Position,
806 aabb_query: &'a AabbQuery<'world, 'state, 'b>,
807 collidable_entity_query: &'a CollidableEntityQuery<'world, 'state>,
808 physics: &'a Physics,
809}
810fn can_player_fit_within_blocks_and_entities_when(ctx: &CanPlayerFitCtx, pose: Pose) -> bool {
811 no_collision(
812 ctx.world,
813 Some(ctx.entity),
814 ctx.aabb_query,
815 ctx.collidable_entity_query,
816 ctx.physics,
817 &calculate_dimensions(EntityKind::Player, pose)
818 .make_bounding_box(*ctx.position)
819 .deflate_all(1.0e-7),
820 false,
821 )
822}