Merge PR 186 fluid foundation and preserve swimming and fire behavior

This commit is contained in:
Cosmic
2026-10-14 16:28:07 -04:00
9 changed files with 684 additions and 235 deletions
@@ -4,7 +4,7 @@ use horizon_client::{
Result,
assets::Assets,
collisions,
motion::{MotionEvent, MotionResources, MotionWorld, PlayerMotion},
motion::{LAVA, MotionEvent, MotionResources, MotionWorld, PlayerMotion, WATER},
world::World,
};
use horizon_core::geometry::Vec3;
@@ -174,6 +174,31 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> {
velocity.y.to_bits(),
velocity.z.to_bits()
)),
MotionEvent::Splash {
high_speed,
volume,
pitch,
} => Some(format!(
"sound {} entity {:08x} {:08x}",
if *high_speed { "splash-high" } else { "splash" },
volume.to_bits(),
pitch.to_bits()
)),
MotionEvent::SplashParticle {
bubble,
position,
velocity,
} => Some(format!(
"splash-particle {} {:016x},{:016x},{:016x} {:016x},{:016x},{:016x}",
if *bubble { "bubble" } else { "splash" },
position.x.to_bits(),
position.y.to_bits(),
position.z.to_bits(),
velocity.x.to_bits(),
velocity.y.to_bits(),
velocity.z.to_bits()
)),
MotionEvent::SplashEvent => Some("splash-event".into()),
// The oracle marks every getAdvancements call (ENTER_BLOCK.trigger) so.
MotionEvent::EnterBlock { .. } => Some("hurt-criterion".into()),
MotionEvent::Waypoint { receiver, enabled } => Some(format!(
@@ -415,6 +440,9 @@ fn main() -> Result<()> {
p,
)?;
}
// Entity.baseTick's fluid phase alone (wasEyeInWater,
// updateFluidInteraction, lava fall halving, firstTick).
"fluid_tick" => world.fluid_base_tick()?,
"travel" => world.travel_in_air(vector(&op["value"]))?,
"tick" => {
let v = vector(&op["value"]);
@@ -541,14 +569,20 @@ fn main() -> Result<()> {
let stuck = player.stuck_multiplier;
writeln!(
out,
"block {} frozen {} {} {} {:016x},{:016x},{:016x}",
"block {} frozen {} {} {} {:016x},{:016x},{:016x} fluid {} {} {} {} {:016x} {:016x}",
check_block.0,
player.ticks_frozen,
player.in_powder_snow,
player.was_in_powder_snow,
stuck.x.to_bits(),
stuck.y.to_bits(),
stuck.z.to_bits()
stuck.z.to_bits(),
player.fluids.was_touching_water,
player.fluids.was_eye_in_water,
player.is_eye_in_fluid(WATER),
player.fluids.first_tick,
player.fluid_height(WATER).to_bits(),
player.fluid_height(LAVA).to_bits()
)?;
writeln!(
out,
+31
View File
@@ -2893,6 +2893,8 @@ impl Game<'_> {
.iter()
.flatten()
.any(|s| immune.is_some_and(|t| t.contains(&*s.item)));
// The dimension's FAST_LAVA: the Nether's lava pushes harder.
player.fluids.fast_lava = self.dim == Dim::Nether;
let grounded = player.ground.on_ground;
let before = (
grounded,
@@ -2986,6 +2988,35 @@ impl Game<'_> {
position,
fall_distance,
} => self.smash_landing_particles(state, position, fall_distance),
MotionEvent::Splash {
high_speed,
volume,
pitch,
} => {
let name = if high_speed {
"minecraft:entity.player.splash.high_speed"
} else {
"minecraft:entity.player.splash"
};
self.audio.play(name, Some(feet), volume, pitch);
}
MotionEvent::SplashParticle {
bubble,
position,
velocity,
} => {
use horizon_client::particles::{ParticleOptions, ParticleType};
let kind = if bubble {
ParticleType::Bubble
} else {
ParticleType::Splash
};
self.particles.add(
&ParticleOptions::simple(kind),
[position.x, position.y, position.z],
[velocity.x, velocity.y, velocity.z],
);
}
_ => {}
}
}
+3 -3
View File
@@ -219,7 +219,7 @@ impl FallDamageWorld for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
type State = BlockStateId;
fn is_in_water(&mut self) -> Result<bool> {
Ok(false)
Ok(self.player.fluids.was_touching_water)
}
fn fall_distance(&self) -> f64 {
self.player.fall_distance
@@ -253,8 +253,8 @@ impl FallDamageWorld for MotionWorld<'_, '_, '_> {
}
impl LivingLandingWorld for MotionWorld<'_, '_, '_> {
fn update_fluid_interaction(&mut self) -> Result<bool> {
Ok(false)
} // dry scene
self.update_fluids()
}
fn is_server_level(&self) -> bool {
true
}
+116 -45
View File
@@ -44,15 +44,17 @@ use std::{
};
pub(crate) mod environment;
mod fluids;
pub use fluids::{FluidResources, LAVA, PlayerFluids, WATER};
pub struct MotionResources {
pub facts: crate::blocks::BlockFacts,
pub attributes: Arc<Catalog>,
pub blocks: BoundMovementProperties,
pub climbable: BTreeSet<String>,
pub fall_reset: BTreeSet<String>,
pub landing: BlockLandingRegistry,
pub health: crate::health::HealthResources,
pub fluids: FluidResources,
}
impl MotionResources {
pub fn load(root: &Path, assets: &Assets) -> Result<Self> {
@@ -87,9 +89,9 @@ impl MotionResources {
.collect())
};
Ok(Self {
facts: crate::blocks::BlockFacts::load(root, assets.registry)?,
landing: crate::landing::load(root, &properties)?,
health: crate::health::HealthResources::load(root)?,
fluids: FluidResources::load(root, assets)?,
attributes,
blocks: properties.bind(&MovementTags {
fences: tag("minecraft:fences")?,
@@ -155,12 +157,23 @@ pub enum MotionEvent {
position: BlockPos,
fall_distance: f64,
},
/// `Entity.doWaterSplashEffect`: the player's splash (or high-speed
/// splash) sound at its position...
Splash {
high_speed: bool,
volume: f32,
pitch: f32,
},
/// ...its BUBBLE (else SPLASH) particles...
SplashParticle {
bubble: bool,
position: Vec3,
velocity: Vec3,
},
/// ...and the SPLASH game event.
SplashEvent,
}
pub struct PlayerMotion {
pub fluids: horizon_world::entity_fluid::EntityFluidInteraction,
pub in_water: bool,
pub eye_in_water: bool,
pub in_lava: bool,
pub swimming: bool,
pub fire_ticks: i32,
pub air: i32,
@@ -227,6 +240,8 @@ pub struct PlayerMotion {
pub health: crate::health::PlayerHealth,
/// Status effects and armor protection seen by movement and damage.
pub status: crate::effects::StatusFlags,
/// Water and lava around the player (`Entity.fluidInteraction`).
pub fluids: PlayerFluids,
/// `Entity.isInPowderSnow` / `wasInPowderSnow`.
pub in_powder_snow: bool,
pub was_in_powder_snow: bool,
@@ -344,13 +359,6 @@ impl PlayerMotion {
local_crouching: false,
pose: crate::pose::Pose::Standing,
dimensions: crate::pose::Pose::Standing.dimensions(1.0),
fluids: horizon_world::entity_fluid::EntityFluidInteraction::new([
environment::WATER,
environment::LAVA,
]),
in_water: false,
eye_in_water: false,
in_lava: false,
swimming: false,
fire_ticks: -20,
air: 300,
@@ -366,6 +374,7 @@ impl PlayerMotion {
sync_position: false,
events: Vec::new(),
attributes,
fluids: PlayerFluids::default(),
in_powder_snow: false,
was_in_powder_snow: false,
ticks_frozen: 0,
@@ -516,8 +525,8 @@ impl PlayerMotion {
horizontal_collision: self.collision.horizontal,
minor_horizontal_collision: self.collision.minor,
moving_slowly: self.moving_slowly(),
in_water: self.in_water,
under_water: self.eye_in_water,
in_water: self.fluids.was_touching_water,
under_water: self.is_eye_in_fluid(WATER),
swimming: self.swimming,
..Default::default()
};
@@ -644,6 +653,14 @@ impl MotionWorld<'_, '_, '_> {
/// caller applies LocalPlayer input preparation once. Empty inventory,
/// equipment and nearby-entity sets are the current scene domain.
pub fn player_movement_tick(&mut self, direction: [f32; 2], jumping: bool) -> Result<()> {
self.fluid_base_tick()?;
self.player_movement_tick_with_fluids(direction, jumping)
}
fn player_movement_tick_with_fluids(
&mut self,
direction: [f32; 2],
jumping: bool,
) -> Result<()> {
// Entity.baseTick
self.player.was_in_powder_snow = self.player.in_powder_snow;
self.player.in_powder_snow = false;
@@ -676,8 +693,8 @@ impl MotionWorld<'_, '_, '_> {
let can_glide = self.player.glider
&& !self.player.ground.on_ground
&& !self.player.flying
&& !self.player.in_water
&& !self.player.in_lava;
&& !self.player.fluids.was_touching_water
&& !self.player.is_in_lava();
if jumping && !toggled && !was_jumping && !self.player.fall_flying && can_glide {
self.player.fall_flying = true;
}
@@ -687,8 +704,8 @@ impl MotionWorld<'_, '_, '_> {
let still = self.player.glider
&& !self.player.ground.on_ground
&& !self.player.flying
&& !self.player.in_water
&& !self.player.in_lava;
&& !self.player.fluids.was_touching_water
&& !self.player.is_in_lava();
if !still {
self.player.fall_flying = false;
} else if (self.player.fall_fly_ticks + 1) % 10 == 0
@@ -727,7 +744,7 @@ impl MotionWorld<'_, '_, '_> {
/// Resident simulation phases in native order. Enclosing entity/world tick
/// services are still incomplete; this composes clocks, movement and hunger.
pub fn simulation_tick(&mut self, direction: [f32; 2], jumping: bool) -> Result<()> {
self.update_fluid_environment()?;
self.fluid_base_tick()?;
self.simulation_tick_with_fluids(direction, jumping)
}
fn simulation_tick_with_fluids(&mut self, direction: [f32; 2], jumping: bool) -> Result<()> {
@@ -735,11 +752,11 @@ impl MotionWorld<'_, '_, '_> {
self.tick_environment_damage()?;
let previous = self.player.position;
self.player.swimming = self.player.sprinting
&& self.player.in_water
&& (self.player.swimming || self.player.eye_in_water)
&& self.player.fluids.was_touching_water
&& (self.player.swimming || self.player.is_eye_in_fluid(WATER))
&& !self.player.flying
&& !self.player.spectator;
self.player_movement_tick(direction, jumping)?;
self.player_movement_tick_with_fluids(direction, jumping)?;
self.apply_fire_contact()?;
self.player.refresh_attributes()?;
self.update_player_pose()?;
@@ -759,7 +776,7 @@ impl MotionWorld<'_, '_, '_> {
self.player.auto_jump_time -= 1;
keys.jump = true;
}
self.update_fluid_environment()?;
self.fluid_base_tick()?;
self.player.sprint_input_tick(keys)?;
self.player.shift_key_down = keys.shift;
let direction = keys.direction();
@@ -808,20 +825,22 @@ impl MotionWorld<'_, '_, '_> {
input.x = 0.0;
input.z = 0.0;
}
if self.player.shift_key_down && !self.player.flying && self.player.in_water {
if self.player.shift_key_down
&& !self.player.flying
&& self.player.fluids.was_touching_water
{
self.player.velocity.y -= f64::from(0.04f32);
}
if self.player.jumping {
let height = self.player.fluids.fluid_height(
self,
if self.player.in_water {
environment::WATER
let height = self
.player
.fluid_height(if self.player.fluids.was_touching_water {
WATER
} else {
environment::LAVA
},
);
LAVA
});
if !self.player.flying
&& (self.player.in_water || self.player.in_lava)
&& (self.player.fluids.was_touching_water || self.player.is_in_lava())
&& (!self.player.ground.on_ground || height > 0.4)
{
self.player.velocity.y += f64::from(0.04f32);
@@ -842,7 +861,7 @@ impl MotionWorld<'_, '_, '_> {
));
if look_y <= 0.0
|| self.player.jumping
|| self.fluid_at(near_surface)?.kind() != horizon_world::fluid::FluidKind::Empty
|| self.fluid_at(near_surface).kind() != horizon_world::fluid::FluidKind::Empty
{
let blend = if look_y < -0.2 { 0.085 } else { 0.06 };
self.player.velocity.y += (look_y - self.player.velocity.y) * blend;
@@ -855,7 +874,9 @@ impl MotionWorld<'_, '_, '_> {
let y = self.player.velocity.y;
self.travel_in_air(input)?;
self.player.velocity.y = y * 0.6;
} else if !self.player.flying && (self.player.in_water || self.player.in_lava) {
} else if !self.player.flying
&& (self.player.fluids.was_touching_water || self.player.is_in_lava())
{
horizon_world::living_fluid::travel_in_fluid(self, input)?;
} else {
self.travel_in_air(input)?;
@@ -1318,10 +1339,10 @@ impl MovementStatisticsWorld for MotionWorld<'_, '_, '_> {
Ok(self.player.swimming)
}
fn eyes_in_water(&mut self) -> Result<bool> {
Ok(self.player.eye_in_water)
Ok(self.player.is_eye_in_fluid(WATER))
}
fn in_water(&mut self) -> Result<bool> {
Ok(self.player.in_water)
Ok(self.player.fluids.was_touching_water)
}
fn on_climbable(&mut self) -> Result<bool> {
self.climbable()
@@ -1444,15 +1465,21 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> {
self.player.fall_distance
}
fn fall_reset_clip(&mut self, from: Vec3, to: Vec3) -> Result<bool> {
// Fluid immersion is handled before travel. Tagged reset blocks use
// a full block in ClipContext.FALLDAMAGE_RESETTING, not their collider.
// ClipContext.Block.FALLDAMAGE_RESETTING: tagged reset blocks are a full
// block, not their collider; ClipContext.Fluid.WATER: the water's shape.
// Both shapes are queried for every visited block (the water's first
// query fixes its cached shape), either one hitting ends the ray.
let hit = traverse_blocks(from, to, 1_000_000, |p| {
let water = match self.water_clip(from, to, p) {
Ok(hit) => hit,
Err(e) => return Some(Err(e)),
};
let name = &self.assets.registry.state(self.block(p)).unwrap().name;
(self.resources.fall_reset.contains(name)
&& VoxelShape::block().clip(from, to, p).is_some())
.then_some(())
let reset = self.resources.fall_reset.contains(name)
&& VoxelShape::block().clip(from, to, p).is_some();
(water || reset).then_some(Ok(()))
})?;
Ok(hit.is_some())
hit.transpose().map(|h| h.is_some())
}
fn reset_fall_distance(&mut self) -> Result<()> {
self.player.fall_distance = 0.0;
@@ -1643,7 +1670,7 @@ impl MovementEmissionWorld for MotionWorld<'_, '_, '_> {
Ok(self.player.swimming)
}
fn in_water(&mut self) -> Result<bool> {
Ok(self.player.in_water)
Ok(self.player.fluids.was_touching_water)
}
fn walking_step_sound(&mut self, position: BlockPos, state: BlockStateId) -> Result<()> {
self.player
@@ -1999,6 +2026,46 @@ mod tests {
/// Footsteps on the prepared vanilla resources, when they are present:
/// none while standing (gravity still moves the player every tick), one
/// per `nextStep` metre while walking.
#[test]
fn resident_water_landing_cancels_a_preset_fall() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
if !root.join("movement-properties.nbt").exists() {
return;
}
let assets = Assets::load(&root).unwrap();
let binding = crate::collisions::load(&root, assets.registry).unwrap();
let resources = MotionResources::load(&root, &assets).unwrap();
for wet in [false, true] {
let mut scene = World::test_scene(&assets, 2).unwrap();
if wet {
let water = assets.registry.default_state("minecraft:water").unwrap();
for x in 19..=21 {
for z in 19..=21 {
scene.set(x, 3, z, water).unwrap();
}
}
}
let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 20.0, 20.5)).unwrap();
player.fall_distance = 30.0;
let mut w = MotionWorld {
player: &mut player,
scene: &mut scene,
assets: &assets,
collision_binding: &binding,
resources: &resources,
};
w.move_self(Vec3::new(0.0, -30.0, 0.0)).unwrap();
assert!(w.player.ground.on_ground);
assert_eq!(w.player.fluids.was_touching_water, wet);
if wet {
assert_eq!(w.player.health.health(), 20.0);
assert_eq!(w.player.fall_distance, 0.0);
} else {
assert!(w.player.health.health() < 20.0);
}
}
}
#[test]
fn resident_water_and_lava_are_not_treated_as_air() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
@@ -2031,6 +2098,10 @@ mod tests {
"resident water must reach the player movement adapter"
);
assert!(MovementStatisticsWorld::eyes_in_water(&mut w).unwrap());
assert!(
!w.player.fluids.was_eye_in_water,
"the first controlled tick must run only one fluid base phase"
);
assert!(
(w.player.velocity.y + 0.005).abs() < 1e-5,
"water drag/gravity must replace air travel: {:?}",
@@ -2198,7 +2269,7 @@ mod tests {
let mut respawn = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap();
respawn.load_environment_once(&mut pending, Some(&extra));
assert_eq!((respawn.fire_ticks, respawn.air), (-20, 300));
w.player.in_water = false;
w.player.fluids.was_touching_water = false;
assert!(
w.player.moving_slowly(),
"dry crawling must still slow input"
+15 -171
View File
@@ -1,55 +1,11 @@
//! Resident bindings for the existing native immersion, current and liquid-travel kernels.
//! Player liquid travel and environmental damage over the shared fluid state.
use super::*;
use horizon_core::{geometry::Direction, random::RandomSource};
use horizon_core::random::RandomSource;
use horizon_world::{
entity_fluid::{
CurrentTarget, FluidInteractionWorld, FluidMembership, FluidSections, FluidTagId,
},
fluid::{FluidHeightWorld, FluidKind, FluidState},
fluid_flow::{FluidFlowWorld, flow_at},
fluid::FluidKind,
living_fluid::{LivingFluidWorld, TravelFluidTag},
};
pub(super) const WATER: FluidTagId = FluidTagId(0);
pub(super) const LAVA: FluidTagId = FluidTagId(1);
impl MotionWorld<'_, '_, '_> {
pub(super) fn fluid_at(&self, p: BlockPos) -> Result<FluidState> {
Ok(FluidState::from_block(
self.assets
.registry
.state(self.block(p))
.ok_or("missing fluid state")?,
)?)
}
pub(super) fn update_fluid_environment(&mut self) -> Result<()> {
let mut fluids = std::mem::take(&mut self.player.fluids);
let result = fluids
.update(self, false, 4096)
.map_err(|e| io::Error::other(e.to_string()));
if let Err(e) = result {
self.player.fluids = fluids;
return Err(e.into());
}
self.player.in_water = fluids.is_in_fluid(self, WATER);
self.player.in_lava = fluids.is_in_fluid(self, LAVA);
self.player.eye_in_water = fluids.is_eye_in_fluid(self, WATER);
if self.player.in_water {
self.player.fall_distance = 0.0;
}
if !self.player.flying && !self.player.spectator {
fluids.apply_current(self, WATER, 0.014)?;
fluids.apply_current(
self,
LAVA,
if self.scene.fast_lava {
0.007
} else {
0.0023333333333333335
},
)?;
}
self.player.fluids = fluids;
Ok(())
}
fn environment_hurt(&mut self, source: &str, damage: f32) -> Result<()> {
if self.player.invulnerable || self.player.spectator {
return Ok(());
@@ -65,19 +21,19 @@ impl MotionWorld<'_, '_, '_> {
Ok(())
}
pub(super) fn tick_environment_damage(&mut self) -> Result<()> {
if self.player.in_water || self.player.spectator {
if self.player.fluids.was_touching_water || self.player.spectator {
self.player.fire_ticks = 0;
}
if self.player.invulnerable && self.player.fire_ticks > 1 {
self.player.fire_ticks = 1;
}
if self.player.fire_ticks > 0 {
if self.player.fire_ticks % 20 == 0 && !self.player.in_lava {
if self.player.fire_ticks % 20 == 0 && !self.player.is_in_lava() {
self.environment_hurt("minecraft:on_fire", 1.0)?;
}
self.player.fire_ticks -= 1;
}
if self.player.eye_in_water
if self.player.is_eye_in_fluid(WATER)
&& !self.player.status.water_breathing
&& !self.player.invulnerable
&& !self.player.spectator
@@ -96,10 +52,9 @@ impl MotionWorld<'_, '_, '_> {
} else {
self.player.air = (self.player.air + 4).min(300);
}
if self.player.in_lava {
if self.player.is_in_lava() {
self.player.ignite_for_ticks(300)?;
self.environment_hurt("minecraft:lava", 4.0)?;
self.player.fall_distance *= 0.5;
}
Ok(())
}
@@ -111,7 +66,7 @@ impl MotionWorld<'_, '_, '_> {
let damage = fire_contact(self.scene, self.assets.registry, self.player.bounds());
if damage > 0.0 {
self.player.ticks_frozen = 0;
if !self.player.in_water {
if !self.player.fluids.was_touching_water {
let multiplier = self.player.attribute("minecraft:burning_time")?;
let ticks = ignite_contact(
self.player.fire_ticks,
@@ -153,117 +108,9 @@ pub(crate) fn fire_contact(
}
damage
}
impl FluidMembership for MotionWorld<'_, '_, '_> {
fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool {
if tag == WATER {
matches!(kind, FluidKind::Water | FluidKind::FlowingWater)
} else {
matches!(kind, FluidKind::Lava | FluidKind::FlowingLava)
}
}
}
impl CurrentTarget for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
fn is_player_class(&self) -> bool {
true
}
fn velocity(&mut self) -> Result<Vec3> {
Ok(self.player.velocity)
}
fn add_delta_movement(&mut self, v: Vec3) -> Result<()> {
let old = self.player.velocity;
self.player.velocity = Vec3::new(old.x + v.x, old.y + v.y, old.z + v.z);
Ok(())
}
}
impl FluidInteractionWorld for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
type Chunk = (i32, i32);
fn interaction_box(&mut self) -> Result<Option<Aabb>> {
Ok(Some(
self.player.bounds().deflate(Vec3::new(1e-5, 1e-5, 1e-5)),
))
}
fn loaded_chunk(&mut self, x: i32, z: i32) -> Result<Option<Self::Chunk>> {
Ok(self.scene.chunks.contains_key(&(x, z)).then_some((x, z)))
}
fn chunk_sections(&mut self, _: Self::Chunk) -> Result<FluidSections<'_>> {
// Resident sections have no fluid-count cache; scan the small interaction box rather than skipping sections.
static SECTIONS: [bool; crate::chunk::SECTIONS] = [true; crate::chunk::SECTIONS];
Ok(FluidSections {
minimum_section_y: crate::chunk::MIN_Y >> 4,
has_fluid: &SECTIONS,
})
}
fn bounding_box_min_y(&self) -> f64 {
self.player.bounds().min_position().y
}
fn block_x(&self) -> i32 {
self.player.position.x.floor() as i32
}
fn block_z(&self) -> i32 {
self.player.position.z.floor() as i32
}
fn eye_y(&mut self) -> Result<f64> {
Ok(self.player.position.y + f64::from(self.player.dimensions.eye_height))
}
fn fluid_state(&mut self, p: BlockPos) -> Result<FluidState> {
self.fluid_at(p)
}
fn fluid_height(&mut self, f: FluidState, p: BlockPos) -> Result<f32> {
f.height_at(self, [p.x, p.y, p.z])
}
fn camera_height(&mut self, f: FluidState, p: BlockPos) -> Result<f32> {
f.camera_height_at(self, [p.x, p.y, p.z])
}
fn flow(&mut self, f: FluidState, p: BlockPos) -> Result<Vec3> {
flow_at(self, f, p)
}
}
impl FluidHeightWorld for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
fn fluid(&mut self, p: [i32; 3]) -> Result<FluidState> {
self.fluid_at(BlockPos::new(p[0], p[1], p[2]))
}
fn sturdy_down(&mut self, p: [i32; 3]) -> Result<bool> {
Ok(self
.resources
.facts
.get(MotionWorld::block(self, BlockPos::new(p[0], p[1], p[2])))
.sturdy_full
& 1
!= 0)
}
}
impl FluidFlowWorld for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
type Block = BlockStateId;
fn fluid(&mut self, p: BlockPos) -> Result<FluidState> {
self.fluid_at(p)
}
fn block(&mut self, p: BlockPos) -> Result<BlockStateId> {
Ok(MotionWorld::block(self, p))
}
fn blocks_fluid_flow(&self, s: BlockStateId) -> bool {
self.assets
.blocks_fluid_flow
.contains(&self.assets.registry.state(s).unwrap().name)
}
fn is_ice_class(&self, s: BlockStateId) -> bool {
self.resources
.facts
.get(s)
.classes
.iter()
.any(|c| c.as_ref() == "IceBlock")
}
fn is_face_sturdy(&mut self, s: BlockStateId, _: BlockPos, d: Direction) -> Result<bool> {
Ok(self.resources.facts.get(s).sturdy_full & (1 << d as u8) != 0)
}
}
impl LivingFluidWorld for MotionWorld<'_, '_, '_> {
fn in_water(&mut self) -> Result<bool> {
Ok(self.player.in_water)
Ok(self.player.fluids.was_touching_water)
}
fn sprinting(&mut self) -> Result<bool> {
Ok(self.player.sprinting)
@@ -278,14 +125,11 @@ impl LivingFluidWorld for MotionWorld<'_, '_, '_> {
Ok(self.player.status.dolphins_grace)
}
fn fluid_height(&mut self, tag: TravelFluidTag) -> Result<f64> {
Ok(self.player.fluids.fluid_height(
self,
if tag == TravelFluidTag::Lava {
LAVA
} else {
WATER
},
))
Ok(self.player.fluid_height(if tag == TravelFluidTag::Lava {
LAVA
} else {
WATER
}))
}
fn fluid_jump_threshold(&mut self) -> Result<f64> {
Ok(0.4)
@@ -306,7 +150,7 @@ impl MotionWorld<'_, '_, '_> {
for x in b.min_position().x.floor() as i32..=b.max_position().x.floor() as i32 {
for y in b.min_position().y.floor() as i32..=b.max_position().y.floor() as i32 {
for z in b.min_position().z.floor() as i32..=b.max_position().z.floor() as i32 {
if self.fluid_at(BlockPos::new(x, y, z))?.kind() != FluidKind::Empty {
if self.fluid_at(BlockPos::new(x, y, z)).kind() != FluidKind::Empty {
return Ok(true);
}
}
+334
View File
@@ -0,0 +1,334 @@
//! The player's fluid immersion over the resident scene: `Entity.updateFluidInteraction`
//! (water, waterlogged blocks, bubble columns and lava, with their currents), the
//! water-entry splash and the fall resets that hinge on touching water.
use super::*;
use horizon_world::{
entity_fluid::{
CurrentTarget, EntityFluidInteraction, FluidInteractionWorld, FluidMembership,
FluidSections, FluidTagId,
},
entity_fluid_tick::{self, EntityFluidTickWorld},
fluid::{FluidHeightWorld, FluidKind, FluidState, FluidStateTable},
fluid_flow::{FluidFlowWorld, flow_at},
fluid_shape::FluidShapeCache,
water_splash::{self, SplashParticle, WaterSplashWorld},
};
use std::sync::Mutex;
/// `FluidTags.WATER` and `FluidTags.LAVA`, the fluids with a current.
pub const WATER: FluidTagId = FluidTagId(0);
pub const LAVA: FluidTagId = FluidTagId(1);
/// Per-state fluid facts the player's immersion and fall-reset rays read.
pub struct FluidResources {
states: FluidStateTable,
/// `isFaceSturdy(FULL)` per `Direction` (bit = ordinal).
sturdy: Vec<u8>,
/// `#minecraft:blocks_fluid_flow` membership.
blocks_flow: Vec<bool>,
/// `IceBlock` and its subclasses.
ice: Vec<bool>,
/// `FlowingFluid.shapes`: the shape of the first query of each fluid
/// state, kept for the whole process like the registered fluid's map.
pub shapes: Mutex<FluidShapeCache>,
}
impl FluidResources {
pub fn load(root: &Path, assets: &Assets) -> Result<Self> {
let facts = crate::blocks::BlockFacts::load(root, assets.registry)?;
Ok(Self {
states: FluidStateTable::new(assets.registry)?,
sturdy: facts.states.iter().map(|s| s.sturdy_full).collect(),
blocks_flow: facts
.states
.iter()
.map(|s| assets.blocks_fluid_flow.contains(&*s.name))
.collect(),
ice: facts
.states
.iter()
.map(|s| s.has_class("IceBlock"))
.collect(),
shapes: Mutex::new(FluidShapeCache::default()),
})
}
pub fn fluid(&self, state: BlockStateId) -> FluidState {
self.states.get(state).unwrap_or(FluidState::EMPTY)
}
fn sturdy(&self, state: BlockStateId, d: Direction) -> bool {
self.sturdy
.get(state.0 as usize)
.is_some_and(|s| s & 1 << d as u8 != 0)
}
}
/// The player's `EntityFluidInteraction` and the water flags around it.
pub struct PlayerFluids {
pub interaction: EntityFluidInteraction,
/// `Entity.wasTouchingWater` (`isInWater`).
pub was_touching_water: bool,
/// `Entity.wasEyeInWater`.
pub was_eye_in_water: bool,
/// `Entity.firstTick`: no splash, and no lava, until the first base tick ends.
pub first_tick: bool,
/// The dimension's `FAST_LAVA` (the Nether), set by the game.
pub fast_lava: bool,
}
impl Default for PlayerFluids {
fn default() -> Self {
Self {
interaction: EntityFluidInteraction::new([WATER, LAVA]),
was_touching_water: false,
was_eye_in_water: false,
first_tick: true,
fast_lava: false,
}
}
}
fn is_tagged(kind: FluidKind, tag: FluidTagId) -> bool {
if tag == WATER {
matches!(kind, FluidKind::Water | FluidKind::FlowingWater)
} else {
matches!(kind, FluidKind::Lava | FluidKind::FlowingLava)
}
}
impl PlayerMotion {
pub fn fluid_height(&self, tag: FluidTagId) -> f64 {
self.fluids.interaction.fluid_height(&Membership, tag)
}
pub fn is_eye_in_fluid(&self, tag: FluidTagId) -> bool {
self.fluids.interaction.is_eye_in_fluid(&Membership, tag)
}
/// `Entity.isInLava`.
pub fn is_in_lava(&self) -> bool {
!self.fluids.first_tick && self.fluids.interaction.is_in_fluid(&Membership, LAVA)
}
}
struct Membership;
impl FluidMembership for Membership {
fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool {
is_tagged(kind, tag)
}
}
impl MotionWorld<'_, '_, '_> {
pub(super) fn fluid_at(&self, p: BlockPos) -> FluidState {
self.resources.fluids.fluid(self.block(p))
}
/// `Entity.baseTick`'s fluid phase: `wasEyeInWater`, `updateFluidInteraction`,
/// the lava's fall halving, and the end of the first tick.
pub fn fluid_base_tick(&mut self) -> Result<()> {
self.player.fluids.was_eye_in_water = self.player.is_eye_in_fluid(WATER);
self.update_fluids()?;
if self.player.is_in_lava() {
self.player.fall_distance *= 0.5;
}
self.player.fluids.first_tick = false;
Ok(())
}
/// `Entity.updateFluidInteraction`: immersion heights, then touching water
/// resets the fall and splashes on entry, then the currents push.
pub fn update_fluids(&mut self) -> Result<bool> {
let mut interaction = std::mem::take(&mut self.player.fluids.interaction);
let result = entity_fluid_tick::update(&mut interaction, self, WATER, LAVA, 1_000_000);
self.player.fluids.interaction = interaction;
result.map_err(|e| e.to_string().into())
}
/// `ClipContext.Fluid.WATER` in a fall-reset ray: the water's shape.
pub(super) fn water_clip(&mut self, from: Vec3, to: Vec3, p: BlockPos) -> Result<bool> {
let fluid = self.fluid_at(p);
if !is_tagged(fluid.kind(), WATER) {
return Ok(false);
}
let resources = self.resources;
let shape = resources
.fluids
.shapes
.lock()
.map_err(|_| "fluid shape cache poisoned")?
.shape(self, fluid, p)?;
Ok(shape.clip(from, to, p).is_some())
}
}
impl FluidMembership for MotionWorld<'_, '_, '_> {
fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool {
is_tagged(kind, tag)
}
}
impl CurrentTarget for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
fn is_player_class(&self) -> bool {
true
}
fn velocity(&mut self) -> Result<Vec3> {
Ok(self.player.velocity)
}
fn add_delta_movement(&mut self, delta: Vec3) -> Result<()> {
// Entity.addDeltaMovement and setDeltaMovement keep only finite values.
let v = self.player.velocity;
let sum = Vec3::new(v.x + delta.x, v.y + delta.y, v.z + delta.z);
if delta.is_finite() && sum.is_finite() {
self.player.velocity = sum;
}
Ok(())
}
}
impl FluidInteractionWorld for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
type Chunk = ();
fn interaction_box(&mut self) -> Result<Option<Aabb>> {
// Entity.getFluidInteractionBox (not riding).
Ok(Some(
self.player.bounds().deflate(Vec3::new(0.001, 0.001, 0.001)),
))
}
fn loaded_chunk(&mut self, x: i32, z: i32) -> Result<Option<()>> {
Ok(self.scene.chunks.contains_key(&(x, z)).then_some(()))
}
fn chunk_sections(&mut self, _: ()) -> Result<FluidSections<'_>> {
// Resident sections keep no fluid count: scanning the box finds no
// fluid where a section without fluid would have skipped it.
static SECTIONS: [bool; crate::chunk::SECTIONS] = [true; crate::chunk::SECTIONS];
Ok(FluidSections {
minimum_section_y: crate::chunk::MIN_Y >> 4,
has_fluid: &SECTIONS,
})
}
fn bounding_box_min_y(&self) -> f64 {
self.player.bounds().min_position().y
}
fn block_x(&self) -> i32 {
self.player.position.x.floor() as i32
}
fn eye_y(&mut self) -> Result<f64> {
Ok(self.player.position.y + f64::from(self.player.dimensions.eye_height))
}
fn block_z(&self) -> i32 {
self.player.position.z.floor() as i32
}
fn fluid_state(&mut self, p: BlockPos) -> Result<FluidState> {
Ok(self.fluid_at(p))
}
fn fluid_height(&mut self, f: FluidState, p: BlockPos) -> Result<f32> {
f.height_at(self, [p.x, p.y, p.z])
}
fn camera_height(&mut self, f: FluidState, p: BlockPos) -> Result<f32> {
f.camera_height_at(self, [p.x, p.y, p.z])
}
fn flow(&mut self, f: FluidState, p: BlockPos) -> Result<Vec3> {
flow_at(self, f, p)
}
}
impl EntityFluidTickWorld for MotionWorld<'_, '_, '_> {
/// `Player.isPushedByFluid`: not while flying.
fn is_pushed_by_fluid(&mut self) -> Result<bool> {
Ok(!self.player.flying)
}
fn reset_fall_distance(&mut self) -> Result<()> {
self.player.fall_distance = 0.0;
Ok(())
}
fn was_touching_water(&self) -> bool {
self.player.fluids.was_touching_water
}
fn first_tick(&self) -> bool {
self.player.fluids.first_tick
}
fn water_splash(&mut self) -> Result<()> {
water_splash::water_splash(self, 1_000_000).map_err(|e| e.to_string())?;
Ok(())
}
fn set_was_touching_water(&mut self, value: bool) {
self.player.fluids.was_touching_water = value;
}
fn fast_lava(&mut self) -> Result<bool> {
Ok(self.player.fluids.fast_lava)
}
}
impl FluidHeightWorld for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
fn fluid(&mut self, p: [i32; 3]) -> Result<FluidState> {
Ok(self.fluid_at(BlockPos::new(p[0], p[1], p[2])))
}
fn sturdy_down(&mut self, p: [i32; 3]) -> Result<bool> {
let state = MotionWorld::block(self, BlockPos::new(p[0], p[1], p[2]));
Ok(self.resources.fluids.sturdy(state, Direction::Down))
}
}
impl FluidFlowWorld for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
type Block = BlockStateId;
fn fluid(&mut self, p: BlockPos) -> Result<FluidState> {
Ok(self.fluid_at(p))
}
fn block(&mut self, p: BlockPos) -> Result<BlockStateId> {
Ok(MotionWorld::block(self, p))
}
fn blocks_fluid_flow(&self, s: BlockStateId) -> bool {
self.resources
.fluids
.blocks_flow
.get(s.0 as usize)
.copied()
.unwrap_or(false)
}
fn is_ice_class(&self, s: BlockStateId) -> bool {
self.resources
.fluids
.ice
.get(s.0 as usize)
.copied()
.unwrap_or(false)
}
fn is_face_sturdy(&mut self, s: BlockStateId, _: BlockPos, d: Direction) -> Result<bool> {
Ok(self.resources.fluids.sturdy(s, d))
}
}
/// `Entity.doWaterSplashEffect` for the player: the world random draws the
/// pitch and particle offsets.
impl WaterSplashWorld for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
type Entity = ();
/// `Player.getSwimHighSpeedSplashSound` when true, else `getSwimSplashSound`.
type Sound = bool;
fn this_entity(&self) {}
fn controlling_passenger(&mut self) -> Result<Option<()>> {
Ok(None)
}
fn velocity(&mut self, _: ()) -> Result<Vec3> {
Ok(self.player.velocity)
}
fn splash_sound(&mut self, high_speed: bool) -> Result<bool> {
Ok(high_speed)
}
fn random_float(&mut self) -> Result<f32> {
Ok(self.scene.random.next_float())
}
fn random_double(&mut self) -> Result<f64> {
Ok(self.scene.random.next_double())
}
fn play_sound(&mut self, high_speed: bool, volume: f32, pitch: f32) -> Result<()> {
self.player.events.push(MotionEvent::Splash {
high_speed,
volume,
pitch,
});
Ok(())
}
fn position(&self) -> Vec3 {
self.player.position
}
fn width(&self) -> f32 {
self.player.dimensions.width
}
fn particle(&mut self, kind: SplashParticle, position: Vec3, velocity: Vec3) -> Result<()> {
self.player.events.push(MotionEvent::SplashParticle {
bubble: matches!(kind, SplashParticle::Bubble),
position,
velocity,
});
Ok(())
}
fn splash_event(&mut self) -> Result<()> {
// The SPLASH game event: sculk listens to the player's moves itself.
self.player.events.push(MotionEvent::SplashEvent);
Ok(())
}
}
+1 -1
View File
@@ -72,7 +72,7 @@ impl PlayerMotion {
Ok(())
}
pub fn moving_slowly(&self) -> bool {
self.local_crouching || (self.pose == Pose::Swimming && !self.in_water)
self.local_crouching || (self.pose == Pose::Swimming && !self.fluids.was_touching_water)
}
}
impl MotionWorld<'_, '_, '_> {
@@ -33,7 +33,7 @@ import static dev.horizonlab.parity.VanillaRegistryCollisionScanOracle.*;
* full death services remain controlled boundaries. Clock operations set up the
* two damage-clock fields, not the complete enclosing native tick methods. */
public final class VanillaSceneMotionOracle {
static Field position,history,support,noBlocks,last,stuck,delay,trigger,attributeStorage,attributeDirty,attributeCached,impact,grace;
static Field blockPositionField,position,history,support,noBlocks,last,stuck,delay,trigger,attributeStorage,attributeDirty,attributeCached,impact,grace;
static MethodHandle aiStep;
static Method refreshAttributes;
static EntityDataAccessor<Float> healthKey,absorptionKey;
@@ -71,6 +71,7 @@ public final class VanillaSceneMotionOracle {
static String vectorBits(Vec3 p){return String.format("%016x,%016x,%016x",Double.doubleToLongBits(p.x),Double.doubleToLongBits(p.y),Double.doubleToLongBits(p.z));}
static String soundName(SoundEvent s){
if(s==SoundEvents.PLAYER_SMALL_FALL)return "small";if(s==SoundEvents.PLAYER_BIG_FALL)return "big";
if(s==SoundEvents.PLAYER_SPLASH)return "splash";if(s==SoundEvents.PLAYER_SPLASH_HIGH_SPEED)return "splash-high";
return VanillaBlockLandingOracle.sound(s);
}
static final class Sources extends DamageSources {
@@ -107,6 +108,15 @@ public final class VanillaSceneMotionOracle {
@Override public BlockGetter getChunkForCollisions(int x,int z){return chunks.get(key(x,z));}
@Override public BlockState getBlockState(BlockPos p){var c=chunks.get(key(p.getX()>>4,p.getZ()>>4));return c==null?Blocks.AIR.defaultBlockState():c.getBlockState(p);}
@Override public FluidState getFluidState(BlockPos p){return getBlockState(p).getFluidState();}
// No dimension layers: FAST_LAVA keeps its default (the Overworld's slow lava).
static final net.minecraft.world.attribute.EnvironmentAttributeSystem ATTRIBUTES=net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().build();
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes(){return ATTRIBUTES;}
// EntityFluidInteraction.hasFluidAndLoaded: resident chunks only.
@Override public net.minecraft.world.level.chunk.ChunkAccess getChunk(int x,int z,net.minecraft.world.level.chunk.status.ChunkStatus status,boolean load){return chunks.get(key(x,z));}
// Entity.doWaterSplashEffect's particles (a client level adds them).
@Override public void addParticle(net.minecraft.core.particles.ParticleOptions particle,double x,double y,double z,double xd,double yd,double zd){
actor.events.add("splash-particle "+(particle==net.minecraft.core.particles.ParticleTypes.BUBBLE?"bubble":particle==net.minecraft.core.particles.ParticleTypes.SPLASH?"splash":"unknown")+" "+vectorBits(new Vec3(x,y,z))+" "+vectorBits(new Vec3(xd,yd,zd)));
}
@Override public List<VoxelShape> getEntityCollisions(Entity e,AABB b){return List.of();}
@Override public List<Entity> getPushableEntities(Entity e,AABB b){return List.of();}
@Override public List<Entity> getEntities(Entity e,AABB b){return e!=actor&&b.intersects(actor.getBoundingBox())?List.of(actor):List.of();}
@@ -162,7 +172,7 @@ public final class VanillaSceneMotionOracle {
@Override public CombatTracker getCombatTracker(){return tracker;}
@Override public net.minecraft.server.PlayerAdvancements getAdvancements(){events.add("hurt-criterion");return advancements;}
@Override public void onSyncedDataUpdated(EntityDataAccessor<?> key){if(key!=healthKey&&key!=absorptionKey)throw new AssertionError(key);events.add(String.format("updated %d %08x %s",key.id(),Float.floatToIntBits(getEntityData().get(key==healthKey?healthKey:absorptionKey)),getEntityData().isDirty()));}
@Override public void gameEvent(Holder<GameEvent> event){if(event==GameEvent.ENTITY_DAMAGE)events.add("entity-damage");else super.gameEvent(event);}
@Override public void gameEvent(Holder<GameEvent> event){if(event==GameEvent.ENTITY_DAMAGE)events.add("entity-damage");else if(event==GameEvent.SPLASH)events.add("splash-event");else super.gameEvent(event);}
@Override public void die(DamageSource source){dead=true;events.add("death-request");}
@Override protected void playHurtSound(DamageSource source){events.add("hurt-sound");}
@Override protected SoundEvent getDeathSound(){return SoundEvents.PLAYER_DEATH;}
@@ -171,20 +181,18 @@ public final class VanillaSceneMotionOracle {
@Override public AttributeMap getAttributes(){return attrs;}
@Override protected boolean getSharedFlag(int bit){return (flags&(1<<bit))!=0;}
@Override protected void setSharedFlag(int bit,boolean v){flags=(byte)(v?flags|(1<<bit):flags&~(1<<bit));}
@Override public void setPos(double x,double y,double z){write(position,this,new Vec3(x,y,z));setBoundingBox(EntityDimensions.scalable(getBbWidth(),getBbHeight()).makeBoundingBox(position()));}
@Override public void setPos(double x,double y,double z){write(position,this,new Vec3(x,y,z));write(blockPositionField,this,BlockPos.containing(x,y,z));setBoundingBox(EntityDimensions.scalable(getBbWidth(),getBbHeight()).makeBoundingBox(position()));}
@Override public BlockPos blockPosition(){return BlockPos.containing(position());}
@Override public BlockState getInBlockState(){return level().getBlockState(blockPosition());}
@Override public ItemStack getMainHandItem(){return ItemStack.EMPTY;}
@Override public boolean isPassenger(){return statisticsFlags!=null&&statFlag(0);}
@Override public boolean isSwimming(){return statisticsFlags!=null&&statFlag(1);}
@Override public boolean isEyeInFluid(net.minecraft.tags.TagKey<net.minecraft.world.level.material.Fluid> tag){return statisticsFlags!=null&&statFlag(2);}
@Override public boolean isInWater(){return statisticsFlags!=null&&statFlag(3);}
@Override public boolean isEyeInFluid(net.minecraft.tags.TagKey<net.minecraft.world.level.material.Fluid> tag){return statisticsFlags!=null?statFlag(2):super.isEyeInFluid(tag);}
@Override public boolean isInWater(){return statisticsFlags!=null?statFlag(3):super.isInWater();}
@Override public boolean onClimbable(){return statisticsFlags!=null?statFlag(4):super.onClimbable();}
@Override public boolean onGround(){return statisticsFlags!=null?statFlag(5):super.onGround();}
@Override public boolean isSprinting(){return statisticsFlags!=null?statFlag(6):super.isSprinting();}
@Override public boolean isCrouching(){return statisticsFlags!=null?statFlag(7):super.isCrouching();}
@Override public boolean isInLava(){return false;}
@Override public boolean isInLiquid(){return false;}
@Override public boolean isFallFlying(){return statisticsFlags!=null&&statFlag(8);}
@Override public boolean isAutoSpinAttack(){return false;}
@Override public boolean isSpectator(){return false;}
@@ -196,7 +204,6 @@ public final class VanillaSceneMotionOracle {
@Override public MoveSimulationType getMoveSimulationType(){return MoveSimulationType.SERVER_AND_CLIENT;}
@Override public boolean isClientAuthoritative(){return false;}
@Override public void recordMovement(MoverType mover,Vec3 movement){}
@Override protected boolean updateFluidInteraction(){return false;}
@Override public void playSound(SoundEvent sound,float volume,float pitch){events.add(String.format("sound %s entity %08x %08x",soundName(sound),Float.floatToIntBits(volume),Float.floatToIntBits(pitch)));}
@Override protected void playBlockFallSound(){events.add("block-fall-sound");}
@Override public void awardStat(net.minecraft.stats.Stat<?> stat,int value){
@@ -213,7 +220,6 @@ public final class VanillaSceneMotionOracle {
@Override protected void playStepSound(BlockPos p,BlockState state){}
@Override public void gameEvent(Holder<GameEvent> event,Entity source){}
@Override public LivingEntity getControllingPassenger(){return null;}
@Override public double getFluidHeight(net.minecraft.tags.TagKey<net.minecraft.world.level.material.Fluid> tag){return 0;}
@Override public double getFluidJumpThreshold(){return .4;}
// Block-inside effects and frozen ticks run only in "snow_tick" operations.
boolean effects;int frozen;Vec3 tickStart;
@@ -243,7 +249,12 @@ public final class VanillaSceneMotionOracle {
}
}
void clock()throws Exception{sceneLevel.time++;tickCount++;if(cooldown.getInt(this)>0)cooldown.setInt(this,cooldown.getInt(this)-1);if(hurtTime>0)hurtTime--;}
// Entity.baseTick's fluid phase: wasEyeInWater, the real
// updateFluidInteraction, lava's fall halving and the first tick's end.
void fluidTick(){wasEyeInWater=isEyeInFluid(net.minecraft.tags.FluidTags.WATER);updateFluidInteraction();if(isInLava())fallDistance*=0.5;firstTick=false;}
String fluidState(){return wasTouchingWater+" "+wasEyeInWater+" "+isEyeInFluid(net.minecraft.tags.FluidTags.WATER)+" "+firstTick+String.format(" %016x %016x",Double.doubleToLongBits(getFluidHeight(net.minecraft.tags.FluidTags.WATER)),Double.doubleToLongBits(getFluidHeight(net.minecraft.tags.FluidTags.LAVA)));}
void playerMovementTick(Vec3 input,boolean jumping){
fluidTick();
preparedInput=true;xxa=(float)input.x;yya=0;zza=(float)input.z;setJumping(jumping);
try{aiStep();}finally{preparedInput=false;}
}
@@ -271,7 +282,7 @@ public final class VanillaSceneMotionOracle {
out.printf("%s %s %s %s %s %s %s %016x %s %s %s %08x %d %08x %d %d %s | %s%n",p.horizontalCollision,p.verticalCollision,p.verticalCollisionBelow,p.minorHorizontalCollision,
p.onGround(),noBlocks.getBoolean(p),pos(support.get(p)),Double.doubleToLongBits(p.fallDistance),pos(last.get(p)),p.needsSync,p.syncPosition,Float.floatToIntBits(storedSpeed.getFloat(p)),delay.getInt(p),Float.floatToIntBits(p.yHeadRot),trigger.getInt(p),grace.getInt(p),impact.get(p)==null?"none":vectorBits((Vec3)impact.get(p)),String.join(";",attributes));
out.println("events "+String.join(" | ",p.events));p.events.clear();
out.println("block "+Block.getId(p.level().getBlockState(new BlockPos(25,3,25)))+" frozen "+p.frozen+" "+p.isInPowderSnow+" "+p.wasInPowderSnow+" "+vectorBits((Vec3)stuck.get(p)));
out.println("block "+Block.getId(p.level().getBlockState(new BlockPos(25,3,25)))+" frozen "+p.frozen+" "+p.isInPowderSnow+" "+p.wasInPowderSnow+" "+vectorBits((Vec3)stuck.get(p))+" fluid "+p.fluidState());
var pp=p.portalProcess;
out.println("portal "+p.getPortalCooldown()+" "+(pp==null?"none":pp.getEntryPosition().getX()+","+pp.getEntryPosition().getY()+","+pp.getEntryPosition().getZ()+" "+pp.getPortalTime()+" "+pp.isInsidePortalThisTick())+" "+(p.travel==null?"-":p.travel));p.travel=null;
out.printf("health %08x %08x %08x %d %d %08x %d %d %s %d %s %s %s %s %s %d%n",
@@ -285,8 +296,12 @@ public final class VanillaSceneMotionOracle {
@SuppressWarnings("unchecked") public static void main(String[] args)throws Exception{
net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]);
VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(Path.of(args[2]).resolve("block-tags.json"))).getAsJsonObject());
// The vanilla data pack's #water and #lava fluid tags.
net.minecraft.core.registries.BuiltInRegistries.FLUID.prepareTagReload(new net.minecraft.tags.TagLoader.LoadResult<>(net.minecraft.core.registries.Registries.FLUID,Map.of(
net.minecraft.tags.FluidTags.WATER,List.<Holder<net.minecraft.world.level.material.Fluid>>of(net.minecraft.world.level.material.Fluids.FLOWING_WATER.builtInRegistryHolder(),net.minecraft.world.level.material.Fluids.WATER.builtInRegistryHolder()),
net.minecraft.tags.FluidTags.LAVA,List.<Holder<net.minecraft.world.level.material.Fluid>>of(net.minecraft.world.level.material.Fluids.FLOWING_LAVA.builtInRegistryHolder(),net.minecraft.world.level.material.Fluids.LAVA.builtInRegistryHolder())))).apply();
var u=Class.forName("sun.misc.Unsafe");var f=u.getDeclaredField("theUnsafe");f.setAccessible(true);var unsafe=f.get(null);var allocate=u.getMethod("allocateInstance",Class.class);
position=field(Entity.class,"position");history=field(Entity.class,"movementThisTick");support=field(Entity.class,"mainSupportingBlockPos");noBlocks=field(Entity.class,"onGroundNoBlocks");last=field(LivingEntity.class,"lastClimbablePos");stuck=field(Entity.class,"stuckSpeedMultiplier");
position=field(Entity.class,"position");blockPositionField=field(Entity.class,"blockPosition");history=field(Entity.class,"movementThisTick");support=field(Entity.class,"mainSupportingBlockPos");noBlocks=field(Entity.class,"onGroundNoBlocks");last=field(LivingEntity.class,"lastClimbablePos");stuck=field(Entity.class,"stuckSpeedMultiplier");
var abilities=field(Player.class,"abilities");
healthKey=(EntityDataAccessor<Float>)field(LivingEntity.class,"DATA_HEALTH_ID").get(null);absorptionKey=(EntityDataAccessor<Float>)field(Player.class,"DATA_PLAYER_ABSORPTION_ID").get(null);
healthDead=field(LivingEntity.class,"dead");cooldown=field(LivingEntity.class,"damageCooldownTime");lastHurt=field(LivingEntity.class,"lastHurt");noAction=field(LivingEntity.class,"noActionTime");lastDamage=field(LivingEntity.class,"lastDamageSource");lastStamp=field(LivingEntity.class,"lastDamageStamp");foodExhaustion=field(FoodData.class,"exhaustionLevel");foodTimer=field(FoodData.class,"tickTimer");
@@ -320,6 +335,8 @@ public final class VanillaSceneMotionOracle {
p.attrs=new TrackedAttributes(VanillaEntityAttributeOracle.supplier(EntityTypes.PLAYER));write(field(LivingEntity.class,"attributes"),p,p.attrs);
write(field(Entity.class,"finalMovementsThisTick"),p,new ArrayList<>());write(field(Entity.class,"visitedBlocks"),p,new it.unimi.dsi.fastutil.longs.LongOpenHashSet());
write(field(Entity.class,"insideEffectCollector"),p,new net.minecraft.world.entity.InsideBlockEffectApplier.StepBasedCollector());
write(field(Entity.class,"fluidInteraction"),p,new net.minecraft.world.entity.EntityFluidInteraction(Set.of(net.minecraft.tags.FluidTags.WATER,net.minecraft.tags.FluidTags.LAVA)));
write(field(Entity.class,"random"),p,level.rng);field(Entity.class,"firstTick").setBoolean(p,true);
write(history,p,new ArrayDeque<>());write(support,p,Optional.empty());write(last,p,Optional.empty());write(stuck,p,Vec3.ZERO);write(abilities,p,new Abilities());
write(field(ServerPlayer.class,"shoulderEntityLeft"),p,new net.minecraft.nbt.CompoundTag());write(field(ServerPlayer.class,"shoulderEntityRight"),p,new net.minecraft.nbt.CompoundTag());
p.connection=(Connection)allocate.invoke(unsafe,Connection.class);
@@ -366,6 +383,7 @@ public final class VanillaSceneMotionOracle {
case "impulse"->p.setIgnoreFallDamageFromCurrentImpulse(op.get("ignore").getAsBoolean(),op.get("value").isJsonNull()?null:VanillaSceneCollisionOracle.vector(op.get("value")));
case "block"->{var v=op.getAsJsonArray("position");var pos=new BlockPos(v.get(0).getAsInt(),v.get(1).getAsInt(),v.get(2).getAsInt());var state=VanillaSceneCollisionOracle.state(op.get("name").getAsString());if(op.has("properties"))for(var property:op.getAsJsonObject("properties").entrySet())state=VanillaSceneCollisionOracle.property(state,state.getBlock().getStateDefinition().getProperty(property.getKey()),property.getValue().getAsString());level.chunks.get(key(pos.getX()>>4,pos.getZ()>>4)).write(pos,Block.getId(state));}
case "landing"->{var v=op.getAsJsonArray("position");p.land(number(op.get("value")),op.get("ground").getAsBoolean(),new BlockPos(v.get(0).getAsInt(),v.get(1).getAsInt(),v.get(2).getAsInt()));}
case "fluid_tick"->p.fluidTick();
case "travel"->p.travel(VanillaSceneCollisionOracle.vector(op.get("value")));
case "tick"->p.movementTick(VanillaSceneCollisionOracle.vector(op.get("value")));
case "player_tick"->p.playerMovementTick(VanillaSceneCollisionOracle.vector(op.get("value")),op.get("jumping").getAsBoolean());
File diff suppressed because one or more lines are too long