//! Entity fluid immersion trackers and current accumulation across update ticks. use crate::fluid::{FluidKind, FluidState}; use horizon_core::{ geometry::{Aabb, Vec3}, position::BlockPos, }; use std::fmt; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct FluidTagId(pub u32); pub trait FluidMembership { fn fluid_in_tag(&self, fluid: FluidKind, tag: FluidTagId) -> bool; } #[derive(Clone, Copy, Debug)] pub struct FluidTracker { pub fluid: FluidKind, pub height: f64, pub eyes_inside: bool, } #[derive(Clone, Copy, Debug)] pub struct CurrentAccumulator { pub height: f64, pub accumulated: Vec3, pub count: i32, } impl Default for CurrentAccumulator { fn default() -> Self { Self { height: 0.0, accumulated: Vec3::ZERO, count: 0, } } } pub trait CurrentTarget { type Error; fn is_player_class(&self) -> bool; fn velocity(&mut self) -> Result; /// Entity.addDeltaMovement, including finite-addition filtering and a fresh /// velocity read. Entity-specific overrides remain the provider's dispatch. fn add_delta_movement(&mut self, delta: Vec3) -> Result<(), Self::Error>; } impl CurrentAccumulator { pub fn reset(&mut self) { *self = Self::default(); } pub fn accumulate(&mut self, current: Vec3) { self.accumulated = add(self.accumulated, current); self.count = self.count.wrapping_add(1); } pub fn apply_to(&self, world: &mut W, speed: f64) -> Result<(), W::Error> { if self.count == 0 || self.accumulated.length_squared() < f64::from(1.0e-5f32) { return Ok(()); } let mut current = if world.is_player_class() { self.accumulated.scale(1.0 / f64::from(self.count)) } else { self.accumulated.normalize() }; let velocity = world.velocity()?; current = current.scale(speed); if velocity.x.abs() < 0.003 && velocity.z.abs() < 0.003 && current.length() < 0.0045000000000000005 { current = current.normalize().scale(0.0045000000000000005); } world.add_delta_movement(current) } } pub struct FluidSections<'a> { pub minimum_section_y: i32, pub has_fluid: &'a [bool], } pub trait FluidInteractionWorld: FluidMembership { type Error; type Chunk: Copy; fn interaction_box(&mut self) -> Result, Self::Error>; /// FULL chunk lookup without generating/loading absent chunks. fn loaded_chunk(&mut self, x: i32, z: i32) -> Result, Self::Error>; fn chunk_sections(&mut self, chunk: Self::Chunk) -> Result, Self::Error>; fn bounding_box_min_y(&self) -> f64; fn block_x(&self) -> i32; fn eye_y(&mut self) -> Result; fn block_z(&self) -> i32; fn fluid_state(&mut self, position: BlockPos) -> Result; fn fluid_height(&mut self, state: FluidState, position: BlockPos) -> Result; fn camera_height(&mut self, state: FluidState, position: BlockPos) -> Result; fn flow(&mut self, state: FluidState, position: BlockPos) -> Result; } #[derive(Debug)] pub enum FluidInteractionError { World(E), NonFiniteBounds, BudgetExceeded, } impl fmt::Display for FluidInteractionError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::World(e) => e.fmt(f), Self::NonFiniteBounds => f.write_str("nonfinite immersion bounds"), Self::BudgetExceeded => f.write_str("immersion query budget exceeded"), } } } impl std::error::Error for FluidInteractionError {} fn spend(budget: &mut usize) -> Result<(), FluidInteractionError> { if *budget == 0 { return Err(FluidInteractionError::BudgetExceeded); } *budget -= 1; Ok(()) } fn add(a: Vec3, b: Vec3) -> Vec3 { Vec3::new(a.x + b.x, a.y + b.y, a.z + b.z) } fn java_max(a: f64, b: f64) -> f64 { if a.is_nan() { a } else if b.is_nan() { b } else if a == 0.0 && b == 0.0 { f64::from_bits(a.to_bits() & b.to_bits()) } else { a.max(b) } } /// Every required chunk must be loaded, even after a wet section is found. /// Chunk order is Z then X; section order is ascending Y without early success. pub fn has_fluid_and_loaded( world: &mut W, min: BlockPos, max: BlockPos, budget: &mut usize, ) -> Result> { let mut present = false; for z in (min.z >> 4)..=(max.z >> 4) { for x in (min.x >> 4)..=(max.x >> 4) { spend(budget)?; let Some(chunk) = world .loaded_chunk(x, z) .map_err(FluidInteractionError::World)? else { return Ok(false); }; let sections = world .chunk_sections(chunk) .map_err(FluidInteractionError::World)?; for y in (min.y >> 4)..=(max.y >> 4) { spend(budget)?; let index = y.wrapping_sub(sections.minimum_section_y); if index >= 0 && (index as usize) < sections.has_fluid.len() { present |= sections.has_fluid[index as usize]; } } } } Ok(present) } #[derive(Default)] pub struct EntityFluidInteraction { trackers: Vec, currents: Vec<(FluidTagId, CurrentAccumulator)>, } impl EntityFluidInteraction { /// Preserve the caller's tag-set iteration order: a fluid's current belongs /// to the first matching tag, even when several tags contain that fluid. pub fn new(tags: impl IntoIterator) -> Self { let mut state = Self::default(); for tag in tags { if !state.currents.iter().any(|(t, _)| *t == tag) { state.currents.push((tag, CurrentAccumulator::default())); } } state } pub fn trackers(&self) -> &[FluidTracker] { &self.trackers } pub fn currents(&self) -> &[(FluidTagId, CurrentAccumulator)] { &self.currents } pub fn fluid_height(&self, tags: &W, tag: FluidTagId) -> f64 { let mut height = 0.0; for t in &self.trackers { if t.height > height && tags.fluid_in_tag(t.fluid, tag) { height = t.height; } } height } pub fn is_in_fluid(&self, tags: &W, tag: FluidTagId) -> bool { self.fluid_height(tags, tag) > 0.0 } pub fn is_eye_in_fluid(&self, tags: &W, tag: FluidTagId) -> bool { self.trackers .iter() .any(|t| t.eyes_inside && tags.fluid_in_tag(t.fluid, tag)) } pub fn apply_current( &self, world: &mut W, tag: FluidTagId, speed: f64, ) -> Result<(), W::Error> { if let Some((_, current)) = self.currents.iter().find(|(t, _)| *t == tag) { current.apply_to(world, speed)?; } Ok(()) } /// Reset previous tick state before any query. Provider failures and budget /// exhaustion retain all preceding tracker/current writes. pub fn update( &mut self, world: &mut W, ignore_current: bool, mut budget: usize, ) -> Result> { self.trackers.retain_mut(|t| { if t.height == 0.0 && !t.eyes_inside { return false; } t.height = 0.0; t.eyes_inside = false; true }); for (_, c) in &mut self.currents { c.reset(); } let Some(bounds) = world .interaction_box() .map_err(FluidInteractionError::World)? else { return Ok(false); }; let a = bounds.min_position(); let b = bounds.max_position(); if [a.x, a.y, a.z, b.x, b.y, b.z] .iter() .any(|v| !v.is_finite()) { return Err(FluidInteractionError::NonFiniteBounds); } let low = BlockPos::new(a.x.floor() as i32, a.y.floor() as i32, a.z.floor() as i32); let high = BlockPos::new( (b.x.ceil() as i32).wrapping_sub(1), (b.y.ceil() as i32).wrapping_sub(1), (b.z.ceil() as i32).wrapping_sub(1), ); if !has_fluid_and_loaded( world, BlockPos::new(low.x.wrapping_sub(1), low.y, low.z.wrapping_sub(1)), BlockPos::new(high.x.wrapping_add(1), high.y, high.z.wrapping_add(1)), &mut budget, )? { return Ok(false); } let base_y = world.bounding_box_min_y(); let block_x = world.block_x(); let eye = world.eye_y().map_err(FluidInteractionError::World)?; let block_z = world.block_z(); let mut last: Option<(FluidKind, usize, Option)> = None; for x in low.x..=high.x { for y in low.y..=high.y { for z in low.z..=high.z { spend(&mut budget)?; let p = BlockPos::new(x, y, z); let state = world.fluid_state(p).map_err(FluidInteractionError::World)?; if state.kind() == FluidKind::Empty { continue; } let surface = f64::from(y) + f64::from( world .fluid_height(state, p) .map_err(FluidInteractionError::World)?, ); if surface < a.y { continue; } let kind = state.kind(); let (_, index, current) = if let Some(last) = last.filter(|(k, _, _)| *k == kind) { last } else { let index = if let Some(i) = self.trackers.iter().position(|t| t.fluid == kind) { i } else { self.trackers.push(FluidTracker { fluid: kind, height: 0.0, eyes_inside: false, }); self.trackers.len() - 1 }; let current = if ignore_current { None } else { self.currents .iter() .position(|(tag, _)| world.fluid_in_tag(kind, *tag)) }; let entry = (kind, index, current); last = Some(entry); entry }; if x == block_x && z == block_z && eye >= f64::from(y) { let top = f64::from(y) + f64::from( world .camera_height(state, p) .map_err(FluidInteractionError::World)?, ); if eye <= top { self.trackers[index].eyes_inside = true; } } self.trackers[index].height = java_max(surface - base_y, self.trackers[index].height); if let Some(i) = current { let mut flow = world.flow(state, p).map_err(FluidInteractionError::World)?; let c = &mut self.currents[i].1; c.height = java_max(self.trackers[index].height, c.height); if c.height < 0.4 { flow = flow.scale(c.height); } c.accumulate(flow); } } } } Ok(last.is_some()) } }