diff --git a/crates/horizon-world/src/level/classes.rs b/crates/horizon-world/src/level/classes.rs index 764edbebe..a80b7294e 100644 --- a/crates/horizon-world/src/level/classes.rs +++ b/crates/horizon-world/src/level/classes.rs @@ -8,7 +8,7 @@ macro_rules! classes { ($($name:ident = $java:literal,)*) => { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] - #[repr(u8)] + #[repr(u16)] pub enum Class { $($name,)* } impl Class { pub const ALL: &'static [Class] = &[$(Class::$name,)*]; @@ -327,7 +327,7 @@ impl Interface { /// Set of recognised classes in one block's chain. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct ClassSet([u64; 4]); +pub struct ClassSet([u64; 5]); impl ClassSet { pub fn insert(&mut self, class: Class) { let i = class as usize; diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index cce3249dc..013327230 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -41,6 +41,7 @@ pub mod state_flags { pub const FULL_COLLISION: u32 = 1 << 14; pub const SKYLIGHT_DOWN: u32 = 1 << 15; pub const REQUIRES_TOOL: u32 = 1 << 16; + pub const SHAPE_OCCLUSION: u32 = 1 << 17; } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -551,6 +552,7 @@ props! { crafting = "crafting", side_chain = "side_chain", copper_golem_pose = "copper_golem_pose", + sculk_sensor_phase = "sculk_sensor_phase", } fn fail(message: &str) -> io::Error { @@ -584,6 +586,33 @@ fn set_type(value: &Value, cache: &mut HashMap>) -> Option io::Result { + use crate::{DATA_VERSION, nbt::Tag}; + fn tag(value: &Value) -> io::Result { + Ok(match value { + Value::String(value) => Tag::String(value.as_str().into()), + Value::Number(value) => Tag::Int(value.as_i64().and_then(|v| i32::try_from(v).ok()).ok_or_else(|| fail("invalid registry number"))?), + Value::Array(values) => Tag::List(values.iter().map(tag).collect::>()?), + Value::Object(values) => Tag::Compound( + values + .iter() + .map(|(name, value)| Ok((name.as_str().into(), tag(value)?))) + .collect::>()?, + ), + _ => return Err(fail("unsupported registry value")), + }) + } + let facts = read_json(&root.join("facts.json"))?; + let states = facts["states"].as_array().ok_or_else(|| fail("missing registry state facts"))?; + BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", Tag::List(states.iter().map(|state| tag(&state[4])).collect::>()?)), + ("defaults", tag(&facts["defaults"])?), + ])) +} + pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result { let mut table = StateTable::new(registry)?; let props = Props::resolve(&mut table); @@ -711,6 +740,7 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result io::Result Sim<'_, L> { + /// `FallingBlockEntity.fall`. + pub(crate) fn falling_block_fall(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let carried = b.table.with_bool(state, b.props.waterlogged, false).unwrap_or(state); + let legacy = b.legacy_block(b.fluid(state)); + self.set_block_and_update(pos, legacy); + self.emit(LevelEvent::FallingBlock { pos, state: carried }); + } + /// `FallingBlock.tick` (and `SpeleothemBlock`'s falling stalactites). + pub(crate) fn falling_block_tick(&mut self, pos: BlockPos, state: BlockStateId) { + if self.is_free(self.below_state(pos)) && pos.y >= self.level.min_y() { + self.falling_block_fall(pos, state); + } + } + /// `SpeleothemBlock.spawnFallingStalactite`. + pub(crate) fn spawn_falling_stalactite(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let p = b.props; + let is_stalactite = |s: BlockStateId| { + b.tag("minecraft:speleothems").is_some_and(|tag| b.in_set(s, tag)) && b.table.dir(s, p.vertical_direction) == Some(Direction::Down) + }; + let mut fall_pos = pos; + let mut fall_state = state; + while is_stalactite(fall_state) { + self.falling_block_fall(fall_pos, fall_state); + let thickness = b.table.text(fall_state, p.thickness); + if thickness == "tip" || thickness == "tip_merge" { + break; + } + fall_pos = below(fall_pos); + fall_state = self.state(fall_pos); + } + } +} + +impl Behaviours { + /// The landing branch of `FallingBlockEntity.tick`, called by the caller's + /// falling-block entity once it is on the ground (or stuck in water as + /// concrete powder). `state` is the carried block state. + pub fn falling_block_landed( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + state: BlockStateId, + stuck_in_water: bool, + ) -> Landing { + let mut sim = self.sim(level, ticks); + let current = sim.state(pos); + if self.is_block(current, self.named.moving_piston) { + return Landing::Continue; + } + let concrete = self.instance_of(state, Class::ConcretePowder); + let may_replace = self.is_replaceable(current); + let would_continue = sim.is_free(sim.below_state(pos)) && (!concrete || !stuck_in_water); + let would_survive = sim.can_survive(state, pos) && !would_continue; + if !(may_replace && would_survive) { + if self.instance_of(state, Class::Anvil) { + sim.level_event(1029, pos, 0); + } + return Landing::Broken; + } + let mut placed = state; + if self.table.has(placed, self.props.waterlogged) && self.is_water_fluid(sim.fluid_at(pos).kind()) { + placed = self.table.set_bool(placed, self.props.waterlogged, true); + } + if !sim.set_block_and_update(pos, placed) { + if self.instance_of(state, Class::Anvil) { + sim.level_event(1029, pos, 0); + } + return Landing::Broken; + } + // Fallable.onLand + if concrete { + if self.is_water_fluid(self.fluid(current).kind()) || sim.concrete_touches_liquid(pos) { + if let Some(solid) = self.data(state).link { + sim.set_block_and_update(pos, self.default_of(solid)); + } + } + } else if self.instance_of(state, Class::Anvil) { + sim.level_event(1031, pos, 0); + } + Landing::Placed(sim.state(pos)) + } +} diff --git a/crates/horizon-world/src/level/hooks.rs b/crates/horizon-world/src/level/hooks.rs index 5aaa21836..c02a32d48 100644 --- a/crates/horizon-world/src/level/hooks.rs +++ b/crates/horizon-world/src/level/hooks.rs @@ -78,7 +78,9 @@ impl Sim<'_, L> { self.rail_update_state(pos, state, moved); } } - Class::Brushable => self.schedule_tick(pos, block, 2), + Class::Brushable => { + self.schedule_tick(pos, block, 2); + } Class::Composter => { if b.table.int(state, b.props.level) == 7 { self.schedule_tick(pos, block, 20); @@ -131,7 +133,9 @@ impl Sim<'_, L> { self.wire_update_neighbors_of_neighboring_wires(pos); } } - Class::Scaffolding => self.schedule_tick(pos, block, 1), + Class::Scaffolding => { + self.schedule_tick(pos, block, 1); + } Class::SculkSensor => { if !same && b.table.int(state, b.props.power) > 0 && !self.ticks.has_block_tick(pos, block) { self.set_block(pos, b.table.set_int(state, b.props.power, 0), 18); @@ -289,6 +293,52 @@ impl Sim<'_, L> { } } + /// `ServerPlayerGameMode.destroyBlock`: `playerWillDestroy` then + /// `removeBlock`. Drops are the caller's (tool-dependent loot). + pub(crate) fn player_destroy(&mut self, pos: BlockPos, creative: bool) -> bool { + let b = self.b; + let p = b.props; + let state = self.state(pos); + if b.is_air(state) { + return false; + } + let data = b.data(state); + if creative && (data.is(Class::DoublePlant) || data.is(Class::Door)) && b.table.text(state, p.half) == "upper" { + let bottom = below(pos); + let bottom_state = self.state(bottom); + if b.is_block(bottom_state, b.block(state)) && b.table.text(bottom_state, p.half) == "lower" { + let replacement = if b.is_water_fluid(b.fluid(bottom_state).kind()) { b.default_of(b.named.water) } else { b.air() }; + self.set_block(bottom, replacement, 35); + self.level_event(2001, bottom, bottom_state.0 as i32); + } + } + if creative && data.is(Class::AbstractBed) && b.table.text(state, p.part) == "foot" { + let head_pos = rel(pos, b.facing(state)); + let head = self.state(head_pos); + if b.is_block(head, b.block(state)) && b.table.text(head, p.part) == "head" { + self.set_block(head_pos, b.air(), 35); + self.level_event(2001, head_pos, head.0 as i32); + } + } + self.level_event(2001, pos, state.0 as i32); + self.game_event(pos, "minecraft:block_destroy"); + self.remove_block(pos, false) + } + /// `entityInside` for entity-sensing blocks. + pub(crate) fn entity_inside(&mut self, pos: BlockPos) { + let b = self.b; + let state = self.state(pos); + let data = b.data(state); + if data.is(Class::BasePressurePlate) { + let signal = self.plate_signal_for_state(state); + if signal == 0 { + self.plate_check_pressed(pos, state, signal); + } + } else if data.is(Class::TripWire) && !b.table.bool(state, b.props.powered) && !self.ticks.has_block_tick(pos, b.block(state)) { + self.tripwire_check_pressed(pos); + } + } + // ---- misc helpers ---- /// `BaseFireBlock.onPlace` (portal ignition is not modelled). @@ -387,16 +437,16 @@ impl Sim<'_, L> { } fn big_dripleaf_reset_tilt(&mut self, pos: BlockPos, state: BlockStateId) { let b = self.b; + let next = b.table.set_text(state, b.props.tilt, "none"); + self.set_block(pos, next, 2); if b.table.text(state, b.props.tilt) != "none" { - let next = b.table.set_text(state, b.props.tilt, "none"); - self.set_block(pos, next, 2); + let pitch = self.random().next_float() * 0.4 + 0.8; self.emit(super::LevelEvent::Sound { pos, sound: "minecraft:block.big_dripleaf.tilt_up".into(), volume: 1.0, - pitch: 1.0, + pitch, }); - self.ticks.blocks.clear_area(horizon_core::ticks::TickArea::new(pos, pos)); } } pub(crate) fn horizontal_neighbours(pos: BlockPos) -> [BlockPos; 4] { diff --git a/crates/horizon-world/src/level/interact.rs b/crates/horizon-world/src/level/interact.rs new file mode 100644 index 000000000..e9a07474d --- /dev/null +++ b/crates/horizon-world/src/level/interact.rs @@ -0,0 +1,12 @@ +//! `useWithoutItem` interactions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum InteractionResult { + Success, + Consume, + Pass, +} +#[derive(Clone, Copy, Debug)] +pub struct PlayerContext { + pub yaw: f32, + pub may_build: bool, +} diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index eef27c95f..b9711e875 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -52,12 +52,13 @@ pub mod data; pub mod states; pub mod ticks; -mod connect; mod falling; mod fluids; +mod hooks; mod interact; mod place; -mod plants; +mod query; +mod rails; mod redstone; mod shapes; mod survive; @@ -68,6 +69,7 @@ mod update; mod tests; pub use data::{BlockData, ItemBinding, ItemKind, Named, Props, PushReaction, StateFacts, Tags}; +pub use falling::Landing; pub use place::{PlaceContext, PlaceOutcome}; pub use interact::{InteractionResult, PlayerContext}; pub use states::{BlockId, PropKey, StateTable}; @@ -173,6 +175,14 @@ pub enum LevelEvent { }, /// `TntBlock.prime`: the TNT block is removed; spawn primed TNT. PrimeTnt { pos: BlockPos }, + /// Block-entity or entity side effects the caller implements: `"dispense"` + /// (dispenser/dropper/crafter scheduled tick), `"hatch"` (frogspawn + /// hatched into tadpoles; the block is already destroyed). + BlockEvent { + pos: BlockPos, + state: BlockStateId, + kind: &'static str, + }, /// `Level.gameEvent` (vibration system), by vanilla identifier. GameEvent { pos: BlockPos, event: &'static str }, } @@ -354,6 +364,56 @@ impl Behaviours { } } +/// Level mutation entry points (all keep vanilla update semantics). +impl Behaviours { + /// `Level.setBlock(pos, state, flags)` with vanilla's update limit (512). + /// Returns false when nothing was written (unloaded, out of bounds, or + /// the state was already present). + pub fn set_block(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, state: BlockStateId, flags: i32) -> bool { + self.sim(level, ticks).set_block(pos, state, flags) + } + /// `Level.removeBlock(pos, movedByPiston)`: replace with the fluid's block. + pub fn remove_block(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, moved_by_piston: bool) -> bool { + self.sim(level, ticks).remove_block(pos, moved_by_piston) + } + /// `Level.destroyBlock(pos, dropResources)`: destroy particles (2001), + /// optional drops, and replacement by the block's fluid. + pub fn destroy_block(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, drop: bool) -> bool { + self.sim(level, ticks).destroy_block(pos, drop, flags::UPDATE_LIMIT) + } + /// A player breaking a block (`playerWillDestroy` + `Level.destroyBlock` + /// without drops; the caller handles the player's loot/tool). Double + /// blocks (doors, tall plants, beds) remove their other half as vanilla. + pub fn player_destroy_block(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, creative: bool) -> bool { + self.sim(level, ticks).player_destroy(pos, creative) + } + /// `BlockState.canSurvive(level, pos)`. + pub fn can_survive(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, state: BlockStateId) -> bool { + self.sim(level, ticks).can_survive(state, pos) + } + /// `Block.updateFromNeighbourShapes`: a state adjusted to its neighbours. + pub fn update_from_neighbour_shapes(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, state: BlockStateId) -> BlockStateId { + self.sim(level, ticks).update_from_neighbour_shapes(state, pos) + } + /// `Level.updateNeighborsAt(pos, block)`: notify the six neighbours. + pub fn update_neighbors_at(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, block: BlockId) { + self.sim(level, ticks).update_neighbors_at(pos, block); + } + /// Entity collision with a block (`entityInside`) for the entity-sensing + /// blocks: pressure plates, tripwires and buttons hit by arrows are + /// re-evaluated through [`LevelAccess::count_entities`]. + pub fn entity_inside(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos) { + self.sim(level, ticks).entity_inside(pos); + } + /// Redstone signal queries (`SignalGetter`). + pub fn has_neighbor_signal(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos) -> bool { + self.sim(level, ticks).has_neighbor_signal(pos) + } + pub fn best_neighbor_signal(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos) -> i32 { + self.sim(level, ticks).best_neighbor_signal(pos) + } +} + /// One mutable view used by the ported behaviour code. pub(crate) struct Sim<'a, L: LevelAccess + ?Sized> { pub b: &'a Behaviours, diff --git a/crates/horizon-world/src/level/place.rs b/crates/horizon-world/src/level/place.rs new file mode 100644 index 000000000..160507eb8 --- /dev/null +++ b/crates/horizon-world/src/level/place.rs @@ -0,0 +1,25 @@ +//! Block placement (`BlockItem.place`, `BlockPlaceContext`, `getStateForPlacement`). +use crate::registry::BlockStateId; +use horizon_core::{ + geometry::{Direction, Vec3}, + position::BlockPos, +}; + +/// `BlockPlaceContext` inputs from the player's use-item-on-block action. +#[derive(Clone, Debug)] +pub struct PlaceContext { + pub clicked_pos: BlockPos, + pub face: Direction, + pub hit: Vec3, + pub inside: bool, + pub yaw: f32, + pub pitch: f32, + pub sneaking: bool, + pub item: String, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PlaceOutcome { + Placed { pos: BlockPos, state: BlockStateId }, + Failed, +} diff --git a/crates/horizon-world/src/level/rails.rs b/crates/horizon-world/src/level/rails.rs new file mode 100644 index 000000000..9a1fb5468 --- /dev/null +++ b/crates/horizon-world/src/level/rails.rs @@ -0,0 +1,598 @@ +//! Rails (`BaseRailBlock`, `RailState`, powered/activator rails) and +//! tripwires (`TripWireBlock`, `TripWireHookBlock`). +use super::{ + LevelAccess, LevelEvent, Sim, + classes::Class, + states::BlockId, + update::{above, below, rel}, +}; +use crate::registry::BlockStateId; +use horizon_core::{ + geometry::{Aabb, Direction, Vec3}, + position::BlockPos, + random::RandomSource, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RailShape { + NorthSouth, + EastWest, + AscendingEast, + AscendingWest, + AscendingNorth, + AscendingSouth, + SouthEast, + SouthWest, + NorthWest, + NorthEast, +} +impl RailShape { + fn parse(text: &str) -> Self { + match text { + "east_west" => Self::EastWest, + "ascending_east" => Self::AscendingEast, + "ascending_west" => Self::AscendingWest, + "ascending_north" => Self::AscendingNorth, + "ascending_south" => Self::AscendingSouth, + "south_east" => Self::SouthEast, + "south_west" => Self::SouthWest, + "north_west" => Self::NorthWest, + "north_east" => Self::NorthEast, + _ => Self::NorthSouth, + } + } + fn name(self) -> &'static str { + match self { + Self::NorthSouth => "north_south", + Self::EastWest => "east_west", + Self::AscendingEast => "ascending_east", + Self::AscendingWest => "ascending_west", + Self::AscendingNorth => "ascending_north", + Self::AscendingSouth => "ascending_south", + Self::SouthEast => "south_east", + Self::SouthWest => "south_west", + Self::NorthWest => "north_west", + Self::NorthEast => "north_east", + } + } + fn is_slope(self) -> bool { + matches!(self, Self::AscendingEast | Self::AscendingWest | Self::AscendingNorth | Self::AscendingSouth) + } +} + +/// `RailState`. +struct Rail { + pos: BlockPos, + state: BlockStateId, + straight: bool, + connections: Vec, +} + +impl Sim<'_, L> { + pub(crate) fn rail_shape(&self, state: BlockStateId) -> &str { + self.b.table.text(state, self.b.props.shape) + } + fn is_rail(&self, state: BlockStateId) -> bool { + self.b.in_set(state, &self.b.tags.rails) && self.b.instance_of(state, Class::BaseRail) + } + fn is_rail_at(&self, pos: BlockPos) -> bool { + self.is_rail(self.state(pos)) + } + fn rail_connections(pos: BlockPos, shape: RailShape) -> Vec { + let (n, s, w, e) = (rel(pos, Direction::North), rel(pos, Direction::South), rel(pos, Direction::West), rel(pos, Direction::East)); + match shape { + RailShape::NorthSouth => vec![n, s], + RailShape::EastWest => vec![w, e], + RailShape::AscendingEast => vec![w, above(e)], + RailShape::AscendingWest => vec![above(w), e], + RailShape::AscendingNorth => vec![above(n), s], + RailShape::AscendingSouth => vec![n, above(s)], + RailShape::SouthEast => vec![e, s], + RailShape::SouthWest => vec![w, s], + RailShape::NorthWest => vec![w, n], + RailShape::NorthEast => vec![e, n], + } + } + fn rail_new(&self, pos: BlockPos, state: BlockStateId) -> Rail { + let shape = RailShape::parse(self.rail_shape(state)); + Rail { + pos, + state, + straight: !self.b.data(state).is(Class::Rail), + connections: Self::rail_connections(pos, shape), + } + } + fn rail_get(&self, pos: BlockPos) -> Option { + for test in [pos, above(pos), below(pos)] { + let state = self.state(test); + if self.is_rail(state) { + return Some(self.rail_new(test, state)); + } + } + None + } + fn rail_has_connection(rail: &Rail, pos: BlockPos) -> bool { + rail.connections.iter().any(|c| c.x == pos.x && c.z == pos.z) + } + fn rail_remove_soft_connections(&self, rail: &mut Rail) { + let mut i = 0; + while i < rail.connections.len() { + match self.rail_get(rail.connections[i]) { + Some(other) if Self::rail_has_connection(&other, rail.pos) => { + rail.connections[i] = other.pos; + i += 1; + } + _ => { + rail.connections.remove(i); + } + } + } + } + fn rail_can_connect_to(rail: &Rail, other: &Rail) -> bool { + Self::rail_has_connection(rail, other.pos) || rail.connections.len() != 2 + } + fn rail_has_neighbor_rail(&self, rail: &Rail, pos: BlockPos) -> bool { + match self.rail_get(pos) { + Some(mut neighbour) => { + self.rail_remove_soft_connections(&mut neighbour); + Self::rail_can_connect_to(&neighbour, rail) + } + None => false, + } + } + fn rail_count_potential_connections(&self, pos: BlockPos) -> i32 { + super::update::HORIZONTAL + .into_iter() + .filter(|d| { + let p = rel(pos, *d); + self.is_rail_at(p) || self.is_rail_at(above(p)) || self.is_rail_at(below(p)) + }) + .count() as i32 + } + fn rail_slopes(&self, pos: BlockPos, shape: Option) -> Option { + let (n, s, w, e) = (rel(pos, Direction::North), rel(pos, Direction::South), rel(pos, Direction::West), rel(pos, Direction::East)); + let mut shape = shape; + if shape == Some(RailShape::NorthSouth) { + if self.is_rail_at(above(n)) { + shape = Some(RailShape::AscendingNorth); + } + if self.is_rail_at(above(s)) { + shape = Some(RailShape::AscendingSouth); + } + } + if shape == Some(RailShape::EastWest) { + if self.is_rail_at(above(e)) { + shape = Some(RailShape::AscendingEast); + } + if self.is_rail_at(above(w)) { + shape = Some(RailShape::AscendingWest); + } + } + shape + } + fn rail_set_shape(&self, state: BlockStateId, shape: RailShape) -> BlockStateId { + self.b.table.set_text(state, self.b.props.shape, shape.name()) + } + fn rail_connect_to(&mut self, rail: &mut Rail, other_pos: BlockPos) { + rail.connections.push(other_pos); + let pos = rail.pos; + let n = Self::rail_has_connection(rail, rel(pos, Direction::North)); + let s = Self::rail_has_connection(rail, rel(pos, Direction::South)); + let w = Self::rail_has_connection(rail, rel(pos, Direction::West)); + let e = Self::rail_has_connection(rail, rel(pos, Direction::East)); + let mut shape = None; + if n || s { + shape = Some(RailShape::NorthSouth); + } + if w || e { + shape = Some(RailShape::EastWest); + } + if !rail.straight { + if s && e && !n && !w { + shape = Some(RailShape::SouthEast); + } + if s && w && !n && !e { + shape = Some(RailShape::SouthWest); + } + if n && w && !s && !e { + shape = Some(RailShape::NorthWest); + } + if n && e && !s && !w { + shape = Some(RailShape::NorthEast); + } + } + let shape = self.rail_slopes(pos, shape).unwrap_or(RailShape::NorthSouth); + rail.state = self.rail_set_shape(rail.state, shape); + self.set_block_and_update(pos, rail.state); + } + /// `RailState.place`; returns the resulting state. + fn rail_place(&mut self, pos: BlockPos, state: BlockStateId, has_signal: bool, first: bool, default: RailShape) -> BlockStateId { + let mut rail = self.rail_new(pos, state); + let n = self.rail_has_neighbor_rail(&rail, rel(pos, Direction::North)); + let s = self.rail_has_neighbor_rail(&rail, rel(pos, Direction::South)); + let w = self.rail_has_neighbor_rail(&rail, rel(pos, Direction::West)); + let e = self.rail_has_neighbor_rail(&rail, rel(pos, Direction::East)); + let mut shape = None; + let ns = n || s; + let we = w || e; + if ns && !we { + shape = Some(RailShape::NorthSouth); + } + if we && !ns { + shape = Some(RailShape::EastWest); + } + let (se, sw, ne, nw) = (s && e, s && w, n && e, n && w); + if !rail.straight { + if se && !n && !w { + shape = Some(RailShape::SouthEast); + } + if sw && !n && !e { + shape = Some(RailShape::SouthWest); + } + if nw && !s && !e { + shape = Some(RailShape::NorthWest); + } + if ne && !s && !w { + shape = Some(RailShape::NorthEast); + } + } + if shape.is_none() { + if ns && we { + shape = Some(default); + } else if ns { + shape = Some(RailShape::NorthSouth); + } else if we { + shape = Some(RailShape::EastWest); + } + if !rail.straight { + if has_signal { + for (cond, s) in [ + (se, RailShape::SouthEast), + (sw, RailShape::SouthWest), + (ne, RailShape::NorthEast), + (nw, RailShape::NorthWest), + ] { + if cond { + shape = Some(s); + } + } + } else { + for (cond, s) in [ + (nw, RailShape::NorthWest), + (ne, RailShape::NorthEast), + (sw, RailShape::SouthWest), + (se, RailShape::SouthEast), + ] { + if cond { + shape = Some(s); + } + } + } + } + } + let shape = self.rail_slopes(pos, shape).unwrap_or(default); + rail.connections = Self::rail_connections(pos, shape); + rail.state = self.rail_set_shape(rail.state, shape); + if first || self.state(pos) != rail.state { + self.set_block_and_update(pos, rail.state); + for i in 0..rail.connections.len() { + if let Some(mut neighbour) = self.rail_get(rail.connections[i]) { + self.rail_remove_soft_connections(&mut neighbour); + if Self::rail_can_connect_to(&neighbour, &rail) { + self.rail_connect_to(&mut neighbour, rail.pos); + } + } + } + } + rail.state + } + fn rail_update_dir(&mut self, pos: BlockPos, state: BlockStateId, first: bool) -> BlockStateId { + let current = RailShape::parse(self.rail_shape(state)); + let signal = self.has_neighbor_signal(pos); + self.rail_place(pos, state, signal, first, current) + } + /// `BaseRailBlock.updateState(state, level, pos, movedByPiston)`. + pub(crate) fn rail_update_state(&mut self, pos: BlockPos, state: BlockStateId, moved: bool) -> BlockStateId { + let state = self.rail_update_dir(pos, state, true); + if !self.b.data(state).is(Class::Rail) { + let block = self.b.block(state); + self.neighbor_changed_full(state, pos, block, moved); + } + state + } + pub(crate) fn rail_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId, changed: BlockId, moved: bool) { + let b = self.b; + if !b.is_block(self.state(pos), b.block(state)) { + return; + } + let shape = RailShape::parse(self.rail_shape(state)); + let support = |sim: &Self, p: BlockPos| sim.can_support_rigid_block(p); + let remove = !support(self, below(pos)) + || match shape { + RailShape::AscendingEast => !support(self, rel(pos, Direction::East)), + RailShape::AscendingWest => !support(self, rel(pos, Direction::West)), + RailShape::AscendingNorth => !support(self, rel(pos, Direction::North)), + RailShape::AscendingSouth => !support(self, rel(pos, Direction::South)), + _ => false, + }; + if remove { + self.drop_resources(state, pos); + self.remove_block(pos, moved); + return; + } + let data = b.data(state); + if data.is(Class::PoweredRail) { + self.powered_rail_update(pos, state); + } else if data.is(Class::Rail) { + let changed_default = b.default_of(changed); + if self.is_signal_source_default(changed_default) && self.rail_count_potential_connections(pos) == 3 { + self.rail_update_dir(pos, state, false); + } + } + } + fn is_signal_source_default(&self, state: BlockStateId) -> bool { + self.b.has_flag(state, super::data::state_flags::SIGNAL_SOURCE) + } + fn powered_rail_update(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let powered = b.table.bool(state, b.props.powered); + let should = self.has_neighbor_signal(pos) || self.powered_rail_find(pos, state, true, 0) || self.powered_rail_find(pos, state, false, 0); + if should != powered { + self.set_block_and_update(pos, b.table.set_bool(state, b.props.powered, should)); + let block = b.block(state); + self.update_neighbors_at(below(pos), block); + if RailShape::parse(self.rail_shape(state)).is_slope() { + self.update_neighbors_at(above(pos), block); + } + } + } + fn powered_rail_find(&self, pos: BlockPos, state: BlockStateId, forward: bool, depth: i32) -> bool { + if depth >= 8 { + return false; + } + let (mut x, mut y, mut z) = (pos.x, pos.y, pos.z); + let mut check_below = true; + let mut shape = RailShape::parse(self.rail_shape(state)); + match shape { + RailShape::NorthSouth => z += if forward { 1 } else { -1 }, + RailShape::EastWest => x += if forward { -1 } else { 1 }, + RailShape::AscendingEast => { + if forward { + x -= 1; + } else { + x += 1; + y += 1; + check_below = false; + } + shape = RailShape::EastWest; + } + RailShape::AscendingWest => { + if forward { + x -= 1; + y += 1; + check_below = false; + } else { + x += 1; + } + shape = RailShape::EastWest; + } + RailShape::AscendingNorth => { + if forward { + z += 1; + } else { + z -= 1; + y += 1; + check_below = false; + } + shape = RailShape::NorthSouth; + } + RailShape::AscendingSouth => { + if forward { + z += 1; + y += 1; + check_below = false; + } else { + z -= 1; + } + shape = RailShape::NorthSouth; + } + _ => {} + } + let block = self.b.block(state); + self.powered_rail_same_with_power(BlockPos::new(x, y, z), block, forward, depth, shape) + || (check_below && self.powered_rail_same_with_power(BlockPos::new(x, y - 1, z), block, forward, depth, shape)) + } + fn powered_rail_same_with_power(&self, pos: BlockPos, block: BlockId, forward: bool, depth: i32, dir: RailShape) -> bool { + let b = self.b; + let state = self.state(pos); + if !b.is_block(state, block) { + return false; + } + let mine = RailShape::parse(self.rail_shape(state)); + if dir == RailShape::EastWest && matches!(mine, RailShape::NorthSouth | RailShape::AscendingNorth | RailShape::AscendingSouth) { + return false; + } + if dir == RailShape::NorthSouth && matches!(mine, RailShape::EastWest | RailShape::AscendingEast | RailShape::AscendingWest) { + return false; + } + if !b.table.bool(state, b.props.powered) { + return false; + } + self.has_neighbor_signal(pos) || self.powered_rail_find(pos, state, forward, depth + 1) + } + + // ---- tripwire ---- + + /// `TripWireBlock.updateSource`. + pub(crate) fn tripwire_update_source(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + for direction in [Direction::South, Direction::West] { + for i in 1..42 { + let [dx, dy, dz] = direction.normal(); + let test = pos.offset(dx * i, dy * i, dz * i); + let block = self.state(test); + if b.is_block(block, b.named.tripwire_hook) { + if b.facing(block) == direction.opposite() { + self.tripwire_hook_calculate(test, block, false, true, i, Some(state)); + } + break; + } + if !b.is_block(block, b.named.tripwire) { + break; + } + } + } + } + pub(crate) fn tripwire_tick(&mut self, pos: BlockPos) { + let b = self.b; + let state = self.state(pos); + if b.table.bool(state, b.props.powered) { + self.tripwire_check_pressed(pos); + } + } + /// `TripWireBlock.checkPressed` with the entities currently inside. + pub(crate) fn tripwire_check_pressed(&mut self, pos: BlockPos) { + let b = self.b; + let state = self.state(pos); + let was = b.table.bool(state, b.props.powered); + let top = if b.table.bool(state, b.props.attached) { 2.5 / 16.0 } else { 8.0 / 16.0 }; + let area = Aabb::new( + Vec3::new(f64::from(pos.x), f64::from(pos.y) + 1.0 / 16.0, f64::from(pos.z)), + Vec3::new(f64::from(pos.x) + 1.0, f64::from(pos.y) + top, f64::from(pos.z) + 1.0), + ); + let pressed = self.level.count_entities(area, super::EntityQuery::Everything) > 0; + let block = b.block(state); + if pressed != was { + let next = b.table.set_bool(state, b.props.powered, pressed); + self.set_block_and_update(pos, next); + self.tripwire_update_source(pos, next); + } + if pressed { + self.schedule_tick(pos, block, 10); + } else if was { + self.schedule_tick(pos, block, 1); + } + } + fn tripwire_hook_notify(&mut self, block: BlockId, pos: BlockPos, direction: Direction) { + let front = direction.opposite(); + self.update_neighbors_at(pos, block); + self.update_neighbors_at(rel(pos, front), block); + } + fn tripwire_emit(&mut self, pos: BlockPos, attached: bool, powered: bool, was_attached: bool, was_powered: bool) { + let (sound, volume, pitch, event) = if powered && !was_powered { + ("minecraft:block.tripwire.click_on", 0.4, 0.6, "minecraft:block_activate") + } else if !powered && was_powered { + ("minecraft:block.tripwire.click_off", 0.4, 0.5, "minecraft:block_deactivate") + } else if attached && !was_attached { + ("minecraft:block.tripwire.attach", 0.4, 0.7, "minecraft:block_attach") + } else if !attached && was_attached { + let pitch = 1.2 / (self.random().next_float() * 0.2 + 0.9); + ("minecraft:block.tripwire.detach", 0.4, pitch, "minecraft:block_detach") + } else { + return; + }; + self.emit(LevelEvent::Sound { + pos, + sound: sound.into(), + volume, + pitch, + }); + self.game_event(pos, event); + } + /// `TripWireHookBlock.calculateState`. + pub(crate) fn tripwire_hook_calculate( + &mut self, + pos: BlockPos, + state: BlockStateId, + destroyed: bool, + can_update: bool, + wire_source: i32, + wire_source_state: Option, + ) { + let b = self.b; + let p = b.props; + let Some(direction) = b.table.dir(state, p.facing) else { + return; + }; + let was_attached = b.table.bool(state, p.attached); + let was_powered = b.table.bool(state, p.powered); + let block = b.block(state); + let mut attached = !destroyed; + let mut powered = false; + let mut receiver = 0; + let mut wires: Vec> = vec![None; 42]; + let [dx, dy, dz] = direction.normal(); + for i in 1..42 { + let test = pos.offset(dx * i, dy * i, dz * i); + let mut wire = self.state(test); + if b.is_block(wire, b.named.tripwire_hook) { + if b.facing(wire) == direction.opposite() { + receiver = i; + } + break; + } + if !b.is_block(wire, b.named.tripwire) && i != wire_source { + wires[i as usize] = None; + attached = false; + } else { + if i == wire_source { + wire = wire_source_state.unwrap_or(wire); + } + let armed = !b.table.bool(wire, p.disarmed); + let wire_powered = b.table.bool(wire, p.powered); + powered |= armed && wire_powered; + wires[i as usize] = Some(wire); + if i == wire_source { + self.schedule_tick(pos, block, 10); + attached &= armed; + } + } + } + attached &= receiver > 1; + powered &= attached; + let new_state = b.table.set_bool(b.table.set_bool(b.default_of(block), p.attached, attached), p.powered, powered); + if receiver > 0 { + let test = pos.offset(dx * receiver, dy * receiver, dz * receiver); + let opposite = direction.opposite(); + self.set_block_and_update(test, b.table.set_dir(new_state, p.facing, opposite)); + self.tripwire_hook_notify(block, test, opposite); + if !b.is_block(self.state(pos), b.named.tripwire_hook) { + self.tripwire_hook_removed(pos, new_state); + return; + } + self.tripwire_emit(test, attached, powered, was_attached, was_powered); + } + self.tripwire_emit(pos, attached, powered, was_attached, was_powered); + if !destroyed { + self.set_block_and_update(pos, b.table.set_dir(new_state, p.facing, direction)); + if can_update { + self.tripwire_hook_notify(block, pos, direction); + } + } + if was_attached != attached { + for i in 1..receiver { + let test = pos.offset(dx * i, dy * i, dz * i); + if let Some(wire) = wires[i as usize] { + let current = self.state(test); + if b.is_block(current, b.named.tripwire) || b.is_block(current, b.named.tripwire_hook) { + let next = b.table.with_bool(wire, p.attached, attached).unwrap_or(wire); + self.set_block_and_update(test, next); + } + } + } + } + } + /// `TripWireHookBlock.onRemoved`. + pub(crate) fn tripwire_hook_removed(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let attached = b.table.bool(state, b.props.attached); + let powered = b.table.bool(state, b.props.powered); + if attached || powered { + self.tripwire_hook_calculate(pos, state, true, false, -1, None); + } + if powered { + let facing = b.facing(state); + self.tripwire_hook_notify(b.block(state), pos, facing); + } + } +} diff --git a/crates/horizon-world/src/level/redstone.rs b/crates/horizon-world/src/level/redstone.rs index 9df44d4c6..4838bcf4b 100644 --- a/crates/horizon-world/src/level/redstone.rs +++ b/crates/horizon-world/src/level/redstone.rs @@ -567,7 +567,7 @@ impl Sim<'_, L> { Class::LavaCauldron => 3, Class::RespawnAnchor => { let charges = b.table.int(state, p.charges); - ((charges - 0) as f32 / 4.0 * 15.0).floor() as i32 + (charges as f32 / 4.0 * 15.0).floor() as i32 } Class::CopperGolemStatue => { let pose = b.table.text(state, p.copper_golem_pose); diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs new file mode 100644 index 000000000..4adc35f78 --- /dev/null +++ b/crates/horizon-world/src/level/tests.rs @@ -0,0 +1,436 @@ +//! Behaviour tests over an in-memory level. They need the prepared client +//! resources (`HORIZON_RESOURCES`, or `.local/horizon-client/26.3` at the +//! repository root) and are skipped when those are absent. +use super::*; +use crate::chunk::BlockState; +use std::{ + collections::{BTreeMap, HashMap}, + path::PathBuf, + sync::OnceLock, +}; + +struct Fixture { + registry: BlockRegistry, + behaviours: Behaviours, +} + +fn fixture() -> Option<&'static Fixture> { + static FIXTURE: OnceLock> = OnceLock::new(); + FIXTURE + .get_or_init(|| { + let root = std::env::var_os("HORIZON_RESOURCES").map(PathBuf::from).unwrap_or_else(|| { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3") + }); + if !root.join("block-behaviours.json").exists() { + eprintln!("skipping level tests: no resources at {}", root.display()); + return None; + } + let registry = data::load_registry(&root).expect("registry"); + let behaviours = Behaviours::load(®istry, &root).expect("behaviours"); + Some(Fixture { registry, behaviours }) + }) + .as_ref() +} + +pub(crate) struct TestLevel { + blocks: HashMap, + air: BlockStateId, + random: LegacyRandom, + pub time: i64, + pub events: Vec, + pub block_light: HashMap, +} +impl TestLevel { + fn new(b: &Behaviours) -> Self { + Self { + blocks: HashMap::new(), + air: b.air(), + random: LegacyRandom::new(42), + time: 0, + events: Vec::new(), + block_light: HashMap::new(), + } + } +} +impl LevelAccess for TestLevel { + fn block_state(&self, pos: BlockPos) -> BlockStateId { + self.blocks.get(&pos).copied().unwrap_or(self.air) + } + fn set_raw(&mut self, pos: BlockPos, state: BlockStateId) -> Option { + Some(self.blocks.insert(pos, state).unwrap_or(self.air)) + } + fn is_loaded(&self, _pos: BlockPos) -> bool { + true + } + fn random(&mut self) -> &mut LegacyRandom { + &mut self.random + } + fn game_time(&self) -> i64 { + self.time + } + fn block_light(&self, pos: BlockPos) -> i32 { + self.block_light.get(&pos).copied().unwrap_or(0) + } + fn emit(&mut self, event: LevelEvent) { + self.events.push(event); + } +} + +struct World<'f> { + f: &'f Fixture, + level: TestLevel, + ticks: Ticks, +} +impl<'f> World<'f> { + fn new(f: &'f Fixture) -> Self { + let mut ticks = Ticks::new(0); + for x in -4..4 { + for z in -4..4 { + ticks.add_empty_chunk(ChunkPos::new(x, z)).unwrap(); + } + } + Self { + level: TestLevel::new(&f.behaviours), + f, + ticks, + } + } + fn b(&self) -> &'f Behaviours { + &self.f.behaviours + } + fn id(&self, name: &str, props: &[(&str, &str)]) -> BlockStateId { + let state = BlockState { + name: format!("minecraft:{name}"), + properties: props.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect::>(), + }; + self.f.registry.resolve(&state).unwrap_or_else(|_| panic!("unknown state {name} {props:?}")) + } + fn set(&mut self, pos: BlockPos, state: BlockStateId) -> bool { + self.f.behaviours.set_block(&mut self.level, &mut self.ticks, pos, state, flags::UPDATE_ALL) + } + /// Raw storage write without updates (world generation). + fn put(&mut self, pos: BlockPos, state: BlockStateId) { + self.level.blocks.insert(pos, state); + } + fn get(&self, pos: BlockPos) -> BlockStateId { + self.level.block_state(pos) + } + fn name(&self, pos: BlockPos) -> String { + let state = self.f.registry.state(self.get(pos)).unwrap(); + let props: Vec = state.properties.iter().map(|(k, v)| format!("{k}={v}")).collect(); + format!("{}[{}]", state.name.trim_start_matches("minecraft:"), props.join(",")) + } + fn prop(&self, pos: BlockPos, key: &str) -> String { + self.f.registry.state(self.get(pos)).unwrap().properties.get(key).cloned().unwrap_or_default() + } + fn tick(&mut self) { + self.level.time += 1; + self.f.behaviours.tick_scheduled(&mut self.level, &mut self.ticks); + } + fn floor(&mut self, y: i32, radius: i32, block: &str) { + let state = self.id(block, &[]); + for x in -radius..=radius { + for z in -radius..=radius { + self.put(BlockPos::new(x, y, z), state); + } + } + } +} + +macro_rules! world { + () => {{ + let Some(f) = fixture() else { + return; + }; + World::new(f) + }}; +} + +#[test] +fn state_table_matches_registry() { + let Some(f) = fixture() else { + return; + }; + let t = &f.behaviours.table; + assert_eq!(t.state_count(), f.registry.len()); + let stairs = f.registry.default_state("minecraft:oak_stairs").unwrap(); + let key = f.behaviours.props.facing; + let east = t.with_text(stairs, key, "east").unwrap(); + assert_eq!(f.registry.state(east).unwrap().properties["facing"], "east"); + assert_eq!(t.text(east, f.behaviours.props.half), "bottom"); + assert!(classes::Class::ALL.len() <= 320); +} + +#[test] +fn fences_connect_and_disconnect() { + let mut w = world!(); + let fence = w.id("oak_fence", &[]); + let a = BlockPos::new(0, 1, 0); + let c = BlockPos::new(1, 1, 0); + w.set(a, fence); + w.set(c, fence); + assert_eq!(w.prop(a, "east"), "true"); + assert_eq!(w.prop(c, "west"), "true"); + let stone = w.id("stone", &[]); + w.set(BlockPos::new(0, 1, -1), stone); + assert_eq!(w.prop(a, "north"), "true", "fences connect to sturdy faces"); + let air = w.b().air(); + w.set(c, air); + assert_eq!(w.prop(a, "east"), "false"); +} + +#[test] +fn walls_and_panes_connect() { + let mut w = world!(); + let wall = w.id("cobblestone_wall", &[]); + let pane = w.id("glass_pane", &[]); + w.set(BlockPos::new(0, 1, 0), wall); + w.set(BlockPos::new(0, 1, 1), wall); + w.set(BlockPos::new(0, 1, 2), wall); + assert_eq!(w.prop(BlockPos::new(0, 1, 1), "north"), "low"); + assert_eq!(w.prop(BlockPos::new(0, 1, 1), "south"), "low"); + assert_eq!(w.prop(BlockPos::new(0, 1, 1), "up"), "false", "straight wall drops its post"); + let stone = w.id("stone", &[]); + w.set(BlockPos::new(0, 2, 1), stone); + assert_eq!(w.prop(BlockPos::new(0, 1, 1), "north"), "tall"); + w.set(BlockPos::new(5, 1, 0), pane); + w.set(BlockPos::new(6, 1, 0), pane); + assert_eq!(w.prop(BlockPos::new(5, 1, 0), "east"), "true"); +} + +#[test] +fn stairs_form_corners() { + let mut w = world!(); + let north = w.id("oak_stairs", &[("facing", "north")]); + let east = w.id("oak_stairs", &[("facing", "east")]); + w.set(BlockPos::new(0, 1, 0), north); + w.set(BlockPos::new(0, 1, -1), east); + // The north-facing stair has an east-facing stair behind it. + assert_eq!(w.prop(BlockPos::new(0, 1, 0), "shape"), "outer_right"); +} + +#[test] +fn torch_and_door_halves_break_with_support() { + let mut w = world!(); + w.floor(0, 3, "stone"); + let torch = w.id("torch", &[]); + w.set(BlockPos::new(1, 1, 1), torch); + let door = w.id("oak_door", &[("half", "lower")]); + let upper = w.id("oak_door", &[("half", "upper")]); + w.set(BlockPos::new(0, 1, 0), door); + w.set(BlockPos::new(0, 2, 0), upper); + let air = w.b().air(); + w.set(BlockPos::new(1, 0, 1), air); + assert_eq!(w.get(BlockPos::new(1, 1, 1)), air, "torch pops without support"); + assert!(w.level.events.iter().any(|e| matches!(e, LevelEvent::DropResources { .. }))); + w.set(BlockPos::new(0, 1, 0), air); + assert_eq!(w.get(BlockPos::new(0, 2, 0)), air, "upper door half goes with the lower"); +} + +#[test] +fn snowy_grass_and_chests_pair() { + let mut w = world!(); + let grass = w.id("grass_block", &[]); + w.set(BlockPos::new(0, 0, 0), grass); + let snow = w.id("snow", &[]); + w.set(BlockPos::new(0, 1, 0), snow); + assert_eq!(w.prop(BlockPos::new(0, 0, 0), "snowy"), "true"); + // A left chest's partner sits clockwise of its facing; removing the + // partner makes it single again. + let left = w.id("chest", &[("facing", "north"), ("type", "left")]); + let right = w.id("chest", &[("facing", "north"), ("type", "right")]); + w.set(BlockPos::new(3, 1, 0), left); + w.set(BlockPos::new(4, 1, 0), right); + let air = w.b().air(); + w.set(BlockPos::new(4, 1, 0), air); + assert_eq!(w.prop(BlockPos::new(3, 1, 0), "type"), "single"); +} + +#[test] +fn sand_falls_and_concrete_solidifies() { + let mut w = world!(); + let sand = w.id("sand", &[]); + w.set(BlockPos::new(0, 5, 0), sand); + w.tick(); + w.tick(); + assert_eq!(w.get(BlockPos::new(0, 5, 0)), w.b().air()); + assert!(w.level.events.iter().any(|e| matches!(e, LevelEvent::FallingBlock { state, .. } if *state == sand))); + w.floor(0, 2, "stone"); + let water = w.id("water", &[]); + w.put(BlockPos::new(1, 1, 0), water); + let powder = w.id("white_concrete_powder", &[]); + let landing = w.b().falling_block_landed(&mut w.level, &mut w.ticks, BlockPos::new(0, 1, 0), powder, false); + assert_eq!(landing, falling::Landing::Placed(w.id("white_concrete", &[]))); +} + +#[test] +fn water_spreads_on_a_floor() { + let mut w = world!(); + w.floor(0, 10, "stone"); + let water = w.id("water", &[]); + w.set(BlockPos::new(0, 1, 0), water); + for _ in 0..60 { + w.tick(); + } + for d in 1..=7 { + let pos = BlockPos::new(d, 1, 0); + assert_eq!(w.prop(pos, "level"), d.to_string(), "flow at distance {d}: {}", w.name(pos)); + } + assert_eq!(w.get(BlockPos::new(8, 1, 0)), w.b().air()); + // Diagonals follow Manhattan distance. + assert_eq!(w.prop(BlockPos::new(2, 1, 2), "level"), "4"); +} + +#[test] +fn water_falls_and_makes_sources() { + let mut w = world!(); + w.floor(0, 4, "stone"); + let water = w.id("water", &[]); + w.set(BlockPos::new(0, 4, 0), water); + for _ in 0..30 { + w.tick(); + } + assert_eq!(w.prop(BlockPos::new(0, 3, 0), "level"), "8", "falling water"); + assert_eq!(w.prop(BlockPos::new(0, 1, 0), "level"), "8"); + // Two sources make a third (no holes within slope distance, so the + // sources spread in every direction). + let mut w = world!(); + w.floor(0, 12, "stone"); + w.set(BlockPos::new(0, 1, 0), water); + w.set(BlockPos::new(2, 1, 0), water); + for _ in 0..20 { + w.tick(); + } + assert_eq!(w.get(BlockPos::new(1, 1, 0)), water); + // On a small platform the water instead seeks the nearest edges. + let mut w = world!(); + w.floor(0, 4, "stone"); + w.set(BlockPos::new(0, 1, 0), water); + w.set(BlockPos::new(2, 1, 0), water); + for _ in 0..20 { + w.tick(); + } + assert_eq!(w.get(BlockPos::new(1, 1, 0)), w.b().air()); + assert_eq!(w.prop(BlockPos::new(-1, 1, 0), "level"), "1"); +} + +#[test] +fn lava_meets_water() { + let mut w = world!(); + w.floor(0, 4, "stone"); + let lava = w.id("lava", &[]); + let water = w.id("water", &[]); + w.set(BlockPos::new(0, 1, 0), lava); + w.set(BlockPos::new(1, 1, 0), water); + assert_eq!(w.get(BlockPos::new(0, 1, 0)), w.id("obsidian", &[])); + let mut w = world!(); + w.floor(0, 4, "stone"); + w.set(BlockPos::new(0, 1, 0), lava); + for _ in 0..40 { + w.tick(); + } + w.set(BlockPos::new(1, 2, 0), water); + for _ in 0..40 { + w.tick(); + } + assert_eq!(w.get(BlockPos::new(1, 1, 0)), w.id("cobblestone", &[]), "{}", w.name(BlockPos::new(1, 1, 0))); +} + +#[test] +fn waterlogged_blocks_schedule_water() { + let mut w = world!(); + w.floor(0, 4, "stone"); + let slab = w.id("oak_slab", &[("waterlogged", "true")]); + w.set(BlockPos::new(0, 1, 0), slab); + // A neighbour shape update schedules the slab's water tick. + let stone = w.id("stone", &[]); + w.set(BlockPos::new(0, 1, 1), stone); + for _ in 0..20 { + w.tick(); + } + assert_eq!(w.prop(BlockPos::new(1, 1, 0), "level"), "1"); +} + +#[test] +fn redstone_lever_wire_and_lamp() { + let mut w = world!(); + w.floor(0, 20, "stone"); + let wire = w.id("redstone_wire", &[]); + let lamp = w.id("redstone_lamp", &[]); + let lever = w.id("lever", &[("face", "floor"), ("facing", "north")]); + for x in 1..=5 { + w.set(BlockPos::new(x, 1, 0), wire); + } + w.set(BlockPos::new(6, 1, 0), lamp); + w.set(BlockPos::new(0, 1, 0), lever); + let lever_on = w.b().table.set_bool(w.get(BlockPos::new(0, 1, 0)), w.b().props.powered, true); + w.set(BlockPos::new(0, 1, 0), lever_on); + assert_eq!(w.prop(BlockPos::new(1, 1, 0), "power"), "15"); + assert_eq!(w.prop(BlockPos::new(5, 1, 0), "power"), "11"); + assert_eq!(w.prop(BlockPos::new(6, 1, 0), "lit"), "true"); + let lever_off = w.b().table.set_bool(lever_on, w.b().props.powered, false); + w.set(BlockPos::new(0, 1, 0), lever_off); + assert_eq!(w.prop(BlockPos::new(3, 1, 0), "power"), "0"); + for _ in 0..5 { + w.tick(); + } + assert_eq!(w.prop(BlockPos::new(6, 1, 0), "lit"), "false"); +} + +#[test] +fn repeater_delays_and_torch_inverts() { + let mut w = world!(); + w.floor(0, 10, "stone"); + let block = w.id("redstone_block", &[]); + // A repeater takes its input from the side it faces. + let repeater = w.id("repeater", &[("facing", "west")]); + w.set(BlockPos::new(1, 1, 0), repeater); + w.set(BlockPos::new(0, 1, 0), block); + assert_eq!(w.prop(BlockPos::new(1, 1, 0), "powered"), "false"); + w.tick(); + w.tick(); + assert_eq!(w.prop(BlockPos::new(1, 1, 0), "powered"), "true"); + let torch = w.id("redstone_torch", &[]); + let stone = w.id("stone", &[]); + w.set(BlockPos::new(5, 1, 0), stone); + w.set(BlockPos::new(5, 2, 0), torch); + // A redstone block only weakly powers the stone: the torch stays lit. + w.set(BlockPos::new(6, 1, 0), block); + w.tick(); + w.tick(); + assert_eq!(w.prop(BlockPos::new(5, 2, 0), "lit"), "true"); + // A lever on the stone strongly powers it. + let air = w.b().air(); + w.set(BlockPos::new(6, 1, 0), air); + let lever = w.id("lever", &[("face", "wall"), ("facing", "east"), ("powered", "true")]); + w.set(BlockPos::new(6, 1, 0), lever); + // LeverBlock.pull notifies the attached block's neighbours. + let lever_block = w.b().block(lever); + w.b().update_neighbors_at(&mut w.level, &mut w.ticks, BlockPos::new(5, 1, 0), lever_block); + w.tick(); + w.tick(); + assert_eq!(w.prop(BlockPos::new(5, 2, 0), "lit"), "false"); +} + +#[test] +fn crops_grow_and_leaves_decay() { + let mut w = world!(); + let farmland = w.id("farmland", &[("moisture", "7")]); + let wheat = w.id("wheat", &[]); + w.put(BlockPos::new(0, 0, 0), farmland); + w.put(BlockPos::new(0, 1, 0), wheat); + for _ in 0..400 { + w.b().random_tick(&mut w.level, &mut w.ticks, BlockPos::new(0, 1, 0)); + } + assert_eq!(w.prop(BlockPos::new(0, 1, 0), "age"), "7"); + let leaves = w.id("oak_leaves", &[("distance", "7")]); + w.put(BlockPos::new(5, 5, 5), leaves); + w.b().random_tick(&mut w.level, &mut w.ticks, BlockPos::new(5, 5, 5)); + assert_eq!(w.get(BlockPos::new(5, 5, 5)), w.b().air()); + let log = w.id("oak_log", &[]); + let leaf = w.id("oak_leaves", &[]); + w.set(BlockPos::new(9, 5, 5), leaf); + w.set(BlockPos::new(8, 5, 5), log); + w.tick(); + assert_eq!(w.prop(BlockPos::new(9, 5, 5), "distance"), "1"); +} diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs new file mode 100644 index 000000000..6cd1cf975 --- /dev/null +++ b/crates/horizon-world/src/level/tick.rs @@ -0,0 +1,1173 @@ +//! Scheduled block ticks (`BlockBehaviour.tick`), random ticks +//! (`BlockBehaviour.randomTick`) and the per-tick drivers. +use super::{ + Behaviours, LevelAccess, LevelEvent, Sim, Ticks, + classes::Class, + data::state_flags, + update::{HORIZONTAL, above, below, rel}, +}; +use crate::{fluid::FluidKind, registry::BlockStateId}; +use horizon_core::{ + geometry::Direction, + position::{BlockPos, ChunkPos}, + random::RandomSource, + ticks::TickTypeId, +}; + +impl Sim<'_, L> { + fn rand_int(&mut self, bound: i32) -> i32 { + self.random().next_int_bound(bound).unwrap_or(0) + } + + /// `BlockState.tick` (scheduled block tick). + pub fn tick_block(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let p = b.props; + let block = b.block(state); + let chain = b.data(state).chain.clone(); + for class in chain { + match class { + Class::BambooStalk + | Class::BigDripleafStem + | Class::Cactus + | Class::ChorusFlower + | Class::ChorusPlant + | Class::GrowingPlant + | Class::SugarCane => { + if !self.can_survive(state, pos) { + self.destroy_block(pos, true, 512); + } + } + Class::HangingMoss => { + let above_state = self.above_state(pos); + if !(b.multiface_can_attach(above_state, Direction::Up) || b.is_block(above_state, block)) { + self.destroy_block(pos, true, 512); + } + } + Class::BasePressurePlate => { + let signal = self.plate_signal_for_state(state); + if signal > 0 { + self.plate_check_pressed(pos, state, signal); + } + } + Class::BigDripleaf => self.big_dripleaf_tick(pos, state), + Class::BubbleColumn => { + let below_state = self.below_state(pos); + self.bubble_column_update(pos, state, below_state); + } + Class::Button => self.button_tick(pos, state), + Class::Diode => self.diode_tick(pos, state), + Class::Composter => { + if b.table.int(state, p.level) == 7 { + self.set_block_and_update(pos, b.table.cycle(state, p.level)); + self.emit(LevelEvent::Sound { + pos, + sound: "minecraft:block.composter.ready".into(), + volume: 1.0, + pitch: 1.0, + }); + } + } + Class::Coral => { + if !self.coral_scan_for_water(pos) { + if let Some(dead) = b.data(state).link { + self.set_block(pos, b.default_of(dead), 2); + } + } + } + Class::CoralFan | Class::CoralPlant | Class::CoralWallFan => { + if !self.coral_plant_scan_for_water(state, pos) { + if let Some(dead) = b.data(state).link { + let mut next = b.table.set_bool(b.default_of(dead), p.waterlogged, false); + if class == Class::CoralWallFan { + next = b.table.set_dir(next, p.facing, b.facing(state)); + } + self.set_block(pos, next, 2); + } + } + } + Class::Dispenser | Class::Crafter => { + self.emit(LevelEvent::BlockEvent { pos, state, kind: "dispense" }); + } + Class::FallingBlock => self.falling_block_tick(pos, state), + Class::Brushable => { + if self.is_free(self.below_state(pos)) && pos.y >= self.level.min_y() { + self.falling_block_fall(pos, state); + } + } + Class::Farmland => { + if !self.can_survive(state, pos) { + self.turn_to_base_block(pos, state); + } + } + Class::Path => self.turn_to_base_block(pos, state), + Class::Fire => self.fire_tick(pos, state), + Class::Frogspawn => { + if !self.can_survive(state, pos) { + self.destroy_block(pos, false, 512); + } else { + self.emit(LevelEvent::BlockEvent { pos, state, kind: "hatch" }); + self.destroy_block(pos, false, 512); + } + } + Class::FrostedIce => self.frosted_ice_tick(pos, state), + Class::Leaves => { + let next = self.leaves_update_distance(state, pos); + self.set_block_and_update(pos, next); + } + Class::LightningRod => { + self.set_block_and_update(pos, b.table.set_bool(state, p.powered, false)); + let facing = b.facing(state); + self.update_neighbors_at(rel(pos, facing.opposite()), block); + } + Class::Liquid => { + if self.should_bubble_column_occupy(state) { + let below_state = self.below_state(pos); + let column = b.named.bubble_column; + self.bubble_column_update_for(column, pos, state, below_state); + } + } + Class::Observer => self.observer_tick(pos, state), + Class::RedstoneLamp => self.lamp_tick(pos, state), + Class::RedstoneTorch => self.torch_tick(pos, state), + Class::Scaffolding => self.scaffolding_tick(pos, state), + Class::Speleothem => { + let tip = b.table.dir(state, p.vertical_direction); + if tip == Some(Direction::Up) && !self.can_survive(state, pos) { + self.destroy_block(pos, true, 512); + } else { + self.spawn_falling_stalactite(pos, state); + } + } + Class::Target => { + if b.table.int(state, p.power) != 0 { + self.set_block_and_update(pos, b.table.set_int(state, p.power, 0)); + } + } + Class::TripWire => self.tripwire_tick(pos), + Class::TripWireHook => self.tripwire_hook_calculate(pos, state, false, true, -1, None), + _ => continue, + } + return; + } + } + + /// `BlockState.randomTick` followed by the fluid's random tick. + pub fn random_tick_at(&mut self, pos: BlockPos) { + let state = self.state(pos); + if self.b.is_randomly_ticking(state) { + self.random_tick_block(state, pos); + } + // Only lava's fluid state ticks randomly. + let fluid = self.b.fluid(state).kind(); + if matches!(fluid, FluidKind::Lava | FluidKind::FlowingLava) && !self.b.instance_of(state, Class::Liquid) { + self.lava_random_tick(pos); + } + } + + pub fn random_tick_block(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let p = b.props; + let block = b.block(state); + let data = b.data(state); + let chain = data.chain.clone(); + for class in chain.iter().copied() { + match class { + Class::BambooSapling => { + if self.rand_int(3) == 0 && self.is_empty_block(above(pos)) && self.raw_brightness(above(pos), 0) >= 9 { + self.bamboo_sapling_grow(pos); + } + } + Class::BambooStalk => { + if b.table.int(state, p.stage) == 0 + && self.rand_int(3) == 0 + && self.is_empty_block(above(pos)) + && self.raw_brightness(above(pos), 0) >= 9 + { + let height = self.bamboo_height_below(pos) + 1; + if height < 16 { + self.bamboo_grow(state, pos, height); + } + } + } + Class::Beetroot | Class::TorchflowerCrop => { + if self.rand_int(3) != 0 { + self.crop_random_tick(state, pos); + } + } + Class::Crop => self.crop_random_tick(state, pos), + Class::BuddingAmethyst => self.budding_amethyst_tick(pos), + Class::Cactus => self.cactus_random_tick(state, pos), + Class::Cocoa => { + if self.rand_int(5) == 0 { + let age = b.table.int(state, p.age); + if age < 2 { + self.set_block(pos, b.table.set_int(state, p.age, age + 1), 2); + } + } + } + Class::Farmland => self.farmland_random_tick(state, pos), + Class::GrowingPlantHead => { + if b.table.int(state, p.age) < 25 && self.random().next_double() < data.grow_probability { + let growth = rel(pos, data.growth_direction); + if self.growing_plant_can_grow_into(state, self.state(growth)) { + let next = self.growing_plant_grow_into_state(state); + self.set_block_and_update(growth, next); + } + } + } + Class::Ice => { + if self.level.block_light(pos) > 11 - i32::from(b.facts(state).dampening) { + self.ice_melt(pos); + } + } + Class::Leaves => { + if !b.table.bool(state, p.persistent) && b.table.int(state, p.distance) == 7 { + self.drop_resources(state, pos); + self.remove_block(pos, false); + } + } + Class::Liquid => self.lava_random_tick(pos), + Class::MangrovePropagule => { + if !b.table.bool(state, p.hanging) { + if self.rand_int(7) == 0 { + self.sapling_advance_tree(pos, state); + } + } else if b.table.int(state, p.age) != 4 { + self.set_block(pos, b.table.cycle(state, p.age), 2); + } + } + Class::Sapling => { + if self.max_local_raw_brightness(above(pos)) >= 9 && self.rand_int(7) == 0 { + self.sapling_advance_tree(pos, state); + } + } + Class::Mushroom => self.mushroom_random_tick(state, pos), + Class::NetherWart => { + let age = b.table.int(state, p.age); + if age < 3 && self.rand_int(10) == 0 { + self.set_block(pos, b.table.set_int(state, p.age, age + 1), 2); + } + } + Class::Nylium => { + if !self.can_be_nylium(state, pos) { + self.set_block_and_update(pos, b.default_of(b.named.netherrack)); + } + } + Class::PitcherCrop => { + let speed = self.crop_growth_speed(block, pos); + if self.rand_int((25.0 / speed) as i32 + 1) == 0 { + self.pitcher_grow(state, pos, 1); + } + } + Class::RedStoneOre => { + if b.table.bool(state, p.lit) { + self.set_block_and_update(pos, b.table.set_bool(state, p.lit, false)); + } + } + Class::SnowLayer => { + if self.level.block_light(pos) > 11 { + self.drop_resources(state, pos); + self.remove_block(pos, false); + self.game_event(pos, "minecraft:block_destroy"); + } + } + Class::SpreadingSnowy => self.spreading_snowy_tick(state, pos), + Class::Stem => self.stem_random_tick(state, pos), + Class::SugarCane => { + if self.is_empty_block(above(pos)) { + let mut height = 1; + while b.is_block(self.state(pos.offset(0, -height, 0)), block) { + height += 1; + } + if height < 3 { + let age = b.table.int(state, p.age); + if age == 15 { + self.set_block_and_update(above(pos), b.default_of(block)); + self.set_block(pos, b.table.set_int(state, p.age, 0), 260); + } else { + self.set_block(pos, b.table.set_int(state, p.age, age + 1), 260); + } + } + } + } + Class::SweetBerryBush => { + let age = b.table.int(state, p.age); + if age < 3 && self.rand_int(5) == 0 && self.raw_brightness(above(pos), 0) >= 9 { + let next = b.table.set_int(state, p.age, age + 1); + self.set_block(pos, next, 2); + self.game_event(pos, "minecraft:block_change"); + } + } + Class::Vine => self.vine_random_tick(state, pos), + Class::WeatheringCopperFull => self.copper_change_over_time(state, pos), + _ => continue, + } + return; + } + if data.implements(super::classes::Interface::WeatheringCopper) { + let upper_door = data.is(Class::Door) && b.table.text(state, p.half) == "upper"; + let right_chest = data.is(Class::Chest) && b.table.text(state, p.kind) == "right"; + if !upper_door && !right_chest { + self.copper_change_over_time(state, pos); + } + } + } + + // ---- helpers ---- + + pub(crate) fn turn_to_base_block(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let base = b.data(state).link.unwrap_or(b.named.dirt); + self.set_block_and_update(pos, b.default_of(base)); + self.game_event(pos, "minecraft:block_change"); + } + /// `FallingBlock.isFree`. + pub(crate) fn is_free(&self, state: BlockStateId) -> bool { + let b = self.b; + b.is_air(state) || b.tag("minecraft:fire").is_some_and(|tag| b.in_set(state, tag)) || b.liquid(state) || b.is_replaceable(state) + } + fn leaves_update_distance(&self, state: BlockStateId, pos: BlockPos) -> BlockStateId { + let mut distance = 7; + for direction in Direction::ALL { + distance = distance.min(self.leaf_distance_at(self.rel_state(pos, direction)) + 1); + if distance == 1 { + break; + } + } + self.b.table.set_int(state, self.b.props.distance, distance) + } + fn bubble_column_update(&mut self, pos: BlockPos, state: BlockStateId, below_state: BlockStateId) { + let column = self.b.block(state); + self.bubble_column_update_for(column, pos, state, below_state); + } + /// `BubbleColumnBlock.updateColumn(column, level, pos, occupyState, belowState)`. + pub(crate) fn bubble_column_update_for(&mut self, column: super::states::BlockId, pos: BlockPos, occupy: BlockStateId, below_state: BlockStateId) { + let b = self.b; + if !self.bubble_column_can_occupy(occupy) { + return; + } + let column_state = if b.is_block(below_state, column) { + below_state + } else if b.in_set(below_state, &b.tags.enables_bubble_column_push_up) { + b.table.set_bool(b.default_of(column), b.props.drag, false) + } else if b.in_set(below_state, &b.tags.enables_bubble_column_drag_down) { + b.table.set_bool(b.default_of(column), b.props.drag, true) + } else if b.is_block(occupy, column) { + b.default_of(b.named.water) + } else { + occupy + }; + self.set_block(pos, column_state, 2); + let mut up = above(pos); + while self.bubble_column_can_occupy(self.state(up)) { + if !self.set_block(up, column_state, 2) { + return; + } + up = above(up); + } + } + fn big_dripleaf_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + if self.has_neighbor_signal(pos) { + let next = b.table.set_text(state, b.props.tilt, "none"); + self.set_block(pos, next, 2); + if b.table.text(state, b.props.tilt) != "none" { + let pitch = self.random().next_float() * 0.4 + 0.8; + self.emit(LevelEvent::Sound { + pos, + sound: "minecraft:block.big_dripleaf.tilt_up".into(), + volume: 1.0, + pitch, + }); + } + return; + } + let (next, delay) = match b.table.text(state, b.props.tilt) { + "unstable" => ("partial", Some(10)), + "partial" => ("full", Some(100)), + "full" => ("none", None), + _ => return, + }; + let next_state = b.table.set_text(state, b.props.tilt, next); + self.set_block(pos, next_state, 2); + if next != "none" { + self.game_event(pos, "minecraft:block_change"); + } + let pitch = self.random().next_float() * 0.4 + 0.8; + let sound = if next == "none" { + "minecraft:block.big_dripleaf.tilt_up" + } else { + "minecraft:block.big_dripleaf.tilt_down" + }; + self.emit(LevelEvent::Sound { + pos, + sound: sound.into(), + volume: 1.0, + pitch, + }); + if let Some(delay) = delay { + self.schedule_tick(pos, b.block(state), delay); + } + } + fn scaffolding_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let distance = self.scaffolding_distance(pos); + let bottom = self.scaffolding_is_bottom(pos, distance); + let next = b.table.set_bool(b.table.set_int(state, b.props.distance, distance), b.props.bottom, bottom); + if distance == 7 { + if b.table.int(state, b.props.distance) == 7 { + self.falling_block_fall(pos, next); + } else { + self.destroy_block(pos, true, 512); + } + } else if state != next { + self.set_block_and_update(pos, next); + } + } + /// `ScaffoldingBlock.isBottom`. + pub(crate) fn scaffolding_is_bottom(&self, pos: BlockPos, distance: i32) -> bool { + let b = self.b; + distance > 0 && !b.is_block(self.below_state(pos), b.named.scaffolding) + } + fn fire_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let p = b.props; + let block = b.block(state); + let delay = 30 + self.rand_int(10); + self.schedule_tick(pos, block, delay); + if !self.level.can_spread_fire_around(pos) { + return; + } + if !self.can_survive(state, pos) { + self.remove_block(pos, false); + } + let below_state = self.below_state(pos); + let infiniburn = match self.level.dimension() { + super::Dimension::Overworld => &b.tags.infiniburn_overworld, + super::Dimension::Nether => &b.tags.infiniburn_nether, + super::Dimension::End => &b.tags.infiniburn_end, + }; + let infini = b.in_set(below_state, infiniburn); + let age = b.table.int(state, p.age); + let raining = self.level.is_raining(); + if !infini && raining && self.fire_near_rain(pos) && self.random().next_float() < 0.2 + age as f32 * 0.03 { + self.remove_block(pos, false); + return; + } + let new_age = 15.min(age + self.rand_int(3) / 2); + let mut state = state; + if age != new_age { + state = b.table.set_int(state, p.age, new_age); + self.set_block(pos, state, 260); + } + if !infini { + if !self.is_valid_fire_location(pos) { + if !self.sturdy(below(pos), Direction::Up) || age > 3 { + self.remove_block(pos, false); + } + return; + } + if age == 15 && self.rand_int(4) == 0 && !self.can_burn(self.below_state(pos)) { + self.remove_block(pos, false); + return; + } + } + let burnout = self.level.dimension() == super::Dimension::Nether && false; + let extra = if burnout { -50 } else { 0 }; + for (direction, chance) in [ + (Direction::East, 300), + (Direction::West, 300), + (Direction::Down, 250), + (Direction::Up, 250), + (Direction::North, 300), + (Direction::South, 300), + ] { + self.fire_check_burn_out(rel(pos, direction), chance + extra, age); + } + for xx in -1..=1 { + for zz in -1..=1 { + for yy in -1..=4 { + if xx == 0 && yy == 0 && zz == 0 { + continue; + } + let mut rate = 100; + if yy > 1 { + rate += (yy - 1) * 100; + } + let test = pos.offset(xx, yy, zz); + let ignite = self.fire_ignite_odds_at(test); + if ignite > 0 { + let mut odds = (ignite + 40 + self.level.difficulty() * 7) / (age + 30); + if burnout { + odds /= 2; + } + if odds > 0 && self.rand_int(rate) <= odds && (!self.level.is_raining() || !self.fire_near_rain(test)) { + let spread_age = 15.min(age + self.rand_int(5) / 4); + let next = self.fire_state_with_age(test, spread_age); + self.set_block_and_update(test, next); + } + } + } + } + } + } + /// `FireBlock.getIgniteOdds(level, pos)`: only for air with flammable neighbours. + fn fire_ignite_odds_at(&self, pos: BlockPos) -> i32 { + if !self.is_empty_block(pos) { + return 0; + } + Direction::ALL.into_iter().map(|d| self.ignite_odds(self.rel_state(pos, d))).max().unwrap_or(0) + } + fn fire_near_rain(&self, pos: BlockPos) -> bool { + self.level.is_raining_at(pos) + || self.level.is_raining_at(rel(pos, Direction::West)) + || self.level.is_raining_at(rel(pos, Direction::East)) + || self.level.is_raining_at(rel(pos, Direction::North)) + || self.level.is_raining_at(rel(pos, Direction::South)) + } + fn fire_check_burn_out(&mut self, pos: BlockPos, chance: i32, age: i32) { + let b = self.b; + let odds = self.burn_odds(self.state(pos)); + if self.rand_int(chance) < odds { + let old = self.state(pos); + if self.rand_int(age + 10) < 5 && !self.level.is_raining_at(pos) { + let new_age = (age + self.rand_int(5) / 4).min(15); + let next = self.fire_state_with_age(pos, new_age); + self.set_block_and_update(pos, next); + } else { + self.remove_block(pos, false); + } + if b.instance_of(old, Class::Tnt) { + self.emit(LevelEvent::PrimeTnt { pos }); + } + } + } + fn frosted_ice_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let block = b.block(state); + let fewer = |sim: &Self, at: BlockPos, limit: i32| { + let mut count = 0; + for d in Direction::ALL { + if sim.b.is_block(sim.rel_state(at, d), block) { + count += 1; + if count >= limit { + return false; + } + } + } + true + }; + if self.rand_int(3) == 0 || fewer(self, pos, 4) { + let brightness = if self.level.dimension() == super::Dimension::End { + self.level.block_light(pos) + } else { + self.max_local_raw_brightness(pos) + }; + let age = b.table.int(state, b.props.age); + if brightness > 11 - age - i32::from(b.facts(state).dampening) && self.frosted_slightly_melt(pos, state) { + for direction in Direction::ALL { + let neighbour_pos = rel(pos, direction); + let neighbour = self.state(neighbour_pos); + if b.is_block(neighbour, block) && !self.frosted_slightly_melt(neighbour_pos, neighbour) { + let delay = self.random().next_int_between_inclusive(20, 40).unwrap_or(20); + self.schedule_tick(neighbour_pos, block, delay); + } + } + return; + } + } + let delay = self.random().next_int_between_inclusive(20, 40).unwrap_or(20); + self.schedule_tick(pos, block, delay); + } + fn frosted_slightly_melt(&mut self, pos: BlockPos, state: BlockStateId) -> bool { + let b = self.b; + let age = b.table.int(state, b.props.age); + if age < 3 { + self.set_block(pos, b.table.set_int(state, b.props.age, age + 1), 2); + false + } else { + self.ice_melt(pos); + true + } + } + + // ---- crops and plants ---- + + /// `CropBlock.getGrowthSpeed`. + pub(crate) fn crop_growth_speed(&self, block: super::states::BlockId, pos: BlockPos) -> f32 { + let b = self.b; + let mut speed = 1.0f32; + let under = below(pos); + for xx in -1..=1 { + for zz in -1..=1 { + let mut block_speed = 0.0f32; + let state = self.state(under.offset(xx, 0, zz)); + if b.in_set(state, &b.tags.grows_crops) { + block_speed = 1.0; + if b.table.int(state, b.props.moisture) > 0 { + block_speed = 3.0; + } + } + if xx != 0 || zz != 0 { + block_speed /= 4.0; + } + speed += block_speed; + } + } + let is = |at: BlockPos| b.is_block(self.state(at), block); + let (n, s, w, e) = (rel(pos, Direction::North), rel(pos, Direction::South), rel(pos, Direction::West), rel(pos, Direction::East)); + let horizontal = is(w) || is(e); + let vertical = is(n) || is(s); + let diagonal = is(rel(w, Direction::North)) || is(rel(e, Direction::North)) || is(rel(e, Direction::South)) || is(rel(w, Direction::South)); + if (horizontal && vertical) || diagonal { + speed /= 2.0; + } + speed + } + fn crop_random_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + if self.raw_brightness(pos, 0) < 9 { + return; + } + let age = b.table.int(state, b.props.age); + let max = b.table.int_range(state, b.props.age).map_or(7, |r| r.1); + if age < max { + let speed = self.crop_growth_speed(b.block(state), pos); + if self.rand_int((25.0 / speed) as i32 + 1) == 0 { + self.set_block(pos, b.table.set_int(state, b.props.age, age + 1), 2); + } + } + } + fn stem_random_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + if self.raw_brightness(pos, 0) < 9 { + return; + } + let speed = self.crop_growth_speed(b.block(state), pos); + if self.rand_int((25.0 / speed) as i32 + 1) != 0 { + return; + } + let age = b.table.int(state, b.props.age); + if age < 7 { + self.set_block(pos, b.table.set_int(state, b.props.age, age + 1), 2); + return; + } + let direction = HORIZONTAL[self.rand_int(4) as usize]; + let relative = rel(pos, direction); + let data = b.data(state); + let below_state = self.below_state(relative); + if b.is_air(self.state(relative)) && data.support_tag2.as_ref().is_some_and(|tag| b.in_set(below_state, tag)) { + if let (Some(fruit), Some(stem)) = (data.link, data.link2) { + self.set_block_and_update(relative, b.default_of(fruit)); + self.set_block_and_update(pos, b.table.set_dir(b.default_of(stem), b.props.facing, direction)); + } + } + } + /// `PitcherCropBlock.grow`. + pub(crate) fn pitcher_grow(&mut self, state: BlockStateId, pos: BlockPos, increase: i32) { + let b = self.b; + let p = b.props; + let (lower_pos, lower) = if b.table.text(state, p.half) == "upper" { + let below_pos = below(pos); + let below_state = self.state(below_pos); + if !b.is_block(below_state, b.named.pitcher_crop) || b.table.text(below_state, p.half) != "lower" { + return; + } + (below_pos, below_state) + } else { + (pos, state) + }; + let new_age = b.table.int(lower, p.age) + increase; + let can_grow = b.table.int(lower, p.age) < 4 + && self.raw_brightness(lower_pos, 0) >= 8 + && self.is_inside_build_height(lower_pos.y + 1) + && (new_age < 3 || { + let upper = self.state(above(lower_pos)); + b.is_air(upper) || b.is_block(upper, b.named.pitcher_crop) + }); + if !can_grow { + return; + } + let grown = b.table.set_int(lower, p.age, new_age); + self.set_block(lower_pos, grown, 2); + if new_age >= 3 { + let upper_pos = above(lower_pos); + let upper = b.table.set_text(grown, p.half, "upper"); + let upper = b.table.with_bool(upper, p.waterlogged, self.is_water_at(upper_pos)).unwrap_or(upper); + self.set_block(upper_pos, upper, 3); + } + } + fn growing_plant_can_grow_into(&self, plant: BlockStateId, state: BlockStateId) -> bool { + let b = self.b; + let data = b.data(plant); + if data.is(Class::Kelp) { + b.is_block(state, b.named.water) && b.fluid(state).amount() == 8 + } else { + // NetherVines.isValidGrowthState / CaveVines: air only. + b.is_air(state) + } + } + fn growing_plant_grow_into_state(&mut self, state: BlockStateId) -> BlockStateId { + let b = self.b; + let next = b.table.cycle(state, b.props.age); + if b.instance_of(state, Class::CaveVines) { + let berries = self.random().next_float() < 0.11; + return b.table.set_bool(next, b.props.berries, berries); + } + next + } + fn cactus_random_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let block = b.block(state); + let above_pos = above(pos); + if !self.is_empty_block(above_pos) { + return; + } + let mut height = 1; + let age = b.table.int(state, b.props.age); + while b.is_block(self.state(pos.offset(0, -height, 0)), block) { + height += 1; + if height == 3 && age == 15 { + return; + } + } + if age == 8 && self.can_survive(b.default_of(block), above_pos) { + let chance = if height >= 3 { 0.25 } else { 0.1 }; + if self.random().next_double() <= chance { + self.set_block_and_update(above_pos, b.default_of(b.named.cactus_flower)); + } + } else if age == 15 && height < 3 { + self.set_block_and_update(above_pos, b.default_of(block)); + let reset = b.table.set_int(state, b.props.age, 0); + self.set_block(pos, reset, 260); + self.neighbor_changed_full(reset, above_pos, block, false); + } + if age < 15 { + self.set_block(pos, b.table.set_int(state, b.props.age, age + 1), 260); + } + } + fn farmland_random_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let moisture = b.table.int(state, b.props.moisture); + let mut near_water = false; + 'search: for x in -4..=4 { + for y in 0..=1 { + for z in -4..=4 { + if b.is_water_fluid(self.fluid_at(pos.offset(x, y, z)).kind()) { + near_water = true; + break 'search; + } + } + } + } + if !near_water && !self.level.is_raining_at(above(pos)) { + if moisture > 0 { + self.set_block(pos, b.table.set_int(state, b.props.moisture, moisture - 1), 2); + } else if !b.in_set(self.above_state(pos), &b.tags.maintains_farmland) { + self.turn_to_base_block(pos, state); + } + } else if moisture < 7 { + self.set_block(pos, b.table.set_int(state, b.props.moisture, 7), 2); + } + } + /// `SaplingBlock.advanceTree`. + pub(crate) fn sapling_advance_tree(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + if b.table.int(state, b.props.stage) == 0 { + self.set_block(pos, b.table.cycle(state, b.props.stage), 260); + } else if let Some(grower) = b.data(state).feature.clone() { + self.emit(LevelEvent::GrowTree { pos, state, grower }); + } + } + fn mushroom_random_tick(&mut self, state: BlockStateId, mut pos: BlockPos) { + let b = self.b; + if self.rand_int(25) != 0 { + return; + } + // canSpread: at most four of this mushroom within a 9x3x9 box. + let block = b.block(state); + let mut max = 5; + for x in -4..=4 { + for y in -1..=1 { + for z in -4..=4 { + if b.is_block(self.state(pos.offset(x, y, z)), block) { + max -= 1; + if max <= 0 { + return; + } + } + } + } + } + let mut offset = self.mushroom_offset(pos); + for _ in 0..4 { + if self.is_empty_block(offset) && self.can_survive(state, offset) { + pos = offset; + } + offset = self.mushroom_offset(pos); + } + if self.is_empty_block(offset) && self.can_survive(state, offset) { + self.set_block(offset, state, 2); + } + } + fn mushroom_offset(&mut self, pos: BlockPos) -> BlockPos { + let x = self.rand_int(3) - 1; + let y = self.rand_int(2) - self.rand_int(2); + let z = self.rand_int(3) - 1; + pos.offset(x, y, z) + } + /// `LightEngine.getLightDampeningInto(state, above, UP, above.dampening) < 15`. + fn top_face_lets_light(&self, state: BlockStateId, above_state: BlockStateId) -> bool { + let b = self.b; + let occluding = |s: BlockStateId| b.has_flag(s, state_flags::CAN_OCCLUDE) && b.has_flag(s, super::data::state_flags::SHAPE_OCCLUSION); + let dampening = i32::from(b.facts(above_state).dampening); + let from_full = occluding(state) && b.collision_face_full(state, Direction::Up); + let to_full = occluding(above_state) && b.collision_face_full(above_state, Direction::Down); + let into = if !occluding(state) && !occluding(above_state) { + dampening + } else if from_full || to_full { + 16 + } else { + dampening + }; + into < 15 + } + fn can_be_nylium(&self, state: BlockStateId, pos: BlockPos) -> bool { + self.top_face_lets_light(state, self.above_state(pos)) + } + fn snowy_can_stay_alive(&self, state: BlockStateId, pos: BlockPos) -> bool { + let b = self.b; + let above_state = self.above_state(pos); + if b.is_block(above_state, b.named.snow) && b.table.int(above_state, b.props.layers) == 1 { + return true; + } + if b.fluid(above_state).is_full() { + return false; + } + self.top_face_lets_light(state, above_state) + } + fn spreading_snowy_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let base = b.data(state).link.unwrap_or(b.named.dirt); + if !self.snowy_can_stay_alive(state, pos) { + self.set_block_and_update(pos, b.default_of(base)); + return; + } + if self.max_local_raw_brightness(above(pos)) < 9 { + return; + } + let default = b.default_of(b.block(state)); + for _ in 0..4 { + let x = self.rand_int(3) - 1; + let y = self.rand_int(5) - 3; + let z = self.rand_int(3) - 1; + let test = pos.offset(x, y, z); + if b.is_block(self.state(test), base) + && self.snowy_can_stay_alive(default, test) + && !b.is_water_fluid(self.fluid_at(above(test)).kind()) + { + let snowy = b.in_set(self.above_state(test), &b.tags.snow); + self.set_block_and_update(test, b.table.set_bool(default, b.props.snowy, snowy)); + } + } + } + fn budding_amethyst_tick(&mut self, pos: BlockPos) { + let b = self.b; + if self.rand_int(5) != 0 { + return; + } + let direction = Direction::ALL[self.rand_int(6) as usize]; + let grow = rel(pos, direction); + let relative = self.state(grow); + let name = |n: &str| b.table.block_by_name(n); + let stages = ["minecraft:small_amethyst_bud", "minecraft:medium_amethyst_bud", "minecraft:large_amethyst_bud", "minecraft:amethyst_cluster"]; + let fluid = b.fluid(relative); + let can_cluster_grow = b.is_air(relative) || (b.is_block(relative, b.named.water) && fluid.amount() == 8); + let next = if can_cluster_grow { + name(stages[0]) + } else { + let mut found = None; + for i in 0..3 { + if name(stages[i]).is_some_and(|s| b.is_block(relative, s)) && b.facing(relative) == direction { + found = name(stages[i + 1]); + } + } + found + }; + if let Some(next) = next { + let state = b.table.set_dir(b.default_of(next), b.props.facing, direction); + let state = b.table.set_bool(state, b.props.waterlogged, fluid == crate::fluid::FluidState::WATER); + self.set_block_and_update(grow, state); + } + } + fn bamboo_sapling_grow(&mut self, pos: BlockPos) { + let b = self.b; + let bamboo = b.default_of(b.named.bamboo); + let state = b.table.set_text(bamboo, b.props.leaves, "small"); + self.set_block(above(pos), state, 3); + } + fn bamboo_height_below(&self, pos: BlockPos) -> i32 { + let mut height = 0; + while height < 16 && self.b.is_block(self.state(pos.offset(0, -(height + 1), 0)), self.b.named.bamboo) { + height += 1; + } + height + } + fn bamboo_height_above(&self, pos: BlockPos) -> i32 { + let mut height = 0; + while height < 16 && self.b.is_block(self.state(pos.offset(0, height + 1, 0)), self.b.named.bamboo) { + height += 1; + } + height + } + /// `BambooStalkBlock.growBamboo`. + fn bamboo_grow(&mut self, state: BlockStateId, pos: BlockPos, height: i32) { + let b = self.b; + let p = b.props; + let below_state = self.below_state(pos); + let below_two = pos.offset(0, -2, 0); + let below_two_state = self.state(below_two); + let mut leaves = "none"; + if height >= 1 { + if !b.is_block(below_state, b.named.bamboo) || b.table.text(below_state, p.leaves) == "none" { + leaves = "small"; + } else if b.is_block(below_state, b.named.bamboo) && b.table.text(below_state, p.leaves) != "none" { + leaves = "large"; + if b.is_block(below_two_state, b.named.bamboo) { + self.set_block(below(pos), b.table.set_text(below_state, p.leaves, "small"), 3); + self.set_block(below_two, b.table.set_text(below_two_state, p.leaves, "none"), 3); + } + } + } + let age = if b.table.int(state, p.age) != 1 && !b.is_block(below_two_state, b.named.bamboo) { 0 } else { 1 }; + let stage = if (height < 11 || self.random().next_float() >= 0.25) && height != 15 { 0 } else { 1 }; + let next = b.table.set_int(b.table.set_int(b.table.set_text(b.default_of(b.named.bamboo), p.leaves, leaves), p.age, age), p.stage, stage); + let _ = self.bamboo_height_above(pos); + self.set_block(above(pos), next, 3); + } + /// `VineBlock.randomTick`. + fn vine_random_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let p = b.props; + let block = b.block(state); + if self.rand_int(4) != 0 { + return; + } + let direction = Direction::ALL[self.rand_int(6) as usize]; + let above_pos = above(pos); + let default = b.default_of(block); + if super::query::is_horizontal(direction) && !b.table.bool(state, self.direction_prop(direction)) { + if !self.vine_can_spread(pos, block) { + return; + } + let test = rel(pos, direction); + let edge = self.state(test); + if b.is_air(edge) { + let cw = super::query::clockwise(direction); + let ccw = super::query::counter_clockwise(direction); + let cw_face = b.table.bool(state, self.direction_prop(cw)); + let ccw_face = b.table.bool(state, self.direction_prop(ccw)); + let cw_test = rel(test, cw); + let ccw_test = rel(test, ccw); + if cw_face && b.multiface_can_attach(self.state(cw_test), cw) { + self.set_block(test, b.table.set_bool(default, self.direction_prop(cw), true), 2); + } else if ccw_face && b.multiface_can_attach(self.state(ccw_test), ccw) { + self.set_block(test, b.table.set_bool(default, self.direction_prop(ccw), true), 2); + } else { + let opposite = direction.opposite(); + if cw_face && self.is_empty_block(cw_test) && b.multiface_can_attach(self.rel_state(pos, cw), opposite) { + self.set_block(cw_test, b.table.set_bool(default, self.direction_prop(opposite), true), 2); + } else if ccw_face && self.is_empty_block(ccw_test) && b.multiface_can_attach(self.rel_state(pos, ccw), opposite) { + self.set_block(ccw_test, b.table.set_bool(default, self.direction_prop(opposite), true), 2); + } else if self.random().next_float() < 0.05 && b.multiface_can_attach(self.state(above(test)), Direction::Up) { + self.set_block(test, b.table.set_bool(default, p.up, true), 2); + } + } + } else if b.multiface_can_attach(edge, direction) { + self.set_block(pos, b.table.set_bool(state, self.direction_prop(direction), true), 2); + } + return; + } + if direction == Direction::Up && pos.y < self.level.max_y() - 1 { + if b.multiface_can_attach(self.state(above_pos), Direction::Up) { + self.set_block(pos, b.table.set_bool(state, p.up, true), 2); + return; + } + if self.is_empty_block(above_pos) { + if !self.vine_can_spread(pos, block) { + return; + } + let mut above_state = state; + for d in HORIZONTAL { + if self.random().next_boolean() || !b.multiface_can_attach(self.state(rel(above_pos, d)), d) { + above_state = b.table.set_bool(above_state, self.direction_prop(d), false); + } + } + if HORIZONTAL.into_iter().any(|d| b.table.bool(above_state, self.direction_prop(d))) { + self.set_block(above_pos, above_state, 2); + } + return; + } + } + if pos.y > self.level.min_y() { + let below_pos = below(pos); + let below_state = self.state(below_pos); + if b.is_air(below_state) || b.is_block(below_state, block) { + let before = if b.is_air(below_state) { default } else { below_state }; + let mut after = before; + for d in HORIZONTAL { + if self.random().next_boolean() && b.table.bool(state, self.direction_prop(d)) { + after = b.table.set_bool(after, self.direction_prop(d), true); + } + } + if before != after && HORIZONTAL.into_iter().any(|d| b.table.bool(after, self.direction_prop(d))) { + self.set_block(below_pos, after, 2); + } + } + } + } + fn vine_can_spread(&self, pos: BlockPos, block: super::states::BlockId) -> bool { + let mut max = 5; + for x in -4..=4 { + for y in -1..=1 { + for z in -4..=4 { + if self.b.is_block(self.state(pos.offset(x, y, z)), block) { + max -= 1; + if max <= 0 { + return false; + } + } + } + } + } + true + } + /// `ChangeOverTimeBlock.changeOverTime` for weathering copper. + fn copper_change_over_time(&mut self, state: BlockStateId, pos: BlockPos) { + if self.random().next_float() >= 0.056_888_89 { + return; + } + let b = self.b; + let own = b.data(state).weather; + let (mut same, mut older) = (0, 0); + for x in -4i32..=4 { + for y in -4i32..=4 { + for z in -4i32..=4 { + if x.abs() + y.abs() + z.abs() > 4 || (x == 0 && y == 0 && z == 0) { + continue; + } + let other = self.state(pos.offset(x, y, z)); + let data = b.data(other); + if !data.implements(super::classes::Interface::WeatheringCopper) { + continue; + } + match data.weather.cmp(&own) { + std::cmp::Ordering::Less => return, + std::cmp::Ordering::Greater => older += 1, + std::cmp::Ordering::Equal => same += 1, + } + } + } + } + let chance = (older + 1) as f32 / (older + same + 1) as f32; + let modifier = if own == 0 { 0.75 } else { 1.0 }; + if self.random().next_float() < chance * chance * modifier { + if let Some(next) = self.copper_next(state) { + self.set_block_and_update(pos, next); + } + } + } + /// `WeatheringCopper.getNext` by registry naming. + pub(crate) fn copper_next(&self, state: BlockStateId) -> Option { + let b = self.b; + let name = &*b.table.info(b.block(state)).name; + let path = name.strip_prefix("minecraft:")?; + let next = if path == "copper_block" { + "exposed_copper".to_owned() + } else if let Some(rest) = path.strip_prefix("exposed_") { + format!("weathered_{rest}") + } else if let Some(rest) = path.strip_prefix("weathered_") { + format!("oxidized_{rest}") + } else if path.starts_with("oxidized_") || path.starts_with("waxed_") { + return None; + } else { + format!("exposed_{path}") + }; + let block = b.table.block_by_name(&format!("minecraft:{next}"))?; + Some(b.table.with_properties_of(block, state)) + } +} + +impl Behaviours { + /// Run due scheduled ticks for the level's current game time, in vanilla + /// order: block ticks then fluid ticks (65536 each at most). + pub fn tick_scheduled(&self, level: &mut L, ticks: &mut Ticks) { + let time = level.game_time(); + { + let level_ref: &L = level; + if ticks.blocks.begin_tick(time, 65536, |chunk: ChunkPos| level_ref.is_ticking_chunk(chunk)).is_err() { + return; + } + } + while let Ok(Some(tick)) = ticks.blocks.next_tick() { + let mut sim = self.sim(level, ticks); + let state = sim.state(tick.pos); + if u32::from(self.block(state).0) == tick.kind.0 { + sim.tick_block(state, tick.pos); + } + } + let _ = ticks.blocks.finish_tick(); + { + let level_ref: &L = level; + if ticks.fluids.begin_tick(time, 65536, |chunk: ChunkPos| level_ref.is_ticking_chunk(chunk)).is_err() { + return; + } + } + while let Ok(Some(tick)) = ticks.fluids.next_tick() { + let mut sim = self.sim(level, ticks); + let fluid = self.fluid(sim.state(tick.pos)).kind(); + if TickTypeId(fluid as u32) == tick.kind { + sim.fluid_tick(tick.pos); + } + } + let _ = ticks.fluids.finish_tick(); + } + /// Random-tick one chunk (`ServerLevel.tickChunk` block part). `sections` + /// yields the minimum block Y of every section the caller considers + /// randomly ticking (vanilla: sections containing randomly-ticking states), + /// in ascending order. Draws `randomTickSpeed` positions per section. + pub fn tick_chunk_random( + &self, + level: &mut L, + ticks: &mut Ticks, + chunk: ChunkPos, + sections: impl IntoIterator, + ) { + let speed = level.game_rules().random_tick_speed; + if speed <= 0 { + return; + } + let (min_x, min_z) = (chunk.x * 16, chunk.z * 16); + for min_y in sections { + for _ in 0..speed { + let pos = ticks.block_random_pos(min_x, min_y, min_z, 15); + self.sim(level, ticks).random_tick_at(pos); + } + } + } + /// Random-tick a single position (block then fluid), as `tickChunk` does. + pub fn random_tick(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos) { + self.sim(level, ticks).random_tick_at(pos); + } + /// Run one scheduled block tick at `pos` immediately (no queue check). + pub fn scheduled_block_tick(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos) { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + sim.tick_block(state, pos); + } + /// Run one scheduled fluid tick at `pos` immediately. + pub fn scheduled_fluid_tick(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos) { + self.sim(level, ticks).fluid_tick(pos); + } +} diff --git a/crates/horizon-world/src/level/update.rs b/crates/horizon-world/src/level/update.rs index 17ea2f64e..1887c038e 100644 --- a/crates/horizon-world/src/level/update.rs +++ b/crates/horizon-world/src/level/update.rs @@ -393,10 +393,7 @@ impl Sim<'_, L> { while let Some(update) = updater.added.pop() { updater.stack.push(update); } - loop { - let Some(top) = self.ticks.updater.stack.last_mut() else { - break; - }; + while let Some(top) = self.ticks.updater.stack.last_mut() { let (step, more) = top.next(); self.execute(step); if !more { diff --git a/crates/horizon-world/src/lib.rs b/crates/horizon-world/src/lib.rs index 6857e263e..bf49481b1 100644 --- a/crates/horizon-world/src/lib.rs +++ b/crates/horizon-world/src/lib.rs @@ -72,6 +72,7 @@ pub mod item_use_catalog; pub mod item_use_lifecycle; pub mod item_use_start; pub mod java_hash_map; +pub mod level; pub mod liquid_collision; pub mod live_attribute_updates; pub mod living_air; diff --git a/tools/prepare_native_client.py b/tools/prepare_native_client.py index 0615f7db1..53815daae 100644 --- a/tools/prepare_native_client.py +++ b/tools/prepare_native_client.py @@ -192,6 +192,22 @@ def main(): subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaGameplayFactsExporter', str(gameplay)], check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) + # Block classes, instance configuration and per-state support/signal/fluid + # facts for horizon-world's level behaviour (level::Behaviours::load). + behaviours = root / 'block-behaviours.json' + behaviour_oracle = oracle.with_name('VanillaBlockBehaviourExporter.java') + behaviour_sources = base.source_hashes([behaviour_oracle]) + if not (previous.get('behaviour_exporters_sha256') == behaviour_sources and behaviours.exists() + and previous.get('server_sha256') == origin['server_sha256']): + classes = lab.LOCAL / 'block-behaviours' / 'classes'; classes.mkdir(parents=True, exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + with (root / 'behaviour-export.log').open('w') as log: + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', + '-cp', dependencies, '-d', str(classes), str(behaviour_oracle)], + check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) + subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.VanillaBlockBehaviourExporter', str(behaviours)], + check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) items = root / 'items.json' if not items.exists() or previous.get('server_sha256') != origin['server_sha256']: # Vanilla's own data generator reports every item's default components. @@ -218,6 +234,7 @@ def main(): 'render_files_sha256': {name: lab.digest(root/name, 'sha256') for name in render_files}, 'model_state_exporters_sha256': binding_sources, 'gameplay_exporters_sha256': gameplay_sources, + 'behaviour_exporters_sha256': behaviour_sources, 'model_states_sha256': lab.digest(model_states, 'sha256'), 'data_version': version['world_version'], 'facts_sha256': lab.digest(facts, 'sha256'), 'block_tags_sha256': lab.digest(root / 'block-tags.json', 'sha256'), 'resource_files': count})