Account for accepted movement distance in resident player hunger

This commit is contained in:
Ludovic Marie
2026-10-07 17:29:13 +02:00
parent 5023f82078
commit ecb3ebfd34
10 changed files with 2307 additions and 9 deletions
@@ -10,6 +10,7 @@ use horizon_client::{
use horizon_core::geometry::Vec3;
use horizon_core::{position::BlockPos, random::RandomSource};
use horizon_world::attributes::{Modifier, Operation};
use horizon_world::movement_statistics::{self, MovementStat, MovementStatisticsWorld};
use serde_json::Value;
use std::{
fs,
@@ -28,6 +29,61 @@ fn vector(v: &Value) -> Vec3 {
fn position(p: Option<horizon_core::position::BlockPos>) -> String {
p.map_or_else(|| "none".into(), |p| format!("{},{},{}", p.x, p.y, p.z))
}
struct StatisticsContext<'a> {
flags: u16,
invulnerable: bool,
player: &'a mut PlayerMotion,
}
impl StatisticsContext<'_> {
fn flag(&self, bit: u32) -> Result<bool> {
Ok(self.flags & (1 << bit) != 0)
}
}
impl MovementStatisticsWorld for StatisticsContext<'_> {
type Error = Box<dyn std::error::Error>;
fn passenger(&mut self) -> Result<bool> {
self.flag(0)
}
fn swimming(&mut self) -> Result<bool> {
self.flag(1)
}
fn eyes_in_water(&mut self) -> Result<bool> {
self.flag(2)
}
fn in_water(&mut self) -> Result<bool> {
self.flag(3)
}
fn on_climbable(&mut self) -> Result<bool> {
self.flag(4)
}
fn on_ground(&mut self) -> Result<bool> {
self.flag(5)
}
fn sprinting(&mut self) -> Result<bool> {
self.flag(6)
}
fn crouching(&mut self) -> Result<bool> {
self.flag(7)
}
fn fall_flying(&mut self) -> Result<bool> {
self.flag(8)
}
fn award(&mut self, stat: MovementStat, amount: i32) -> Result<()> {
self.player.events.push(MotionEvent::Health(
horizon_client::health::HealthEvent::Statistic {
name: stat.name(),
amount,
},
));
Ok(())
}
fn exhaust(&mut self, amount: f32) -> Result<()> {
if !self.invulnerable {
self.player.health.food.add_exhaustion(amount);
}
Ok(())
}
}
fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> {
// Compare membership and stored values without allocating lazy instances or
// evaluating computed values. Runtime identity hashes differ between VMs.
@@ -146,6 +202,15 @@ fn main() -> Result<()> {
resources: &resources,
};
match op["mode"].as_str().unwrap() {
"movement_statistics" => world.check_movement_statistics(vector(&op["value"]))?,
"statistics_context" => movement_statistics::check(
&mut StatisticsContext {
player: world.player,
flags: op["flags"].as_u64().unwrap() as u16,
invulnerable: op["invulnerable"].as_bool().unwrap(),
},
vector(&op["value"]),
)?,
"tick_count" => {
world.player.health.tick_count = op["value"].as_i64().unwrap() as i32
}
+54
View File
@@ -24,6 +24,7 @@ use horizon_world::{
RegistryMovementWorld,
},
movement_restitution::{self, RestitutionInput, RestitutionWorld},
movement_statistics::{self, MovementStat, MovementStatisticsWorld},
movement_support::{self, MovementLocation},
nbt::{self, Limits},
registry::BlockStateId,
@@ -359,10 +360,17 @@ impl MotionWorld<'_, '_, '_> {
/// services are still incomplete; this composes clocks, movement and hunger.
pub fn simulation_tick(&mut self, direction: [f32; 2], jumping: bool) -> Result<()> {
self.player.health.advance_clock();
let previous = self.player.position;
self.player_movement_tick(direction, jumping)?;
// The resident scene accepts the resolved local movement directly.
// Vanilla dispatches this separately from travel, on packet acceptance.
self.check_movement_statistics(previous.vector_to(self.player.position))?;
self.player
.food_tick(&self.resources.health, self.scene.health_rules)
}
pub fn check_movement_statistics(&mut self, delta: Vec3) -> Result<()> {
movement_statistics::check(self, delta)
}
fn dry_tick(&mut self, input: TickInput) -> Result<()> {
if self.player.no_jump_delay > 0 {
self.player.no_jump_delay -= 1;
@@ -421,6 +429,52 @@ impl MotionWorld<'_, '_, '_> {
entity_move::move_entity(self, MoverType::SelfMovement, movement)
}
}
// Current resident movement domain: dry, standing, no vehicles or gliding.
// The shared kernel also handles swimming/crouching/flight when those states
// are supplied by their eventual runtime bindings.
impl MovementStatisticsWorld for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
fn passenger(&mut self) -> Result<bool> {
Ok(false)
}
fn swimming(&mut self) -> Result<bool> {
Ok(false)
}
fn eyes_in_water(&mut self) -> Result<bool> {
Ok(false)
}
fn in_water(&mut self) -> Result<bool> {
Ok(false)
}
fn on_climbable(&mut self) -> Result<bool> {
self.climbable()
}
fn on_ground(&mut self) -> Result<bool> {
Ok(self.player.ground.on_ground)
}
fn sprinting(&mut self) -> Result<bool> {
Ok(self.player.sprinting)
}
fn crouching(&mut self) -> Result<bool> {
Ok(false)
}
fn fall_flying(&mut self) -> Result<bool> {
Ok(false)
}
fn award(&mut self, stat: MovementStat, amount: i32) -> Result<()> {
self.player
.events
.push(MotionEvent::Health(crate::health::HealthEvent::Statistic {
name: stat.name(),
amount,
}));
Ok(())
}
fn exhaust(&mut self, amount: f32) -> Result<()> {
self.player.health.food.add_exhaustion(amount);
Ok(())
}
}
impl MovementBlockProvider for MotionWorld<'_, '_, '_> {
type Error = io::Error;
fn movement_block_state(&mut self, p: BlockPos) -> io::Result<BlockStateId> {
+1
View File
@@ -85,6 +85,7 @@ pub mod living_motion;
pub mod movement_emission;
pub mod movement_properties;
pub mod movement_restitution;
pub mod movement_statistics;
pub mod movement_support;
pub mod nbt;
pub mod object_open_map;
@@ -0,0 +1,128 @@
//! ServerPlayer.checkMovementStatistics. Called for accepted movement, separately
//! from Entity.move/travel: the packet listener owns that boundary in vanilla.
use horizon_core::geometry::Vec3;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MovementStat {
Swim,
WalkUnderWater,
WalkOnWater,
Climb,
Sprint,
Crouch,
Walk,
Aviate,
Fly,
}
impl MovementStat {
pub fn name(self) -> &'static str {
match self {
Self::Swim => "swim_one_cm",
Self::WalkUnderWater => "walk_under_water_one_cm",
Self::WalkOnWater => "walk_on_water_one_cm",
Self::Climb => "climb_one_cm",
Self::Sprint => "sprint_one_cm",
Self::Crouch => "crouch_one_cm",
Self::Walk => "walk_one_cm",
Self::Aviate => "aviate_one_cm",
Self::Fly => "fly_one_cm",
}
}
}
pub trait MovementStatisticsWorld {
type Error;
fn passenger(&mut self) -> Result<bool, Self::Error>;
fn swimming(&mut self) -> Result<bool, Self::Error>;
fn eyes_in_water(&mut self) -> Result<bool, Self::Error>;
fn in_water(&mut self) -> Result<bool, Self::Error>;
fn on_climbable(&mut self) -> Result<bool, Self::Error>;
fn on_ground(&mut self) -> Result<bool, Self::Error>;
fn sprinting(&mut self) -> Result<bool, Self::Error>;
fn crouching(&mut self) -> Result<bool, Self::Error>;
fn fall_flying(&mut self) -> Result<bool, Self::Error>;
fn award(&mut self, stat: MovementStat, amount: i32) -> Result<(), Self::Error>;
fn exhaust(&mut self, amount: f32) -> Result<(), Self::Error>;
}
fn round_float(value: f32) -> i32 {
let bits = value.to_bits() as i32;
let shift = 149 - ((bits >> 23) & 0xff);
if (0..32).contains(&shift) {
let mut significand = (bits & 0x7f_ffff) | 0x80_0000;
if bits < 0 {
significand = -significand;
}
((significand >> shift) + 1) >> 1
} else {
value as i32
}
}
fn round_double(value: f64) -> i64 {
let bits = value.to_bits() as i64;
let shift = 1074 - ((bits >> 52) & 0x7ff);
if (0..64).contains(&shift) {
let mut significand = (bits & 0xf_ffff_ffff_ffff) | 0x10_0000_0000_0000;
if bits < 0 {
significand = -significand;
}
((significand >> shift) + 1) >> 1
} else {
value as i64
}
}
fn centimeters(squared: f64) -> i32 {
// Java narrows the square root BEFORE multiplying by 100f and rounding.
round_float(squared.sqrt() as f32 * 100.0)
}
fn distance_with_exhaustion<W: MovementStatisticsWorld>(
world: &mut W,
stat: MovementStat,
cm: i32,
rate: f32,
) -> Result<(), W::Error> {
if cm > 0 {
world.award(stat, cm)?;
world.exhaust(rate * cm as f32 * 0.01)?;
}
Ok(())
}
pub fn check<W: MovementStatisticsWorld>(world: &mut W, delta: Vec3) -> Result<(), W::Error> {
if world.passenger()? || (delta.x == 0.0 && delta.y == 0.0 && delta.z == 0.0) {
return Ok(());
}
let distance_3d = || centimeters(delta.x * delta.x + delta.y * delta.y + delta.z * delta.z);
let horizontal = || centimeters(delta.x * delta.x + delta.z * delta.z);
if world.swimming()? {
distance_with_exhaustion(world, MovementStat::Swim, distance_3d(), 0.01)
} else if world.eyes_in_water()? {
distance_with_exhaustion(world, MovementStat::WalkUnderWater, distance_3d(), 0.01)
} else if world.in_water()? {
distance_with_exhaustion(world, MovementStat::WalkOnWater, horizontal(), 0.01)
} else if world.on_climbable()? {
if delta.y > 0.0 {
// The native double round returns long; l2i then wraps, not saturates.
world.award(MovementStat::Climb, round_double(delta.y * 100.0) as i32)?;
}
Ok(())
} else if world.on_ground()? {
let cm = horizontal();
if cm > 0 {
let (stat, rate) = if world.sprinting()? {
(MovementStat::Sprint, 0.1)
} else if world.crouching()? {
(MovementStat::Crouch, 0.0)
} else {
(MovementStat::Walk, 0.0)
};
distance_with_exhaustion(world, stat, cm, rate)?;
}
Ok(())
} else if world.fall_flying()? {
world.award(MovementStat::Aviate, distance_3d())
} else {
let cm = horizontal();
if cm > 25 {
world.award(MovementStat::Fly, cm)?;
}
Ok(())
}
}