1pub mod entity_collisions;
2pub mod world_collisions;
3
4use std::{ops::Add, sync::LazyLock};
5
6use azalea_block::{BlockState, fluid_state::FluidState};
7use azalea_core::{
8 aabb::Aabb,
9 direction::Axis,
10 math::{self, EPSILON},
11 position::{BlockPos, Vec3},
12};
13use azalea_entity::{
14 Attributes, Jumping, LookDirection, OnClimbable, Physics, PlayerAbilities, Pose, Position,
15 metadata::Sprinting,
16};
17use azalea_physics_collision::{
18 BlockWithShape,
19 shape::{BLOCK_SHAPE, EMPTY_SHAPE, Shapes, VoxelShape, box_shape},
20};
21use azalea_registry::builtin::BlockKind;
22use azalea_world::{ChunkStorage, World};
23use bevy_ecs::{entity::Entity, world::Mut};
24use entity_collisions::{CollidableEntityQuery, get_entity_collisions};
25use tracing::warn;
26
27use self::world_collisions::get_block_collisions;
28use crate::{
29 client_movement::ClientMovementState, collision_impl::entity_collisions::AabbQuery,
30 travel::no_collision,
31};
32
33#[derive(Clone, Copy, Debug, Eq, PartialEq)]
34pub enum MoverType {
35 Own,
36 Player,
37 Piston,
38 ShulkerBox,
39 Shulker,
40}
41
42fn collide(ctx: &MoveCtx, movement: Vec3) -> Vec3 {
44 let entity_bounding_box = ctx.physics.bounding_box;
45 let entity_collisions = get_entity_collisions(
46 ctx.world,
47 &entity_bounding_box.expand_towards(movement),
48 Some(ctx.source_entity),
49 ctx.aabb_query,
50 ctx.collidable_entity_query,
51 );
52 let world = ctx.world;
53 let collided_delta = if movement.length_squared() == 0.0 {
54 movement
55 } else {
56 collide_bounding_box(movement, &entity_bounding_box, world, &entity_collisions)
57 };
58
59 let x_collision = movement.x != collided_delta.x;
60 let y_collision = movement.y != collided_delta.y;
61 let z_collision = movement.z != collided_delta.z;
62
63 let on_ground = ctx.physics.on_ground() || y_collision && movement.y < 0.;
64
65 let max_up_step = 0.6;
66 if max_up_step > 0. && on_ground && (x_collision || z_collision) {
67 let mut step_to_delta = collide_bounding_box(
68 movement.with_y(max_up_step),
69 &entity_bounding_box,
70 world,
71 &entity_collisions,
72 );
73 let directly_up_delta = collide_bounding_box(
74 Vec3::ZERO.with_y(max_up_step),
75 &entity_bounding_box.expand_towards(Vec3::new(movement.x, 0., movement.z)),
76 world,
77 &entity_collisions,
78 );
79 if directly_up_delta.y < max_up_step {
80 let target_movement = collide_bounding_box(
81 movement.with_y(0.),
82 &entity_bounding_box.move_relative(directly_up_delta),
83 world,
84 &entity_collisions,
85 )
86 .add(directly_up_delta);
87 if target_movement.horizontal_distance_squared()
88 > step_to_delta.horizontal_distance_squared()
89 {
90 step_to_delta = target_movement;
91 }
92 }
93
94 if step_to_delta.horizontal_distance_squared()
95 > collided_delta.horizontal_distance_squared()
96 {
97 return step_to_delta.add(collide_bounding_box(
98 Vec3::ZERO.with_y(-step_to_delta.y + movement.y),
99 &entity_bounding_box.move_relative(step_to_delta),
100 world,
101 &entity_collisions,
102 ));
103 }
104 }
105
106 collided_delta
107}
108
109pub struct MoveCtx<'world, 'state, 'a, 'b> {
110 pub mover_type: MoverType,
111 pub world: &'a World,
112 pub position: Mut<'a, Position>,
113 pub physics: &'a mut Physics,
114 pub source_entity: Entity,
115 pub aabb_query: &'a AabbQuery<'world, 'state, 'b>,
116 pub collidable_entity_query: &'a CollidableEntityQuery<'world, 'state>,
117 pub physics_state: Option<&'a ClientMovementState>,
118 pub attributes: &'a Attributes,
119 pub abilities: Option<&'a PlayerAbilities>,
120
121 pub direction: LookDirection,
122 pub sprinting: Sprinting,
123 pub on_climbable: OnClimbable,
124 pub pose: Option<Pose>,
125 pub jumping: Jumping,
126}
127
128pub fn move_colliding(ctx: &mut MoveCtx, mut movement: Vec3) {
132 movement = maybe_back_off_from_edge(ctx, movement);
152 let collide_result = collide(ctx, movement);
153
154 let move_distance_sqr = collide_result.length_squared();
155
156 let position = &mut ctx.position;
157 let physics = &mut *ctx.physics;
158 let world = ctx.world;
159
160 if move_distance_sqr > EPSILON || movement.length_squared() - move_distance_sqr < EPSILON {
161 let new_pos = {
164 Vec3 {
165 x: position.x + collide_result.x,
166 y: position.y + collide_result.y,
167 z: position.z + collide_result.z,
168 }
169 };
170
171 if new_pos != ***position {
172 ***position = new_pos;
173 }
174 }
175
176 let x_collision = !math::equal(movement.x, collide_result.x);
177 let z_collision = !math::equal(movement.z, collide_result.z);
178 let horizontal_collision = x_collision || z_collision;
179 physics.horizontal_collision = horizontal_collision;
180
181 let vertical_collision = movement.y != collide_result.y;
182 physics.vertical_collision = vertical_collision;
183 let on_ground = vertical_collision && movement.y < 0.;
184 physics.set_on_ground(on_ground);
185
186 let block_pos_below = azalea_entity::on_pos_legacy(&world.chunks, **position);
189 let block_state_below = world.get_block_state(block_pos_below).unwrap_or_default();
190
191 check_fall_damage(
192 physics,
193 collide_result.y,
194 block_state_below,
195 block_pos_below,
196 );
197
198 if horizontal_collision {
201 let delta_movement = &physics.velocity;
202 physics.velocity = Vec3 {
203 x: if x_collision { 0. } else { delta_movement.x },
204 y: delta_movement.y,
205 z: if z_collision { 0. } else { delta_movement.z },
206 }
207 }
208
209 if vertical_collision {
210 physics.velocity.y = 0.;
214 }
215
216 if on_ground {
217 }
220
221 }
244
245fn check_fall_damage(
246 physics: &mut Physics,
247 delta_y: f64,
248 _block_state_below: BlockState,
249 _block_pos_below: BlockPos,
250) {
251 if !physics.is_in_water() && delta_y < 0. {
252 physics.fall_distance -= delta_y as f32 as f64;
253 }
254
255 if physics.on_ground() {
256 physics.fall_distance = 0.;
259 }
260}
261
262fn maybe_back_off_from_edge(move_ctx: &mut MoveCtx, mut movement: Vec3) -> Vec3 {
263 let is_staying_on_ground_surface = move_ctx.physics_state.is_some_and(|s| s.trying_to_crouch);
264 let max_up_step = get_max_up_step(move_ctx.attributes);
265
266 let fall_ctx = CanFallAtLeastCtx {
267 physics: move_ctx.physics,
268 world: move_ctx.world,
269 source_entity: move_ctx.source_entity,
270 aabb_query: move_ctx.aabb_query,
271 collidable_entity_query: move_ctx.collidable_entity_query,
272 };
273
274 let Some(abilities) = move_ctx.abilities else {
275 return movement;
276 };
277
278 let is_backing_off = !abilities.flying
279 && movement.y <= 0.
280 && matches!(move_ctx.mover_type, MoverType::Own | MoverType::Player)
281 && is_staying_on_ground_surface
282 && is_above_ground(&fall_ctx, max_up_step);
283 if !is_backing_off {
284 return movement;
285 }
286
287 let min_movement = 0.05;
288 let min_movement_x = movement.x.signum() * min_movement;
289 let min_movement_z = movement.z.signum() * min_movement;
290
291 while movement.x != 0. && can_fall_at_least(&fall_ctx, movement.x, 0., max_up_step as f64) {
292 if movement.x.abs() <= min_movement {
293 movement.x = 0.;
294 break;
295 }
296
297 movement.x -= min_movement_x
298 }
299 while movement.z != 0. && can_fall_at_least(&fall_ctx, 0., movement.z, max_up_step as f64) {
300 if movement.z.abs() <= min_movement {
301 movement.z = 0.;
302 break;
303 }
304
305 movement.z -= min_movement_z
306 }
307 while movement.x != 0.0
308 && movement.z != 0.0
309 && can_fall_at_least(&fall_ctx, movement.x, movement.z, max_up_step as f64)
310 {
311 if movement.x.abs() <= min_movement {
312 movement.x = 0.;
313 } else {
314 movement.x -= min_movement_x;
315 }
316 if movement.z.abs() <= min_movement {
317 movement.z = 0.;
318 } else {
319 movement.z -= min_movement_z;
320 }
321 }
322
323 movement
324}
325
326fn get_max_up_step(attributes: &Attributes) -> f32 {
327 attributes.step_height.calculate() as f32
329}
330
331fn is_above_ground(ctx: &CanFallAtLeastCtx, max_up_step: f32) -> bool {
332 ctx.physics.on_ground()
333 && ctx.physics.fall_distance < max_up_step as f64
334 && !can_fall_at_least(ctx, 0., 0., max_up_step as f64 - ctx.physics.fall_distance)
335}
336
337pub struct CanFallAtLeastCtx<'world, 'state, 'a, 'b> {
338 physics: &'a Physics,
339 world: &'a World,
340 source_entity: Entity,
341 aabb_query: &'a AabbQuery<'world, 'state, 'b>,
342 collidable_entity_query: &'a CollidableEntityQuery<'world, 'state>,
343}
344
345fn can_fall_at_least(
346 ctx: &CanFallAtLeastCtx,
347 delta_x: f64,
348 delta_z: f64,
349 max_up_step: f64,
350) -> bool {
351 let aabb = ctx.physics.bounding_box;
352 let aabb = Aabb {
353 min: Vec3 {
354 x: aabb.min.x + EPSILON + delta_x,
355 y: aabb.min.y - max_up_step - EPSILON,
356 z: aabb.min.z + EPSILON + delta_z,
357 },
358 max: Vec3 {
359 x: aabb.max.x - EPSILON + delta_x,
360 y: aabb.min.y,
361 z: aabb.max.z - EPSILON + delta_z,
362 },
363 };
364 no_collision(
365 ctx.world,
366 Some(ctx.source_entity),
367 ctx.aabb_query,
368 ctx.collidable_entity_query,
369 ctx.physics,
370 &aabb,
371 false,
372 )
373}
374
375fn collide_bounding_box(
376 movement: Vec3,
377 entity_bounding_box: &Aabb,
378 world: &World,
379 entity_collisions: &[VoxelShape],
380) -> Vec3 {
381 let mut collision_boxes: Vec<VoxelShape> = Vec::with_capacity(entity_collisions.len() + 1);
382
383 if !entity_collisions.is_empty() {
384 collision_boxes.extend_from_slice(entity_collisions);
385 }
386
387 let block_collisions =
390 get_block_collisions(world, &entity_bounding_box.expand_towards(movement));
391 collision_boxes.extend(block_collisions);
392 collide_with_shapes(movement, *entity_bounding_box, &collision_boxes)
393}
394
395fn collide_with_shapes(
396 mut movement: Vec3,
397 mut entity_box: Aabb,
398 collision_boxes: &[VoxelShape],
399) -> Vec3 {
400 if collision_boxes.is_empty() {
401 return movement;
402 }
403
404 if movement.y != 0. {
405 movement.y = Shapes::collide(Axis::Y, &entity_box, collision_boxes, movement.y);
406 if movement.y != 0. {
407 entity_box = entity_box.move_relative(Vec3::new(0., movement.y, 0.));
408 }
409 }
410
411 let more_z_movement = movement.x.abs() < movement.z.abs();
414
415 if more_z_movement && movement.z != 0. {
416 movement.z = Shapes::collide(Axis::Z, &entity_box, collision_boxes, movement.z);
417 if movement.z != 0. {
418 entity_box = entity_box.move_relative(Vec3::new(0., 0., movement.z));
419 }
420 }
421
422 if movement.x != 0. {
423 movement.x = Shapes::collide(Axis::X, &entity_box, collision_boxes, movement.x);
424 if movement.x != 0. {
425 entity_box = entity_box.move_relative(Vec3::new(movement.x, 0., 0.));
426 }
427 }
428
429 if !more_z_movement && movement.z != 0. {
430 movement.z = Shapes::collide(Axis::Z, &entity_box, collision_boxes, movement.z);
431 }
432
433 movement
434}
435
436pub fn fluid_shape(fluid: &FluidState, world: &ChunkStorage, pos: BlockPos) -> &'static VoxelShape {
441 if fluid.amount == 9 {
442 let fluid_state_above = world.get_fluid_state(pos.up(1)).unwrap_or_default();
443 if fluid_state_above.kind == fluid.kind {
444 return &BLOCK_SHAPE;
445 }
446 }
447 if fluid.amount > 9 {
448 warn!("Tried to calculate shape for fluid with height > 9: {fluid:?} at {pos}");
449 return &EMPTY_SHAPE;
450 }
451
452 static FLUID_SHAPES: LazyLock<[VoxelShape; 10]> = LazyLock::new(|| {
456 [
457 calculate_shape_for_fluid(0),
458 calculate_shape_for_fluid(1),
459 calculate_shape_for_fluid(2),
460 calculate_shape_for_fluid(3),
461 calculate_shape_for_fluid(4),
462 calculate_shape_for_fluid(5),
463 calculate_shape_for_fluid(6),
464 calculate_shape_for_fluid(7),
465 calculate_shape_for_fluid(8),
466 calculate_shape_for_fluid(9),
467 ]
468 });
469
470 &FLUID_SHAPES[fluid.amount as usize]
471}
472fn calculate_shape_for_fluid(amount: u8) -> VoxelShape {
473 box_shape(0.0, 0.0, 0.0, 1.0, (f32::from(amount) / 9.0) as f64, 1.0)
474}
475
476pub fn legacy_blocks_motion(block: BlockState) -> bool {
480 if block == BlockState::AIR {
481 return false;
483 }
484
485 let registry_block = BlockKind::from(block);
486 legacy_calculate_solid(block)
487 && registry_block != BlockKind::Cobweb
488 && registry_block != BlockKind::BambooSapling
489}
490
491pub fn legacy_calculate_solid(block: BlockState) -> bool {
492 if let Some(solid) = block.behavior().force_solid {
494 return solid;
495 }
496
497 let shape = block.base_collision_shape();
498 if shape.is_empty() {
499 return false;
500 }
501 let bounds = shape.bounds();
502 bounds.size() >= 0.7291666666666666 || bounds.get_size(Axis::Y) >= 1.0
503}