From 653c717d52d4bd54f54f5329cc7c62ed1427e077 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 03:22:22 +0200 Subject: [PATCH] Add native placement parity harness and game master item gating Behaviours::placement_state exposes BlockItem placement-state selection without writing to the level; tools/test_level_place_parity.py compares it with vanilla (VanillaPlacementOracle) over random neighbourhoods: 20000/20000 cases match. PlaceContext gains can_use_game_master_blocks. Level module formatted with rustfmt. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../examples/level_place_fixture.rs | 107 +++ .../examples/level_shape_fixture.rs | 65 +- crates/horizon-world/src/level/data.rs | 205 ++++-- crates/horizon-world/src/level/falling.rs | 24 +- crates/horizon-world/src/level/fluids.rs | 220 ++++-- crates/horizon-world/src/level/hooks.rs | 97 ++- crates/horizon-world/src/level/interact.rs | 103 ++- crates/horizon-world/src/level/mod.rs | 113 +++- crates/horizon-world/src/level/pistons.rs | 246 +++++-- crates/horizon-world/src/level/place.rs | 624 ++++++++++++++---- crates/horizon-world/src/level/query.rs | 36 +- crates/horizon-world/src/level/rails.rs | 181 ++++- crates/horizon-world/src/level/redstone.rs | 309 +++++++-- crates/horizon-world/src/level/shapes.rs | 429 +++++++++--- crates/horizon-world/src/level/speleothem.rs | 138 +++- crates/horizon-world/src/level/states.rs | 59 +- crates/horizon-world/src/level/survive.rs | 165 +++-- crates/horizon-world/src/level/tests.rs | 400 +++++++++-- crates/horizon-world/src/level/tick.rs | 368 +++++++++-- crates/horizon-world/src/level/ticks.rs | 36 +- crates/horizon-world/src/level/update.rs | 122 +++- .../parity/VanillaLevelShapeOracle.java | 2 +- .../parity/VanillaPlacementOracle.java | 227 ++++--- tools/test_level_place_parity.py | 115 ++++ 24 files changed, 3592 insertions(+), 799 deletions(-) create mode 100644 crates/horizon-world/examples/level_place_fixture.rs create mode 100644 tools/test_level_place_parity.py diff --git a/crates/horizon-world/examples/level_place_fixture.rs b/crates/horizon-world/examples/level_place_fixture.rs new file mode 100644 index 000000000..a8f00edd1 --- /dev/null +++ b/crates/horizon-world/examples/level_place_fixture.rs @@ -0,0 +1,107 @@ +//! Rust side of `tools/test_level_place_parity.py`: evaluates +//! `Behaviours::placement_state` for generated neighbourhoods. +use horizon_core::{ + geometry::{Direction, Vec3}, + position::{BlockPos, ChunkPos}, + random::LegacyRandom, +}; +use horizon_world::{ + level::{Behaviours, LevelAccess, PlaceContext, Ticks, data::load_registry}, + registry::BlockStateId, +}; +use serde_json::Value; +use std::{ + collections::HashMap, + io::{BufRead, Write}, + path::Path, +}; + +struct Cells { + cells: HashMap, + air: BlockStateId, + random: LegacyRandom, +} +impl LevelAccess for Cells { + fn block_state(&self, pos: BlockPos) -> BlockStateId { + self.cells.get(&pos).copied().unwrap_or(self.air) + } + fn set_raw(&mut self, _pos: BlockPos, _state: BlockStateId) -> Option { + None + } + fn is_loaded(&self, _pos: BlockPos) -> bool { + true + } + fn random(&mut self) -> &mut LegacyRandom { + &mut self.random + } + fn game_time(&self) -> i64 { + 0 + } +} + +fn main() -> Result<(), Box> { + let mut args = std::env::args().skip(1); + let resources = args.next().expect("resource directory"); + let cases = args.next().expect("case file"); + let output = args.next().expect("output file"); + let resources = Path::new(&resources); + let registry = load_registry(resources)?; + let behaviours = Behaviours::load(®istry, resources)?; + let air = registry.default_state("minecraft:air").unwrap(); + let mut out = std::io::BufWriter::new(std::fs::File::create(output)?); + for line in std::io::BufReader::new(std::fs::File::open(cases)?).lines() { + let case: Value = serde_json::from_str(&line?)?; + let mut cells = HashMap::new(); + for cell in case["cells"].as_array().unwrap() { + let c: Vec = cell + .as_array() + .unwrap() + .iter() + .map(|v| v.as_i64().unwrap()) + .collect(); + cells.insert( + BlockPos::new(c[0] as i32, c[1] as i32, c[2] as i32), + BlockStateId(c[3] as u32), + ); + } + let mut level = Cells { + cells, + air, + random: LegacyRandom::new(case["seed"].as_i64().unwrap()), + }; + let mut ticks = Ticks::new(0); + for x in -2..=2 { + for z in -2..=2 { + ticks.add_empty_chunk(ChunkPos::new(x, z))?; + } + } + let p: Vec = case["pos"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_i64().unwrap() as i32) + .collect(); + let h: Vec = case["hit"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_f64().unwrap()) + .collect(); + let ctx = PlaceContext { + clicked_pos: BlockPos::new(p[0], p[1], p[2]), + face: Direction::ALL[case["face"].as_u64().unwrap() as usize], + hit: Vec3::new(h[0], h[1], h[2]), + inside: false, + yaw: case["yaw"].as_f64().unwrap() as f32, + pitch: case["pitch"].as_f64().unwrap() as f32, + sneaking: case["sneak"].as_bool().unwrap(), + item: case["item"].as_str().unwrap().to_owned(), + can_use_game_master_blocks: false, + }; + match behaviours.placement_state(&mut level, &mut ticks, &ctx) { + Some((pos, state)) => writeln!(out, "place {},{},{} {}", pos.x, pos.y, pos.z, state.0)?, + None => writeln!(out, "place none")?, + } + } + Ok(()) +} diff --git a/crates/horizon-world/examples/level_shape_fixture.rs b/crates/horizon-world/examples/level_shape_fixture.rs index 24bdfad73..1e4909928 100644 --- a/crates/horizon-world/examples/level_shape_fixture.rs +++ b/crates/horizon-world/examples/level_shape_fixture.rs @@ -57,8 +57,16 @@ fn main() -> Result<(), Box> { let case: Value = serde_json::from_str(&line?)?; let mut cells = HashMap::new(); for cell in case["cells"].as_array().unwrap() { - let c: Vec = cell.as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(); - cells.insert(BlockPos::new(c[0] as i32, c[1] as i32, c[2] as i32), BlockStateId(c[3] as u32)); + let c: Vec = cell + .as_array() + .unwrap() + .iter() + .map(|v| v.as_i64().unwrap()) + .collect(); + cells.insert( + BlockPos::new(c[0] as i32, c[1] as i32, c[2] as i32), + BlockStateId(c[3] as u32), + ); } let mut level = Cells { cells, @@ -72,31 +80,68 @@ fn main() -> Result<(), Box> { ticks.add_empty_chunk(ChunkPos::new(x, z))?; } } - let p: Vec = case["pos"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap() as i32).collect(); + let p: Vec = case["pos"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_i64().unwrap() as i32) + .collect(); let pos = BlockPos::new(p[0], p[1], p[2]); let direction = Direction::ALL[case["dir"].as_u64().unwrap() as usize]; let [dx, dy, dz] = direction.normal(); let neighbour_pos = pos.offset(dx, dy, dz); let state = level.block_state(pos); let neighbour = level.block_state(neighbour_pos); - let shape = behaviours.update_shape(&mut level, &mut ticks, state, pos, direction, neighbour_pos, neighbour); + let shape = behaviours.update_shape( + &mut level, + &mut ticks, + state, + pos, + direction, + neighbour_pos, + neighbour, + ); let mut scheduled = BTreeSet::new(); for x in -2..=2 { for z in -2..=2 { let chunk = ChunkPos::new(x, z); - for tick in ticks.blocks.chunk(chunk).map(|c| c.queued()).unwrap_or_default() { - let name = &behaviours.table.info(horizon_world::level::BlockId(tick.kind.0 as u16)).name; - scheduled.insert(format!("{name}@{},{},{}+{}p{}", tick.pos.x, tick.pos.y, tick.pos.z, tick.trigger_tick, tick.priority as i32)); + for tick in ticks + .blocks + .chunk(chunk) + .map(|c| c.queued()) + .unwrap_or_default() + { + let name = &behaviours + .table + .info(horizon_world::level::BlockId(tick.kind.0 as u16)) + .name; + scheduled.insert(format!( + "{name}@{},{},{}+{}p{}", + tick.pos.x, tick.pos.y, tick.pos.z, tick.trigger_tick, tick.priority as i32 + )); } - for tick in ticks.fluids.chunk(chunk).map(|c| c.queued()).unwrap_or_default() { + for tick in ticks + .fluids + .chunk(chunk) + .map(|c| c.queued()) + .unwrap_or_default() + { let name = horizon_world::fluid::FluidKind::ALL[tick.kind.0 as usize].name(); - scheduled.insert(format!("{name}@{},{},{}+{}p{}", tick.pos.x, tick.pos.y, tick.pos.z, tick.trigger_tick, tick.priority as i32)); + scheduled.insert(format!( + "{name}@{},{},{}+{}p{}", + tick.pos.x, tick.pos.y, tick.pos.z, tick.trigger_tick, tick.priority as i32 + )); } } } let survive = behaviours.can_survive(&mut level, &mut ticks, pos, state); let scheduled: Vec = scheduled.into_iter().collect(); - writeln!(out, "shape {} ticks {} survive {survive}", shape.0, scheduled.join(" "))?; + writeln!( + out, + "shape {} ticks {} survive {survive}", + shape.0, + scheduled.join(" ") + )?; } Ok(()) } diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index 5eb0da78b..854248aa7 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -133,8 +133,15 @@ pub(crate) fn analyse_shape(shape: &VoxelShape) -> io::Result { (0.0, 7.0, 9.0, 9.0), ]; for (bit, (x0, z0, x1, z1)) in tests.into_iter().enumerate() { - let test = VoxelShape::from_box(Aabb::new(Vec3::new(px(x0), 0.0, px(z0)), Vec3::new(px(x1), 1.0, px(z1)))).map_err(err)?; - if !test.join_is_not_empty(&above, ShapeOp::ONLY_FIRST).map_err(err)? { + let test = VoxelShape::from_box(Aabb::new( + Vec3::new(px(x0), 0.0, px(z0)), + Vec3::new(px(x1), 1.0, px(z1)), + )) + .map_err(err)?; + if !test + .join_is_not_empty(&above, ShapeOp::ONLY_FIRST) + .map_err(err)? + { info.wall_cover |= 1 << bit; } } @@ -222,6 +229,9 @@ pub struct ItemBinding { /// StandingAndWallBlockItem.attachmentDirection (DOWN for torches/signs, UP for hanging signs). pub attachment: Option, pub kind: ItemKind, + /// GameMasterBlockItem (command/structure/jigsaw blocks): only placeable + /// by players that can use game master blocks. + pub game_master: bool, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ItemKind { @@ -563,7 +573,10 @@ fn read_json(path: &Path) -> io::Result { } fn interned(cache: &mut HashMap>, text: &str) -> Arc { - cache.entry(text.to_owned()).or_insert_with(|| Arc::from(text)).clone() + cache + .entry(text.to_owned()) + .or_insert_with(|| Arc::from(text)) + .clone() } fn set_type(value: &Value, cache: &mut HashMap>) -> Option { @@ -592,7 +605,12 @@ pub fn load_registry(root: &Path) -> io::Result { 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::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 @@ -604,10 +622,20 @@ pub fn load_registry(root: &Path) -> io::Result { }) } let facts = read_json(&root.join("facts.json"))?; - let states = facts["states"].as_array().ok_or_else(|| fail("missing registry state facts"))?; + 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::>()?)), + ( + "states", + Tag::List( + states + .iter() + .map(|state| tag(&state[4])) + .collect::>()?, + ), + ), ("defaults", tag(&facts["defaults"])?), ])) } @@ -618,9 +646,15 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result io::Result io::Result Option> { - all_tags.get(name.strip_prefix('#').unwrap_or(name)).cloned() + all_tags + .get(name.strip_prefix('#').unwrap_or(name)) + .cloned() }; // Collision shapes. - let collision_tag = nbt::read_named(&fs::read(root.join("cached-collision.nbt"))?, Limits::default()) - .map_err(|e| invalid(e.to_string()))? - .0 - .tag; + let collision_tag = nbt::read_named( + &fs::read(root.join("cached-collision.nbt"))?, + Limits::default(), + ) + .map_err(|e| invalid(e.to_string()))? + .0 + .tag; let cached = CachedCollisionRegistry::from_nbt(&collision_tag, registry)?; let mut shapes: Vec = Vec::new(); let mut shape_ids = Vec::with_capacity(table.state_count()); @@ -687,7 +738,10 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result>>()?; + let shape_info = shapes + .iter() + .map(analyse_shape) + .collect::>>()?; // Fluid tags. let mut fluid_definitions = TagDefinitions::default(); @@ -698,7 +752,11 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result io::Result io::Result io::Result PushReaction::Push, "POPPED" => PushReaction::Popped, "IMMOVEABLE" => PushReaction::Immoveable, @@ -774,19 +842,29 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result i32 { - fire.get(key).and_then(|m| m.get(name)).and_then(Value::as_i64).unwrap_or(0) as i32 + fire.get(key) + .and_then(|m| m.get(name)) + .and_then(Value::as_i64) + .unwrap_or(0) as i32 }; let mut strings = HashMap::new(); let mut blocks = Vec::with_capacity(table.block_count()); for (index, json) in blocks_json.iter().enumerate() { let block = BlockId(index as u16); - let name = json["name"].as_str().ok_or_else(|| fail("block without name"))?; + let name = json["name"] + .as_str() + .ok_or_else(|| fail("block without name"))?; if name != &*table.info(block).name { return Err(fail("behaviour block order differs from registry")); } let mut classes = ClassSet::default(); let mut chain = Vec::new(); - for java in json["class"].as_array().into_iter().flatten().filter_map(Value::as_str) { + for java in json["class"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + { if let Some(c) = Class::from_java(java) { classes.insert(c); chain.push(c); @@ -794,14 +872,23 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result set_type(&wood["setType"], &mut strings), @@ -836,10 +923,16 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result Direction::Down, @@ -848,7 +941,14 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result>| { - interned(strings, sound.get(key).and_then(|s| s.get("id")).and_then(Value::as_str).unwrap_or("")) + interned( + strings, + sound + .get(key) + .and_then(|s| s.get("id")) + .and_then(Value::as_str) + .unwrap_or(""), + ) }; let sounds = Arc::new(Sounds { volume: sound.get("volume").and_then(Value::as_f64).unwrap_or(1.0) as f32, @@ -867,16 +967,22 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result 1, Some("WEATHERED") => 2, @@ -886,19 +992,34 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result = binding["class"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + let classes: Vec<&str> = binding["class"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); let has = |name: &str| classes.contains(&name); let kind = if has("HangingSignItem") { ItemKind::HangingSign @@ -921,13 +1042,17 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result Some(Direction::Up), Some("DOWN") => Some(Direction::Down), _ => None, }, kind, + game_master: has("GameMasterBlockItem"), }, ); } @@ -937,7 +1062,9 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> 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 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 }); + 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) { @@ -38,7 +44,9 @@ impl Sim<'_, L> { 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) + 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; @@ -77,7 +85,11 @@ impl Behaviours { pos, hit_pos: pos, face: Direction::Up, - hit: horizon_core::geometry::Vec3::new(f64::from(pos.x) + 0.5, f64::from(pos.y), f64::from(pos.z) + 0.5), + hit: horizon_core::geometry::Vec3::new( + f64::from(pos.x) + 0.5, + f64::from(pos.y), + f64::from(pos.z) + 0.5, + ), inside: false, yaw: 0.0, pitch: 90.0, @@ -95,7 +107,9 @@ impl Behaviours { return Landing::Broken; } let mut placed = state; - if self.table.has(placed, self.props.waterlogged) && self.is_water_fluid(sim.fluid_at(pos).kind()) { + 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) { diff --git a/crates/horizon-world/src/level/fluids.rs b/crates/horizon-world/src/level/fluids.rs index 116310476..d1017fb34 100644 --- a/crates/horizon-world/src/level/fluids.rs +++ b/crates/horizon-world/src/level/fluids.rs @@ -29,10 +29,18 @@ fn is_water(kind: FluidKind) -> bool { matches!(kind, FluidKind::Water | FluidKind::FlowingWater) } fn source_of(kind: FluidKind) -> FluidKind { - if is_water(kind) { FluidKind::Water } else { FluidKind::Lava } + if is_water(kind) { + FluidKind::Water + } else { + FluidKind::Lava + } } fn flowing_of(kind: FluidKind) -> FluidKind { - if is_water(kind) { FluidKind::FlowingWater } else { FluidKind::FlowingLava } + if is_water(kind) { + FluidKind::FlowingWater + } else { + FluidKind::FlowingLava + } } /// `FlowingFluid.SpreadContext`: per-spread caches keyed by horizontal offset. @@ -68,14 +76,26 @@ impl Sim<'_, L> { } } fn drop_off(&self, kind: FluidKind) -> i32 { - if is_water(kind) || self.fast_lava() { 1 } else { 2 } + if is_water(kind) || self.fast_lava() { + 1 + } else { + 2 + } } fn slope_find_distance(&self, kind: FluidKind) -> i32 { - if is_water(kind) || self.fast_lava() { 4 } else { 2 } + if is_water(kind) || self.fast_lava() { + 4 + } else { + 2 + } } fn can_convert_to_source(&self, kind: FluidKind) -> bool { let rules = self.level.game_rules(); - if is_water(kind) { rules.water_source_conversion } else { rules.lava_source_conversion } + if is_water(kind) { + rules.water_source_conversion + } else { + rules.lava_source_conversion + } } fn fluid_height(&self, fluid: FluidState, pos: BlockPos) -> f32 { if fluid.kind() == FluidKind::Empty { @@ -88,10 +108,18 @@ impl Sim<'_, L> { } } /// `FluidState.canBeReplacedWith(level, pos, other, direction)`. - fn can_be_replaced_with(&self, fluid: FluidState, pos: BlockPos, other: FluidKind, direction: Direction) -> bool { + fn can_be_replaced_with( + &self, + fluid: FluidState, + pos: BlockPos, + other: FluidKind, + direction: Direction, + ) -> bool { match fluid.kind() { FluidKind::Empty => true, - FluidKind::Water | FluidKind::FlowingWater => direction == Direction::Down && !is_water(other), + FluidKind::Water | FluidKind::FlowingWater => { + direction == Direction::Down && !is_water(other) + } _ => self.fluid_height(fluid, pos) >= 0.444_444_45 && is_water(other), } } @@ -106,7 +134,12 @@ impl Sim<'_, L> { } } /// `FlowingFluid.canPassThroughWall`. - fn can_pass_through_wall(&self, direction: Direction, source: BlockStateId, target: BlockStateId) -> bool { + fn can_pass_through_wall( + &self, + direction: Direction, + source: BlockStateId, + target: BlockStateId, + ) -> bool { let (target_index, target_shape) = self.collision_or_empty(target); let block = VoxelShape::block(); if target_shape.same_identity(&block) { @@ -123,7 +156,13 @@ impl Sim<'_, L> { let cacheable = source_index >= 0 && target_index >= 0; let key = (source_index, target_index, direction as u8); if cacheable { - if let Some(result) = self.b.occlusion_cache.lock().ok().and_then(|cache| cache.get(&key).copied()) { + if let Some(result) = self + .b + .occlusion_cache + .lock() + .ok() + .and_then(|cache| cache.get(&key).copied()) + { return result; } } @@ -140,7 +179,8 @@ impl Sim<'_, L> { /// `LiquidBlockContainer` membership (`canHoldAnyFluid` first clause). fn is_liquid_container(&self, state: BlockStateId) -> bool { - self.b.implements(state, Interface::LiquidBlockContainer) || self.b.implements(state, Interface::SimpleWaterlogged) + self.b.implements(state, Interface::LiquidBlockContainer) + || self.b.implements(state, Interface::SimpleWaterlogged) } /// `LiquidBlockContainer.canPlaceLiquid(null, level, pos, state, fluid)`. pub(crate) fn can_place_liquid(&self, state: BlockStateId, fluid: FluidKind) -> bool { @@ -160,9 +200,17 @@ impl Sim<'_, L> { fluid == FluidKind::Water } /// `LiquidBlockContainer.placeLiquid`. - pub(crate) fn place_liquid(&mut self, pos: BlockPos, state: BlockStateId, fluid: FluidState) -> bool { + pub(crate) fn place_liquid( + &mut self, + pos: BlockPos, + state: BlockStateId, + fluid: FluidState, + ) -> bool { let b = self.b; - if !self.can_place_liquid(state, fluid.kind()) || fluid.kind() != FluidKind::Water || !b.table.has(state, b.props.waterlogged) { + if !self.can_place_liquid(state, fluid.kind()) + || fluid.kind() != FluidKind::Water + || !b.table.has(state, b.props.waterlogged) + { return false; } if b.is_waterlogged(state) { @@ -170,7 +218,8 @@ impl Sim<'_, L> { } let mut next = b.table.set_bool(state, b.props.waterlogged, true); let data = b.data(state); - if (data.is(Class::Candle) || data.is(Class::Campfire)) && b.table.bool(state, b.props.lit) { + if (data.is(Class::Candle) || data.is(Class::Campfire)) && b.table.bool(state, b.props.lit) + { next = b.table.set_bool(next, b.props.lit, false); if data.is(Class::Campfire) { self.emit(super::LevelEvent::Sound { @@ -203,7 +252,9 @@ impl Sim<'_, L> { } return false; } - if b.implements(state, Interface::SimpleWaterlogged) && b.table.has(state, b.props.waterlogged) { + if b.implements(state, Interface::SimpleWaterlogged) + && b.table.has(state, b.props.waterlogged) + { if b.is_waterlogged(state) { self.set_block_and_update(pos, b.table.set_bool(state, b.props.waterlogged, false)); if !self.can_survive(state, pos) { @@ -223,7 +274,11 @@ impl Sim<'_, L> { self.is_liquid_container(state) || self.b.in_set(state, &self.b.tags.washed_away_by_fluids) } fn can_hold_specific_fluid(&self, state: BlockStateId, fluid: FluidKind) -> bool { - if self.is_liquid_container(state) { self.can_place_liquid(state, fluid) } else { true } + if self.is_liquid_container(state) { + self.can_place_liquid(state, fluid) + } else { + true + } } fn can_hold_fluid(&self, state: BlockStateId, fluid: FluidKind) -> bool { self.can_hold_any_fluid(state) && self.can_hold_specific_fluid(state, fluid) @@ -242,7 +297,9 @@ impl Sim<'_, L> { for direction in HORIZONTAL { let neighbour = self.rel_state(pos, direction); let fluid = b.fluid(neighbour); - if fluid.kind().same_family(kind) && self.can_pass_through_wall(direction, state, neighbour) { + if fluid.kind().same_family(kind) + && self.can_pass_through_wall(direction, state, neighbour) + { if fluid.is_source() { sources += 1; } @@ -280,11 +337,28 @@ impl Sim<'_, L> { self.can_hold_fluid(bottom, flowing_of(kind)) } } - fn can_maybe_pass_through(&self, kind: FluidKind, source: BlockStateId, direction: Direction, test: BlockStateId, test_fluid: FluidState) -> bool { - !self.is_source_of(kind, test_fluid) && self.can_hold_any_fluid(test) && self.can_pass_through_wall(direction, source, test) + fn can_maybe_pass_through( + &self, + kind: FluidKind, + source: BlockStateId, + direction: Direction, + test: BlockStateId, + test_fluid: FluidState, + ) -> bool { + !self.is_source_of(kind, test_fluid) + && self.can_hold_any_fluid(test) + && self.can_pass_through_wall(direction, source, test) } - fn can_pass_through(&self, kind: FluidKind, source: BlockStateId, direction: Direction, test: BlockStateId, test_fluid: FluidState) -> bool { - self.can_maybe_pass_through(kind, source, direction, test, test_fluid) && self.can_hold_specific_fluid(test, flowing_of(kind)) + fn can_pass_through( + &self, + kind: FluidKind, + source: BlockStateId, + direction: Direction, + test: BlockStateId, + test_fluid: FluidState, + ) -> bool { + self.can_maybe_pass_through(kind, source, direction, test, test_fluid) + && self.can_hold_specific_fluid(test, flowing_of(kind)) } fn context_state(&self, context: &mut SpreadContext, pos: BlockPos) -> BlockStateId { let key = context.key(pos); @@ -306,7 +380,15 @@ impl Sim<'_, L> { context.holes.insert(key, hole); hole } - fn slope_distance(&self, kind: FluidKind, pos: BlockPos, pass: i32, from: Direction, state: BlockStateId, context: &mut SpreadContext) -> i32 { + fn slope_distance( + &self, + kind: FluidKind, + pos: BlockPos, + pass: i32, + from: Direction, + state: BlockStateId, + context: &mut SpreadContext, + ) -> i32 { let mut lowest = 1000; for direction in HORIZONTAL { if direction == from { @@ -320,7 +402,14 @@ impl Sim<'_, L> { return pass; } if pass < self.slope_find_distance(kind) { - let distance = self.slope_distance(kind, test_pos, pass + 1, direction.opposite(), test_state, context); + let distance = self.slope_distance( + kind, + test_pos, + pass + 1, + direction.opposite(), + test_state, + context, + ); lowest = lowest.min(distance); } } @@ -328,7 +417,12 @@ impl Sim<'_, L> { lowest } /// `FlowingFluid.getSpread` (EnumMap: iteration in Direction order). - fn spread_targets(&self, kind: FluidKind, pos: BlockPos, state: BlockStateId) -> Vec<(Direction, FluidState)> { + fn spread_targets( + &self, + kind: FluidKind, + pos: BlockPos, + state: BlockStateId, + ) -> Vec<(Direction, FluidState)> { let mut lowest = 1000; let mut result: Vec<(Direction, FluidState)> = Vec::new(); let mut context: Option = None; @@ -367,12 +461,25 @@ impl Sim<'_, L> { result } fn source_neighbour_count(&self, kind: FluidKind, pos: BlockPos) -> i32 { - HORIZONTAL.into_iter().filter(|d| self.is_source_of(kind, self.fluid_at(rel(pos, *d)))).count() as i32 + HORIZONTAL + .into_iter() + .filter(|d| self.is_source_of(kind, self.fluid_at(rel(pos, *d)))) + .count() as i32 } /// `FlowingFluid.spreadTo` (with LavaFluid's water-to-stone override). - fn spread_to(&mut self, kind: FluidKind, pos: BlockPos, state: BlockStateId, direction: Direction, target: FluidState) { + fn spread_to( + &mut self, + kind: FluidKind, + pos: BlockPos, + state: BlockStateId, + direction: Direction, + target: FluidState, + ) { let b = self.b; - if !is_water(kind) && direction == Direction::Down && b.is_water_fluid(self.fluid_at(pos).kind()) { + if !is_water(kind) + && direction == Direction::Down + && b.is_water_fluid(self.fluid_at(pos).kind()) + { if b.instance_of(state, Class::Liquid) { self.set_block_and_update(pos, b.default_of(b.named.stone)); } @@ -393,7 +500,13 @@ impl Sim<'_, L> { self.set_block_and_update(pos, legacy); } } - fn spread_to_sides(&mut self, kind: FluidKind, pos: BlockPos, fluid: FluidState, state: BlockStateId) { + fn spread_to_sides( + &mut self, + kind: FluidKind, + pos: BlockPos, + fluid: FluidState, + state: BlockStateId, + ) { let mut neighbour = i32::from(fluid.amount()) - self.drop_off(kind); if fluid.falling() { neighbour = 7; @@ -454,7 +567,13 @@ impl Sim<'_, L> { } self.spread(kind, pos, state, fluid); } - fn spread_delay(&mut self, kind: FluidKind, pos: BlockPos, old: FluidState, new: FluidState) -> i32 { + fn spread_delay( + &mut self, + kind: FluidKind, + pos: BlockPos, + old: FluidState, + new: FluidState, + ) -> i32 { let delay = self.fluid_tick_delay(kind); if is_water(kind) { return delay; @@ -484,7 +603,11 @@ impl Sim<'_, L> { for direction in POSSIBLE_FLOW_DIRECTIONS { let neighbour = rel(pos, direction.opposite()); if b.is_water_fluid(self.fluid_at(neighbour).kind()) { - let block = if self.fluid_at(pos).is_source() { b.named.obsidian } else { b.named.cobblestone }; + let block = if self.fluid_at(pos).is_source() { + b.named.obsidian + } else { + b.named.cobblestone + }; self.set_block_and_update(pos, b.default_of(block)); self.level_event(1501, pos, 0); return false; @@ -528,12 +651,19 @@ impl Sim<'_, L> { } let state = self.state(test); if self.b.is_air(state) { - if Direction::ALL.into_iter().any(|d| self.lava_flammable(rel(test, d))) { + if Direction::ALL + .into_iter() + .any(|d| self.lava_flammable(rel(test, d))) + { let fire = self.fire_state_for(test); self.set_block_and_update(test, fire); return; } - } else if self.b.tag("minecraft:blocks_lava_fire_spread").is_some_and(|tag| self.b.in_set(state, tag)) { + } else if self + .b + .tag("minecraft:blocks_lava_fire_spread") + .is_some_and(|tag| self.b.in_set(state, tag)) + { return; } } @@ -556,23 +686,35 @@ impl Sim<'_, L> { if self.is_inside_build_height(pos.y) && !self.level.is_loaded(pos) { return false; } - self.b.has_flag(self.state(pos), super::data::state_flags::IGNITED_BY_LAVA) + self.b + .has_flag(self.state(pos), super::data::state_flags::IGNITED_BY_LAVA) } } /// `Shapes.mergedFaceOccludes(shape, occluder, direction)`. -pub(crate) fn merged_face_occludes(shape: &VoxelShape, occluder: &VoxelShape, direction: Direction) -> bool { +pub(crate) fn merged_face_occludes( + shape: &VoxelShape, + occluder: &VoxelShape, + direction: Direction, +) -> bool { let block = VoxelShape::block(); if shape.same_identity(&block) || occluder.same_identity(&block) { return true; } - let positive = matches!(direction, Direction::Up | Direction::South | Direction::East); + let positive = matches!( + direction, + Direction::Up | Direction::South | Direction::East + ); let axis = match direction { Direction::West | Direction::East => Axis::X, Direction::Down | Direction::Up => Axis::Y, _ => Axis::Z, }; - let (first, second) = if positive { (shape, occluder) } else { (occluder, shape) }; + let (first, second) = if positive { + (shape, occluder) + } else { + (occluder, shape) + }; let max_face = match axis { Axis::X => Direction::East, Axis::Y => Direction::Up, @@ -587,7 +729,9 @@ pub(crate) fn merged_face_occludes(shape: &VoxelShape, occluder: &VoxelShape, di empty.clone() }; let second_slice = if !second.is_empty() && second.min(axis).abs() <= 1.0e-7 { - second.face_shape(max_face.opposite()).unwrap_or_else(|_| empty.clone()) + second + .face_shape(max_face.opposite()) + .unwrap_or_else(|_| empty.clone()) } else { empty.clone() }; @@ -595,5 +739,7 @@ pub(crate) fn merged_face_occludes(shape: &VoxelShape, occluder: &VoxelShape, di Ok(shape) => shape, Err(_) => return false, }; - !block.join_is_not_empty(&union, ShapeOp::ONLY_FIRST).unwrap_or(true) + !block + .join_is_not_empty(&union, ShapeOp::ONLY_FIRST) + .unwrap_or(true) } diff --git a/crates/horizon-world/src/level/hooks.rs b/crates/horizon-world/src/level/hooks.rs index 2045beac4..a56e42738 100644 --- a/crates/horizon-world/src/level/hooks.rs +++ b/crates/horizon-world/src/level/hooks.rs @@ -11,7 +11,13 @@ use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource impl Sim<'_, L> { /// `BlockState.handleNeighborChanged`. - pub fn neighbor_changed(&mut self, state: BlockStateId, pos: BlockPos, changed: BlockId, moved: bool) { + pub fn neighbor_changed( + &mut self, + state: BlockStateId, + pos: BlockPos, + changed: BlockId, + moved: bool, + ) { let b = self.b; let block = b.block(state); let chain = &b.data(state).chain; @@ -32,7 +38,9 @@ impl Sim<'_, L> { Class::Door => self.door_neighbor_changed(pos, state, changed), Class::FenceGate => self.gate_neighbor_changed(pos, state), Class::FrostedIce => { - if b.block_data(changed).is(Class::FrostedIce) && self.frosted_ice_fewer_neighbours_than(pos, 2) { + if b.block_data(changed).is(Class::FrostedIce) + && self.frosted_ice_fewer_neighbours_than(pos, 2) + { self.frosted_ice_melt(pos, state); } } @@ -98,10 +106,16 @@ impl Sim<'_, L> { self.copper_bulb_check(pos, state); } } - Class::CoralFan | Class::CoralPlant | Class::CoralWallFan => self.coral_try_schedule_die_tick(state, pos), + Class::CoralFan | Class::CoralPlant | Class::CoralWallFan => { + self.coral_try_schedule_die_tick(state, pos) + } Class::Diode => self.diode_update_neighbors_in_front(pos, state), Class::FallingBlock => { - let delay = if b.data(state).is(Class::DragonEgg) { 5 } else { 2 }; + let delay = if b.data(state).is(Class::DragonEgg) { + 5 + } else { + 2 + }; self.schedule_tick(pos, block, delay); } Class::Frogspawn => { @@ -109,7 +123,10 @@ impl Sim<'_, L> { self.schedule_tick(pos, block, delay); } Class::FrostedIce => { - let delay = self.random().next_int_between_inclusive(60, 120).unwrap_or(60); + let delay = self + .random() + .next_int_between_inclusive(60, 120) + .unwrap_or(60); self.schedule_tick(pos, block, delay); } Class::Hopper => { @@ -118,7 +135,10 @@ impl Sim<'_, L> { } } Class::LightningRod => { - if !same && b.table.bool(state, b.props.powered) && !self.ticks.has_block_tick(pos, block) { + if !same + && b.table.bool(state, b.props.powered) + && !self.ticks.has_block_tick(pos, block) + { self.schedule_tick(pos, block, 8); } } @@ -129,7 +149,10 @@ impl Sim<'_, L> { } } Class::Observer => { - if !same && b.table.bool(state, b.props.powered) && !self.ticks.has_block_tick(pos, block) { + if !same + && b.table.bool(state, b.props.powered) + && !self.ticks.has_block_tick(pos, block) + { let next = b.table.set_bool(state, b.props.powered, false); self.set_block(pos, next, 18); self.observer_update_in_front(pos, next); @@ -149,7 +172,10 @@ impl Sim<'_, L> { 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) { + 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); } } @@ -172,7 +198,10 @@ impl Sim<'_, L> { } } Class::Target => { - if !same && b.table.int(state, b.props.power) > 0 && !self.ticks.has_block_tick(pos, block) { + 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); } } @@ -198,7 +227,12 @@ impl Sim<'_, L> { } /// `BlockState.affectNeighborsAfterRemoval`. - pub fn affect_neighbors_after_removal(&mut self, state: BlockStateId, pos: BlockPos, moved: bool) { + pub fn affect_neighbors_after_removal( + &mut self, + state: BlockStateId, + pos: BlockPos, + moved: bool, + ) { let b = self.b; let block = b.block(state); let chain = &b.data(state).chain; @@ -263,7 +297,8 @@ impl Sim<'_, L> { } } Class::Observer => { - if b.table.bool(state, b.props.powered) && self.ticks.has_block_tick(pos, block) { + if b.table.bool(state, b.props.powered) && self.ticks.has_block_tick(pos, block) + { let off = b.table.set_bool(state, b.props.powered, false); self.observer_update_in_front(pos, off); } @@ -306,7 +341,13 @@ impl Sim<'_, L> { } /// `BlockState.updateIndirectNeighbourShapes` (only redstone wire overrides it). - pub fn update_indirect_neighbour_shapes(&mut self, state: BlockStateId, pos: BlockPos, flags: i32, limit: i32) { + pub fn update_indirect_neighbour_shapes( + &mut self, + state: BlockStateId, + pos: BlockPos, + flags: i32, + limit: i32, + ) { if self.b.is_block(state, self.b.named.redstone_wire) { self.wire_update_indirect(state, pos, flags, limit); } @@ -322,11 +363,20 @@ impl Sim<'_, L> { return false; } let data = b.data(state); - if creative && (data.is(Class::DoublePlant) || data.is(Class::Door)) && b.table.text(state, p.half) == "upper" { + 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() }; + 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); } @@ -353,7 +403,10 @@ impl Sim<'_, L> { 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)) { + } 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); } } @@ -403,7 +456,11 @@ impl Sim<'_, L> { } else { let n = b.named; let block = b.block(state); - if block != n.kelp && block != n.kelp_plant && block != n.seagrass && block != n.tall_seagrass { + if block != n.kelp + && block != n.kelp_plant + && block != n.seagrass + && block != n.tall_seagrass + { continue; } self.drop_resources(state, pos); @@ -430,7 +487,11 @@ impl Sim<'_, L> { fn frosted_ice_fewer_neighbours_than(&self, pos: BlockPos, limit: i32) -> bool { let mut count = 0; for direction in Direction::ALL { - if self.b.data(self.rel_state(pos, direction)).is(Class::FrostedIce) { + if self + .b + .data(self.rel_state(pos, direction)) + .is(Class::FrostedIce) + { count += 1; if count >= limit { return false; diff --git a/crates/horizon-world/src/level/interact.rs b/crates/horizon-world/src/level/interact.rs index 74b1c8338..0c888bb77 100644 --- a/crates/horizon-world/src/level/interact.rs +++ b/crates/horizon-world/src/level/interact.rs @@ -1,6 +1,8 @@ //! `BlockBehaviour.useWithoutItem` (right-click with an empty hand or an item //! that does not handle the block itself). -use super::{Behaviours, LevelAccess, LevelEvent, Sim, Ticks, classes::Class, query::axis_of, update::below}; +use super::{ + Behaviours, LevelAccess, LevelEvent, Sim, Ticks, classes::Class, query::axis_of, update::below, +}; use crate::registry::BlockStateId; use horizon_core::{ geometry::{Axis, Direction, Vec3}, @@ -61,7 +63,13 @@ impl Sim<'_, L> { self.emit(LevelEvent::Player { pos, state, effect }); } - pub(crate) fn use_without_item(&mut self, pos: BlockPos, face: Direction, hit: Vec3, player: PlayerContext) -> InteractionResult { + pub(crate) fn use_without_item( + &mut self, + pos: BlockPos, + face: Direction, + hit: Vec3, + player: PlayerContext, + ) -> InteractionResult { let b = self.b; let p = b.props; let table = &b.table; @@ -79,7 +87,14 @@ impl Sim<'_, L> { self.set_block(pos, next, 10); let open = table.bool(next, p.open); self.door_sound(pos, next, open); - self.game_event(pos, if open { "minecraft:block_open" } else { "minecraft:block_close" }); + self.game_event( + pos, + if open { + "minecraft:block_open" + } else { + "minecraft:block_close" + }, + ); Success } Class::TrapDoor => { @@ -107,12 +122,23 @@ impl Sim<'_, L> { }; self.set_block(pos, next, 10); let opens = table.bool(next, p.open); - let sound = if opens { data.gate_open.clone() } else { data.gate_close.clone() }; + let sound = if opens { + data.gate_open.clone() + } else { + data.gate_close.clone() + }; let pitch = self.random().next_float() * 0.1 + 0.9; if let Some(sound) = sound { self.sound(pos, &sound, 1.0, pitch); } - self.game_event(pos, if opens { "minecraft:block_open" } else { "minecraft:block_close" }); + self.game_event( + pos, + if opens { + "minecraft:block_open" + } else { + "minecraft:block_close" + }, + ); Success } Class::Button => { @@ -138,7 +164,11 @@ impl Sim<'_, L> { return Pass; } let next = table.cycle(state, p.mode); - let pitch = if table.text(next, p.mode) == "subtract" { 0.55 } else { 0.5 }; + let pitch = if table.text(next, p.mode) == "subtract" { + 0.55 + } else { + 0.5 + }; self.emit(LevelEvent::Sound { pos, sound: "minecraft:block.comparator.click".into(), @@ -197,7 +227,11 @@ impl Sim<'_, L> { if table.int(state, p.level) != 8 { return Pass; } - self.player_effect(pos, state, PlayerEffect::DropItem("minecraft:bone_meal".into())); + self.player_effect( + pos, + state, + PlayerEffect::DropItem("minecraft:bone_meal".into()), + ); self.set_block_and_update(pos, table.set_int(state, p.level, 0)); self.game_event(pos, "minecraft:block_change"); self.emit(LevelEvent::Sound { @@ -212,7 +246,11 @@ impl Sim<'_, L> { if !table.bool(state, p.berries) { return Pass; } - self.player_effect(pos, state, PlayerEffect::InteractLoot("minecraft:harvest/cave_vine")); + self.player_effect( + pos, + state, + PlayerEffect::InteractLoot("minecraft:harvest/cave_vine"), + ); let pitch = self.random().next_float() * 0.4 + 0.8; self.emit(LevelEvent::Sound { pos, @@ -229,7 +267,11 @@ impl Sim<'_, L> { if table.int(state, p.age) <= 1 { return Pass; } - self.player_effect(pos, state, PlayerEffect::InteractLoot("minecraft:harvest/sweet_berry_bush")); + self.player_effect( + pos, + state, + PlayerEffect::InteractLoot("minecraft:harvest/sweet_berry_bush"), + ); let pitch = 0.8 + self.random().next_float() * 0.4; self.emit(LevelEvent::Sound { pos, @@ -261,10 +303,18 @@ impl Sim<'_, L> { Class::AbstractBed => { let part = table.text(state, p.part).to_owned(); let facing = b.facing(state); - let other_dir = if part == "foot" { facing } else { facing.opposite() }; + let other_dir = if part == "foot" { + facing + } else { + facing.opposite() + }; let other = self.state(super::update::rel(pos, other_dir)); if b.is_block(other, block) && table.text(other, p.part) != part { - let head = if part == "head" { pos } else { super::update::rel(pos, facing) }; + let head = if part == "head" { + pos + } else { + super::update::rel(pos, facing) + }; let head_state = self.state(head); self.player_effect(head, head_state, PlayerEffect::Sleep); Success @@ -350,7 +400,12 @@ impl Sim<'_, L> { } /// `RedstoneWireBlock.useWithoutItem`: toggle between dot and cross. - fn wire_use(&mut self, pos: BlockPos, state: BlockStateId, player: PlayerContext) -> InteractionResult { + fn wire_use( + &mut self, + pos: BlockPos, + state: BlockStateId, + player: PlayerContext, + ) -> InteractionResult { let b = self.b; if !player.may_build { return InteractionResult::Pass; @@ -364,7 +419,8 @@ impl Sim<'_, L> { } let power = b.table.int(state, b.props.power); let base = if cross { - b.table.set_int(b.default_of(b.named.redstone_wire), b.props.power, power) + b.table + .set_int(b.default_of(b.named.redstone_wire), b.props.power, power) } else { self.wire_cross_state(power) }; @@ -375,7 +431,9 @@ impl Sim<'_, L> { self.set_block_and_update(pos, next); for direction in horizontal { let relative = super::update::rel(pos, direction); - if connected(state, direction) != connected(next, direction) && self.is_redstone_conductor(self.state(relative), relative) { + if connected(state, direction) != connected(next, direction) + && self.is_redstone_conductor(self.state(relative), relative) + { let block = b.block(next); self.update_neighbors_at_except(relative, block, direction.opposite()); } @@ -387,11 +445,17 @@ impl Sim<'_, L> { fn dragon_egg_teleport(&mut self, pos: BlockPos, state: BlockStateId) { let b = self.b; for _ in 0..1000 { - let dx = self.random().next_int_bound(16).unwrap_or(0) - self.random().next_int_bound(16).unwrap_or(0); - let dy = self.random().next_int_bound(8).unwrap_or(0) - self.random().next_int_bound(8).unwrap_or(0); - let dz = self.random().next_int_bound(16).unwrap_or(0) - self.random().next_int_bound(16).unwrap_or(0); + let dx = self.random().next_int_bound(16).unwrap_or(0) + - self.random().next_int_bound(16).unwrap_or(0); + let dy = self.random().next_int_bound(8).unwrap_or(0) + - self.random().next_int_bound(8).unwrap_or(0); + let dz = self.random().next_int_bound(16).unwrap_or(0) + - self.random().next_int_bound(16).unwrap_or(0); let test = pos.offset(dx, dy, dz); - if b.is_air(self.state(test)) && !b.is_air(self.below_state(test)) && self.is_inside_build_height(test.y) { + if b.is_air(self.state(test)) + && !b.is_air(self.below_state(test)) + && self.is_inside_build_height(test.y) + { // BlockUtil.packDifferenceInPosition(pos, test, 16, 8, 16) let packed = ((dx + 16) << 16) | ((dy + 8) << 8) | (dz + 16); self.level_event(2015, pos, packed); @@ -415,6 +479,7 @@ impl Behaviours { hit: Vec3, player: PlayerContext, ) -> InteractionResult { - self.sim(level, ticks).use_without_item(pos, face, hit, player) + self.sim(level, ticks) + .use_without_item(pos, face, hit, player) } } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 253f1a677..ee7dca6b9 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -78,7 +78,7 @@ //! //! // Player actions: //! behaviours.place_block(&mut level, &mut ticks, &PlaceContext { clicked_pos, face, hit, inside: false, -//! yaw, pitch, sneaking, item: "minecraft:oak_stairs".into() }); +//! yaw, pitch, sneaking, item: "minecraft:oak_stairs".into(), can_use_game_master_blocks: false }); //! behaviours.use_without_item(&mut level, &mut ticks, pos, face, hit, player_context); //! behaviours.player_destroy_block(&mut level, &mut ticks, pos, creative); //! // Falling-block entity landed: @@ -104,8 +104,8 @@ mod falling; mod fluids; mod hooks; mod interact; -mod place; pub mod pistons; +mod place; mod query; mod rails; mod redstone; @@ -120,9 +120,9 @@ mod tests; pub use data::{BlockData, ItemBinding, ItemKind, Named, Props, PushReaction, StateFacts, Tags}; pub use falling::Landing; +pub use interact::{InteractionResult, PlayerContext, PlayerEffect}; pub use pistons::{BlockEventData, MovingPiston}; pub use place::{PlaceContext, PlaceOutcome}; -pub use interact::{InteractionResult, PlayerContext, PlayerEffect}; pub use states::{BlockId, PropKey, StateTable}; pub use tick::{Precipitation, PrecipitationKind}; pub use ticks::Ticks; @@ -304,12 +304,22 @@ pub trait LevelAccess { /// Comparator input from a block entity (`getAnalogOutputSignal` of /// containers, jukeboxes, lecterns, ...). State-only sources (cake, /// composter, cauldrons, beehives, ...) are evaluated by the library. - fn block_entity_analog_signal(&self, _pos: BlockPos, _state: BlockStateId, _direction: Direction) -> i32 { + fn block_entity_analog_signal( + &self, + _pos: BlockPos, + _state: BlockStateId, + _direction: Direction, + ) -> i32 { 0 } /// Weak/strong signal of a block-entity-driven source (trapped chest /// openers); other sources are evaluated by the library. - fn block_entity_signal(&self, _pos: BlockPos, _state: BlockStateId, _direction: Direction) -> i32 { + fn block_entity_signal( + &self, + _pos: BlockPos, + _state: BlockStateId, + _direction: Direction, + ) -> i32 { 0 } /// Biome answers for a precipitation tick at the column of `pos` (see @@ -434,26 +444,58 @@ 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 { + 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 { + 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) + 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 { + 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 { + pub fn can_survive( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + state: BlockStateId, + ) -> bool { self.sim(level, ticks).can_survive(state, pos) } /// `BlockState.updateShape(level, ticks, pos, direction, neighbourPos, @@ -470,27 +512,56 @@ impl Behaviours { neighbour_pos: BlockPos, neighbour: BlockStateId, ) -> BlockStateId { - self.sim(level, ticks).update_shape(state, pos, direction, neighbour_pos, neighbour) + self.sim(level, ticks) + .update_shape(state, pos, direction, neighbour_pos, neighbour) } /// `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) + 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) { + 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) { + 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 { + 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 { + pub fn best_neighbor_signal( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) -> i32 { self.sim(level, ticks).best_neighbor_signal(pos) } } @@ -505,7 +576,11 @@ pub(crate) struct Sim<'a, L: LevelAccess + ?Sized> { pub wire_signal_off: std::cell::Cell, } impl Behaviours { - pub(crate) fn sim<'a, L: LevelAccess + ?Sized>(&'a self, level: &'a mut L, ticks: &'a mut Ticks) -> Sim<'a, L> { + pub(crate) fn sim<'a, L: LevelAccess + ?Sized>( + &'a self, + level: &'a mut L, + ticks: &'a mut Ticks, + ) -> Sim<'a, L> { Sim { b: self, level, diff --git a/crates/horizon-world/src/level/pistons.rs b/crates/horizon-world/src/level/pistons.rs index 5faa0962a..0beb512c8 100644 --- a/crates/horizon-world/src/level/pistons.rs +++ b/crates/horizon-world/src/level/pistons.rs @@ -10,7 +10,10 @@ use super::{ states::BlockId, update::{above, rel}, }; -use crate::{java_hash_map::{JavaHashMap, JavaKey}, registry::BlockStateId}; +use crate::{ + java_hash_map::{JavaHashMap, JavaKey}, + registry::BlockStateId, +}; use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource}; use std::cmp::Ordering; @@ -29,7 +32,11 @@ pub struct MovingPiston { } impl MovingPiston { pub fn movement_direction(&self) -> Direction { - if self.extending { self.direction } else { self.direction.opposite() } + if self.extending { + self.direction + } else { + self.direction.opposite() + } } } @@ -46,11 +53,19 @@ pub struct BlockEventData { struct PosKey(BlockPos); impl JavaKey for PosKey { fn java_hash(&self) -> i32 { - (self.0.y.wrapping_add(self.0.z.wrapping_mul(31))).wrapping_mul(31).wrapping_add(self.0.x) + (self.0.y.wrapping_add(self.0.z.wrapping_mul(31))) + .wrapping_mul(31) + .wrapping_add(self.0.x) } fn comparable_compare(&self, other: &Self) -> Option { // Vec3i implements Comparable: y, then z, then x. - Some(self.0.y.cmp(&other.0.y).then(self.0.z.cmp(&other.0.z)).then(self.0.x.cmp(&other.0.x))) + Some( + self.0 + .y + .cmp(&other.0.y) + .then(self.0.z.cmp(&other.0.z)) + .then(self.0.x.cmp(&other.0.x)), + ) } fn tie_break(&self, _other: &Self) -> Ordering { Ordering::Less @@ -74,8 +89,19 @@ fn rel_n(pos: BlockPos, direction: Direction, n: i32) -> BlockPos { impl Sim<'_, L> { // ---- block events ---- - pub(crate) fn block_event(&mut self, pos: BlockPos, block: BlockId, param_a: i32, param_b: i32) { - let event = BlockEventData { pos, block, param_a, param_b }; + pub(crate) fn block_event( + &mut self, + pos: BlockPos, + block: BlockId, + param_a: i32, + param_b: i32, + ) { + let event = BlockEventData { + pos, + block, + param_a, + param_b, + }; if !self.ticks.block_events.contains(&event) { self.ticks.block_events.push(event); } @@ -92,7 +118,11 @@ impl Sim<'_, L> { // ---- moving piston block entities ---- pub(crate) fn moving_piston(&self, pos: BlockPos) -> Option { - self.ticks.moving_pistons.iter().find(|(p, _)| *p == pos).map(|(_, m)| *m) + self.ticks + .moving_pistons + .iter() + .find(|(p, _)| *p == pos) + .map(|(_, m)| *m) } fn set_moving_piston(&mut self, pos: BlockPos, mut piston: MovingPiston) { self.ticks.moving_pistons.retain(|(p, _)| *p != pos); @@ -101,7 +131,11 @@ impl Sim<'_, L> { self.ticks.moving_pistons.push((pos, piston)); } pub(crate) fn remove_moving_piston(&mut self, pos: BlockPos) -> Option { - let index = self.ticks.moving_pistons.iter().position(|(p, _)| *p == pos)?; + let index = self + .ticks + .moving_pistons + .iter() + .position(|(p, _)| *p == pos)?; Some(self.ticks.moving_pistons.remove(index).1) } /// `PistonMovingBlockEntity.finalTick`. @@ -115,7 +149,11 @@ impl Sim<'_, L> { self.remove_moving_piston(pos); let b = self.b; if b.is_block(self.state(pos), b.named.moving_piston) { - let new = if piston.source { b.air() } else { self.update_from_neighbour_shapes(piston.moved_state, pos) }; + let new = if piston.source { + b.air() + } else { + self.update_from_neighbour_shapes(piston.moved_state, pos) + }; self.set_block_and_update(pos, new); let block = b.block(new); self.neighbor_changed_at(pos, block); @@ -135,7 +173,13 @@ impl Sim<'_, L> { let mut new = self.update_from_neighbour_shapes(piston.moved_state, pos); if b.is_air(new) { self.set_block(pos, piston.moved_state, 340); - self.update_or_destroy(piston.moved_state, new, pos, 3, super::flags::UPDATE_LIMIT); + self.update_or_destroy( + piston.moved_state, + new, + pos, + 3, + super::flags::UPDATE_LIMIT, + ); } else { if b.is_waterlogged(new) { new = b.table.set_bool(new, b.props.waterlogged, false); @@ -147,7 +191,12 @@ impl Sim<'_, L> { } } else { piston.progress = (piston.progress + 0.5).min(1.0); - if let Some(entry) = self.ticks.moving_pistons.iter_mut().find(|(p, _)| *p == pos) { + if let Some(entry) = self + .ticks + .moving_pistons + .iter_mut() + .find(|(p, _)| *p == pos) + { entry.1 = piston; } } @@ -167,9 +216,9 @@ impl Sim<'_, L> { return true; } let up = above(pos); - Direction::ALL - .into_iter() - .any(|direction| direction != Direction::Down && self.has_signal(rel(up, direction), direction)) + Direction::ALL.into_iter().any(|direction| { + direction != Direction::Down && self.has_signal(rel(up, direction), direction) + }) } /// `PistonBaseBlock.checkIfExtend`. pub(crate) fn piston_check_if_extend(&mut self, pos: BlockPos, state: BlockStateId) { @@ -189,7 +238,9 @@ impl Sim<'_, L> { if b.is_block(pushed, b.named.moving_piston) && b.facing(pushed) == direction { if let Some(piston) = self.moving_piston(pushed_pos) { if piston.extending - && (piston.progress_o < 0.5 || self.level.game_time() == piston.last_ticked || self.ticks.handling_tick) + && (piston.progress_o < 0.5 + || self.level.game_time() == piston.last_ticked + || self.ticks.handling_tick) { event = 2; } @@ -199,7 +250,14 @@ impl Sim<'_, L> { } } /// `PistonBaseBlock.isPushable`. - fn is_pushable(&self, state: BlockStateId, pos: BlockPos, direction: Direction, allow_destroyable: bool, connection: Direction) -> bool { + fn is_pushable( + &self, + state: BlockStateId, + pos: BlockPos, + direction: Direction, + allow_destroyable: bool, + connection: Direction, + ) -> bool { let b = self.b; let (min_y, max_y) = (self.level.min_y(), self.level.max_y() - 1); if pos.y < min_y || pos.y > max_y { @@ -214,7 +272,8 @@ impl Sim<'_, L> { if direction == Direction::Up && pos.y == max_y { return false; } - let is_piston = b.is_block(state, b.named.piston) || b.is_block(state, b.named.sticky_piston); + let is_piston = + b.is_block(state, b.named.piston) || b.is_block(state, b.named.sticky_piston); if !is_piston { if b.facts(state).hardness == -1.0 { return false; @@ -231,24 +290,44 @@ impl Sim<'_, L> { !b.has_flag(state, super::data::state_flags::BLOCK_ENTITY) } fn is_slime_or_honey(&self, state: BlockStateId) -> bool { - self.b.is_block(state, self.b.named.slime_block) || self.b.is_block(state, self.b.named.honey_block) + self.b.is_block(state, self.b.named.slime_block) + || self.b.is_block(state, self.b.named.honey_block) } fn can_stick(&self, first: BlockStateId, second: BlockStateId) -> bool { let n = self.b.named; - let (honey1, slime1) = (self.b.is_block(first, n.honey_block), self.b.is_block(first, n.slime_block)); - let (honey2, slime2) = (self.b.is_block(second, n.honey_block), self.b.is_block(second, n.slime_block)); + let (honey1, slime1) = ( + self.b.is_block(first, n.honey_block), + self.b.is_block(first, n.slime_block), + ); + let (honey2, slime2) = ( + self.b.is_block(second, n.honey_block), + self.b.is_block(second, n.slime_block), + ); if (honey1 && slime2) || (slime1 && honey2) { return false; } self.is_slime_or_honey(first) || self.is_slime_or_honey(second) } /// `PistonStructureResolver.resolve`; None when the structure cannot move. - fn piston_resolve(&self, piston_pos: BlockPos, direction: Direction, extending: bool) -> Option<(Vec, Vec, Direction)> { + fn piston_resolve( + &self, + piston_pos: BlockPos, + direction: Direction, + extending: bool, + ) -> Option<(Vec, Vec, Direction)> { let mut r = Resolver { piston_pos, extending, - start: if extending { rel(piston_pos, direction) } else { rel_n(piston_pos, direction, 2) }, - push_direction: if extending { direction } else { direction.opposite() }, + start: if extending { + rel(piston_pos, direction) + } else { + rel_n(piston_pos, direction, 2) + }, + push_direction: if extending { + direction + } else { + direction.opposite() + }, piston_direction: direction, to_push: Vec::new(), to_destroy: Vec::new(), @@ -281,7 +360,10 @@ impl Sim<'_, L> { if self.b.is_air(next) { return true; } - if !self.is_pushable(next, start, r.push_direction, false, direction) || start == r.piston_pos || r.to_push.contains(&start) { + if !self.is_pushable(next, start, r.push_direction, false, direction) + || start == r.piston_pos + || r.to_push.contains(&start) + { return true; } let mut count = 1; @@ -294,7 +376,13 @@ impl Sim<'_, L> { next = self.state(pos); if self.b.is_air(next) || !self.can_stick(previous, next) - || !self.is_pushable(next, pos, r.push_direction, false, r.push_direction.opposite()) + || !self.is_pushable( + next, + pos, + r.push_direction, + false, + r.push_direction.opposite(), + ) || pos == r.piston_pos { break; @@ -306,7 +394,8 @@ impl Sim<'_, L> { } let mut added = 0; for i in (0..count).rev() { - r.to_push.push(rel_n(start, r.push_direction.opposite(), i as i32)); + r.to_push + .push(rel_n(start, r.push_direction.opposite(), i as i32)); added += 1; } let mut i = 1; @@ -316,7 +405,9 @@ impl Sim<'_, L> { self.reorder_at_collision(r, added, collision); for j in 0..=collision + added { let block_pos = r.to_push[j]; - if self.is_slime_or_honey(self.state(block_pos)) && !self.add_branching_blocks(r, block_pos) { + if self.is_slime_or_honey(self.state(block_pos)) + && !self.add_branching_blocks(r, block_pos) + { return false; } } @@ -326,7 +417,9 @@ impl Sim<'_, L> { if self.b.is_air(next) { return true; } - if !self.is_pushable(next, pos, r.push_direction, true, r.push_direction) || pos == r.piston_pos { + if !self.is_pushable(next, pos, r.push_direction, true, r.push_direction) + || pos == r.piston_pos + { return false; } if self.b.facts(next).push == PushReaction::Popped { @@ -357,7 +450,9 @@ impl Sim<'_, L> { if super::query::axis_of(direction) != super::query::axis_of(r.push_direction) { let neighbour = rel(from, direction); let neighbour_state = self.state(neighbour); - if self.can_stick(neighbour_state, from_state) && !self.add_block_line(r, neighbour, direction) { + if self.can_stick(neighbour_state, from_state) + && !self.add_block_line(r, neighbour, direction) + { return false; } } @@ -366,17 +461,33 @@ impl Sim<'_, L> { } fn moving_piston_state(&self, direction: Direction, sticky: bool) -> BlockStateId { let b = self.b; - let state = b.table.set_dir(b.default_of(b.named.moving_piston), b.props.facing, direction); - b.table.set_text(state, b.props.kind, if sticky { "sticky" } else { "normal" }) + let state = b.table.set_dir( + b.default_of(b.named.moving_piston), + b.props.facing, + direction, + ); + b.table.set_text( + state, + b.props.kind, + if sticky { "sticky" } else { "normal" }, + ) } /// `PistonBaseBlock.moveBlocks`. - fn piston_move_blocks(&mut self, piston_pos: BlockPos, direction: Direction, extending: bool, sticky: bool) -> bool { + fn piston_move_blocks( + &mut self, + piston_pos: BlockPos, + direction: Direction, + extending: bool, + sticky: bool, + ) -> bool { let b = self.b; let arm = rel(piston_pos, direction); if !extending && b.is_block(self.state(arm), b.named.piston_head) { self.set_block(arm, b.air(), 276); } - let Some((to_push, to_destroy, push_direction)) = self.piston_resolve(piston_pos, direction, extending) else { + let Some((to_push, to_destroy, push_direction)) = + self.piston_resolve(piston_pos, direction, extending) + else { return false; }; let mut delete_after: JavaHashMap = JavaHashMap::default(); @@ -387,7 +498,11 @@ impl Sim<'_, L> { delete_after.put(PosKey(*pos), state); } let mut to_update = Vec::with_capacity(to_push.len() + to_destroy.len()); - let move_direction = if extending { direction } else { direction.opposite() }; + let move_direction = if extending { + direction + } else { + direction.opposite() + }; for pos in to_destroy.iter().rev() { let state = self.state(*pos); self.drop_resources(state, *pos); @@ -399,7 +514,11 @@ impl Sim<'_, L> { let state = self.state(*pos); let target = rel(*pos, move_direction); delete_after.remove(&PosKey(target)); - let moving = b.table.set_dir(b.default_of(b.named.moving_piston), b.props.facing, direction); + let moving = b.table.set_dir( + b.default_of(b.named.moving_piston), + b.props.facing, + direction, + ); self.set_block(target, moving, 324); self.set_moving_piston( target, @@ -418,7 +537,8 @@ impl Sim<'_, L> { } if extending { let head = b.table.set_text( - b.table.set_dir(b.default_of(b.named.piston_head), b.props.facing, direction), + b.table + .set_dir(b.default_of(b.named.piston_head), b.props.facing, direction), b.props.kind, if sticky { "sticky" } else { "normal" }, ); @@ -440,7 +560,8 @@ impl Sim<'_, L> { ); } let air = b.air(); - let entries: Vec<(BlockPos, BlockStateId)> = delete_after.entries().map(|(k, v)| (k.0, *v)).collect(); + let entries: Vec<(BlockPos, BlockStateId)> = + delete_after.entries().map(|(k, v)| (k.0, *v)).collect(); for (pos, _) in &entries { self.set_block(*pos, air, 82); } @@ -470,7 +591,13 @@ impl Sim<'_, L> { true } /// `PistonBaseBlock.triggerEvent`. - fn piston_trigger_event(&mut self, pos: BlockPos, state: BlockStateId, a: i32, param_b: i32) -> bool { + fn piston_trigger_event( + &mut self, + pos: BlockPos, + state: BlockStateId, + a: i32, + param_b: i32, + ) -> bool { let b = self.b; let p = b.props; let direction = b.facing(state); @@ -501,7 +628,11 @@ impl Sim<'_, L> { self.moving_piston_final_tick(rel(pos, direction)); let moving = self.moving_piston_state(direction, sticky); self.set_block(pos, moving, 276); - let piston_default = b.table.set_dir(b.default_of(b.block(state)), p.facing, Direction::ALL[(param_b & 7).min(5) as usize]); + let piston_default = b.table.set_dir( + b.default_of(b.block(state)), + p.facing, + Direction::ALL[(param_b & 7).min(5) as usize], + ); self.set_moving_piston( pos, MovingPiston { @@ -530,10 +661,17 @@ impl Sim<'_, L> { } } if !piston_piece { - let is_piston = b.is_block(moving_state, b.named.piston) || b.is_block(moving_state, b.named.sticky_piston); + let is_piston = b.is_block(moving_state, b.named.piston) + || b.is_block(moving_state, b.named.sticky_piston); if a != 1 || b.is_air(moving_state) - || !self.is_pushable(moving_state, two, direction.opposite(), false, direction) + || !self.is_pushable( + moving_state, + two, + direction.opposite(), + false, + direction, + ) || (b.facts(moving_state).push != PushReaction::PushPull && !is_piston) { self.remove_block(rel(pos, direction), false); @@ -559,13 +697,20 @@ impl Sim<'_, L> { // ---- PistonHeadBlock ---- pub(crate) fn piston_head_fitting_base(&self, head: BlockStateId, base: BlockStateId) -> bool { let b = self.b; - let expected = if b.table.text(head, b.props.kind) == "sticky" { b.named.sticky_piston } else { b.named.piston }; - b.is_block(base, expected) && b.table.bool(base, b.props.extended) && b.facing(base) == b.facing(head) + let expected = if b.table.text(head, b.props.kind) == "sticky" { + b.named.sticky_piston + } else { + b.named.piston + }; + b.is_block(base, expected) + && b.table.bool(base, b.props.extended) + && b.facing(base) == b.facing(head) } pub(crate) fn piston_head_can_survive(&self, head: BlockStateId, pos: BlockPos) -> bool { let b = self.b; let base = self.rel_state(pos, b.facing(head).opposite()); - self.piston_head_fitting_base(head, base) || (b.is_block(base, b.named.moving_piston) && b.facing(base) == b.facing(head)) + self.piston_head_fitting_base(head, base) + || (b.is_block(base, b.named.moving_piston) && b.facing(base) == b.facing(head)) } } @@ -596,9 +741,18 @@ impl Behaviours { /// whose ticking changes blocks). Entries added during the pass wait for /// the next tick, as vanilla's pending tickers do. pub fn tick_block_entities(&self, level: &mut L, ticks: &mut Ticks) { - let tickers: Vec<(BlockPos, u64)> = ticks.moving_pistons.iter().map(|(p, m)| (*p, m.id)).collect(); + let tickers: Vec<(BlockPos, u64)> = ticks + .moving_pistons + .iter() + .map(|(p, m)| (*p, m.id)) + .collect(); for (pos, id) in tickers { - if !level.is_ticking_chunk(pos.chunk()) || !ticks.moving_pistons.iter().any(|(p, m)| *p == pos && m.id == id) { + if !level.is_ticking_chunk(pos.chunk()) + || !ticks + .moving_pistons + .iter() + .any(|(p, m)| *p == pos && m.id == id) + { continue; } self.sim(level, ticks).moving_piston_tick(pos); diff --git a/crates/horizon-world/src/level/place.rs b/crates/horizon-world/src/level/place.rs index ab568e449..01e9527c2 100644 --- a/crates/horizon-world/src/level/place.rs +++ b/crates/horizon-world/src/level/place.rs @@ -34,6 +34,9 @@ pub struct PlaceContext { pub sneaking: bool, /// The item in hand (registry name, e.g. `minecraft:oak_stairs`). pub item: String, + /// `Player.canUseGameMasterBlocks` (creative operator); gates command, + /// structure, jigsaw and test blocks. + pub can_use_game_master_blocks: bool, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -75,10 +78,24 @@ pub(crate) fn ordered_by_nearest(yaw: f32, pitch: f32) -> [Direction; 6] { let z_yaw = if z_pos { yaw_cos } else { -yaw_cos }; let x_mag = x_yaw * pitch_cos; let z_mag = z_yaw * pitch_cos; - let ax = if x_pos { Direction::East } else { Direction::West }; - let ay = if y_pos { Direction::Up } else { Direction::Down }; - let az = if z_pos { Direction::South } else { Direction::North }; - let make = |a: Direction, b: Direction, c: Direction| [a, b, c, c.opposite(), b.opposite(), a.opposite()]; + let ax = if x_pos { + Direction::East + } else { + Direction::West + }; + let ay = if y_pos { + Direction::Up + } else { + Direction::Down + }; + let az = if z_pos { + Direction::South + } else { + Direction::North + }; + let make = |a: Direction, b: Direction, c: Direction| { + [a, b, c, c.opposite(), b.opposite(), a.opposite()] + }; if x_yaw > z_yaw { if y_mag > x_mag { make(ay, ax, az) @@ -137,7 +154,11 @@ impl Ctx { ordered_by_nearest(self.yaw, self.pitch)[0] } fn nearest_looking_vertical(&self) -> Direction { - if self.pitch < 0.0 { Direction::Up } else { Direction::Down } + if self.pitch < 0.0 { + Direction::Up + } else { + Direction::Down + } } fn click_y(&self) -> f64 { self.hit.y - f64::from(self.pos.y) @@ -159,21 +180,45 @@ impl Sim<'_, L> { let p = b.props; let block = b.block(state); let data = b.data(state); - let default = |sim: &Self| b.is_replaceable(state) && (ctx.item.is_empty() || !sim.item_is(ctx, block)); + let default = |sim: &Self| { + b.is_replaceable(state) && (ctx.item.is_empty() || !sim.item_is(ctx, block)) + }; for class in &data.chain { return match class { Class::Candle => { - (!ctx.sneaking && self.item_is(ctx, block) && b.table.int(state, p.candles) < 4) || default(self) + (!ctx.sneaking && self.item_is(ctx, block) && b.table.int(state, p.candles) < 4) + || default(self) + } + Class::SeaPickle => { + (!ctx.sneaking && self.item_is(ctx, block) && b.table.int(state, p.pickles) < 4) + || default(self) + } + Class::TurtleEgg => { + (!ctx.sneaking && self.item_is(ctx, block) && b.table.int(state, p.eggs) < 4) + || default(self) + } + Class::FlowerBed => { + (!ctx.sneaking + && self.item_is(ctx, block) + && b.table.int(state, p.flower_amount) < 4) + || default(self) + } + Class::LeafLitter => { + (!ctx.sneaking + && self.item_is(ctx, block) + && b.table.int(state, p.segment_amount) < 4) + || default(self) } - Class::SeaPickle => (!ctx.sneaking && self.item_is(ctx, block) && b.table.int(state, p.pickles) < 4) || default(self), - Class::TurtleEgg => (!ctx.sneaking && self.item_is(ctx, block) && b.table.int(state, p.eggs) < 4) || default(self), - Class::FlowerBed => (!ctx.sneaking && self.item_is(ctx, block) && b.table.int(state, p.flower_amount) < 4) || default(self), - Class::LeafLitter => (!ctx.sneaking && self.item_is(ctx, block) && b.table.int(state, p.segment_amount) < 4) || default(self), Class::GrowingPlantBody => { let (head, _) = self.growing_plant_pair(block); default(self) && !self.item_is(ctx, head) } - Class::Multiface => !self.item_is(ctx, block) || Direction::ALL.into_iter().any(|d| !self.multiface_has_face(state, d)), + Class::Multiface => { + !self.item_is(ctx, block) + || Direction::ALL + .into_iter() + .any(|d| !self.multiface_has_face(state, d)) + } Class::PitcherCrop => false, Class::Scaffolding => self.item_is(ctx, block), Class::Slab => { @@ -223,7 +268,11 @@ impl Sim<'_, L> { } /// `Block.getStateForPlacement(context)` for `block`. - pub(crate) fn state_for_placement(&mut self, block: BlockId, ctx: &Ctx) -> Option { + pub(crate) fn state_for_placement( + &mut self, + block: BlockId, + ctx: &Ctx, + ) -> Option { self.placement_at(block, 0, ctx) } @@ -239,7 +288,13 @@ impl Sim<'_, L> { } #[allow(clippy::option_option)] - fn placement_class(&mut self, class: Class, depth: usize, block: BlockId, ctx: &Ctx) -> Option> { + fn placement_class( + &mut self, + class: Class, + depth: usize, + block: BlockId, + ctx: &Ctx, + ) -> Option> { let b = self.b; let p = b.props; let t = &b.tags; @@ -278,8 +333,16 @@ impl Sim<'_, L> { let locked = self.diode_is_locked(pos, state); Some(table.set_bool(state, p.locked, locked)) } - Class::EndPortalFrame => Some(table.set_bool(table.set_dir(default, p.facing, horizontal.opposite()), p.eye, false)), - Class::Lectern => Some(table.set_bool(table.set_dir(default, p.facing, horizontal.opposite()), p.has_book, false)), + Class::EndPortalFrame => Some(table.set_bool( + table.set_dir(default, p.facing, horizontal.opposite()), + p.eye, + false, + )), + Class::Lectern => Some(table.set_bool( + table.set_dir(default, p.facing, horizontal.opposite()), + p.has_book, + false, + )), Class::AbstractSkull => { let signal = self.has_neighbor_signal(pos); Some(table.set_bool(default, p.powered, signal)) @@ -312,7 +375,11 @@ impl Sim<'_, L> { } else if b.is_block(below_state, n.bamboo_sapling) { Some(table.set_int(default, p.age, 0)) } else if b.is_block(below_state, n.bamboo) { - let age = if table.int(below_state, p.age) > 0 { 1 } else { 0 }; + let age = if table.int(below_state, p.age) > 0 { + 1 + } else { + 0 + }; Some(table.set_int(default, p.age, age)) } else { let above_state = self.above_state(pos); @@ -323,13 +390,31 @@ impl Sim<'_, L> { } } } - Class::Banner => Some(table.set_int(default, p.rotation, rotation_segment(ctx.yaw + 180.0))), - Class::StandingSign => Some(wl(table.set_int(default, p.rotation, rotation_segment(ctx.yaw + 180.0)))), - Class::Barrel | Class::Command | Class::Dispenser => { - Some(table.set_dir(default, p.facing, ctx.nearest_looking_direction().opposite())) + Class::Banner => { + Some(table.set_int(default, p.rotation, rotation_segment(ctx.yaw + 180.0))) } - Class::Observer => Some(table.set_dir(default, p.facing, ctx.nearest_looking_direction())), - Class::PistonBase => Some(table.set_bool(table.set_dir(default, p.facing, ctx.nearest_looking_direction().opposite()), p.extended, false)), + Class::StandingSign => Some(wl(table.set_int( + default, + p.rotation, + rotation_segment(ctx.yaw + 180.0), + ))), + Class::Barrel | Class::Command | Class::Dispenser => Some(table.set_dir( + default, + p.facing, + ctx.nearest_looking_direction().opposite(), + )), + Class::Observer => { + Some(table.set_dir(default, p.facing, ctx.nearest_looking_direction())) + } + Class::PistonBase => Some(table.set_bool( + table.set_dir( + default, + p.facing, + ctx.nearest_looking_direction().opposite(), + ), + p.extended, + false, + )), Class::Barrier | Class::HeavyCore | Class::SculkSensor @@ -337,7 +422,10 @@ impl Sim<'_, L> { | Class::Chain | Class::MangroveRoots | Class::WaterloggedTransparent => { - let state = if class == Class::Chain || class == Class::MangroveRoots || class == Class::WaterloggedTransparent { + let state = if class == Class::Chain + || class == Class::MangroveRoots + || class == Class::WaterloggedTransparent + { sup!()? } else { default @@ -350,7 +438,11 @@ impl Sim<'_, L> { } Class::BaseCoralPlantType | Class::Conduit => { let fluid = self.fluid_at(pos); - Some(table.set_bool(default, p.waterlogged, b.is_water_fluid(fluid.kind()) && fluid.is_full())) + Some(table.set_bool( + default, + p.waterlogged, + b.is_water_fluid(fluid.kind()) && fluid.is_full(), + )) } Class::BaseCoralWallFan | Class::WallBanner @@ -368,12 +460,18 @@ impl Sim<'_, L> { } let mut state = match class { Class::BaseCoralWallFan => sup!()?, - Class::TripWireHook => table.set_bool(table.set_bool(default, p.powered, false), p.attached, false), + Class::TripWireHook => { + table.set_bool(table.set_bool(default, p.powered, false), p.attached, false) + } _ => default, }; for direction in ctx.nearest_looking_directions() { if is_horizontal(direction) { - let facing = if class == Class::Cocoa { direction } else { direction.opposite() }; + let facing = if class == Class::Cocoa { + direction + } else { + direction.opposite() + }; state = table.set_dir(state, p.facing, facing); if self.can_survive(state, pos) { return Some(Some(match class { @@ -404,7 +502,9 @@ impl Sim<'_, L> { for direction in ctx.nearest_looking_directions() { if is_horizontal(direction) && axis_of(direction) != axis_of(ctx.face) { state = table.set_dir(state, p.facing, direction.opposite()); - if self.can_survive(state, pos) && self.wall_hanging_sign_can_place(state, pos) { + if self.can_survive(state, pos) + && self.wall_hanging_sign_can_place(state, pos) + { return Some(Some(wl(state))); } } @@ -414,9 +514,12 @@ impl Sim<'_, L> { Class::CeilingHangingSign => { let above_pos = above(pos); let above_state = self.state(above_pos); - let below_hanging = b.tag("minecraft:all_hanging_signs").is_some_and(|tag| b.in_set(above_state, tag)); + let below_hanging = b + .tag("minecraft:all_hanging_signs") + .is_some_and(|tag| b.in_set(above_state, tag)); let direction = from_y_rot(f64::from(ctx.yaw)); - let mut attached_to_middle = !b.collision_face_full(above_state, Direction::Down) || ctx.sneaking; + let mut attached_to_middle = + !b.collision_face_full(above_state, Direction::Down) || ctx.sneaking; if below_hanging && !ctx.sneaking { if b.instance_of(above_state, Class::WallHangingSign) { if axis_of(b.facing(above_state)) == axis_of(direction) { @@ -441,24 +544,45 @@ impl Sim<'_, L> { } else { rotation_segment(ctx.yaw + 180.0) }; - Some(wl(table.set_int(table.set_bool(default, p.attached, attached_to_middle), p.rotation, segment))) + Some(wl(table.set_int( + table.set_bool(default, p.attached, attached_to_middle), + p.rotation, + segment, + ))) } Class::BaseFire | Class::Fire | Class::SoulFire => Some(self.fire_state_for(pos)), Class::BaseRail => { let east_west = matches!(horizontal, Direction::East | Direction::West); - let shape = if east_west { "east_west" } else { "north_south" }; + let shape = if east_west { + "east_west" + } else { + "north_south" + }; Some(wl(table.set_text(default, p.shape, shape))) } Class::Bell => { let face = ctx.face; if axis_of(face) == Axis::Y { - let attachment = if face == Direction::Down { "ceiling" } else { "floor" }; - let state = table.set_dir(table.set_text(default, p.attachment, attachment), p.facing, horizontal); - if self.can_survive(state, pos) { Some(state) } else { None } + let attachment = if face == Direction::Down { + "ceiling" + } else { + "floor" + }; + let state = table.set_dir( + table.set_text(default, p.attachment, attachment), + p.facing, + horizontal, + ); + if self.can_survive(state, pos) { + Some(state) + } else { + None + } } else { let double = match axis_of(face) { Axis::X => { - self.sturdy(rel(pos, Direction::West), Direction::East) && self.sturdy(rel(pos, Direction::East), Direction::West) + self.sturdy(rel(pos, Direction::West), Direction::East) + && self.sturdy(rel(pos, Direction::East), Direction::West) } _ => { self.sturdy(rel(pos, Direction::North), Direction::South) @@ -474,20 +598,39 @@ impl Sim<'_, L> { return Some(Some(state)); } let floor = self.sturdy(below(pos), Direction::Up); - state = table.set_text(state, p.attachment, if floor { "floor" } else { "ceiling" }); - if self.can_survive(state, pos) { Some(state) } else { None } + state = table.set_text( + state, + p.attachment, + if floor { "floor" } else { "ceiling" }, + ); + if self.can_survive(state, pos) { + Some(state) + } else { + None + } } } Class::BigDripleaf => { let below_state = self.below_state(pos); - let dripleaf_part = b.is_block(below_state, n.big_dripleaf) || b.is_block(below_state, n.big_dripleaf_stem); - let facing = if dripleaf_part { b.facing(below_state) } else { horizontal.opposite() }; + let dripleaf_part = b.is_block(below_state, n.big_dripleaf) + || b.is_block(below_state, n.big_dripleaf_stem); + let facing = if dripleaf_part { + b.facing(below_state) + } else { + horizontal.opposite() + }; let source = self.fluid_at(pos) == FluidState::WATER; - Some(table.set_dir(table.set_bool(default, p.waterlogged, source), p.facing, facing)) + Some(table.set_dir( + table.set_bool(default, p.waterlogged, source), + p.facing, + facing, + )) } Class::Campfire => { let water = self.fluid_at(pos).kind() == crate::fluid::FluidKind::Water; - let hay = table.block_by_name("minecraft:hay_block").is_some_and(|hay| b.is_block(self.below_state(pos), hay)); + let hay = table + .block_by_name("minecraft:hay_block") + .is_some_and(|hay| b.is_block(self.below_state(pos), hay)); let state = table.set_bool(default, p.waterlogged, water); let state = table.set_bool(state, p.signal_fire, hay); let state = table.set_bool(state, p.lit, !water); @@ -505,7 +648,11 @@ impl Sim<'_, L> { Class::SeaPickle => { let current = self.state(pos); if b.is_block(current, block) { - Some(table.set_int(current, p.pickles, (table.int(current, p.pickles) + 1).min(4))) + Some(table.set_int( + current, + p.pickles, + (table.int(current, p.pickles) + 1).min(4), + )) } else { let state = sup!()?; Some(wl(state)) @@ -522,14 +669,22 @@ impl Sim<'_, L> { Class::SnowLayer => { let current = self.state(pos); if b.is_block(current, block) { - Some(table.set_int(current, p.layers, (table.int(current, p.layers) + 1).min(8))) + Some(table.set_int( + current, + p.layers, + (table.int(current, p.layers) + 1).min(8), + )) } else { sup!() } } Class::FlowerBed | Class::LeafLitter => { let current = self.state(pos); - let key = if class == Class::FlowerBed { p.flower_amount } else { p.segment_amount }; + let key = if class == Class::FlowerBed { + p.flower_amount + } else { + p.segment_amount + }; if b.is_block(current, block) { Some(table.set_int(current, key, (table.int(current, key) + 1).min(4))) } else { @@ -541,21 +696,38 @@ impl Sim<'_, L> { let mut facing = horizontal.opposite(); let face = ctx.face; if is_horizontal(face) && ctx.sneaking { - if let Some(neighbour_facing) = self.chest_candidate_partner_facing(default, pos, face.opposite()) { + if let Some(neighbour_facing) = + self.chest_candidate_partner_facing(default, pos, face.opposite()) + { if axis_of(neighbour_facing) != axis_of(face) { facing = neighbour_facing; - kind = if counter_clockwise(facing) == face.opposite() { "right" } else { "left" }; + kind = if counter_clockwise(facing) == face.opposite() { + "right" + } else { + "left" + }; } } } if kind == "single" && !ctx.sneaking { - if self.chest_candidate_partner_facing(default, pos, clockwise(facing)) == Some(facing) { + if self.chest_candidate_partner_facing(default, pos, clockwise(facing)) + == Some(facing) + { kind = "left"; - } else if self.chest_candidate_partner_facing(default, pos, counter_clockwise(facing)) == Some(facing) { + } else if self.chest_candidate_partner_facing( + default, + pos, + counter_clockwise(facing), + ) == Some(facing) + { kind = "right"; } } - Some(wl(table.set_text(table.set_dir(default, p.facing, facing), p.kind, kind))) + Some(wl(table.set_text( + table.set_dir(default, p.facing, facing), + p.kind, + kind, + ))) } Class::ChorusPlant => Some(self.chorus_plant_with_connections(pos, default)), Class::ConcretePowder => { @@ -588,14 +760,30 @@ impl Sim<'_, L> { Direction::Up => horizontal, _ => Direction::Up, }; - let orientation = format!("{}_{}", super::states::direction_name(front), super::states::direction_name(top)); + let orientation = format!( + "{}_{}", + super::states::direction_name(front), + super::states::direction_name(top) + ); let signal = self.has_neighbor_signal(pos); - Some(table.set_bool(table.set_text(default, p.orientation, &orientation), p.triggered, signal)) + Some(table.set_bool( + table.set_text(default, p.orientation, &orientation), + p.triggered, + signal, + )) } Class::Jigsaw => { let front = ctx.face; - let top = if axis_of(front) == Axis::Y { horizontal.opposite() } else { Direction::Up }; - let orientation = format!("{}_{}", super::states::direction_name(front), super::states::direction_name(top)); + let top = if axis_of(front) == Axis::Y { + horizontal.opposite() + } else { + Direction::Up + }; + let orientation = format!( + "{}_{}", + super::states::direction_name(front), + super::states::direction_name(top) + ); Some(table.set_text(default, p.orientation, &orientation)) } Class::CreakingHeart | Class::RotatedPillar | Class::InfestedRotatedPillar => { @@ -606,19 +794,25 @@ impl Sim<'_, L> { Some(table.set_bool(wl(state), p.cracked, false)) } Class::Door => { - if pos.y < self.level.max_y() - 1 && self.can_be_replaced(self.state(above(pos)), ctx) { - let powered = self.has_neighbor_signal(pos) || self.has_neighbor_signal(above(pos)); + if pos.y < self.level.max_y() - 1 + && self.can_be_replaced(self.state(above(pos)), ctx) + { + let powered = + self.has_neighbor_signal(pos) || self.has_neighbor_signal(above(pos)); let hinge = self.door_hinge(ctx); let state = table.set_dir(default, p.facing, horizontal); let state = table.set_text(state, p.hinge, hinge); - let state = table.set_bool(table.set_bool(state, p.powered, powered), p.open, powered); + let state = + table.set_bool(table.set_bool(state, p.powered, powered), p.open, powered); Some(table.set_text(state, p.half, "lower")) } else { None } } Class::DoublePlant => { - if pos.y < self.level.max_y() - 1 && self.can_be_replaced(self.state(above(pos)), ctx) { + if pos.y < self.level.max_y() - 1 + && self.can_be_replaced(self.state(above(pos)), ctx) + { sup!() } else { None @@ -629,12 +823,20 @@ impl Sim<'_, L> { let state = sup!()?; let state = table.set_dir(state, p.facing, horizontal.opposite()); let water = self.is_water_at(pos); - Some(table.with_bool(state, p.waterlogged, water).unwrap_or(state)) + Some( + table + .with_bool(state, p.waterlogged, water) + .unwrap_or(state), + ) } Class::TallSeagrass => { let state = sup!()?; let fluid = self.fluid_at(above(pos)); - if b.is_water_fluid(fluid.kind()) && fluid.is_full() { Some(state) } else { None } + if b.is_water_fluid(fluid.kind()) && fluid.is_full() { + Some(state) + } else { + None + } } Class::DriedGhast => { let state = sup!()?; @@ -653,10 +855,18 @@ impl Sim<'_, L> { Class::FaceAttachedHorizontalDirectional => { for direction in ctx.nearest_looking_directions() { let state = if axis_of(direction) == Axis::Y { - let face = if direction == Direction::Up { "ceiling" } else { "floor" }; + let face = if direction == Direction::Up { + "ceiling" + } else { + "floor" + }; table.set_dir(table.set_text(default, p.face, face), p.facing, horizontal) } else { - table.set_dir(table.set_text(default, p.face, "wall"), p.facing, direction.opposite()) + table.set_dir( + table.set_text(default, p.face, "wall"), + p.facing, + direction.opposite(), + ) }; if self.can_survive(state, pos) { return Some(Some(state)); @@ -683,24 +893,44 @@ impl Sim<'_, L> { for direction in HORIZONTAL { let neighbour = self.rel_state(pos, direction); let sturdy = b.is_face_sturdy(neighbour, direction.opposite()); - let connect = self.fence_connects_to(default, neighbour, sturdy, direction.opposite()); + let connect = + self.fence_connects_to(default, neighbour, sturdy, direction.opposite()); state = table.set_bool(state, self.direction_prop(direction), connect); } Some(wl(state)) } Class::IronBars => { let mut state = default; - for direction in [Direction::North, Direction::South, Direction::West, Direction::East] { + for direction in [ + Direction::North, + Direction::South, + Direction::West, + Direction::East, + ] { let neighbour = self.rel_state(pos, direction); let sturdy = b.is_face_sturdy(neighbour, direction.opposite()); - state = table.set_bool(state, self.direction_prop(direction), self.bars_attach_to(neighbour, sturdy)); + state = table.set_bool( + state, + self.direction_prop(direction), + self.bars_attach_to(neighbour, sturdy), + ); } Some(wl(state)) } Class::Wall => { - let sides = [Direction::North, Direction::East, Direction::South, Direction::West].map(|direction| { + let sides = [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, + ] + .map(|direction| { let neighbour = self.rel_state(pos, direction); - self.wall_connects_to(neighbour, b.is_face_sturdy(neighbour, direction.opposite()), direction.opposite()) + self.wall_connects_to( + neighbour, + b.is_face_sturdy(neighbour, direction.opposite()), + direction.opposite(), + ) }); let top_pos = above(pos); let top = self.state(top_pos); @@ -734,11 +964,19 @@ impl Sim<'_, L> { } Class::Kelp => { let fluid = self.fluid_at(pos); - if b.is_water_fluid(fluid.kind()) && fluid.is_full() { sup!() } else { None } + if b.is_water_fluid(fluid.kind()) && fluid.is_full() { + sup!() + } else { + None + } } Class::Seagrass => { let fluid = self.fluid_at(pos); - if b.is_water_fluid(fluid.kind()) && fluid.is_full() { sup!() } else { None } + if b.is_water_fluid(fluid.kind()) && fluid.is_full() { + sup!() + } else { + None + } } Class::HangingRoots => { let state = sup!()?; @@ -746,7 +984,11 @@ impl Sim<'_, L> { } Class::Hopper => { let direction = ctx.face.opposite(); - let facing = if axis_of(direction) == Axis::Y { Direction::Down } else { direction }; + let facing = if axis_of(direction) == Axis::Y { + Direction::Down + } else { + direction + }; Some(table.set_bool(table.set_dir(default, p.facing, facing), p.enabled, true)) } Class::HugeMushroom => { @@ -772,7 +1014,8 @@ impl Sim<'_, L> { let state = wl(table.set_bool(default, p.persistent, true)); let mut distance = 7; for direction in Direction::ALL { - distance = distance.min(self.leaf_distance_at(self.rel_state(pos, direction)) + 1); + distance = + distance.min(self.leaf_distance_at(self.rel_state(pos, direction)) + 1); if distance == 1 { break; } @@ -812,24 +1055,49 @@ impl Sim<'_, L> { Class::Slab => { let replaced = self.state(pos); if b.is_block(replaced, block) { - return Some(Some(table.set_bool(table.set_text(replaced, p.kind, "double"), p.waterlogged, false))); + return Some(Some(table.set_bool( + table.set_text(replaced, p.kind, "double"), + p.waterlogged, + false, + ))); } let result = wl(table.set_text(default, p.kind, "bottom")); - if ctx.half_from_click() { Some(result) } else { Some(table.set_text(result, p.kind, "top")) } + if ctx.half_from_click() { + Some(result) + } else { + Some(table.set_text(result, p.kind, "top")) + } } Class::Stair => { - let half = if ctx.half_from_click() { "bottom" } else { "top" }; - let state = wl(table.set_text(table.set_dir(default, p.facing, horizontal), p.half, half)); + let half = if ctx.half_from_click() { + "bottom" + } else { + "top" + }; + let state = + wl(table.set_text(table.set_dir(default, p.facing, horizontal), p.half, half)); let shape = self.stairs_shape(state, pos); Some(table.set_text(state, p.shape, shape)) } Class::TrapDoor => { let mut state = if !ctx.replace_clicked && is_horizontal(ctx.face) { let top = ctx.hit.y - f64::from(pos.y) > 0.5; - table.set_text(table.set_dir(default, p.facing, ctx.face), p.half, if top { "top" } else { "bottom" }) + table.set_text( + table.set_dir(default, p.facing, ctx.face), + p.half, + if top { "top" } else { "bottom" }, + ) } else { - let half = if ctx.face == Direction::Up { "bottom" } else { "top" }; - table.set_text(table.set_dir(default, p.facing, horizontal.opposite()), p.half, half) + let half = if ctx.face == Direction::Up { + "bottom" + } else { + "top" + }; + table.set_text( + table.set_dir(default, p.facing, horizontal.opposite()), + p.half, + half, + ) }; if self.has_neighbor_signal(pos) { state = table.set_bool(table.set_bool(state, p.open, true), p.powered, true); @@ -856,7 +1124,8 @@ impl Sim<'_, L> { Class::TripWire => { let mut state = default; for direction in HORIZONTAL { - let connect = self.tripwire_should_connect_to(self.rel_state(pos, direction), direction); + let connect = + self.tripwire_should_connect_to(self.rel_state(pos, direction), direction); state = table.set_bool(state, self.direction_prop(direction), connect); } Some(state) @@ -882,16 +1151,27 @@ impl Sim<'_, L> { }) } - fn chest_candidate_partner_facing(&self, chest: BlockStateId, pos: BlockPos, direction: Direction) -> Option { + fn chest_candidate_partner_facing( + &self, + chest: BlockStateId, + pos: BlockPos, + direction: Direction, + ) -> Option { let state = self.rel_state(pos, direction); - if self.chest_can_connect_to(chest, state) && self.b.table.text(state, self.b.props.kind) == "single" { + if self.chest_can_connect_to(chest, state) + && self.b.table.text(state, self.b.props.kind) == "single" + { Some(self.b.facing(state)) } else { None } } /// `ChorusPlantBlock.getStateWithConnections`. - pub(crate) fn chorus_plant_with_connections(&self, pos: BlockPos, state: BlockStateId) -> BlockStateId { + pub(crate) fn chorus_plant_with_connections( + &self, + pos: BlockPos, + state: BlockStateId, + ) -> BlockStateId { let b = self.b; let block = b.block(state); let flower = b.named.chorus_flower; @@ -902,7 +1182,10 @@ impl Sim<'_, L> { if direction == Direction::Down { connect |= b.in_set(neighbour, &b.tags.supports_chorus_plant); } - result = b.table.with_bool(result, self.direction_prop(direction), connect).unwrap_or(result); + result = b + .table + .with_bool(result, self.direction_prop(direction), connect) + .unwrap_or(result); } result } @@ -911,15 +1194,24 @@ impl Sim<'_, L> { let facing = b.facing(state); let attach = |side: Direction, face: Direction| { let attach_state = self.rel_state(pos, side); - if b.tag("minecraft:wall_hanging_signs").is_some_and(|tag| b.in_set(attach_state, tag)) { + if b.tag("minecraft:wall_hanging_signs") + .is_some_and(|tag| b.in_set(attach_state, tag)) + { axis_of(b.facing(attach_state)) == axis_of(facing) } else { b.is_face_sturdy(attach_state, face) } }; - attach(clockwise(facing), counter_clockwise(facing)) || attach(counter_clockwise(facing), clockwise(facing)) + attach(clockwise(facing), counter_clockwise(facing)) + || attach(counter_clockwise(facing), clockwise(facing)) } - fn multiface_placement(&self, block: BlockId, old: BlockStateId, pos: BlockPos, direction: Direction) -> Option { + fn multiface_placement( + &self, + block: BlockId, + old: BlockStateId, + pos: BlockPos, + direction: Direction, + ) -> Option { let b = self.b; if b.is_block(old, block) && self.multiface_has_face(old, direction) { return None; @@ -930,11 +1222,15 @@ impl Sim<'_, L> { let state = if b.is_block(old, block) { old } else if b.fluid(old) == FluidState::WATER { - b.table.set_bool(b.default_of(block), b.props.waterlogged, true) + b.table + .set_bool(b.default_of(block), b.props.waterlogged, true) } else { b.default_of(block) }; - Some(b.table.set_bool(state, self.direction_prop(direction), true)) + Some( + b.table + .set_bool(state, self.direction_prop(direction), true), + ) } fn vine_can_support_at(&self, vine: BlockStateId, pos: BlockPos, direction: Direction) -> bool { let b = self.b; @@ -948,24 +1244,41 @@ impl Sim<'_, L> { return false; } let above_state = self.above_state(pos); - b.is_block(above_state, b.block(vine)) && b.table.bool(above_state, self.direction_prop(direction)) + b.is_block(above_state, b.block(vine)) + && b.table.bool(above_state, self.direction_prop(direction)) } - fn speleothem_thickness_for(&self, block: BlockId, pos: BlockPos, tip: Direction, merge: bool) -> &'static str { + fn speleothem_thickness_for( + &self, + block: BlockId, + pos: BlockPos, + tip: Direction, + merge: bool, + ) -> &'static str { let b = self.b; let p = b.props; let base = tip.opposite(); let is_with = |state: BlockStateId, direction: Direction| { - b.tag("minecraft:speleothems").is_some_and(|tag| b.in_set(state, tag)) && b.table.dir(state, p.vertical_direction) == Some(direction) + b.tag("minecraft:speleothems") + .is_some_and(|tag| b.in_set(state, tag)) + && b.table.dir(state, p.vertical_direction) == Some(direction) }; let front = self.rel_state(pos, tip); if is_with(front, base) && b.is_block(front, block) { - if !merge && b.table.text(front, p.thickness) != "tip_merge" { "tip" } else { "tip_merge" } + if !merge && b.table.text(front, p.thickness) != "tip_merge" { + "tip" + } else { + "tip_merge" + } } else if !is_with(front, tip) { "tip" } else { let thickness = b.table.text(front, p.thickness); if thickness != "tip" && thickness != "tip_merge" { - if !is_with(self.rel_state(pos, base), tip) { "base" } else { "middle" } + if !is_with(self.rel_state(pos, base), tip) { + "base" + } else { + "middle" + } } else { "frustum" } @@ -984,8 +1297,12 @@ impl Sim<'_, L> { let right_state = self.rel_state(pos, right); let right_above = self.rel_state(above_pos, right); let full = |s: BlockStateId| b.full_collision(s); - let balance = -i32::from(full(left_state)) - i32::from(full(left_above)) + i32::from(full(right_state)) + i32::from(full(right_above)); - let lower_door = |s: BlockStateId| b.instance_of(s, Class::Door) && b.table.text(s, b.props.half) == "lower"; + let balance = -i32::from(full(left_state)) - i32::from(full(left_above)) + + i32::from(full(right_state)) + + i32::from(full(right_above)); + let lower_door = |s: BlockStateId| { + b.instance_of(s, Class::Door) && b.table.text(s, b.props.half) == "lower" + }; let door_left = lower_door(left_state); let door_right = lower_door(right_state); if (door_left && !door_right) || balance > 0 { @@ -998,7 +1315,11 @@ impl Sim<'_, L> { let step_z = place.normal()[2]; let click_x = ctx.hit.x - f64::from(pos.x); let click_z = ctx.hit.z - f64::from(pos.z); - if (step_x >= 0 || click_z >= 0.5) && (step_x <= 0 || click_z <= 0.5) && (step_z >= 0 || click_x <= 0.5) && (step_z <= 0 || click_x >= 0.5) { + if (step_x >= 0 || click_z >= 0.5) + && (step_x <= 0 || click_z <= 0.5) + && (step_z >= 0 || click_x <= 0.5) + && (step_z <= 0 || click_x >= 0.5) + { "left" } else { "right" @@ -1027,15 +1348,25 @@ impl Sim<'_, L> { } else if data.is(Class::PitcherCrop) { } else if data.is(Class::SmallDripleaf) { let above_pos = above(pos); - let upper = b.table.set_dir(b.table.set_text(b.default_of(block), p.half, "upper"), p.facing, b.facing(state)); + let upper = b.table.set_dir( + b.table.set_text(b.default_of(block), p.half, "upper"), + p.facing, + b.facing(state), + ); let water = self.is_water_at(above_pos); - let upper = b.table.with_bool(upper, p.waterlogged, water).unwrap_or(upper); + let upper = b + .table + .with_bool(upper, p.waterlogged, water) + .unwrap_or(upper); self.set_block_and_update(above_pos, upper); } else if data.is(Class::DoublePlant) { let above_pos = above(pos); let upper = b.table.set_text(b.default_of(block), p.half, "upper"); let water = self.is_water_at(above_pos); - let upper = b.table.with_bool(upper, p.waterlogged, water).unwrap_or(upper); + let upper = b + .table + .with_bool(upper, p.waterlogged, water) + .unwrap_or(upper); self.set_block_and_update(above_pos, upper); } else if data.is(Class::PistonBase) { self.piston_check_if_extend(pos, state); @@ -1056,7 +1387,9 @@ impl Sim<'_, L> { let above_pos = above(pos); let above_state = self.state(above_pos); let is_carpet = b.is_block(above_state, block); - if (!is_carpet || !b.table.bool(above_state, p.bottom)) && (is_carpet || b.is_replaceable(above_state)) { + if (!is_carpet || !b.table.bool(above_state, p.bottom)) + && (is_carpet || b.is_replaceable(above_state)) + { let carpet = b.table.set_bool(b.default_of(block), p.bottom, false); let updated = self.mossy_carpet_updated_state(carpet, above_pos, true); let mut result = updated; @@ -1074,11 +1407,14 @@ impl Sim<'_, L> { } /// `BlockItem.place` (and its subclasses' overrides). - pub(crate) fn place(&mut self, input: &PlaceContext) -> PlaceOutcome { + /// `BlockPlaceContext` resolution, `updatePlacementContext` and the item's + /// `getPlacementState` (survival and obstruction checks included). + pub(crate) fn placement( + &mut self, + input: &PlaceContext, + ) -> Option<(Ctx, super::data::ItemBinding, BlockStateId)> { let b = self.b; - let Some(binding) = b.item_binding(&input.item).cloned() else { - return PlaceOutcome::Failed; - }; + let binding = b.item_binding(&input.item).cloned()?; let mut ctx = Ctx { pos: input.clicked_pos, hit_pos: input.clicked_pos, @@ -1096,27 +1432,30 @@ impl Sim<'_, L> { ctx.pos = rel(input.clicked_pos, input.face); } if !ctx.replace_clicked && !self.can_be_replaced(self.state(ctx.pos), &ctx) { - return PlaceOutcome::Failed; + return None; } if binding.kind == ItemKind::Scaffolding { - match self.scaffolding_update_context(&ctx, binding.block) { - Some(updated) => ctx = updated, - None => return PlaceOutcome::Failed, - } + ctx = self.scaffolding_update_context(&ctx, binding.block)?; } - if !self.is_in_valid_bounds(ctx.pos) { - return PlaceOutcome::Failed; + if binding.game_master && !input.can_use_game_master_blocks { + return None; } let state = match binding.kind { ItemKind::StandingAndWall | ItemKind::HangingSign => { - let wall = binding.wall_block.and_then(|wall| self.state_for_placement(wall, &ctx)); + let wall = binding + .wall_block + .and_then(|wall| self.state_for_placement(wall, &ctx)); let attachment = binding.attachment.unwrap_or(Direction::Down); let mut chosen = None; for direction in ctx.nearest_looking_directions() { if direction == attachment.opposite() { continue; } - let candidate = if direction == attachment { self.state_for_placement(binding.block, &ctx) } else { wall }; + let candidate = if direction == attachment { + self.state_for_placement(binding.block, &ctx) + } else { + wall + }; if let Some(candidate) = candidate { let hanging_ok = binding.kind != ItemKind::HangingSign || !b.instance_of(candidate, Class::WallHangingSign) @@ -1132,15 +1471,32 @@ impl Sim<'_, L> { _ => { let must_survive = binding.kind != ItemKind::Scaffolding; self.state_for_placement(binding.block, &ctx) - .filter(|state| (!must_survive || self.can_survive(*state, ctx.pos)) && self.level.is_unobstructed(ctx.pos, *state)) + .filter(|state| { + (!must_survive || self.can_survive(*state, ctx.pos)) + && self.level.is_unobstructed(ctx.pos, *state) + }) } }; - let Some(state) = state else { + state.map(|state| (ctx, binding, state)) + } + + /// `BlockItem.place` (and its subclasses' overrides). + pub(crate) fn place(&mut self, input: &PlaceContext) -> PlaceOutcome { + let b = self.b; + let Some((ctx, binding, state)) = self.placement(input) else { return PlaceOutcome::Failed; }; + if !self.is_in_valid_bounds(ctx.pos) { + return PlaceOutcome::Failed; + } + if binding.kind == ItemKind::DoubleHigh { let above_pos = above(ctx.pos); - let replacement = if self.is_water_at(above_pos) { b.default_of(b.named.water) } else { b.air() }; + let replacement = if self.is_water_at(above_pos) { + b.default_of(b.named.water) + } else { + b.air() + }; self.set_block(above_pos, replacement, 27); } if !self.set_block(ctx.pos, state, 11) { @@ -1159,17 +1515,28 @@ impl Sim<'_, L> { pitch: sounds.pitch * 0.8, }); self.game_event(ctx.pos, "minecraft:block_place"); - PlaceOutcome::Placed { pos: ctx.pos, state: placed } + PlaceOutcome::Placed { + pos: ctx.pos, + state: placed, + } } /// `ScaffoldingBlockItem.updatePlacementContext`. fn scaffolding_update_context(&self, ctx: &Ctx, block: BlockId) -> Option { let b = self.b; let pos = ctx.pos; if !b.is_block(self.state(pos), block) { - return if self.scaffolding_distance(pos) == 7 { None } else { Some(ctx.clone()) }; + return if self.scaffolding_distance(pos) == 7 { + None + } else { + Some(ctx.clone()) + }; } let direction = if ctx.sneaking { - if ctx.inside { ctx.face.opposite() } else { ctx.face } + if ctx.inside { + ctx.face.opposite() + } else { + ctx.face + } } else if ctx.face == Direction::Up { ctx.horizontal_direction() } else { @@ -1215,9 +1582,26 @@ impl Behaviours { /// position, computes `getStateForPlacement`, checks survival and entity /// obstruction, writes the block (flags 11), runs `setPlacedBy` (second /// halves of doors, beds, tall plants) and reports the place sound. - pub fn place_block(&self, level: &mut L, ticks: &mut Ticks, ctx: &PlaceContext) -> PlaceOutcome { + pub fn place_block( + &self, + level: &mut L, + ticks: &mut Ticks, + ctx: &PlaceContext, + ) -> PlaceOutcome { self.sim(level, ticks).place(ctx) } + /// The position and state `BlockItem.place` would place for `ctx`, without + /// writing anything (None when vanilla's placement fails). + pub fn placement_state( + &self, + level: &mut L, + ticks: &mut Ticks, + ctx: &PlaceContext, + ) -> Option<(BlockPos, BlockStateId)> { + self.sim(level, ticks) + .placement(ctx) + .map(|(ctx, _, state)| (ctx.pos, state)) + } /// `getStateForPlacement` of `block` for `ctx` without placing anything /// (`None` when vanilla refuses the placement). The position is resolved /// as `BlockPlaceContext` does. diff --git a/crates/horizon-world/src/level/query.rs b/crates/horizon-world/src/level/query.rs index 580b6276f..f10bd158a 100644 --- a/crates/horizon-world/src/level/query.rs +++ b/crates/horizon-world/src/level/query.rs @@ -41,7 +41,12 @@ pub(crate) fn axis_of(direction: Direction) -> horizon_core::geometry::Axis { } /// `Direction.from2DDataValue` (S, W, N, E). pub(crate) fn from_2d(value: i32) -> Direction { - [Direction::South, Direction::West, Direction::North, Direction::East][value.rem_euclid(4) as usize] + [ + Direction::South, + Direction::West, + Direction::North, + Direction::East, + ][value.rem_euclid(4) as usize] } pub(crate) fn data_2d(direction: Direction) -> i32 { match direction { @@ -89,7 +94,11 @@ impl Behaviours { self.shape_info(state).full_faces & (1 << direction as u8) != 0 } /// `MultifaceBlock.canAttachTo(level, direction, neighbourPos, neighbourState)`. - pub(crate) fn multiface_can_attach(&self, neighbour: BlockStateId, direction: Direction) -> bool { + pub(crate) fn multiface_can_attach( + &self, + neighbour: BlockStateId, + direction: Direction, + ) -> bool { let face = direction.opposite(); self.is_face_sturdy(neighbour, face) || self.collision_face_full(neighbour, face) } @@ -109,7 +118,9 @@ impl Behaviours { self.table.bool(state, self.props.waterlogged) } pub(crate) fn facing(&self, state: BlockStateId) -> Direction { - self.table.dir(state, self.props.facing).unwrap_or(Direction::North) + self.table + .dir(state, self.props.facing) + .unwrap_or(Direction::North) } /// The boolean/enum property named after `direction` (`north`, `up`, ...). pub(crate) fn dir_prop(&self, direction: Direction) -> PropKey { @@ -139,12 +150,18 @@ impl crate::dynamic_support::DynamicSupportWorld for NoBlockEntities { fn shulker_is_closed(&mut self, _position: [i32; 3]) -> Result, Self::Error> { Ok(None) } - fn moving_piston_shape(&mut self, _position: [i32; 3]) -> Result, Self::Error> { + fn moving_piston_shape( + &mut self, + _position: [i32; 3], + ) -> Result, Self::Error> { Ok(None) } } impl crate::block_collision::DynamicCollisionWorld for NoBlockEntities { - fn shulker_collision_state(&mut self, _position: [i32; 3]) -> Result, Self::Error> { + fn shulker_collision_state( + &mut self, + _position: [i32; 3], + ) -> Result, Self::Error> { Ok(None) } } @@ -152,7 +169,11 @@ impl crate::block_collision::DynamicCollisionWorld for NoBlockEntities { impl Sim<'_, L> { /// Shape queries over `getCollisionShape(level, pos)`, including the /// position-dependent shapes (bamboo, speleothems, shulker boxes). - pub(crate) fn shape_info_at(&self, state: BlockStateId, pos: BlockPos) -> super::data::ShapeInfo { + pub(crate) fn shape_info_at( + &self, + state: BlockStateId, + pos: BlockPos, + ) -> super::data::ShapeInfo { if self.b.facts(state).shape >= 0 { return self.b.shape_info(state); } @@ -175,7 +196,8 @@ impl Sim<'_, L> { /// `Block.canSupportCenter(level, pos, direction)`. pub fn can_support_center(&self, pos: BlockPos, direction: Direction) -> bool { let state = self.state(pos); - if direction == Direction::Down && self.b.in_set(state, &self.b.tags.unstable_bottom_center) { + if direction == Direction::Down && self.b.in_set(state, &self.b.tags.unstable_bottom_center) + { return false; } self.b.is_face_sturdy_center(state, direction) diff --git a/crates/horizon-world/src/level/rails.rs b/crates/horizon-world/src/level/rails.rs index 9a1fb5468..b5a784796 100644 --- a/crates/horizon-world/src/level/rails.rs +++ b/crates/horizon-world/src/level/rails.rs @@ -56,7 +56,10 @@ impl RailShape { } } fn is_slope(self) -> bool { - matches!(self, Self::AscendingEast | Self::AscendingWest | Self::AscendingNorth | Self::AscendingSouth) + matches!( + self, + Self::AscendingEast | Self::AscendingWest | Self::AscendingNorth | Self::AscendingSouth + ) } } @@ -79,7 +82,12 @@ impl Sim<'_, L> { 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)); + 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], @@ -112,7 +120,9 @@ impl Sim<'_, L> { None } fn rail_has_connection(rail: &Rail, pos: BlockPos) -> bool { - rail.connections.iter().any(|c| c.x == pos.x && c.z == pos.z) + 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; @@ -150,7 +160,12 @@ impl Sim<'_, L> { .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 (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)) { @@ -171,7 +186,9 @@ impl Sim<'_, L> { shape } fn rail_set_shape(&self, state: BlockStateId, shape: RailShape) -> BlockStateId { - self.b.table.set_text(state, self.b.props.shape, shape.name()) + 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); @@ -201,12 +218,21 @@ impl Sim<'_, L> { shape = Some(RailShape::NorthEast); } } - let shape = self.rail_slopes(pos, shape).unwrap_or(RailShape::NorthSouth); + 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 { + 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)); @@ -292,7 +318,12 @@ impl Sim<'_, L> { 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 { + 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); @@ -300,7 +331,13 @@ impl Sim<'_, L> { } state } - pub(crate) fn rail_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId, changed: BlockId, moved: bool) { + 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; @@ -325,18 +362,23 @@ impl Sim<'_, L> { 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 { + 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) + 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); + 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); @@ -346,7 +388,13 @@ impl Sim<'_, L> { } } } - fn powered_rail_find(&self, pos: BlockPos, state: BlockStateId, forward: bool, depth: i32) -> bool { + fn powered_rail_find( + &self, + pos: BlockPos, + state: BlockStateId, + forward: bool, + depth: i32, + ) -> bool { if depth >= 8 { return false; } @@ -400,19 +448,43 @@ impl Sim<'_, L> { } 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)) + || (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 { + 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) { + 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) { + if dir == RailShape::NorthSouth + && matches!( + mine, + RailShape::EastWest | RailShape::AscendingEast | RailShape::AscendingWest + ) + { return false; } if !b.table.bool(state, b.props.powered) { @@ -455,12 +527,27 @@ impl Sim<'_, L> { 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 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), + 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 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); @@ -478,16 +565,43 @@ impl Sim<'_, L> { 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) { + 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") + ( + "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") + ( + "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") + ( + "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") + ( + "minecraft:block.tripwire.detach", + 0.4, + pitch, + "minecraft:block_detach", + ) } else { return; }; @@ -550,7 +664,11 @@ impl Sim<'_, L> { } 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); + 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(); @@ -574,8 +692,13 @@ impl Sim<'_, L> { 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); + 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); } } diff --git a/crates/horizon-world/src/level/redstone.rs b/crates/horizon-world/src/level/redstone.rs index eaa9d6d2b..ea3440842 100644 --- a/crates/horizon-world/src/level/redstone.rs +++ b/crates/horizon-world/src/level/redstone.rs @@ -10,7 +10,9 @@ use super::{ update::{HORIZONTAL, above, below, rel}, }; use crate::registry::BlockStateId; -use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource, ticks::TickPriority}; +use horizon_core::{ + geometry::Direction, position::BlockPos, random::RandomSource, ticks::TickPriority, +}; const SIGNAL_ORDER: [Direction; 6] = [ Direction::Down, @@ -32,7 +34,12 @@ impl Sim<'_, L> { self.b.has_flag(state, state_flags::SIGNAL_SOURCE) } /// `BlockState.getSignal(level, pos, direction)`. - pub(crate) fn state_signal(&self, state: BlockStateId, pos: BlockPos, direction: Direction) -> i32 { + pub(crate) fn state_signal( + &self, + state: BlockStateId, + pos: BlockPos, + direction: Direction, + ) -> i32 { let b = self.b; if !b.has_flag(state, state_flags::SIGNAL_SOURCE) { return 0; @@ -52,7 +59,12 @@ impl Sim<'_, L> { } } /// `BlockState.getDirectSignal(level, pos, direction)`. - pub(crate) fn state_direct_signal(&self, state: BlockStateId, pos: BlockPos, direction: Direction) -> i32 { + pub(crate) fn state_direct_signal( + &self, + state: BlockStateId, + pos: BlockPos, + direction: Direction, + ) -> i32 { let b = self.b; if !b.has_flag(state, state_flags::SIGNAL_SOURCE) { return 0; @@ -77,7 +89,11 @@ impl Sim<'_, L> { } } pub(crate) fn comparator_output(&self, pos: BlockPos) -> i32 { - self.ticks.comparator_outputs.get(&pos).copied().unwrap_or(0) + self.ticks + .comparator_outputs + .get(&pos) + .copied() + .unwrap_or(0) } fn wire_signal(&self, state: BlockStateId, pos: BlockPos, direction: Direction) -> i32 { if self.wire_signal_off.get() || direction == Direction::Down { @@ -89,7 +105,12 @@ impl Sim<'_, L> { } if direction != Direction::Up { let connected = self.wire_connection_state(state, pos); - if self.b.table.text(connected, self.direction_prop(direction.opposite())) == "none" { + if self + .b + .table + .text(connected, self.direction_prop(direction.opposite())) + == "none" + { return 0; } } @@ -125,7 +146,9 @@ impl Sim<'_, L> { } /// `SignalGetter.hasNeighborSignal`. pub fn has_neighbor_signal(&self, pos: BlockPos) -> bool { - SIGNAL_ORDER.into_iter().any(|direction| self.signal(rel(pos, direction), direction) > 0) + SIGNAL_ORDER + .into_iter() + .any(|direction| self.signal(rel(pos, direction), direction) > 0) } /// `SignalGetter.getBestNeighborSignal`. pub fn best_neighbor_signal(&self, pos: BlockPos) -> i32 { @@ -144,7 +167,11 @@ impl Sim<'_, L> { let b = self.b; let state = self.state(pos); if only_diodes { - if b.instance_of(state, Class::Diode) { self.direct_signal(pos, direction) } else { 0 } + if b.instance_of(state, Class::Diode) { + self.direct_signal(pos, direction) + } else { + 0 + } } else if b.is_block(state, b.named.redstone_block) { 15 } else if b.is_block(state, b.named.redstone_wire) { @@ -173,18 +200,30 @@ impl Sim<'_, L> { fn wire_can_survive_on(&self, state: BlockStateId) -> bool { self.b.is_face_sturdy(state, Direction::Up) || self.b.is_block(state, self.b.named.hopper) } - fn wire_connecting_side(&self, pos: BlockPos, direction: Direction, can_connect_up: bool) -> &'static str { + fn wire_connecting_side( + &self, + pos: BlockPos, + direction: Direction, + can_connect_up: bool, + ) -> &'static str { let b = self.b; let relative_pos = rel(pos, direction); let relative = self.state(relative_pos); if can_connect_up { - let placeable_above = b.instance_of(relative, Class::TrapDoor) || self.wire_can_survive_on(relative); - if placeable_above && self.should_wire_connect_to(self.state(above(relative_pos)), None) { - return if b.is_face_sturdy(relative, direction.opposite()) { "up" } else { "side" }; + let placeable_above = + b.instance_of(relative, Class::TrapDoor) || self.wire_can_survive_on(relative); + if placeable_above && self.should_wire_connect_to(self.state(above(relative_pos)), None) + { + return if b.is_face_sturdy(relative, direction.opposite()) { + "up" + } else { + "side" + }; } } if !self.should_wire_connect_to(relative, Some(direction)) - && (self.is_redstone_conductor(relative, relative_pos) || !self.should_wire_connect_to(self.state(below(relative_pos)), None)) + && (self.is_redstone_conductor(relative, relative_pos) + || !self.should_wire_connect_to(self.state(below(relative_pos)), None)) { "none" } else { @@ -198,16 +237,22 @@ impl Sim<'_, L> { self.b.table.text(state, self.direction_prop(direction)) != "none" } fn wire_is_cross(&self, state: BlockStateId) -> bool { - HORIZONTAL.into_iter().all(|d| self.wire_connected(state, d)) + HORIZONTAL + .into_iter() + .all(|d| self.wire_connected(state, d)) } fn wire_is_dot(&self, state: BlockStateId) -> bool { - !HORIZONTAL.into_iter().any(|d| self.wire_connected(state, d)) + !HORIZONTAL + .into_iter() + .any(|d| self.wire_connected(state, d)) } pub(crate) fn wire_cross_state(&self, power: i32) -> BlockStateId { let b = self.b; let mut state = b.default_of(b.named.redstone_wire); for direction in HORIZONTAL { - state = b.table.set_text(state, self.direction_prop(direction), "side"); + state = b + .table + .set_text(state, self.direction_prop(direction), "side"); } b.table.set_int(state, b.props.power, power) } @@ -216,7 +261,11 @@ impl Sim<'_, L> { let b = self.b; let table = &b.table; let was_dot = self.wire_is_dot(state); - let mut result = table.set_int(b.default_of(b.named.redstone_wire), b.props.power, table.int(state, b.props.power)); + let mut result = table.set_int( + b.default_of(b.named.redstone_wire), + b.props.power, + table.int(state, b.props.power), + ); let can_up = self.wire_can_connect_up(pos); for direction in HORIZONTAL { if !self.wire_connected(result, direction) { @@ -268,7 +317,9 @@ impl Sim<'_, L> { _ => { let side = self.wire_connecting_side(pos, direction, self.wire_can_connect_up(pos)); let key = self.direction_prop(direction); - if (side != "none") == self.wire_connected(state, direction) && !self.wire_is_cross(state) { + if (side != "none") == self.wire_connected(state, direction) + && !self.wire_is_cross(state) + { b.table.set_text(state, key, side) } else { let power = b.table.int(state, b.props.power); @@ -279,22 +330,44 @@ impl Sim<'_, L> { } } /// `RedstoneWireBlock.updateIndirectNeighbourShapes`. - pub(crate) fn wire_update_indirect(&mut self, state: BlockStateId, pos: BlockPos, flags: i32, limit: i32) { + pub(crate) fn wire_update_indirect( + &mut self, + state: BlockStateId, + pos: BlockPos, + flags: i32, + limit: i32, + ) { let b = self.b; let wire = b.named.redstone_wire; for direction in HORIZONTAL { - if b.table.text(state, self.direction_prop(direction)) != "none" && !b.is_block(self.rel_state(pos, direction), wire) { + if b.table.text(state, self.direction_prop(direction)) != "none" + && !b.is_block(self.rel_state(pos, direction), wire) + { let down = below(rel(pos, direction)); if b.is_block(self.state(down), wire) { let neighbour = rel(down, direction.opposite()); let neighbour_state = self.state(neighbour); - self.neighbor_shape_changed(direction.opposite(), down, neighbour, neighbour_state, flags, limit); + self.neighbor_shape_changed( + direction.opposite(), + down, + neighbour, + neighbour_state, + flags, + limit, + ); } let up = above(rel(pos, direction)); if b.is_block(self.state(up), wire) { let neighbour = rel(up, direction.opposite()); let neighbour_state = self.state(neighbour); - self.neighbor_shape_changed(direction.opposite(), up, neighbour, neighbour_state, flags, limit); + self.neighbor_shape_changed( + direction.opposite(), + up, + neighbour, + neighbour_state, + flags, + limit, + ); } } } @@ -319,7 +392,9 @@ impl Sim<'_, L> { let neighbour = self.state(neighbour_pos); signal = signal.max(self.wire_power_of(neighbour)); let above_pos = above(pos); - if self.is_redstone_conductor(neighbour, neighbour_pos) && !self.is_redstone_conductor(self.state(above_pos), above_pos) { + if self.is_redstone_conductor(neighbour, neighbour_pos) + && !self.is_redstone_conductor(self.state(above_pos), above_pos) + { signal = signal.max(self.wire_power_of(self.state(above(neighbour_pos)))); } else if !self.is_redstone_conductor(neighbour, neighbour_pos) { signal = signal.max(self.wire_power_of(self.state(below(neighbour_pos)))); @@ -343,7 +418,9 @@ impl Sim<'_, L> { // Vanilla iterates a HashSet of the position and its six // neighbours; BlockPos hash order is reproduced below. let wire = self.b.named.redstone_wire; - let mut targets: Vec = std::iter::once(pos).chain(Direction::ALL.map(|d| rel(pos, d))).collect(); + let mut targets: Vec = std::iter::once(pos) + .chain(Direction::ALL.map(|d| rel(pos, d))) + .collect(); java_hash_set_order(&mut targets); for target_pos in targets { self.update_neighbors_at(target_pos, wire); @@ -425,7 +502,8 @@ impl Sim<'_, L> { return false; } let side = self.diode_alternate_signal(pos, state); - input > side || (input == side && self.b.table.text(state, self.b.props.mode) == "compare") + input > side + || (input == side && self.b.table.text(state, self.b.props.mode) == "compare") } else { self.diode_input_signal(pos, state) > 0 } @@ -463,8 +541,15 @@ impl Sim<'_, L> { if !self.ticks.will_block_tick_this_tick(pos, block) { let output = self.comparator_calculate_output(pos, state); let old = self.comparator_output(pos); - if output != old || self.b.table.bool(state, self.b.props.powered) != self.diode_should_turn_on(pos, state) { - let priority = if self.diode_should_prioritize(pos, state) { TickPriority::High } else { TickPriority::Normal }; + if output != old + || self.b.table.bool(state, self.b.props.powered) + != self.diode_should_turn_on(pos, state) + { + let priority = if self.diode_should_prioritize(pos, state) { + TickPriority::High + } else { + TickPriority::Normal + }; self.schedule_tick_priority(pos, block, 2, priority); } } @@ -512,7 +597,11 @@ impl Sim<'_, L> { pub(crate) fn comparator_refresh(&mut self, pos: BlockPos, state: BlockStateId) { let b = self.b; let output = self.comparator_calculate_output(pos, state); - let old = self.ticks.comparator_outputs.insert(pos, output).unwrap_or(0); + let old = self + .ticks + .comparator_outputs + .insert(pos, output) + .unwrap_or(0); if old != output || b.table.text(state, b.props.mode) == "compare" { let should = self.diode_should_turn_on(pos, state); let on = b.table.bool(state, b.props.powered); @@ -542,7 +631,12 @@ impl Sim<'_, L> { } /// `getAnalogOutputSignal` for state-only sources; others ask the caller. - pub(crate) fn analog_output(&self, state: BlockStateId, pos: BlockPos, direction: Direction) -> i32 { + pub(crate) fn analog_output( + &self, + state: BlockStateId, + pos: BlockPos, + direction: Direction, + ) -> i32 { let b = self.b; let p = b.props; match b.data(state).class { @@ -571,7 +665,10 @@ impl Sim<'_, L> { } Class::CopperGolemStatue => { let pose = b.table.text(state, p.copper_golem_pose); - ["standing", "sitting", "running", "star"].iter().position(|p| *p == pose).map_or(1, |i| i as i32 + 1) + ["standing", "sitting", "running", "star"] + .iter() + .position(|p| *p == pose) + .map_or(1, |i| i as i32 + 1) } _ => self.level.block_entity_analog_signal(pos, state, direction), } @@ -606,13 +703,24 @@ impl Sim<'_, L> { let time = self.level.game_time(); self.ticks.torch_toggles.push((pos, time)); } - self.ticks.torch_toggles.iter().filter(|(p, _)| *p == pos).take(8).count() >= 8 + self.ticks + .torch_toggles + .iter() + .filter(|(p, _)| *p == pos) + .take(8) + .count() + >= 8 } pub(crate) fn torch_tick(&mut self, pos: BlockPos, state: BlockStateId) { let b = self.b; let signal = self.torch_has_neighbor_signal(pos, state); let time = self.level.game_time(); - while self.ticks.torch_toggles.first().is_some_and(|(_, when)| time - when > 60) { + while self + .ticks + .torch_toggles + .first() + .is_some_and(|(_, when)| time - when > 60) + { self.ticks.torch_toggles.remove(0); } if b.table.bool(state, b.props.lit) { @@ -681,13 +789,25 @@ impl Sim<'_, L> { use horizon_core::geometry::{Aabb, Vec3}; let b = self.b; let area = Aabb::new( - Vec3::new(f64::from(pos.x) + 0.0625, f64::from(pos.y), f64::from(pos.z) + 0.0625), - Vec3::new(f64::from(pos.x) + 0.9375, f64::from(pos.y) + 0.25, f64::from(pos.z) + 0.9375), + Vec3::new( + f64::from(pos.x) + 0.0625, + f64::from(pos.y), + f64::from(pos.z) + 0.0625, + ), + Vec3::new( + f64::from(pos.x) + 0.9375, + f64::from(pos.y) + 0.25, + f64::from(pos.z) + 0.9375, + ), ); let data = b.data(state); if data.is(Class::WeightedPressurePlate) { let max = data.max_weight.max(1); - let count = (self.level.count_entities(area, super::EntityQuery::Everything) as i32).min(max); + let count = (self + .level + .count_entities(area, super::EntityQuery::Everything) + as i32) + .min(max); if count > 0 { (count.min(max) as f32 / max as f32 * 15.0).ceil() as i32 } else { @@ -699,11 +819,20 @@ impl Sim<'_, L> { } else { super::EntityQuery::Everything }; - if self.level.count_entities(area, query) > 0 { 15 } else { 0 } + if self.level.count_entities(area, query) > 0 { + 15 + } else { + 0 + } } } /// `BasePressurePlateBlock.checkPressed`. - pub(crate) fn plate_check_pressed(&mut self, pos: BlockPos, state: BlockStateId, old_signal: i32) { + pub(crate) fn plate_check_pressed( + &mut self, + pos: BlockPos, + state: BlockStateId, + old_signal: i32, + ) { let b = self.b; let signal = self.plate_signal_strength(pos, state); let was = old_signal > 0; @@ -728,7 +857,11 @@ impl Sim<'_, L> { } } if is { - let delay = if b.instance_of(state, Class::WeightedPressurePlate) { 10 } else { 20 }; + let delay = if b.instance_of(state, Class::WeightedPressurePlate) { + 10 + } else { + 20 + }; self.schedule_tick(pos, block, delay); } } @@ -770,38 +903,78 @@ impl Sim<'_, L> { volume: 0.3, pitch: if powered { 0.6 } else { 0.5 }, }); - self.game_event(pos, if powered { "minecraft:block_activate" } else { "minecraft:block_deactivate" }); + self.game_event( + pos, + if powered { + "minecraft:block_activate" + } else { + "minecraft:block_deactivate" + }, + ); } // ---- consumers ---- - pub(crate) fn door_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId, changed: BlockId) { + pub(crate) fn door_neighbor_changed( + &mut self, + pos: BlockPos, + state: BlockStateId, + changed: BlockId, + ) { let b = self.b; let p = b.props; - let other = if b.table.text(state, p.half) == "lower" { Direction::Up } else { Direction::Down }; + let other = if b.table.text(state, p.half) == "lower" { + Direction::Up + } else { + Direction::Down + }; let signal = self.has_neighbor_signal(pos) || self.has_neighbor_signal(rel(pos, other)); if b.block(state) != changed && signal != b.table.bool(state, p.powered) { if signal != b.table.bool(state, p.open) { self.door_sound(pos, state, signal); - self.game_event(pos, if signal { "minecraft:block_open" } else { "minecraft:block_close" }); + self.game_event( + pos, + if signal { + "minecraft:block_open" + } else { + "minecraft:block_close" + }, + ); } - let next = b.table.set_bool(b.table.set_bool(state, p.powered, signal), p.open, signal); + let next = b + .table + .set_bool(b.table.set_bool(state, p.powered, signal), p.open, signal); self.set_block(pos, next, 2); } } pub(crate) fn door_sound(&mut self, pos: BlockPos, state: BlockStateId, open: bool) { if let Some(set) = self.b.data(state).set_type.clone() { let pitch = self.random().next_float() * 0.1 + 0.9; - let sound = if open { set.door_open.clone() } else { set.door_close.clone() }; + let sound = if open { + set.door_open.clone() + } else { + set.door_close.clone() + }; self.sound(pos, &sound, 1.0, pitch); } } pub(crate) fn trapdoor_sound(&mut self, pos: BlockPos, state: BlockStateId, open: bool) { if let Some(set) = self.b.data(state).set_type.clone() { let pitch = self.random().next_float() * 0.1 + 0.9; - let sound = if open { set.trapdoor_open.clone() } else { set.trapdoor_close.clone() }; + let sound = if open { + set.trapdoor_open.clone() + } else { + set.trapdoor_close.clone() + }; self.sound(pos, &sound, 1.0, pitch); - self.game_event(pos, if open { "minecraft:block_open" } else { "minecraft:block_close" }); + self.game_event( + pos, + if open { + "minecraft:block_open" + } else { + "minecraft:block_close" + }, + ); } } pub(crate) fn trapdoor_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId) { @@ -825,16 +998,29 @@ impl Sim<'_, L> { let p = b.props; let power = self.has_neighbor_signal(pos); if b.table.bool(state, p.powered) != power { - let next = b.table.set_bool(b.table.set_bool(state, p.powered, power), p.open, power); + let next = b + .table + .set_bool(b.table.set_bool(state, p.powered, power), p.open, power); self.set_block(pos, next, 2); if b.table.bool(state, p.open) != power { let data = b.data(state); - let sound = if power { data.gate_open.clone() } else { data.gate_close.clone() }; + let sound = if power { + data.gate_open.clone() + } else { + data.gate_close.clone() + }; let pitch = self.random().next_float() * 0.1 + 0.9; if let Some(sound) = sound { self.sound(pos, &sound, 1.0, pitch); } - self.game_event(pos, if power { "minecraft:block_open" } else { "minecraft:block_close" }); + self.game_event( + pos, + if power { + "minecraft:block_open" + } else { + "minecraft:block_close" + }, + ); } } } @@ -883,10 +1069,17 @@ impl Sim<'_, L> { pub(crate) fn note_play(&mut self, pos: BlockPos, state: BlockStateId) { let b = self.b; let instrument = b.table.text(state, b.props.instrument).to_owned(); - let mob_head = super::data::INSTRUMENTS.iter().position(|n| *n == instrument).is_some_and(|i| super::data::instrument_works_above(i as u8)); + let mob_head = super::data::INSTRUMENTS + .iter() + .position(|n| *n == instrument) + .is_some_and(|i| super::data::instrument_works_above(i as u8)); if mob_head || b.is_air(self.above_state(pos)) { let note = b.table.int(state, b.props.note); - let pitch = if mob_head { 1.0 } else { 2f64.powf(f64::from(note - 12) / 12.0) as f32 }; + let pitch = if mob_head { + 1.0 + } else { + 2f64.powf(f64::from(note - 12) / 12.0) as f32 + }; let sound = match instrument.as_str() { "custom_head" => "minecraft:ui.button.click".to_owned(), "dragon" => "minecraft:block.note_block.imitate.ender_dragon".to_owned(), @@ -968,7 +1161,11 @@ impl Sim<'_, L> { self.schedule_tick(pos, b.block(state), 4); self.set_block(pos, b.table.set_bool(state, b.props.triggered, true), 2); } else if !trigger && triggered { - let next = b.table.set_bool(b.table.set_bool(state, b.props.triggered, false), b.props.crafting, false); + let next = b.table.set_bool( + b.table.set_bool(state, b.props.triggered, false), + b.props.crafting, + false, + ); self.set_block(pos, next, 2); } } @@ -979,7 +1176,9 @@ impl Sim<'_, L> { fn java_hash_set_order(positions: &mut Vec) { fn hash(pos: BlockPos) -> i32 { // Vec3i.hashCode: (y + z * 31) * 31 + x - (pos.y.wrapping_add(pos.z.wrapping_mul(31))).wrapping_mul(31).wrapping_add(pos.x) + (pos.y.wrapping_add(pos.z.wrapping_mul(31))) + .wrapping_mul(31) + .wrapping_add(pos.x) } let mut unique: Vec = Vec::new(); for pos in positions.iter() { @@ -992,7 +1191,11 @@ fn java_hash_set_order(positions: &mut Vec) { let h = hash(pos); ((h ^ ((h as u32) >> 16) as i32) & (buckets - 1)) as usize }; - let mut ordered: Vec<(usize, usize, BlockPos)> = unique.iter().enumerate().map(|(i, p)| (bucket(*p), i, *p)).collect(); + let mut ordered: Vec<(usize, usize, BlockPos)> = unique + .iter() + .enumerate() + .map(|(i, p)| (bucket(*p), i, *p)) + .collect(); ordered.sort_by_key(|(b, i, _)| (*b, *i)); *positions = ordered.into_iter().map(|(_, _, p)| p).collect(); } diff --git a/crates/horizon-world/src/level/shapes.rs b/crates/horizon-world/src/level/shapes.rs index 7acbff205..6b9399346 100644 --- a/crates/horizon-world/src/level/shapes.rs +++ b/crates/horizon-world/src/level/shapes.rs @@ -47,7 +47,15 @@ impl Sim<'_, L> { let chain_len = self.b.data(state).chain.len(); for index in depth..chain_len { let class = self.b.data(state).chain[index]; - if let Some(result) = self.update_shape_class(class, index, state, pos, direction, neighbour_pos, neighbour) { + if let Some(result) = self.update_shape_class( + class, + index, + state, + pos, + direction, + neighbour_pos, + neighbour, + ) { return result; } } @@ -80,13 +88,19 @@ impl Sim<'_, L> { // `dir == X && !canSurvive ? AIR : super`. macro_rules! survive_or_air { ($cond:expr) => {{ - if $cond && !self.can_survive(state, pos) { air } else { sup!() } + if $cond && !self.can_survive(state, pos) { + air + } else { + sup!() + } }}; } Some(match class { Class::AbstractBed => { if dir == self.bed_neighbour_direction(state) { - if b.is_block(nstate, block) && table.text(nstate, p.part) != table.text(state, p.part) { + if b.is_block(nstate, block) + && table.text(nstate, p.part) != table.text(state, p.part) + { table.set_bool(state, p.occupied, table.bool(nstate, p.occupied)) } else { air @@ -102,7 +116,12 @@ impl Sim<'_, L> { survive_or_air!(dir == b.facing(state).opposite()) } Class::AttachedStem => { - if !b.data(state).link.is_some_and(|fruit| b.is_block(nstate, fruit)) && dir == b.facing(state) { + if !b + .data(state) + .link + .is_some_and(|fruit| b.is_block(nstate, fruit)) + && dir == b.facing(state) + { if let Some(stem) = b.data(state).link2 { return Some(table.set_int(b.default_of(stem), p.age, 7)); } @@ -122,7 +141,10 @@ impl Sim<'_, L> { if !self.can_survive(state, pos) { self.schedule_tick(pos, block, 1); } - if dir == Direction::Up && b.is_block(nstate, n.bamboo) && table.int(nstate, p.age) > table.int(state, p.age) { + if dir == Direction::Up + && b.is_block(nstate, n.bamboo) + && table.int(nstate, p.age) > table.int(state, p.age) + { table.cycle(state, p.age) } else { sup!() @@ -165,13 +187,18 @@ impl Sim<'_, L> { } Class::BaseCoralWallFan => { self.waterlogged_tick(state, pos); - if dir.opposite() == b.facing(state) && !self.can_survive(state, pos) { air } else { state } + if dir.opposite() == b.facing(state) && !self.can_survive(state, pos) { + air + } else { + state + } } Class::Beehive => sup!(), Class::Bell => { let attachment = table.text(state, p.attachment); let connected = self.bell_connected_direction(state).opposite(); - if connected == dir && !self.can_survive(state, pos) && attachment != "double_wall" { + if connected == dir && !self.can_survive(state, pos) && attachment != "double_wall" + { return Some(air); } if axis_of(dir) == axis_of(b.facing(state)) { @@ -179,7 +206,10 @@ impl Sim<'_, L> { let single = table.set_text(state, p.attachment, "single_wall"); return Some(table.set_dir(single, p.facing, dir.opposite())); } - if attachment == "single_wall" && connected.opposite() == dir && b.is_face_sturdy(nstate, b.facing(state)) { + if attachment == "single_wall" + && connected.opposite() == dir + && b.is_face_sturdy(nstate, b.facing(state)) + { return Some(table.set_text(state, p.attachment, "double_wall")); } } @@ -211,7 +241,9 @@ impl Sim<'_, L> { self.schedule_water_tick(pos); if !self.can_survive(state, pos) || dir == Direction::Down - || (dir == Direction::Up && !b.is_block(nstate, block) && self.bubble_column_can_occupy(nstate)) + || (dir == Direction::Up + && !b.is_block(nstate, block) + && self.bubble_column_can_occupy(nstate)) { self.schedule_tick(pos, block, 5); } @@ -227,12 +259,18 @@ impl Sim<'_, L> { self.waterlogged_tick(state, pos); if dir == Direction::Down { let hay = table.block_by_name("minecraft:hay_block"); - table.set_bool(state, p.signal_fire, hay.is_some_and(|hay| b.is_block(nstate, hay))) + table.set_bool( + state, + p.signal_fire, + hay.is_some_and(|hay| b.is_block(nstate, hay)), + ) } else { sup!() } } - Class::Carpet | Class::SnowLayer | Class::Vegetation | Class::Frogspawn => survive_or_air!(true), + Class::Carpet | Class::SnowLayer | Class::Vegetation | Class::Frogspawn => { + survive_or_air!(true) + } Class::SeaPickle => { if !self.can_survive(state, pos) { return Some(air); @@ -240,7 +278,9 @@ impl Sim<'_, L> { self.waterlogged_tick(state, pos); sup!() } - Class::CeilingHangingSign | Class::SporeBlossom => survive_or_air!(dir == Direction::Up), + Class::CeilingHangingSign | Class::SporeBlossom => { + survive_or_air!(dir == Direction::Up) + } Class::Chest => { self.waterlogged_tick(state, pos); if self.chest_can_connect_to(state, nstate) && is_horizontal(dir) { @@ -250,7 +290,11 @@ impl Sim<'_, L> { && b.facing(state) == b.facing(nstate) && self.chest_connected_direction(nstate) == dir.opposite() { - let opposite = if neighbour_type == "left" { "right" } else { "left" }; + let opposite = if neighbour_type == "left" { + "right" + } else { + "left" + }; return Some(table.set_text(state, p.kind, opposite)); } } else if self.chest_connected_direction(state) == dir { @@ -287,11 +331,17 @@ impl Sim<'_, L> { } Class::Cocoa => survive_or_air!(dir == b.facing(state)), Class::Comparator => { - if dir == Direction::Down && !b.is_face_sturdy_rigid(nstate, Direction::Up) { air } else { sup!() } + if dir == Direction::Down && !b.is_face_sturdy_rigid(nstate, Direction::Up) { + air + } else { + sup!() + } } Class::ConcretePowder => { if self.concrete_touches_liquid(pos) { - b.data(state).link.map_or(state, |concrete| b.default_of(concrete)) + b.data(state) + .link + .map_or(state, |concrete| b.default_of(concrete)) } else { sup!() } @@ -326,8 +376,14 @@ impl Sim<'_, L> { Class::Door => { let lower = table.text(state, p.half) == "lower"; if dir.normal()[1] == 0 || lower != (dir == Direction::Up) { - if lower && dir == Direction::Down && !self.can_survive(state, pos) { air } else { sup!() } - } else if b.instance_of(nstate, Class::Door) && table.text(nstate, p.half) != table.text(state, p.half) { + if lower && dir == Direction::Down && !self.can_survive(state, pos) { + air + } else { + sup!() + } + } else if b.instance_of(nstate, Class::Door) + && table.text(nstate, p.half) != table.text(state, p.half) + { table.set_text(nstate, p.half, table.text(state, p.half)) } else { air @@ -340,7 +396,11 @@ impl Sim<'_, L> { || lower != (dir == Direction::Up) || (b.is_block(nstate, block) && table.text(nstate, p.half) != half) { - if lower && dir == Direction::Down && !self.can_survive(state, pos) { air } else { sup!() } + if lower && dir == Direction::Down && !self.can_survive(state, pos) { + air + } else { + sup!() + } } else { air } @@ -357,14 +417,22 @@ impl Sim<'_, L> { Class::FaceAttachedHorizontalDirectional | Class::Lantern => { if class == Class::Lantern { self.waterlogged_tick(state, pos); - let connected = if table.bool(state, p.hanging) { Direction::Down } else { Direction::Up }; + let connected = if table.bool(state, p.hanging) { + Direction::Down + } else { + Direction::Up + }; survive_or_air!(connected.opposite() == dir) } else { survive_or_air!(self.face_attached_connected(state).opposite() == dir) } } Class::FallingBlock => { - let delay = if class_is(b, block, Class::DragonEgg) { 5 } else { 2 }; + let delay = if class_is(b, block, Class::DragonEgg) { + 5 + } else { + 2 + }; self.schedule_tick(pos, block, delay); sup!() } @@ -378,7 +446,11 @@ impl Sim<'_, L> { self.waterlogged_tick(state, pos); if is_horizontal(dir) { let sturdy = b.is_face_sturdy(nstate, dir.opposite()); - table.set_bool(state, self.direction_prop(dir), self.fence_connects_to(state, nstate, sturdy, dir.opposite())) + table.set_bool( + state, + self.direction_prop(dir), + self.fence_connects_to(state, nstate, sturdy, dir.opposite()), + ) } else { sup!() } @@ -387,7 +459,11 @@ impl Sim<'_, L> { self.waterlogged_tick(state, pos); if is_horizontal(dir) { let sturdy = b.is_face_sturdy(nstate, dir.opposite()); - table.set_bool(state, self.direction_prop(dir), self.bars_attach_to(nstate, sturdy)) + table.set_bool( + state, + self.direction_prop(dir), + self.bars_attach_to(nstate, sturdy), + ) } else { sup!() } @@ -410,7 +486,11 @@ impl Sim<'_, L> { } } Class::SoulFire => { - if self.can_survive(state, pos) { b.default_of(block) } else { air } + if self.can_survive(state, pos) { + b.default_of(block) + } else { + air + } } Class::GrowingPlantBody => { let growth = b.data(state).growth_direction; @@ -438,7 +518,9 @@ impl Sim<'_, L> { let to_body = |sim: &Self| { let body_state = b.default_of(body); if class_is(b, block, Class::CaveVines) { - sim.b.table.set_bool(body_state, p.berries, table.bool(state, p.berries)) + sim.b + .table + .set_bool(body_state, p.berries, table.bool(state, p.berries)) } else { body_state } @@ -464,7 +546,9 @@ impl Sim<'_, L> { } Class::HangingMoss => { let above_state = self.above_state(pos); - if !(b.multiface_can_attach(above_state, Direction::Up) || b.is_block(above_state, block)) { + if !(b.multiface_can_attach(above_state, Direction::Up) + || b.is_block(above_state, block)) + { self.schedule_tick(pos, block, 1); } table.set_bool(state, p.tip, !b.is_block(self.below_state(pos), block)) @@ -477,7 +561,11 @@ impl Sim<'_, L> { sup!() } Class::HugeMushroom => { - if b.is_block(nstate, block) { table.set_bool(state, self.direction_prop(dir), false) } else { sup!() } + if b.is_block(nstate, block) { + table.set_bool(state, self.direction_prop(dir), false) + } else { + sup!() + } } Class::Ladder => { if dir.opposite() == b.facing(state) && !self.can_survive(state, pos) { @@ -514,22 +602,42 @@ impl Sim<'_, L> { return Some(air); } let updated = self.mossy_carpet_updated_state(state, pos, false); - if self.mossy_carpet_has_faces(updated) { updated } else { air } + if self.mossy_carpet_has_faces(updated) { + updated + } else { + air + } } Class::Multiface => { self.waterlogged_tick(state, pos); - if !Direction::ALL.into_iter().any(|d| self.multiface_has_face(state, d)) { + if !Direction::ALL + .into_iter() + .any(|d| self.multiface_has_face(state, d)) + { air - } else if self.multiface_has_face(state, dir) && !b.multiface_can_attach(nstate, dir) { + } else if self.multiface_has_face(state, dir) + && !b.multiface_can_attach(nstate, dir) + { let removed = table.set_bool(state, self.direction_prop(dir), false); - if Direction::ALL.into_iter().any(|d| self.multiface_has_face(removed, d)) { removed } else { air } + if Direction::ALL + .into_iter() + .any(|d| self.multiface_has_face(removed, d)) + { + removed + } else { + air + } } else { state } } Class::PistonHead => survive_or_air!(dir.opposite() == b.facing(state)), Class::Note => { - if dir.normal()[1] != 0 { self.note_block_instrument(pos, state) } else { sup!() } + if dir.normal()[1] != 0 { + self.note_block_instrument(pos, state) + } else { + sup!() + } } Class::Observer => { if b.facing(state) == dir && !table.bool(state, p.powered) { @@ -537,7 +645,11 @@ impl Sim<'_, L> { } sup!() } - Class::RedstoneWallTorch | Class::WallTorch | Class::TripWireHook | Class::WallBanner | Class::WallSign => { + Class::RedstoneWallTorch + | Class::WallTorch + | Class::TripWireHook + | Class::WallBanner + | Class::WallSign => { let attached = dir.opposite() == b.facing(state); let fails = attached && !self.can_survive(state, pos); match class { @@ -581,14 +693,20 @@ impl Sim<'_, L> { result } Class::Snowy => { - if dir == Direction::Up { table.set_bool(state, p.snowy, b.in_set(nstate, &t.snow)) } else { sup!() } + if dir == Direction::Up { + table.set_bool(state, p.snowy, b.in_set(nstate, &t.snow)) + } else { + sup!() + } } Class::Speleothem => { self.waterlogged_tick(state, pos); if !matches!(dir, Direction::Up | Direction::Down) { return Some(state); } - let tip = table.dir(state, p.vertical_direction).unwrap_or(Direction::Up); + let tip = table + .dir(state, p.vertical_direction) + .unwrap_or(Direction::Up); if tip == Direction::Down && self.ticks.has_block_tick(pos, block) { return Some(state); } @@ -623,7 +741,11 @@ impl Sim<'_, L> { sup!() } else { let updated = self.vine_updated_state(state, pos); - if self.vine_count_faces(updated) == 0 { air } else { updated } + if self.vine_count_faces(updated) == 0 { + air + } else { + updated + } } } Class::Wall => { @@ -631,15 +753,30 @@ impl Sim<'_, L> { match dir { Direction::Down => sup!(), Direction::Up => { - let sides = [Direction::North, Direction::East, Direction::South, Direction::West] - .map(|d| table.text(state, self.direction_prop(d)) != "none"); + let sides = [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, + ] + .map(|d| table.text(state, self.direction_prop(d)) != "none"); self.wall_shape(state, npos, nstate, sides) } _ => { let opposite = dir.opposite(); - let sides = [Direction::North, Direction::East, Direction::South, Direction::West].map(|d| { + let sides = [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, + ] + .map(|d| { if d == dir { - self.wall_connects_to(nstate, b.is_face_sturdy(nstate, opposite), opposite) + self.wall_connects_to( + nstate, + b.is_face_sturdy(nstate, opposite), + opposite, + ) } else { table.text(state, self.direction_prop(d)) != "none" } @@ -689,12 +826,18 @@ impl Sim<'_, L> { fn bed_neighbour_direction(&self, state: BlockStateId) -> Direction { let facing = self.b.facing(state); - if self.b.table.text(state, self.b.props.part) == "foot" { facing } else { facing.opposite() } + if self.b.table.text(state, self.b.props.part) == "foot" { + facing + } else { + facing.opposite() + } } pub(crate) fn chest_can_connect_to(&self, state: BlockStateId, other: BlockStateId) -> bool { let b = self.b; if b.instance_of(state, Class::CopperChest) { - b.tag("minecraft:copper_chests").is_some_and(|tag| b.in_set(other, tag)) && b.table.has(other, b.props.kind) + b.tag("minecraft:copper_chests") + .is_some_and(|tag| b.in_set(other, tag)) + && b.table.has(other, b.props.kind) } else { b.block(state) == b.block(other) } @@ -702,34 +845,68 @@ impl Sim<'_, L> { /// `ChestBlock.getConnectedDirection`. pub(crate) fn chest_connected_direction(&self, state: BlockStateId) -> Direction { let facing = self.b.facing(state); - if self.b.table.text(state, self.b.props.kind) == "left" { clockwise(facing) } else { counter_clockwise(facing) } + if self.b.table.text(state, self.b.props.kind) == "left" { + clockwise(facing) + } else { + counter_clockwise(facing) + } } /// `FenceBlock.connectsTo`. - pub(crate) fn fence_connects_to(&self, fence: BlockStateId, state: BlockStateId, face_solid: bool, direction: Direction) -> bool { + pub(crate) fn fence_connects_to( + &self, + fence: BlockStateId, + state: BlockStateId, + face_solid: bool, + direction: Direction, + ) -> bool { let b = self.b; let t = &b.tags; - let same_fence = b.in_set(state, &t.fences) && b.in_set(state, &t.wooden_fences) == b.in_set(fence, &t.wooden_fences); - let gate = b.instance_of(state, Class::FenceGate) && axis_of(b.facing(state)) == axis_of(clockwise(direction)); + let same_fence = b.in_set(state, &t.fences) + && b.in_set(state, &t.wooden_fences) == b.in_set(fence, &t.wooden_fences); + let gate = b.instance_of(state, Class::FenceGate) + && axis_of(b.facing(state)) == axis_of(clockwise(direction)); (!b.is_exception_for_connection(state) && face_solid) || same_fence || gate } /// `IronBarsBlock.attachsTo`. pub(crate) fn bars_attach_to(&self, state: BlockStateId, face_solid: bool) -> bool { let b = self.b; - (!b.is_exception_for_connection(state) && face_solid) || b.instance_of(state, Class::IronBars) || b.in_set(state, &b.tags.walls) + (!b.is_exception_for_connection(state) && face_solid) + || b.instance_of(state, Class::IronBars) + || b.in_set(state, &b.tags.walls) } /// `WallBlock.connectsTo`. - pub(crate) fn wall_connects_to(&self, state: BlockStateId, face_solid: bool, direction: Direction) -> bool { + pub(crate) fn wall_connects_to( + &self, + state: BlockStateId, + face_solid: bool, + direction: Direction, + ) -> bool { let b = self.b; - let gate = b.instance_of(state, Class::FenceGate) && axis_of(b.facing(state)) == axis_of(clockwise(direction)); - b.in_set(state, &b.tags.walls) || (!b.is_exception_for_connection(state) && face_solid) || b.instance_of(state, Class::IronBars) || gate + let gate = b.instance_of(state, Class::FenceGate) + && axis_of(b.facing(state)) == axis_of(clockwise(direction)); + b.in_set(state, &b.tags.walls) + || (!b.is_exception_for_connection(state) && face_solid) + || b.instance_of(state, Class::IronBars) + || gate } /// `WallBlock.updateShape(level, state, topPos, topNeighbour, n, e, s, w)`. - pub(crate) fn wall_shape(&self, state: BlockStateId, top_pos: BlockPos, top: BlockStateId, sides: [bool; 4]) -> BlockStateId { + pub(crate) fn wall_shape( + &self, + state: BlockStateId, + top_pos: BlockPos, + top: BlockStateId, + sides: [bool; 4], + ) -> BlockStateId { let b = self.b; let table = &b.table; let cover = self.shape_info_at(top, top_pos).wall_cover; let mut result = state; - let directions = [Direction::North, Direction::East, Direction::South, Direction::West]; + let directions = [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, + ]; for (i, direction) in directions.into_iter().enumerate() { let value = if !sides[i] { "none" @@ -742,11 +919,21 @@ impl Sim<'_, L> { } // shouldRaisePost let side = |d: Direction| table.text(result, self.direction_prop(d)).to_owned(); - let (north, south, east, west) = (side(Direction::North), side(Direction::South), side(Direction::East), side(Direction::West)); + let (north, south, east, west) = ( + side(Direction::North), + side(Direction::South), + side(Direction::East), + side(Direction::West), + ); let raise = if b.instance_of(top, Class::Wall) && table.bool(top, b.props.up) { true } else { - let (nn, sn, en, wn) = (north == "none", south == "none", east == "none", west == "none"); + let (nn, sn, en, wn) = ( + north == "none", + south == "none", + east == "none", + west == "none", + ); if (nn && sn && wn && en) || nn != sn || wn != en { true } else if (north == "tall" && south == "tall") || (east == "tall" && west == "tall") { @@ -767,20 +954,37 @@ impl Sim<'_, L> { let behind = self.rel_state(pos, facing); if b.instance_of(behind, Class::Stair) && table.text(behind, p.half) == half { let behind_facing = b.facing(behind); - if axis_of(behind_facing) != axis_of(facing) && self.stairs_can_take_shape(state, pos, behind_facing.opposite()) { - return if behind_facing == counter_clockwise(facing) { "outer_left" } else { "outer_right" }; + if axis_of(behind_facing) != axis_of(facing) + && self.stairs_can_take_shape(state, pos, behind_facing.opposite()) + { + return if behind_facing == counter_clockwise(facing) { + "outer_left" + } else { + "outer_right" + }; } } let front = self.rel_state(pos, facing.opposite()); if b.instance_of(front, Class::Stair) && table.text(front, p.half) == half { let front_facing = b.facing(front); - if axis_of(front_facing) != axis_of(facing) && self.stairs_can_take_shape(state, pos, front_facing) { - return if front_facing == counter_clockwise(facing) { "inner_left" } else { "inner_right" }; + if axis_of(front_facing) != axis_of(facing) + && self.stairs_can_take_shape(state, pos, front_facing) + { + return if front_facing == counter_clockwise(facing) { + "inner_left" + } else { + "inner_right" + }; } } "straight" } - fn stairs_can_take_shape(&self, state: BlockStateId, pos: BlockPos, direction: Direction) -> bool { + fn stairs_can_take_shape( + &self, + state: BlockStateId, + pos: BlockPos, + direction: Direction, + ) -> bool { let b = self.b; let neighbour = self.rel_state(pos, direction); !b.instance_of(neighbour, Class::Stair) @@ -788,7 +992,11 @@ impl Sim<'_, L> { || b.table.text(neighbour, b.props.half) != b.table.text(state, b.props.half) } /// `TripWireBlock.shouldConnectTo`. - pub(crate) fn tripwire_should_connect_to(&self, state: BlockStateId, direction: Direction) -> bool { + pub(crate) fn tripwire_should_connect_to( + &self, + state: BlockStateId, + direction: Direction, + ) -> bool { let b = self.b; if b.is_block(state, b.named.tripwire_hook) { b.facing(state) == direction.opposite() @@ -825,7 +1033,9 @@ impl Sim<'_, L> { false } pub(crate) fn coral_scan_for_water(&self, pos: BlockPos) -> bool { - Direction::ALL.into_iter().any(|d| self.b.is_water_fluid(self.fluid_at(rel(pos, d)).kind())) + Direction::ALL + .into_iter() + .any(|d| self.b.is_water_fluid(self.fluid_at(rel(pos, d)).kind())) } /// `BaseCoralPlantTypeBlock.scanForWater(state, level, pos)`. pub(crate) fn coral_plant_scan_for_water(&self, state: BlockStateId, pos: BlockPos) -> bool { @@ -854,11 +1064,23 @@ impl Sim<'_, L> { } pub(crate) fn should_bubble_column_occupy(&self, state: BlockStateId) -> bool { let fluid = self.b.fluid(state); - self.b.fluid_in(fluid.kind(), self.b.fluid_tags.bubble_column_can_occupy) && fluid.is_source() && fluid.is_full() + self.b + .fluid_in(fluid.kind(), self.b.fluid_tags.bubble_column_can_occupy) + && fluid.is_source() + && fluid.is_full() } - pub(crate) fn try_schedule_bubble_column(&mut self, pos: BlockPos, below_state: BlockStateId, block: BlockId) { + pub(crate) fn try_schedule_bubble_column( + &mut self, + pos: BlockPos, + below_state: BlockStateId, + block: BlockId, + ) { let t = &self.b.tags; - if self.b.in_set(below_state, &t.enables_bubble_column_drag_down) || self.b.in_set(below_state, &t.enables_bubble_column_push_up) { + if self + .b + .in_set(below_state, &t.enables_bubble_column_drag_down) + || self.b.in_set(below_state, &t.enables_bubble_column_push_up) + { self.schedule_tick(pos, block, 20); } } @@ -870,29 +1092,52 @@ impl Sim<'_, L> { above } else { let below = b.facts(self.below_state(pos)).instrument; - if super::data::instrument_works_above(below) { 0 } else { below } + if super::data::instrument_works_above(below) { + 0 + } else { + below + } }; - b.table.set_text(state, b.props.instrument, super::data::INSTRUMENTS[name as usize]) + b.table.set_text( + state, + b.props.instrument, + super::data::INSTRUMENTS[name as usize], + ) } /// `SpeleothemBlock.calculateSpeleothemThickness`. - pub(crate) fn speleothem_thickness(&self, pos: BlockPos, tip: Direction, merge: bool) -> &'static str { + pub(crate) fn speleothem_thickness( + &self, + pos: BlockPos, + tip: Direction, + merge: bool, + ) -> &'static str { let b = self.b; let p = b.props; let base = tip.opposite(); let is_with = |state: BlockStateId, direction: Direction| { - b.tag("minecraft:speleothems").is_some_and(|tag| b.in_set(state, tag)) && b.table.dir(state, p.vertical_direction) == Some(direction) + b.tag("minecraft:speleothems") + .is_some_and(|tag| b.in_set(state, tag)) + && b.table.dir(state, p.vertical_direction) == Some(direction) }; let front = self.rel_state(pos, tip); let block = b.block(self.state(pos)); if is_with(front, base) && b.is_block(front, block) { - if !merge && b.table.text(front, p.thickness) != "tip_merge" { "tip" } else { "tip_merge" } + if !merge && b.table.text(front, p.thickness) != "tip_merge" { + "tip" + } else { + "tip_merge" + } } else if !is_with(front, tip) { "tip" } else { let front_thickness = b.table.text(front, p.thickness); if front_thickness != "tip" && front_thickness != "tip_merge" { let behind = self.rel_state(pos, base); - if !is_with(behind, tip) { "base" } else { "middle" } + if !is_with(behind, tip) { + "base" + } else { + "middle" + } } else { "frustum" } @@ -902,7 +1147,11 @@ impl Sim<'_, L> { pub(crate) fn fire_state_with_age(&self, pos: BlockPos, age: i32) -> BlockStateId { let b = self.b; let placement = self.fire_state_for(pos); - if b.is_block(placement, b.named.fire) { b.table.set_int(placement, b.props.age, age) } else { placement } + if b.is_block(placement, b.named.fire) { + b.table.set_int(placement, b.props.age, age) + } else { + placement + } } /// `BaseFireBlock.getState(level, pos)`. pub(crate) fn fire_state_for(&self, pos: BlockPos) -> BlockStateId { @@ -920,7 +1169,9 @@ impl Sim<'_, L> { continue; } let burn = self.can_burn(self.rel_state(pos, direction)); - result = b.table.set_bool(result, self.direction_prop(direction), burn); + result = b + .table + .set_bool(result, self.direction_prop(direction), burn); } result } else { @@ -928,7 +1179,12 @@ impl Sim<'_, L> { } } /// `MossyCarpetBlock.getUpdatedState`. - pub(crate) fn mossy_carpet_updated_state(&self, mut state: BlockStateId, pos: BlockPos, create_sides: bool) -> BlockStateId { + pub(crate) fn mossy_carpet_updated_state( + &self, + mut state: BlockStateId, + pos: BlockPos, + create_sides: bool, + ) -> BlockStateId { let b = self.b; let table = &b.table; let block = b.block(state); @@ -936,17 +1192,29 @@ impl Sim<'_, L> { let create_sides = create_sides || base; let mut above_state = None; let mut below_state = None; - for direction in [Direction::North, Direction::East, Direction::South, Direction::West] { + for direction in [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, + ] { let key = self.direction_prop(direction); let supported = b.multiface_can_attach(self.rel_state(pos, direction), direction); let mut side = if supported { - if create_sides { "low" } else { table.text(state, key) } + if create_sides { + "low" + } else { + table.text(state, key) + } } else { "none" }; if side == "low" { let above = *above_state.get_or_insert_with(|| self.above_state(pos)); - if b.is_block(above, block) && table.text(above, key) != "none" && !table.bool(above, b.props.bottom) { + if b.is_block(above, block) + && table.text(above, key) != "none" + && !table.bool(above, b.props.bottom) + { side = "tall"; } if !base { @@ -964,9 +1232,14 @@ impl Sim<'_, L> { pub(crate) fn mossy_carpet_has_faces(&self, state: BlockStateId) -> bool { let b = self.b; table_bool(b, state) - || [Direction::North, Direction::East, Direction::South, Direction::West] - .into_iter() - .any(|d| b.table.text(state, self.direction_prop(d)) != "none") + || [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, + ] + .into_iter() + .any(|d| b.table.text(state, self.direction_prop(d)) != "none") } } diff --git a/crates/horizon-world/src/level/speleothem.rs b/crates/horizon-world/src/level/speleothem.rs index 2bca8f115..60059cfe9 100644 --- a/crates/horizon-world/src/level/speleothem.rs +++ b/crates/horizon-world/src/level/speleothem.rs @@ -11,10 +11,13 @@ use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource impl Sim<'_, L> { fn speleothem_tag(&self, state: BlockStateId) -> bool { - self.b.tag("minecraft:speleothems").is_some_and(|tag| self.b.in_set(state, tag)) + self.b + .tag("minecraft:speleothems") + .is_some_and(|tag| self.b.in_set(state, tag)) } fn speleothem_with(&self, state: BlockStateId, direction: Direction) -> bool { - self.speleothem_tag(state) && self.b.table.dir(state, self.b.props.vertical_direction) == Some(direction) + self.speleothem_tag(state) + && self.b.table.dir(state, self.b.props.vertical_direction) == Some(direction) } fn speleothem_is_tip(&self, state: BlockStateId, include_merged: bool) -> bool { if !self.speleothem_tag(state) { @@ -50,17 +53,29 @@ impl Sim<'_, L> { } None } - fn speleothem_find_tip(&self, state: BlockStateId, pos: BlockPos, max: i32, include_merged: bool) -> Option { + fn speleothem_find_tip( + &self, + state: BlockStateId, + pos: BlockPos, + max: i32, + include_merged: bool, + ) -> Option { if self.speleothem_is_tip(state, include_merged) { return Some(pos); } let b = self.b; - let direction = b.table.dir(state, b.props.vertical_direction).unwrap_or(Direction::Up); + let direction = b + .table + .dir(state, b.props.vertical_direction) + .unwrap_or(Direction::Up); let block = b.block(state); self.find_block_vertical( pos, direction == Direction::Up, - |sim, _, s| sim.b.is_block(s, block) && sim.b.table.dir(s, sim.b.props.vertical_direction) == Some(direction), + |sim, _, s| { + sim.b.is_block(s, block) + && sim.b.table.dir(s, sim.b.props.vertical_direction) == Some(direction) + }, |sim, s| sim.speleothem_is_tip(s, include_merged), max, ) @@ -72,7 +87,8 @@ impl Sim<'_, L> { let value = self.random().next_float(); self.dripstone_transfer_fluid(state, pos, value); } - let start = self.speleothem_with(state, Direction::Down) && !b.is_block(self.above_state(pos), b.block(state)); + let start = self.speleothem_with(state, Direction::Down) + && !b.is_block(self.above_state(pos), b.block(state)); if self.random().next_float() < 0.011_377_778 && start { self.speleothem_grow(state, pos); } @@ -81,7 +97,9 @@ impl Sim<'_, L> { let b = self.b; let block = b.block(state); let data = b.data(state); - let mut can_grow = data.link.is_some_and(|grow_on| b.is_block(self.above_state(pos), grow_on)); + let mut can_grow = data + .link + .is_some_and(|grow_on| b.is_block(self.above_state(pos), grow_on)); if data.is(Class::PointedDripstone) { let fluid = b.fluid(self.state(pos.offset(0, 2, 0))); can_grow &= fluid.kind() == FluidKind::Water; @@ -94,7 +112,8 @@ impl Sim<'_, L> { return; }; let tip = self.state(tip_pos); - if self.is_free_hanging_stalactite(tip) && self.speleothem_can_tip_grow(block, tip, tip_pos) { + if self.is_free_hanging_stalactite(tip) && self.speleothem_can_tip_grow(block, tip, tip_pos) + { if self.random().next_boolean() { self.speleothem_grow_to(block, tip_pos, Direction::Down); } else { @@ -102,11 +121,27 @@ impl Sim<'_, L> { } } } - fn speleothem_unmerged_tip(&self, block: BlockId, state: BlockStateId, direction: Direction) -> bool { - self.speleothem_is_tip(state, false) && self.b.table.dir(state, self.b.props.vertical_direction) == Some(direction) && self.b.is_block(state, block) + fn speleothem_unmerged_tip( + &self, + block: BlockId, + state: BlockStateId, + direction: Direction, + ) -> bool { + self.speleothem_is_tip(state, false) + && self.b.table.dir(state, self.b.props.vertical_direction) == Some(direction) + && self.b.is_block(state, block) } - fn speleothem_can_tip_grow(&self, block: BlockId, tip: BlockStateId, tip_pos: BlockPos) -> bool { - let direction = self.b.table.dir(tip, self.b.props.vertical_direction).unwrap_or(Direction::Up); + fn speleothem_can_tip_grow( + &self, + block: BlockId, + tip: BlockStateId, + tip_pos: BlockPos, + ) -> bool { + let direction = self + .b + .table + .dir(tip, self.b.props.vertical_direction) + .unwrap_or(Direction::Up); let grow = self.rel_state(tip_pos, direction); if self.b.fluid(grow).kind() != FluidKind::Empty { false @@ -114,11 +149,20 @@ impl Sim<'_, L> { self.b.is_air(grow) || self.speleothem_unmerged_tip(block, grow, direction.opposite()) } } - fn speleothem_create(&mut self, block: BlockId, pos: BlockPos, direction: Direction, thickness: &str) { + fn speleothem_create( + &mut self, + block: BlockId, + pos: BlockPos, + direction: Direction, + thickness: &str, + ) { let b = self.b; - let state = b.table.set_dir(b.default_of(block), b.props.vertical_direction, direction); + let state = b + .table + .set_dir(b.default_of(block), b.props.vertical_direction, direction); let state = b.table.set_text(state, b.props.thickness, thickness); - let water = self.fluid_at(pos) == crate::fluid::FluidState::WATER || self.fluid_at(pos).kind() == FluidKind::Water; + let water = self.fluid_at(pos) == crate::fluid::FluidState::WATER + || self.fluid_at(pos).kind() == FluidKind::Water; self.set_block_and_update(pos, b.table.set_bool(state, b.props.waterlogged, water)); } fn speleothem_grow_to(&mut self, block: BlockId, from: BlockPos, direction: Direction) { @@ -126,11 +170,12 @@ impl Sim<'_, L> { let target = rel(from, direction); let existing = self.state(target); if self.speleothem_unmerged_tip(block, existing, direction.opposite()) { - let (stalactite, stalagmite) = if b.table.dir(existing, b.props.vertical_direction) == Some(Direction::Up) { - (above(target), target) - } else { - (target, below(target)) - }; + let (stalactite, stalagmite) = + if b.table.dir(existing, b.props.vertical_direction) == Some(Direction::Up) { + (above(target), target) + } else { + (target, below(target)) + }; self.speleothem_create(block, stalactite, Direction::Down, "tip_merge"); self.speleothem_create(block, stalagmite, Direction::Up, "tip_merge"); } else if b.is_air(existing) || b.is_block(existing, b.named.water) { @@ -146,15 +191,21 @@ impl Sim<'_, L> { if b.fluid(state).kind() != FluidKind::Empty { return; } - if self.speleothem_unmerged_tip(block, state, Direction::Up) && self.speleothem_can_tip_grow(block, state, pos) { + if self.speleothem_unmerged_tip(block, state, Direction::Up) + && self.speleothem_can_tip_grow(block, state, pos) + { self.speleothem_grow_to(block, pos, Direction::Up); return; } - if self.is_valid_speleothem_placement(block, pos, Direction::Up) && !self.is_water_at(below(pos)) { + if self.is_valid_speleothem_placement(block, pos, Direction::Up) + && !self.is_water_at(below(pos)) + { self.speleothem_grow_to(block, below(pos), Direction::Up); return; } - if b.data(b.default_of(block)).is(Class::PointedDripstone) && !self.dripstone_can_drip_through(state) { + if b.data(b.default_of(block)).is(Class::PointedDripstone) + && !self.dripstone_can_drip_through(state) + { return; } } @@ -172,17 +223,27 @@ impl Sim<'_, L> { match b.collision_shape(state) { None => true, Some(shape) => { - let column = horizon_core::geometry::VoxelShape::from_box(horizon_core::geometry::Aabb::new( - horizon_core::geometry::Vec3::new(0.375, 0.0, 0.375), - horizon_core::geometry::Vec3::new(0.625, 1.0, 0.625), - )); - column.is_ok_and(|column| !column.join_is_not_empty(shape, horizon_core::geometry::ShapeOp::AND).unwrap_or(true)) + let column = horizon_core::geometry::VoxelShape::from_box( + horizon_core::geometry::Aabb::new( + horizon_core::geometry::Vec3::new(0.375, 0.0, 0.375), + horizon_core::geometry::Vec3::new(0.625, 1.0, 0.625), + ), + ); + column.is_ok_and(|column| { + !column + .join_is_not_empty(shape, horizon_core::geometry::ShapeOp::AND) + .unwrap_or(true) + }) } } } /// `PointedDripstoneBlock.getFluidAboveStalactite`: (position above the /// root, fluid, state there). - fn dripstone_fluid_above(&self, state: BlockStateId, pos: BlockPos) -> Option<(BlockPos, FluidKind, BlockStateId)> { + fn dripstone_fluid_above( + &self, + state: BlockStateId, + pos: BlockPos, + ) -> Option<(BlockPos, FluidKind, BlockStateId)> { let b = self.b; if !self.speleothem_with(state, Direction::Down) { return None; @@ -192,13 +253,18 @@ impl Sim<'_, L> { let root = self.find_block_vertical( pos, true, - |sim, _, s| sim.b.is_block(s, block) && sim.b.table.dir(s, sim.b.props.vertical_direction) == Some(direction), + |sim, _, s| { + sim.b.is_block(s, block) + && sim.b.table.dir(s, sim.b.props.vertical_direction) == Some(direction) + }, |sim, s| !sim.b.is_block(s, block), 11, )?; let above_pos = above(root); let above_state = self.state(above_pos); - let fluid = if b.is_block(above_state, b.named.mud) && self.level.dimension() != super::Dimension::Nether { + let fluid = if b.is_block(above_state, b.named.mud) + && self.level.dimension() != super::Dimension::Nether + { FluidKind::Water } else { b.fluid(above_state).kind() @@ -210,7 +276,9 @@ impl Sim<'_, L> { if value > 0.175_781_25 { return; } - if !(self.speleothem_with(state, Direction::Down) && !b.is_block(self.above_state(pos), b.block(state))) { + if !(self.speleothem_with(state, Direction::Down) + && !b.is_block(self.above_state(pos), b.block(state))) + { return; } let Some((source_pos, fluid, source_state)) = self.dripstone_fluid_above(state, pos) else { @@ -281,7 +349,11 @@ impl Sim<'_, L> { } let data = b.data(state); if data.is(Class::Cauldron) { - let (next, event) = if fluid == FluidKind::Water { (b.named.water_cauldron, 1047) } else { (b.named.lava_cauldron, 1046) }; + let (next, event) = if fluid == FluidKind::Water { + (b.named.water_cauldron, 1047) + } else { + (b.named.lava_cauldron, 1046) + }; self.set_block_and_update(pos, b.default_of(next)); self.game_event(pos, "minecraft:block_change"); self.level_event(event, pos, 0); diff --git a/crates/horizon-world/src/level/states.rs b/crates/horizon-world/src/level/states.rs index b26bcf805..abe6c08cf 100644 --- a/crates/horizon-world/src/level/states.rs +++ b/crates/horizon-world/src/level/states.rs @@ -108,7 +108,9 @@ impl StateTable { while index < registry.len() { let first = registry.state(BlockStateId(index as u32)).unwrap(); let mut end = index + 1; - while end < registry.len() && registry.state(BlockStateId(end as u32)).unwrap().name == first.name { + while end < registry.len() + && registry.state(BlockStateId(end as u32)).unwrap().name == first.name + { end += 1; } let count = (end - index) as u32; @@ -121,7 +123,11 @@ impl StateTable { // first states with stride steps give each value in order. let mut seen = Vec::<&str>::new(); for offset in 0..count { - let value = registry.state(BlockStateId(index as u32 + offset)).unwrap().properties[*name].as_str(); + let value = registry + .state(BlockStateId(index as u32 + offset)) + .unwrap() + .properties[*name] + .as_str(); if !seen.contains(&value) { seen.push(value); } @@ -131,7 +137,11 @@ impl StateTable { values.push(PropValue::new(value)); } let key = table.key_or_insert(name); - slots.push(Slot { key, stride, values }); + slots.push(Slot { + key, + stride, + values, + }); } if stride != 1 { return Err(invalid("block state count is not a property product")); @@ -143,12 +153,16 @@ impl StateTable { slot.values = (0..len) .map(|i| { PropValue::new( - ®istry.state(BlockStateId(index as u32 + i * slot.stride)).unwrap().properties[name], + ®istry + .state(BlockStateId(index as u32 + i * slot.stride)) + .unwrap() + .properties[name], ) }) .collect(); } - let block = BlockId(u16::try_from(table.blocks.len()).map_err(|_| invalid("too many blocks"))?); + let block = + BlockId(u16::try_from(table.blocks.len()).map_err(|_| invalid("too many blocks"))?); let default = registry .default_state(&first.name) .ok_or_else(|| invalid("block without default state"))?; @@ -162,9 +176,12 @@ impl StateTable { for offset in 0..count { let state = registry.state(BlockStateId(index as u32 + offset)).unwrap(); for slot in &info.slots { - let value = &slot.values[((offset / slot.stride) % slot.values.len() as u32) as usize]; + let value = + &slot.values[((offset / slot.stride) % slot.values.len() as u32) as usize]; if *value.text != *state.properties[&table.key_names[slot.key.0 as usize]] { - return Err(invalid("registry state order differs from vanilla's state definition")); + return Err(invalid( + "registry state order differs from vanilla's state definition", + )); } } table.state_block.push(block.0); @@ -216,7 +233,10 @@ impl StateTable { self.state_block[state.0 as usize] == block.0 } fn slot(&self, state: BlockStateId, key: PropKey) -> Option<&Slot> { - self.info(self.block(state)).slots.iter().find(|slot| slot.key == key) + self.info(self.block(state)) + .slots + .iter() + .find(|slot| slot.key == key) } pub fn has(&self, state: BlockStateId, key: PropKey) -> bool { self.slot(state, key).is_some() @@ -234,7 +254,9 @@ impl StateTable { } /// Missing boolean properties read as false. pub fn bool(&self, state: BlockStateId, key: PropKey) -> bool { - self.value(state, key).and_then(|v| v.boolean).unwrap_or(false) + self.value(state, key) + .and_then(|v| v.boolean) + .unwrap_or(false) } /// Missing integer properties read as 0. pub fn int(&self, state: BlockStateId, key: PropKey) -> i32 { @@ -271,12 +293,22 @@ impl StateTable { let index = slot.values.iter().position(|v| v.int == Some(value))?; Some(self.with_index(state, slot, index as u32)) } - pub fn with_bool(&self, state: BlockStateId, key: PropKey, value: bool) -> Option { + pub fn with_bool( + &self, + state: BlockStateId, + key: PropKey, + value: bool, + ) -> Option { let slot = self.slot(state, key)?; let index = slot.values.iter().position(|v| v.boolean == Some(value))?; Some(self.with_index(state, slot, index as u32)) } - pub fn with_dir(&self, state: BlockStateId, key: PropKey, value: Direction) -> Option { + pub fn with_dir( + &self, + state: BlockStateId, + key: PropKey, + value: Direction, + ) -> Option { self.with_text(state, key, direction_name(value)) } /// Vanilla `setValue` callers always pass legal values; when Horizon's port @@ -313,6 +345,9 @@ impl StateTable { result } pub fn property_names(&self, block: BlockId) -> impl Iterator { - self.info(block).slots.iter().map(|slot| self.key_names[slot.key.0 as usize].as_str()) + self.info(block) + .slots + .iter() + .map(|slot| self.key_names[slot.key.0 as usize].as_str()) } } diff --git a/crates/horizon-world/src/level/survive.rs b/crates/horizon-world/src/level/survive.rs index 75fef433c..0feda8c7c 100644 --- a/crates/horizon-world/src/level/survive.rs +++ b/crates/horizon-world/src/level/survive.rs @@ -24,7 +24,13 @@ impl Sim<'_, L> { } true } - fn can_survive_class(&self, class: Class, depth: usize, state: BlockStateId, pos: BlockPos) -> Option { + fn can_survive_class( + &self, + class: Class, + depth: usize, + state: BlockStateId, + pos: BlockPos, + ) -> Option { let b = self.b; let p = &b.props; let t = &b.tags; @@ -35,8 +41,12 @@ impl Sim<'_, L> { let facing = b.facing(state); self.sturdy(rel(pos, facing.opposite()), facing) } - Class::BambooSapling | Class::BambooStalk => b.in_set(self.below_state(pos), &t.supports_bamboo), - Class::Banner | Class::Cake | Class::CandleCake | Class::StandingSign => b.is_solid(self.below_state(pos)), + Class::BambooSapling | Class::BambooStalk => { + b.in_set(self.below_state(pos), &t.supports_bamboo) + } + Class::Banner | Class::Cake | Class::CandleCake | Class::StandingSign => { + b.is_solid(self.below_state(pos)) + } Class::BaseCoralPlantType | Class::LeafLitter => self.sturdy(below(pos), Direction::Up), Class::BasePressurePlate => { let below = below(pos); @@ -54,7 +64,9 @@ impl Sim<'_, L> { } Class::BigDripleaf => { let below = self.below_state(pos); - b.is_block(below, block) || b.is_block(below, n.big_dripleaf_stem) || b.in_set(below, &t.supports_big_dripleaf) + b.is_block(below, block) + || b.is_block(below, n.big_dripleaf_stem) + || b.in_set(below, &t.supports_big_dripleaf) } Class::BigDripleafStem => { let below = self.below_state(pos); @@ -76,10 +88,13 @@ impl Sim<'_, L> { } } let below = self.below_state(pos); - (b.is_block(below, block) || b.in_set(below, &t.supports_cactus)) && !b.liquid(self.above_state(pos)) + (b.is_block(below, block) || b.in_set(below, &t.supports_cactus)) + && !b.liquid(self.above_state(pos)) } Class::Carpet => !self.is_empty_block(below(pos)), - Class::CeilingHangingSign => b.is_face_sturdy_center(self.above_state(pos), Direction::Down), + Class::CeilingHangingSign => { + b.is_face_sturdy_center(self.above_state(pos), Direction::Down) + } Class::ChorusFlower => { let below = self.below_state(pos); if b.is_block(below, n.chorus_plant) || b.in_set(below, &t.supports_chorus_flower) { @@ -120,7 +135,9 @@ impl Sim<'_, L> { b.is_block(below_state, block) || b.in_set(below_state, &t.supports_chorus_plant) } Class::Cocoa => b.in_set(self.rel_state(pos, b.facing(state)), &t.supports_cocoa), - Class::Crop => self.raw_brightness(pos, 0) >= 8 && self.can_survive_at(depth + 1, state, pos), + Class::Crop => { + self.raw_brightness(pos, 0) >= 8 && self.can_survive_at(depth + 1, state, pos) + } Class::Diode => b.is_face_sturdy_rigid(self.below_state(pos), Direction::Up), Class::Door => { let below_state = self.below_state(pos); @@ -147,13 +164,19 @@ impl Sim<'_, L> { Class::TallSeagrass => { if b.table.text(state, p.half) == "upper" { let below_state = self.below_state(pos); - return Some(b.is_block(below_state, block) && b.table.text(below_state, p.half) == "lower"); + return Some( + b.is_block(below_state, block) + && b.table.text(below_state, p.half) == "lower", + ); } let fluid = self.fluid_at(pos); - self.can_survive_at(depth + 1, state, pos) && b.is_water_fluid(fluid.kind()) && fluid.is_full() + self.can_survive_at(depth + 1, state, pos) + && b.is_water_fluid(fluid.kind()) + && fluid.is_full() } Class::PitcherCrop => { - let lower = b.is_block(state, n.pitcher_crop) && b.table.text(state, p.half) == "lower"; + let lower = + b.is_block(state, n.pitcher_crop) && b.table.text(state, p.half) == "lower"; if lower && self.raw_brightness(pos, 0) < 8 { false } else { @@ -170,7 +193,9 @@ impl Sim<'_, L> { let above = self.above_state(pos); !b.is_solid(above) || b.in_set(above, &t.maintains_farmland) } - Class::Fire => self.sturdy(below(pos), Direction::Up) || self.is_valid_fire_location(pos), + Class::Fire => { + self.sturdy(below(pos), Direction::Up) || self.is_valid_fire_location(pos) + } Class::SoulFire => b.in_set(self.below_state(pos), &t.soul_fire_base_blocks), Class::Frogspawn => self.frogspawn_may_place_on(below(pos)), Class::GrowingPlant => { @@ -182,7 +207,9 @@ impl Sim<'_, L> { return Some(false); } let (head, body) = self.growing_plant_pair(block); - b.is_block(attached, head) || b.is_block(attached, body) || b.is_face_sturdy(attached, growth) + b.is_block(attached, head) + || b.is_block(attached, body) + || b.is_face_sturdy(attached, growth) } Class::HangingMoss => { let neighbour = self.above_state(pos); @@ -194,12 +221,19 @@ impl Sim<'_, L> { self.sturdy(rel(pos, facing.opposite()), facing) } Class::Lantern => { - let direction = if b.table.bool(state, p.hanging) { Direction::Up } else { Direction::Down }; + let direction = if b.table.bool(state, p.hanging) { + Direction::Up + } else { + Direction::Down + }; self.can_support_center(rel(pos, direction), direction.opposite()) } Class::MangrovePropagule => { if b.table.bool(state, p.hanging) { - b.in_set(self.above_state(pos), &t.supports_hanging_mangrove_propagule) + b.in_set( + self.above_state(pos), + &t.supports_hanging_mangrove_propagule, + ) } else { self.can_survive_at(depth + 1, state, pos) } @@ -230,7 +264,8 @@ impl Sim<'_, L> { if b.in_set(below_state, &t.overrides_mushroom_light_requirement) { true } else { - self.raw_brightness(pos, 0) < 13 && self.may_place_on(state, below_state, below_pos) + self.raw_brightness(pos, 0) < 13 + && self.may_place_on(state, below_state, below_pos) } } Class::Path => { @@ -257,15 +292,23 @@ impl Sim<'_, L> { } else if b.in_set(below_state, &t.support_override_snow_layer) { true } else { - self.shape_info_at(below_state, below(pos)).full_faces & (1 << Direction::Up as u8) != 0 - || (b.is_block(below_state, block) && b.table.int(below_state, p.layers) == 8) + self.shape_info_at(below_state, below(pos)).full_faces + & (1 << Direction::Up as u8) + != 0 + || (b.is_block(below_state, block) + && b.table.int(below_state, p.layers) == 8) } } Class::Speleothem => { - let tip = b.table.dir(state, p.vertical_direction).unwrap_or(Direction::Up); + let tip = b + .table + .dir(state, p.vertical_direction) + .unwrap_or(Direction::Up); self.is_valid_speleothem_placement(block, pos, tip) } - Class::SporeBlossom => self.can_support_center(above(pos), Direction::Down) && !self.is_water_at(pos), + Class::SporeBlossom => { + self.can_support_center(above(pos), Direction::Down) && !self.is_water_at(pos) + } Class::SugarCane => { let below_state = self.below_state(pos); if b.is_block(below_state, block) { @@ -297,32 +340,43 @@ impl Sim<'_, L> { let updated = self.vine_updated_state(state, pos); self.vine_count_faces(updated) > 0 } - Class::WallBanner | Class::WallSign => b.is_solid(self.rel_state(pos, b.facing(state).opposite())), + Class::WallBanner | Class::WallSign => { + b.is_solid(self.rel_state(pos, b.facing(state).opposite())) + } _ => return None, }) } /// `VegetationBlock.mayPlaceOn` (virtual) for `state`'s block. - pub fn may_place_on(&self, state: BlockStateId, ground: BlockStateId, ground_pos: BlockPos) -> bool { + pub fn may_place_on( + &self, + state: BlockStateId, + ground: BlockStateId, + ground_pos: BlockPos, + ) -> bool { let b = self.b; let t = &b.tags; let data = b.data(state); for class in &data.chain { let result = match class { Class::AttachedStem | Class::NetherFungus | Class::NetherRoots | Class::Stem => { - data.support_tag.as_ref().is_some_and(|tag| b.in_set(ground, tag)) + data.support_tag + .as_ref() + .is_some_and(|tag| b.in_set(ground, tag)) } Class::Azalea => b.in_set(ground, &t.supports_azalea), Class::CactusFlower => { let below = self.state(ground_pos); - b.in_set(below, &t.support_override_cactus_flower) || b.is_face_sturdy_center(below, Direction::Up) + b.in_set(below, &t.support_override_cactus_flower) + || b.is_face_sturdy_center(below, Direction::Up) } Class::Crop | Class::PitcherCrop => b.in_set(ground, &t.supports_crops), Class::DryVegetation => b.in_set(ground, &t.supports_dry_vegetation), Class::LilyPad => { let fluid = self.fluid_at(ground_pos); let above = self.fluid_at(above(ground_pos)); - (b.fluid_in(fluid.kind(), b.fluid_tags.supports_lily_pad) || b.in_set(ground, &t.supports_lily_pad)) + (b.fluid_in(fluid.kind(), b.fluid_tags.supports_lily_pad) + || b.in_set(ground, &t.supports_lily_pad)) && above.kind() == crate::fluid::FluidKind::Empty } Class::MangrovePropagule => b.in_set(ground, &t.supports_mangrove_propagule), @@ -330,10 +384,14 @@ impl Sim<'_, L> { Class::NetherSprouts => b.in_set(ground, &t.supports_nether_sprouts), Class::NetherWart => b.in_set(ground, &t.supports_nether_wart), Class::SeaPickle => { - self.shape_info_at(ground, ground_pos).nonempty_faces & (1 << Direction::Up as u8) != 0 || b.is_face_sturdy(ground, Direction::Up) + self.shape_info_at(ground, ground_pos).nonempty_faces + & (1 << Direction::Up as u8) + != 0 + || b.is_face_sturdy(ground, Direction::Up) } Class::Seagrass | Class::TallSeagrass => { - b.is_face_sturdy(ground, Direction::Up) && !b.in_set(ground, &t.cannot_support_seagrass) + b.is_face_sturdy(ground, Direction::Up) + && !b.in_set(ground, &t.cannot_support_seagrass) } Class::SmallDripleaf => { b.in_set(ground, &t.supports_small_dripleaf) @@ -353,7 +411,8 @@ impl Sim<'_, L> { let b = self.b; let fluid = self.fluid_at(pos); let above = self.fluid_at(above(pos)); - (b.fluid_in(fluid.kind(), b.fluid_tags.supports_frogspawn) || b.in_set(self.state(pos), &b.tags.supports_frogspawn)) + (b.fluid_in(fluid.kind(), b.fluid_tags.supports_frogspawn) + || b.in_set(self.state(pos), &b.tags.supports_frogspawn)) && above.kind() == crate::fluid::FluidKind::Empty } @@ -387,11 +446,18 @@ impl Sim<'_, L> { } } /// Head and body blocks of a growing-plant family. - pub(crate) fn growing_plant_pair(&self, block: super::states::BlockId) -> (super::states::BlockId, super::states::BlockId) { + pub(crate) fn growing_plant_pair( + &self, + block: super::states::BlockId, + ) -> (super::states::BlockId, super::states::BlockId) { let name = &*self.b.table.info(block).name; let head = name.strip_suffix("_plant").unwrap_or(name); let head = self.b.table.block_by_name(head).unwrap_or(block); - let body = self.b.table.block_by_name(&format!("{}_plant", &*self.b.table.info(head).name)).unwrap_or(block); + let body = self + .b + .table + .block_by_name(&format!("{}_plant", &*self.b.table.info(head).name)) + .unwrap_or(block); (head, body) } /// `GrowingPlantBlock.canAttachTo` (kelp refuses `cannot_support_kelp`). @@ -405,7 +471,9 @@ impl Sim<'_, L> { } /// `FireBlock.isValidFireLocation`. pub(crate) fn is_valid_fire_location(&self, pos: BlockPos) -> bool { - Direction::ALL.into_iter().any(|direction| self.can_burn(self.rel_state(pos, direction))) + Direction::ALL + .into_iter() + .any(|direction| self.can_burn(self.rel_state(pos, direction))) } /// `FireBlock.canBurn`: ignite odds above zero (waterlogged states never burn). pub(crate) fn can_burn(&self, state: BlockStateId) -> bool { @@ -448,14 +516,24 @@ impl Sim<'_, L> { distance } /// `SpeleothemBlock.isValidSpeleothemPlacement`. - pub(crate) fn is_valid_speleothem_placement(&self, block: super::states::BlockId, pos: BlockPos, tip: Direction) -> bool { + pub(crate) fn is_valid_speleothem_placement( + &self, + block: super::states::BlockId, + pos: BlockPos, + tip: Direction, + ) -> bool { let behind_pos = rel(pos, tip.opposite()); let behind = self.state(behind_pos); self.b.is_face_sturdy(behind, tip) - || (self.b.is_block(behind, block) && self.b.table.dir(behind, self.b.props.vertical_direction) == Some(tip)) + || (self.b.is_block(behind, block) + && self.b.table.dir(behind, self.b.props.vertical_direction) == Some(tip)) } /// `VineBlock.getUpdatedState`. - pub(crate) fn vine_updated_state(&self, mut state: BlockStateId, pos: BlockPos) -> BlockStateId { + pub(crate) fn vine_updated_state( + &self, + mut state: BlockStateId, + pos: BlockPos, + ) -> BlockStateId { let b = self.b; let p = &b.props; let above_pos = above(pos); @@ -477,7 +555,12 @@ impl Sim<'_, L> { } state } - fn vine_can_support_at_face(&self, state: BlockStateId, pos: BlockPos, direction: Direction) -> bool { + fn vine_can_support_at_face( + &self, + state: BlockStateId, + pos: BlockPos, + direction: Direction, + ) -> bool { let b = self.b; if direction == Direction::Down { return false; @@ -492,9 +575,15 @@ impl Sim<'_, L> { b.is_block(above, b.block(state)) && b.table.bool(above, self.direction_prop(direction)) } pub(crate) fn vine_count_faces(&self, state: BlockStateId) -> usize { - [Direction::Up, Direction::North, Direction::East, Direction::South, Direction::West] - .into_iter() - .filter(|d| self.b.table.bool(state, self.direction_prop(*d))) - .count() + [ + Direction::Up, + Direction::North, + Direction::East, + Direction::South, + Direction::West, + ] + .into_iter() + .filter(|d| self.b.table.bool(state, self.direction_prop(*d))) + .count() } } diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs index 36aa1cce4..c1ffce5a1 100644 --- a/crates/horizon-world/src/level/tests.rs +++ b/crates/horizon-world/src/level/tests.rs @@ -18,16 +18,22 @@ 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") - }); + 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 }) + Some(Fixture { + registry, + behaviours, + }) }) .as_ref() } @@ -101,12 +107,24 @@ impl<'f> World<'f> { 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::>(), + 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:?}")) + 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) + 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) { @@ -117,21 +135,42 @@ impl<'f> World<'f> { } 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(",")) + 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() + 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); + self.f + .behaviours + .tick_scheduled(&mut self.level, &mut self.ticks); } /// Scheduled ticks, block events and block entities, as `ServerLevel.tick`. fn full_tick(&mut self) { self.tick(); - self.f.behaviours.run_block_events(&mut self.level, &mut self.ticks); - self.f.behaviours.tick_block_entities(&mut self.level, &mut self.ticks); + self.f + .behaviours + .run_block_events(&mut self.level, &mut self.ticks); + self.f + .behaviours + .tick_block_entities(&mut self.level, &mut self.ticks); } fn floor(&mut self, y: i32, radius: i32, block: &str) { let state = self.id(block, &[]); @@ -195,7 +234,11 @@ fn walls_and_panes_connect() { 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"); + 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"); @@ -227,10 +270,23 @@ fn torch_and_door_halves_break_with_support() { 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 { .. }))); + 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"); + assert_eq!( + w.get(BlockPos::new(0, 2, 0)), + air, + "upper door half goes with the lower" + ); } #[test] @@ -260,13 +316,27 @@ fn sand_falls_and_concrete_solidifies() { 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))); + 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", &[]))); + 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] @@ -280,7 +350,12 @@ fn water_spreads_on_a_floor() { } 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.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. @@ -296,7 +371,11 @@ fn water_falls_and_makes_sources() { 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, 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). @@ -339,7 +418,12 @@ fn lava_meets_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))); + assert_eq!( + w.get(BlockPos::new(1, 1, 0)), + w.id("cobblestone", &[]), + "{}", + w.name(BlockPos::new(1, 1, 0)) + ); } #[test] @@ -369,7 +453,10 @@ fn redstone_lever_wire_and_lamp() { } 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); + 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"); @@ -408,11 +495,19 @@ fn repeater_delays_and_torch_inverts() { // 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")]); + 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.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"); @@ -426,12 +521,14 @@ fn crops_grow_and_leaves_decay() { 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)); + 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)); + 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", &[]); @@ -444,7 +541,15 @@ fn crops_grow_and_leaves_decay() { impl World<'_> { /// Right-click `item` on the `face` of `clicked`, hitting the face centre /// (offset vertically by `dy`), looking with `yaw`/`pitch`. - fn place(&mut self, item: &str, clicked: BlockPos, face: Direction, yaw: f32, pitch: f32, dy: f64) -> PlaceOutcome { + fn place( + &mut self, + item: &str, + clicked: BlockPos, + face: Direction, + yaw: f32, + pitch: f32, + dy: f64, + ) -> PlaceOutcome { let [nx, ny, nz] = face.normal(); let hit = horizon_core::geometry::Vec3::new( f64::from(clicked.x) + 0.5 + f64::from(nx) * 0.5, @@ -460,8 +565,11 @@ impl World<'_> { pitch, sneaking: false, item: format!("minecraft:{item}"), + can_use_game_master_blocks: false, }; - self.f.behaviours.place_block(&mut self.level, &mut self.ticks, &ctx) + self.f + .behaviours + .place_block(&mut self.level, &mut self.ticks, &ctx) } fn use_block(&mut self, pos: BlockPos) -> InteractionResult { let player = PlayerContext { @@ -471,8 +579,19 @@ impl World<'_> { can_eat: true, game_master: false, }; - let hit = horizon_core::geometry::Vec3::new(f64::from(pos.x) + 0.5, f64::from(pos.y) + 0.5, f64::from(pos.z)); - self.f.behaviours.use_without_item(&mut self.level, &mut self.ticks, pos, Direction::North, hit, player) + let hit = horizon_core::geometry::Vec3::new( + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 0.5, + f64::from(pos.z), + ); + self.f.behaviours.use_without_item( + &mut self.level, + &mut self.ticks, + pos, + Direction::North, + hit, + player, + ) } } @@ -483,17 +602,55 @@ fn placement_orients_blocks() { let ground = BlockPos::new(0, 0, 0); // Looking north (yaw 180) at the top of the floor. w.place("oak_stairs", ground, Direction::Up, 180.0, 30.0, 0.0); - assert_eq!(w.name(BlockPos::new(0, 1, 0)), "oak_stairs[facing=north,half=bottom,shape=straight,waterlogged=false]"); - w.place("oak_log", BlockPos::new(1, 0, 0), Direction::Up, 0.0, 0.0, 0.0); - w.place("oak_log", BlockPos::new(1, 1, 0), Direction::East, 0.0, 0.0, 0.0); + assert_eq!( + w.name(BlockPos::new(0, 1, 0)), + "oak_stairs[facing=north,half=bottom,shape=straight,waterlogged=false]" + ); + w.place( + "oak_log", + BlockPos::new(1, 0, 0), + Direction::Up, + 0.0, + 0.0, + 0.0, + ); + w.place( + "oak_log", + BlockPos::new(1, 1, 0), + Direction::East, + 0.0, + 0.0, + 0.0, + ); assert_eq!(w.prop(BlockPos::new(2, 1, 0), "axis"), "x"); // Torch against the log's east face becomes a wall torch facing east. - w.place("torch", BlockPos::new(2, 1, 0), Direction::East, 270.0, 0.0, 0.0); + w.place( + "torch", + BlockPos::new(2, 1, 0), + Direction::East, + 270.0, + 0.0, + 0.0, + ); assert_eq!(w.name(BlockPos::new(3, 1, 0)), "wall_torch[facing=east]"); // Furnaces face the player; observers face where the player looks. - w.place("furnace", BlockPos::new(-2, 0, 0), Direction::Up, 0.0, 0.0, 0.0); + w.place( + "furnace", + BlockPos::new(-2, 0, 0), + Direction::Up, + 0.0, + 0.0, + 0.0, + ); assert_eq!(w.prop(BlockPos::new(-2, 1, 0), "facing"), "north"); - w.place("observer", BlockPos::new(-3, 0, 0), Direction::Up, 0.0, 0.0, 0.0); + w.place( + "observer", + BlockPos::new(-3, 0, 0), + Direction::Up, + 0.0, + 0.0, + 0.0, + ); assert_eq!(w.prop(BlockPos::new(-3, 1, 0), "facing"), "south"); } @@ -504,16 +661,58 @@ fn placement_merges_slabs_and_stacks() { let ground = BlockPos::new(0, 0, 0); w.place("oak_slab", ground, Direction::Up, 0.0, 60.0, 0.0); assert_eq!(w.prop(BlockPos::new(0, 1, 0), "type"), "bottom"); - w.place("oak_slab", BlockPos::new(0, 1, 0), Direction::Up, 0.0, 60.0, -0.5); + w.place( + "oak_slab", + BlockPos::new(0, 1, 0), + Direction::Up, + 0.0, + 60.0, + -0.5, + ); assert_eq!(w.prop(BlockPos::new(0, 1, 0), "type"), "double"); // Clicking the upper half of a side face places a top slab. - w.place("oak_slab", BlockPos::new(0, 1, 0), Direction::East, 0.0, 0.0, 0.25); + w.place( + "oak_slab", + BlockPos::new(0, 1, 0), + Direction::East, + 0.0, + 0.0, + 0.25, + ); assert_eq!(w.prop(BlockPos::new(1, 1, 0), "type"), "top"); - w.place("snow", BlockPos::new(3, 0, 0), Direction::Up, 0.0, 60.0, 0.0); - w.place("snow", BlockPos::new(3, 1, 0), Direction::Up, 0.0, 60.0, -0.375); + w.place( + "snow", + BlockPos::new(3, 0, 0), + Direction::Up, + 0.0, + 60.0, + 0.0, + ); + w.place( + "snow", + BlockPos::new(3, 1, 0), + Direction::Up, + 0.0, + 60.0, + -0.375, + ); assert_eq!(w.prop(BlockPos::new(3, 1, 0), "layers"), "2"); - w.place("candle", BlockPos::new(-3, 0, 0), Direction::Up, 0.0, 60.0, 0.0); - w.place("candle", BlockPos::new(-3, 1, 0), Direction::Up, 0.0, 60.0, -0.4); + w.place( + "candle", + BlockPos::new(-3, 0, 0), + Direction::Up, + 0.0, + 60.0, + 0.0, + ); + w.place( + "candle", + BlockPos::new(-3, 1, 0), + Direction::Up, + 0.0, + 60.0, + -0.4, + ); assert_eq!(w.prop(BlockPos::new(-3, 1, 0), "candles"), "2"); } @@ -525,36 +724,98 @@ fn doors_beds_and_plants_place_both_halves() { w.place("oak_door", ground, Direction::Up, 180.0, 30.0, 0.0); assert_eq!(w.prop(BlockPos::new(0, 1, 0), "half"), "lower"); assert_eq!(w.prop(BlockPos::new(0, 2, 0), "half"), "upper"); - assert_eq!(w.use_block(BlockPos::new(0, 1, 0)), InteractionResult::Success); + assert_eq!( + w.use_block(BlockPos::new(0, 1, 0)), + InteractionResult::Success + ); assert_eq!(w.prop(BlockPos::new(0, 1, 0), "open"), "true"); - assert_eq!(w.prop(BlockPos::new(0, 2, 0), "open"), "true", "the upper half follows"); - w.place("red_bed", BlockPos::new(3, 0, 0), Direction::Up, 180.0, 30.0, 0.0); + assert_eq!( + w.prop(BlockPos::new(0, 2, 0), "open"), + "true", + "the upper half follows" + ); + w.place( + "red_bed", + BlockPos::new(3, 0, 0), + Direction::Up, + 180.0, + 30.0, + 0.0, + ); assert_eq!(w.prop(BlockPos::new(3, 1, 0), "part"), "foot"); assert_eq!(w.prop(BlockPos::new(3, 1, -1), "part"), "head"); - w.place("sunflower", BlockPos::new(-3, 0, 0), Direction::Up, 0.0, 30.0, 0.0); + w.place( + "sunflower", + BlockPos::new(-3, 0, 0), + Direction::Up, + 0.0, + 30.0, + 0.0, + ); assert_eq!(w.prop(BlockPos::new(-3, 2, 0), "half"), "upper"); // Iron doors cannot be opened by hand. - w.place("iron_door", BlockPos::new(5, 0, 0), Direction::Up, 180.0, 30.0, 0.0); + w.place( + "iron_door", + BlockPos::new(5, 0, 0), + Direction::Up, + 180.0, + 30.0, + 0.0, + ); assert_eq!(w.use_block(BlockPos::new(5, 1, 0)), InteractionResult::Pass); // A placement into a solid block fails. - assert_eq!(w.place("stone", BlockPos::new(0, 0, 0), Direction::West, 0.0, 0.0, 0.0), PlaceOutcome::Failed); + assert_eq!( + w.place( + "stone", + BlockPos::new(0, 0, 0), + Direction::West, + 0.0, + 0.0, + 0.0 + ), + PlaceOutcome::Failed + ); } #[test] fn levers_power_wire_through_interaction() { let mut w = world!(); w.floor(0, 8, "stone"); - w.place("lever", BlockPos::new(0, 0, 0), Direction::Up, 0.0, 60.0, 0.0); + w.place( + "lever", + BlockPos::new(0, 0, 0), + Direction::Up, + 0.0, + 60.0, + 0.0, + ); for x in 1..=3 { - w.place("redstone", BlockPos::new(x, 0, 0), Direction::Up, 0.0, 60.0, 0.0); + w.place( + "redstone", + BlockPos::new(x, 0, 0), + Direction::Up, + 0.0, + 60.0, + 0.0, + ); } - assert_eq!(w.use_block(BlockPos::new(0, 1, 0)), InteractionResult::Success); + assert_eq!( + w.use_block(BlockPos::new(0, 1, 0)), + InteractionResult::Success + ); assert_eq!(w.prop(BlockPos::new(0, 1, 0), "powered"), "true"); assert_eq!(w.prop(BlockPos::new(3, 1, 0), "power"), "13"); w.use_block(BlockPos::new(0, 1, 0)); assert_eq!(w.prop(BlockPos::new(1, 1, 0), "power"), "0"); // Buttons release after their pressed time. - w.place("stone_button", BlockPos::new(5, 0, 0), Direction::Up, 0.0, 60.0, 0.0); + w.place( + "stone_button", + BlockPos::new(5, 0, 0), + Direction::Up, + 0.0, + 60.0, + 0.0, + ); w.use_block(BlockPos::new(5, 1, 0)); assert_eq!(w.prop(BlockPos::new(5, 1, 0), "powered"), "true"); for _ in 0..20 { @@ -578,7 +839,10 @@ fn pistons_push_and_sticky_pistons_pull() { w.full_tick(); } assert_eq!(w.prop(BlockPos::new(0, 1, 0), "extended"), "true"); - assert_eq!(w.name(BlockPos::new(1, 1, 0)), "piston_head[facing=east,short=false,type=sticky]"); + assert_eq!( + w.name(BlockPos::new(1, 1, 0)), + "piston_head[facing=east,short=false,type=sticky]" + ); assert_eq!(w.get(BlockPos::new(2, 1, 0)), dirt); assert!(w.ticks.moving_pistons.is_empty()); w.set(BlockPos::new(-1, 1, 0), air); @@ -586,7 +850,11 @@ fn pistons_push_and_sticky_pistons_pull() { w.full_tick(); } assert_eq!(w.prop(BlockPos::new(0, 1, 0), "extended"), "false"); - assert_eq!(w.get(BlockPos::new(1, 1, 0)), dirt, "the sticky piston pulled the block back"); + assert_eq!( + w.get(BlockPos::new(1, 1, 0)), + dirt, + "the sticky piston pulled the block back" + ); assert_eq!(w.get(BlockPos::new(2, 1, 0)), air); } @@ -604,8 +872,16 @@ fn pistons_pop_fragile_blocks_and_refuse_obsidian() { for _ in 0..4 { w.full_tick(); } - assert_eq!(w.name(BlockPos::new(1, 1, 0)), "piston_head[facing=east,short=false,type=normal]"); - assert!(w.level.events.iter().any(|e| matches!(e, LevelEvent::DropResources { state, .. } if *state == torch))); + assert_eq!( + w.name(BlockPos::new(1, 1, 0)), + "piston_head[facing=east,short=false,type=normal]" + ); + assert!( + w.level + .events + .iter() + .any(|e| matches!(e, LevelEvent::DropResources { state, .. } if *state == torch)) + ); let mut w = world!(); w.floor(0, 10, "stone"); w.set(BlockPos::new(0, 1, 0), piston); @@ -623,14 +899,18 @@ fn dripstone_fills_cauldrons() { let mut w = world!(); let block = w.id("dripstone_block", &[]); let water = w.id("water", &[]); - let tip = w.id("pointed_dripstone", &[("vertical_direction", "down"), ("thickness", "tip")]); + let tip = w.id( + "pointed_dripstone", + &[("vertical_direction", "down"), ("thickness", "tip")], + ); let cauldron = w.id("cauldron", &[]); w.put(BlockPos::new(0, 11, 0), water); w.put(BlockPos::new(0, 10, 0), block); w.put(BlockPos::new(0, 9, 0), tip); w.put(BlockPos::new(0, 5, 0), cauldron); for _ in 0..100 { - w.b().random_tick(&mut w.level, &mut w.ticks, BlockPos::new(0, 9, 0)); + w.b() + .random_tick(&mut w.level, &mut w.ticks, BlockPos::new(0, 9, 0)); } for _ in 0..80 { w.tick(); diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index b9dae2f0d..555ba2a85 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -40,7 +40,9 @@ impl Sim<'_, L> { } Class::HangingMoss => { let above_state = self.above_state(pos); - if !(b.multiface_can_attach(above_state, Direction::Up) || b.is_block(above_state, block)) { + if !(b.multiface_can_attach(above_state, Direction::Up) + || b.is_block(above_state, block)) + { self.destroy_block(pos, true, 512); } } @@ -79,7 +81,8 @@ impl Sim<'_, L> { 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); + 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)); } @@ -88,7 +91,11 @@ impl Sim<'_, L> { } } Class::Dispenser | Class::Crafter => { - self.emit(LevelEvent::BlockEvent { pos, state, kind: "dispense" }); + self.emit(LevelEvent::BlockEvent { + pos, + state, + kind: "dispense", + }); } Class::FallingBlock => self.falling_block_tick(pos, state), Class::Brushable => { @@ -107,7 +114,11 @@ impl Sim<'_, L> { if !self.can_survive(state, pos) { self.destroy_block(pos, false, 512); } else { - self.emit(LevelEvent::BlockEvent { pos, state, kind: "hatch" }); + self.emit(LevelEvent::BlockEvent { + pos, + state, + kind: "hatch", + }); self.destroy_block(pos, false, 512); } } @@ -146,7 +157,9 @@ impl Sim<'_, L> { } } Class::TripWire => self.tripwire_tick(pos), - Class::TripWireHook => self.tripwire_hook_calculate(pos, state, false, true, -1, None), + Class::TripWireHook => { + self.tripwire_hook_calculate(pos, state, false, true, -1, None) + } _ => continue, } return; @@ -176,7 +189,10 @@ impl Sim<'_, L> { 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 { + if self.rand_int(3) == 0 + && self.is_empty_block(above(pos)) + && self.raw_brightness(above(pos), 0) >= 9 + { self.bamboo_sapling_grow(pos); } } @@ -211,7 +227,9 @@ impl Sim<'_, L> { } 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 { + 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); @@ -231,7 +249,10 @@ impl Sim<'_, L> { } } Class::Liquid => { - if matches!(b.fluid(state).kind(), FluidKind::Lava | FluidKind::FlowingLava) { + if matches!( + b.fluid(state).kind(), + FluidKind::Lava | FluidKind::FlowingLava + ) { self.lava_random_tick(pos); } } @@ -333,7 +354,11 @@ impl Sim<'_, L> { /// `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) + 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; @@ -345,12 +370,23 @@ impl Sim<'_, L> { } self.b.table.set_int(state, self.b.props.distance, distance) } - fn bubble_column_update(&mut self, pos: BlockPos, state: BlockStateId, below_state: BlockStateId) { + 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) { + 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; @@ -422,7 +458,11 @@ impl Sim<'_, L> { 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); + 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); @@ -459,7 +499,11 @@ impl Sim<'_, L> { 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 { + 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; } @@ -510,7 +554,10 @@ impl Sim<'_, L> { if burnout { odds /= 2; } - if odds > 0 && self.rand_int(rate) <= odds && (!self.level.is_raining() || !self.fire_near_rain(test)) { + 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); @@ -525,7 +572,11 @@ impl Sim<'_, L> { 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) + 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) @@ -573,19 +624,29 @@ impl Sim<'_, L> { 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) { + 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); + 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); + 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 { @@ -624,10 +685,18 @@ impl Sim<'_, L> { } } 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 (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)); + 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; } @@ -665,10 +734,19 @@ impl Sim<'_, L> { 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 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)); + self.set_block_and_update( + pos, + b.table + .set_dir(b.default_of(stem), b.props.facing, direction), + ); } } } @@ -679,7 +757,9 @@ impl Sim<'_, L> { 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" { + if !b.is_block(below_state, b.named.pitcher_crop) + || b.table.text(below_state, p.half) != "lower" + { return; } (below_pos, below_state) @@ -702,7 +782,10 @@ impl Sim<'_, L> { 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); + 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); } } @@ -771,7 +854,11 @@ impl Sim<'_, L> { } 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); + 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); } @@ -828,7 +915,10 @@ impl Sim<'_, L> { /// `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 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); @@ -889,23 +979,37 @@ impl Sim<'_, L> { 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 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 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 { + 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); + 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); } } @@ -917,14 +1021,24 @@ impl Sim<'_, L> { } 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) { + 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) { + while height < 16 + && self.b.is_block( + self.state(pos.offset(0, height + 1, 0)), + self.b.named.bamboo, + ) + { height += 1; } height @@ -938,19 +1052,49 @@ impl Sim<'_, L> { 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" { + 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" { + } 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); + 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 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); } @@ -965,7 +1109,9 @@ impl Sim<'_, L> { 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 super::query::is_horizontal(direction) + && !b.table.bool(state, self.direction_prop(direction)) + { if !self.vine_can_spread(pos, block) { return; } @@ -979,21 +1125,52 @@ impl Sim<'_, L> { 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); + 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); + 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) { + 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); + self.set_block( + pos, + b.table + .set_bool(state, self.direction_prop(direction), true), + 2, + ); } return; } @@ -1008,11 +1185,16 @@ impl Sim<'_, L> { } 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) { + 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))) { + if HORIZONTAL + .into_iter() + .any(|d| b.table.bool(above_state, self.direction_prop(d))) + { self.set_block(above_pos, above_state, 2); } return; @@ -1022,14 +1204,22 @@ impl Sim<'_, L> { 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 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))) { + if before != after + && HORIZONTAL + .into_iter() + .any(|d| b.table.bool(after, self.direction_prop(d))) + { self.set_block(below_pos, after, 2); } } @@ -1089,13 +1279,19 @@ impl Sim<'_, L> { grow_up = true; } let all_empty = |sim: &Self, at: BlockPos, ignore: Option| { - HORIZONTAL.into_iter().all(|d| Some(d) == ignore || sim.is_empty_block(rel(at, d))) + HORIZONTAL + .into_iter() + .all(|d| Some(d) == ignore || sim.is_empty_block(rel(at, d))) }; let plant_state = b.default_of(plant); if grow_up && all_empty(self, above_pos, None) && self.is_empty_block(pos.offset(0, 2, 0)) { let connected = self.chorus_plant_with_connections(pos, plant_state); self.set_block(pos, connected, 2); - self.set_block(above_pos, b.table.set_int(b.default_of(block), p.age, age), 2); + self.set_block( + above_pos, + b.table.set_int(b.default_of(block), p.age, age), + 2, + ); self.level_event(1033, above_pos, 0); } else if age < 4 { let mut attempts = self.rand_int(4); @@ -1106,8 +1302,15 @@ impl Sim<'_, L> { for _ in 0..attempts { let direction = HORIZONTAL[self.rand_int(4) as usize]; let target = rel(pos, direction); - if self.is_empty_block(target) && self.is_empty_block(below(target)) && all_empty(self, target, Some(direction.opposite())) { - self.set_block(target, b.table.set_int(b.default_of(block), p.age, age + 1), 2); + if self.is_empty_block(target) + && self.is_empty_block(below(target)) + && all_empty(self, target, Some(direction.opposite())) + { + self.set_block( + target, + b.table.set_int(b.default_of(block), p.age, age + 1), + 2, + ); self.level_event(1033, target, 0); branched = true; } @@ -1159,13 +1362,19 @@ impl Sim<'_, L> { }; if data.is(Class::Cauldron) { if self.random().next_float() < chance { - let next = if info.kind == PrecipitationKind::Rain { b.named.water_cauldron } else { b.named.powder_snow_cauldron }; + let next = if info.kind == PrecipitationKind::Rain { + b.named.water_cauldron + } else { + b.named.powder_snow_cauldron + }; self.set_block_and_update(below_pos, b.default_of(next)); self.game_event(below_pos, "minecraft:block_change"); } } else if data.is(Class::LayeredCauldron) && self.random().next_float() < chance { - let matches = (info.kind == PrecipitationKind::Rain && b.is_block(below_state, b.named.water_cauldron)) - || (info.kind == PrecipitationKind::Snow && b.is_block(below_state, b.named.powder_snow_cauldron)); + let matches = (info.kind == PrecipitationKind::Rain + && b.is_block(below_state, b.named.water_cauldron)) + || (info.kind == PrecipitationKind::Snow + && b.is_block(below_state, b.named.powder_snow_cauldron)); if b.table.int(below_state, p.level) != 3 && matches { self.set_block_and_update(below_pos, b.table.cycle(below_state, p.level)); self.game_event(below_pos, "minecraft:block_change"); @@ -1257,7 +1466,13 @@ impl Behaviours { ticks.handling_tick = true; { let level_ref: &L = level; - if ticks.blocks.begin_tick(time, 65536, |chunk: ChunkPos| level_ref.is_ticking_chunk(chunk)).is_err() { + if ticks + .blocks + .begin_tick(time, 65536, |chunk: ChunkPos| { + level_ref.is_ticking_chunk(chunk) + }) + .is_err() + { ticks.handling_tick = false; return; } @@ -1272,7 +1487,13 @@ impl Behaviours { 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() { + if ticks + .fluids + .begin_tick(time, 65536, |chunk: ChunkPos| { + level_ref.is_ticking_chunk(chunk) + }) + .is_err() + { ticks.handling_tick = false; return; } @@ -1319,17 +1540,32 @@ impl Behaviours { } } /// Random-tick a single position (block then fluid), as `tickChunk` does. - pub fn random_tick(&self, level: &mut L, ticks: &mut Ticks, pos: BlockPos) { + 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) { + 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) { + 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/ticks.rs b/crates/horizon-world/src/level/ticks.rs index 943ab8369..c6be4282f 100644 --- a/crates/horizon-world/src/level/ticks.rs +++ b/crates/horizon-world/src/level/ticks.rs @@ -4,7 +4,9 @@ use super::{states::BlockId, update::NeighborUpdater}; use crate::fluid::FluidKind; use horizon_core::{ position::{BlockPos, ChunkPos}, - ticks::{ChunkTicks, LevelTicks, ScheduleResult, ScheduledTick, TickError, TickPriority, TickTypeId}, + ticks::{ + ChunkTicks, LevelTicks, ScheduleResult, ScheduledTick, TickError, TickPriority, TickTypeId, + }, }; /// Owned by the caller next to its chunk storage. Chunks must be registered @@ -57,7 +59,12 @@ impl Ticks { } } /// Register a loaded chunk's saved block and fluid ticks. - pub fn add_chunk(&mut self, pos: ChunkPos, blocks: ChunkTicks, fluids: ChunkTicks) -> Result<(), TickError> { + pub fn add_chunk( + &mut self, + pos: ChunkPos, + blocks: ChunkTicks, + fluids: ChunkTicks, + ) -> Result<(), TickError> { self.blocks.add_chunk(pos, blocks)?; self.fluids.add_chunk(pos, fluids) } @@ -91,7 +98,13 @@ impl Ticks { }; self.blocks.schedule(tick) } - pub fn schedule_fluid(&mut self, game_time: i64, pos: BlockPos, fluid: FluidKind, delay: i32) -> ScheduleResult { + pub fn schedule_fluid( + &mut self, + game_time: i64, + pos: BlockPos, + fluid: FluidKind, + delay: i32, + ) -> ScheduleResult { let tick = ScheduledTick { kind: TickTypeId(fluid as u32), pos, @@ -102,18 +115,27 @@ impl Ticks { self.fluids.schedule(tick) } pub fn has_block_tick(&self, pos: BlockPos, block: BlockId) -> bool { - self.blocks.has_scheduled(pos, TickTypeId(u32::from(block.0))) + self.blocks + .has_scheduled(pos, TickTypeId(u32::from(block.0))) } pub fn has_fluid_tick(&self, pos: BlockPos, fluid: FluidKind) -> bool { self.fluids.has_scheduled(pos, TickTypeId(fluid as u32)) } pub fn will_block_tick_this_tick(&mut self, pos: BlockPos, block: BlockId) -> bool { - self.blocks.will_tick_this_tick(pos, TickTypeId(u32::from(block.0))) + self.blocks + .will_tick_this_tick(pos, TickTypeId(u32::from(block.0))) } /// `Level.getBlockRandomPos`. pub fn block_random_pos(&mut self, x: i32, y: i32, z: i32, y_mask: i32) -> BlockPos { - self.random_tick_value = self.random_tick_value.wrapping_mul(3).wrapping_add(1_013_904_223); + self.random_tick_value = self + .random_tick_value + .wrapping_mul(3) + .wrapping_add(1_013_904_223); let value = self.random_tick_value >> 2; - BlockPos::new(x + (value & 15), y + ((value >> 16) & y_mask), z + ((value >> 8) & 15)) + BlockPos::new( + x + (value & 15), + y + ((value >> 16) & y_mask), + z + ((value >> 8) & 15), + ) } } diff --git a/crates/horizon-world/src/level/update.rs b/crates/horizon-world/src/level/update.rs index 70c27ad71..b981e1a6f 100644 --- a/crates/horizon-world/src/level/update.rs +++ b/crates/horizon-world/src/level/update.rs @@ -27,7 +27,12 @@ pub(crate) const UPDATE_SHAPE_ORDER: [Direction; 6] = [ Direction::Down, Direction::Up, ]; -pub(crate) const HORIZONTAL: [Direction; 4] = [Direction::North, Direction::East, Direction::South, Direction::West]; +pub(crate) const HORIZONTAL: [Direction; 4] = [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, +]; /// `MinecraftServer.getMaxChainedNeighborUpdates` default. const MAX_CHAINED_NEIGHBOR_UPDATES: i32 = 1_000_000; @@ -126,7 +131,12 @@ impl Update { }, false, ), - Self::Full { state, pos, block, moved } => ( + Self::Full { + state, + pos, + block, + moved, + } => ( Step::Neighbor { state: Some(state), pos, @@ -201,11 +211,22 @@ impl Sim<'_, L> { pub fn schedule_tick(&mut self, pos: BlockPos, block: BlockId, delay: i32) -> ScheduleResult { self.schedule_tick_priority(pos, block, delay, TickPriority::Normal) } - pub fn schedule_tick_priority(&mut self, pos: BlockPos, block: BlockId, delay: i32, priority: TickPriority) -> ScheduleResult { + pub fn schedule_tick_priority( + &mut self, + pos: BlockPos, + block: BlockId, + delay: i32, + priority: TickPriority, + ) -> ScheduleResult { let time = self.level.game_time(); self.ticks.schedule_block(time, pos, block, delay, priority) } - pub fn schedule_fluid_tick(&mut self, pos: BlockPos, fluid: crate::fluid::FluidKind, delay: i32) -> ScheduleResult { + pub fn schedule_fluid_tick( + &mut self, + pos: BlockPos, + fluid: crate::fluid::FluidKind, + delay: i32, + ) -> ScheduleResult { let time = self.level.game_time(); self.ticks.schedule_fluid(time, pos, fluid, delay) } @@ -217,7 +238,13 @@ impl Sim<'_, L> { pub fn set_block_and_update(&mut self, pos: BlockPos, state: BlockStateId) -> bool { self.set_block(pos, state, flags::UPDATE_ALL) } - pub fn set_block_limit(&mut self, pos: BlockPos, state: BlockStateId, update_flags: i32, limit: i32) -> bool { + pub fn set_block_limit( + &mut self, + pos: BlockPos, + state: BlockStateId, + update_flags: i32, + limit: i32, + ) -> bool { if !self.is_in_valid_bounds(pos) || !self.level.is_loaded(pos) { return false; } @@ -229,13 +256,17 @@ impl Sim<'_, L> { if update_flags & flags::UPDATE_NEIGHBORS != 0 { let old_block = self.block_of(old); self.update_neighbors_at(pos, old_block); - if self.b.has_flag(state, super::data::state_flags::ANALOG_OUTPUT) { + if self + .b + .has_flag(state, super::data::state_flags::ANALOG_OUTPUT) + { let block = self.block_of(state); self.update_neighbour_for_output_signal(pos, block); } } if update_flags & flags::UPDATE_KNOWN_SHAPE == 0 && limit > 0 { - let neighbour_flags = update_flags & !(flags::UPDATE_NEIGHBORS | flags::UPDATE_SUPPRESS_DROPS); + let neighbour_flags = + update_flags & !(flags::UPDATE_NEIGHBORS | flags::UPDATE_SUPPRESS_DROPS); self.update_indirect_neighbour_shapes(old, pos, neighbour_flags, limit - 1); self.update_neighbour_shapes(state, pos, neighbour_flags, limit - 1); self.update_indirect_neighbour_shapes(state, pos, neighbour_flags, limit - 1); @@ -244,7 +275,12 @@ impl Sim<'_, L> { true } /// `LevelChunk.setBlockState`: the previous state when the write happened. - fn chunk_set_block_state(&mut self, pos: BlockPos, state: BlockStateId, update_flags: i32) -> Option { + fn chunk_set_block_state( + &mut self, + pos: BlockPos, + state: BlockStateId, + update_flags: i32, + ) -> Option { let current = self.state(pos); if current == state { return None; @@ -261,7 +297,11 @@ impl Sim<'_, L> { self.remove_moving_piston(pos); } let moved = update_flags & flags::UPDATE_MOVE_BY_PISTON != 0; - if (block_changed || self.b.block_data(new_block).is(super::classes::Class::BaseRail)) + if (block_changed + || self + .b + .block_data(new_block) + .is(super::classes::Class::BaseRail)) && (update_flags & flags::UPDATE_NEIGHBORS != 0 || moved) { self.affect_neighbors_after_removal(old, pos, moved); @@ -304,17 +344,33 @@ impl Sim<'_, L> { } } /// `Block.updateOrDestroy`. - pub fn update_or_destroy(&mut self, old: BlockStateId, new: BlockStateId, pos: BlockPos, update_flags: i32, limit: i32) { + pub fn update_or_destroy( + &mut self, + old: BlockStateId, + new: BlockStateId, + pos: BlockPos, + update_flags: i32, + limit: i32, + ) { if new != old { if self.b.is_air(new) { self.destroy_block(pos, update_flags & flags::UPDATE_SUPPRESS_DROPS == 0, limit); } else { - self.set_block_limit(pos, new, update_flags & !flags::UPDATE_SUPPRESS_DROPS, limit); + self.set_block_limit( + pos, + new, + update_flags & !flags::UPDATE_SUPPRESS_DROPS, + limit, + ); } } } /// `Block.updateFromNeighbourShapes`. - pub fn update_from_neighbour_shapes(&mut self, state: BlockStateId, pos: BlockPos) -> BlockStateId { + pub fn update_from_neighbour_shapes( + &mut self, + state: BlockStateId, + pos: BlockPos, + ) -> BlockStateId { let mut new = state; for direction in UPDATE_SHAPE_ORDER { let neighbour = rel(pos, direction); @@ -324,10 +380,23 @@ impl Sim<'_, L> { new } /// `BlockStateBase.updateNeighbourShapes`. - pub fn update_neighbour_shapes(&mut self, state: BlockStateId, pos: BlockPos, update_flags: i32, limit: i32) { + pub fn update_neighbour_shapes( + &mut self, + state: BlockStateId, + pos: BlockPos, + update_flags: i32, + limit: i32, + ) { for direction in UPDATE_SHAPE_ORDER { let neighbour = rel(pos, direction); - self.neighbor_shape_changed(direction.opposite(), neighbour, pos, state, update_flags, limit); + self.neighbor_shape_changed( + direction.opposite(), + neighbour, + pos, + state, + update_flags, + limit, + ); } } @@ -352,8 +421,19 @@ impl Sim<'_, L> { pub fn neighbor_changed_at(&mut self, pos: BlockPos, block: BlockId) { self.add_and_run(Update::Simple { pos, block }); } - pub fn neighbor_changed_full(&mut self, state: BlockStateId, pos: BlockPos, block: BlockId, moved: bool) { - self.add_and_run(Update::Full { state, pos, block, moved }); + pub fn neighbor_changed_full( + &mut self, + state: BlockStateId, + pos: BlockPos, + block: BlockId, + moved: bool, + ) { + self.add_and_run(Update::Full { + state, + pos, + block, + moved, + }); } pub fn neighbor_shape_changed( &mut self, @@ -429,11 +509,17 @@ impl Sim<'_, L> { if update_flags & flags::UPDATE_SKIP_SHAPE_UPDATE_ON_WIRE == 0 || !self.b.table.is(current, self.b.named.redstone_wire) { - let new = self.update_shape(current, pos, direction, neighbor_pos, neighbor_state); + let new = + self.update_shape(current, pos, direction, neighbor_pos, neighbor_state); self.update_or_destroy(current, new, pos, update_flags, limit); } } - Step::Neighbor { state, pos, block, moved } => { + Step::Neighbor { + state, + pos, + block, + moved, + } => { let state = state.unwrap_or_else(|| self.state(pos)); self.neighbor_changed(state, pos, block, moved); } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLevelShapeOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLevelShapeOracle.java index e0555a4b0..e3ff99b24 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLevelShapeOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLevelShapeOracle.java @@ -28,7 +28,7 @@ import net.minecraft.world.ticks.TickPriority; * through ScheduledTickAccess are recorded instead of queued. */ public final class VanillaLevelShapeOracle { - private static void bindFluidTags(Path dir) throws Exception { + static void bindFluidTags(Path dir) throws Exception { var registry = BuiltInRegistries.FLUID; var loader = new TagLoader>((id, required) -> registry.get(id).map(value -> (Holder) value), "tags/fluid"); var definitions = new HashMap>(); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java index 528b8f893..1d4b3262a 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java @@ -1,100 +1,159 @@ package dev.horizonlab.parity; + import com.google.gson.*; -import com.mojang.serialization.JsonOps; -import java.io.*; -import java.lang.reflect.Proxy; -import java.lang.reflect.InvocationHandler; -import java.nio.charset.StandardCharsets; +import java.io.PrintWriter; +import java.lang.reflect.Method; import java.nio.file.*; import java.util.*; import net.minecraft.core.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.server.level.ServerPlayer; import net.minecraft.util.RandomSource; -import net.minecraft.world.level.*; -import net.minecraft.world.level.biome.*; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.levelgen.*; -import net.minecraft.world.level.levelgen.densityfunction.DensityFunctions; -import net.minecraft.world.level.levelgen.material.rule.BlockRule; -import net.minecraft.world.level.levelgen.placement.*; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.LegacyRandomSource; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.CollisionContext; -/** Original transport invoking actual placement codecs and modifier callbacks. */ +/** + * Native BlockItem placement-state selection (BlockPlaceContext resolution, + * updatePlacementContext and getPlacementState) over generated neighbourhoods. + * Entities never obstruct; nothing is written to the world. + */ public final class VanillaPlacementOracle { - private static final class Stop extends RuntimeException {} - private static PlacementContext context(JsonObject f) {return context(f,null);} - private static PlacementContext context(JsonObject f,PrintWriter out) { - var v=f.getAsJsonArray("context");int min=v.get(0).getAsInt(),height=v.get(1).getAsInt(),sea=v.get(2).getAsInt(); - var zero=DensityFunctions.zero(); - var settings=new NoiseGeneratorSettings(new NoiseSettings(min,height),Blocks.STONE.defaultBlockState(),Blocks.WATER.defaultBlockState(),new NoiseRouter(zero,zero,zero,zero,zero,zero,zero,zero),Holder.direct(new BlockRule(Blocks.STONE.defaultBlockState())),List.of(),sea,false,Optional.empty(),false,NoiseGeneratorSettings.DebugFunctions.EMPTY); - var biome=Holder.Reference.createStandAlone(new HolderOwner(){},Biomes.PLAINS); - var generator=new NoiseBasedChunkGenerator(new FixedBiomeSource(biome),Holder.direct(settings)); - int worldMin=f.has("world_min")?f.get("world_min").getAsInt():min;int mode=f.has("height_mode")?f.get("height_mode").getAsInt():0;int fail=f.has("query_fail")?f.get("query_fail").getAsInt():-1;int[] calls={0};boolean layerWorld=f.has("layer_world")&&f.get("layer_world").getAsBoolean(); - var level=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class[]{WorldGenLevel.class},(proxy,method,args)->switch(method.getName()) { - case "isInsideBuildHeight"->{ - if(args[0] instanceof BlockPos p) { - if(out!=null)out.println("inside "+p.getX()+" "+p.getY()+" "+p.getZ()); - if(calls[0]++==fail)throw new IllegalArgumentException("bounds query failure"); - var result=InvocationHandler.invokeDefault(proxy,method,args); - if(out!=null)out.println("bounds_result "+result);yield result; - } - yield InvocationHandler.invokeDefault(proxy,method,args); - } - case "isOutsideBuildHeight"->{ - if(out!=null)out.println("outside "+args[0]); - if(calls[0]++==fail)throw new IllegalArgumentException("bounds query failure"); - var result=InvocationHandler.invokeDefault(proxy,method,args); - if(out!=null)out.println("bounds_result "+result);yield result; - } - case "getMaxY"->InvocationHandler.invokeDefault(proxy,method,args); - case "getMinY"->worldMin; - case "getHeight"->{ - if(args==null||args.length==0)yield height; - var kind=(Heightmap.Types)args[0];int x=(Integer)args[1],z=(Integer)args[2]; - if(out!=null)out.println("height "+kind.name()+" "+x+" "+z); - if(calls[0]++==fail)throw new IllegalArgumentException("height query failure"); - int result; - if(layerWorld)result=min+24+((x^z)&3); - else if(mode==0)result=min+Math.floorMod(x*31+z*17+kind.ordinal()*7,129)-64; - else {int[] values={Integer.MIN_VALUE,Integer.MAX_VALUE,0,-1,min,min+1};result=values[(kind.ordinal()+((x^z)&3))%6];} - if(out!=null)out.println("height_result "+result);yield result; - } - case "getBlockState"->{ - var p=(BlockPos)args[0];if(out!=null)out.println("block "+p.getX()+" "+p.getY()+" "+p.getZ()); - if(calls[0]++==fail)throw new IllegalArgumentException("block query failure"); - var blocks=new net.minecraft.world.level.block.Block[]{Blocks.BEDROCK,Blocks.STONE,Blocks.AIR,Blocks.WATER,Blocks.DIRT,Blocks.CAVE_AIR,Blocks.LAVA,Blocks.BUBBLE_COLUMN,Blocks.VOID_AIR,Blocks.GRASS_BLOCK,Blocks.AIR,Blocks.WATER}; - int index=p.getY()<=min?0:Math.floorMod(p.getY()-min+((p.getX()*31+p.getZ()*17)&3),12); - var block=blocks[index];if(out!=null)out.println("block_result "+net.minecraft.core.registries.BuiltInRegistries.BLOCK.getKey(block));yield block.defaultBlockState(); - } - case "getSeaLevel"->sea; - default->throw new AssertionError("unexpected world method "+method); - }); - var context=new PlacementContext(level,generator,Optional.empty());return context; + static Object unsafe; + static Method allocate; + static int errors; + static final Set bound = new HashSet<>(); + + static T make(Class type) { + try { + return type.cast(allocate.invoke(unsafe, type)); + } catch (Exception e) { + throw new AssertionError(e); + } } + + static final class FakePlayer extends ServerPlayer { + float yaw, pitch; + boolean sneak; + World world; + ItemStack held; + FakePlayer() { + super(null, null, null, null); + } + @Override public float getViewXRot(final float a) { return pitch; } + @Override public float getViewYRot(final float a) { return yaw; } + @Override public float getXRot() { return pitch; } + @Override public float getYRot() { return yaw; } + @Override public Direction getDirection() { return Direction.fromYRot(yaw); } + @Override public boolean isSecondaryUseActive() { return sneak; } + @Override public boolean isShiftKeyDown() { return sneak; } + @Override public boolean isDescending() { return sneak; } + @Override public ItemStack getMainHandItem() { return held; } + @Override public boolean canUseGameMasterBlocks() { return false; } + @Override public net.minecraft.server.level.ServerLevel level() { return world; } + } + + static final class World extends net.minecraft.server.level.ServerLevel { + Map cells; + RandomSource random; + World() { + super(null, null, null, null, null, null, false, 0L, List.of(), false); + } + @Override public BlockState getBlockState(BlockPos p) { return cells.getOrDefault(p, net.minecraft.world.level.block.Blocks.AIR.defaultBlockState()); } + @Override public FluidState getFluidState(BlockPos p) { return getBlockState(p).getFluidState(); } + @Override public net.minecraft.world.level.block.entity.BlockEntity getBlockEntity(BlockPos p) { return null; } + @Override public boolean isClientSide() { return false; } + @Override public RandomSource getRandom() { return random; } + @Override public int getMinY() { return -64; } + @Override public int getHeight() { return 384; } + @Override public boolean isUnobstructed(BlockState state, BlockPos pos, CollisionContext context) { return true; } + @Override public boolean isUnobstructed(Entity entity) { return true; } + @Override public void scheduleTick(BlockPos pos, Block block, int delay) { } + @Override public net.minecraft.core.RegistryAccess registryAccess() { return RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); } + @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.DEFAULT_FLAGS; } + @Override public net.minecraft.world.level.border.WorldBorder getWorldBorder() { return new net.minecraft.world.level.border.WorldBorder(); } + @Override public void gameEvent(net.minecraft.core.Holder e, BlockPos p, net.minecraft.world.level.gameevent.GameEvent.Context c) { } + @Override public int getSeaLevel() { return 63; } + @Override public int getBrightness(net.minecraft.world.level.LightLayer layer, BlockPos p) { return layer == net.minecraft.world.level.LightLayer.SKY ? 15 : 0; } + @Override public int getRawBrightness(BlockPos p, int darkening) { return 15 - darkening; } + @Override public int getSkyDarken() { return 0; } + @Override public List getEntities(Entity except, net.minecraft.world.phys.AABB box, java.util.function.Predicate filter) { return List.of(); } + } + public static void main(String[] args) throws Exception { - net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]); - try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt"),StandardCharsets.UTF_8))) { - for(var line:Files.readAllLines(dir.resolve("inputs.txt"))) { - var f=JsonParser.parseString(line).getAsJsonObject();var context=context(f,out);long seed=f.get("seed").getAsLong(); - RandomSource random=f.get("legacy").getAsBoolean()?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); - Optional decoded; - try {decoded=PlacementModifier.CODEC.parse(JsonOps.INSTANCE,JsonParser.parseString(f.get("definition").getAsString())).result();}catch(IllegalArgumentException error){decoded=Optional.empty();} - if(decoded.isEmpty())out.println("decode error");else { - out.println("decode ok");var provider=decoded.get(); - for(var value:f.getAsJsonArray("positions")) { - var p=value.getAsJsonArray();var position=new BlockPos(p.get(0).getAsInt(),p.get(1).getAsInt(),p.get(2).getAsInt()); - if(f.has("count_only")&&f.get("count_only").getAsBoolean()) { - try {out.println("count "+((RepeatingPlacement)provider).count(random,position));}catch(IllegalArgumentException error){out.println("count error");} - out.println("next "+random.nextLong());continue; + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + Path resources = Path.of(args[0]); + VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(resources.resolve("block-tags.json"))).getAsJsonObject()); + VanillaLevelShapeOracle.bindFluidTags(resources.resolve("data/minecraft/tags/fluid")); + var position = Entity.class.getDeclaredField("position"); + position.setAccessible(true); + var allocator = Class.forName("sun.misc.Unsafe"); + var field = allocator.getDeclaredField("theUnsafe"); + field.setAccessible(true); + unsafe = field.get(null); + allocate = allocator.getMethod("allocateInstance", Class.class); + Method getPlacementState = BlockItem.class.getDeclaredMethod("getPlacementState", BlockPlaceContext.class); + getPlacementState.setAccessible(true); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2]))); var lines = Files.lines(Path.of(args[1]))) { + for (var line : (Iterable) lines::iterator) { + var f = JsonParser.parseString(line).getAsJsonObject(); + var world = make(World.class); + world.cells = new HashMap<>(); + for (var cell : f.getAsJsonArray("cells")) { + var c = cell.getAsJsonArray(); + world.cells.put(new BlockPos(c.get(0).getAsInt(), c.get(1).getAsInt(), c.get(2).getAsInt()), Block.stateById(c.get(3).getAsInt())); + } + world.random = new LegacyRandomSource(f.get("seed").getAsLong()); + var player = make(FakePlayer.class); + player.world = world; + player.yaw = f.get("yaw").getAsFloat(); + player.pitch = f.get("pitch").getAsFloat(); + player.sneak = f.get("sneak").getAsBoolean(); + position.set(player, Vec3.ZERO); + var item = (BlockItem) BuiltInRegistries.ITEM.getValue(Identifier.parse(f.get("item").getAsString())); + if (bound.add(item)) { + item.builtInRegistryHolder().bindComponents(net.minecraft.core.component.DataComponentMap.EMPTY); + } + var h = f.getAsJsonArray("hit"); + var p = f.getAsJsonArray("pos"); + var hit = new BlockHitResult(new Vec3(h.get(0).getAsDouble(), h.get(1).getAsDouble(), h.get(2).getAsDouble()), + Direction.from3DDataValue(f.get("face").getAsInt()), new BlockPos(p.get(0).getAsInt(), p.get(1).getAsInt(), p.get(2).getAsInt()), false); + String result; + try { + player.held = new ItemStack(item); + var context = new BlockPlaceContext(player, InteractionHand.MAIN_HAND, player.held, hit); + if (!context.canPlace()) { + result = "none"; + } else { + var updated = item.updatePlacementContext(context); + if (updated == null) { + result = "none"; + } else { + var state = (BlockState) getPlacementState.invoke(item, updated); + var at = updated.getClickedPos(); + result = state == null ? "none" : at.getX() + "," + at.getY() + "," + at.getZ() + " " + Block.getId(state); } - int[] count={0};int fail=f.get("fail").getAsInt();boolean draw=f.get("draw").getAsBoolean(); - try {provider.modify(context,random,position,result->{ - if(count[0]++==fail)throw new Stop(); - out.println("position "+result.getX()+" "+result.getY()+" "+result.getZ()); - if(draw)out.println("consumer "+random.nextLong()); - });out.println("modify ok");}catch(Stop|IllegalArgumentException error){out.println("modify error");} - out.println("next "+random.nextLong()); + } + } catch (Exception | AssertionError e) { + Throwable cause = e instanceof java.lang.reflect.InvocationTargetException ite ? ite.getCause() : e; + result = "error " + cause.getClass().getSimpleName(); + if (errors++ < 3) { + cause.printStackTrace(); } } - out.println("tail "+random.nextLong()); + out.println("place " + result); } } } diff --git a/tools/test_level_place_parity.py b/tools/test_level_place_parity.py new file mode 100644 index 000000000..53b51007b --- /dev/null +++ b/tools/test_level_place_parity.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Compare horizon-world's placement port (BlockItem placement state) with pinned vanilla. + +Generates random neighbourhoods and use-item-on-block actions for random block +items, resolves the placed position and state with the native oracle +(VanillaPlacementOracle) and with Behaviours (level_place_fixture), and reports +differing cases grouped by item. +""" +import argparse +import json +import os +import random +import subprocess +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + +# Items whose placement reads block-entity data or entities. +SKIP = {'minecraft:lectern', 'minecraft:test_block', 'minecraft:moving_piston'} + + +def generate(resources, count, seed): + facts = json.loads((resources / 'facts.json').read_text()) + behaviours = json.loads((resources / 'block-behaviours.json').read_text()) + by_block = {} + for index, state in enumerate(facts['states']): + by_block.setdefault(state[0], []).append(index) + items = sorted(name for name, item in behaviours['items'].items() if name not in SKIP and item['fields'].get('block') in by_block) + names = list(by_block) + common = [by_block[name][0] for name in ['minecraft:stone', 'minecraft:dirt', 'minecraft:grass_block', 'minecraft:water', + 'minecraft:oak_planks', 'minecraft:glass', 'minecraft:sand', 'minecraft:oak_log']] + rng = random.Random(seed) + cases = [] + for _ in range(count): + item = rng.choice(items) + block = behaviours['items'][item]['fields']['block'] + related = by_block[block] + cells = [] + for x in range(-2, 3): + for y in range(-2, 3): + for z in range(-2, 3): + roll = rng.random() + if (x, y, z) == (0, 0, 0): + roll = rng.random() * 1.2 + if roll < 0.35: + continue + if roll < 0.6: + cells.append([x, y, z, rng.choice(common)]) + elif roll < 0.8: + cells.append([x, y, z, rng.choice(related)]) + else: + cells.append([x, y, z, rng.choice(by_block[rng.choice(names)])]) + face = rng.randrange(6) + normal = [(0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1), (-1, 0, 0), (1, 0, 0)][face] + hit = [] + for axis in range(3): + if normal[axis] < 0: + hit.append(0.0) + elif normal[axis] > 0: + hit.append(1.0) + else: + hit.append(rng.choice([0.5, rng.random()])) + cases.append({'seed': rng.randrange(1 << 40), 'item': item, 'pos': [0, 0, 0], 'face': face, 'hit': hit, + 'yaw': rng.randrange(-180 * 64, 180 * 64) / 64, 'pitch': rng.randrange(-90 * 64, 90 * 64) / 64, + 'sneak': rng.random() < 0.2, 'cells': cells}) + return cases + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--count', type=int, default=20000) + parser.add_argument('--seed', type=int, default=1) + args = parser.parse_args() + lock, jars, libraries = base.verify_artifacts() + resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version'] + work = lab.LOCAL / 'level-place-parity' + work.mkdir(parents=True, exist_ok=True) + cases = generate(resources, args.count, args.seed) + (work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in cases)) + classes = work / 'classes' + classes.mkdir(exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + parity = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' + sources = [parity / 'VanillaPlacementOracle.java', parity / 'VanillaHeightmapOracle.java', parity / 'VanillaLevelShapeOracle.java'] + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-cp', dependencies, + '-d', str(classes), *map(str, sources)], check=True) + subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.VanillaPlacementOracle', str(resources), str(work / 'cases.jsonl'), + str(work / 'native.txt')], check=True) + subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'level_place_fixture', '--', + str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT) + native = (work / 'native.txt').read_text().splitlines() + rust = (work / 'rust.txt').read_text().splitlines() + differences = {} + for case, a, b in zip(cases, native, rust): + if a != b: + differences.setdefault(case['item'], []).append((case, a, b)) + total = sum(len(v) for v in differences.values()) + facts = json.loads((resources / 'facts.json').read_text())['states'] + def describe(line): + parts = line.split() + return line if len(parts) < 3 or not parts[2].isdigit() else f'{parts[1]} {facts[int(parts[2])][3]}' + for item, entries in sorted(differences.items(), key=lambda entry: -len(entry[1])): + case, a, b = entries[0] + print(f'{item}: {len(entries)} differing; e.g. face={case["face"]} yaw={case["yaw"]} pitch={case["pitch"]} sneak={case["sneak"]}' + f'\n native {describe(a)}\n rust {describe(b)}') + print(f'{len(cases) - total}/{len(cases)} cases match') + (work / 'differences.json').write_text(json.dumps({k: [[c, a, b] for c, a, b in v[:5]] for k, v in differences.items()})) + raise SystemExit(1 if total else 0) + + +if __name__ == '__main__': + main()