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 new file mode 100644 index 000000000..1e4909928 --- /dev/null +++ b/crates/horizon-world/examples/level_shape_fixture.rs @@ -0,0 +1,147 @@ +//! Rust side of `tools/test_level_shape_parity.py`: evaluates +//! `Behaviours::update_shape` and `can_survive` for generated neighbourhoods. +use horizon_core::{ + geometry::Direction, + position::{BlockPos, ChunkPos}, + random::LegacyRandom, +}; +use horizon_world::{ + level::{Behaviours, LevelAccess, Ticks, data::load_registry}, + registry::BlockStateId, +}; +use serde_json::Value; +use std::{ + collections::{BTreeSet, HashMap}, + io::{BufRead, Write}, + path::Path, +}; + +struct Cells { + cells: HashMap, + air: BlockStateId, + random: LegacyRandom, + light: i32, +} +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 sky_light(&self, _pos: BlockPos) -> i32 { + self.light + } +} + +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()), + light: case["light"].as_i64().unwrap() as i32, + }; + 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 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 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 + .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 + )); + } + } + } + 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(" ") + )?; + } + Ok(()) +} diff --git a/crates/horizon-world/src/fluid.rs b/crates/horizon-world/src/fluid.rs index 4e08a5145..4a89764a8 100644 --- a/crates/horizon-world/src/fluid.rs +++ b/crates/horizon-world/src/fluid.rs @@ -127,6 +127,17 @@ impl FluidState { } serde_json::to_string(&value).map_err(|e| invalid(e.to_string())) } + /// A fluid state from its parts; the empty fluid ignores amount and falling. + pub const fn new(kind: FluidKind, amount: u8, falling: bool) -> Self { + if matches!(kind, FluidKind::Empty) { + return Self::EMPTY; + } + Self { + kind, + amount, + falling, + } + } pub const EMPTY: Self = Self { kind: FluidKind::Empty, amount: 0, diff --git a/crates/horizon-world/src/level/classes.rs b/crates/horizon-world/src/level/classes.rs new file mode 100644 index 000000000..9540a5a47 --- /dev/null +++ b/crates/horizon-world/src/level/classes.rs @@ -0,0 +1,341 @@ +//! Vanilla block classes recognised by Horizon's behaviour port. +//! +//! Each block's exported class chain (most derived first) is matched against +//! this list: `class` is the most derived recognised class (it selects the +//! ported overrides), and `instance_of` answers Java `instanceof` checks such +//! as `state.getBlock() instanceof LeavesBlock` for any recognised ancestor. + +macro_rules! classes { + ($($name:ident = $java:literal,)*) => { + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + #[repr(u16)] + pub enum Class { $($name,)* } + impl Class { + pub const ALL: &'static [Class] = &[$(Class::$name,)*]; + pub fn from_java(name: &str) -> Option { + match name { $($java => Some(Class::$name),)* _ => None } + } + pub const fn java_name(self) -> &'static str { + match self { $(Class::$name => $java,)* } + } + } + }; +} + +classes! { + Block = "Block", + Air = "AirBlock", + AmethystCluster = "AmethystClusterBlock", + Anvil = "AnvilBlock", + AttachedStem = "AttachedStemBlock", + Azalea = "AzaleaBlock", + BambooSapling = "BambooSaplingBlock", + BambooStalk = "BambooStalkBlock", + AbstractBanner = "AbstractBannerBlock", + Banner = "BannerBlock", + WallBanner = "WallBannerBlock", + Barrel = "BarrelBlock", + BaseCoralPlantType = "BaseCoralPlantTypeBlock", + BaseCoralPlant = "BaseCoralPlantBlock", + BaseCoralFan = "BaseCoralFanBlock", + BaseCoralWallFan = "BaseCoralWallFanBlock", + CoralPlant = "CoralPlantBlock", + CoralFan = "CoralFanBlock", + CoralWallFan = "CoralWallFanBlock", + Coral = "CoralBlock", + BaseEntity = "BaseEntityBlock", + BaseFire = "BaseFireBlock", + Fire = "FireBlock", + SoulFire = "SoulFireBlock", + BasePressurePlate = "BasePressurePlateBlock", + PressurePlate = "PressurePlateBlock", + WeightedPressurePlate = "WeightedPressurePlateBlock", + BaseRail = "BaseRailBlock", + Rail = "RailBlock", + PoweredRail = "PoweredRailBlock", + DetectorRail = "DetectorRailBlock", + BaseTorch = "BaseTorchBlock", + Torch = "TorchBlock", + WallTorch = "WallTorchBlock", + RedstoneTorch = "RedstoneTorchBlock", + RedstoneWallTorch = "RedstoneWallTorchBlock", + AbstractBed = "AbstractBedBlock", + Bed = "BedBlock", + StrawBed = "StrawBedBlock", + Beehive = "BeehiveBlock", + Beetroot = "BeetrootBlock", + Bell = "BellBlock", + BigDripleaf = "BigDripleafBlock", + BigDripleafStem = "BigDripleafStemBlock", + BonemealableFeaturePlacer = "BonemealableFeaturePlacerBlock", + BubbleColumn = "BubbleColumnBlock", + BuddingAmethyst = "BuddingAmethystBlock", + Bush = "BushBlock", + Button = "ButtonBlock", + Cactus = "CactusBlock", + CactusFlower = "CactusFlowerBlock", + Cake = "CakeBlock", + Campfire = "CampfireBlock", + AbstractCandle = "AbstractCandleBlock", + Candle = "CandleBlock", + CandleCake = "CandleCakeBlock", + Carpet = "CarpetBlock", + WoolCarpet = "WoolCarpetBlock", + MossyCarpet = "MossyCarpetBlock", + Carrot = "CarrotBlock", + CarvedPumpkin = "CarvedPumpkinBlock", + AbstractCauldron = "AbstractCauldronBlock", + Cauldron = "CauldronBlock", + LavaCauldron = "LavaCauldronBlock", + LayeredCauldron = "LayeredCauldronBlock", + GrowingPlant = "GrowingPlantBlock", + GrowingPlantHead = "GrowingPlantHeadBlock", + GrowingPlantBody = "GrowingPlantBodyBlock", + CaveVines = "CaveVinesBlock", + CaveVinesPlant = "CaveVinesPlantBlock", + Kelp = "KelpBlock", + KelpPlant = "KelpPlantBlock", + TwistingVines = "TwistingVinesBlock", + TwistingVinesPlant = "TwistingVinesPlantBlock", + WeepingVines = "WeepingVinesBlock", + WeepingVinesPlant = "WeepingVinesPlantBlock", + Sign = "SignBlock", + StandingSign = "StandingSignBlock", + WallSign = "WallSignBlock", + CeilingHangingSign = "CeilingHangingSignBlock", + WallHangingSign = "WallHangingSignBlock", + RotatedPillar = "RotatedPillarBlock", + Chain = "ChainBlock", + AbstractChest = "AbstractChestBlock", + Chest = "ChestBlock", + TrappedChest = "TrappedChestBlock", + CopperChest = "CopperChestBlock", + EnderChest = "EnderChestBlock", + ChiseledBookShelf = "ChiseledBookShelfBlock", + ChorusFlower = "ChorusFlowerBlock", + ChorusPlant = "ChorusPlantBlock", + Pipe = "PipeBlock", + Cocoa = "CocoaBlock", + FallingBlock = "FallingBlock", + ColoredFalling = "ColoredFallingBlock", + Sand = "SandBlock", + ConcretePowder = "ConcretePowderBlock", + DragonEgg = "DragonEggBlock", + Comparator = "ComparatorBlock", + Repeater = "RepeaterBlock", + Diode = "DiodeBlock", + Composter = "ComposterBlock", + CopperBulb = "CopperBulbBlock", + Crafter = "CrafterBlock", + CraftingTable = "CraftingTableBlock", + CreakingHeart = "CreakingHeartBlock", + Crop = "CropBlock", + CrossCollision = "CrossCollisionBlock", + DaylightDetector = "DaylightDetectorBlock", + DecoratedPot = "DecoratedPotBlock", + Directional = "DirectionalBlock", + Dispenser = "DispenserBlock", + Dropper = "DropperBlock", + Door = "DoorBlock", + DoublePlant = "DoublePlantBlock", + DriedGhast = "DriedGhastBlock", + DropExperience = "DropExperienceBlock", + DryVegetation = "DryVegetationBlock", + ShortDryGrass = "ShortDryGrassBlock", + TallDryGrass = "TallDryGrassBlock", + EndPortalFrame = "EndPortalFrameBlock", + Rod = "RodBlock", + EndRod = "EndRodBlock", + LightningRod = "LightningRodBlock", + Flower = "FlowerBlock", + Eyeblossom = "EyeblossomBlock", + WitherRose = "WitherRoseBlock", + FaceAttachedHorizontalDirectional = "FaceAttachedHorizontalDirectionalBlock", + Farmland = "FarmlandBlock", + Fence = "FenceBlock", + FenceGate = "FenceGateBlock", + FireflyBush = "FireflyBushBlock", + FlowerBed = "FlowerBedBlock", + FlowerPot = "FlowerPotBlock", + Frogspawn = "FrogspawnBlock", + Ice = "IceBlock", + FrostedIce = "FrostedIceBlock", + AbstractFurnace = "AbstractFurnaceBlock", + GlazedTerracotta = "GlazedTerracottaBlock", + Multiface = "MultifaceBlock", + MultifaceSpreadeable = "MultifaceSpreadeableBlock", + GlowLichen = "GlowLichenBlock", + SculkVein = "SculkVeinBlock", + Snowy = "SnowyBlock", + SpreadingSnowy = "SpreadingSnowyBlock", + Grass = "GrassBlock", + Mycelium = "MyceliumBlock", + Grindstone = "GrindstoneBlock", + HalfTransparent = "HalfTransparentBlock", + HangingMoss = "HangingMossBlock", + HangingRoots = "HangingRootsBlock", + Hay = "HayBlock", + Hopper = "HopperBlock", + HorizontalDirectional = "HorizontalDirectionalBlock", + HugeMushroom = "HugeMushroomBlock", + Infested = "InfestedBlock", + InfestedRotatedPillar = "InfestedRotatedPillarBlock", + IronBars = "IronBarsBlock", + StainedGlassPane = "StainedGlassPaneBlock", + Jukebox = "JukeboxBlock", + Ladder = "LadderBlock", + Lantern = "LanternBlock", + LeafLitter = "LeafLitterBlock", + Leaves = "LeavesBlock", + MangroveLeaves = "MangroveLeavesBlock", + Lectern = "LecternBlock", + Lever = "LeverBlock", + Light = "LightBlock", + LilyPad = "LilyPadBlock", + Liquid = "LiquidBlock", + Loom = "LoomBlock", + Magma = "MagmaBlock", + MangrovePropagule = "MangrovePropaguleBlock", + MangroveRoots = "MangroveRootsBlock", + MovingPiston = "MovingPistonBlock", + Mud = "MudBlock", + Mushroom = "MushroomBlock", + NetherFungus = "NetherFungusBlock", + NetherPortal = "NetherPortalBlock", + NetherRoots = "NetherRootsBlock", + NetherSprouts = "NetherSproutsBlock", + NetherWart = "NetherWartBlock", + Note = "NoteBlock", + Nylium = "NyliumBlock", + Observer = "ObserverBlock", + Path = "PathBlock", + AbstractSkull = "AbstractSkullBlock", + Skull = "SkullBlock", + WallSkull = "WallSkullBlock", + PistonBase = "PistonBaseBlock", + PistonHead = "PistonHeadBlock", + PitcherCrop = "PitcherCropBlock", + Speleothem = "SpeleothemBlock", + PointedDripstone = "PointedDripstoneBlock", + SulfurSpike = "SulfurSpikeBlock", + Potato = "PotatoBlock", + PowderSnow = "PowderSnowBlock", + Powered = "PoweredBlock", + Pumpkin = "PumpkinBlock", + RedStoneOre = "RedStoneOreBlock", + RedstoneLamp = "RedstoneLampBlock", + RedstoneWire = "RedstoneWireBlock", + RespawnAnchor = "RespawnAnchorBlock", + RootedDirt = "RootedDirtBlock", + Sapling = "SaplingBlock", + Scaffolding = "ScaffoldingBlock", + SculkSensor = "SculkSensorBlock", + CalibratedSculkSensor = "CalibratedSculkSensorBlock", + SculkShrieker = "SculkShriekerBlock", + SeaPickle = "SeaPickleBlock", + Seagrass = "SeagrassBlock", + Shelf = "ShelfBlock", + ShelfMushroom = "ShelfMushroomBlock", + ShulkerBox = "ShulkerBoxBlock", + Slab = "SlabBlock", + SmallDripleaf = "SmallDripleafBlock", + SnifferEgg = "SnifferEggBlock", + SnowLayer = "SnowLayerBlock", + SoulSand = "SoulSandBlock", + Sponge = "SpongeBlock", + WetSponge = "WetSpongeBlock", + SporeBlossom = "SporeBlossomBlock", + Stair = "StairBlock", + Stem = "StemBlock", + Stonecutter = "StonecutterBlock", + SugarCane = "SugarCaneBlock", + SweetBerryBush = "SweetBerryBushBlock", + TallFlower = "TallFlowerBlock", + TallGrass = "TallGrassBlock", + TallSeagrass = "TallSeagrassBlock", + Target = "TargetBlock", + Tnt = "TntBlock", + TorchflowerCrop = "TorchflowerCropBlock", + TrapDoor = "TrapDoorBlock", + TripWire = "TripWireBlock", + TripWireHook = "TripWireHookBlock", + TurtleEgg = "TurtleEggBlock", + Vegetation = "VegetationBlock", + Vine = "VineBlock", + Wall = "WallBlock", + WaterloggedTransparent = "WaterloggedTransparentBlock", + WeatheringCopperFull = "WeatheringCopperFullBlock", + Web = "WebBlock", + CopperGolemStatue = "CopperGolemStatueBlock", + Beacon = "BeaconBlock", + BrewingStand = "BrewingStandBlock", + Brushable = "BrushableBlock", + Conduit = "ConduitBlock", + EnchantingTable = "EnchantingTableBlock", + EndGateway = "EndGatewayBlock", + EndPortal = "EndPortalBlock", + Spawner = "SpawnerBlock", + TrialSpawner = "TrialSpawnerBlock", + Vault = "VaultBlock", + Barrier = "BarrierBlock", + StructureVoid = "StructureVoidBlock", + Command = "CommandBlock", + Structure = "StructureBlock", + Jigsaw = "JigsawBlock", + SmithingTable = "SmithingTableBlock", + CartographyTable = "CartographyTableBlock", + Netherrack = "NetherrackBlock", + Sculk = "SculkBlock", + SculkCatalyst = "SculkCatalystBlock", + PotentSulfur = "PotentSulfurBlock", + Honey = "HoneyBlock", + Slime = "SlimeBlock", + HeavyCore = "HeavyCoreBlock", + CryingObsidian = "CryingObsidianBlock", +} + +/// Java interfaces Horizon's port consults through `instanceof`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum Interface { + SimpleWaterlogged, + LiquidBlockContainer, + BucketPickup, + Bonemealable, + Fallable, + Entity, + WeatheringCopper, + CaveVines, +} +impl Interface { + pub fn from_java(name: &str) -> Option { + Some(match name { + "SimpleWaterloggedBlock" => Self::SimpleWaterlogged, + "LiquidBlockContainer" => Self::LiquidBlockContainer, + "BucketPickup" => Self::BucketPickup, + "BonemealableBlock" => Self::Bonemealable, + "Fallable" => Self::Fallable, + "EntityBlock" => Self::Entity, + "WeatheringCopper" => Self::WeatheringCopper, + "CaveVines" => Self::CaveVines, + _ => return None, + }) + } + pub const fn mask(self) -> u16 { + 1 << self as u8 + } +} + +/// Set of recognised classes in one block's chain. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ClassSet([u64; 5]); +impl ClassSet { + pub fn insert(&mut self, class: Class) { + let i = class as usize; + self.0[i / 64] |= 1 << (i % 64); + } + pub fn contains(self, class: Class) -> bool { + let i = class as usize; + self.0[i / 64] & (1 << (i % 64)) != 0 + } +} diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs new file mode 100644 index 000000000..854248aa7 --- /dev/null +++ b/crates/horizon-world/src/level/data.rs @@ -0,0 +1,1129 @@ +//! Behaviour tables built once from the pinned client resources. +use super::{ + Behaviours, + classes::{Class, ClassSet, Interface}, + states::{BlockId, PropKey, StateTable}, +}; +use crate::{ + collision::CachedCollisionRegistry, + compression::invalid, + fluid::{FluidBlockBindings, FluidKind, FluidState}, + nbt::{self, Limits}, + registry::{BlockRegistry, BlockStateId}, + worldgen::tags::TagDefinitions, +}; +use horizon_core::geometry::{Aabb, Direction, ShapeOp, Vec3, VoxelShape}; +use serde_json::Value; +use std::{ + collections::HashMap, + fs::{self, File}, + io::{self, BufReader}, + path::Path, + sync::Arc, +}; + +/// Per-state flags read from vanilla accessors over an empty level. +pub mod state_flags { + pub const SOLID: u32 = 1; + pub const AIR: u32 = 1 << 1; + pub const CONDUCTOR: u32 = 1 << 2; + pub const SIGNAL_SOURCE: u32 = 1 << 3; + pub const ANALOG_OUTPUT: u32 = 1 << 4; + pub const COLLISION_EMPTY: u32 = 1 << 5; + pub const SUFFOCATING: u32 = 1 << 6; + pub const REPLACEABLE: u32 = 1 << 7; + pub const RANDOM_TICKS: u32 = 1 << 8; + pub const SOLID_RENDER: u32 = 1 << 9; + pub const LIQUID: u32 = 1 << 10; + pub const BLOCK_ENTITY: u32 = 1 << 11; + pub const IGNITED_BY_LAVA: u32 = 1 << 12; + pub const CAN_OCCLUDE: u32 = 1 << 13; + pub const FULL_COLLISION: u32 = 1 << 14; + pub const SKYLIGHT_DOWN: u32 = 1 << 15; + pub const REQUIRES_TOOL: u32 = 1 << 16; + pub const SHAPE_OCCLUSION: u32 = 1 << 17; +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PushReaction { + PushPull, + Push, + Popped, + Immoveable, + IgnoreEntity, +} + +#[derive(Clone, Copy, Debug)] +pub struct StateFacts { + pub flags: u32, + /// isFaceSturdy bits: support type (FULL, CENTER, RIGID) * 6 + direction. + pub sturdy: u32, + /// getSignal / getDirectSignal over an empty level, 4 bits per direction. + pub weak: u32, + pub strong: u32, + pub fluid: FluidState, + pub emission: u8, + pub dampening: u8, + pub hardness: f32, + pub push: PushReaction, + pub instrument: u8, + /// Index into `Behaviours::shapes`, or -1 for an uncached (dynamic) shape. + pub shape: i32, +} + +#[derive(Clone, Debug)] +pub struct SetType { + pub name: Box, + pub can_open_by_hand: bool, + pub can_open_by_wind_charge: bool, + pub arrows: bool, + /// true: MOBS sensitivity (living entities only); false: EVERYTHING. + pub mobs_only: bool, + pub door_open: Arc, + pub door_close: Arc, + pub trapdoor_open: Arc, + pub trapdoor_close: Arc, + pub plate_on: Arc, + pub plate_off: Arc, + pub button_on: Arc, + pub button_off: Arc, +} + +#[derive(Clone, Debug)] +pub struct Sounds { + pub volume: f32, + pub pitch: f32, + pub place: Arc, + pub break_: Arc, + pub fall: Arc, +} + +/// Precomputed queries over one cached collision shape. +#[derive(Clone, Copy, Debug, Default)] +pub struct ShapeInfo { + /// `Block.isFaceFull(shape, direction)` per direction bit. + pub full_faces: u8, + /// `!shape.getFaceShape(direction).isEmpty()` per direction bit. + pub nonempty_faces: u8, + /// WallBlock `isCovered(shape.getFaceShape(DOWN), test)` for the post (bit 0) + /// and the north/east/south/west wall tests (bits 1..=4). + pub wall_cover: u8, +} + +pub(crate) fn analyse_shape(shape: &VoxelShape) -> io::Result { + let err = |e: horizon_core::geometry::ShapeError| invalid(e.to_string()); + let mut info = ShapeInfo::default(); + let block = VoxelShape::block(); + for direction in Direction::ALL { + let face = shape.face_shape(direction).map_err(err)?; + if !block.join_is_not_empty(&face, ShapeOp::XOR).map_err(err)? { + info.full_faces |= 1 << direction as u8; + } + if !face.is_empty() { + info.nonempty_faces |= 1 << direction as u8; + } + } + let above = shape.face_shape(Direction::Down).map_err(err)?; + let px = |v: f64| v / 16.0; + let tests = [ + (7.0, 7.0, 9.0, 9.0), + (7.0, 0.0, 9.0, 9.0), + (7.0, 7.0, 16.0, 9.0), + (7.0, 7.0, 9.0, 16.0), + (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)? + { + info.wall_cover |= 1 << bit; + } + } + Ok(info) +} + +/// Fluid tags as masks over `FluidKind::mask`. +#[derive(Clone, Copy, Debug, Default)] +pub struct FluidTags { + pub water: u8, + pub lava: u8, + pub supports_frogspawn: u8, + pub supports_lily_pad: u8, + pub supports_sugar_cane_adjacently: u8, + pub bubble_column_can_occupy: u8, +} + +/// A set of blocks (a resolved block tag). +#[derive(Clone, Debug, Default)] +pub struct BlockSet(Vec); +impl BlockSet { + pub fn with_capacity(blocks: usize) -> Self { + Self(vec![0; blocks.div_ceil(64)]) + } + pub fn insert(&mut self, block: BlockId) { + let i = block.0 as usize; + if i / 64 >= self.0.len() { + self.0.resize(i / 64 + 1, 0); + } + self.0[i / 64] |= 1 << (i % 64); + } + pub fn contains(&self, block: BlockId) -> bool { + let i = block.0 as usize; + self.0.get(i / 64).is_some_and(|w| w & (1 << (i % 64)) != 0) + } +} + +#[derive(Clone, Debug)] +pub struct BlockData { + pub class: Class, + /// Recognised classes of the Java class chain, most derived first; ported + /// overrides dispatch along it so `super` calls reach the next override. + pub chain: Vec, + pub classes: ClassSet, + pub interfaces: u16, + pub set_type: Option>, + pub gate_open: Option>, + pub gate_close: Option>, + pub open_sound: Option>, + pub close_sound: Option>, + pub ticks_to_stay_pressed: i32, + pub max_weight: i32, + /// Block-valued configuration: concrete (powder), fruit (stems), potted + /// content, dead coral, stair base, candle (candle cakes), required nylium. + pub link: Option, + /// Second block link: attached stem (stems) or stem (attached stems). + pub link2: Option, + pub support_tag: Option>, + pub support_tag2: Option>, + pub feature: Option>, + pub grow_probability: f64, + pub growth_direction: Direction, + pub schedule_fluid_ticks: bool, + pub weather: u8, + pub ignite_odds: i32, + pub burn_odds: i32, + pub sounds: Arc, + pub item: Arc, + pub dynamic_shape: bool, +} +impl BlockData { + pub fn is(&self, class: Class) -> bool { + self.class == class || self.classes.contains(class) + } + pub fn implements(&self, interface: Interface) -> bool { + self.interfaces & interface.mask() != 0 + } +} + +/// Item-to-block placement bindings (BlockItem and its subclasses). +#[derive(Clone, Debug)] +pub struct ItemBinding { + pub block: BlockId, + pub wall_block: Option, + /// 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 { + Block, + DoubleHigh, + StandingAndWall, + Scaffolding, + PlaceOnWater, + HangingSign, + SolidBucket, + Other, +} + +macro_rules! named_blocks { + ($($field:ident = $name:literal,)*) => { + /// Blocks referenced by identity in vanilla code (`Blocks.X`). + #[derive(Clone, Copy, Debug)] + pub struct Named { $(pub $field: BlockId,)* } + impl Named { + fn resolve(table: &StateTable) -> io::Result { + Ok(Self { $($field: table.block_by_name(concat!("minecraft:", $name)).ok_or_else(|| invalid(concat!("missing block ", $name)))?,)* }) + } + } + }; +} +named_blocks! { + air = "air", + cave_air = "cave_air", + void_air = "void_air", + water = "water", + lava = "lava", + stone = "stone", + cobblestone = "cobblestone", + obsidian = "obsidian", + basalt = "basalt", + soul_soil = "soul_soil", + blue_ice = "blue_ice", + ice = "ice", + frosted_ice = "frosted_ice", + snow = "snow", + snow_block = "snow_block", + powder_snow = "powder_snow", + dirt = "dirt", + grass_block = "grass_block", + mycelium = "mycelium", + podzol = "podzol", + farmland = "farmland", + dirt_path = "dirt_path", + mud = "mud", + clay = "clay", + sponge = "sponge", + wet_sponge = "wet_sponge", + fire = "fire", + soul_fire = "soul_fire", + redstone_wire = "redstone_wire", + comparator = "comparator", + repeater = "repeater", + redstone_torch = "redstone_torch", + redstone_wall_torch = "redstone_wall_torch", + redstone_block = "redstone_block", + redstone_lamp = "redstone_lamp", + observer = "observer", + piston = "piston", + sticky_piston = "sticky_piston", + piston_head = "piston_head", + moving_piston = "moving_piston", + tnt = "tnt", + magma_block = "magma_block", + soul_sand = "soul_sand", + bubble_column = "bubble_column", + kelp = "kelp", + kelp_plant = "kelp_plant", + seagrass = "seagrass", + tall_seagrass = "tall_seagrass", + cactus = "cactus", + cactus_flower = "cactus_flower", + sugar_cane = "sugar_cane", + bamboo = "bamboo", + bamboo_sapling = "bamboo_sapling", + scaffolding = "scaffolding", + melon = "melon", + pumpkin = "pumpkin", + carved_pumpkin = "carved_pumpkin", + jack_o_lantern = "jack_o_lantern", + barrier = "barrier", + cake = "cake", + flower_pot = "flower_pot", + cauldron = "cauldron", + water_cauldron = "water_cauldron", + lava_cauldron = "lava_cauldron", + powder_snow_cauldron = "powder_snow_cauldron", + dragon_egg = "dragon_egg", + tripwire = "tripwire", + tripwire_hook = "tripwire_hook", + slime_block = "slime_block", + honey_block = "honey_block", + hopper = "hopper", + note_block = "note_block", + chorus_plant = "chorus_plant", + chorus_flower = "chorus_flower", + end_stone = "end_stone", + vine = "vine", + lily_pad = "lily_pad", + small_dripleaf = "small_dripleaf", + big_dripleaf = "big_dripleaf", + big_dripleaf_stem = "big_dripleaf_stem", + pointed_dripstone = "pointed_dripstone", + ladder = "ladder", + sweet_berry_bush = "sweet_berry_bush", + torchflower = "torchflower", + pitcher_plant = "pitcher_plant", + pitcher_crop = "pitcher_crop", + moss_block = "moss_block", + short_grass = "short_grass", + tall_grass = "tall_grass", + fern = "fern", + large_fern = "large_fern", + dead_bush = "dead_bush", + netherrack = "netherrack", + soul_campfire = "soul_campfire", + campfire = "campfire", + light = "light", + sculk_sensor = "sculk_sensor", + lectern = "lectern", + target = "target", + daylight_detector = "daylight_detector", + lever = "lever", + beehive = "beehive", + bee_nest = "bee_nest", + composter = "composter", + respawn_anchor = "respawn_anchor", + end_portal_frame = "end_portal_frame", + crafter = "crafter", + copper_bulb = "copper_bulb", + glow_lichen = "glow_lichen", + hanging_roots = "hanging_roots", + mangrove_roots = "mangrove_roots", + big_dripleaf_fallback = "big_dripleaf", + nether_portal = "nether_portal", + frogspawn = "frogspawn", + turtle_egg = "turtle_egg", + sniffer_egg = "sniffer_egg", + sea_pickle = "sea_pickle", + coarse_dirt = "coarse_dirt", + rooted_dirt = "rooted_dirt", + crimson_nylium = "crimson_nylium", + warped_nylium = "warped_nylium", +} + +macro_rules! tags { + ($($field:ident = $name:literal,)*) => { + /// Block tags consulted by ported behaviour. + #[derive(Clone, Debug, Default)] + pub struct Tags { $(pub $field: Arc,)* } + impl Tags { + fn resolve(all: &HashMap>) -> Self { + Self { $($field: all.get(concat!("minecraft:", $name)).cloned().unwrap_or_default(),)* } + } + } + }; +} +tags! { + leaves = "leaves", + logs = "logs", + prevents_nearby_leaf_decay = "prevents_nearby_leaf_decay", + walls = "walls", + fences = "fences", + wooden_fences = "wooden_fences", + fence_gates = "fence_gates", + stairs = "stairs", + slabs = "slabs", + doors = "doors", + trapdoors = "trapdoors", + rails = "rails", + beds = "beds", + wall_post_override = "wall_post_override", + replaceable = "replaceable", + dirt = "dirt", + sand = "sand", + ice = "ice", + snow = "snow", + infiniburn_overworld = "infiniburn_overworld", + infiniburn_nether = "infiniburn_nether", + infiniburn_end = "infiniburn_end", + soul_fire_base_blocks = "soul_fire_base_blocks", + washed_away_by_fluids = "washed_away_by_fluids", + blocks_fluid_flow = "blocks_fluid_flow", + blocks_motion = "blocks_motion", + unstable_bottom_center = "unstable_bottom_center", + cannot_support_snow_layer = "cannot_support_snow_layer", + support_override_snow_layer = "support_override_snow_layer", + maintains_farmland = "maintains_farmland", + supports_vegetation = "supports_vegetation", + supports_crops = "supports_crops", + supports_cactus = "supports_cactus", + supports_sugar_cane = "supports_sugar_cane", + supports_sugar_cane_adjacently = "supports_sugar_cane_adjacently", + supports_bamboo = "supports_bamboo", + supports_cocoa = "supports_cocoa", + supports_azalea = "supports_azalea", + supports_dry_vegetation = "supports_dry_vegetation", + supports_nether_sprouts = "supports_nether_sprouts", + supports_nether_wart = "supports_nether_wart", + supports_wither_rose = "supports_wither_rose", + supports_lily_pad = "supports_lily_pad", + supports_frogspawn = "supports_frogspawn", + supports_big_dripleaf = "supports_big_dripleaf", + supports_small_dripleaf = "supports_small_dripleaf", + supports_mangrove_propagule = "supports_mangrove_propagule", + supports_hanging_mangrove_propagule = "supports_hanging_mangrove_propagule", + supports_chorus_plant = "supports_chorus_plant", + supports_chorus_flower = "supports_chorus_flower", + support_override_cactus_flower = "support_override_cactus_flower", + cannot_support_seagrass = "cannot_support_seagrass", + cannot_support_kelp = "cannot_support_kelp", + overrides_mushroom_light_requirement = "overrides_mushroom_light_requirement", + enables_bubble_column_push_up = "enables_bubble_column_push_up", + enables_bubble_column_drag_down = "enables_bubble_column_drag_down", + shulker_boxes = "shulker_boxes", + convertible_to_mud = "convertible_to_mud", + grows_crops = "grows_crops", + candles = "candles", + candle_cakes = "candle_cakes", + campfires = "campfires", + buttons = "buttons", + pressure_plates = "pressure_plates", + wool = "wool", + crops = "crops", + small_flowers = "small_flowers", + flowers = "flowers", + saplings = "saplings", + anvil = "anvil", + lanterns = "lanterns", + climbable = "climbable", + nylium = "nylium", + mushroom_grow_block = "mushroom_grow_block", + guarded_by_piglins = "guarded_by_piglins", + copper = "copper", +} + +/// Property keys interned at load. +macro_rules! props { + ($($field:ident = $name:literal,)*) => { + #[derive(Clone, Copy, Debug)] + pub struct Props { $(pub $field: PropKey,)* } + impl Props { + fn resolve(table: &mut StateTable) -> Self { + Self { $($field: table.key($name),)* } + } + } + }; +} +props! { + waterlogged = "waterlogged", + facing = "facing", + half = "half", + shape = "shape", + open = "open", + powered = "powered", + hinge = "hinge", + in_wall = "in_wall", + axis = "axis", + age = "age", + level = "level", + layers = "layers", + snowy = "snowy", + north = "north", + south = "south", + east = "east", + west = "west", + up = "up", + down = "down", + distance = "distance", + persistent = "persistent", + moisture = "moisture", + face = "face", + lit = "lit", + power = "power", + delay = "delay", + locked = "locked", + mode = "mode", + triggered = "triggered", + extended = "extended", + kind = "type", + part = "part", + occupied = "occupied", + hanging = "hanging", + attached = "attached", + candles = "candles", + pickles = "pickles", + eggs = "eggs", + hatch = "hatch", + note = "note", + instrument = "instrument", + bites = "bites", + rotation = "rotation", + stage = "stage", + leaves = "leaves", + bottom = "bottom", + falling = "falling", + drag = "drag", + tilt = "tilt", + attachment = "attachment", + vertical_direction = "vertical_direction", + thickness = "thickness", + berries = "berries", + flower_amount = "flower_amount", + segment_amount = "segment_amount", + charges = "charges", + eye = "eye", + has_bottle_0 = "has_bottle_0", + disarmed = "disarmed", + inverted = "inverted", + enabled = "enabled", + conditional = "conditional", + short = "short", + unstable = "unstable", + tip = "tip", + honey_level = "honey_level", + bloom = "bloom", + natural = "natural", + cracked = "cracked", + has_book = "has_book", + signal_fire = "signal_fire", + orientation = "orientation", + crafting = "crafting", + side_chain = "side_chain", + copper_golem_pose = "copper_golem_pose", + sculk_sensor_phase = "sculk_sensor_phase", + potent_sulfur_state = "potent_sulfur_state", +} + +fn fail(message: &str) -> io::Error { + invalid(message) +} + +fn read_json(path: &Path) -> io::Result { + serde_json::from_reader(BufReader::new(File::open(path)?)).map_err(|e| invalid(e.to_string())) +} + +fn interned(cache: &mut HashMap>, text: &str) -> Arc { + cache + .entry(text.to_owned()) + .or_insert_with(|| Arc::from(text)) + .clone() +} + +fn set_type(value: &Value, cache: &mut HashMap>) -> Option { + let text = |key: &str| value.get(key).and_then(Value::as_str).unwrap_or(""); + Some(SetType { + name: value.get("name")?.as_str()?.into(), + can_open_by_hand: value.get("canOpenByHand")?.as_bool()?, + can_open_by_wind_charge: value.get("canOpenByWindCharge")?.as_bool()?, + arrows: value.get("canButtonBeActivatedByArrows")?.as_bool()?, + mobs_only: value.get("pressurePlateSensitivity")?.as_str()? == "MOBS", + door_open: interned(cache, text("doorOpen")), + door_close: interned(cache, text("doorClose")), + trapdoor_open: interned(cache, text("trapdoorOpen")), + trapdoor_close: interned(cache, text("trapdoorClose")), + plate_on: interned(cache, text("pressurePlateClickOn")), + plate_off: interned(cache, text("pressurePlateClickOff")), + button_on: interned(cache, text("buttonClickOn")), + button_off: interned(cache, text("buttonClickOff")), + }) +} + +/// Build the block-state registry from the resources' `facts.json` (the +/// same source the native client uses). +pub fn load_registry(root: &Path) -> io::Result { + use crate::{DATA_VERSION, nbt::Tag}; + fn tag(value: &Value) -> io::Result { + Ok(match value { + Value::String(value) => Tag::String(value.as_str().into()), + Value::Number(value) => Tag::Int( + value + .as_i64() + .and_then(|v| i32::try_from(v).ok()) + .ok_or_else(|| fail("invalid registry number"))?, + ), + Value::Array(values) => Tag::List(values.iter().map(tag).collect::>()?), + Value::Object(values) => Tag::Compound( + values + .iter() + .map(|(name, value)| Ok((name.as_str().into(), tag(value)?))) + .collect::>()?, + ), + _ => return Err(fail("unsupported registry value")), + }) + } + let facts = read_json(&root.join("facts.json"))?; + let states = facts["states"] + .as_array() + .ok_or_else(|| fail("missing registry state facts"))?; + BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List( + states + .iter() + .map(|state| tag(&state[4])) + .collect::>()?, + ), + ), + ("defaults", tag(&facts["defaults"])?), + ])) +} + +pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result { + let mut table = StateTable::new(registry)?; + let props = Props::resolve(&mut table); + let named = Named::resolve(&table)?; + let behaviour = read_json(&root.join("block-behaviours.json"))?; + let gameplay = read_json(&root.join("gameplay-facts.json"))?; + let blocks_json = behaviour["blocks"] + .as_array() + .ok_or_else(|| fail("missing behaviour blocks"))?; + let states_json = behaviour["states"] + .as_array() + .ok_or_else(|| fail("missing behaviour states"))?; + let gameplay_states = gameplay["states"] + .as_array() + .ok_or_else(|| fail("missing gameplay states"))?; + if blocks_json.len() != table.block_count() + || states_json.len() != table.state_count() + || gameplay_states.len() != table.state_count() + { + return Err(fail("behaviour exports do not match the block registry")); + } + // Fluid registry order fixes the fluid tick type IDs. + let fluids: Vec<&str> = behaviour["fluids"] + .as_array() + .ok_or_else(|| fail("missing fluid registry"))? + .iter() + .filter_map(Value::as_str) + .collect(); + if fluids + .iter() + .copied() + .ne(FluidKind::ALL.iter().map(|k| k.name())) + { + return Err(fail("fluid registry order differs from Horizon's")); + } + + // Tags. + let bundle = read_json(&root.join("block-tags.json"))?; + let mut definitions = TagDefinitions::default(); + for (name, text) in bundle + .as_object() + .ok_or_else(|| fail("invalid block tag bundle"))? + { + definitions + .apply_json( + name, + "vanilla", + text.as_str() + .ok_or_else(|| fail("invalid block tag text"))?, + ) + .map_err(|e| invalid(e.to_string()))?; + } + let built = definitions + .build(|name, _| table.block_by_name(name).map(|_| name.to_owned())) + .map_err(|e| invalid(e.to_string()))?; + let mut all_tags = HashMap::new(); + for (name, members) in &built.tags { + let mut set = BlockSet::with_capacity(table.block_count()); + for member in members { + if let Some(block) = table.block_by_name(member) { + set.insert(block); + } + } + all_tags.insert(name.clone(), Arc::new(set)); + } + let tags = Tags::resolve(&all_tags); + let tag = |name: &str| -> Option> { + 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 cached = CachedCollisionRegistry::from_nbt(&collision_tag, registry)?; + let mut shapes: Vec = Vec::new(); + let mut shape_ids = Vec::with_capacity(table.state_count()); + for id in 0..table.state_count() { + let Some(shape) = cached.cached_shape(BlockStateId(id as u32))? else { + shape_ids.push(-1); + continue; + }; + let index = match shapes.iter().position(|s| s.same_identity(shape)) { + Some(index) => index, + None => { + shapes.push(shape.clone()); + shapes.len() - 1 + } + }; + shape_ids.push(index as i32); + } + + let shape_info = shapes + .iter() + .map(analyse_shape) + .collect::>>()?; + + // Fluid tags. + let mut fluid_definitions = TagDefinitions::default(); + let fluid_dir = root.join("data/minecraft/tags/fluid"); + for entry in fs::read_dir(&fluid_dir)? { + let path = entry?.path(); + let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { + continue; + }; + fluid_definitions + .apply_json( + &format!("minecraft:{stem}"), + "vanilla", + &fs::read_to_string(&path)?, + ) + .map_err(|e| invalid(e.to_string()))?; + } + let fluid_built = fluid_definitions + .build(|name, _| FluidKind::from_name(name).map(|kind| kind as u8)) + .map_err(|e| invalid(e.to_string()))?; + let fluid_mask = |name: &str| -> u8 { + fluid_built + .tags + .get(name) + .into_iter() + .flatten() + .fold(0, |mask, kind| mask | 1 << kind) + }; + let fluid_tags = FluidTags { + water: fluid_mask("minecraft:water"), + lava: fluid_mask("minecraft:lava"), + supports_frogspawn: fluid_mask("minecraft:supports_frogspawn"), + supports_lily_pad: fluid_mask("minecraft:supports_lily_pad"), + supports_sugar_cane_adjacently: fluid_mask("minecraft:supports_sugar_cane_adjacently"), + bubble_column_can_occupy: fluid_mask("minecraft:bubble_column_can_occupy"), + }; + + // Per-state facts. + let mut facts = Vec::with_capacity(table.state_count()); + for (id, (exported, game)) in states_json.iter().zip(gameplay_states).enumerate() { + let row = exported + .as_array() + .ok_or_else(|| fail("invalid behaviour state row"))?; + let int = |i: usize| row.get(i).and_then(Value::as_i64).unwrap_or(0); + let gb = |key: &str| game.get(key).and_then(Value::as_bool).unwrap_or(false); + let mut flags = int(1) as u32 & 0x7f; + for (key, bit) in [ + ("replaceable", state_flags::REPLACEABLE), + ("random_ticks", state_flags::RANDOM_TICKS), + ("solid_render", state_flags::SOLID_RENDER), + ("liquid", state_flags::LIQUID), + ("block_entity", state_flags::BLOCK_ENTITY), + ("ignited_by_lava", state_flags::IGNITED_BY_LAVA), + ("can_occlude", state_flags::CAN_OCCLUDE), + ("full_collision", state_flags::FULL_COLLISION), + ("skylight_down", state_flags::SKYLIGHT_DOWN), + ("requires_tool", state_flags::REQUIRES_TOOL), + ("shape_occlusion", state_flags::SHAPE_OCCLUSION), + ] { + if gb(key) { + flags |= bit; + } + } + let fluid_kind = FluidKind::ALL + .get(int(2) as usize) + .copied() + .ok_or_else(|| fail("invalid exported fluid"))?; + let fluid = FluidState::new( + fluid_kind, + int(3) as u8, + row.get(4).and_then(Value::as_bool).unwrap_or(false), + ); + facts.push(StateFacts { + flags, + sturdy: int(0) as u32, + weak: int(5) as u32, + strong: int(6) as u32, + fluid, + emission: game.get("emission").and_then(Value::as_u64).unwrap_or(0) as u8, + dampening: game.get("dampening").and_then(Value::as_u64).unwrap_or(0) as u8, + hardness: game.get("hardness").and_then(Value::as_f64).unwrap_or(0.0) as f32, + push: match game + .get("push") + .and_then(Value::as_str) + .unwrap_or("PUSH_PULL") + { + "PUSH" => PushReaction::Push, + "POPPED" => PushReaction::Popped, + "IMMOVEABLE" => PushReaction::Immoveable, + "IGNORE_ENTITY" => PushReaction::IgnoreEntity, + _ => PushReaction::PushPull, + }, + instrument: instrument_index(row.get(8).and_then(Value::as_str).unwrap_or("HARP")), + shape: shape_ids[id], + }); + } + + // Per-block data. + let fire = &behaviour["fire"]; + let odds = |key: &str, name: &str| -> 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"))?; + 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) + { + if let Some(c) = Class::from_java(java) { + classes.insert(c); + chain.push(c); + } + } + let class = chain.first().copied().unwrap_or(Class::Block); + let mut interfaces = 0; + for java in json["interfaces"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + { + if let Some(i) = Interface::from_java(java) { + interfaces |= i.mask(); + } + } + let fields = &json["fields"]; + let field = |key: &str| fields.get(key); + let block_field = |key: &str| { + field(key) + .and_then(Value::as_str) + .and_then(|n| table.block_by_name(n)) + }; + let wood = field("type").filter(|t| t.get("setType").is_some()); + let set_type = match wood { + Some(wood) => set_type(&wood["setType"], &mut strings), + None => field("type").and_then(|t| set_type(t, &mut strings)), + } + .map(Arc::new); + let text = |value: Option<&Value>, strings: &mut HashMap>| { + value.and_then(Value::as_str).map(|s| interned(strings, s)) + }; + let gate_open = text(wood.and_then(|w| w.get("fenceGateOpen")), &mut strings); + let gate_close = text(wood.and_then(|w| w.get("fenceGateClose")), &mut strings); + let open_sound = text(field("openSound"), &mut strings); + let close_sound = text(field("closeSound"), &mut strings); + let link = [ + "concrete", + "fruit", + "potted", + "deadBlock", + "base", + "candleBlock", + "requiredBlock", + "baseBlock", + ] + .into_iter() + .find_map(block_field) + .or_else(|| { + let state = field("blockToGrowOn")?.get("state")?.as_u64()?; + (state < table.state_count() as u64).then(|| table.block(BlockStateId(state as u32))) + }); + let link2 = ["attachedStem", "stem"].into_iter().find_map(block_field); + let support_tag = ["stemSupportBlocks", "supportBlocks"] + .into_iter() + .find_map(|k| field(k).and_then(Value::as_str)) + .and_then(tag); + let support_tag2 = field("fruitSupportBlocks") + .and_then(Value::as_str) + .and_then(tag); + let feature = field("feature") + .and_then(Value::as_str) + .or_else(|| { + field("treeGrower") + .and_then(|g| g.get("name")) + .and_then(Value::as_str) + }) + .map(|s| interned(&mut strings, s)); + let growth_direction = match field("growthDirection").and_then(Value::as_str) { + Some("DOWN") => Direction::Down, + _ => Direction::Up, + }; + let default = table.default_state(block); + let sound = &gameplay_states[default.0 as usize]["sound"]; + let sound_id = |key: &str, strings: &mut HashMap>| { + 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, + pitch: sound.get("pitch").and_then(Value::as_f64).unwrap_or(1.0) as f32, + place: sound_id("place", &mut strings), + break_: sound_id("break", &mut strings), + fall: sound_id("fall", &mut strings), + }); + blocks.push(BlockData { + class, + chain, + classes, + interfaces, + set_type, + gate_open, + gate_close, + open_sound, + close_sound, + ticks_to_stay_pressed: field("ticksToStayPressed") + .and_then(Value::as_i64) + .unwrap_or(0) as i32, + max_weight: field("maxWeight").and_then(Value::as_i64).unwrap_or(0) as i32, + link, + link2, + support_tag, + support_tag2, + feature, + grow_probability: field("growPerTickProbability") + .and_then(Value::as_f64) + .unwrap_or(0.0), + growth_direction, + schedule_fluid_ticks: field("scheduleFluidTicks") + .and_then(Value::as_bool) + .unwrap_or(false), + weather: match field("weatherState").and_then(Value::as_str) { + Some("EXPOSED") => 1, + Some("WEATHERED") => 2, + Some("OXIDIZED") => 3, + _ => 0, + }, + ignite_odds: odds("igniteOdds", name), + burn_odds: odds("burnOdds", name), + sounds, + item: interned( + &mut strings, + json["item"].as_str().unwrap_or("minecraft:air"), + ), + dynamic_shape: json["dynamic_shape"].as_bool().unwrap_or(false), + }); + } + + // Item bindings. + let mut items = HashMap::new(); + for (item, binding) in behaviour["items"] + .as_object() + .ok_or_else(|| fail("missing item bindings"))? + { + let fields = &binding["fields"]; + let Some(block) = fields + .get("block") + .and_then(Value::as_str) + .and_then(|n| table.block_by_name(n)) + else { + continue; + }; + 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 + } else if has("StandingAndWallBlockItem") { + ItemKind::StandingAndWall + } else if has("DoubleHighBlockItem") { + ItemKind::DoubleHigh + } else if has("ScaffoldingBlockItem") { + ItemKind::Scaffolding + } else if has("PlaceOnWaterBlockItem") { + ItemKind::PlaceOnWater + } else if has("SolidBucketItem") { + ItemKind::SolidBucket + } else if has("BlockItem") { + ItemKind::Block + } else { + ItemKind::Other + }; + items.insert( + item.clone(), + ItemBinding { + block, + wall_block: fields + .get("wallBlock") + .and_then(Value::as_str) + .and_then(|n| table.block_by_name(n)), + attachment: match fields.get("attachmentDirection").and_then(Value::as_str) { + Some("UP") => Some(Direction::Up), + Some("DOWN") => Some(Direction::Down), + _ => None, + }, + kind, + game_master: has("GameMasterBlockItem"), + }, + ); + } + + let liquid_blocks = FluidBlockBindings::new(registry)?; + let mut dynamic = HashMap::new(); + for (id, fact) in facts.iter().enumerate() { + if fact.shape < 0 { + let state = BlockStateId(id as u32); + if let Some(support) = + crate::dynamic_support::DynamicSupport::from_state(registry.state(state).unwrap())? + { + dynamic.insert(state, support); + } + } + } + Ok(Behaviours { + table, + props, + named, + tags, + all_tags, + facts, + shapes, + shape_info, + fluid_tags, + blocks, + items, + liquid_blocks, + dynamic, + occlusion_cache: Default::default(), + }) +} + +/// `NoteBlockInstrument` serialized names in declaration order. +pub const INSTRUMENTS: [&str; 27] = [ + "harp", + "basedrum", + "snare", + "hat", + "bass", + "flute", + "bell", + "guitar", + "chime", + "xylophone", + "iron_xylophone", + "cow_bell", + "didgeridoo", + "bit", + "banjo", + "pling", + "trumpet", + "trumpet_exposed", + "trumpet_oxidized", + "trumpet_weathered", + "zombie", + "skeleton", + "creeper", + "dragon", + "wither_skeleton", + "piglin", + "custom_head", +]; +/// `NoteBlockInstrument.worksAboveNoteBlock` (mob heads and custom heads). +pub fn instrument_works_above(index: u8) -> bool { + index >= 20 +} +fn instrument_index(name: &str) -> u8 { + INSTRUMENTS + .iter() + .position(|n| n.eq_ignore_ascii_case(name)) + .map_or(0, |i| i as u8) +} diff --git a/crates/horizon-world/src/level/falling.rs b/crates/horizon-world/src/level/falling.rs new file mode 100644 index 000000000..c2b9c9bde --- /dev/null +++ b/crates/horizon-world/src/level/falling.rs @@ -0,0 +1,133 @@ +//! Gravity blocks: `FallingBlock.tick`, `FallingBlockEntity.fall` and the +//! landing branch of `FallingBlockEntity.tick`. The falling entity itself +//! (motion, collision, entity damage) is simulated by the caller. +use super::{Behaviours, LevelAccess, LevelEvent, Sim, Ticks, classes::Class, update::below}; +use crate::registry::BlockStateId; +use horizon_core::{geometry::Direction, position::BlockPos}; + +/// Outcome of [`Behaviours::falling_block_landed`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Landing { + /// The block was placed at the position (concrete powder may have + /// solidified); discard the entity. + Placed(BlockStateId), + /// The block could not be placed: discard the entity and, if the entity + /// drops items, spawn the block's item (vanilla `spawnAtLocation`). + Broken, + /// The landing position holds a moving piston: keep falling. + Continue, +} + +impl Sim<'_, L> { + /// `FallingBlockEntity.fall`. + pub(crate) fn falling_block_fall(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let carried = b + .table + .with_bool(state, b.props.waterlogged, false) + .unwrap_or(state); + let legacy = b.legacy_block(b.fluid(state)); + self.set_block_and_update(pos, legacy); + self.emit(LevelEvent::FallingBlock { + pos, + state: carried, + }); + } + /// `FallingBlock.tick` (and `SpeleothemBlock`'s falling stalactites). + pub(crate) fn falling_block_tick(&mut self, pos: BlockPos, state: BlockStateId) { + if self.is_free(self.below_state(pos)) && pos.y >= self.level.min_y() { + self.falling_block_fall(pos, state); + } + } + /// `SpeleothemBlock.spawnFallingStalactite`. + pub(crate) fn spawn_falling_stalactite(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let p = b.props; + let is_stalactite = |s: BlockStateId| { + b.tag("minecraft:speleothems") + .is_some_and(|tag| b.in_set(s, tag)) + && b.table.dir(s, p.vertical_direction) == Some(Direction::Down) + }; + let mut fall_pos = pos; + let mut fall_state = state; + while is_stalactite(fall_state) { + self.falling_block_fall(fall_pos, fall_state); + let thickness = b.table.text(fall_state, p.thickness); + if thickness == "tip" || thickness == "tip_merge" { + break; + } + fall_pos = below(fall_pos); + fall_state = self.state(fall_pos); + } + } +} + +impl Behaviours { + /// The landing branch of `FallingBlockEntity.tick`, called by the caller's + /// falling-block entity once it is on the ground (or stuck in water as + /// concrete powder). `state` is the carried block state. + pub fn falling_block_landed( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + state: BlockStateId, + stuck_in_water: bool, + ) -> Landing { + let mut sim = self.sim(level, ticks); + let current = sim.state(pos); + if self.is_block(current, self.named.moving_piston) { + return Landing::Continue; + } + let concrete = self.instance_of(state, Class::ConcretePowder); + // DirectionalPlaceContext(level, pos, DOWN, ItemStack.EMPTY, UP). + let ctx = super::place::Ctx { + 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, + ), + inside: false, + yaw: 0.0, + pitch: 90.0, + sneaking: false, + item: String::new(), + replace_clicked: true, + }; + let may_replace = sim.can_be_replaced(current, &ctx); + let would_continue = sim.is_free(sim.below_state(pos)) && (!concrete || !stuck_in_water); + let would_survive = sim.can_survive(state, pos) && !would_continue; + if !(may_replace && would_survive) { + if self.instance_of(state, Class::Anvil) { + sim.level_event(1029, pos, 0); + } + return Landing::Broken; + } + let mut placed = state; + if self.table.has(placed, self.props.waterlogged) + && self.is_water_fluid(sim.fluid_at(pos).kind()) + { + placed = self.table.set_bool(placed, self.props.waterlogged, true); + } + if !sim.set_block_and_update(pos, placed) { + if self.instance_of(state, Class::Anvil) { + sim.level_event(1029, pos, 0); + } + return Landing::Broken; + } + // Fallable.onLand + if concrete { + if self.is_water_fluid(self.fluid(current).kind()) || sim.concrete_touches_liquid(pos) { + if let Some(solid) = self.data(state).link { + sim.set_block_and_update(pos, self.default_of(solid)); + } + } + } else if self.instance_of(state, Class::Anvil) { + sim.level_event(1031, pos, 0); + } + Landing::Placed(sim.state(pos)) + } +} diff --git a/crates/horizon-world/src/level/fluids.rs b/crates/horizon-world/src/level/fluids.rs new file mode 100644 index 000000000..d1017fb34 --- /dev/null +++ b/crates/horizon-world/src/level/fluids.rs @@ -0,0 +1,745 @@ +//! `FlowingFluid` (water and lava) ticking and spreading, `LiquidBlock` +//! interactions, liquid containers (waterlogging) and bucket pickup. +use super::{ + Dimension, LevelAccess, Sim, + classes::{Class, Interface}, + update::{HORIZONTAL, above, below, rel}, +}; +use crate::{ + fluid::{FluidKind, FluidState}, + registry::BlockStateId, +}; +use horizon_core::{ + geometry::{Axis, Direction, ShapeOp, VoxelShape}, + position::BlockPos, + random::RandomSource, +}; +use std::collections::HashMap; + +/// `LiquidBlock.POSSIBLE_FLOW_DIRECTIONS`. +const POSSIBLE_FLOW_DIRECTIONS: [Direction; 5] = [ + Direction::Down, + Direction::South, + Direction::North, + Direction::East, + Direction::West, +]; + +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 + } +} +fn flowing_of(kind: FluidKind) -> FluidKind { + if is_water(kind) { + FluidKind::FlowingWater + } else { + FluidKind::FlowingLava + } +} + +/// `FlowingFluid.SpreadContext`: per-spread caches keyed by horizontal offset. +struct SpreadContext { + origin: BlockPos, + states: HashMap, + holes: HashMap, +} +impl SpreadContext { + fn key(&self, pos: BlockPos) -> i16 { + let x = pos.x.wrapping_sub(self.origin.x).wrapping_add(128) & 0xff; + let z = pos.z.wrapping_sub(self.origin.z).wrapping_add(128) & 0xff; + ((x << 8) | z) as i16 + } +} + +impl Sim<'_, L> { + fn fast_lava(&self) -> bool { + self.level.dimension() == Dimension::Nether + } + /// `Fluid.getTickDelay`. + pub(crate) fn fluid_tick_delay(&self, kind: FluidKind) -> i32 { + match kind { + FluidKind::Empty => 0, + FluidKind::Water | FluidKind::FlowingWater => 5, + _ => { + if self.fast_lava() { + 10 + } else { + 30 + } + } + } + } + fn drop_off(&self, kind: FluidKind) -> i32 { + 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 + } + } + 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 + } + } + fn fluid_height(&self, fluid: FluidState, pos: BlockPos) -> f32 { + if fluid.kind() == FluidKind::Empty { + return 0.0; + } + if fluid.kind().same_family(self.fluid_at(above(pos)).kind()) { + 1.0 + } else { + fluid.own_height() + } + } + /// `FluidState.canBeReplacedWith(level, pos, other, direction)`. + 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) + } + _ => self.fluid_height(fluid, pos) >= 0.444_444_45 && is_water(other), + } + } + + // ---- shape occlusion ---- + + fn collision_or_empty(&self, state: BlockStateId) -> (i32, VoxelShape) { + let index = self.b.facts(state).shape; + match self.b.collision_shape(state) { + Some(shape) => (index, shape.clone()), + None => (-1, VoxelShape::empty()), + } + } + /// `FlowingFluid.canPassThroughWall`. + 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) { + return false; + } + let (source_index, source_shape) = self.collision_or_empty(source); + if source_shape.same_identity(&block) { + return false; + } + let empty = VoxelShape::empty(); + if source_shape.same_identity(&empty) && target_shape.same_identity(&empty) { + return true; + } + 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()) + { + return result; + } + } + let result = !merged_face_occludes(&source_shape, &target_shape, direction); + if cacheable { + if let Ok(mut cache) = self.b.occlusion_cache.lock() { + cache.insert(key, result); + } + } + result + } + + // ---- liquid containers ---- + + /// `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) + } + /// `LiquidBlockContainer.canPlaceLiquid(null, level, pos, state, fluid)`. + pub(crate) fn can_place_liquid(&self, state: BlockStateId, fluid: FluidKind) -> bool { + let b = self.b; + let data = b.data(state); + if data.is(Class::Kelp) + || data.is(Class::KelpPlant) + || data.is(Class::Seagrass) + || data.is(Class::TallSeagrass) + || data.is(Class::Barrier) + { + return false; + } + if data.is(Class::Slab) && b.table.text(state, b.props.kind) == "double" { + return false; + } + fluid == FluidKind::Water + } + /// `LiquidBlockContainer.placeLiquid`. + 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) + { + return false; + } + if b.is_waterlogged(state) { + return false; + } + 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) + { + next = b.table.set_bool(next, b.props.lit, false); + if data.is(Class::Campfire) { + self.emit(super::LevelEvent::Sound { + pos, + sound: "minecraft:block.generic.extinguish_fire".into(), + volume: 1.0, + pitch: 1.0, + }); + } else { + self.emit(super::LevelEvent::Sound { + pos, + sound: "minecraft:block.candle.extinguish".into(), + volume: 1.0, + pitch: 1.0, + }); + } + } + self.set_block_and_update(pos, next); + let delay = self.fluid_tick_delay(fluid.kind()); + self.schedule_fluid_tick(pos, fluid.kind(), delay); + true + } + /// `BucketPickup.pickupBlock`: true when a fluid was taken. + pub(crate) fn pickup_block(&mut self, pos: BlockPos, state: BlockStateId) -> bool { + let b = self.b; + if b.instance_of(state, Class::Liquid) { + if b.table.int(state, b.props.level) == 0 { + self.set_block(pos, b.air(), 11); + return true; + } + return false; + } + 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) { + self.destroy_block(pos, true, 512); + } + return true; + } + return false; + } + if b.is_block(state, b.named.powder_snow) { + self.set_block(pos, b.air(), 11); + return true; + } + false + } + fn can_hold_any_fluid(&self, state: BlockStateId) -> bool { + 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 + } + } + fn can_hold_fluid(&self, state: BlockStateId, fluid: FluidKind) -> bool { + self.can_hold_any_fluid(state) && self.can_hold_specific_fluid(state, fluid) + } + + // ---- FlowingFluid ---- + + fn is_source_of(&self, kind: FluidKind, fluid: FluidState) -> bool { + fluid.kind().same_family(kind) && fluid.is_source() + } + /// `FlowingFluid.getNewLiquid`. + fn new_liquid(&self, kind: FluidKind, pos: BlockPos, state: BlockStateId) -> FluidState { + let b = self.b; + let mut highest = 0; + let mut sources = 0; + 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.is_source() { + sources += 1; + } + highest = highest.max(i32::from(fluid.amount())); + } + } + if sources >= 2 && self.can_convert_to_source(kind) { + let below_state = self.below_state(pos); + if b.is_solid(below_state) || self.is_source_of(kind, b.fluid(below_state)) { + return FluidState::new(source_of(kind), 8, false); + } + } + let above_state = self.above_state(pos); + let above_fluid = b.fluid(above_state); + if above_fluid.kind() != FluidKind::Empty + && above_fluid.kind().same_family(kind) + && self.can_pass_through_wall(Direction::Up, state, above_state) + { + return FluidState::new(flowing_of(kind), 8, true); + } + let amount = highest - self.drop_off(kind); + if amount <= 0 { + FluidState::EMPTY + } else { + FluidState::new(flowing_of(kind), amount as u8, false) + } + } + fn is_water_hole(&self, kind: FluidKind, top: BlockStateId, bottom: BlockStateId) -> bool { + if !self.can_pass_through_wall(Direction::Down, top, bottom) { + return false; + } + if self.b.fluid(bottom).kind().same_family(kind) { + true + } else { + 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_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); + if let Some(state) = context.states.get(&key) { + return *state; + } + let state = self.state(pos); + context.states.insert(key, state); + state + } + fn context_is_hole(&self, kind: FluidKind, context: &mut SpreadContext, pos: BlockPos) -> bool { + let key = context.key(pos); + if let Some(hole) = context.holes.get(&key) { + return *hole; + } + let state = self.context_state(context, pos); + let below_state = self.below_state(pos); + let hole = self.is_water_hole(kind, state, below_state); + context.holes.insert(key, hole); + hole + } + 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 { + continue; + } + let test_pos = rel(pos, direction); + let test_state = self.context_state(context, test_pos); + let test_fluid = self.b.fluid(test_state); + if self.can_pass_through(kind, state, direction, test_state, test_fluid) { + if self.context_is_hole(kind, context, test_pos) { + return pass; + } + if pass < self.slope_find_distance(kind) { + let distance = self.slope_distance( + kind, + test_pos, + pass + 1, + direction.opposite(), + test_state, + context, + ); + lowest = lowest.min(distance); + } + } + } + lowest + } + /// `FlowingFluid.getSpread` (EnumMap: iteration in Direction order). + 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; + for direction in HORIZONTAL { + let test_pos = rel(pos, direction); + let test_state = self.state(test_pos); + let test_fluid = self.b.fluid(test_state); + if !self.can_maybe_pass_through(kind, state, direction, test_state, test_fluid) { + continue; + } + let new_fluid = self.new_liquid(kind, test_pos, test_state); + if !self.can_hold_specific_fluid(test_state, new_fluid.kind()) { + continue; + } + let context = context.get_or_insert_with(|| SpreadContext { + origin: pos, + states: HashMap::new(), + holes: HashMap::new(), + }); + let distance = if self.context_is_hole(kind, context, test_pos) { + 0 + } else { + self.slope_distance(kind, test_pos, 1, direction.opposite(), test_state, context) + }; + if distance < lowest { + result.clear(); + } + if distance <= lowest { + if self.can_be_replaced_with(test_fluid, test_pos, new_fluid.kind(), direction) { + result.push((direction, new_fluid)); + } + lowest = distance; + } + } + result.sort_by_key(|(direction, _)| *direction as u8); + 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 + } + /// `FlowingFluid.spreadTo` (with LavaFluid's water-to-stone override). + 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 b.instance_of(state, Class::Liquid) { + self.set_block_and_update(pos, b.default_of(b.named.stone)); + } + self.level_event(1501, pos, 0); + return; + } + if self.is_liquid_container(state) { + self.place_liquid(pos, state, target); + } else { + if !b.is_air(state) { + if is_water(kind) { + self.drop_resources(state, pos); + } else { + self.level_event(1501, pos, 0); + } + } + let legacy = b.legacy_block(target); + self.set_block_and_update(pos, legacy); + } + } + 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; + } + if neighbour > 0 { + for (direction, new_fluid) in self.spread_targets(kind, pos, state) { + let neighbour_pos = rel(pos, direction); + let neighbour_state = self.state(neighbour_pos); + self.spread_to(kind, neighbour_pos, neighbour_state, direction, new_fluid); + } + } + } + /// `FlowingFluid.spread`. + fn spread(&mut self, kind: FluidKind, pos: BlockPos, state: BlockStateId, fluid: FluidState) { + if fluid.kind() == FluidKind::Empty { + return; + } + let below_pos = below(pos); + let below_state = self.state(below_pos); + let below_fluid = self.b.fluid(below_state); + if self.can_maybe_pass_through(kind, state, Direction::Down, below_state, below_fluid) { + let new_below = self.new_liquid(kind, below_pos, below_state); + if self.can_be_replaced_with(below_fluid, below_pos, new_below.kind(), Direction::Down) + && self.can_hold_specific_fluid(below_state, new_below.kind()) + { + self.spread_to(kind, below_pos, below_state, Direction::Down, new_below); + if self.source_neighbour_count(kind, pos) >= 3 { + self.spread_to_sides(kind, pos, fluid, state); + } + return; + } + } + if fluid.is_source() || !self.is_water_hole(kind, state, below_state) { + self.spread_to_sides(kind, pos, fluid, state); + } + } + /// `FlowingFluid.tick` for the fluid at `pos`. + pub(crate) fn fluid_tick(&mut self, pos: BlockPos) { + let mut state = self.state(pos); + let mut fluid = self.b.fluid(state); + let kind = fluid.kind(); + if kind == FluidKind::Empty { + return; + } + if !fluid.is_source() { + let new_fluid = self.new_liquid(kind, pos, state); + let delay = self.spread_delay(kind, pos, fluid, new_fluid); + if new_fluid.kind() == FluidKind::Empty { + fluid = new_fluid; + state = self.b.air(); + self.set_block_and_update(pos, state); + } else if new_fluid != fluid { + fluid = new_fluid; + state = self.b.legacy_block(fluid); + self.set_block_and_update(pos, state); + self.schedule_fluid_tick(pos, fluid.kind(), delay); + } + } + self.spread(kind, pos, state, fluid); + } + 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; + } + if old.kind() != FluidKind::Empty + && new.kind() != FluidKind::Empty + && !old.falling() + && !new.falling() + && self.fluid_height(new, pos) > self.fluid_height(old, pos) + && self.random().next_int_bound(4).unwrap_or(0) != 0 + { + delay * 4 + } else { + delay + } + } + + // ---- LiquidBlock ---- + + /// `LiquidBlock.shouldSpreadLiquid`, including lava's conversions. + pub(crate) fn should_spread_liquid(&mut self, pos: BlockPos, state: BlockStateId) -> bool { + let b = self.b; + if !b.is_lava_fluid(b.fluid(state).kind()) { + return true; + } + let over_soul_soil = b.is_block(self.below_state(pos), b.named.soul_soil); + 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 + }; + self.set_block_and_update(pos, b.default_of(block)); + self.level_event(1501, pos, 0); + return false; + } + if over_soul_soil && b.is_block(self.state(neighbour), b.named.blue_ice) { + self.set_block_and_update(pos, b.default_of(b.named.basalt)); + self.level_event(1501, pos, 0); + return false; + } + } + true + } + /// `LiquidBlock.onPlace` / `neighborChanged`. + pub(crate) fn liquid_block_changed(&mut self, pos: BlockPos, state: BlockStateId) { + if self.should_spread_liquid(pos, state) { + let kind = self.b.fluid(state).kind(); + let delay = self.fluid_tick_delay(kind); + self.schedule_fluid_tick(pos, kind, delay); + } + if self.should_bubble_column_occupy(state) { + let below_state = self.below_state(pos); + let block = self.b.block(state); + self.try_schedule_bubble_column(pos, below_state, block); + } + } + + /// `LavaFluid.randomTick`. + pub(crate) fn lava_random_tick(&mut self, pos: BlockPos) { + if !self.level.can_spread_fire_around(pos) { + return; + } + let passes = self.random().next_int_bound(3).unwrap_or(0); + if passes > 0 { + let mut test = pos; + for _ in 0..passes { + let dx = self.random().next_int_bound(3).unwrap_or(0) - 1; + let dz = self.random().next_int_bound(3).unwrap_or(0) - 1; + test = test.offset(dx, 1, dz); + if !self.level.is_loaded(test) { + return; + } + let state = self.state(test); + if self.b.is_air(state) { + 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)) + { + return; + } + } + } else { + for _ in 0..3 { + let dx = self.random().next_int_bound(3).unwrap_or(0) - 1; + let dz = self.random().next_int_bound(3).unwrap_or(0) - 1; + let test = pos.offset(dx, 0, dz); + if !self.level.is_loaded(test) { + return; + } + if self.is_empty_block(above(test)) && self.lava_flammable(test) { + let fire = self.fire_state_for(test); + self.set_block_and_update(above(test), fire); + } + } + } + } + fn lava_flammable(&self, pos: BlockPos) -> bool { + 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) + } +} + +/// `Shapes.mergedFaceOccludes(shape, occluder, direction)`. +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 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 max_face = match axis { + Axis::X => Direction::East, + Axis::Y => Direction::Up, + Axis::Z => Direction::South, + }; + let empty = VoxelShape::empty(); + // SliceShape(first, axis, last layer) / SliceShape(second, axis, 0): the face + // shapes sample the same boundary layers when the shapes touch the face. + let first_slice = if !first.is_empty() && (first.max(axis) - 1.0).abs() <= 1.0e-7 { + first.face_shape(max_face).unwrap_or_else(|_| empty.clone()) + } else { + 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()) + } else { + empty.clone() + }; + let union = match first_slice.join(&second_slice, ShapeOp::OR) { + Ok(shape) => shape, + Err(_) => return false, + }; + !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 new file mode 100644 index 000000000..a56e42738 --- /dev/null +++ b/crates/horizon-world/src/level/hooks.rs @@ -0,0 +1,538 @@ +//! `neighborChanged`, `onPlace`, `affectNeighborsAfterRemoval` and +//! `updateIndirectNeighbourShapes` for the overriding vanilla classes. +use super::{ + LevelAccess, Sim, + classes::Class, + states::BlockId, + update::{below, rel}, +}; +use crate::registry::BlockStateId; +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, + ) { + let b = self.b; + let block = b.block(state); + let chain = &b.data(state).chain; + for &class in chain.iter() { + match class { + Class::AbstractSkull => self.skull_neighbor_changed(pos, state), + Class::BaseRail => self.rail_neighbor_changed(pos, state, changed, moved), + Class::Bell => self.bell_neighbor_changed(pos, state), + Class::BigDripleaf => { + if self.has_neighbor_signal(pos) { + self.big_dripleaf_reset_tilt(pos, state); + } + } + Class::CopperBulb => self.copper_bulb_check(pos, state), + Class::Crafter => self.crafter_neighbor_changed(pos, state), + Class::Diode => self.diode_neighbor_changed(pos, state), + Class::Dispenser => self.dispenser_neighbor_changed(pos, state), + 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) + { + self.frosted_ice_melt(pos, state); + } + } + Class::Hopper => self.hopper_check_powered(pos, state), + Class::Liquid => self.liquid_block_changed(pos, state), + Class::Note => self.note_neighbor_changed(pos, state), + Class::PistonBase => self.piston_check_if_extend(pos, state), + Class::PistonHead => { + if self.piston_head_can_survive(state, pos) { + let base = rel(pos, b.facing(state).opposite()); + self.neighbor_changed_at(base, changed); + } + } + Class::RedstoneLamp => self.lamp_neighbor_changed(pos, state), + Class::RedstoneTorch => self.torch_neighbor_changed(pos, state), + Class::RedstoneWire => { + if self.can_survive(state, pos) { + self.wire_update_power(pos, state); + } else { + self.drop_resources(state, pos); + self.remove_block(pos, false); + } + } + Class::Sponge => self.sponge_try_absorb(pos), + Class::Tnt => self.tnt_check(pos), + Class::TrapDoor => self.trapdoor_neighbor_changed(pos, state), + _ => continue, + } + let _ = block; + return; + } + } + + /// `BlockState.onPlace`. + pub fn on_place(&mut self, state: BlockStateId, pos: BlockPos, old: BlockStateId, moved: bool) { + let b = self.b; + let block = b.block(state); + let same = b.block(old) == block; + let chain = &b.data(state).chain; + for &class in chain.iter() { + match class { + Class::Fire => { + self.base_fire_on_place(pos, state, same); + let delay = 30 + self.random().next_int_bound(10).unwrap_or(0); + self.schedule_tick(pos, block, delay); + } + Class::BaseFire => self.base_fire_on_place(pos, state, same), + Class::DetectorRail | Class::BaseRail => { + if !same { + self.rail_update_state(pos, state, moved); + } + } + Class::Brushable => { + self.schedule_tick(pos, block, 2); + } + Class::Composter => { + if b.table.int(state, b.props.level) == 7 { + self.schedule_tick(pos, block, 20); + } + } + Class::CopperBulb => { + if !same { + self.copper_bulb_check(pos, state); + } + } + 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 + }; + self.schedule_tick(pos, block, delay); + } + Class::Frogspawn => { + let delay = self.random().next_int_between(3600, 12000).unwrap_or(3600); + self.schedule_tick(pos, block, delay); + } + Class::FrostedIce => { + let delay = self + .random() + .next_int_between_inclusive(60, 120) + .unwrap_or(60); + self.schedule_tick(pos, block, delay); + } + Class::Hopper => { + if !same { + self.hopper_check_powered(pos, state); + } + } + Class::LightningRod => { + if !same + && b.table.bool(state, b.props.powered) + && !self.ticks.has_block_tick(pos, block) + { + self.schedule_tick(pos, block, 8); + } + } + Class::Liquid => self.liquid_block_changed(pos, state), + Class::PistonBase => { + if !same && self.moving_piston(pos).is_none() { + self.piston_check_if_extend(pos, state); + } + } + Class::Observer => { + 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); + } + } + Class::RedstoneTorch => self.torch_notify_neighbors(pos, state), + Class::RedstoneWire => { + if !same { + self.wire_update_power(pos, state); + for direction in [Direction::Up, Direction::Down] { + self.update_neighbors_at(rel(pos, direction), block); + } + self.wire_update_neighbors_of_neighboring_wires(pos); + } + } + Class::Scaffolding => { + self.schedule_tick(pos, block, 1); + } + Class::SculkSensor => { + if !same + && b.table.int(state, b.props.power) > 0 + && !self.ticks.has_block_tick(pos, block) + { + self.set_block(pos, b.table.set_int(state, b.props.power, 0), 18); + } + } + Class::Sponge => { + if !same { + self.sponge_try_absorb(pos); + } + } + Class::WetSponge => { + if self.level.dimension() == super::Dimension::Nether { + self.set_block_and_update(pos, b.default_of(b.named.sponge)); + self.level_event(2009, pos, 0); + let pitch = (1.0 + self.random().next_float() * 0.2) * 0.7; + self.emit(super::LevelEvent::Sound { + pos, + sound: "minecraft:block.wet_sponge.dries".into(), + volume: 1.0, + pitch, + }); + } + } + Class::Target => { + 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); + } + } + Class::Tnt => { + if !same { + self.tnt_check(pos); + } + } + Class::TripWire => { + if !same { + self.tripwire_update_source(pos, state); + } + } + Class::TurtleEgg => { + if b.in_set(self.below_state(pos), &b.tags.sand) { + self.level_event(2012, pos, 15); + } + } + _ => continue, + } + return; + } + } + + /// `BlockState.affectNeighborsAfterRemoval`. + 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; + for &class in chain.iter() { + match class { + Class::AbstractFurnace + | Class::Barrel + | Class::BrewingStand + | Class::Chest + | Class::ChiseledBookShelf + | Class::Crafter + | Class::CreakingHeart + | Class::DecoratedPot + | Class::Dispenser + | Class::Hopper + | Class::Jukebox + | Class::ShulkerBox + | Class::CopperGolemStatue => self.update_neighbour_for_output_signal(pos, block), + Class::Shelf => self.update_neighbour_for_output_signal(pos, block), + Class::BasePressurePlate => { + if !moved && self.plate_signal_for_state(state) > 0 { + self.plate_update_neighbours(pos, block); + } + } + Class::BaseRail => { + if !moved { + if self.rail_shape(state).starts_with("ascending") { + self.update_neighbors_at(super::update::above(pos), block); + } + if !b.data(state).is(Class::Rail) { + self.update_neighbors_at(pos, block); + self.update_neighbors_at(below(pos), block); + } + } + } + Class::Button | Class::Lever => { + if !moved && b.table.bool(state, b.props.powered) { + self.attached_update_neighbours(pos, state); + } + } + Class::LightningRod => { + if b.table.bool(state, b.props.powered) { + let facing = b.facing(state); + self.update_neighbors_at(rel(pos, facing.opposite()), block); + } + } + Class::PistonHead => { + let base_pos = rel(pos, b.facing(state).opposite()); + let base = self.state(base_pos); + if self.piston_head_fitting_base(state, base) { + self.destroy_block(base_pos, true, super::flags::UPDATE_LIMIT); + } + } + Class::Lectern => { + if b.table.bool(state, b.props.powered) { + self.update_neighbors_at(below(pos), block); + } + } + Class::Diode => { + if !moved { + self.diode_update_neighbors_in_front(pos, state); + } + } + Class::Observer => { + 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); + } + } + Class::RedstoneTorch => { + if !moved { + self.torch_notify_neighbors(pos, state); + } + } + Class::RedstoneWire => { + if !moved { + for direction in Direction::ALL { + self.update_neighbors_at(rel(pos, direction), block); + } + self.wire_update_power(pos, state); + self.wire_update_neighbors_of_neighboring_wires(pos); + } + } + Class::SculkSensor => { + if b.table.text(state, b.table_phase_key()) == "active" { + self.update_neighbors_at(pos, block); + self.update_neighbors_at(below(pos), block); + } + } + Class::TripWire => { + if !moved { + let powered = b.table.set_bool(state, b.props.powered, true); + self.tripwire_update_source(pos, powered); + } + } + Class::TripWireHook => { + if !moved { + self.tripwire_hook_removed(pos, state); + } + } + _ => continue, + } + return; + } + } + + /// `BlockState.updateIndirectNeighbourShapes` (only redstone wire overrides it). + 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); + } + } + + /// `ServerPlayerGameMode.destroyBlock`: `playerWillDestroy` then + /// `removeBlock`. Drops are the caller's (tool-dependent loot). + pub(crate) fn player_destroy(&mut self, pos: BlockPos, creative: bool) -> bool { + let b = self.b; + let p = b.props; + let state = self.state(pos); + if b.is_air(state) { + return false; + } + let data = b.data(state); + if creative + && (data.is(Class::DoublePlant) || data.is(Class::Door)) + && b.table.text(state, p.half) == "upper" + { + let bottom = below(pos); + let bottom_state = self.state(bottom); + if b.is_block(bottom_state, b.block(state)) + && b.table.text(bottom_state, p.half) == "lower" + { + let replacement = if b.is_water_fluid(b.fluid(bottom_state).kind()) { + b.default_of(b.named.water) + } else { + b.air() + }; + self.set_block(bottom, replacement, 35); + self.level_event(2001, bottom, bottom_state.0 as i32); + } + } + if creative && data.is(Class::AbstractBed) && b.table.text(state, p.part) == "foot" { + let head_pos = rel(pos, b.facing(state)); + let head = self.state(head_pos); + if b.is_block(head, b.block(state)) && b.table.text(head, p.part) == "head" { + self.set_block(head_pos, b.air(), 35); + self.level_event(2001, head_pos, head.0 as i32); + } + } + self.level_event(2001, pos, state.0 as i32); + self.game_event(pos, "minecraft:block_destroy"); + self.remove_block(pos, false) + } + /// `entityInside` for entity-sensing blocks. + pub(crate) fn entity_inside(&mut self, pos: BlockPos) { + let b = self.b; + let state = self.state(pos); + let data = b.data(state); + if data.is(Class::BasePressurePlate) { + let signal = self.plate_signal_for_state(state); + if signal == 0 { + self.plate_check_pressed(pos, state, signal); + } + } else if data.is(Class::TripWire) + && !b.table.bool(state, b.props.powered) + && !self.ticks.has_block_tick(pos, b.block(state)) + { + self.tripwire_check_pressed(pos); + } + } + + // ---- misc helpers ---- + + /// `BaseFireBlock.onPlace` (portal ignition is not modelled). + fn base_fire_on_place(&mut self, pos: BlockPos, state: BlockStateId, same: bool) { + if !same && !self.can_survive(state, pos) { + self.remove_block(pos, false); + } + } + /// `SpongeBlock.tryAbsorbWater`. + pub(crate) fn sponge_try_absorb(&mut self, start: BlockPos) { + if self.sponge_remove_water(start) { + let b = self.b; + self.set_block(start, b.default_of(b.named.wet_sponge), 2); + self.emit(super::LevelEvent::Sound { + pos: start, + sound: "minecraft:block.sponge.absorb".into(), + volume: 1.0, + pitch: 1.0, + }); + } + } + fn sponge_remove_water(&mut self, start: BlockPos) -> bool { + use std::collections::{HashSet, VecDeque}; + let b = self.b; + let mut queue = VecDeque::from([(start, 0)]); + let mut visited = HashSet::new(); + let mut count = 0; + while let Some((pos, depth)) = queue.pop_front() { + if !visited.insert(pos) { + continue; + } + let accept = if pos == start { + true + } else { + let state = self.state(pos); + if !b.is_water_fluid(self.fluid_at(pos).kind()) { + false + } else if self.pickup_block(pos, state) { + true + } else { + if b.instance_of(state, Class::Liquid) { + self.set_block_and_update(pos, b.air()); + } 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 + { + continue; + } + self.drop_resources(state, pos); + self.set_block_and_update(pos, b.air()); + } + true + } + }; + if !accept { + continue; + } + count += 1; + if count >= 65 { + return count > 1; + } + if depth < 6 { + for direction in Direction::ALL { + queue.push_back((rel(pos, direction), depth + 1)); + } + } + } + count > 1 + } + 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) + { + count += 1; + if count >= limit { + return false; + } + } + } + true + } + /// `FrostedIceBlock.melt` → `IceBlock.melt`. + pub(crate) fn frosted_ice_melt(&mut self, pos: BlockPos, _state: BlockStateId) { + self.ice_melt(pos); + } + /// `IceBlock.melt`. + pub(crate) fn ice_melt(&mut self, pos: BlockPos) { + let b = self.b; + if self.level.dimension() == super::Dimension::Nether { + self.remove_block(pos, false); + } else { + let water = b.default_of(b.named.water); + self.set_block_and_update(pos, water); + self.neighbor_changed_at(pos, b.named.water); + } + } + fn big_dripleaf_reset_tilt(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let next = b.table.set_text(state, b.props.tilt, "none"); + self.set_block(pos, next, 2); + if b.table.text(state, b.props.tilt) != "none" { + let pitch = self.random().next_float() * 0.4 + 0.8; + self.emit(super::LevelEvent::Sound { + pos, + sound: "minecraft:block.big_dripleaf.tilt_up".into(), + volume: 1.0, + pitch, + }); + } + } +} + +impl super::Behaviours { + pub(crate) fn table_phase_key(&self) -> super::states::PropKey { + self.props.sculk_sensor_phase + } +} diff --git a/crates/horizon-world/src/level/interact.rs b/crates/horizon-world/src/level/interact.rs new file mode 100644 index 000000000..0c888bb77 --- /dev/null +++ b/crates/horizon-world/src/level/interact.rs @@ -0,0 +1,485 @@ +//! `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 crate::registry::BlockStateId; +use horizon_core::{ + geometry::{Axis, Direction, Vec3}, + position::BlockPos, + random::RandomSource, +}; +use std::sync::Arc; + +/// `InteractionResult` as seen by the server. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum InteractionResult { + Success, + Consume, + Pass, +} +impl InteractionResult { + pub fn consumes_action(self) -> bool { + !matches!(self, Self::Pass) + } +} + +/// The interacting player, as far as block behaviour needs it. +#[derive(Clone, Copy, Debug)] +pub struct PlayerContext { + /// View rotation in degrees. + pub yaw: f32, + pub pitch: f32, + /// `Abilities.mayBuild` (false in adventure mode). + pub may_build: bool, + /// `Player.canEat(false)` (hunger below max, or creative). + pub can_eat: bool, + /// `Player.canUseGameMasterBlocks` (creative operator). + pub game_master: bool, +} + +/// Player-side effects of an interaction, reported through +/// [`LevelEvent::Player`]; block changes are already applied. +#[derive(Clone, Debug, PartialEq)] +pub enum PlayerEffect { + /// Open the block's menu (crafting table, furnace, chest, sign editor, ...). + OpenMenu, + /// `CakeBlock.eat`: the player eats a slice (food 2, saturation 0.1). + EatCake, + /// Give the item to the player (dropping it when the inventory is full). + GiveItem(Arc), + /// Pop the item at the block (composter bone meal). + DropItem(Arc), + /// Evaluate the block-interaction loot table and pop the results. + InteractLoot(&'static str), + /// Try to sleep in the bed whose head is at the event position. + Sleep, + /// Respawn anchor: set the respawn point (or explode outside the Nether). + RespawnAnchor, +} + +impl Sim<'_, L> { + fn player_effect(&mut self, pos: BlockPos, state: BlockStateId, effect: PlayerEffect) { + self.emit(LevelEvent::Player { pos, state, effect }); + } + + 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; + let state = self.state(pos); + let data = b.data(state); + let block = b.block(state); + use InteractionResult::*; + for &class in data.chain.iter() { + return match class { + Class::Door => { + if !data.set_type.as_ref().is_some_and(|s| s.can_open_by_hand) { + return Pass; + } + let next = table.cycle(state, p.open); + 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" + }, + ); + Success + } + Class::TrapDoor => { + if !data.set_type.as_ref().is_some_and(|s| s.can_open_by_hand) { + return Pass; + } + let next = table.cycle(state, p.open); + self.set_block(pos, next, 2); + if b.is_waterlogged(next) { + self.schedule_water_tick(pos); + } + self.trapdoor_sound(pos, next, table.bool(next, p.open)); + Success + } + Class::FenceGate => { + let next = if table.bool(state, p.open) { + table.set_bool(state, p.open, false) + } else { + let direction = super::place::from_y_rot(f64::from(player.yaw)); + let mut next = state; + if b.facing(state) == direction.opposite() { + next = table.set_dir(next, p.facing, direction); + } + table.set_bool(next, p.open, true) + }; + 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 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" + }, + ); + Success + } + Class::Button => { + if table.bool(state, p.powered) { + return Consume; + } + self.button_press(pos, state); + Success + } + Class::Lever => { + self.lever_pull(pos, state); + Success + } + Class::Repeater => { + if !player.may_build { + return Pass; + } + self.set_block_and_update(pos, table.cycle(state, p.delay)); + Success + } + Class::Comparator => { + if !player.may_build { + return Pass; + } + let next = table.cycle(state, p.mode); + 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(), + volume: 0.3, + pitch, + }); + self.set_block(pos, next, 2); + if b.is_block(self.state(pos), block) { + self.comparator_refresh(pos, next); + } + Success + } + Class::Note => { + let next = table.cycle(state, p.note); + self.set_block_and_update(pos, next); + self.note_play(pos, next); + Success + } + Class::RedstoneWire => self.wire_use(pos, state, player), + Class::DaylightDetector => { + if !player.may_build { + return Pass; + } + let next = table.cycle(state, p.inverted); + self.set_block(pos, next, 2); + self.game_event(pos, "minecraft:block_change"); + Success + } + Class::Cake => { + if !player.can_eat { + return Pass; + } + self.player_effect(pos, state, PlayerEffect::EatCake); + self.game_event(pos, "minecraft:eat"); + let bites = table.int(state, p.bites); + if bites < 6 { + self.set_block_and_update(pos, table.set_int(state, p.bites, bites + 1)); + } else { + self.remove_block(pos, false); + self.game_event(pos, "minecraft:block_destroy"); + } + Success + } + Class::CandleCake => { + if !player.can_eat { + return Pass; + } + self.player_effect(pos, state, PlayerEffect::EatCake); + self.game_event(pos, "minecraft:eat"); + let cake = b.default_of(b.named.cake); + self.set_block_and_update(pos, table.set_int(cake, p.bites, 1)); + self.drop_resources(state, pos); + Success + } + Class::Composter => { + if table.int(state, p.level) != 8 { + return Pass; + } + 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 { + pos, + sound: "minecraft:block.composter.empty".into(), + volume: 1.0, + pitch: 1.0, + }); + Success + } + Class::CaveVines | Class::CaveVinesPlant => { + if !table.bool(state, p.berries) { + return Pass; + } + 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, + sound: "minecraft:block.cave_vines.pick_berries".into(), + volume: 1.0, + pitch, + }); + let next = table.set_bool(state, p.berries, false); + self.set_block(pos, next, 2); + self.game_event(pos, "minecraft:block_change"); + Success + } + Class::SweetBerryBush => { + if table.int(state, p.age) <= 1 { + return Pass; + } + 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, + sound: "minecraft:block.sweet_berry_bush.pick_berries".into(), + volume: 1.0, + pitch, + }); + self.set_block(pos, table.set_int(state, p.age, 1), 2); + self.game_event(pos, "minecraft:block_change"); + Success + } + Class::FlowerPot => { + let Some(potted) = data.link else { + return Consume; + }; + if b.is_air(b.default_of(potted)) { + return Consume; + } + let item = b.block_data(potted).item.clone(); + self.player_effect(pos, state, PlayerEffect::GiveItem(item)); + self.set_block_and_update(pos, b.default_of(b.named.flower_pot)); + self.game_event(pos, "minecraft:block_change"); + Success + } + Class::DragonEgg => { + self.dragon_egg_teleport(pos, state); + Success + } + 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 = 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_state = self.state(head); + self.player_effect(head, head_state, PlayerEffect::Sleep); + Success + } else { + Consume + } + } + Class::RespawnAnchor => { + if table.int(state, p.charges) == 0 { + return Pass; + } + self.player_effect(pos, state, PlayerEffect::RespawnAnchor); + Success + } + Class::Light => { + if player.game_master { + self.set_block(pos, table.cycle(state, p.level), 2); + Success + } else { + Consume + } + } + Class::Bell => { + let click_y = hit.y - f64::from(pos.y); + let proper = axis_of(face) != Axis::Y && click_y <= 0.8124 && { + let facing_axis = axis_of(b.facing(state)); + match table.text(state, p.attachment) { + "floor" => facing_axis == axis_of(face), + "single_wall" | "double_wall" => facing_axis != axis_of(face), + "ceiling" => true, + _ => false, + } + }; + if proper { + self.emit(LevelEvent::Sound { + pos, + sound: "minecraft:block.bell.use".into(), + volume: 2.0, + pitch: 1.0, + }); + self.game_event(pos, "minecraft:block_change"); + Success + } else { + Pass + } + } + Class::AbstractFurnace + | Class::Anvil + | Class::Barrel + | Class::Beacon + | Class::BrewingStand + | Class::CartographyTable + | Class::Chest + | Class::Crafter + | Class::CraftingTable + | Class::Dispenser + | Class::EnchantingTable + | Class::EnderChest + | Class::Grindstone + | Class::Hopper + | Class::Loom + | Class::ShulkerBox + | Class::Sign + | Class::SmithingTable + | Class::Stonecutter + | Class::Lectern => { + self.player_effect(pos, state, PlayerEffect::OpenMenu); + Success + } + Class::Command | Class::Structure | Class::Jigsaw => { + if player.game_master { + self.player_effect(pos, state, PlayerEffect::OpenMenu); + Success + } else { + Pass + } + } + _ => continue, + }; + } + let _ = below; + Pass + } + + /// `RedstoneWireBlock.useWithoutItem`: toggle between dot and cross. + fn wire_use( + &mut self, + pos: BlockPos, + state: BlockStateId, + player: PlayerContext, + ) -> InteractionResult { + let b = self.b; + if !player.may_build { + return InteractionResult::Pass; + } + let connected = |s: BlockStateId, d: Direction| b.table.text(s, b.dir_prop(d)) != "none"; + let horizontal = super::update::HORIZONTAL; + let cross = horizontal.into_iter().all(|d| connected(state, d)); + let dot = !horizontal.into_iter().any(|d| connected(state, d)); + if !(cross || dot) { + return InteractionResult::Pass; + } + 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) + } else { + self.wire_cross_state(power) + }; + let next = self.wire_connection_state(base, pos); + if next == state { + return InteractionResult::Pass; + } + 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) + { + let block = b.block(next); + self.update_neighbors_at_except(relative, block, direction.opposite()); + } + } + InteractionResult::Success + } + + /// `DragonEggBlock.teleport`. + 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 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) + { + // BlockUtil.packDifferenceInPosition(pos, test, 16, 8, 16) + let packed = ((dx + 16) << 16) | ((dy + 8) << 8) | (dz + 16); + self.level_event(2015, pos, packed); + self.set_block(test, state, 2); + self.remove_block(pos, false); + return; + } + } + } +} + +impl Behaviours { + /// `BlockState.useWithoutItem` for a right-click on `pos` (hit face and + /// absolute hit location as in `BlockHitResult`). + pub fn use_without_item( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + face: Direction, + hit: Vec3, + player: PlayerContext, + ) -> InteractionResult { + 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 new file mode 100644 index 000000000..ee7dca6b9 --- /dev/null +++ b/crates/horizon-world/src/level/mod.rs @@ -0,0 +1,591 @@ +//! Server-side vanilla block behaviour: `Level.setBlock` with neighbour and +//! shape-update propagation, scheduled block/fluid ticks, random ticks, +//! placement (`getStateForPlacement`) and interaction (`useWithoutItem`). +//! +//! The library is client-agnostic. A game owns its chunk storage and exposes +//! it through [`LevelAccess`]; it also owns one [`Ticks`] per level (scheduled +//! tick queues, the in-flight neighbour-update queue and the random-tick LCG). +//! [`Behaviours`] holds immutable tables loaded once from the pinned client +//! resources (`block-behaviours.json`, `gameplay-facts.json`, +//! `block-tags.json`, `cached-collision.nbt`; see +//! `tools/prepare_native_client.py`). +//! +//! # Driving a level +//! +//! Per server tick, in vanilla order (`ServerLevel.tick`): +//! 1. [`Behaviours::tick_scheduled`] runs due block ticks then fluid ticks +//! (`blockTicks.tick(time, 65536, ...)`, then `fluidTicks`). +//! 2. For every ticking chunk, [`Behaviours::tick_chunk_random`] performs +//! `ServerLevel.tickChunk`'s random ticks: for each non-empty section, +//! `randomTickSpeed` (game rule, default 3) positions are drawn with +//! `Level.getBlockRandomPos` and randomly-ticking block and fluid states are +//! ticked. The caller decides which sections are randomly ticking (vanilla +//! counts randomly-ticking states per section); [`Behaviours::random_tick`] +//! ticks a single position. +//! 3. [`Behaviours::run_block_events`] runs queued block events (pistons), +//! then (after entities) [`Behaviours::tick_block_entities`] advances +//! moving pistons ([`Ticks::moving_pistons`]). +//! 4. Player actions call [`Behaviours::place_block`] / +//! [`Behaviours::use_without_item`] / [`Behaviours::destroy_block`]. +//! +//! Every block mutation goes through [`Behaviours::set_block`] with vanilla's +//! update flags ([`flags`]). The library writes storage only through +//! [`LevelAccess::set_raw`]; the caller updates heightmaps, light, block +//! entities and render meshes for the written position. +//! +//! Side effects the library cannot perform (sounds, particles, item drops, +//! spawning falling-block or TNT entities, growing trees) are reported as +//! [`LevelEvent`]s through [`LevelAccess::emit`], in vanilla call order. +//! +//! Randomness is drawn from [`LevelAccess::random`] (vanilla `level.random`, a +//! `LegacyRandomSource`) in the same order as vanilla. +//! +//! # Integration sketch +//! +//! ```ignore +//! use horizon_world::level::{self, Behaviours, LevelAccess, LevelEvent, PlaceContext, Ticks, flags}; +//! +//! struct GameLevel { chunks: Chunks, random: LegacyRandom, time: i64, events: Vec } +//! impl LevelAccess for GameLevel { +//! fn block_state(&self, pos: BlockPos) -> BlockStateId { self.chunks.get(pos) } +//! fn set_raw(&mut self, pos: BlockPos, state: BlockStateId) -> Option { +//! let old = self.chunks.set(pos, state)?; // also mark light/heightmap/mesh dirty +//! Some(old) +//! } +//! fn is_loaded(&self, pos: BlockPos) -> bool { self.chunks.contains(pos.chunk()) } +//! fn random(&mut self) -> &mut LegacyRandom { &mut self.random } +//! fn game_time(&self) -> i64 { self.time } +//! fn block_light(&self, pos: BlockPos) -> i32 { self.chunks.block_light(pos) } +//! fn sky_light(&self, pos: BlockPos) -> i32 { self.chunks.sky_light(pos) } +//! fn emit(&mut self, event: LevelEvent) { self.events.push(event) } +//! } +//! +//! let registry = level::data::load_registry(&resources)?; +//! let behaviours = Behaviours::load(®istry, &resources)?; +//! let mut ticks = Ticks::new(seed as i32); +//! ticks.add_empty_chunk(chunk_pos)?; // when a chunk loads (remove_chunk on unload) +//! +//! // Every server tick: +//! level.time += 1; +//! behaviours.tick_scheduled(&mut level, &mut ticks); +//! for chunk in ticking_chunks { +//! behaviours.tick_chunk_random(&mut level, &mut ticks, chunk, randomly_ticking_section_min_ys(chunk)); +//! } +//! behaviours.run_block_events(&mut level, &mut ticks); +//! /* tick entities */ +//! behaviours.tick_block_entities(&mut level, &mut ticks); +//! for event in level.events.drain(..) { /* play sounds, spawn drops/falling blocks, grow trees */ } +//! +//! // Player actions: +//! behaviours.place_block(&mut level, &mut ticks, &PlaceContext { clicked_pos, face, hit, inside: false, +//! 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: +//! behaviours.falling_block_landed(&mut level, &mut ticks, landing_pos, carried_state, false); +//! ``` +use crate::{ + fluid::{FluidBlockBindings, FluidKind, FluidState}, + registry::{BlockRegistry, BlockStateId}, +}; +use horizon_core::{ + geometry::{Aabb, Direction, VoxelShape}, + position::{BlockPos, ChunkPos}, + random::LegacyRandom, +}; +use std::{collections::HashMap, io, path::Path, sync::Arc, sync::Mutex}; + +pub mod classes; +pub mod data; +pub mod states; +pub mod ticks; + +mod falling; +mod fluids; +mod hooks; +mod interact; +pub mod pistons; +mod place; +mod query; +mod rails; +mod redstone; +mod shapes; +mod speleothem; +mod survive; +mod tick; +mod update; + +#[cfg(test)] +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 states::{BlockId, PropKey, StateTable}; +pub use tick::{Precipitation, PrecipitationKind}; +pub use ticks::Ticks; + +/// `Block.UPDATE_*` flags accepted by [`Behaviours::set_block`]. +pub mod flags { + pub const UPDATE_NEIGHBORS: i32 = 1; + pub const UPDATE_CLIENTS: i32 = 2; + pub const UPDATE_INVISIBLE: i32 = 4; + pub const UPDATE_IMMEDIATE: i32 = 8; + pub const UPDATE_KNOWN_SHAPE: i32 = 16; + pub const UPDATE_SUPPRESS_DROPS: i32 = 32; + pub const UPDATE_MOVE_BY_PISTON: i32 = 64; + pub const UPDATE_SKIP_SHAPE_UPDATE_ON_WIRE: i32 = 128; + pub const UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS: i32 = 256; + pub const UPDATE_SKIP_ON_PLACE: i32 = 512; + pub const UPDATE_NONE: i32 = 260; + pub const UPDATE_ALL: i32 = 3; + pub const UPDATE_ALL_IMMEDIATE: i32 = 11; + pub const UPDATE_SKIP_ALL_SIDEEFFECTS: i32 = 816; + /// `Block.UPDATE_LIMIT`, the recursion budget of shape updates. + pub const UPDATE_LIMIT: i32 = 512; +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Dimension { + Overworld, + Nether, + End, +} + +/// Game rules consulted by block behaviour (vanilla defaults). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct GameRules { + pub water_source_conversion: bool, + pub lava_source_conversion: bool, + pub random_tick_speed: i32, + pub block_drops: bool, + pub mob_griefing: bool, + pub max_snow_accumulation_height: i32, +} +impl Default for GameRules { + fn default() -> Self { + Self { + water_source_conversion: true, + lava_source_conversion: false, + random_tick_speed: 3, + block_drops: true, + mob_griefing: true, + max_snow_accumulation_height: 1, + } + } +} + +/// Entity filters for the entity-sensing blocks (pressure plates, tripwire). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EntityQuery { + /// Any entity that does not ignore block triggers (wooden plates, tripwire). + Everything, + /// Living entities only (stone plates). + Mobs, +} + +/// Side effects reported to the caller, in vanilla call order. +#[derive(Clone, Debug, PartialEq)] +pub enum LevelEvent { + /// `Level.levelEvent(type, pos, data)`, using vanilla's numeric event IDs + /// (e.g. 2001 block destroyed with `data` = state ID, 1501 lava + /// extinguished, 1009 fire extinguished, 1502 redstone torch burnout, + /// 2009 dripping water/sponge, 1033/1034 ... per `LevelEvent.java`). + LevelEvent { id: i32, pos: BlockPos, data: i32 }, + /// `Level.playSound(null, pos, sound, BLOCKS, volume, pitch)`. + Sound { + pos: BlockPos, + sound: Arc, + volume: f32, + pitch: f32, + }, + /// `Block.dropResources(state, level, pos)`: the caller evaluates the + /// block's loot table (no tool, no breaker) and pops the items. + DropResources { pos: BlockPos, state: BlockStateId }, + /// `FallingBlockEntity.fall`: the block at `pos` was already replaced by its + /// fluid's legacy block; the caller spawns and simulates a falling-block + /// entity carrying `state` and calls [`Behaviours::falling_block_landed`] + /// (or drops the item) when it lands. + FallingBlock { pos: BlockPos, state: BlockStateId }, + /// A sapling reached stage 1 and tried to grow (`TreeGrower.growTree`). + /// The caller runs the grower's configured feature and, on success, + /// replaces the sapling (vanilla leaves the sapling on failure). + GrowTree { + pos: BlockPos, + state: BlockStateId, + grower: Arc, + }, + /// A configured feature placement request from a bonemealed or random-ticked + /// block (huge mushrooms, fungi). The block was already removed when vanilla + /// does so before placing; on failure the caller restores `state`. + PlaceFeature { + pos: BlockPos, + state: BlockStateId, + feature: Arc, + }, + /// `TntBlock.prime`: the TNT block is removed; spawn primed TNT. + PrimeTnt { pos: BlockPos }, + /// Block-entity or entity side effects the caller implements: `"dispense"` + /// (dispenser/dropper/crafter scheduled tick), `"hatch"` (frogspawn + /// hatched into tadpoles; the block is already destroyed). + BlockEvent { + pos: BlockPos, + state: BlockStateId, + kind: &'static str, + }, + /// A player-side effect of [`Behaviours::use_without_item`]. + Player { + pos: BlockPos, + state: BlockStateId, + effect: PlayerEffect, + }, + /// `Level.gameEvent` (vibration system), by vanilla identifier. + GameEvent { pos: BlockPos, event: &'static str }, +} + +/// The world as seen by block behaviour. Implemented by the game and tests. +pub trait LevelAccess { + /// `getBlockState`. Unloaded or out-of-bounds positions read as air. + fn block_state(&self, pos: BlockPos) -> BlockStateId; + /// Storage write (`LevelChunkSection.setBlockState`). Returns the previous + /// state, or None when nothing could be stored (unloaded chunk). + fn set_raw(&mut self, pos: BlockPos, state: BlockStateId) -> Option; + fn is_loaded(&self, pos: BlockPos) -> bool; + /// Inclusive minimum and exclusive maximum build height. + fn min_y(&self) -> i32 { + -64 + } + fn max_y(&self) -> i32 { + 320 + } + /// Vanilla `level.random` (a `LegacyRandomSource`). + fn random(&mut self) -> &mut LegacyRandom; + fn game_time(&self) -> i64; + fn block_light(&self, _pos: BlockPos) -> i32 { + 0 + } + fn sky_light(&self, _pos: BlockPos) -> i32 { + 15 + } + /// `Level.getSkyDarken` (0 at noon, up to 11 at night). + fn sky_darken(&self) -> i32 { + 0 + } + fn is_raining(&self) -> bool { + false + } + fn is_thundering(&self) -> bool { + false + } + fn is_raining_at(&self, _pos: BlockPos) -> bool { + false + } + fn dimension(&self) -> Dimension { + Dimension::Overworld + } + fn game_rules(&self) -> GameRules { + GameRules::default() + } + /// `Difficulty.getId()` (peaceful 0 .. hard 3). + fn difficulty(&self) -> i32 { + 2 + } + /// `ServerLevel.canSpreadFireAround` (fire-spread radius around players). + fn can_spread_fire_around(&self, _pos: BlockPos) -> bool { + true + } + /// `Level.isUnobstructed(state, pos, context)`: whether the state's + /// collision shape at `pos` would intersect an entity. + fn is_unobstructed(&self, _pos: BlockPos, _state: BlockStateId) -> bool { + true + } + /// 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 { + 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 { + 0 + } + /// Biome answers for a precipitation tick at the column of `pos` (see + /// [`Precipitation`]); None skips snow/ice formation and cauldron filling. + fn precipitation(&self, _pos: BlockPos) -> Option { + None + } + /// Count of entities intersecting `area` that trigger pressure plates or + /// tripwires under `query`. + fn count_entities(&self, _area: Aabb, _query: EntityQuery) -> usize { + 0 + } + /// `ServerLevel.isPositionTickingWithEntitiesLoaded` for scheduled ticks. + fn is_ticking_chunk(&self, _chunk: ChunkPos) -> bool { + true + } + fn emit(&mut self, _event: LevelEvent) {} +} + +/// Raw brightness as `Level.getRawBrightness(pos, skyDarken)`. +pub fn raw_brightness(level: &L, pos: BlockPos, sky_darken: i32) -> i32 { + (level.sky_light(pos) - sky_darken).max(level.block_light(pos)) +} + +/// Immutable vanilla block-behaviour tables. Build once with [`Behaviours::load`]. +pub struct Behaviours { + pub table: StateTable, + pub props: Props, + pub named: Named, + pub tags: Tags, + all_tags: HashMap>, + facts: Vec, + shapes: Vec, + shape_info: Vec, + pub fluid_tags: data::FluidTags, + blocks: Vec, + items: HashMap, + liquid_blocks: FluidBlockBindings, + /// Uncached (position- or block-entity-dependent) collision shapes. + dynamic: HashMap, + occlusion_cache: Mutex>, +} + +impl Behaviours { + /// Load from a prepared client resource directory (`.local/horizon-client/`). + pub fn load(registry: &BlockRegistry, resources_dir: &Path) -> io::Result { + data::load(registry, resources_dir) + } + pub fn facts(&self, state: BlockStateId) -> &StateFacts { + &self.facts[state.0 as usize] + } + pub fn block_data(&self, block: BlockId) -> &BlockData { + &self.blocks[block.0 as usize] + } + pub fn data(&self, state: BlockStateId) -> &BlockData { + self.block_data(self.table.block(state)) + } + pub fn block(&self, state: BlockStateId) -> BlockId { + self.table.block(state) + } + pub fn item_binding(&self, item: &str) -> Option<&ItemBinding> { + self.items.get(item) + } + pub fn tag(&self, name: &str) -> Option<&data::BlockSet> { + self.all_tags.get(name).map(|s| &**s) + } + pub fn fluid(&self, state: BlockStateId) -> FluidState { + self.facts(state).fluid + } + /// `FluidState.createLegacyBlock`. + pub fn legacy_block(&self, fluid: FluidState) -> BlockStateId { + self.liquid_blocks.block(fluid) + } + /// Cached collision shape (`getCollisionShape(level, pos)` for states whose + /// shape does not depend on the world); None for dynamic shapes. + pub fn collision_shape(&self, state: BlockStateId) -> Option<&VoxelShape> { + let index = self.facts(state).shape; + (index >= 0).then(|| &self.shapes[index as usize]) + } + /// Precomputed shape queries; dynamic shapes read as empty. + pub fn shape_info(&self, state: BlockStateId) -> data::ShapeInfo { + let index = self.facts(state).shape; + if index < 0 { + data::ShapeInfo::default() + } else { + self.shape_info[index as usize] + } + } + pub(crate) fn has_flag(&self, state: BlockStateId, flag: u32) -> bool { + self.facts(state).flags & flag != 0 + } + pub fn is_air(&self, state: BlockStateId) -> bool { + self.has_flag(state, data::state_flags::AIR) + } + pub fn is_solid(&self, state: BlockStateId) -> bool { + self.has_flag(state, data::state_flags::SOLID) + } + pub fn is_replaceable(&self, state: BlockStateId) -> bool { + self.has_flag(state, data::state_flags::REPLACEABLE) + } + pub fn is_randomly_ticking(&self, state: BlockStateId) -> bool { + self.has_flag(state, data::state_flags::RANDOM_TICKS) + } + /// `isFaceSturdy(level, pos, direction, FULL)` from the empty-level cache. + pub fn is_face_sturdy(&self, state: BlockStateId, direction: Direction) -> bool { + self.facts(state).sturdy & (1 << direction as u32) != 0 + } + pub fn is_face_sturdy_center(&self, state: BlockStateId, direction: Direction) -> bool { + self.facts(state).sturdy & (1 << (6 + direction as u32)) != 0 + } + pub fn is_face_sturdy_rigid(&self, state: BlockStateId, direction: Direction) -> bool { + self.facts(state).sturdy & (1 << (12 + direction as u32)) != 0 + } + /// Tick type ID of a fluid for [`Ticks::schedule_fluid`]. + pub fn fluid_kind(&self, state: BlockStateId) -> FluidKind { + self.fluid(state).kind() + } +} + +/// Level mutation entry points (all keep vanilla update semantics). +impl Behaviours { + /// `Level.setBlock(pos, state, flags)` with vanilla's update limit (512). + /// Returns false when nothing was written (unloaded, out of bounds, or + /// the state was already present). + pub fn set_block( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + state: BlockStateId, + flags: i32, + ) -> bool { + self.sim(level, ticks).set_block(pos, state, flags) + } + /// `Level.removeBlock(pos, movedByPiston)`: replace with the fluid's block. + pub fn remove_block( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + moved_by_piston: bool, + ) -> bool { + self.sim(level, ticks).remove_block(pos, moved_by_piston) + } + /// `Level.destroyBlock(pos, dropResources)`: destroy particles (2001), + /// optional drops, and replacement by the block's fluid. + pub fn destroy_block( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + drop: bool, + ) -> bool { + self.sim(level, ticks) + .destroy_block(pos, drop, flags::UPDATE_LIMIT) + } + /// A player breaking a block (`playerWillDestroy` + `Level.destroyBlock` + /// without drops; the caller handles the player's loot/tool). Double + /// blocks (doors, tall plants, beds) remove their other half as vanilla. + pub fn player_destroy_block( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + creative: bool, + ) -> bool { + self.sim(level, ticks).player_destroy(pos, creative) + } + /// `BlockState.canSurvive(level, pos)`. + pub fn can_survive( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + state: BlockStateId, + ) -> bool { + self.sim(level, ticks).can_survive(state, pos) + } + /// `BlockState.updateShape(level, ticks, pos, direction, neighbourPos, + /// neighbourState, random)`: the state `state` at `pos` would take after its + /// neighbour in `direction` became `neighbour` (ticks it requests are queued). + #[allow(clippy::too_many_arguments)] + pub fn update_shape( + &self, + level: &mut L, + ticks: &mut Ticks, + state: BlockStateId, + pos: BlockPos, + direction: Direction, + neighbour_pos: BlockPos, + neighbour: BlockStateId, + ) -> BlockStateId { + 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) + } + /// `Level.updateNeighborsAt(pos, block)`: notify the six neighbours. + pub fn update_neighbors_at( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + block: BlockId, + ) { + self.sim(level, ticks).update_neighbors_at(pos, block); + } + /// Entity collision with a block (`entityInside`) for the entity-sensing + /// blocks: pressure plates, tripwires and buttons hit by arrows are + /// re-evaluated through [`LevelAccess::count_entities`]. + pub fn entity_inside( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) { + self.sim(level, ticks).entity_inside(pos); + } + /// Redstone signal queries (`SignalGetter`). + pub fn has_neighbor_signal( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) -> bool { + self.sim(level, ticks).has_neighbor_signal(pos) + } + pub fn best_neighbor_signal( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) -> i32 { + self.sim(level, ticks).best_neighbor_signal(pos) + } +} + +/// One mutable view used by the ported behaviour code. +pub(crate) struct Sim<'a, L: LevelAccess + ?Sized> { + pub b: &'a Behaviours, + pub level: &'a mut L, + pub ticks: &'a mut Ticks, + /// `RedstoneWireBlock.shouldSignal` is false while a wire samples its + /// neighbours (`getBlockSignal`). + 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> { + Sim { + b: self, + level, + ticks, + wire_signal_off: std::cell::Cell::new(false), + } + } +} diff --git a/crates/horizon-world/src/level/pistons.rs b/crates/horizon-world/src/level/pistons.rs new file mode 100644 index 000000000..0beb512c8 --- /dev/null +++ b/crates/horizon-world/src/level/pistons.rs @@ -0,0 +1,761 @@ +//! Pistons: `PistonBaseBlock` (signal checks, block events, `moveBlocks`), +//! `PistonStructureResolver`, `PistonHeadBlock`, and the +//! `PistonMovingBlockEntity` progress ticking, plus the level's block-event +//! queue (`ServerLevel.blockEvent` / `runBlockEvents`). +//! +//! Entity pushing by moving blocks is the caller's (see `piston_movement`). +use super::{ + Behaviours, LevelAccess, LevelEvent, Sim, Ticks, + data::PushReaction, + states::BlockId, + update::{above, rel}, +}; +use crate::{ + java_hash_map::{JavaHashMap, JavaKey}, + registry::BlockStateId, +}; +use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource}; +use std::cmp::Ordering; + +/// `PistonMovingBlockEntity` state, owned by [`Ticks::moving_pistons`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MovingPiston { + pub moved_state: BlockStateId, + pub direction: Direction, + pub extending: bool, + pub source: bool, + pub progress: f32, + pub progress_o: f32, + pub last_ticked: i64, + /// Identity of this block entity (a replaced entity is a new ticker). + pub id: u64, +} +impl MovingPiston { + pub fn movement_direction(&self) -> Direction { + if self.extending { + self.direction + } else { + self.direction.opposite() + } + } +} + +/// `BlockEventData`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BlockEventData { + pub pos: BlockPos, + pub block: BlockId, + pub param_a: i32, + pub param_b: i32, +} + +#[derive(PartialEq, Eq)] +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) + } + 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)), + ) + } + fn tie_break(&self, _other: &Self) -> Ordering { + Ordering::Less + } +} + +struct Resolver { + piston_pos: BlockPos, + extending: bool, + start: BlockPos, + push_direction: Direction, + piston_direction: Direction, + to_push: Vec, + to_destroy: Vec, +} + +fn rel_n(pos: BlockPos, direction: Direction, n: i32) -> BlockPos { + let [x, y, z] = direction.normal(); + pos.offset(x * n, y * n, z * n) +} + +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, + }; + if !self.ticks.block_events.contains(&event) { + self.ticks.block_events.push(event); + } + } + /// `BlockState.triggerEvent`. + fn trigger_event(&mut self, state: BlockStateId, pos: BlockPos, a: i32, b: i32) -> bool { + let data = self.b.data(state); + if data.is(super::classes::Class::PistonBase) { + self.piston_trigger_event(pos, state, a, b) + } else { + false + } + } + + // ---- 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) + } + fn set_moving_piston(&mut self, pos: BlockPos, mut piston: MovingPiston) { + self.ticks.moving_pistons.retain(|(p, _)| *p != pos); + self.ticks.next_block_entity_id += 1; + piston.id = self.ticks.next_block_entity_id; + 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)?; + Some(self.ticks.moving_pistons.remove(index).1) + } + /// `PistonMovingBlockEntity.finalTick`. + fn moving_piston_final_tick(&mut self, pos: BlockPos) { + let Some(piston) = self.moving_piston(pos) else { + return; + }; + if piston.progress_o >= 1.0 { + return; + } + 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) + }; + self.set_block_and_update(pos, new); + let block = b.block(new); + self.neighbor_changed_at(pos, block); + } + } + /// `PistonMovingBlockEntity.tick` (entity pushing excluded). + fn moving_piston_tick(&mut self, pos: BlockPos) { + let Some(mut piston) = self.moving_piston(pos) else { + return; + }; + let b = self.b; + piston.last_ticked = self.level.game_time(); + piston.progress_o = piston.progress; + if piston.progress_o >= 1.0 { + self.remove_moving_piston(pos); + if b.is_block(self.state(pos), b.named.moving_piston) { + 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, + ); + } else { + if b.is_waterlogged(new) { + new = b.table.set_bool(new, b.props.waterlogged, false); + } + self.set_block(pos, new, 67); + let block = b.block(new); + self.neighbor_changed_at(pos, block); + } + } + } else { + piston.progress = (piston.progress + 0.5).min(1.0); + if let Some(entry) = self + .ticks + .moving_pistons + .iter_mut() + .find(|(p, _)| *p == pos) + { + entry.1 = piston; + } + } + } + + // ---- PistonBaseBlock ---- + fn is_sticky_piston(&self, state: BlockStateId) -> bool { + self.b.is_block(state, self.b.named.sticky_piston) + } + fn piston_neighbor_signal(&self, pos: BlockPos, push: Direction) -> bool { + for direction in Direction::ALL { + if direction != push && self.has_signal(rel(pos, direction), direction) { + return true; + } + } + if self.has_signal(pos, Direction::Down) { + return true; + } + let up = above(pos); + 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) { + let b = self.b; + let direction = b.facing(state); + let extend = self.piston_neighbor_signal(pos, direction); + let extended = b.table.bool(state, b.props.extended); + let block = b.block(state); + if extend && !extended { + if self.piston_resolve(pos, direction, true).is_some() { + self.block_event(pos, block, 0, direction as i32); + } + } else if !extend && extended { + let pushed_pos = rel_n(pos, direction, 2); + let pushed = self.state(pushed_pos); + let mut event = 1; + 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) + { + event = 2; + } + } + } + self.block_event(pos, block, event, direction as i32); + } + } + /// `PistonBaseBlock.isPushable`. + 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 { + return false; + } + if b.is_air(state) { + return true; + } + if direction == Direction::Down && pos.y == min_y { + return false; + } + 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); + if !is_piston { + if b.facts(state).hardness == -1.0 { + return false; + } + match b.facts(state).push { + PushReaction::Immoveable => return false, + PushReaction::Popped => return allow_destroyable, + PushReaction::Push => return direction == connection, + _ => {} + } + } else if b.table.bool(state, b.props.extended) { + return false; + } + !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) + } + 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), + ); + 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)> { + 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() + }, + piston_direction: direction, + to_push: Vec::new(), + to_destroy: Vec::new(), + }; + let next = self.state(r.start); + if !self.is_pushable(next, r.start, r.push_direction, false, r.piston_direction) { + if r.extending && self.b.facts(next).push == PushReaction::Popped { + r.to_destroy.push(r.start); + return Some((r.to_push, r.to_destroy, r.push_direction)); + } + return None; + } + let start = r.start; + let push = r.push_direction; + if !self.add_block_line(&mut r, start, push) { + return None; + } + let mut i = 0; + while i < r.to_push.len() { + let pos = r.to_push[i]; + if self.is_slime_or_honey(self.state(pos)) && !self.add_branching_blocks(&mut r, pos) { + return None; + } + i += 1; + } + Some((r.to_push, r.to_destroy, r.push_direction)) + } + fn add_block_line(&self, r: &mut Resolver, start: BlockPos, direction: Direction) -> bool { + let mut next = self.state(start); + 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) + { + return true; + } + let mut count = 1; + if count + r.to_push.len() > 12 { + return false; + } + while self.is_slime_or_honey(next) { + let pos = rel_n(start, r.push_direction.opposite(), count as i32); + let previous = next; + 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(), + ) + || pos == r.piston_pos + { + break; + } + count += 1; + if count + r.to_push.len() > 12 { + return false; + } + } + let mut added = 0; + for i in (0..count).rev() { + r.to_push + .push(rel_n(start, r.push_direction.opposite(), i as i32)); + added += 1; + } + let mut i = 1; + loop { + let pos = rel_n(start, r.push_direction, i); + if let Some(collision) = r.to_push.iter().position(|p| *p == pos) { + 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) + { + return false; + } + } + return true; + } + next = self.state(pos); + 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 + { + return false; + } + if self.b.facts(next).push == PushReaction::Popped { + r.to_destroy.push(pos); + return true; + } + if r.to_push.len() >= 12 { + return false; + } + r.to_push.push(pos); + added += 1; + i += 1; + } + } + fn reorder_at_collision(&self, r: &mut Resolver, added: usize, collision: usize) { + let len = r.to_push.len(); + let head: Vec = r.to_push[..collision].to_vec(); + let last_line: Vec = r.to_push[len - added..].to_vec(); + let middle: Vec = r.to_push[collision..len - added].to_vec(); + r.to_push.clear(); + r.to_push.extend(head); + r.to_push.extend(last_line); + r.to_push.extend(middle); + } + fn add_branching_blocks(&self, r: &mut Resolver, from: BlockPos) -> bool { + let from_state = self.state(from); + for direction in Direction::ALL { + 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) + { + return false; + } + } + } + true + } + 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" }, + ) + } + /// `PistonBaseBlock.moveBlocks`. + 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 { + return false; + }; + let mut delete_after: JavaHashMap = JavaHashMap::default(); + let mut shapes = Vec::with_capacity(to_push.len()); + for pos in &to_push { + let state = self.state(*pos); + shapes.push(state); + 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() + }; + for pos in to_destroy.iter().rev() { + let state = self.state(*pos); + self.drop_resources(state, *pos); + self.set_block(*pos, b.air(), 18); + self.game_event(*pos, "minecraft:block_destroy"); + to_update.push(state); + } + for (i, pos) in to_push.iter().enumerate().rev() { + 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, + ); + self.set_block(target, moving, 324); + self.set_moving_piston( + target, + MovingPiston { + moved_state: shapes[i], + direction, + extending, + source: false, + progress: 0.0, + progress_o: 0.0, + last_ticked: 0, + id: 0, + }, + ); + to_update.push(state); + } + if extending { + let head = b.table.set_text( + b.table + .set_dir(b.default_of(b.named.piston_head), b.props.facing, direction), + b.props.kind, + if sticky { "sticky" } else { "normal" }, + ); + let moving = self.moving_piston_state(direction, sticky); + delete_after.remove(&PosKey(arm)); + self.set_block(arm, moving, 324); + self.set_moving_piston( + arm, + MovingPiston { + moved_state: head, + direction, + extending: true, + source: true, + progress: 0.0, + progress_o: 0.0, + last_ticked: 0, + id: 0, + }, + ); + } + let air = b.air(); + 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); + } + for (pos, old) in &entries { + self.update_indirect_neighbour_shapes(*old, *pos, 2, super::flags::UPDATE_LIMIT); + self.update_neighbour_shapes(air, *pos, 2, super::flags::UPDATE_LIMIT); + self.update_indirect_neighbour_shapes(air, *pos, 2, super::flags::UPDATE_LIMIT); + } + let mut index = 0; + for pos in to_destroy.iter().rev() { + let state = to_update[index]; + index += 1; + self.affect_neighbors_after_removal(state, *pos, false); + self.update_indirect_neighbour_shapes(state, *pos, 2, super::flags::UPDATE_LIMIT); + let block = b.block(state); + self.update_neighbors_at(*pos, block); + } + for pos in to_push.iter().rev() { + let block = b.block(to_update[index]); + index += 1; + self.update_neighbors_at(*pos, block); + } + if extending { + self.update_neighbors_at(arm, b.named.piston_head); + } + let _ = push_direction; + true + } + /// `PistonBaseBlock.triggerEvent`. + 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); + let extended_state = b.table.set_bool(state, p.extended, true); + let sticky = self.is_sticky_piston(state); + let extend = self.piston_neighbor_signal(pos, direction); + if extend && (a == 1 || a == 2) { + self.set_block(pos, extended_state, 2); + return false; + } + if !extend && a == 0 { + return false; + } + if a == 0 { + if !self.piston_move_blocks(pos, direction, true, sticky) { + return false; + } + self.set_block(pos, extended_state, 67); + let pitch = self.random().next_float() * 0.25 + 0.6; + self.emit(LevelEvent::Sound { + pos, + sound: "minecraft:block.piston.extend".into(), + volume: 0.5, + pitch, + }); + self.game_event(pos, "minecraft:block_activate"); + } else if a == 1 || a == 2 { + 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], + ); + self.set_moving_piston( + pos, + MovingPiston { + moved_state: piston_default, + direction, + extending: false, + source: true, + progress: 0.0, + progress_o: 0.0, + last_ticked: 0, + id: 0, + }, + ); + self.update_neighbors_at(pos, b.named.moving_piston); + self.update_neighbour_shapes(moving, pos, 2, super::flags::UPDATE_LIMIT); + if sticky { + let two = rel_n(pos, direction, 2); + let moving_state = self.state(two); + let mut piston_piece = false; + if b.is_block(moving_state, b.named.moving_piston) { + if let Some(entity) = self.moving_piston(two) { + if entity.direction == direction && entity.extending { + self.moving_piston_final_tick(two); + piston_piece = true; + } + } + } + if !piston_piece { + 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, + ) + || (b.facts(moving_state).push != PushReaction::PushPull && !is_piston) + { + self.remove_block(rel(pos, direction), false); + } else { + self.piston_move_blocks(pos, direction, false, sticky); + } + } + } else { + self.remove_block(rel(pos, direction), false); + } + let pitch = self.random().next_float() * 0.15 + 0.6; + self.emit(LevelEvent::Sound { + pos, + sound: "minecraft:block.piston.contract".into(), + volume: 0.5, + pitch, + }); + self.game_event(pos, "minecraft:block_deactivate"); + } + true + } + + // ---- 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) + } + 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)) + } +} + +impl Behaviours { + /// `ServerLevel.runBlockEvents`: run queued block events (piston moves). + /// Call once per tick after scheduled and random ticks. + pub fn run_block_events(&self, level: &mut L, ticks: &mut Ticks) { + let mut reschedule = Vec::new(); + while !ticks.block_events.is_empty() { + let event = ticks.block_events.remove(0); + if !level.is_ticking_chunk(event.pos.chunk()) { + reschedule.push(event); + continue; + } + let mut sim = self.sim(level, ticks); + let state = sim.state(event.pos); + if self.block(state) == event.block { + sim.trigger_event(state, event.pos, event.param_a, event.param_b); + } + } + for event in reschedule { + if !ticks.block_events.contains(&event) { + ticks.block_events.push(event); + } + } + } + /// `Level.tickBlockEntities` for moving pistons (the only block entities + /// 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(); + for (pos, id) in tickers { + 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 new file mode 100644 index 000000000..01e9527c2 --- /dev/null +++ b/crates/horizon-world/src/level/place.rs @@ -0,0 +1,1634 @@ +//! Block placement: `BlockItem.place`, `BlockPlaceContext`, +//! `canBeReplaced(state, context)` and `getStateForPlacement` for every +//! overriding class. +use super::{ + Behaviours, LevelAccess, LevelEvent, Sim, Ticks, + classes::Class, + data::ItemKind, + query::{axis_of, clockwise, counter_clockwise, is_horizontal}, + states::BlockId, + update::{HORIZONTAL, above, below, rel}, +}; +use crate::{fluid::FluidState, registry::BlockStateId}; +use horizon_core::{ + geometry::{Axis, Direction, Vec3, trig}, + position::BlockPos, + random::RandomSource, +}; + +/// A player's use-item-on-block action (`UseOnContext` inputs). +#[derive(Clone, Debug)] +pub struct PlaceContext { + /// The block that was hit (`BlockHitResult.getBlockPos`). + pub clicked_pos: BlockPos, + /// The face that was hit. + pub face: Direction, + /// Absolute hit location. + pub hit: Vec3, + /// `BlockHitResult.isInside`. + pub inside: bool, + /// Player view rotation in degrees (`getYRot`, `getXRot`). + pub yaw: f32, + pub pitch: f32, + /// `isSecondaryUseActive` (sneaking). + 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)] +pub enum PlaceOutcome { + /// The block was placed (the caller consumes the item). + Placed { pos: BlockPos, state: BlockStateId }, + /// `InteractionResult.FAIL`. + Failed, +} + +/// `BlockPlaceContext` after resolving the replaced position. +#[derive(Clone, Debug)] +pub(crate) struct Ctx { + pub pos: BlockPos, + pub hit_pos: BlockPos, + pub face: Direction, + pub hit: Vec3, + pub inside: bool, + pub yaw: f32, + pub pitch: f32, + pub sneaking: bool, + pub item: String, + pub replace_clicked: bool, +} + +/// `Direction.orderedByNearest(entity)`. +pub(crate) fn ordered_by_nearest(yaw: f32, pitch: f32) -> [Direction; 6] { + let pitch_rad = pitch * (std::f32::consts::PI / 180.0); + let yaw_rad = -yaw * (std::f32::consts::PI / 180.0); + let pitch_sin = trig::sin(f64::from(pitch_rad)); + let pitch_cos = trig::cos(f64::from(pitch_rad)); + let yaw_sin = trig::sin(f64::from(yaw_rad)); + let yaw_cos = trig::cos(f64::from(yaw_rad)); + let x_pos = yaw_sin > 0.0; + let y_pos = pitch_sin < 0.0; + let z_pos = yaw_cos > 0.0; + let x_yaw = if x_pos { yaw_sin } else { -yaw_sin }; + let y_mag = if y_pos { -pitch_sin } else { pitch_sin }; + 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()] + }; + if x_yaw > z_yaw { + if y_mag > x_mag { + make(ay, ax, az) + } else if z_mag > y_mag { + make(ax, az, ay) + } else { + make(ax, ay, az) + } + } else if y_mag > z_mag { + make(ay, az, ax) + } else if x_mag > y_mag { + make(az, ax, ay) + } else { + make(az, ay, ax) + } +} + +/// `Direction.fromYRot`. +pub(crate) fn from_y_rot(yaw: f64) -> Direction { + let value = ((yaw / 90.0 + 0.5).floor() as i64 & 3) as i32; + super::query::from_2d(value) +} + +/// `RotationSegment.convertToSegment(float)`. +pub(crate) fn rotation_segment(degrees: f32) -> i32 { + ((degrees * (16.0 / 360.0) + 0.5).floor() as i32) & 15 +} +/// `RotationSegment.convertToSegment(Direction)`. +fn rotation_segment_of(direction: Direction) -> i32 { + if !is_horizontal(direction) { + 0 + } else { + super::query::data_2d(direction) << 2 + } +} + +impl Ctx { + fn horizontal_direction(&self) -> Direction { + from_y_rot(f64::from(self.yaw)) + } + fn nearest_looking_directions(&self) -> [Direction; 6] { + let mut directions = ordered_by_nearest(self.yaw, self.pitch); + if self.replace_clicked { + return directions; + } + let target = self.face.opposite(); + if let Some(index) = directions.iter().position(|d| *d == target) { + if index > 0 { + directions.copy_within(0..index, 1); + directions[0] = target; + } + } + directions + } + fn nearest_looking_direction(&self) -> Direction { + ordered_by_nearest(self.yaw, self.pitch)[0] + } + fn nearest_looking_vertical(&self) -> Direction { + if self.pitch < 0.0 { + Direction::Up + } else { + Direction::Down + } + } + fn click_y(&self) -> f64 { + self.hit.y - f64::from(self.pos.y) + } + /// `UseOnContext.getClickedPos` vs `BlockPlaceContext.getClickedPos`. + fn half_from_click(&self) -> bool { + // true = bottom + self.face != Direction::Down && (self.face == Direction::Up || self.click_y() <= 0.5) + } +} + +impl Sim<'_, L> { + fn item_is(&self, ctx: &Ctx, block: BlockId) -> bool { + !ctx.item.is_empty() && *self.b.block_data(block).item == *ctx.item + } + /// `BlockState.canBeReplaced(BlockPlaceContext)`. + pub(crate) fn can_be_replaced(&self, state: BlockStateId, ctx: &Ctx) -> bool { + let b = self.b; + 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)) + }; + 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) + } + 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::PitcherCrop => false, + Class::Scaffolding => self.item_is(ctx, block), + Class::Slab => { + let kind = b.table.text(state, p.kind); + if kind == "double" || !self.item_is(ctx, block) { + false + } else if ctx.replace_clicked { + let above = ctx.hit.y - f64::from(ctx.hit_pos.y) > 0.5; + if kind == "bottom" { + ctx.face == Direction::Up || (above && is_horizontal(ctx.face)) + } else { + ctx.face == Direction::Down || (!above && is_horizontal(ctx.face)) + } + } else { + true + } + } + Class::SnowLayer => { + let layers = b.table.int(state, p.layers); + if !self.item_is(ctx, block) || layers >= 8 { + layers == 1 + } else if ctx.replace_clicked { + ctx.face == Direction::Up + } else { + true + } + } + Class::Vine => { + let clicked = self.state(ctx.pos); + if b.is_block(clicked, block) { + self.vine_count_faces(clicked) < 5 + } else { + default(self) + } + } + _ => continue, + }; + } + default(self) + } + + fn fluid_is_water_source(&self, pos: BlockPos) -> bool { + self.fluid_at(pos) == FluidState::WATER || { + let f = self.fluid_at(pos); + f.kind() == crate::fluid::FluidKind::Water + } + } + + /// `Block.getStateForPlacement(context)` for `block`. + pub(crate) fn state_for_placement( + &mut self, + block: BlockId, + ctx: &Ctx, + ) -> Option { + self.placement_at(block, 0, ctx) + } + + fn placement_at(&mut self, block: BlockId, depth: usize, ctx: &Ctx) -> Option { + let b = self.b; + let chain = &b.block_data(block).chain; + for (index, class) in chain.iter().copied().enumerate().skip(depth) { + if let Some(result) = self.placement_class(class, index, block, ctx) { + return result; + } + } + Some(self.b.default_of(block)) + } + + #[allow(clippy::option_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; + let n = b.named; + let table = &b.table; + let default = b.default_of(block); + let pos = ctx.pos; + let water_source = self.fluid_is_water_source(pos); + let wl = |state: BlockStateId| table.set_bool(state, p.waterlogged, water_source); + macro_rules! sup { + () => { + self.placement_at(block, depth + 1, ctx) + }; + } + let horizontal = ctx.horizontal_direction(); + Some(match class { + Class::AbstractBed => { + let relative = rel(pos, horizontal); + if self.can_be_replaced(self.state(relative), ctx) { + Some(table.set_dir(default, p.facing, horizontal)) + } else { + None + } + } + Class::AbstractFurnace + | Class::Beehive + | Class::CarvedPumpkin + | Class::ChiseledBookShelf + | Class::Diode + | Class::GlazedTerracotta + | Class::Loom + | Class::Stonecutter + | Class::Vault => Some(table.set_dir(default, p.facing, horizontal.opposite())), + Class::Repeater => { + let state = sup!()?; + 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::AbstractSkull => { + let signal = self.has_neighbor_signal(pos); + Some(table.set_bool(default, p.powered, signal)) + } + Class::Skull => { + let state = sup!()?; + Some(table.set_int(state, p.rotation, rotation_segment(ctx.yaw))) + } + Class::WallSkull => { + let mut state = sup!()?; + for direction in ctx.nearest_looking_directions() { + if is_horizontal(direction) { + state = table.set_dir(state, p.facing, direction.opposite()); + if !self.can_be_replaced(self.state(rel(pos, direction)), ctx) { + return Some(Some(state)); + } + } + } + None + } + Class::AmethystCluster => Some(table.set_dir(wl(default), p.facing, ctx.face)), + Class::Anvil => Some(table.set_dir(default, p.facing, clockwise(horizontal))), + Class::BambooStalk => { + if self.fluid_at(pos).kind() != crate::fluid::FluidKind::Empty { + return Some(None); + } + let below_state = self.below_state(pos); + if !b.in_set(below_state, &t.supports_bamboo) { + None + } 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 + }; + Some(table.set_int(default, p.age, age)) + } else { + let above_state = self.above_state(pos); + if b.is_block(above_state, n.bamboo) { + Some(table.set_int(default, p.age, table.int(above_state, p.age))) + } else { + Some(b.default_of(n.bamboo_sapling)) + } + } + } + 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::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 + | Class::SculkShrieker + | Class::Chain + | Class::MangroveRoots + | Class::WaterloggedTransparent => { + let state = if class == Class::Chain + || class == Class::MangroveRoots + || class == Class::WaterloggedTransparent + { + sup!()? + } else { + default + }; + Some(wl(state)) + } + Class::CalibratedSculkSensor => { + let state = sup!()?; + Some(table.set_dir(state, p.facing, horizontal)) + } + 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(), + )) + } + Class::BaseCoralWallFan + | Class::WallBanner + | Class::WallSign + | Class::WallTorch + | Class::ShelfMushroom + | Class::TripWireHook + | Class::Ladder + | Class::Cocoa => { + if class == Class::Ladder && !ctx.replace_clicked { + let behind = self.state(rel(pos, ctx.face.opposite())); + if b.is_block(behind, block) && b.facing(behind) == ctx.face { + return Some(None); + } + } + let mut state = match class { + Class::BaseCoralWallFan => sup!()?, + 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() + }; + state = table.set_dir(state, p.facing, facing); + if self.can_survive(state, pos) { + return Some(Some(match class { + Class::WallSign | Class::Ladder => wl(state), + _ => state, + })); + } + } + } + None + } + Class::RedstoneWallTorch => { + let wall = b.default_of(table.block_by_name("minecraft:wall_torch")?); + let mut found = None; + for direction in ctx.nearest_looking_directions() { + if is_horizontal(direction) { + let state = table.set_dir(wall, p.facing, direction.opposite()); + if self.can_survive(state, pos) { + found = Some(state); + break; + } + } + } + found.map(|state| table.set_dir(default, p.facing, b.facing(state))) + } + Class::WallHangingSign => { + let mut state = default; + 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) + { + return Some(Some(wl(state))); + } + } + } + None + } + 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 direction = from_y_rot(f64::from(ctx.yaw)); + 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) { + attached_to_middle = false; + } + } else if table.has(above_state, p.rotation) { + let segment = table.int(above_state, p.rotation); + let above_direction = match segment { + 0 => Some(Direction::North), + 4 => Some(Direction::East), + 8 => Some(Direction::South), + 12 => Some(Direction::West), + _ => None, + }; + if above_direction.is_some_and(|d| axis_of(d) == axis_of(direction)) { + attached_to_middle = false; + } + } + } + let segment = if !attached_to_middle { + rotation_segment_of(direction.opposite()) + } else { + rotation_segment(ctx.yaw + 180.0) + }; + 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" + }; + 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 + } + } 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::North), Direction::South) + && self.sturdy(rel(pos, Direction::South), Direction::North) + } + }; + let mut state = table.set_text( + table.set_dir(default, p.facing, face.opposite()), + p.attachment, + if double { "double_wall" } else { "single_wall" }, + ); + if self.can_survive(state, pos) { + 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 + } + } + } + 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 source = self.fluid_at(pos) == FluidState::WATER; + 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 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); + Some(table.set_dir(state, p.facing, horizontal)) + } + Class::Candle => { + let current = self.state(pos); + if b.is_block(current, block) { + Some(table.cycle(current, p.candles)) + } else { + let state = sup!()?; + Some(wl(state)) + } + } + 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), + )) + } else { + let state = sup!()?; + Some(wl(state)) + } + } + Class::TurtleEgg => { + let current = self.state(pos); + if b.is_block(current, block) { + Some(table.set_int(current, p.eggs, (table.int(current, p.eggs) + 1).min(4))) + } else { + sup!() + } + } + 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), + )) + } else { + sup!() + } + } + Class::FlowerBed | Class::LeafLitter => { + let current = self.state(pos); + 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 { + Some(table.set_dir(default, p.facing, horizontal.opposite())) + } + } + Class::Chest => { + let mut kind = "single"; + 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 axis_of(neighbour_facing) != axis_of(face) { + facing = neighbour_facing; + 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) + { + kind = "left"; + } 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, + ))) + } + Class::ChorusPlant => Some(self.chorus_plant_with_connections(pos, default)), + Class::ConcretePowder => { + let replaced = self.state(pos); + if b.is_water_fluid(b.fluid(replaced).kind()) || self.concrete_touches_liquid(pos) { + Some(b.data(default).link.map_or(default, |c| b.default_of(c))) + } else { + sup!() + } + } + Class::CopperGolemStatue | Class::EnderChest | Class::Shelf => { + let mut state = wl(table.set_dir(default, p.facing, horizontal.opposite())); + if class == Class::Shelf { + let signal = self.has_neighbor_signal(pos); + state = table.set_bool(state, p.powered, signal); + } + Some(state) + } + Class::Coral => { + if !self.coral_scan_for_water(pos) { + let delay = 60 + self.random().next_int_bound(40).unwrap_or(0); + self.schedule_tick(pos, block, delay); + } + Some(default) + } + Class::Crafter => { + let front = ctx.nearest_looking_direction().opposite(); + let top = match front { + Direction::Down => horizontal.opposite(), + Direction::Up => horizontal, + _ => Direction::Up, + }; + 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, + )) + } + 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) + ); + Some(table.set_text(default, p.orientation, &orientation)) + } + Class::CreakingHeart | Class::RotatedPillar | Class::InfestedRotatedPillar => { + Some(table.set_text(default, p.axis, super::states::axis_name(axis_of(ctx.face)))) + } + Class::DecoratedPot => { + let state = table.set_dir(default, p.facing, horizontal); + 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)); + 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); + 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) + { + sup!() + } else { + None + } + } + Class::PitcherCrop => Some(default), + Class::SmallDripleaf => { + 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), + ) + } + 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 + } + } + Class::DriedGhast => { + let state = sup!()?; + Some(table.set_dir(wl(state), p.facing, horizontal.opposite())) + } + Class::EndRod => { + let behind = self.state(rel(pos, ctx.face.opposite())); + if b.is_block(behind, block) && b.facing(behind) == ctx.face { + Some(table.set_dir(default, p.facing, ctx.face.opposite())) + } else { + Some(table.set_dir(default, p.facing, ctx.face)) + } + } + Class::LightningRod => Some(wl(table.set_dir(default, p.facing, ctx.face))), + Class::ShulkerBox => Some(table.set_dir(default, p.facing, ctx.face)), + 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" + }; + 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(), + ) + }; + if self.can_survive(state, pos) { + return Some(Some(state)); + } + } + None + } + Class::Farmland => { + if !self.can_survive(default, pos) { + Some(b.default_of(b.data(default).link.unwrap_or(n.dirt))) + } else { + sup!() + } + } + Class::Path => { + if !self.can_survive(default, pos) { + Some(b.default_of(n.dirt)) + } else { + sup!() + } + } + Class::Fence => { + let mut state = sup!()?; + 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()); + 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, + ] { + 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), + ); + } + Some(wl(state)) + } + Class::Wall => { + 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(), + ) + }); + let top_pos = above(pos); + let top = self.state(top_pos); + Some(self.wall_shape(wl(default), top_pos, top, sides)) + } + Class::FenceGate => { + let open = self.has_neighbor_signal(pos); + let wall = |sim: &Self, d: Direction| b.in_set(sim.rel_state(pos, d), &t.walls); + let in_wall = match axis_of(horizontal) { + Axis::Z => wall(self, Direction::West) || wall(self, Direction::East), + _ => wall(self, Direction::North) || wall(self, Direction::South), + }; + let state = table.set_dir(default, p.facing, horizontal); + let state = table.set_bool(table.set_bool(state, p.open, open), p.powered, open); + Some(table.set_bool(state, p.in_wall, in_wall)) + } + Class::GrowingPlant => { + let growth = b.block_data(block).growth_direction; + let (head, body) = self.growing_plant_pair(block); + let next = self.rel_state(pos, growth); + if !b.is_block(next, head) && !b.is_block(next, body) { + if b.block_data(block).is(Class::GrowingPlantHead) { + let age = self.random().next_int_bound(25).unwrap_or(0); + Some(table.set_int(default, p.age, age)) + } else { + Some(default) + } + } else { + Some(b.default_of(body)) + } + } + Class::Kelp => { + let fluid = self.fluid_at(pos); + 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 + } + } + Class::HangingRoots => { + let state = sup!()?; + Some(wl(state)) + } + Class::Hopper => { + let direction = ctx.face.opposite(); + 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 => { + let mut state = default; + for direction in Direction::ALL { + let same = b.is_block(self.rel_state(pos, direction), block); + state = table.set_bool(state, self.direction_prop(direction), !same); + } + Some(state) + } + Class::Lantern => { + for direction in ctx.nearest_looking_directions() { + if axis_of(direction) == Axis::Y { + let state = table.set_bool(default, p.hanging, direction == Direction::Up); + if self.can_survive(state, pos) { + return Some(Some(wl(state))); + } + } + } + None + } + Class::Leaves => { + 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); + if distance == 1 { + break; + } + } + Some(table.set_int(state, p.distance, distance)) + } + Class::MangrovePropagule => { + let state = sup!()?; + Some(table.set_int(wl(state), p.age, 4)) + } + Class::MossyCarpet => Some(self.mossy_carpet_updated_state(default, pos, true)), + Class::Multiface => { + let old = self.state(pos); + for direction in ctx.nearest_looking_directions() { + if let Some(state) = self.multiface_placement(block, old, pos, direction) { + return Some(Some(state)); + } + } + None + } + Class::Note => Some(self.note_block_instrument(pos, default)), + Class::RedstoneLamp => { + let signal = self.has_neighbor_signal(pos); + Some(table.set_bool(default, p.lit, signal)) + } + Class::RedstoneWire => { + let cross = self.wire_cross_state(0); + Some(self.wire_connection_state(cross, pos)) + } + Class::Scaffolding => { + let distance = self.scaffolding_distance(pos); + let bottom = self.scaffolding_is_bottom(pos, distance); + let water = self.fluid_at(pos).kind() == crate::fluid::FluidKind::Water; + let state = table.set_bool(default, p.waterlogged, water); + Some(table.set_bool(table.set_int(state, p.distance, distance), p.bottom, bottom)) + } + 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, + ))); + } + 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")) + } + } + 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 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" }, + ) + } 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, + ) + }; + if self.has_neighbor_signal(pos) { + state = table.set_bool(table.set_bool(state, p.open, true), p.powered, true); + } + Some(wl(state)) + } + Class::Snowy => { + let snowy = b.in_set(self.above_state(pos), &t.snow); + Some(table.set_bool(default, p.snowy, snowy)) + } + Class::Speleothem => { + let default_tip = ctx.nearest_looking_vertical().opposite(); + let tip = if self.is_valid_speleothem_placement(block, pos, default_tip) { + default_tip + } else if self.is_valid_speleothem_placement(block, pos, default_tip.opposite()) { + default_tip.opposite() + } else { + return Some(None); + }; + let thickness = self.speleothem_thickness_for(block, pos, tip, !ctx.sneaking); + let state = table.set_dir(default, p.vertical_direction, tip); + Some(wl(table.set_text(state, p.thickness, thickness))) + } + Class::TripWire => { + let mut state = default; + for direction in HORIZONTAL { + 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) + } + Class::Vine => { + let clicked = self.state(pos); + let clicked_vine = b.is_block(clicked, block); + let result = if clicked_vine { clicked } else { default }; + for direction in ctx.nearest_looking_directions() { + if direction != Direction::Down { + let key = self.direction_prop(direction); + let occupied = clicked_vine && table.bool(clicked, key); + if !occupied && self.vine_can_support_at(result, pos, direction) { + return Some(Some(table.set_bool(result, key, true))); + } + } + } + if clicked_vine { Some(result) } else { None } + } + Class::PotentSulfur => Some(self.potent_sulfur_state(default, pos)), + Class::Nylium => sup!(), + _ => return None, + }) + } + + 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" + { + Some(self.b.facing(state)) + } else { + None + } + } + /// `ChorusPlantBlock.getStateWithConnections`. + 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; + let mut result = state; + for direction in Direction::ALL { + let neighbour = self.rel_state(pos, direction); + let mut connect = b.is_block(neighbour, block) || b.is_block(neighbour, flower); + 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 + } + fn wall_hanging_sign_can_place(&self, state: BlockStateId, pos: BlockPos) -> bool { + let b = self.b; + 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)) + { + 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)) + } + 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; + } + if !b.multiface_can_attach(self.rel_state(pos, direction), direction) { + return None; + } + 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) + } else { + b.default_of(block) + }; + 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; + if direction == Direction::Down { + return false; + } + if b.multiface_can_attach(self.rel_state(pos, direction), direction) { + return true; + } + if direction == Direction::Up { + 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)) + } + 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) + }; + 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" + } + } 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" + } + } else { + "frustum" + } + } + } + /// `DoorBlock.getHinge`. + fn door_hinge(&self, ctx: &Ctx) -> &'static str { + let b = self.b; + let pos = ctx.pos; + let place = ctx.horizontal_direction(); + let above_pos = above(pos); + let left = counter_clockwise(place); + let right = clockwise(place); + let left_state = self.rel_state(pos, left); + let left_above = self.rel_state(above_pos, left); + 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 door_left = lower_door(left_state); + let door_right = lower_door(right_state); + if (door_left && !door_right) || balance > 0 { + return "right"; + } + if (door_right && !door_left) || balance < 0 { + return "left"; + } + let step_x = place.normal()[0]; + 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) + { + "left" + } else { + "right" + } + } + + /// `Block.setPlacedBy` for the blocks that place companions. + fn set_placed_by(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let p = b.props; + let data = b.data(state); + let block = b.block(state); + if data.is(Class::AbstractBed) { + let other = rel(pos, b.facing(state)); + self.set_block_and_update(other, b.table.set_text(state, p.part, "head")); + } else if data.is(Class::Crafter) { + if b.table.bool(state, p.triggered) { + self.schedule_tick(pos, block, 4); + } + } else if data.is(Class::Diode) { + if self.diode_should_turn_on(pos, state) { + self.schedule_tick(pos, block, 1); + } + } else if data.is(Class::Door) { + self.set_block_and_update(above(pos), b.table.set_text(state, p.half, "upper")); + } 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 water = self.is_water_at(above_pos); + 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); + self.set_block_and_update(above_pos, upper); + } else if data.is(Class::PistonBase) { + self.piston_check_if_extend(pos, state); + } else if data.is(Class::TripWireHook) { + self.tripwire_hook_calculate(pos, state, false, false, -1, None); + } else if data.is(Class::MossyCarpet) { + let topper = self.mossy_carpet_topper(pos); + if !b.is_air(topper) { + self.set_block_and_update(above(pos), topper); + } + } + } + /// `MossyCarpetBlock.createTopperWithSideChance(level, pos, random::nextBoolean)`. + fn mossy_carpet_topper(&mut self, pos: BlockPos) -> BlockStateId { + let b = self.b; + let p = b.props; + let block = b.block(self.state(pos)); + 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)) + { + 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; + for direction in HORIZONTAL { + let key = self.direction_prop(direction); + if b.table.text(result, key) != "none" && !self.random().next_boolean() { + result = b.table.set_text(result, key, "none"); + } + } + if self.mossy_carpet_has_faces(result) && result != above_state { + return result; + } + } + b.air() + } + + /// `BlockItem.place` (and its subclasses' overrides). + /// `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 binding = b.item_binding(&input.item).cloned()?; + let mut ctx = Ctx { + pos: input.clicked_pos, + hit_pos: input.clicked_pos, + face: input.face, + hit: input.hit, + inside: input.inside, + yaw: input.yaw, + pitch: input.pitch, + sneaking: input.sneaking, + item: input.item.clone(), + replace_clicked: true, + }; + ctx.replace_clicked = self.can_be_replaced(self.state(input.clicked_pos), &ctx); + if !ctx.replace_clicked { + ctx.pos = rel(input.clicked_pos, input.face); + } + if !ctx.replace_clicked && !self.can_be_replaced(self.state(ctx.pos), &ctx) { + return None; + } + if binding.kind == ItemKind::Scaffolding { + ctx = self.scaffolding_update_context(&ctx, binding.block)?; + } + 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 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 + }; + if let Some(candidate) = candidate { + let hanging_ok = binding.kind != ItemKind::HangingSign + || !b.instance_of(candidate, Class::WallHangingSign) + || self.wall_hanging_sign_can_place(candidate, ctx.pos); + if hanging_ok && self.can_survive(candidate, ctx.pos) { + chosen = Some(candidate); + break; + } + } + } + chosen.filter(|state| self.level.is_unobstructed(ctx.pos, *state)) + } + _ => { + 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) + }) + } + }; + 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() + }; + self.set_block(above_pos, replacement, 27); + } + if !self.set_block(ctx.pos, state, 11) { + return PlaceOutcome::Failed; + } + let placed = self.state(ctx.pos); + if b.block(placed) == b.block(state) { + self.set_placed_by(ctx.pos, placed); + } + let placed = self.state(ctx.pos); + let sounds = b.data(placed).sounds.clone(); + self.emit(LevelEvent::Sound { + pos: ctx.pos, + sound: sounds.place.clone(), + volume: (sounds.volume + 1.0) / 2.0, + pitch: sounds.pitch * 0.8, + }); + self.game_event(ctx.pos, "minecraft:block_place"); + 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()) + }; + } + let direction = if ctx.sneaking { + if ctx.inside { + ctx.face.opposite() + } else { + ctx.face + } + } else if ctx.face == Direction::Up { + ctx.horizontal_direction() + } else { + Direction::Up + }; + let mut horizontal_distance = 0; + let mut placement = rel(pos, direction); + while horizontal_distance < 7 { + if !self.is_in_valid_bounds(placement) { + break; + } + let replaced = self.state(placement); + if !b.is_block(replaced, block) { + if self.can_be_replaced(replaced, ctx) { + let [dx, dy, dz] = direction.normal(); + return Some(Ctx { + pos: placement, + hit_pos: placement, + face: direction, + hit: Vec3::new( + f64::from(placement.x) + 0.5 + f64::from(dx) * 0.5, + f64::from(placement.y) + 0.5 + f64::from(dy) * 0.5, + f64::from(placement.z) + 0.5 + f64::from(dz) * 0.5, + ), + inside: false, + replace_clicked: true, + ..ctx.clone() + }); + } + break; + } + placement = rel(placement, direction); + if is_horizontal(direction) { + horizontal_distance += 1; + } + } + None + } +} + +impl Behaviours { + /// `BlockItem.place` for the item in `ctx`: resolves the replaced + /// 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 { + 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. + pub fn state_for_placement( + &self, + level: &mut L, + ticks: &mut Ticks, + block: BlockId, + input: &PlaceContext, + ) -> Option { + let mut sim = self.sim(level, ticks); + let mut ctx = Ctx { + pos: input.clicked_pos, + hit_pos: input.clicked_pos, + face: input.face, + hit: input.hit, + inside: input.inside, + yaw: input.yaw, + pitch: input.pitch, + sneaking: input.sneaking, + item: input.item.clone(), + replace_clicked: true, + }; + ctx.replace_clicked = sim.can_be_replaced(sim.state(input.clicked_pos), &ctx); + if !ctx.replace_clicked { + ctx.pos = rel(input.clicked_pos, input.face); + } + sim.state_for_placement(block, &ctx) + } +} diff --git a/crates/horizon-world/src/level/query.rs b/crates/horizon-world/src/level/query.rs new file mode 100644 index 000000000..f10bd158a --- /dev/null +++ b/crates/horizon-world/src/level/query.rs @@ -0,0 +1,235 @@ +//! Block-state queries shared by the ported behaviour (`BlockStateBase` +//! accessors and `Block` static helpers). +use super::{ + Behaviours, LevelAccess, Sim, + classes::{Class, Interface}, + data::{BlockSet, state_flags}, + states::{BlockId, PropKey}, + update::{above, below, rel}, +}; +use crate::{fluid::FluidKind, registry::BlockStateId}; +use horizon_core::{geometry::Direction, position::BlockPos}; + +pub(crate) const fn clockwise(direction: Direction) -> Direction { + match direction { + Direction::North => Direction::East, + Direction::East => Direction::South, + Direction::South => Direction::West, + Direction::West => Direction::North, + other => other, + } +} +pub(crate) const fn counter_clockwise(direction: Direction) -> Direction { + match direction { + Direction::North => Direction::West, + Direction::West => Direction::South, + Direction::South => Direction::East, + Direction::East => Direction::North, + other => other, + } +} +pub(crate) const fn is_horizontal(direction: Direction) -> bool { + !matches!(direction, Direction::Up | Direction::Down) +} +pub(crate) fn axis_of(direction: Direction) -> horizon_core::geometry::Axis { + use horizon_core::geometry::Axis; + match direction { + Direction::West | Direction::East => Axis::X, + Direction::Up | Direction::Down => Axis::Y, + Direction::North | Direction::South => Axis::Z, + } +} +/// `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] +} +pub(crate) fn data_2d(direction: Direction) -> i32 { + match direction { + Direction::South => 0, + Direction::West => 1, + Direction::North => 2, + Direction::East => 3, + _ => -1, + } +} + +impl Behaviours { + pub(crate) fn in_set(&self, state: BlockStateId, set: &BlockSet) -> bool { + set.contains(self.table.block(state)) + } + pub(crate) fn is_block(&self, state: BlockStateId, block: BlockId) -> bool { + self.table.is(state, block) + } + pub(crate) fn instance_of(&self, state: BlockStateId, class: Class) -> bool { + self.data(state).is(class) + } + pub(crate) fn implements(&self, state: BlockStateId, interface: Interface) -> bool { + self.data(state).implements(interface) + } + pub(crate) fn fluid_in(&self, kind: FluidKind, mask: u8) -> bool { + mask & (1 << kind as u8) != 0 + } + pub(crate) fn is_water_fluid(&self, kind: FluidKind) -> bool { + self.fluid_in(kind, self.fluid_tags.water) + } + pub(crate) fn is_lava_fluid(&self, kind: FluidKind) -> bool { + self.fluid_in(kind, self.fluid_tags.lava) + } + pub(crate) fn liquid(&self, state: BlockStateId) -> bool { + self.has_flag(state, state_flags::LIQUID) + } + pub(crate) fn solid_render(&self, state: BlockStateId) -> bool { + self.has_flag(state, state_flags::SOLID_RENDER) + } + pub(crate) fn full_collision(&self, state: BlockStateId) -> bool { + self.has_flag(state, state_flags::FULL_COLLISION) + } + /// `Block.isFaceFull(state.getCollisionShape(level, pos), direction)`. + pub(crate) fn collision_face_full(&self, state: BlockStateId, direction: Direction) -> bool { + 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 { + let face = direction.opposite(); + self.is_face_sturdy(neighbour, face) || self.collision_face_full(neighbour, face) + } + /// `Block.isExceptionForConnection`. + pub(crate) fn is_exception_for_connection(&self, state: BlockStateId) -> bool { + let n = &self.named; + let block = self.table.block(state); + self.instance_of(state, Class::Leaves) + || block == n.barrier + || block == n.carved_pumpkin + || block == n.jack_o_lantern + || block == n.melon + || block == n.pumpkin + || self.tags.shulker_boxes.contains(block) + } + pub(crate) fn is_waterlogged(&self, state: BlockStateId) -> bool { + 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) + } + /// The boolean/enum property named after `direction` (`north`, `up`, ...). + pub(crate) fn dir_prop(&self, direction: Direction) -> PropKey { + let p = &self.props; + match direction { + Direction::Down => p.down, + Direction::Up => p.up, + Direction::North => p.north, + Direction::South => p.south, + Direction::West => p.west, + Direction::East => p.east, + } + } + pub(crate) fn default_of(&self, block: BlockId) -> BlockStateId { + self.table.default_state(block) + } + pub(crate) fn air(&self) -> BlockStateId { + self.table.default_state(self.named.air) + } +} + +/// Block-entity lookups for dynamic shapes: Horizon's level keeps no shulker +/// box animation state, so boxes read as closed (a full cube). +struct NoBlockEntities; +impl crate::dynamic_support::DynamicSupportWorld for NoBlockEntities { + type Error = std::convert::Infallible; + 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> { + Ok(None) + } +} +impl crate::block_collision::DynamicCollisionWorld for NoBlockEntities { + fn shulker_collision_state( + &mut self, + _position: [i32; 3], + ) -> Result, Self::Error> { + Ok(None) + } +} + +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 { + if self.b.facts(state).shape >= 0 { + return self.b.shape_info(state); + } + match self.b.dynamic.get(&state) { + Some(support) => support + .collision_shape(&mut NoBlockEntities, [pos.x, pos.y, pos.z]) + .ok() + .and_then(|shape| super::data::analyse_shape(&shape).ok()) + .unwrap_or_default(), + None => super::data::ShapeInfo::default(), + } + } + pub fn sturdy(&self, pos: BlockPos, direction: Direction) -> bool { + self.b.is_face_sturdy(self.state(pos), direction) + } + /// `Block.canSupportRigidBlock(level, below)`. + pub fn can_support_rigid_block(&self, pos: BlockPos) -> bool { + self.b.is_face_sturdy_rigid(self.state(pos), Direction::Up) + } + /// `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) + { + return false; + } + self.b.is_face_sturdy_center(state, direction) + } + pub fn is_empty_block(&self, pos: BlockPos) -> bool { + self.b.is_air(self.state(pos)) + } + /// `LevelReader.isWaterAt`: the fluid at `pos` is in the water tag. + pub fn is_water_at(&self, pos: BlockPos) -> bool { + self.b.is_water_fluid(self.fluid_at(pos).kind()) + } + /// `Level.getRawBrightness(pos, darken)`. + pub fn raw_brightness(&self, pos: BlockPos, darken: i32) -> i32 { + super::raw_brightness(self.level, pos, darken) + } + /// `LevelReader.getMaxLocalRawBrightness(pos)`. + pub fn max_local_raw_brightness(&self, pos: BlockPos) -> i32 { + self.raw_brightness(pos, self.level.sky_darken()) + } + pub fn is_redstone_conductor(&self, state: BlockStateId, _pos: BlockPos) -> bool { + self.b.has_flag(state, state_flags::CONDUCTOR) + } + pub(crate) fn above_state(&self, pos: BlockPos) -> BlockStateId { + self.state(above(pos)) + } + pub(crate) fn below_state(&self, pos: BlockPos) -> BlockStateId { + self.state(below(pos)) + } + pub(crate) fn rel_state(&self, pos: BlockPos, direction: Direction) -> BlockStateId { + self.state(rel(pos, direction)) + } + pub(crate) fn is_inside_build_height(&self, y: i32) -> bool { + y >= self.level.min_y() && y < self.level.max_y() + } +} diff --git a/crates/horizon-world/src/level/rails.rs b/crates/horizon-world/src/level/rails.rs new file mode 100644 index 000000000..b5a784796 --- /dev/null +++ b/crates/horizon-world/src/level/rails.rs @@ -0,0 +1,721 @@ +//! Rails (`BaseRailBlock`, `RailState`, powered/activator rails) and +//! tripwires (`TripWireBlock`, `TripWireHookBlock`). +use super::{ + LevelAccess, LevelEvent, Sim, + classes::Class, + states::BlockId, + update::{above, below, rel}, +}; +use crate::registry::BlockStateId; +use horizon_core::{ + geometry::{Aabb, Direction, Vec3}, + position::BlockPos, + random::RandomSource, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RailShape { + NorthSouth, + EastWest, + AscendingEast, + AscendingWest, + AscendingNorth, + AscendingSouth, + SouthEast, + SouthWest, + NorthWest, + NorthEast, +} +impl RailShape { + fn parse(text: &str) -> Self { + match text { + "east_west" => Self::EastWest, + "ascending_east" => Self::AscendingEast, + "ascending_west" => Self::AscendingWest, + "ascending_north" => Self::AscendingNorth, + "ascending_south" => Self::AscendingSouth, + "south_east" => Self::SouthEast, + "south_west" => Self::SouthWest, + "north_west" => Self::NorthWest, + "north_east" => Self::NorthEast, + _ => Self::NorthSouth, + } + } + fn name(self) -> &'static str { + match self { + Self::NorthSouth => "north_south", + Self::EastWest => "east_west", + Self::AscendingEast => "ascending_east", + Self::AscendingWest => "ascending_west", + Self::AscendingNorth => "ascending_north", + Self::AscendingSouth => "ascending_south", + Self::SouthEast => "south_east", + Self::SouthWest => "south_west", + Self::NorthWest => "north_west", + Self::NorthEast => "north_east", + } + } + fn is_slope(self) -> bool { + matches!( + self, + Self::AscendingEast | Self::AscendingWest | Self::AscendingNorth | Self::AscendingSouth + ) + } +} + +/// `RailState`. +struct Rail { + pos: BlockPos, + state: BlockStateId, + straight: bool, + connections: Vec, +} + +impl Sim<'_, L> { + pub(crate) fn rail_shape(&self, state: BlockStateId) -> &str { + self.b.table.text(state, self.b.props.shape) + } + fn is_rail(&self, state: BlockStateId) -> bool { + self.b.in_set(state, &self.b.tags.rails) && self.b.instance_of(state, Class::BaseRail) + } + fn is_rail_at(&self, pos: BlockPos) -> bool { + self.is_rail(self.state(pos)) + } + fn rail_connections(pos: BlockPos, shape: RailShape) -> Vec { + let (n, s, w, e) = ( + rel(pos, Direction::North), + rel(pos, Direction::South), + rel(pos, Direction::West), + rel(pos, Direction::East), + ); + match shape { + RailShape::NorthSouth => vec![n, s], + RailShape::EastWest => vec![w, e], + RailShape::AscendingEast => vec![w, above(e)], + RailShape::AscendingWest => vec![above(w), e], + RailShape::AscendingNorth => vec![above(n), s], + RailShape::AscendingSouth => vec![n, above(s)], + RailShape::SouthEast => vec![e, s], + RailShape::SouthWest => vec![w, s], + RailShape::NorthWest => vec![w, n], + RailShape::NorthEast => vec![e, n], + } + } + fn rail_new(&self, pos: BlockPos, state: BlockStateId) -> Rail { + let shape = RailShape::parse(self.rail_shape(state)); + Rail { + pos, + state, + straight: !self.b.data(state).is(Class::Rail), + connections: Self::rail_connections(pos, shape), + } + } + fn rail_get(&self, pos: BlockPos) -> Option { + for test in [pos, above(pos), below(pos)] { + let state = self.state(test); + if self.is_rail(state) { + return Some(self.rail_new(test, state)); + } + } + None + } + fn rail_has_connection(rail: &Rail, pos: BlockPos) -> bool { + rail.connections + .iter() + .any(|c| c.x == pos.x && c.z == pos.z) + } + fn rail_remove_soft_connections(&self, rail: &mut Rail) { + let mut i = 0; + while i < rail.connections.len() { + match self.rail_get(rail.connections[i]) { + Some(other) if Self::rail_has_connection(&other, rail.pos) => { + rail.connections[i] = other.pos; + i += 1; + } + _ => { + rail.connections.remove(i); + } + } + } + } + fn rail_can_connect_to(rail: &Rail, other: &Rail) -> bool { + Self::rail_has_connection(rail, other.pos) || rail.connections.len() != 2 + } + fn rail_has_neighbor_rail(&self, rail: &Rail, pos: BlockPos) -> bool { + match self.rail_get(pos) { + Some(mut neighbour) => { + self.rail_remove_soft_connections(&mut neighbour); + Self::rail_can_connect_to(&neighbour, rail) + } + None => false, + } + } + fn rail_count_potential_connections(&self, pos: BlockPos) -> i32 { + super::update::HORIZONTAL + .into_iter() + .filter(|d| { + let p = rel(pos, *d); + self.is_rail_at(p) || self.is_rail_at(above(p)) || self.is_rail_at(below(p)) + }) + .count() as i32 + } + fn rail_slopes(&self, pos: BlockPos, shape: Option) -> Option { + let (n, s, w, e) = ( + rel(pos, Direction::North), + rel(pos, Direction::South), + rel(pos, Direction::West), + rel(pos, Direction::East), + ); + let mut shape = shape; + if shape == Some(RailShape::NorthSouth) { + if self.is_rail_at(above(n)) { + shape = Some(RailShape::AscendingNorth); + } + if self.is_rail_at(above(s)) { + shape = Some(RailShape::AscendingSouth); + } + } + if shape == Some(RailShape::EastWest) { + if self.is_rail_at(above(e)) { + shape = Some(RailShape::AscendingEast); + } + if self.is_rail_at(above(w)) { + shape = Some(RailShape::AscendingWest); + } + } + shape + } + fn rail_set_shape(&self, state: BlockStateId, shape: RailShape) -> BlockStateId { + self.b + .table + .set_text(state, self.b.props.shape, shape.name()) + } + fn rail_connect_to(&mut self, rail: &mut Rail, other_pos: BlockPos) { + rail.connections.push(other_pos); + let pos = rail.pos; + let n = Self::rail_has_connection(rail, rel(pos, Direction::North)); + let s = Self::rail_has_connection(rail, rel(pos, Direction::South)); + let w = Self::rail_has_connection(rail, rel(pos, Direction::West)); + let e = Self::rail_has_connection(rail, rel(pos, Direction::East)); + let mut shape = None; + if n || s { + shape = Some(RailShape::NorthSouth); + } + if w || e { + shape = Some(RailShape::EastWest); + } + if !rail.straight { + if s && e && !n && !w { + shape = Some(RailShape::SouthEast); + } + if s && w && !n && !e { + shape = Some(RailShape::SouthWest); + } + if n && w && !s && !e { + shape = Some(RailShape::NorthWest); + } + if n && e && !s && !w { + shape = Some(RailShape::NorthEast); + } + } + let shape = self + .rail_slopes(pos, shape) + .unwrap_or(RailShape::NorthSouth); + rail.state = self.rail_set_shape(rail.state, shape); + self.set_block_and_update(pos, rail.state); + } + /// `RailState.place`; returns the resulting state. + fn rail_place( + &mut self, + pos: BlockPos, + state: BlockStateId, + has_signal: bool, + first: bool, + default: RailShape, + ) -> BlockStateId { + let mut rail = self.rail_new(pos, state); + let n = self.rail_has_neighbor_rail(&rail, rel(pos, Direction::North)); + let s = self.rail_has_neighbor_rail(&rail, rel(pos, Direction::South)); + let w = self.rail_has_neighbor_rail(&rail, rel(pos, Direction::West)); + let e = self.rail_has_neighbor_rail(&rail, rel(pos, Direction::East)); + let mut shape = None; + let ns = n || s; + let we = w || e; + if ns && !we { + shape = Some(RailShape::NorthSouth); + } + if we && !ns { + shape = Some(RailShape::EastWest); + } + let (se, sw, ne, nw) = (s && e, s && w, n && e, n && w); + if !rail.straight { + if se && !n && !w { + shape = Some(RailShape::SouthEast); + } + if sw && !n && !e { + shape = Some(RailShape::SouthWest); + } + if nw && !s && !e { + shape = Some(RailShape::NorthWest); + } + if ne && !s && !w { + shape = Some(RailShape::NorthEast); + } + } + if shape.is_none() { + if ns && we { + shape = Some(default); + } else if ns { + shape = Some(RailShape::NorthSouth); + } else if we { + shape = Some(RailShape::EastWest); + } + if !rail.straight { + if has_signal { + for (cond, s) in [ + (se, RailShape::SouthEast), + (sw, RailShape::SouthWest), + (ne, RailShape::NorthEast), + (nw, RailShape::NorthWest), + ] { + if cond { + shape = Some(s); + } + } + } else { + for (cond, s) in [ + (nw, RailShape::NorthWest), + (ne, RailShape::NorthEast), + (sw, RailShape::SouthWest), + (se, RailShape::SouthEast), + ] { + if cond { + shape = Some(s); + } + } + } + } + } + let shape = self.rail_slopes(pos, shape).unwrap_or(default); + rail.connections = Self::rail_connections(pos, shape); + rail.state = self.rail_set_shape(rail.state, shape); + if first || self.state(pos) != rail.state { + self.set_block_and_update(pos, rail.state); + for i in 0..rail.connections.len() { + if let Some(mut neighbour) = self.rail_get(rail.connections[i]) { + self.rail_remove_soft_connections(&mut neighbour); + if Self::rail_can_connect_to(&neighbour, &rail) { + self.rail_connect_to(&mut neighbour, rail.pos); + } + } + } + } + rail.state + } + fn rail_update_dir(&mut self, pos: BlockPos, state: BlockStateId, first: bool) -> BlockStateId { + let current = RailShape::parse(self.rail_shape(state)); + let signal = self.has_neighbor_signal(pos); + self.rail_place(pos, state, signal, first, current) + } + /// `BaseRailBlock.updateState(state, level, pos, movedByPiston)`. + pub(crate) fn rail_update_state( + &mut self, + pos: BlockPos, + state: BlockStateId, + moved: bool, + ) -> BlockStateId { + let state = self.rail_update_dir(pos, state, true); + if !self.b.data(state).is(Class::Rail) { + let block = self.b.block(state); + self.neighbor_changed_full(state, pos, block, moved); + } + state + } + pub(crate) fn rail_neighbor_changed( + &mut self, + pos: BlockPos, + state: BlockStateId, + changed: BlockId, + moved: bool, + ) { + let b = self.b; + if !b.is_block(self.state(pos), b.block(state)) { + return; + } + let shape = RailShape::parse(self.rail_shape(state)); + let support = |sim: &Self, p: BlockPos| sim.can_support_rigid_block(p); + let remove = !support(self, below(pos)) + || match shape { + RailShape::AscendingEast => !support(self, rel(pos, Direction::East)), + RailShape::AscendingWest => !support(self, rel(pos, Direction::West)), + RailShape::AscendingNorth => !support(self, rel(pos, Direction::North)), + RailShape::AscendingSouth => !support(self, rel(pos, Direction::South)), + _ => false, + }; + if remove { + self.drop_resources(state, pos); + self.remove_block(pos, moved); + return; + } + let data = b.data(state); + if data.is(Class::PoweredRail) { + self.powered_rail_update(pos, state); + } else if data.is(Class::Rail) { + let changed_default = b.default_of(changed); + if self.is_signal_source_default(changed_default) + && self.rail_count_potential_connections(pos) == 3 + { + self.rail_update_dir(pos, state, false); + } + } + } + fn is_signal_source_default(&self, state: BlockStateId) -> bool { + self.b + .has_flag(state, super::data::state_flags::SIGNAL_SOURCE) + } + fn powered_rail_update(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let powered = b.table.bool(state, b.props.powered); + let should = self.has_neighbor_signal(pos) + || self.powered_rail_find(pos, state, true, 0) + || self.powered_rail_find(pos, state, false, 0); + if should != powered { + self.set_block_and_update(pos, b.table.set_bool(state, b.props.powered, should)); + let block = b.block(state); + self.update_neighbors_at(below(pos), block); + if RailShape::parse(self.rail_shape(state)).is_slope() { + self.update_neighbors_at(above(pos), block); + } + } + } + fn powered_rail_find( + &self, + pos: BlockPos, + state: BlockStateId, + forward: bool, + depth: i32, + ) -> bool { + if depth >= 8 { + return false; + } + let (mut x, mut y, mut z) = (pos.x, pos.y, pos.z); + let mut check_below = true; + let mut shape = RailShape::parse(self.rail_shape(state)); + match shape { + RailShape::NorthSouth => z += if forward { 1 } else { -1 }, + RailShape::EastWest => x += if forward { -1 } else { 1 }, + RailShape::AscendingEast => { + if forward { + x -= 1; + } else { + x += 1; + y += 1; + check_below = false; + } + shape = RailShape::EastWest; + } + RailShape::AscendingWest => { + if forward { + x -= 1; + y += 1; + check_below = false; + } else { + x += 1; + } + shape = RailShape::EastWest; + } + RailShape::AscendingNorth => { + if forward { + z += 1; + } else { + z -= 1; + y += 1; + check_below = false; + } + shape = RailShape::NorthSouth; + } + RailShape::AscendingSouth => { + if forward { + z += 1; + y += 1; + check_below = false; + } else { + z -= 1; + } + shape = RailShape::NorthSouth; + } + _ => {} + } + let block = self.b.block(state); + self.powered_rail_same_with_power(BlockPos::new(x, y, z), block, forward, depth, shape) + || (check_below + && self.powered_rail_same_with_power( + BlockPos::new(x, y - 1, z), + block, + forward, + depth, + shape, + )) + } + fn powered_rail_same_with_power( + &self, + pos: BlockPos, + block: BlockId, + forward: bool, + depth: i32, + dir: RailShape, + ) -> bool { + let b = self.b; + let state = self.state(pos); + if !b.is_block(state, block) { + return false; + } + let mine = RailShape::parse(self.rail_shape(state)); + if dir == RailShape::EastWest + && matches!( + mine, + RailShape::NorthSouth | RailShape::AscendingNorth | RailShape::AscendingSouth + ) + { + return false; + } + if dir == RailShape::NorthSouth + && matches!( + mine, + RailShape::EastWest | RailShape::AscendingEast | RailShape::AscendingWest + ) + { + return false; + } + if !b.table.bool(state, b.props.powered) { + return false; + } + self.has_neighbor_signal(pos) || self.powered_rail_find(pos, state, forward, depth + 1) + } + + // ---- tripwire ---- + + /// `TripWireBlock.updateSource`. + pub(crate) fn tripwire_update_source(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + for direction in [Direction::South, Direction::West] { + for i in 1..42 { + let [dx, dy, dz] = direction.normal(); + let test = pos.offset(dx * i, dy * i, dz * i); + let block = self.state(test); + if b.is_block(block, b.named.tripwire_hook) { + if b.facing(block) == direction.opposite() { + self.tripwire_hook_calculate(test, block, false, true, i, Some(state)); + } + break; + } + if !b.is_block(block, b.named.tripwire) { + break; + } + } + } + } + pub(crate) fn tripwire_tick(&mut self, pos: BlockPos) { + let b = self.b; + let state = self.state(pos); + if b.table.bool(state, b.props.powered) { + self.tripwire_check_pressed(pos); + } + } + /// `TripWireBlock.checkPressed` with the entities currently inside. + pub(crate) fn tripwire_check_pressed(&mut self, pos: BlockPos) { + let b = self.b; + let state = self.state(pos); + let was = b.table.bool(state, b.props.powered); + let top = if b.table.bool(state, b.props.attached) { + 2.5 / 16.0 + } else { + 8.0 / 16.0 + }; + let area = Aabb::new( + Vec3::new( + f64::from(pos.x), + f64::from(pos.y) + 1.0 / 16.0, + f64::from(pos.z), + ), + Vec3::new( + f64::from(pos.x) + 1.0, + f64::from(pos.y) + top, + f64::from(pos.z) + 1.0, + ), + ); + let pressed = self + .level + .count_entities(area, super::EntityQuery::Everything) + > 0; + let block = b.block(state); + if pressed != was { + let next = b.table.set_bool(state, b.props.powered, pressed); + self.set_block_and_update(pos, next); + self.tripwire_update_source(pos, next); + } + if pressed { + self.schedule_tick(pos, block, 10); + } else if was { + self.schedule_tick(pos, block, 1); + } + } + fn tripwire_hook_notify(&mut self, block: BlockId, pos: BlockPos, direction: Direction) { + let front = direction.opposite(); + self.update_neighbors_at(pos, block); + self.update_neighbors_at(rel(pos, front), block); + } + fn tripwire_emit( + &mut self, + pos: BlockPos, + attached: bool, + powered: bool, + was_attached: bool, + was_powered: bool, + ) { + let (sound, volume, pitch, event) = if powered && !was_powered { + ( + "minecraft:block.tripwire.click_on", + 0.4, + 0.6, + "minecraft:block_activate", + ) + } else if !powered && was_powered { + ( + "minecraft:block.tripwire.click_off", + 0.4, + 0.5, + "minecraft:block_deactivate", + ) + } else if attached && !was_attached { + ( + "minecraft:block.tripwire.attach", + 0.4, + 0.7, + "minecraft:block_attach", + ) + } else if !attached && was_attached { + let pitch = 1.2 / (self.random().next_float() * 0.2 + 0.9); + ( + "minecraft:block.tripwire.detach", + 0.4, + pitch, + "minecraft:block_detach", + ) + } else { + return; + }; + self.emit(LevelEvent::Sound { + pos, + sound: sound.into(), + volume, + pitch, + }); + self.game_event(pos, event); + } + /// `TripWireHookBlock.calculateState`. + pub(crate) fn tripwire_hook_calculate( + &mut self, + pos: BlockPos, + state: BlockStateId, + destroyed: bool, + can_update: bool, + wire_source: i32, + wire_source_state: Option, + ) { + let b = self.b; + let p = b.props; + let Some(direction) = b.table.dir(state, p.facing) else { + return; + }; + let was_attached = b.table.bool(state, p.attached); + let was_powered = b.table.bool(state, p.powered); + let block = b.block(state); + let mut attached = !destroyed; + let mut powered = false; + let mut receiver = 0; + let mut wires: Vec> = vec![None; 42]; + let [dx, dy, dz] = direction.normal(); + for i in 1..42 { + let test = pos.offset(dx * i, dy * i, dz * i); + let mut wire = self.state(test); + if b.is_block(wire, b.named.tripwire_hook) { + if b.facing(wire) == direction.opposite() { + receiver = i; + } + break; + } + if !b.is_block(wire, b.named.tripwire) && i != wire_source { + wires[i as usize] = None; + attached = false; + } else { + if i == wire_source { + wire = wire_source_state.unwrap_or(wire); + } + let armed = !b.table.bool(wire, p.disarmed); + let wire_powered = b.table.bool(wire, p.powered); + powered |= armed && wire_powered; + wires[i as usize] = Some(wire); + if i == wire_source { + self.schedule_tick(pos, block, 10); + attached &= armed; + } + } + } + attached &= receiver > 1; + powered &= attached; + let new_state = b.table.set_bool( + b.table.set_bool(b.default_of(block), p.attached, attached), + p.powered, + powered, + ); + if receiver > 0 { + let test = pos.offset(dx * receiver, dy * receiver, dz * receiver); + let opposite = direction.opposite(); + self.set_block_and_update(test, b.table.set_dir(new_state, p.facing, opposite)); + self.tripwire_hook_notify(block, test, opposite); + if !b.is_block(self.state(pos), b.named.tripwire_hook) { + self.tripwire_hook_removed(pos, new_state); + return; + } + self.tripwire_emit(test, attached, powered, was_attached, was_powered); + } + self.tripwire_emit(pos, attached, powered, was_attached, was_powered); + if !destroyed { + self.set_block_and_update(pos, b.table.set_dir(new_state, p.facing, direction)); + if can_update { + self.tripwire_hook_notify(block, pos, direction); + } + } + if was_attached != attached { + for i in 1..receiver { + let test = pos.offset(dx * i, dy * i, dz * i); + if let Some(wire) = wires[i as usize] { + let current = self.state(test); + if b.is_block(current, b.named.tripwire) + || b.is_block(current, b.named.tripwire_hook) + { + let next = b + .table + .with_bool(wire, p.attached, attached) + .unwrap_or(wire); + self.set_block_and_update(test, next); + } + } + } + } + } + /// `TripWireHookBlock.onRemoved`. + pub(crate) fn tripwire_hook_removed(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let attached = b.table.bool(state, b.props.attached); + let powered = b.table.bool(state, b.props.powered); + if attached || powered { + self.tripwire_hook_calculate(pos, state, true, false, -1, None); + } + if powered { + let facing = b.facing(state); + self.tripwire_hook_notify(b.block(state), pos, facing); + } + } +} diff --git a/crates/horizon-world/src/level/redstone.rs b/crates/horizon-world/src/level/redstone.rs new file mode 100644 index 000000000..ea3440842 --- /dev/null +++ b/crates/horizon-world/src/level/redstone.rs @@ -0,0 +1,1201 @@ +//! Redstone: `SignalGetter`, redstone wire (default evaluator), torches, +//! diodes (repeaters, comparators), observers, lamps and the power-driven +//! responses of doors, trapdoors, gates and other consumers. +use super::{ + LevelAccess, LevelEvent, Sim, + classes::Class, + data::state_flags, + query::{clockwise, counter_clockwise}, + states::BlockId, + update::{HORIZONTAL, above, below, rel}, +}; +use crate::registry::BlockStateId; +use horizon_core::{ + geometry::Direction, position::BlockPos, random::RandomSource, ticks::TickPriority, +}; + +const SIGNAL_ORDER: [Direction; 6] = [ + Direction::Down, + Direction::Up, + Direction::North, + Direction::South, + Direction::West, + Direction::East, +]; + +impl Sim<'_, L> { + fn nibble(word: u32, direction: Direction) -> i32 { + ((word >> (4 * direction as u32)) & 15) as i32 + } + pub(crate) fn is_signal_source(&self, state: BlockStateId) -> bool { + if self.b.is_block(state, self.b.named.redstone_wire) { + return !self.wire_signal_off.get(); + } + 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 { + let b = self.b; + if !b.has_flag(state, state_flags::SIGNAL_SOURCE) { + return 0; + } + let data = b.data(state); + match data.class { + Class::RedstoneWire => self.wire_signal(state, pos, direction), + Class::Comparator => { + if b.facing(state) == direction && b.table.bool(state, b.props.powered) { + self.comparator_output(pos) + } else { + 0 + } + } + Class::TrappedChest => self.level.block_entity_signal(pos, state, direction), + _ => Self::nibble(b.facts(state).weak, direction), + } + } + /// `BlockState.getDirectSignal(level, pos, direction)`. + 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; + } + match b.data(state).class { + Class::RedstoneWire => { + if self.wire_signal_off.get() { + 0 + } else { + self.wire_signal(state, pos, direction) + } + } + Class::Comparator => self.state_signal(state, pos, direction), + Class::TrappedChest => { + if direction == Direction::Up { + self.level.block_entity_signal(pos, state, direction) + } else { + 0 + } + } + _ => Self::nibble(b.facts(state).strong, direction), + } + } + pub(crate) fn comparator_output(&self, pos: BlockPos) -> i32 { + 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 { + return 0; + } + let power = self.b.table.int(state, self.b.props.power); + if power == 0 { + return 0; + } + if direction != Direction::Up { + let connected = self.wire_connection_state(state, pos); + if self + .b + .table + .text(connected, self.direction_prop(direction.opposite())) + == "none" + { + return 0; + } + } + power + } + /// `SignalGetter.getDirectSignal(pos, direction)`. + pub fn direct_signal(&self, pos: BlockPos, direction: Direction) -> i32 { + self.state_direct_signal(self.state(pos), pos, direction) + } + /// `SignalGetter.getDirectSignalTo`. + pub fn direct_signal_to(&self, pos: BlockPos) -> i32 { + let mut result = 0; + for direction in SIGNAL_ORDER { + result = result.max(self.direct_signal(rel(pos, direction), direction)); + if result >= 15 { + return result; + } + } + result + } + /// `SignalGetter.getSignal(pos, direction)`. + pub fn signal(&self, pos: BlockPos, direction: Direction) -> i32 { + let state = self.state(pos); + let signal = self.state_signal(state, pos, direction); + if self.is_redstone_conductor(state, pos) { + signal.max(self.direct_signal_to(pos)) + } else { + signal + } + } + pub fn has_signal(&self, pos: BlockPos, direction: Direction) -> bool { + self.signal(pos, direction) > 0 + } + /// `SignalGetter.hasNeighborSignal`. + pub fn has_neighbor_signal(&self, pos: BlockPos) -> bool { + SIGNAL_ORDER + .into_iter() + .any(|direction| self.signal(rel(pos, direction), direction) > 0) + } + /// `SignalGetter.getBestNeighborSignal`. + pub fn best_neighbor_signal(&self, pos: BlockPos) -> i32 { + let mut best = 0; + for direction in SIGNAL_ORDER { + let signal = self.signal(rel(pos, direction), direction); + if signal >= 15 { + return 15; + } + best = best.max(signal); + } + best + } + /// `SignalGetter.getControlInputSignal`. + fn control_input_signal(&self, pos: BlockPos, direction: Direction, only_diodes: bool) -> i32 { + 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 + } + } else if b.is_block(state, b.named.redstone_block) { + 15 + } else if b.is_block(state, b.named.redstone_wire) { + b.table.int(state, b.props.power) + } else if self.is_signal_source(state) { + self.direct_signal(pos, direction) + } else { + 0 + } + } + + // ---- redstone wire ---- + + fn should_wire_connect_to(&self, state: BlockStateId, direction: Option) -> bool { + let b = self.b; + match b.data(state).class { + Class::RedstoneWire => true, + Class::Observer => direction == Some(b.facing(state)), + Class::Repeater => { + let facing = b.facing(state); + direction == Some(facing) || direction == Some(facing.opposite()) + } + _ => self.is_signal_source(state) && direction.is_some(), + } + } + 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 { + 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" + }; + } + } + 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)) + { + "none" + } else { + "side" + } + } + fn wire_can_connect_up(&self, pos: BlockPos) -> bool { + !self.is_redstone_conductor(self.above_state(pos), pos) + } + fn wire_connected(&self, state: BlockStateId, direction: Direction) -> bool { + 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)) + } + fn wire_is_dot(&self, state: BlockStateId) -> bool { + !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"); + } + b.table.set_int(state, b.props.power, power) + } + /// `RedstoneWireBlock.getConnectionState`. + pub(crate) fn wire_connection_state(&self, state: BlockStateId, pos: BlockPos) -> BlockStateId { + 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 can_up = self.wire_can_connect_up(pos); + for direction in HORIZONTAL { + if !self.wire_connected(result, direction) { + let side = self.wire_connecting_side(pos, direction, can_up); + result = table.set_text(result, self.direction_prop(direction), side); + } + } + if was_dot && self.wire_is_dot(result) { + return result; + } + let north = self.wire_connected(result, Direction::North); + let south = self.wire_connected(result, Direction::South); + let east = self.wire_connected(result, Direction::East); + let west = self.wire_connected(result, Direction::West); + let ns_empty = !north && !south; + let ew_empty = !east && !west; + if !west && ns_empty { + result = table.set_text(result, b.props.west, "side"); + } + if !east && ns_empty { + result = table.set_text(result, b.props.east, "side"); + } + if !north && ew_empty { + result = table.set_text(result, b.props.north, "side"); + } + if !south && ew_empty { + result = table.set_text(result, b.props.south, "side"); + } + result + } + pub(crate) fn redstone_wire_update_shape( + &self, + state: BlockStateId, + pos: BlockPos, + direction: Direction, + _npos: BlockPos, + neighbour: BlockStateId, + ) -> BlockStateId { + let b = self.b; + match direction { + Direction::Down => { + if self.wire_can_survive_on(neighbour) { + state + } else { + b.air() + } + } + Direction::Up => self.wire_connection_state(state, pos), + _ => { + 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) + { + b.table.set_text(state, key, side) + } else { + let power = b.table.int(state, b.props.power); + let cross = b.table.set_text(self.wire_cross_state(power), key, side); + self.wire_connection_state(cross, pos) + } + } + } + } + /// `RedstoneWireBlock.updateIndirectNeighbourShapes`. + 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) + { + 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, + ); + } + 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, + ); + } + } + } + } + fn wire_block_signal(&self, pos: BlockPos) -> i32 { + self.wire_signal_off.set(true); + let signal = self.best_neighbor_signal(pos); + self.wire_signal_off.set(false); + signal + } + fn wire_power_of(&self, state: BlockStateId) -> i32 { + if self.b.is_block(state, self.b.named.redstone_wire) { + self.b.table.int(state, self.b.props.power) + } else { + 0 + } + } + fn wire_incoming_signal(&self, pos: BlockPos) -> i32 { + let mut signal = 0; + for direction in HORIZONTAL { + let neighbour_pos = rel(pos, direction); + 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) + { + 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)))); + } + } + (signal - 1).max(0) + } + /// `DefaultRedstoneWireEvaluator.updatePowerStrength`. + pub(crate) fn wire_update_power(&mut self, pos: BlockPos, state: BlockStateId) { + let block_signal = self.wire_block_signal(pos); + let target = if block_signal == 15 { + 15 + } else { + block_signal.max(self.wire_incoming_signal(pos)) + }; + if self.b.table.int(state, self.b.props.power) != target { + if self.state(pos) == state { + let next = self.b.table.set_int(state, self.b.props.power, target); + self.set_block(pos, next, 2); + } + // 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(); + java_hash_set_order(&mut targets); + for target_pos in targets { + self.update_neighbors_at(target_pos, wire); + } + } + } + fn wire_check_corner(&mut self, pos: BlockPos) { + let wire = self.b.named.redstone_wire; + if self.b.is_block(self.state(pos), wire) { + self.update_neighbors_at(pos, wire); + for direction in Direction::ALL { + self.update_neighbors_at(rel(pos, direction), wire); + } + } + } + pub(crate) fn wire_update_neighbors_of_neighboring_wires(&mut self, pos: BlockPos) { + for direction in HORIZONTAL { + self.wire_check_corner(rel(pos, direction)); + } + for direction in HORIZONTAL { + let target = rel(pos, direction); + if self.is_redstone_conductor(self.state(target), target) { + self.wire_check_corner(above(target)); + } else { + self.wire_check_corner(below(target)); + } + } + } + + // ---- diodes ---- + + pub(crate) fn diode_delay(&self, state: BlockStateId) -> i32 { + if self.b.instance_of(state, Class::Repeater) { + self.b.table.int(state, self.b.props.delay) * 2 + } else { + 2 + } + } + pub(crate) fn diode_is_locked(&self, pos: BlockPos, state: BlockStateId) -> bool { + self.b.instance_of(state, Class::Repeater) && self.diode_alternate_signal(pos, state) > 0 + } + fn diode_alternate_signal(&self, pos: BlockPos, state: BlockStateId) -> i32 { + let facing = self.b.facing(state); + let only_diodes = self.b.instance_of(state, Class::Repeater); + let cw = clockwise(facing); + let ccw = counter_clockwise(facing); + self.control_input_signal(rel(pos, cw), cw, only_diodes) + .max(self.control_input_signal(rel(pos, ccw), ccw, only_diodes)) + } + fn diode_input_signal(&self, pos: BlockPos, state: BlockStateId) -> i32 { + let b = self.b; + let facing = b.facing(state); + let target = rel(pos, facing); + let input = self.signal(target, facing); + let mut result = if input >= 15 { + input + } else { + let target_state = self.state(target); + input.max(self.wire_power_of(target_state)) + }; + if b.instance_of(state, Class::Comparator) { + let target_state = self.state(target); + if b.has_flag(target_state, state_flags::ANALOG_OUTPUT) { + result = self.analog_output(target_state, target, facing.opposite()); + } else if result < 15 && self.is_redstone_conductor(target_state, target) { + let further = rel(target, facing); + let further_state = self.state(further); + if b.has_flag(further_state, state_flags::ANALOG_OUTPUT) { + result = self.analog_output(further_state, further, facing.opposite()); + } + } + } + result + } + pub(crate) fn diode_should_turn_on(&self, pos: BlockPos, state: BlockStateId) -> bool { + if self.b.instance_of(state, Class::Comparator) { + let input = self.diode_input_signal(pos, state); + if input == 0 { + return false; + } + let side = self.diode_alternate_signal(pos, state); + input > side + || (input == side && self.b.table.text(state, self.b.props.mode) == "compare") + } else { + self.diode_input_signal(pos, state) > 0 + } + } + fn diode_should_prioritize(&self, pos: BlockPos, state: BlockStateId) -> bool { + let direction = self.b.facing(state).opposite(); + let opposite = self.rel_state(pos, direction); + self.b.instance_of(opposite, Class::Diode) && self.b.facing(opposite) != direction + } + pub(crate) fn diode_update_neighbors_in_front(&mut self, pos: BlockPos, state: BlockStateId) { + let direction = self.b.facing(state); + let opposite_pos = rel(pos, direction.opposite()); + let block = self.b.block(state); + self.neighbor_changed_at(opposite_pos, block); + self.update_neighbors_at_except(opposite_pos, block, direction); + } + fn comparator_calculate_output(&self, pos: BlockPos, state: BlockStateId) -> i32 { + let input = self.diode_input_signal(pos, state); + if input == 0 { + return 0; + } + let alternate = self.diode_alternate_signal(pos, state); + if alternate > input { + 0 + } else if self.b.table.text(state, self.b.props.mode) == "subtract" { + input - alternate + } else { + input + } + } + /// `DiodeBlock.checkTickOnNeighbor` (and the comparator override). + pub(crate) fn diode_check_tick_on_neighbor(&mut self, pos: BlockPos, state: BlockStateId) { + let block = self.b.block(state); + if self.b.instance_of(state, Class::Comparator) { + 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 + }; + self.schedule_tick_priority(pos, block, 2, priority); + } + } + return; + } + if self.diode_is_locked(pos, state) { + return; + } + let on = self.b.table.bool(state, self.b.props.powered); + let should = self.diode_should_turn_on(pos, state); + if on != should && !self.ticks.will_block_tick_this_tick(pos, block) { + let priority = if self.diode_should_prioritize(pos, state) { + TickPriority::ExtremelyHigh + } else if on { + TickPriority::VeryHigh + } else { + TickPriority::High + }; + let delay = self.diode_delay(state); + self.schedule_tick_priority(pos, block, delay, priority); + } + } + /// `DiodeBlock.tick` / `ComparatorBlock.tick`. + pub(crate) fn diode_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + if b.instance_of(state, Class::Comparator) { + self.comparator_refresh(pos, state); + return; + } + if self.diode_is_locked(pos, state) { + return; + } + let on = b.table.bool(state, b.props.powered); + let should = self.diode_should_turn_on(pos, state); + if on && !should { + self.set_block(pos, b.table.set_bool(state, b.props.powered, false), 2); + } else if !on { + self.set_block(pos, b.table.set_bool(state, b.props.powered, true), 2); + if !should { + let delay = self.diode_delay(state); + self.schedule_tick_priority(pos, b.block(state), delay, TickPriority::VeryHigh); + } + } + } + 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); + 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); + if on && !should { + self.set_block(pos, b.table.set_bool(state, b.props.powered, false), 2); + } else if !on && should { + self.set_block(pos, b.table.set_bool(state, b.props.powered, true), 2); + } + self.diode_update_neighbors_in_front(pos, state); + } + } + /// `DiodeBlock.neighborChanged`. + pub(crate) fn diode_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId) { + let block = self.b.block(state); + if !self.b.is_block(self.state(pos), block) { + return; + } + if self.can_survive(state, pos) { + self.diode_check_tick_on_neighbor(pos, state); + } else { + self.drop_resources(state, pos); + self.remove_block(pos, false); + for direction in Direction::ALL { + self.update_neighbors_at(rel(pos, direction), block); + } + } + } + + /// `getAnalogOutputSignal` for state-only sources; others ask the caller. + 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 { + Class::Beehive => b.table.int(state, p.honey_level), + Class::Cake => (7 - b.table.int(state, p.bites)) * 2, + Class::CandleCake => 14, + Class::Composter | Class::LayeredCauldron => b.table.int(state, p.level), + Class::CopperBulb => { + if b.table.bool(self.state(pos), p.lit) { + 15 + } else { + 0 + } + } + Class::EndPortalFrame => { + if b.table.bool(state, p.eye) { + 15 + } else { + 0 + } + } + Class::LavaCauldron => 3, + Class::RespawnAnchor => { + let charges = b.table.int(state, p.charges); + (charges as f32 / 4.0 * 15.0).floor() as i32 + } + 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) + } + _ => self.level.block_entity_analog_signal(pos, state, direction), + } + } + + // ---- torches ---- + + fn torch_has_neighbor_signal(&self, pos: BlockPos, state: BlockStateId) -> bool { + if self.b.instance_of(state, Class::RedstoneWallTorch) { + let opposite = self.b.facing(state).opposite(); + self.has_signal(rel(pos, opposite), opposite) + } else { + self.has_signal(below(pos), Direction::Down) + } + } + pub(crate) fn torch_notify_neighbors(&mut self, pos: BlockPos, state: BlockStateId) { + let block = self.b.block(state); + for direction in Direction::ALL { + self.update_neighbors_at(rel(pos, direction), block); + } + } + pub(crate) fn torch_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId) { + let block = self.b.block(state); + if self.b.table.bool(state, self.b.props.lit) == self.torch_has_neighbor_signal(pos, state) + && !self.ticks.will_block_tick_this_tick(pos, block) + { + self.schedule_tick(pos, block, 2); + } + } + fn torch_toggled_too_frequently(&mut self, pos: BlockPos, add: bool) -> bool { + if add { + 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 + } + 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) + { + self.ticks.torch_toggles.remove(0); + } + if b.table.bool(state, b.props.lit) { + if signal { + self.set_block_and_update(pos, b.table.set_bool(state, b.props.lit, false)); + if self.torch_toggled_too_frequently(pos, true) { + self.level_event(1502, pos, 0); + let block = b.block(self.state(pos)); + self.schedule_tick(pos, block, 160); + } + } + } else if !signal && !self.torch_toggled_too_frequently(pos, false) { + self.set_block_and_update(pos, b.table.set_bool(state, b.props.lit, true)); + } + } + + // ---- observers ---- + + pub(crate) fn observer_start_signal(&mut self, pos: BlockPos, block: BlockId) { + if !self.ticks.has_block_tick(pos, block) { + self.schedule_tick(pos, block, 2); + } + } + pub(crate) fn observer_update_in_front(&mut self, pos: BlockPos, state: BlockStateId) { + let direction = self.b.facing(state); + let opposite = rel(pos, direction.opposite()); + let block = self.b.block(state); + self.neighbor_changed_at(opposite, block); + self.update_neighbors_at_except(opposite, block, direction); + } + pub(crate) fn observer_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + if b.table.bool(state, b.props.powered) { + self.set_block(pos, b.table.set_bool(state, b.props.powered, false), 2); + } else { + self.set_block(pos, b.table.set_bool(state, b.props.powered, true), 2); + self.schedule_tick(pos, b.block(state), 2); + } + self.observer_update_in_front(pos, state); + } + + // ---- buttons, levers, plates ---- + + /// `ButtonBlock/LeverBlock.updateNeighbours`. + pub(crate) fn attached_update_neighbours(&mut self, pos: BlockPos, state: BlockStateId) { + let front = self.face_attached_connected(state).opposite(); + let block = self.b.block(state); + self.update_neighbors_at(pos, block); + self.update_neighbors_at(rel(pos, front), block); + } + pub(crate) fn plate_update_neighbours(&mut self, pos: BlockPos, block: BlockId) { + self.update_neighbors_at(pos, block); + self.update_neighbors_at(below(pos), block); + } + pub(crate) fn plate_signal_for_state(&self, state: BlockStateId) -> i32 { + let b = self.b; + if b.instance_of(state, Class::WeightedPressurePlate) { + b.table.int(state, b.props.power) + } else if b.table.bool(state, b.props.powered) { + 15 + } else { + 0 + } + } + fn plate_signal_strength(&self, pos: BlockPos, state: BlockStateId) -> i32 { + 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, + ), + ); + 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); + if count > 0 { + (count.min(max) as f32 / max as f32 * 15.0).ceil() as i32 + } else { + 0 + } + } else { + let query = if data.set_type.as_ref().is_some_and(|s| s.mobs_only) { + super::EntityQuery::Mobs + } else { + super::EntityQuery::Everything + }; + 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, + ) { + let b = self.b; + let signal = self.plate_signal_strength(pos, state); + let was = old_signal > 0; + let is = signal > 0; + let block = b.block(state); + if old_signal != signal { + let new = if b.instance_of(state, Class::WeightedPressurePlate) { + b.table.set_int(state, b.props.power, signal) + } else { + b.table.set_bool(state, b.props.powered, signal > 0) + }; + self.set_block(pos, new, 2); + self.plate_update_neighbours(pos, block); + } + if let Some(set) = b.data(state).set_type.clone() { + if !is && was { + self.sound(pos, &set.plate_off, 1.0, 1.0); + self.game_event(pos, "minecraft:block_deactivate"); + } else if is && !was { + self.sound(pos, &set.plate_on, 1.0, 1.0); + self.game_event(pos, "minecraft:block_activate"); + } + } + if is { + let delay = if b.instance_of(state, Class::WeightedPressurePlate) { + 10 + } else { + 20 + }; + self.schedule_tick(pos, block, delay); + } + } + /// `ButtonBlock.press`. + pub(crate) fn button_press(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + self.set_block_and_update(pos, b.table.set_bool(state, b.props.powered, true)); + self.attached_update_neighbours(pos, state); + let data = b.data(state); + self.schedule_tick(pos, b.block(state), data.ticks_to_stay_pressed); + if let Some(set) = data.set_type.clone() { + self.sound(pos, &set.button_on, 1.0, 1.0); + } + self.game_event(pos, "minecraft:block_activate"); + } + /// `ButtonBlock.checkPressed` with no arrows present. + pub(crate) fn button_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + if !b.table.bool(state, b.props.powered) { + return; + } + self.set_block_and_update(pos, b.table.set_bool(state, b.props.powered, false)); + self.attached_update_neighbours(pos, state); + if let Some(set) = b.data(state).set_type.clone() { + self.sound(pos, &set.button_off, 1.0, 1.0); + } + self.game_event(pos, "minecraft:block_deactivate"); + } + /// `LeverBlock.pull`. + pub(crate) fn lever_pull(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let state = b.table.cycle(state, b.props.powered); + self.set_block_and_update(pos, state); + self.attached_update_neighbours(pos, state); + let powered = b.table.bool(state, b.props.powered); + self.emit(LevelEvent::Sound { + pos, + sound: "minecraft:block.lever.click".into(), + volume: 0.3, + pitch: if powered { 0.6 } else { 0.5 }, + }); + 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, + ) { + let b = self.b; + let p = b.props; + 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" + }, + ); + } + 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() + }; + 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() + }; + self.sound(pos, &sound, 1.0, pitch); + 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) { + let b = self.b; + let p = b.props; + let signal = self.has_neighbor_signal(pos); + if signal != b.table.bool(state, p.powered) { + let mut state = state; + if b.table.bool(state, p.open) != signal { + state = b.table.set_bool(state, p.open, signal); + self.trapdoor_sound(pos, state, signal); + } + self.set_block(pos, b.table.set_bool(state, p.powered, signal), 2); + if b.is_waterlogged(state) { + self.schedule_water_tick(pos); + } + } + } + pub(crate) fn gate_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + 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); + 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 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" + }, + ); + } + } + } + pub(crate) fn lamp_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let lit = b.table.bool(state, b.props.lit); + if lit != self.has_neighbor_signal(pos) { + if lit { + self.schedule_tick(pos, b.block(state), 4); + } else { + self.set_block(pos, b.table.cycle(state, b.props.lit), 2); + } + } + } + pub(crate) fn lamp_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + if b.table.bool(state, b.props.lit) && !self.has_neighbor_signal(pos) { + self.set_block(pos, b.table.cycle(state, b.props.lit), 2); + } + } + /// `CopperBulbBlock.checkAndFlip`. + pub(crate) fn copper_bulb_check(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let p = b.props; + let signal = self.has_neighbor_signal(pos); + if signal != b.table.bool(state, p.powered) { + let mut next = state; + if !b.table.bool(state, p.powered) { + next = b.table.cycle(next, p.lit); + let sound = if b.table.bool(next, p.lit) { + "minecraft:block.copper_bulb.turn_on" + } else { + "minecraft:block.copper_bulb.turn_off" + }; + self.emit(LevelEvent::Sound { + pos, + sound: sound.into(), + volume: 1.0, + pitch: 1.0, + }); + } + self.set_block(pos, b.table.set_bool(next, p.powered, signal), 3); + } + } + /// `NoteBlock.playNote` (block event; instrument pitch from `note`). + 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)); + 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 sound = match instrument.as_str() { + "custom_head" => "minecraft:ui.button.click".to_owned(), + "dragon" => "minecraft:block.note_block.imitate.ender_dragon".to_owned(), + name if mob_head => format!("minecraft:block.note_block.imitate.{name}"), + name => format!("minecraft:block.note_block.{name}"), + }; + self.emit(LevelEvent::Sound { + pos, + sound: sound.into(), + volume: 3.0, + pitch, + }); + self.game_event(pos, "minecraft:note_block_play"); + } + } + pub(crate) fn note_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let signal = self.has_neighbor_signal(pos); + if signal != b.table.bool(state, b.props.powered) { + if signal { + self.note_play(pos, state); + } + self.set_block_and_update(pos, b.table.set_bool(state, b.props.powered, signal)); + } + } + /// `TntBlock.prime` then `removeBlock`. + pub(crate) fn tnt_check(&mut self, pos: BlockPos) { + if self.has_neighbor_signal(pos) { + self.emit(LevelEvent::PrimeTnt { pos }); + self.remove_block(pos, false); + } + } + pub(crate) fn dispenser_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let trigger = self.has_neighbor_signal(pos) || self.has_neighbor_signal(above(pos)); + let triggered = b.table.bool(state, b.props.triggered); + if trigger && !triggered { + 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 { + self.set_block(pos, b.table.set_bool(state, b.props.triggered, false), 2); + } + } + pub(crate) fn hopper_check_powered(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let enabled = !self.has_neighbor_signal(pos); + if enabled != b.table.bool(state, b.props.enabled) { + self.set_block(pos, b.table.set_bool(state, b.props.enabled, enabled), 2); + } + } + pub(crate) fn skull_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let signal = self.has_neighbor_signal(pos); + if signal != b.table.bool(state, b.props.powered) { + self.set_block(pos, b.table.set_bool(state, b.props.powered, signal), 2); + } + } + pub(crate) fn bell_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let signal = self.has_neighbor_signal(pos); + if signal != b.table.bool(state, b.props.powered) { + if signal { + self.emit(LevelEvent::Sound { + pos, + sound: "minecraft:block.bell.use".into(), + volume: 2.0, + pitch: 1.0, + }); + self.game_event(pos, "minecraft:block_change"); + } + self.set_block_and_update(pos, b.table.set_bool(state, b.props.powered, signal)); + } + } + pub(crate) fn crafter_neighbor_changed(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let trigger = self.has_neighbor_signal(pos); + let triggered = b.table.bool(state, b.props.triggered); + if trigger && !triggered { + 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, + ); + self.set_block(pos, next, 2); + } + } +} + +/// Order `positions` as a `java.util.HashSet` of capacity 16 would +/// iterate them (bucket index of the spread hash, then insertion order). +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) + } + let mut unique: Vec = Vec::new(); + for pos in positions.iter() { + if !unique.contains(pos) { + unique.push(*pos); + } + } + let buckets = 16; + let bucket = |pos: BlockPos| { + 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(); + 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 new file mode 100644 index 000000000..6b9399346 --- /dev/null +++ b/crates/horizon-world/src/level/shapes.rs @@ -0,0 +1,1251 @@ +//! `BlockBehaviour.updateShape` for every overriding vanilla class. +//! +//! Dispatch walks the block's class chain; a handler returning `None` defers +//! to the next class (the Java `super` call), the end of the chain returns the +//! state unchanged (`BlockBehaviour.updateShape`). +use super::{ + LevelAccess, Sim, + classes::Class, + query::{axis_of, clockwise, counter_clockwise, is_horizontal}, + states::BlockId, + update::{above, below, rel}, +}; +use crate::{fluid::FluidKind, registry::BlockStateId}; +use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource}; + +impl Sim<'_, L> { + /// `BlockState.updateShape(level, ticks, pos, direction, neighbourPos, neighbourState, random)`. + pub fn update_shape( + &mut self, + state: BlockStateId, + pos: BlockPos, + direction: Direction, + neighbour_pos: BlockPos, + neighbour: BlockStateId, + ) -> BlockStateId { + self.update_shape_at(0, state, pos, direction, neighbour_pos, neighbour) + } + + pub(crate) fn schedule_water_tick(&mut self, pos: BlockPos) { + self.schedule_fluid_tick(pos, FluidKind::Water, 5); + } + fn waterlogged_tick(&mut self, state: BlockStateId, pos: BlockPos) { + if self.b.is_waterlogged(state) { + self.schedule_water_tick(pos); + } + } + + fn update_shape_at( + &mut self, + depth: usize, + state: BlockStateId, + pos: BlockPos, + direction: Direction, + neighbour_pos: BlockPos, + neighbour: BlockStateId, + ) -> BlockStateId { + 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, + ) { + return result; + } + } + state + } + + #[allow(clippy::too_many_arguments)] + fn update_shape_class( + &mut self, + class: Class, + depth: usize, + state: BlockStateId, + pos: BlockPos, + dir: Direction, + npos: BlockPos, + nstate: BlockStateId, + ) -> Option { + let b = self.b; + let p = b.props; + let t = &b.tags; + let n = b.named; + let table = &b.table; + let air = b.air(); + let block = b.block(state); + macro_rules! sup { + () => { + self.update_shape_at(depth + 1, state, pos, dir, npos, nstate) + }; + } + // `dir == X && !canSurvive ? AIR : super`. + macro_rules! survive_or_air { + ($cond:expr) => {{ + 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) + { + table.set_bool(state, p.occupied, table.bool(nstate, p.occupied)) + } else { + air + } + } else { + sup!() + } + } + Class::AmethystCluster | Class::ShelfMushroom => { + if class == Class::AmethystCluster { + self.waterlogged_tick(state, pos); + } + 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 let Some(stem) = b.data(state).link2 { + return Some(table.set_int(b.default_of(stem), p.age, 7)); + } + } + sup!() + } + Class::BambooSapling => { + if !self.can_survive(state, pos) { + air + } else if dir == Direction::Up && b.is_block(nstate, n.bamboo) { + b.default_of(n.bamboo) + } else { + sup!() + } + } + Class::BambooStalk => { + 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) + { + table.cycle(state, p.age) + } else { + sup!() + } + } + Class::Banner + | Class::BasePressurePlate + | Class::BaseTorch + | Class::Cake + | Class::CandleCake + | Class::FlowerPot + | Class::StandingSign => survive_or_air!(dir == Direction::Down), + Class::Barrier + | Class::BaseRail + | Class::Candle + | Class::Chain + | Class::Conduit + | Class::CopperGolemStatue + | Class::DecoratedPot + | Class::DriedGhast + | Class::EnderChest + | Class::HeavyCore + | Class::Light + | Class::LightningRod + | Class::MangroveRoots + | Class::SculkSensor + | Class::SculkShrieker + | Class::Shelf + | Class::Sign + | Class::Slab + | Class::SmallDripleaf + | Class::TrapDoor + | Class::WaterloggedTransparent => { + self.waterlogged_tick(state, pos); + sup!() + } + Class::BaseCoralPlantType => { + self.waterlogged_tick(state, pos); + survive_or_air!(dir == Direction::Down) + } + Class::BaseCoralWallFan => { + self.waterlogged_tick(state, pos); + 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" + { + return Some(air); + } + if axis_of(dir) == axis_of(b.facing(state)) { + if attachment == "double_wall" && !b.is_face_sturdy(nstate, dir) { + 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)) + { + return Some(table.set_text(state, p.attachment, "double_wall")); + } + } + sup!() + } + Class::BigDripleaf => { + if dir == Direction::Down && !self.can_survive(state, pos) { + return Some(air); + } + self.waterlogged_tick(state, pos); + if dir == Direction::Up && b.is_block(nstate, block) { + table.with_properties_of(n.big_dripleaf_stem, state) + } else { + sup!() + } + } + Class::BigDripleafStem => { + if matches!(dir, Direction::Down | Direction::Up) && !self.can_survive(state, pos) { + self.schedule_tick(pos, block, 1); + } + self.waterlogged_tick(state, pos); + sup!() + } + Class::Brushable => { + self.schedule_tick(pos, block, 2); + sup!() + } + Class::BubbleColumn => { + 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)) + { + self.schedule_tick(pos, block, 5); + } + sup!() + } + Class::Cactus | Class::SugarCane => { + if !self.can_survive(state, pos) { + self.schedule_tick(pos, block, 1); + } + sup!() + } + Class::Campfire => { + 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)), + ) + } else { + sup!() + } + } + Class::Carpet | Class::SnowLayer | Class::Vegetation | Class::Frogspawn => { + survive_or_air!(true) + } + Class::SeaPickle => { + if !self.can_survive(state, pos) { + return Some(air); + } + self.waterlogged_tick(state, pos); + sup!() + } + 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) { + let neighbour_type = table.text(nstate, p.kind); + if table.text(state, p.kind) == "single" + && neighbour_type != "single" + && b.facing(state) == b.facing(nstate) + && self.chest_connected_direction(nstate) == dir.opposite() + { + 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 { + return Some(table.set_text(state, p.kind, "single")); + } + sup!() + } + Class::CopperChest => { + let result = sup!(); + if self.chest_can_connect_to(state, nstate) + && table.text(result, p.kind) != "single" + && self.chest_connected_direction(result) == dir + { + return Some(table.with_properties_of(b.block(nstate), result)); + } + result + } + Class::ChorusFlower => { + if dir != Direction::Up && !self.can_survive(state, pos) { + self.schedule_tick(pos, block, 1); + } + sup!() + } + Class::ChorusPlant => { + if !self.can_survive(state, pos) { + self.schedule_tick(pos, block, 1); + sup!() + } else { + let connect = b.is_block(nstate, block) + || b.is_block(nstate, n.chorus_flower) + || (dir == Direction::Down && b.in_set(nstate, &t.supports_chorus_plant)); + table.set_bool(state, self.direction_prop(dir), connect) + } + } + 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!() + } + } + Class::ConcretePowder => { + if self.concrete_touches_liquid(pos) { + b.data(state) + .link + .map_or(state, |concrete| b.default_of(concrete)) + } else { + sup!() + } + } + Class::Coral => { + if !self.coral_scan_for_water(pos) { + let delay = 60 + self.random().next_int_bound(40).unwrap_or(0); + self.schedule_tick(pos, block, delay); + } + sup!() + } + Class::CoralFan | Class::CoralPlant => { + if dir == Direction::Down && !self.can_survive(state, pos) { + return Some(air); + } + self.coral_try_schedule_die_tick(state, pos); + self.waterlogged_tick(state, pos); + sup!() + } + Class::CoralWallFan => { + if dir.opposite() == b.facing(state) && !self.can_survive(state, pos) { + return Some(air); + } + self.waterlogged_tick(state, pos); + self.coral_try_schedule_die_tick(state, pos); + sup!() + } + Class::CreakingHeart => { + self.schedule_tick(pos, block, 1); + sup!() + } + 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) + { + table.set_text(nstate, p.half, table.text(state, p.half)) + } else { + air + } + } + Class::DoublePlant => { + let half = table.text(state, p.half); + let lower = half == "lower"; + if dir.normal()[1] == 0 + || 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!() + } + } else { + air + } + } + Class::PitcherCrop => { + if table.int(state, p.age) >= 3 { + sup!() + } else if self.can_survive(state, pos) { + state + } else { + air + } + } + 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 + }; + 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 + }; + self.schedule_tick(pos, block, delay); + sup!() + } + Class::Farmland | Class::Path => { + if dir == Direction::Up && !self.can_survive(state, pos) { + self.schedule_tick(pos, block, 1); + } + sup!() + } + Class::Fence => { + 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()), + ) + } else { + sup!() + } + } + Class::IronBars => { + 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), + ) + } else { + sup!() + } + } + Class::FenceGate => { + if axis_of(clockwise(b.facing(state))) != axis_of(dir) { + sup!() + } else { + let other = self.rel_state(pos, dir.opposite()); + let in_wall = b.in_set(nstate, &t.walls) || b.in_set(other, &t.walls); + table.set_bool(state, p.in_wall, in_wall) + } + } + Class::Fire => { + if self.can_survive(state, pos) { + let age = table.int(state, p.age); + self.fire_state_with_age(pos, age) + } else { + air + } + } + Class::SoulFire => { + if self.can_survive(state, pos) { + b.default_of(block) + } else { + air + } + } + Class::GrowingPlantBody => { + let growth = b.data(state).growth_direction; + if dir == growth.opposite() && !self.can_survive(state, pos) { + self.schedule_tick(pos, block, 1); + } + let (head, _) = self.growing_plant_pair(block); + if dir == growth && !b.is_block(nstate, block) && !b.is_block(nstate, head) { + let age = self.random().next_int_bound(25).unwrap_or(0); + let head_state = table.set_int(b.default_of(head), p.age, age); + return Some(if class_is(b, block, Class::CaveVinesPlant) { + table.set_bool(head_state, p.berries, table.bool(state, p.berries)) + } else { + head_state + }); + } + if b.data(state).schedule_fluid_ticks { + self.schedule_water_tick(pos); + } + sup!() + } + Class::GrowingPlantHead => { + let growth = b.data(state).growth_direction; + let (_, body) = self.growing_plant_pair(block); + 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)) + } else { + body_state + } + }; + if dir == growth.opposite() { + if !self.can_survive(state, pos) { + self.schedule_tick(pos, block, 1); + } else { + let next = self.rel_state(pos, growth); + if b.is_block(next, block) || b.is_block(next, body) { + return Some(to_body(self)); + } + } + } + if dir != growth || (!b.is_block(nstate, block) && !b.is_block(nstate, body)) { + if b.data(state).schedule_fluid_ticks { + self.schedule_water_tick(pos); + } + sup!() + } else { + to_body(self) + } + } + Class::HangingMoss => { + let above_state = self.above_state(pos); + if !(b.multiface_can_attach(above_state, Direction::Up) + || b.is_block(above_state, block)) + { + self.schedule_tick(pos, block, 1); + } + table.set_bool(state, p.tip, !b.is_block(self.below_state(pos), block)) + } + Class::HangingRoots => { + if dir == Direction::Up && !self.can_survive(state, pos) { + return Some(air); + } + self.waterlogged_tick(state, pos); + sup!() + } + Class::HugeMushroom => { + 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) { + return Some(air); + } + self.waterlogged_tick(state, pos); + sup!() + } + Class::Leaves => { + self.waterlogged_tick(state, pos); + let distance = self.leaf_distance_at(nstate) + 1; + if distance != 1 || table.int(state, p.distance) != distance { + self.schedule_tick(pos, block, 1); + } + state + } + Class::Liquid => { + let fluid = b.fluid(state); + if fluid.is_source() || b.fluid(nstate).is_source() { + let delay = self.fluid_tick_delay(fluid.kind()); + self.schedule_fluid_tick(pos, fluid.kind(), delay); + } + if dir == Direction::Down && self.should_bubble_column_occupy(state) { + self.try_schedule_bubble_column(pos, nstate, block); + } + sup!() + } + Class::MangrovePropagule => { + self.waterlogged_tick(state, pos); + survive_or_air!(dir == Direction::Up) + } + Class::MossyCarpet => { + if !self.can_survive(state, pos) { + return Some(air); + } + let updated = self.mossy_carpet_updated_state(state, pos, false); + 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)) + { + air + } 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 + } + } 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!() + } + } + Class::Observer => { + if b.facing(state) == dir && !table.bool(state, p.powered) { + self.observer_start_signal(pos, block); + } + sup!() + } + 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 { + Class::RedstoneWallTorch | Class::WallTorch => { + if fails { + air + } else { + state + } + } + _ => { + if fails { + air + } else { + sup!() + } + } + } + } + Class::RedstoneWire => self.redstone_wire_update_shape(state, pos, dir, npos, nstate), + Class::Repeater => { + if dir == Direction::Down && !b.is_face_sturdy_rigid(nstate, Direction::Up) { + air + } else if axis_of(dir) != axis_of(b.facing(state)) { + let locked = self.diode_is_locked(pos, state); + table.set_bool(state, p.locked, locked) + } else { + sup!() + } + } + Class::Scaffolding => { + self.waterlogged_tick(state, pos); + self.schedule_tick(pos, block, 1); + state + } + Class::Seagrass => { + let result = sup!(); + if !b.is_air(result) { + self.schedule_water_tick(pos); + } + result + } + Class::Snowy => { + 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); + if tip == Direction::Down && self.ticks.has_block_tick(pos, block) { + return Some(state); + } + if dir == tip.opposite() && !self.can_survive(state, pos) { + self.schedule_tick(pos, block, if tip == Direction::Down { 2 } else { 1 }); + state + } else { + let merge = table.text(state, p.thickness) == "tip_merge"; + let thickness = self.speleothem_thickness(pos, tip, merge); + table.set_text(state, p.thickness, thickness) + } + } + Class::Stair => { + self.waterlogged_tick(state, pos); + if is_horizontal(dir) { + let shape = self.stairs_shape(state, pos); + table.set_text(state, p.shape, shape) + } else { + sup!() + } + } + Class::TripWire => { + if is_horizontal(dir) { + let connect = self.tripwire_should_connect_to(nstate, dir); + table.set_bool(state, self.direction_prop(dir), connect) + } else { + sup!() + } + } + Class::Vine => { + if dir == Direction::Down { + sup!() + } else { + let updated = self.vine_updated_state(state, pos); + if self.vine_count_faces(updated) == 0 { + air + } else { + updated + } + } + } + Class::Wall => { + self.waterlogged_tick(state, pos); + 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"); + self.wall_shape(state, npos, nstate, sides) + } + _ => { + let opposite = dir.opposite(); + 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, + ) + } else { + table.text(state, self.direction_prop(d)) != "none" + } + }); + let above_pos = above(pos); + let above_state = self.state(above_pos); + self.wall_shape(state, above_pos, above_state, sides) + } + } + } + Class::WallHangingSign => { + survive_or_air!(axis_of(dir) == axis_of(clockwise(b.facing(state)))) + } + Class::PotentSulfur => self.potent_sulfur_state(state, pos), + Class::NetherPortal => sup!(), + _ => return None, + }) + } + + // ---- family helpers ---- + + /// `PotentSulfurBlock.validBlockState` (the geyser block-entity countdown + /// reset is the caller's). + pub(crate) fn potent_sulfur_state(&self, state: BlockStateId, pos: BlockPos) -> BlockStateId { + let b = self.b; + let key = b.props.potent_sulfur_state; + if self.fluid_at(above(pos)).kind() != FluidKind::Water { + return b.table.set_text(state, key, "dry"); + } + let below_state = self.below_state(pos); + let fluid = b.fluid(below_state); + let source_if_fluid = fluid.kind() == FluidKind::Empty || fluid.is_source(); + let tagged = |name: &str| b.tag(name).is_some_and(|tag| b.in_set(below_state, tag)); + if tagged("minecraft:causes_continuous_geyser_eruptions") && source_if_fluid { + return b.table.set_text(state, key, "continuous"); + } + if tagged("minecraft:causes_periodic_geyser_eruptions") && source_if_fluid { + if b.table.text(state, key) == "erupting" { + state + } else { + b.table.set_text(state, key, "dormant") + } + } else { + b.table.set_text(state, key, "wet") + } + } + + 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() + } + } + 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) + } else { + b.block(state) == b.block(other) + } + } + /// `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) + } + } + /// `FenceBlock.connectsTo`. + 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)); + (!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) + } + /// `WallBlock.connectsTo`. + 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 + } + /// `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 { + 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, + ]; + for (i, direction) in directions.into_iter().enumerate() { + let value = if !sides[i] { + "none" + } else if cover & (1 << (i + 1)) != 0 { + "tall" + } else { + "low" + }; + result = table.set_text(result, self.direction_prop(direction), value); + } + // 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 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", + ); + if (nn && sn && wn && en) || nn != sn || wn != en { + true + } else if (north == "tall" && south == "tall") || (east == "tall" && west == "tall") { + false + } else { + b.in_set(top, &b.tags.wall_post_override) || cover & 1 != 0 + } + }; + table.set_bool(result, b.props.up, raise) + } + /// `StairBlock.getStairsShape`. + pub(crate) fn stairs_shape(&self, state: BlockStateId, pos: BlockPos) -> &'static str { + let b = self.b; + let p = b.props; + let table = &b.table; + let facing = b.facing(state); + let half = table.text(state, p.half); + 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" + }; + } + } + 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" + }; + } + } + "straight" + } + 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) + || b.facing(neighbour) != b.facing(state) + || 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 { + let b = self.b; + if b.is_block(state, b.named.tripwire_hook) { + b.facing(state) == direction.opposite() + } else { + b.is_block(state, b.named.tripwire) + } + } + /// `LeavesBlock.getDistanceAt`. + pub(crate) fn leaf_distance_at(&self, state: BlockStateId) -> i32 { + let b = self.b; + if b.in_set(state, &b.tags.prevents_nearby_leaf_decay) { + 0 + } else if b.table.has(state, b.props.distance) { + b.table.int(state, b.props.distance) + } else { + 7 + } + } + /// `ConcretePowderBlock.touchesLiquid`. + pub(crate) fn concrete_touches_liquid(&self, pos: BlockPos) -> bool { + let b = self.b; + let solidifies = |state: BlockStateId| b.is_water_fluid(b.fluid(state).kind()); + let mut test = pos; + for direction in Direction::ALL { + let current = self.state(test); + if direction != Direction::Down || solidifies(current) { + test = rel(pos, direction); + let state = self.state(test); + if solidifies(state) && !b.is_face_sturdy(state, direction.opposite()) { + return true; + } + } + } + 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())) + } + /// `BaseCoralPlantTypeBlock.scanForWater(state, level, pos)`. + pub(crate) fn coral_plant_scan_for_water(&self, state: BlockStateId, pos: BlockPos) -> bool { + if self.b.is_waterlogged(state) { + return true; + } + self.coral_scan_for_water(pos) + } + /// `BaseCoralPlantTypeBlock.tryScheduleDieTick`. + pub(crate) fn coral_try_schedule_die_tick(&mut self, state: BlockStateId, pos: BlockPos) { + if !self.coral_plant_scan_for_water(state, pos) { + let delay = 60 + self.random().next_int_bound(40).unwrap_or(0); + let block = self.b.block(state); + self.schedule_tick(pos, block, delay); + } + } + /// `BubbleColumnBlock.canOccupy`. + pub(crate) fn bubble_column_can_occupy(&self, state: BlockStateId) -> bool { + let b = self.b; + let fluid = b.fluid(state); + b.is_block(state, b.named.bubble_column) + || (b.fluid_in(fluid.kind(), b.fluid_tags.bubble_column_can_occupy) + && b.instance_of(state, Class::Liquid) + && fluid.is_source() + && fluid.amount() >= 8) + } + 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() + } + 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) + { + self.schedule_tick(pos, block, 20); + } + } + /// `NoteBlock.setInstrument`. + pub(crate) fn note_block_instrument(&self, pos: BlockPos, state: BlockStateId) -> BlockStateId { + let b = self.b; + let above = b.facts(self.above_state(pos)).instrument; + let name = if super::data::instrument_works_above(above) { + above + } else { + let below = b.facts(self.below_state(pos)).instrument; + if super::data::instrument_works_above(below) { + 0 + } else { + below + } + }; + 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 { + 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) + }; + 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" + } + } 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" + } + } else { + "frustum" + } + } + } + /// `FireBlock.getStateWithAge` via `BaseFireBlock.getState`. + 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 + } + } + /// `BaseFireBlock.getState(level, pos)`. + pub(crate) fn fire_state_for(&self, pos: BlockPos) -> BlockStateId { + let b = self.b; + let below_pos = below(pos); + let below_state = self.state(below_pos); + if b.in_set(below_state, &b.tags.soul_fire_base_blocks) { + return b.default_of(b.named.soul_fire); + } + let fire = b.default_of(b.named.fire); + if !self.can_burn(below_state) && !b.is_face_sturdy(below_state, Direction::Up) { + let mut result = fire; + for direction in Direction::ALL { + if direction == Direction::Down { + continue; + } + let burn = self.can_burn(self.rel_state(pos, direction)); + result = b + .table + .set_bool(result, self.direction_prop(direction), burn); + } + result + } else { + fire + } + } + /// `MossyCarpetBlock.getUpdatedState`. + 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); + let base = table.bool(state, b.props.bottom); + 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, + ] { + 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) + } + } 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) + { + side = "tall"; + } + if !base { + let below = *below_state.get_or_insert_with(|| self.below_state(pos)); + if b.is_block(below, block) && table.text(below, key) == "none" { + side = "none"; + } + } + } + let side = side.to_owned(); + state = table.set_text(state, key, &side); + } + state + } + 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") + } +} + +fn table_bool(b: &super::Behaviours, state: BlockStateId) -> bool { + b.table.bool(state, b.props.bottom) +} +fn class_is(b: &super::Behaviours, block: BlockId, class: Class) -> bool { + b.block_data(block).is(class) +} diff --git a/crates/horizon-world/src/level/speleothem.rs b/crates/horizon-world/src/level/speleothem.rs new file mode 100644 index 000000000..60059cfe9 --- /dev/null +++ b/crates/horizon-world/src/level/speleothem.rs @@ -0,0 +1,369 @@ +//! `SpeleothemBlock` growth (pointed dripstone, sulfur spikes) and +//! `PointedDripstoneBlock` fluid transfer into cauldrons and mud. +use super::{ + LevelAccess, Sim, + classes::Class, + states::BlockId, + update::{above, below, rel}, +}; +use crate::{fluid::FluidKind, registry::BlockStateId}; +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)) + } + 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) + } + fn speleothem_is_tip(&self, state: BlockStateId, include_merged: bool) -> bool { + if !self.speleothem_tag(state) { + return false; + } + let thickness = self.b.table.text(state, self.b.props.thickness); + thickness == "tip" || (include_merged && thickness == "tip_merge") + } + fn is_free_hanging_stalactite(&self, state: BlockStateId) -> bool { + self.speleothem_with(state, Direction::Down) + && self.b.table.text(state, self.b.props.thickness) == "tip" + && !self.b.is_waterlogged(state) + } + /// `SpeleothemBlock.findBlockVertical`. + fn find_block_vertical( + &self, + pos: BlockPos, + up: bool, + path: impl Fn(&Self, BlockPos, BlockStateId) -> bool, + target: impl Fn(&Self, BlockStateId) -> bool, + max_steps: i32, + ) -> Option { + let mut current = pos; + for _ in 1..max_steps { + current = if up { above(current) } else { below(current) }; + let state = self.state(current); + if target(self, state) { + return Some(current); + } + if !self.is_inside_build_height(current.y) || !path(self, current, state) { + return None; + } + } + None + } + 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 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.speleothem_is_tip(s, include_merged), + max, + ) + } + /// `SpeleothemBlock.randomTick` (+ `PointedDripstoneBlock.maybeTransferFluid`). + pub(crate) fn speleothem_random_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + if b.instance_of(state, Class::PointedDripstone) { + 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)); + if self.random().next_float() < 0.011_377_778 && start { + self.speleothem_grow(state, pos); + } + } + fn speleothem_grow(&mut self, state: BlockStateId, pos: BlockPos) { + 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)); + if data.is(Class::PointedDripstone) { + let fluid = b.fluid(self.state(pos.offset(0, 2, 0))); + can_grow &= fluid.kind() == FluidKind::Water; + } + if !can_grow { + return; + } + let max = if data.is(Class::SulfurSpike) { 2 } else { 7 }; + let Some(tip_pos) = self.speleothem_find_tip(state, pos, max, false) else { + 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.random().next_boolean() { + self.speleothem_grow_to(block, tip_pos, Direction::Down); + } else { + self.speleothem_grow_stalagmite_below(block, tip_pos); + } + } + } + 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); + let grow = self.rel_state(tip_pos, direction); + if self.b.fluid(grow).kind() != FluidKind::Empty { + false + } else { + 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, + ) { + let b = self.b; + 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; + 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) { + let b = self.b; + 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)) + }; + 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) { + self.speleothem_create(block, target, direction, "tip"); + } + } + fn speleothem_grow_stalagmite_below(&mut self, block: BlockId, from: BlockPos) { + let b = self.b; + let mut pos = from; + for _ in 0..10 { + pos = below(pos); + let state = self.state(pos); + 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) + { + 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)) + { + 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) + { + return; + } + } + } + /// `PointedDripstoneBlock.canDripThrough`. + fn dripstone_can_drip_through(&self, state: BlockStateId) -> bool { + let b = self.b; + if b.is_air(state) { + return true; + } + if b.solid_render(state) || b.fluid(state).kind() != FluidKind::Empty { + return false; + } + // REQUIRED_SPACE_TO_DRIP_THROUGH_NON_SOLID_BLOCK = column(4, 0, 16). + 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) + }) + } + } + } + /// `PointedDripstoneBlock.getFluidAboveStalactite`: (position above the + /// root, fluid, state there). + 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; + } + let block = b.block(state); + let direction = Direction::Down; + 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), + 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 + { + FluidKind::Water + } else { + b.fluid(above_state).kind() + }; + Some((above_pos, fluid, above_state)) + } + fn dripstone_transfer_fluid(&mut self, state: BlockStateId, pos: BlockPos, value: f32) { + let b = self.b; + if value > 0.175_781_25 { + return; + } + 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 { + return; + }; + let probability = match fluid { + FluidKind::Water => 0.175_781_25, + FluidKind::Lava => 0.058_593_75, + _ => return, + }; + if value >= probability { + return; + } + let Some(tip) = self.speleothem_find_tip(state, pos, 11, false) else { + return; + }; + if b.is_block(source_state, b.named.mud) && fluid == FluidKind::Water { + self.set_block_and_update(source_pos, b.default_of(b.named.clay)); + self.game_event(source_pos, "minecraft:block_change"); + self.level_event(1504, tip, 0); + } else if let Some(cauldron) = self.dripstone_find_cauldron(tip, fluid) { + self.level_event(1504, tip, 0); + let delay = 50 + tip.y - cauldron.y; + let block = b.block(self.state(cauldron)); + self.schedule_tick(cauldron, block, delay); + } + } + fn cauldron_can_receive(&self, state: BlockStateId, fluid: FluidKind) -> bool { + let b = self.b; + let data = b.data(state); + if data.is(Class::Cauldron) { + true + } else if data.is(Class::LayeredCauldron) { + fluid == FluidKind::Water && b.is_block(state, b.named.water_cauldron) + } else { + false + } + } + fn dripstone_find_cauldron(&self, tip: BlockPos, fluid: FluidKind) -> Option { + self.find_block_vertical( + tip, + false, + |sim, _, s| sim.dripstone_can_drip_through(s), + |sim, s| sim.cauldron_can_receive(s, fluid), + 11, + ) + } + /// `AbstractCauldronBlock.tick`: receive a drip from a stalactite above. + pub(crate) fn cauldron_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let Some(tip) = self.find_block_vertical( + pos, + true, + |sim, _, s| sim.dripstone_can_drip_through(s), + |sim, s| sim.is_free_hanging_stalactite(s), + 11, + ) else { + return; + }; + let tip_state = self.state(tip); + let fluid = self + .dripstone_fluid_above(tip_state, tip) + .map(|(_, f, _)| f) + .filter(|f| matches!(f, FluidKind::Water | FluidKind::Lava)) + .unwrap_or(FluidKind::Empty); + if fluid == FluidKind::Empty || !self.cauldron_can_receive(state, fluid) { + return; + } + 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) + }; + self.set_block_and_update(pos, b.default_of(next)); + self.game_event(pos, "minecraft:block_change"); + self.level_event(event, pos, 0); + } else if data.is(Class::LayeredCauldron) { + let level = b.table.int(state, b.props.level); + if level < 3 { + self.set_block_and_update(pos, b.table.set_int(state, b.props.level, level + 1)); + self.game_event(pos, "minecraft:block_change"); + self.level_event(1047, pos, 0); + } + } + } +} diff --git a/crates/horizon-world/src/level/states.rs b/crates/horizon-world/src/level/states.rs new file mode 100644 index 000000000..abe6c08cf --- /dev/null +++ b/crates/horizon-world/src/level/states.rs @@ -0,0 +1,353 @@ +//! O(1) block-state property access over the pinned registry. +//! +//! Vanilla's `StateDefinition` enumerates a block's states as the cartesian +//! product of its properties sorted by name, the last property varying fastest, +//! and the global state registry lists every block's states contiguously. The +//! table below derives each property's stride from that layout and verifies it +//! against every registry descriptor at load, so `setValue` is arithmetic. +use crate::{ + compression::invalid, + registry::{BlockRegistry, BlockStateId}, +}; +use horizon_core::geometry::{Axis, Direction}; +use std::{collections::HashMap, io}; + +/// Registry-order block index; equals vanilla's `Block` registry ID. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct BlockId(pub u16); + +/// Interned property name (`facing`, `waterlogged`, ...), shared by all blocks. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct PropKey(pub u16); + +#[derive(Clone, Debug)] +pub struct PropValue { + pub text: Box, + pub int: Option, + pub boolean: Option, + pub direction: Option, +} +impl PropValue { + fn new(text: &str) -> Self { + Self { + int: text.parse().ok(), + boolean: match text { + "true" => Some(true), + "false" => Some(false), + _ => None, + }, + direction: direction_from_name(text), + text: text.into(), + } + } +} + +#[derive(Clone, Debug)] +struct Slot { + key: PropKey, + stride: u32, + values: Vec, +} + +#[derive(Clone, Debug)] +pub struct BlockInfo { + pub name: Box, + pub base: BlockStateId, + pub count: u32, + pub default: BlockStateId, + slots: Vec, +} + +pub struct StateTable { + blocks: Vec, + state_block: Vec, + keys: HashMap, + key_names: Vec, + by_name: HashMap, BlockId>, +} + +pub fn direction_from_name(name: &str) -> Option { + Some(match name { + "down" => Direction::Down, + "up" => Direction::Up, + "north" => Direction::North, + "south" => Direction::South, + "west" => Direction::West, + "east" => Direction::East, + _ => return None, + }) +} +pub const fn direction_name(direction: Direction) -> &'static str { + match direction { + Direction::Down => "down", + Direction::Up => "up", + Direction::North => "north", + Direction::South => "south", + Direction::West => "west", + Direction::East => "east", + } +} +pub const fn axis_name(axis: Axis) -> &'static str { + match axis { + Axis::X => "x", + Axis::Y => "y", + Axis::Z => "z", + } +} + +impl StateTable { + pub fn new(registry: &BlockRegistry) -> io::Result { + let mut table = Self { + blocks: Vec::new(), + state_block: Vec::with_capacity(registry.len()), + keys: HashMap::new(), + key_names: Vec::new(), + by_name: HashMap::new(), + }; + let mut index = 0; + 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 + { + end += 1; + } + let count = (end - index) as u32; + let names: Vec<&String> = first.properties.keys().collect(); + let mut slots = Vec::with_capacity(names.len()); + let mut stride = count; + for name in &names { + let mut values = Vec::new(); + // Values of this property cycle with period (stride / len); the + // 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(); + if !seen.contains(&value) { + seen.push(value); + } + } + stride /= seen.len() as u32; + for value in seen { + values.push(PropValue::new(value)); + } + let key = table.key_or_insert(name); + slots.push(Slot { + key, + stride, + values, + }); + } + if stride != 1 { + return Err(invalid("block state count is not a property product")); + } + // Order of values: derive from the states at multiples of stride. + for slot in &mut slots { + let len = slot.values.len() as u32; + let name = &table.key_names[slot.key.0 as usize]; + slot.values = (0..len) + .map(|i| { + PropValue::new( + ®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 default = registry + .default_state(&first.name) + .ok_or_else(|| invalid("block without default state"))?; + let info = BlockInfo { + name: first.name.as_str().into(), + base: BlockStateId(index as u32), + count, + default, + slots, + }; + 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]; + 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", + )); + } + } + table.state_block.push(block.0); + } + if table.by_name.insert(info.name.clone(), block).is_some() { + return Err(invalid("block states are not contiguous")); + } + table.blocks.push(info); + index = end; + } + Ok(table) + } + fn key_or_insert(&mut self, name: &str) -> PropKey { + if let Some(key) = self.keys.get(name) { + return *key; + } + let key = PropKey(self.key_names.len() as u16); + self.key_names.push(name.to_owned()); + self.keys.insert(name.to_owned(), key); + key + } + /// Property keys absent from every block resolve to an unused key, so + /// lookups through them simply report "no such property". + pub fn key(&mut self, name: &str) -> PropKey { + self.key_or_insert(name) + } + pub fn state_count(&self) -> usize { + self.state_block.len() + } + pub fn block_count(&self) -> usize { + self.blocks.len() + } + pub fn block(&self, state: BlockStateId) -> BlockId { + BlockId(self.state_block[state.0 as usize]) + } + pub fn info(&self, block: BlockId) -> &BlockInfo { + &self.blocks[block.0 as usize] + } + pub fn name(&self, state: BlockStateId) -> &str { + &self.info(self.block(state)).name + } + pub fn block_by_name(&self, name: &str) -> Option { + self.by_name.get(name).copied() + } + pub fn default_state(&self, block: BlockId) -> BlockStateId { + self.info(block).default + } + pub fn is(&self, state: BlockStateId, block: BlockId) -> bool { + 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) + } + pub fn has(&self, state: BlockStateId, key: PropKey) -> bool { + self.slot(state, key).is_some() + } + fn index_in(&self, state: BlockStateId, slot: &Slot) -> u32 { + let base = self.info(self.block(state)).base.0; + ((state.0 - base) / slot.stride) % slot.values.len() as u32 + } + pub fn value(&self, state: BlockStateId, key: PropKey) -> Option<&PropValue> { + let slot = self.slot(state, key)?; + Some(&slot.values[self.index_in(state, slot) as usize]) + } + pub fn text(&self, state: BlockStateId, key: PropKey) -> &str { + self.value(state, key).map_or("", |v| &v.text) + } + /// 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) + } + /// Missing integer properties read as 0. + pub fn int(&self, state: BlockStateId, key: PropKey) -> i32 { + self.value(state, key).and_then(|v| v.int).unwrap_or(0) + } + pub fn dir(&self, state: BlockStateId, key: PropKey) -> Option { + self.value(state, key).and_then(|v| v.direction) + } + /// Number of values and minimum/maximum for integer properties. + pub fn int_range(&self, state: BlockStateId, key: PropKey) -> Option<(i32, i32)> { + let slot = self.slot(state, key)?; + let ints = slot.values.iter().filter_map(|v| v.int); + Some((ints.clone().min()?, ints.max()?)) + } + pub fn values(&self, block: BlockId, key: PropKey) -> impl Iterator { + self.info(block) + .slots + .iter() + .filter(move |slot| slot.key == key) + .flat_map(|slot| slot.values.iter()) + } + fn with_index(&self, state: BlockStateId, slot: &Slot, index: u32) -> BlockStateId { + let current = self.index_in(state, slot); + BlockStateId(state.0 - current * slot.stride + index * slot.stride) + } + /// `setValue` by text; None if the block lacks the property or value. + pub fn with_text(&self, state: BlockStateId, key: PropKey, text: &str) -> Option { + let slot = self.slot(state, key)?; + let index = slot.values.iter().position(|v| &*v.text == text)?; + Some(self.with_index(state, slot, index as u32)) + } + pub fn with_int(&self, state: BlockStateId, key: PropKey, value: i32) -> Option { + let slot = self.slot(state, key)?; + 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 { + 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 { + self.with_text(state, key, direction_name(value)) + } + /// Vanilla `setValue` callers always pass legal values; when Horizon's port + /// would compute an illegal one the state is returned unchanged. + pub fn set_text(&self, state: BlockStateId, key: PropKey, text: &str) -> BlockStateId { + self.with_text(state, key, text).unwrap_or(state) + } + pub fn set_int(&self, state: BlockStateId, key: PropKey, value: i32) -> BlockStateId { + self.with_int(state, key, value).unwrap_or(state) + } + pub fn set_bool(&self, state: BlockStateId, key: PropKey, value: bool) -> BlockStateId { + self.with_bool(state, key, value).unwrap_or(state) + } + pub fn set_dir(&self, state: BlockStateId, key: PropKey, value: Direction) -> BlockStateId { + self.with_dir(state, key, value).unwrap_or(state) + } + /// `cycle`: the next value in definition order, wrapping around. + pub fn cycle(&self, state: BlockStateId, key: PropKey) -> BlockStateId { + let Some(slot) = self.slot(state, key) else { + return state; + }; + let next = (self.index_in(state, slot) + 1) % slot.values.len() as u32; + self.with_index(state, slot, next) + } + /// `Block.withPropertiesOf`: copy every property the target block shares. + pub fn with_properties_of(&self, target: BlockId, source: BlockStateId) -> BlockStateId { + let mut result = self.default_state(target); + for slot in &self.info(self.block(source)).slots { + let value = &slot.values[self.index_in(source, slot) as usize]; + if let Some(next) = self.with_text(result, slot.key, &value.text) { + result = next; + } + } + 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()) + } +} diff --git a/crates/horizon-world/src/level/survive.rs b/crates/horizon-world/src/level/survive.rs new file mode 100644 index 000000000..0feda8c7c --- /dev/null +++ b/crates/horizon-world/src/level/survive.rs @@ -0,0 +1,589 @@ +//! `canSurvive` and `VegetationBlock.mayPlaceOn` for every overriding class. +//! Rules mirror the natively-validated `block_survival` port; dispatch follows +//! the Java class chain so `super.canSurvive` reaches the next override. +use super::{ + LevelAccess, Sim, + classes::Class, + query::is_horizontal, + update::{HORIZONTAL, above, below, rel}, +}; +use crate::registry::BlockStateId; +use horizon_core::{geometry::Direction, position::BlockPos}; + +impl Sim<'_, L> { + /// `BlockState.canSurvive(level, pos)`. + pub fn can_survive(&self, state: BlockStateId, pos: BlockPos) -> bool { + self.can_survive_at(0, state, pos) + } + fn can_survive_at(&self, depth: usize, state: BlockStateId, pos: BlockPos) -> bool { + let chain = &self.b.data(state).chain; + for (index, class) in chain.iter().enumerate().skip(depth) { + if let Some(result) = self.can_survive_class(*class, index, state, pos) { + return result; + } + } + true + } + 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; + let n = &b.named; + let block = b.block(state); + Some(match class { + Class::AmethystCluster | Class::ShelfMushroom | Class::BaseCoralWallFan => { + 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::BaseCoralPlantType | Class::LeafLitter => self.sturdy(below(pos), Direction::Up), + Class::BasePressurePlate => { + let below = below(pos); + self.can_support_rigid_block(below) || self.can_support_center(below, Direction::Up) + } + Class::BaseRail => self.can_support_rigid_block(below(pos)), + Class::BaseTorch | Class::Candle => self.can_support_center(below(pos), Direction::Up), + Class::Bell => { + let connection = self.bell_connected_direction(state).opposite(); + if connection == Direction::Up { + self.can_support_center(above(pos), Direction::Down) + } else { + self.sturdy(rel(pos, connection), connection.opposite()) + } + } + 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) + } + Class::BigDripleafStem => { + let below = self.below_state(pos); + let above = self.above_state(pos); + (b.is_block(below, block) || b.in_set(below, &t.supports_big_dripleaf)) + && (b.is_block(above, block) || b.is_block(above, n.big_dripleaf)) + } + Class::BubbleColumn => { + let below = self.below_state(pos); + b.is_block(below, block) + || b.in_set(below, &t.enables_bubble_column_push_up) + || b.in_set(below, &t.enables_bubble_column_drag_down) + } + Class::Cactus => { + for direction in HORIZONTAL { + let at = rel(pos, direction); + if b.is_solid(self.state(at)) || b.is_lava_fluid(self.fluid_at(at).kind()) { + return Some(false); + } + } + let below = self.below_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::ChorusFlower => { + let below = self.below_state(pos); + if b.is_block(below, n.chorus_plant) || b.in_set(below, &t.supports_chorus_flower) { + return Some(true); + } + if !b.is_air(below) { + return Some(false); + } + let mut one = false; + for direction in HORIZONTAL { + let neighbour = self.rel_state(pos, direction); + if b.is_block(neighbour, n.chorus_plant) { + if one { + return Some(false); + } + one = true; + } else if !b.is_air(neighbour) { + return Some(false); + } + } + one + } + Class::ChorusPlant => { + let below_state = self.below_state(pos); + let vertical = !b.is_air(self.above_state(pos)) && !b.is_air(below_state); + for direction in HORIZONTAL { + let neighbour_pos = rel(pos, direction); + if b.is_block(self.state(neighbour_pos), block) { + if vertical { + return Some(false); + } + let under = self.below_state(neighbour_pos); + if b.is_block(under, block) || b.in_set(under, &t.supports_chorus_plant) { + return Some(true); + } + } + } + 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::Diode => b.is_face_sturdy_rigid(self.below_state(pos), Direction::Up), + Class::Door => { + let below_state = self.below_state(pos); + if b.table.text(state, p.half) == "lower" { + b.is_face_sturdy(below_state, Direction::Up) + } else { + b.is_block(below_state, block) + } + } + Class::DoublePlant => { + if b.table.text(state, p.half) != "upper" { + return Some(self.can_survive_at(depth + 1, state, pos)); + } + let below_state = self.below_state(pos); + b.is_block(below_state, block) && b.table.text(below_state, p.half) == "lower" + } + Class::SmallDripleaf => { + if b.table.text(state, p.half) == "upper" { + return Some(self.can_survive_at(depth + 1, state, pos)); + } + let below = below(pos); + self.may_place_on(state, self.state(below), below) + } + 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", + ); + } + let fluid = self.fluid_at(pos); + 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"; + if lower && self.raw_brightness(pos, 0) < 8 { + false + } else { + self.can_survive_at(depth + 1, state, pos) + } + } + Class::FaceAttachedHorizontalDirectional => { + let direction = self.face_attached_connected(state).opposite(); + self.sturdy(rel(pos, direction), direction.opposite()) + } + Class::Grindstone => true, + Class::PistonHead => self.piston_head_can_survive(state, pos), + Class::Farmland => { + 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::SoulFire => b.in_set(self.below_state(pos), &t.soul_fire_base_blocks), + Class::Frogspawn => self.frogspawn_may_place_on(below(pos)), + Class::GrowingPlant => { + let data = b.data(state); + let growth = data.growth_direction; + let attached_pos = rel(pos, growth.opposite()); + let attached = self.state(attached_pos); + if !self.growing_plant_can_attach_to(state, attached) { + 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) + } + Class::HangingMoss => { + let neighbour = self.above_state(pos); + b.multiface_can_attach(neighbour, Direction::Up) || b.is_block(neighbour, block) + } + Class::HangingRoots => self.sturdy(above(pos), Direction::Down), + Class::Ladder => { + let facing = b.facing(state); + self.sturdy(rel(pos, facing.opposite()), facing) + } + Class::Lantern => { + 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, + ) + } else { + self.can_survive_at(depth + 1, state, pos) + } + } + Class::MossyCarpet => { + let below_state = self.below_state(pos); + if b.table.bool(state, p.bottom) { + !b.is_air(below_state) + } else { + b.is_block(below_state, block) && b.table.bool(below_state, p.bottom) + } + } + Class::Multiface => { + let mut any = false; + for direction in Direction::ALL { + if self.multiface_has_face(state, direction) { + if !b.multiface_can_attach(self.rel_state(pos, direction), direction) { + return Some(false); + } + any = true; + } + } + any + } + Class::Mushroom => { + let below_pos = below(pos); + let below_state = self.state(below_pos); + 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) + } + } + Class::Path => { + let above = self.above_state(pos); + !b.is_solid(above) || b.instance_of(above, Class::FenceGate) + } + Class::RedstoneWallTorch | Class::WallTorch => { + let facing = b.facing(state); + self.sturdy(rel(pos, facing.opposite()), facing) + } + Class::RedstoneWire => { + let below_state = self.below_state(pos); + b.is_face_sturdy(below_state, Direction::Up) || b.is_block(below_state, n.hopper) + } + Class::Scaffolding => self.scaffolding_distance(pos) < 7, + Class::SeaPickle => { + let below = below(pos); + self.may_place_on(state, self.state(below), below) + } + Class::SnowLayer => { + let below_state = self.below_state(pos); + if b.in_set(below_state, &t.cannot_support_snow_layer) { + false + } 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) + } + } + Class::Speleothem => { + 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::SugarCane => { + let below_state = self.below_state(pos); + if b.is_block(below_state, block) { + return Some(true); + } + if b.in_set(below_state, &t.supports_sugar_cane) { + let below = below(pos); + for direction in HORIZONTAL { + let at = rel(below, direction); + let fluid = self.fluid_at(at); + if b.fluid_in(fluid.kind(), b.fluid_tags.supports_sugar_cane_adjacently) + || b.in_set(self.state(at), &t.supports_sugar_cane_adjacently) + { + return Some(true); + } + } + } + false + } + Class::TripWireHook => { + let facing = b.facing(state); + is_horizontal(facing) && self.sturdy(rel(pos, facing.opposite()), facing) + } + Class::Vegetation => { + let below = below(pos); + self.may_place_on(state, self.state(below), below) + } + Class::Vine => { + 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())) + } + _ => return None, + }) + } + + /// `VegetationBlock.mayPlaceOn` (virtual) for `state`'s block. + 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)) + } + 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) + } + 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)) + && above.kind() == crate::fluid::FluidKind::Empty + } + Class::MangrovePropagule => b.in_set(ground, &t.supports_mangrove_propagule), + Class::Mushroom => b.solid_render(ground), + 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) + } + Class::Seagrass | Class::TallSeagrass => { + 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) + || (self.fluid_at(above(ground_pos)) == crate::fluid::FluidState::WATER + && b.in_set(ground, &t.supports_vegetation)) + } + Class::WitherRose => b.in_set(ground, &t.supports_wither_rose), + Class::Vegetation => b.in_set(ground, &t.supports_vegetation), + _ => continue, + }; + return result; + } + false + } + + fn frogspawn_may_place_on(&self, pos: BlockPos) -> bool { + 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)) + && above.kind() == crate::fluid::FluidKind::Empty + } + + pub(crate) fn bell_connected_direction(&self, state: BlockStateId) -> Direction { + match self.b.table.text(state, self.b.props.attachment) { + "floor" => Direction::Up, + "ceiling" => Direction::Down, + _ => self.b.facing(state).opposite(), + } + } + /// `FaceAttachedHorizontalDirectionalBlock.getConnectedDirection`. + pub(crate) fn face_attached_connected(&self, state: BlockStateId) -> Direction { + match self.b.table.text(state, self.b.props.face) { + "ceiling" => Direction::Down, + "floor" => Direction::Up, + _ => self.b.facing(state), + } + } + pub(crate) fn multiface_has_face(&self, state: BlockStateId, direction: Direction) -> bool { + self.b.table.bool(state, self.direction_prop(direction)) + } + pub(crate) fn direction_prop(&self, direction: Direction) -> super::states::PropKey { + let p = &self.b.props; + match direction { + Direction::Down => p.down, + Direction::Up => p.up, + Direction::North => p.north, + Direction::South => p.south, + Direction::West => p.west, + Direction::East => p.east, + } + } + /// 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) { + 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); + (head, body) + } + /// `GrowingPlantBlock.canAttachTo` (kelp refuses `cannot_support_kelp`). + fn growing_plant_can_attach_to(&self, state: BlockStateId, attached: BlockStateId) -> bool { + let b = self.b; + if b.instance_of(state, Class::Kelp) || b.instance_of(state, Class::KelpPlant) { + !b.in_set(attached, &b.tags.cannot_support_kelp) + } else { + true + } + } + /// `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))) + } + /// `FireBlock.canBurn`: ignite odds above zero (waterlogged states never burn). + pub(crate) fn can_burn(&self, state: BlockStateId) -> bool { + self.ignite_odds(state) > 0 + } + pub(crate) fn ignite_odds(&self, state: BlockStateId) -> i32 { + if self.b.is_waterlogged(state) { + 0 + } else { + self.b.data(state).ignite_odds + } + } + pub(crate) fn burn_odds(&self, state: BlockStateId) -> i32 { + if self.b.is_waterlogged(state) { + 0 + } else { + self.b.data(state).burn_odds + } + } + /// `ScaffoldingBlock.getDistance`. + pub(crate) fn scaffolding_distance(&self, pos: BlockPos) -> i32 { + let b = self.b; + let below_pos = below(pos); + let below_state = self.state(below_pos); + let mut distance = 7; + if b.is_block(below_state, b.named.scaffolding) { + distance = b.table.int(below_state, b.props.distance); + } else if b.is_face_sturdy(below_state, Direction::Up) { + return 0; + } + for direction in HORIZONTAL { + let neighbour = self.rel_state(pos, direction); + if b.is_block(neighbour, b.named.scaffolding) { + distance = distance.min(b.table.int(neighbour, b.props.distance) + 1); + if distance == 1 { + break; + } + } + } + distance + } + /// `SpeleothemBlock.isValidSpeleothemPlacement`. + 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)) + } + /// `VineBlock.getUpdatedState`. + 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); + if b.table.bool(state, p.up) { + let accept = b.multiface_can_attach(self.state(above_pos), Direction::Down); + state = b.table.set_bool(state, p.up, accept); + } + let mut above_state = None; + for direction in HORIZONTAL { + let key = self.direction_prop(direction); + if b.table.bool(state, key) { + let mut support = self.vine_can_support_at_face(state, pos, direction); + if !support { + let above = *above_state.get_or_insert_with(|| self.state(above_pos)); + support = b.is_block(above, b.block(state)) && b.table.bool(above, key); + } + state = b.table.set_bool(state, key, support); + } + } + state + } + fn vine_can_support_at_face( + &self, + state: BlockStateId, + pos: BlockPos, + direction: Direction, + ) -> bool { + let b = self.b; + if direction == Direction::Down { + return false; + } + if b.multiface_can_attach(self.rel_state(pos, direction), direction) { + return true; + } + if direction == Direction::Up { + return false; + } + let above = self.above_state(pos); + 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() + } +} diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs new file mode 100644 index 000000000..c1ffce5a1 --- /dev/null +++ b/crates/horizon-world/src/level/tests.rs @@ -0,0 +1,919 @@ +//! Behaviour tests over an in-memory level. They need the prepared client +//! resources (`HORIZON_RESOURCES`, or `.local/horizon-client/26.3` at the +//! repository root) and are skipped when those are absent. +use super::*; +use crate::chunk::BlockState; +use std::{ + collections::{BTreeMap, HashMap}, + path::PathBuf, + sync::OnceLock, +}; + +struct Fixture { + registry: BlockRegistry, + behaviours: Behaviours, +} + +fn fixture() -> Option<&'static Fixture> { + static FIXTURE: OnceLock> = OnceLock::new(); + FIXTURE + .get_or_init(|| { + let root = std::env::var_os("HORIZON_RESOURCES") + .map(PathBuf::from) + .unwrap_or_else(|| { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3") + }); + if !root.join("block-behaviours.json").exists() { + eprintln!("skipping level tests: no resources at {}", root.display()); + return None; + } + let registry = data::load_registry(&root).expect("registry"); + let behaviours = Behaviours::load(®istry, &root).expect("behaviours"); + Some(Fixture { + registry, + behaviours, + }) + }) + .as_ref() +} + +pub(crate) struct TestLevel { + blocks: HashMap, + air: BlockStateId, + random: LegacyRandom, + pub time: i64, + pub events: Vec, + pub block_light: HashMap, +} +impl TestLevel { + fn new(b: &Behaviours) -> Self { + Self { + blocks: HashMap::new(), + air: b.air(), + random: LegacyRandom::new(42), + time: 0, + events: Vec::new(), + block_light: HashMap::new(), + } + } +} +impl LevelAccess for TestLevel { + fn block_state(&self, pos: BlockPos) -> BlockStateId { + self.blocks.get(&pos).copied().unwrap_or(self.air) + } + fn set_raw(&mut self, pos: BlockPos, state: BlockStateId) -> Option { + Some(self.blocks.insert(pos, state).unwrap_or(self.air)) + } + fn is_loaded(&self, _pos: BlockPos) -> bool { + true + } + fn random(&mut self) -> &mut LegacyRandom { + &mut self.random + } + fn game_time(&self) -> i64 { + self.time + } + fn block_light(&self, pos: BlockPos) -> i32 { + self.block_light.get(&pos).copied().unwrap_or(0) + } + fn emit(&mut self, event: LevelEvent) { + self.events.push(event); + } +} + +struct World<'f> { + f: &'f Fixture, + level: TestLevel, + ticks: Ticks, +} +impl<'f> World<'f> { + fn new(f: &'f Fixture) -> Self { + let mut ticks = Ticks::new(0); + for x in -4..4 { + for z in -4..4 { + ticks.add_empty_chunk(ChunkPos::new(x, z)).unwrap(); + } + } + Self { + level: TestLevel::new(&f.behaviours), + f, + ticks, + } + } + fn b(&self) -> &'f Behaviours { + &self.f.behaviours + } + fn id(&self, name: &str, props: &[(&str, &str)]) -> BlockStateId { + let state = BlockState { + name: format!("minecraft:{name}"), + properties: props + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect::>(), + }; + self.f + .registry + .resolve(&state) + .unwrap_or_else(|_| panic!("unknown state {name} {props:?}")) + } + fn set(&mut self, pos: BlockPos, state: BlockStateId) -> bool { + self.f.behaviours.set_block( + &mut self.level, + &mut self.ticks, + pos, + state, + flags::UPDATE_ALL, + ) + } + /// Raw storage write without updates (world generation). + fn put(&mut self, pos: BlockPos, state: BlockStateId) { + self.level.blocks.insert(pos, state); + } + fn get(&self, pos: BlockPos) -> BlockStateId { + self.level.block_state(pos) + } + fn name(&self, pos: BlockPos) -> String { + let state = self.f.registry.state(self.get(pos)).unwrap(); + let props: Vec = state + .properties + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect(); + format!( + "{}[{}]", + state.name.trim_start_matches("minecraft:"), + props.join(",") + ) + } + fn prop(&self, pos: BlockPos, key: &str) -> String { + self.f + .registry + .state(self.get(pos)) + .unwrap() + .properties + .get(key) + .cloned() + .unwrap_or_default() + } + fn tick(&mut self) { + self.level.time += 1; + self.f + .behaviours + .tick_scheduled(&mut self.level, &mut self.ticks); + } + /// 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); + } + fn floor(&mut self, y: i32, radius: i32, block: &str) { + let state = self.id(block, &[]); + for x in -radius..=radius { + for z in -radius..=radius { + self.put(BlockPos::new(x, y, z), state); + } + } + } +} + +macro_rules! world { + () => {{ + let Some(f) = fixture() else { + return; + }; + World::new(f) + }}; +} + +#[test] +fn state_table_matches_registry() { + let Some(f) = fixture() else { + return; + }; + let t = &f.behaviours.table; + assert_eq!(t.state_count(), f.registry.len()); + let stairs = f.registry.default_state("minecraft:oak_stairs").unwrap(); + let key = f.behaviours.props.facing; + let east = t.with_text(stairs, key, "east").unwrap(); + assert_eq!(f.registry.state(east).unwrap().properties["facing"], "east"); + assert_eq!(t.text(east, f.behaviours.props.half), "bottom"); + assert!(classes::Class::ALL.len() <= 320); +} + +#[test] +fn fences_connect_and_disconnect() { + let mut w = world!(); + let fence = w.id("oak_fence", &[]); + let a = BlockPos::new(0, 1, 0); + let c = BlockPos::new(1, 1, 0); + w.set(a, fence); + w.set(c, fence); + assert_eq!(w.prop(a, "east"), "true"); + assert_eq!(w.prop(c, "west"), "true"); + let stone = w.id("stone", &[]); + w.set(BlockPos::new(0, 1, -1), stone); + assert_eq!(w.prop(a, "north"), "true", "fences connect to sturdy faces"); + let air = w.b().air(); + w.set(c, air); + assert_eq!(w.prop(a, "east"), "false"); +} + +#[test] +fn walls_and_panes_connect() { + let mut w = world!(); + let wall = w.id("cobblestone_wall", &[]); + let pane = w.id("glass_pane", &[]); + w.set(BlockPos::new(0, 1, 0), wall); + w.set(BlockPos::new(0, 1, 1), wall); + w.set(BlockPos::new(0, 1, 2), wall); + assert_eq!(w.prop(BlockPos::new(0, 1, 1), "north"), "low"); + assert_eq!(w.prop(BlockPos::new(0, 1, 1), "south"), "low"); + assert_eq!( + w.prop(BlockPos::new(0, 1, 1), "up"), + "false", + "straight wall drops its post" + ); + let stone = w.id("stone", &[]); + w.set(BlockPos::new(0, 2, 1), stone); + assert_eq!(w.prop(BlockPos::new(0, 1, 1), "north"), "tall"); + w.set(BlockPos::new(5, 1, 0), pane); + w.set(BlockPos::new(6, 1, 0), pane); + assert_eq!(w.prop(BlockPos::new(5, 1, 0), "east"), "true"); +} + +#[test] +fn stairs_form_corners() { + let mut w = world!(); + let north = w.id("oak_stairs", &[("facing", "north")]); + let east = w.id("oak_stairs", &[("facing", "east")]); + w.set(BlockPos::new(0, 1, 0), north); + w.set(BlockPos::new(0, 1, -1), east); + // The north-facing stair has an east-facing stair behind it. + assert_eq!(w.prop(BlockPos::new(0, 1, 0), "shape"), "outer_right"); +} + +#[test] +fn torch_and_door_halves_break_with_support() { + let mut w = world!(); + w.floor(0, 3, "stone"); + let torch = w.id("torch", &[]); + w.set(BlockPos::new(1, 1, 1), torch); + let door = w.id("oak_door", &[("half", "lower")]); + let upper = w.id("oak_door", &[("half", "upper")]); + w.set(BlockPos::new(0, 1, 0), door); + w.set(BlockPos::new(0, 2, 0), upper); + let air = w.b().air(); + w.set(BlockPos::new(1, 0, 1), air); + assert_eq!( + w.get(BlockPos::new(1, 1, 1)), + air, + "torch pops without support" + ); + assert!( + w.level + .events + .iter() + .any(|e| matches!(e, LevelEvent::DropResources { .. })) + ); + w.set(BlockPos::new(0, 1, 0), air); + assert_eq!( + w.get(BlockPos::new(0, 2, 0)), + air, + "upper door half goes with the lower" + ); +} + +#[test] +fn snowy_grass_and_chests_pair() { + let mut w = world!(); + let grass = w.id("grass_block", &[]); + w.set(BlockPos::new(0, 0, 0), grass); + let snow = w.id("snow", &[]); + w.set(BlockPos::new(0, 1, 0), snow); + assert_eq!(w.prop(BlockPos::new(0, 0, 0), "snowy"), "true"); + // A left chest's partner sits clockwise of its facing; removing the + // partner makes it single again. + let left = w.id("chest", &[("facing", "north"), ("type", "left")]); + let right = w.id("chest", &[("facing", "north"), ("type", "right")]); + w.set(BlockPos::new(3, 1, 0), left); + w.set(BlockPos::new(4, 1, 0), right); + let air = w.b().air(); + w.set(BlockPos::new(4, 1, 0), air); + assert_eq!(w.prop(BlockPos::new(3, 1, 0), "type"), "single"); +} + +#[test] +fn sand_falls_and_concrete_solidifies() { + let mut w = world!(); + let sand = w.id("sand", &[]); + w.set(BlockPos::new(0, 5, 0), sand); + w.tick(); + w.tick(); + assert_eq!(w.get(BlockPos::new(0, 5, 0)), w.b().air()); + assert!( + w.level + .events + .iter() + .any(|e| matches!(e, LevelEvent::FallingBlock { state, .. } if *state == sand)) + ); + w.floor(0, 2, "stone"); + let water = w.id("water", &[]); + w.put(BlockPos::new(1, 1, 0), water); + let powder = w.id("white_concrete_powder", &[]); + let landing = w.b().falling_block_landed( + &mut w.level, + &mut w.ticks, + BlockPos::new(0, 1, 0), + powder, + false, + ); + assert_eq!( + landing, + falling::Landing::Placed(w.id("white_concrete", &[])) + ); +} + +#[test] +fn water_spreads_on_a_floor() { + let mut w = world!(); + w.floor(0, 10, "stone"); + let water = w.id("water", &[]); + w.set(BlockPos::new(0, 1, 0), water); + for _ in 0..60 { + w.tick(); + } + for d in 1..=7 { + let pos = BlockPos::new(d, 1, 0); + assert_eq!( + w.prop(pos, "level"), + d.to_string(), + "flow at distance {d}: {}", + w.name(pos) + ); + } + assert_eq!(w.get(BlockPos::new(8, 1, 0)), w.b().air()); + // Diagonals follow Manhattan distance. + assert_eq!(w.prop(BlockPos::new(2, 1, 2), "level"), "4"); +} + +#[test] +fn water_falls_and_makes_sources() { + let mut w = world!(); + w.floor(0, 4, "stone"); + let water = w.id("water", &[]); + w.set(BlockPos::new(0, 4, 0), water); + for _ in 0..30 { + w.tick(); + } + assert_eq!( + w.prop(BlockPos::new(0, 3, 0), "level"), + "8", + "falling water" + ); + assert_eq!(w.prop(BlockPos::new(0, 1, 0), "level"), "8"); + // Two sources make a third (no holes within slope distance, so the + // sources spread in every direction). + let mut w = world!(); + w.floor(0, 12, "stone"); + w.set(BlockPos::new(0, 1, 0), water); + w.set(BlockPos::new(2, 1, 0), water); + for _ in 0..20 { + w.tick(); + } + assert_eq!(w.get(BlockPos::new(1, 1, 0)), water); + // On a small platform the water instead seeks the nearest edges. + let mut w = world!(); + w.floor(0, 4, "stone"); + w.set(BlockPos::new(0, 1, 0), water); + w.set(BlockPos::new(2, 1, 0), water); + for _ in 0..20 { + w.tick(); + } + assert_eq!(w.get(BlockPos::new(1, 1, 0)), w.b().air()); + assert_eq!(w.prop(BlockPos::new(-1, 1, 0), "level"), "1"); +} + +#[test] +fn lava_meets_water() { + let mut w = world!(); + w.floor(0, 4, "stone"); + let lava = w.id("lava", &[]); + let water = w.id("water", &[]); + w.set(BlockPos::new(0, 1, 0), lava); + w.set(BlockPos::new(1, 1, 0), water); + assert_eq!(w.get(BlockPos::new(0, 1, 0)), w.id("obsidian", &[])); + let mut w = world!(); + w.floor(0, 4, "stone"); + w.set(BlockPos::new(0, 1, 0), lava); + for _ in 0..40 { + w.tick(); + } + w.set(BlockPos::new(1, 2, 0), water); + for _ in 0..40 { + w.tick(); + } + assert_eq!( + w.get(BlockPos::new(1, 1, 0)), + w.id("cobblestone", &[]), + "{}", + w.name(BlockPos::new(1, 1, 0)) + ); +} + +#[test] +fn waterlogged_blocks_schedule_water() { + let mut w = world!(); + w.floor(0, 4, "stone"); + let slab = w.id("oak_slab", &[("waterlogged", "true")]); + w.set(BlockPos::new(0, 1, 0), slab); + // A neighbour shape update schedules the slab's water tick. + let stone = w.id("stone", &[]); + w.set(BlockPos::new(0, 1, 1), stone); + for _ in 0..20 { + w.tick(); + } + assert_eq!(w.prop(BlockPos::new(1, 1, 0), "level"), "1"); +} + +#[test] +fn redstone_lever_wire_and_lamp() { + let mut w = world!(); + w.floor(0, 20, "stone"); + let wire = w.id("redstone_wire", &[]); + let lamp = w.id("redstone_lamp", &[]); + let lever = w.id("lever", &[("face", "floor"), ("facing", "north")]); + for x in 1..=5 { + w.set(BlockPos::new(x, 1, 0), wire); + } + w.set(BlockPos::new(6, 1, 0), lamp); + w.set(BlockPos::new(0, 1, 0), lever); + let lever_on = w + .b() + .table + .set_bool(w.get(BlockPos::new(0, 1, 0)), w.b().props.powered, true); + w.set(BlockPos::new(0, 1, 0), lever_on); + assert_eq!(w.prop(BlockPos::new(1, 1, 0), "power"), "15"); + assert_eq!(w.prop(BlockPos::new(5, 1, 0), "power"), "11"); + assert_eq!(w.prop(BlockPos::new(6, 1, 0), "lit"), "true"); + let lever_off = w.b().table.set_bool(lever_on, w.b().props.powered, false); + w.set(BlockPos::new(0, 1, 0), lever_off); + assert_eq!(w.prop(BlockPos::new(3, 1, 0), "power"), "0"); + for _ in 0..5 { + w.tick(); + } + assert_eq!(w.prop(BlockPos::new(6, 1, 0), "lit"), "false"); +} + +#[test] +fn repeater_delays_and_torch_inverts() { + let mut w = world!(); + w.floor(0, 10, "stone"); + let block = w.id("redstone_block", &[]); + // A repeater takes its input from the side it faces. + let repeater = w.id("repeater", &[("facing", "west")]); + w.set(BlockPos::new(1, 1, 0), repeater); + w.set(BlockPos::new(0, 1, 0), block); + assert_eq!(w.prop(BlockPos::new(1, 1, 0), "powered"), "false"); + w.tick(); + w.tick(); + assert_eq!(w.prop(BlockPos::new(1, 1, 0), "powered"), "true"); + let torch = w.id("redstone_torch", &[]); + let stone = w.id("stone", &[]); + w.set(BlockPos::new(5, 1, 0), stone); + w.set(BlockPos::new(5, 2, 0), torch); + // A redstone block only weakly powers the stone: the torch stays lit. + w.set(BlockPos::new(6, 1, 0), block); + w.tick(); + w.tick(); + assert_eq!(w.prop(BlockPos::new(5, 2, 0), "lit"), "true"); + // A lever on the stone strongly powers it. + let air = w.b().air(); + w.set(BlockPos::new(6, 1, 0), air); + let lever = w.id( + "lever", + &[("face", "wall"), ("facing", "east"), ("powered", "true")], + ); + w.set(BlockPos::new(6, 1, 0), lever); + // LeverBlock.pull notifies the attached block's neighbours. + let lever_block = w.b().block(lever); + w.b().update_neighbors_at( + &mut w.level, + &mut w.ticks, + BlockPos::new(5, 1, 0), + lever_block, + ); + w.tick(); + w.tick(); + assert_eq!(w.prop(BlockPos::new(5, 2, 0), "lit"), "false"); +} + +#[test] +fn crops_grow_and_leaves_decay() { + let mut w = world!(); + let farmland = w.id("farmland", &[("moisture", "7")]); + let wheat = w.id("wheat", &[]); + w.put(BlockPos::new(0, 0, 0), farmland); + w.put(BlockPos::new(0, 1, 0), wheat); + for _ in 0..400 { + w.b() + .random_tick(&mut w.level, &mut w.ticks, BlockPos::new(0, 1, 0)); + } + assert_eq!(w.prop(BlockPos::new(0, 1, 0), "age"), "7"); + let leaves = w.id("oak_leaves", &[("distance", "7")]); + w.put(BlockPos::new(5, 5, 5), leaves); + w.b() + .random_tick(&mut w.level, &mut w.ticks, BlockPos::new(5, 5, 5)); + assert_eq!(w.get(BlockPos::new(5, 5, 5)), w.b().air()); + let log = w.id("oak_log", &[]); + let leaf = w.id("oak_leaves", &[]); + w.set(BlockPos::new(9, 5, 5), leaf); + w.set(BlockPos::new(8, 5, 5), log); + w.tick(); + assert_eq!(w.prop(BlockPos::new(9, 5, 5), "distance"), "1"); +} + +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 { + let [nx, ny, nz] = face.normal(); + let hit = horizon_core::geometry::Vec3::new( + f64::from(clicked.x) + 0.5 + f64::from(nx) * 0.5, + f64::from(clicked.y) + 0.5 + f64::from(ny) * 0.5 + dy, + f64::from(clicked.z) + 0.5 + f64::from(nz) * 0.5, + ); + let ctx = PlaceContext { + clicked_pos: clicked, + face, + hit, + inside: false, + yaw, + 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) + } + fn use_block(&mut self, pos: BlockPos) -> InteractionResult { + let player = PlayerContext { + yaw: 0.0, + pitch: 0.0, + may_build: true, + 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, + ) + } +} + +#[test] +fn placement_orients_blocks() { + let mut w = world!(); + w.floor(0, 6, "stone"); + 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.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, + ); + 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, + ); + 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, + ); + assert_eq!(w.prop(BlockPos::new(-3, 1, 0), "facing"), "south"); +} + +#[test] +fn placement_merges_slabs_and_stacks() { + let mut w = world!(); + w.floor(0, 4, "stone"); + 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, + ); + 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, + ); + 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, + ); + 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, + ); + assert_eq!(w.prop(BlockPos::new(-3, 1, 0), "candles"), "2"); +} + +#[test] +fn doors_beds_and_plants_place_both_halves() { + let mut w = world!(); + w.floor(0, 6, "grass_block"); + let ground = BlockPos::new(0, 0, 0); + 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.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(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, + ); + 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, + ); + 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 + ); +} + +#[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, + ); + for x in 1..=3 { + 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.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.use_block(BlockPos::new(5, 1, 0)); + assert_eq!(w.prop(BlockPos::new(5, 1, 0), "powered"), "true"); + for _ in 0..20 { + w.tick(); + } + assert_eq!(w.prop(BlockPos::new(5, 1, 0), "powered"), "false"); +} + +#[test] +fn pistons_push_and_sticky_pistons_pull() { + let mut w = world!(); + w.floor(0, 10, "stone"); + let piston = w.id("sticky_piston", &[("facing", "east")]); + let block = w.id("redstone_block", &[]); + let dirt = w.id("dirt", &[]); + let air = w.b().air(); + w.set(BlockPos::new(0, 1, 0), piston); + w.set(BlockPos::new(1, 1, 0), dirt); + w.set(BlockPos::new(-1, 1, 0), block); + for _ in 0..4 { + 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.get(BlockPos::new(2, 1, 0)), dirt); + assert!(w.ticks.moving_pistons.is_empty()); + w.set(BlockPos::new(-1, 1, 0), air); + for _ in 0..4 { + 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(2, 1, 0)), air); +} + +#[test] +fn pistons_pop_fragile_blocks_and_refuse_obsidian() { + let mut w = world!(); + w.floor(0, 10, "stone"); + let piston = w.id("piston", &[("facing", "east")]); + let block = w.id("redstone_block", &[]); + let torch = w.id("torch", &[]); + let obsidian = w.id("obsidian", &[]); + w.set(BlockPos::new(0, 1, 0), piston); + w.set(BlockPos::new(1, 1, 0), torch); + w.set(BlockPos::new(-1, 1, 0), block); + 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)) + ); + let mut w = world!(); + w.floor(0, 10, "stone"); + w.set(BlockPos::new(0, 1, 0), piston); + w.set(BlockPos::new(1, 1, 0), obsidian); + w.set(BlockPos::new(-1, 1, 0), block); + for _ in 0..4 { + w.full_tick(); + } + assert_eq!(w.prop(BlockPos::new(0, 1, 0), "extended"), "false"); + assert_eq!(w.get(BlockPos::new(1, 1, 0)), obsidian); +} + +#[test] +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 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)); + } + for _ in 0..80 { + w.tick(); + } + assert_eq!(w.name(BlockPos::new(0, 5, 0)), "water_cauldron[level=1]"); +} diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs new file mode 100644 index 000000000..555ba2a85 --- /dev/null +++ b/crates/horizon-world/src/level/tick.rs @@ -0,0 +1,1571 @@ +//! Scheduled block ticks (`BlockBehaviour.tick`), random ticks +//! (`BlockBehaviour.randomTick`) and the per-tick drivers. +use super::{ + Behaviours, LevelAccess, LevelEvent, Sim, Ticks, + classes::Class, + data::state_flags, + update::{HORIZONTAL, above, below, rel}, +}; +use crate::{fluid::FluidKind, registry::BlockStateId}; +use horizon_core::{ + geometry::Direction, + position::{BlockPos, ChunkPos}, + random::RandomSource, + ticks::TickTypeId, +}; + +impl Sim<'_, L> { + fn rand_int(&mut self, bound: i32) -> i32 { + self.random().next_int_bound(bound).unwrap_or(0) + } + + /// `BlockState.tick` (scheduled block tick). + pub fn tick_block(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let p = b.props; + let block = b.block(state); + let chain = &b.data(state).chain; + for &class in chain.iter() { + match class { + Class::BambooStalk + | Class::BigDripleafStem + | Class::Cactus + | Class::ChorusFlower + | Class::ChorusPlant + | Class::GrowingPlant + | Class::SugarCane => { + if !self.can_survive(state, pos) { + self.destroy_block(pos, true, 512); + } + } + Class::HangingMoss => { + let above_state = self.above_state(pos); + if !(b.multiface_can_attach(above_state, Direction::Up) + || b.is_block(above_state, block)) + { + self.destroy_block(pos, true, 512); + } + } + Class::BasePressurePlate => { + let signal = self.plate_signal_for_state(state); + if signal > 0 { + self.plate_check_pressed(pos, state, signal); + } + } + Class::BigDripleaf => self.big_dripleaf_tick(pos, state), + Class::AbstractCauldron => self.cauldron_tick(state, pos), + Class::BubbleColumn => { + let below_state = self.below_state(pos); + self.bubble_column_update(pos, state, below_state); + } + Class::Button => self.button_tick(pos, state), + Class::Diode => self.diode_tick(pos, state), + Class::Composter => { + if b.table.int(state, p.level) == 7 { + self.set_block_and_update(pos, b.table.cycle(state, p.level)); + self.emit(LevelEvent::Sound { + pos, + sound: "minecraft:block.composter.ready".into(), + volume: 1.0, + pitch: 1.0, + }); + } + } + Class::Coral => { + if !self.coral_scan_for_water(pos) { + if let Some(dead) = b.data(state).link { + self.set_block(pos, b.default_of(dead), 2); + } + } + } + Class::CoralFan | Class::CoralPlant | Class::CoralWallFan => { + if !self.coral_plant_scan_for_water(state, pos) { + if let Some(dead) = b.data(state).link { + let mut next = + b.table.set_bool(b.default_of(dead), p.waterlogged, false); + if class == Class::CoralWallFan { + next = b.table.set_dir(next, p.facing, b.facing(state)); + } + self.set_block(pos, next, 2); + } + } + } + Class::Dispenser | Class::Crafter => { + self.emit(LevelEvent::BlockEvent { + pos, + state, + kind: "dispense", + }); + } + Class::FallingBlock => self.falling_block_tick(pos, state), + Class::Brushable => { + if self.is_free(self.below_state(pos)) && pos.y >= self.level.min_y() { + self.falling_block_fall(pos, state); + } + } + Class::Farmland => { + if !self.can_survive(state, pos) { + self.turn_to_base_block(pos, state); + } + } + Class::Path => self.turn_to_base_block(pos, state), + Class::Fire => self.fire_tick(pos, state), + Class::Frogspawn => { + if !self.can_survive(state, pos) { + self.destroy_block(pos, false, 512); + } else { + self.emit(LevelEvent::BlockEvent { + pos, + state, + kind: "hatch", + }); + self.destroy_block(pos, false, 512); + } + } + Class::FrostedIce => self.frosted_ice_tick(pos, state), + Class::Leaves => { + let next = self.leaves_update_distance(state, pos); + self.set_block_and_update(pos, next); + } + Class::LightningRod => { + self.set_block_and_update(pos, b.table.set_bool(state, p.powered, false)); + let facing = b.facing(state); + self.update_neighbors_at(rel(pos, facing.opposite()), block); + } + Class::Liquid => { + if self.should_bubble_column_occupy(state) { + let below_state = self.below_state(pos); + let column = b.named.bubble_column; + self.bubble_column_update_for(column, pos, state, below_state); + } + } + Class::Observer => self.observer_tick(pos, state), + Class::RedstoneLamp => self.lamp_tick(pos, state), + Class::RedstoneTorch => self.torch_tick(pos, state), + Class::Scaffolding => self.scaffolding_tick(pos, state), + Class::Speleothem => { + let tip = b.table.dir(state, p.vertical_direction); + if tip == Some(Direction::Up) && !self.can_survive(state, pos) { + self.destroy_block(pos, true, 512); + } else { + self.spawn_falling_stalactite(pos, state); + } + } + Class::Target => { + if b.table.int(state, p.power) != 0 { + self.set_block_and_update(pos, b.table.set_int(state, p.power, 0)); + } + } + Class::TripWire => self.tripwire_tick(pos), + Class::TripWireHook => { + self.tripwire_hook_calculate(pos, state, false, true, -1, None) + } + _ => continue, + } + return; + } + } + + /// `BlockState.randomTick` followed by the fluid's random tick. + pub fn random_tick_at(&mut self, pos: BlockPos) { + let state = self.state(pos); + if self.b.is_randomly_ticking(state) { + self.random_tick_block(state, pos); + } + // Only lava's fluid state ticks randomly. A lava block is ticked twice + // (LiquidBlock.randomTick, then FluidState.randomTick), as in vanilla. + let fluid = self.b.fluid(state).kind(); + if matches!(fluid, FluidKind::Lava | FluidKind::FlowingLava) { + self.lava_random_tick(pos); + } + } + + pub fn random_tick_block(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let p = b.props; + let block = b.block(state); + let data = b.data(state); + let chain = &data.chain; + for class in chain.iter().copied() { + match class { + Class::BambooSapling => { + if self.rand_int(3) == 0 + && self.is_empty_block(above(pos)) + && self.raw_brightness(above(pos), 0) >= 9 + { + self.bamboo_sapling_grow(pos); + } + } + Class::BambooStalk => { + if b.table.int(state, p.stage) == 0 + && self.rand_int(3) == 0 + && self.is_empty_block(above(pos)) + && self.raw_brightness(above(pos), 0) >= 9 + { + let height = self.bamboo_height_below(pos) + 1; + if height < 16 { + self.bamboo_grow(state, pos, height); + } + } + } + Class::Beetroot | Class::TorchflowerCrop => { + if self.rand_int(3) != 0 { + self.crop_random_tick(state, pos); + } + } + Class::Crop => self.crop_random_tick(state, pos), + Class::BuddingAmethyst => self.budding_amethyst_tick(pos), + Class::Cactus => self.cactus_random_tick(state, pos), + Class::ChorusFlower => self.chorus_flower_random_tick(state, pos), + Class::Cocoa => { + if self.rand_int(5) == 0 { + let age = b.table.int(state, p.age); + if age < 2 { + self.set_block(pos, b.table.set_int(state, p.age, age + 1), 2); + } + } + } + Class::Farmland => self.farmland_random_tick(state, pos), + Class::GrowingPlantHead => { + if b.table.int(state, p.age) < 25 + && self.random().next_double() < data.grow_probability + { + let growth = rel(pos, data.growth_direction); + if self.growing_plant_can_grow_into(state, self.state(growth)) { + let next = self.growing_plant_grow_into_state(state); + self.set_block_and_update(growth, next); + } + } + } + Class::Ice => { + if self.level.block_light(pos) > 11 - i32::from(b.facts(state).dampening) { + self.ice_melt(pos); + } + } + Class::Leaves => { + if !b.table.bool(state, p.persistent) && b.table.int(state, p.distance) == 7 { + self.drop_resources(state, pos); + self.remove_block(pos, false); + } + } + Class::Liquid => { + if matches!( + b.fluid(state).kind(), + FluidKind::Lava | FluidKind::FlowingLava + ) { + self.lava_random_tick(pos); + } + } + Class::MangrovePropagule => { + if !b.table.bool(state, p.hanging) { + if self.rand_int(7) == 0 { + self.sapling_advance_tree(pos, state); + } + } else if b.table.int(state, p.age) != 4 { + self.set_block(pos, b.table.cycle(state, p.age), 2); + } + } + Class::Sapling => { + if self.max_local_raw_brightness(above(pos)) >= 9 && self.rand_int(7) == 0 { + self.sapling_advance_tree(pos, state); + } + } + Class::Mushroom => self.mushroom_random_tick(state, pos), + Class::NetherWart => { + let age = b.table.int(state, p.age); + if age < 3 && self.rand_int(10) == 0 { + self.set_block(pos, b.table.set_int(state, p.age, age + 1), 2); + } + } + Class::Nylium => { + if !self.can_be_nylium(state, pos) { + self.set_block_and_update(pos, b.default_of(b.named.netherrack)); + } + } + Class::PitcherCrop => { + let speed = self.crop_growth_speed(block, pos); + if self.rand_int((25.0 / speed) as i32 + 1) == 0 { + self.pitcher_grow(state, pos, 1); + } + } + Class::Speleothem => self.speleothem_random_tick(state, pos), + Class::RedStoneOre => { + if b.table.bool(state, p.lit) { + self.set_block_and_update(pos, b.table.set_bool(state, p.lit, false)); + } + } + Class::SnowLayer => { + if self.level.block_light(pos) > 11 { + self.drop_resources(state, pos); + self.remove_block(pos, false); + self.game_event(pos, "minecraft:block_destroy"); + } + } + Class::SpreadingSnowy => self.spreading_snowy_tick(state, pos), + Class::Stem => self.stem_random_tick(state, pos), + Class::SugarCane => { + if self.is_empty_block(above(pos)) { + let mut height = 1; + while b.is_block(self.state(pos.offset(0, -height, 0)), block) { + height += 1; + } + if height < 3 { + let age = b.table.int(state, p.age); + if age == 15 { + self.set_block_and_update(above(pos), b.default_of(block)); + self.set_block(pos, b.table.set_int(state, p.age, 0), 260); + } else { + self.set_block(pos, b.table.set_int(state, p.age, age + 1), 260); + } + } + } + } + Class::SweetBerryBush => { + let age = b.table.int(state, p.age); + if age < 3 && self.rand_int(5) == 0 && self.raw_brightness(above(pos), 0) >= 9 { + let next = b.table.set_int(state, p.age, age + 1); + self.set_block(pos, next, 2); + self.game_event(pos, "minecraft:block_change"); + } + } + Class::Vine => self.vine_random_tick(state, pos), + Class::WeatheringCopperFull => self.copper_change_over_time(state, pos), + _ => continue, + } + return; + } + if data.implements(super::classes::Interface::WeatheringCopper) { + let upper_door = data.is(Class::Door) && b.table.text(state, p.half) == "upper"; + let right_chest = data.is(Class::Chest) && b.table.text(state, p.kind) == "right"; + if !upper_door && !right_chest { + self.copper_change_over_time(state, pos); + } + } + } + + // ---- helpers ---- + + pub(crate) fn turn_to_base_block(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let base = b.data(state).link.unwrap_or(b.named.dirt); + self.set_block_and_update(pos, b.default_of(base)); + self.game_event(pos, "minecraft:block_change"); + } + /// `FallingBlock.isFree`. + pub(crate) fn is_free(&self, state: BlockStateId) -> bool { + let b = self.b; + b.is_air(state) + || b.tag("minecraft:fire") + .is_some_and(|tag| b.in_set(state, tag)) + || b.liquid(state) + || b.is_replaceable(state) + } + fn leaves_update_distance(&self, state: BlockStateId, pos: BlockPos) -> BlockStateId { + let mut distance = 7; + for direction in Direction::ALL { + distance = distance.min(self.leaf_distance_at(self.rel_state(pos, direction)) + 1); + if distance == 1 { + break; + } + } + self.b.table.set_int(state, self.b.props.distance, distance) + } + fn bubble_column_update( + &mut self, + pos: BlockPos, + state: BlockStateId, + below_state: BlockStateId, + ) { + let column = self.b.block(state); + self.bubble_column_update_for(column, pos, state, below_state); + } + /// `BubbleColumnBlock.updateColumn(column, level, pos, occupyState, belowState)`. + pub(crate) fn bubble_column_update_for( + &mut self, + column: super::states::BlockId, + pos: BlockPos, + occupy: BlockStateId, + below_state: BlockStateId, + ) { + let b = self.b; + if !self.bubble_column_can_occupy(occupy) { + return; + } + let column_state = if b.is_block(below_state, column) { + below_state + } else if b.in_set(below_state, &b.tags.enables_bubble_column_push_up) { + b.table.set_bool(b.default_of(column), b.props.drag, false) + } else if b.in_set(below_state, &b.tags.enables_bubble_column_drag_down) { + b.table.set_bool(b.default_of(column), b.props.drag, true) + } else if b.is_block(occupy, column) { + b.default_of(b.named.water) + } else { + occupy + }; + self.set_block(pos, column_state, 2); + let mut up = above(pos); + while self.bubble_column_can_occupy(self.state(up)) { + if !self.set_block(up, column_state, 2) { + return; + } + up = above(up); + } + } + fn big_dripleaf_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + if self.has_neighbor_signal(pos) { + let next = b.table.set_text(state, b.props.tilt, "none"); + self.set_block(pos, next, 2); + if b.table.text(state, b.props.tilt) != "none" { + let pitch = self.random().next_float() * 0.4 + 0.8; + self.emit(LevelEvent::Sound { + pos, + sound: "minecraft:block.big_dripleaf.tilt_up".into(), + volume: 1.0, + pitch, + }); + } + return; + } + let (next, delay) = match b.table.text(state, b.props.tilt) { + "unstable" => ("partial", Some(10)), + "partial" => ("full", Some(100)), + "full" => ("none", None), + _ => return, + }; + let next_state = b.table.set_text(state, b.props.tilt, next); + self.set_block(pos, next_state, 2); + if next != "none" { + self.game_event(pos, "minecraft:block_change"); + } + let pitch = self.random().next_float() * 0.4 + 0.8; + let sound = if next == "none" { + "minecraft:block.big_dripleaf.tilt_up" + } else { + "minecraft:block.big_dripleaf.tilt_down" + }; + self.emit(LevelEvent::Sound { + pos, + sound: sound.into(), + volume: 1.0, + pitch, + }); + if let Some(delay) = delay { + self.schedule_tick(pos, b.block(state), delay); + } + } + fn scaffolding_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let distance = self.scaffolding_distance(pos); + let bottom = self.scaffolding_is_bottom(pos, distance); + let next = b.table.set_bool( + b.table.set_int(state, b.props.distance, distance), + b.props.bottom, + bottom, + ); + if distance == 7 { + if b.table.int(state, b.props.distance) == 7 { + self.falling_block_fall(pos, next); + } else { + self.destroy_block(pos, true, 512); + } + } else if state != next { + self.set_block_and_update(pos, next); + } + } + /// `ScaffoldingBlock.isBottom`. + pub(crate) fn scaffolding_is_bottom(&self, pos: BlockPos, distance: i32) -> bool { + let b = self.b; + distance > 0 && !b.is_block(self.below_state(pos), b.named.scaffolding) + } + fn fire_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let p = b.props; + let block = b.block(state); + let delay = 30 + self.rand_int(10); + self.schedule_tick(pos, block, delay); + if !self.level.can_spread_fire_around(pos) { + return; + } + if !self.can_survive(state, pos) { + self.remove_block(pos, false); + } + let below_state = self.below_state(pos); + let infiniburn = match self.level.dimension() { + super::Dimension::Overworld => &b.tags.infiniburn_overworld, + super::Dimension::Nether => &b.tags.infiniburn_nether, + super::Dimension::End => &b.tags.infiniburn_end, + }; + let infini = b.in_set(below_state, infiniburn); + let age = b.table.int(state, p.age); + let raining = self.level.is_raining(); + if !infini + && raining + && self.fire_near_rain(pos) + && self.random().next_float() < 0.2 + age as f32 * 0.03 + { + self.remove_block(pos, false); + return; + } + let new_age = 15.min(age + self.rand_int(3) / 2); + let mut state = state; + if age != new_age { + state = b.table.set_int(state, p.age, new_age); + self.set_block(pos, state, 260); + } + if !infini { + if !self.is_valid_fire_location(pos) { + if !self.sturdy(below(pos), Direction::Up) || age > 3 { + self.remove_block(pos, false); + } + return; + } + if age == 15 && self.rand_int(4) == 0 && !self.can_burn(self.below_state(pos)) { + self.remove_block(pos, false); + return; + } + } + let burnout = self.level.dimension() == super::Dimension::Nether && false; + let extra = if burnout { -50 } else { 0 }; + for (direction, chance) in [ + (Direction::East, 300), + (Direction::West, 300), + (Direction::Down, 250), + (Direction::Up, 250), + (Direction::North, 300), + (Direction::South, 300), + ] { + self.fire_check_burn_out(rel(pos, direction), chance + extra, age); + } + for xx in -1..=1 { + for zz in -1..=1 { + for yy in -1..=4 { + if xx == 0 && yy == 0 && zz == 0 { + continue; + } + let mut rate = 100; + if yy > 1 { + rate += (yy - 1) * 100; + } + let test = pos.offset(xx, yy, zz); + let ignite = self.fire_ignite_odds_at(test); + if ignite > 0 { + let mut odds = (ignite + 40 + self.level.difficulty() * 7) / (age + 30); + if burnout { + odds /= 2; + } + if odds > 0 + && self.rand_int(rate) <= odds + && (!self.level.is_raining() || !self.fire_near_rain(test)) + { + let spread_age = 15.min(age + self.rand_int(5) / 4); + let next = self.fire_state_with_age(test, spread_age); + self.set_block_and_update(test, next); + } + } + } + } + } + } + /// `FireBlock.getIgniteOdds(level, pos)`: only for air with flammable neighbours. + fn fire_ignite_odds_at(&self, pos: BlockPos) -> i32 { + if !self.is_empty_block(pos) { + return 0; + } + Direction::ALL + .into_iter() + .map(|d| self.ignite_odds(self.rel_state(pos, d))) + .max() + .unwrap_or(0) + } + fn fire_near_rain(&self, pos: BlockPos) -> bool { + self.level.is_raining_at(pos) + || self.level.is_raining_at(rel(pos, Direction::West)) + || self.level.is_raining_at(rel(pos, Direction::East)) + || self.level.is_raining_at(rel(pos, Direction::North)) + || self.level.is_raining_at(rel(pos, Direction::South)) + } + fn fire_check_burn_out(&mut self, pos: BlockPos, chance: i32, age: i32) { + let b = self.b; + let odds = self.burn_odds(self.state(pos)); + if self.rand_int(chance) < odds { + let old = self.state(pos); + if self.rand_int(age + 10) < 5 && !self.level.is_raining_at(pos) { + let new_age = (age + self.rand_int(5) / 4).min(15); + let next = self.fire_state_with_age(pos, new_age); + self.set_block_and_update(pos, next); + } else { + self.remove_block(pos, false); + } + if b.instance_of(old, Class::Tnt) { + self.emit(LevelEvent::PrimeTnt { pos }); + } + } + } + fn frosted_ice_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let block = b.block(state); + let fewer = |sim: &Self, at: BlockPos, limit: i32| { + let mut count = 0; + for d in Direction::ALL { + if sim.b.is_block(sim.rel_state(at, d), block) { + count += 1; + if count >= limit { + return false; + } + } + } + true + }; + if self.rand_int(3) == 0 || fewer(self, pos, 4) { + let brightness = if self.level.dimension() == super::Dimension::End { + self.level.block_light(pos) + } else { + self.max_local_raw_brightness(pos) + }; + let age = b.table.int(state, b.props.age); + if brightness > 11 - age - i32::from(b.facts(state).dampening) + && self.frosted_slightly_melt(pos, state) + { + for direction in Direction::ALL { + let neighbour_pos = rel(pos, direction); + let neighbour = self.state(neighbour_pos); + if b.is_block(neighbour, block) + && !self.frosted_slightly_melt(neighbour_pos, neighbour) + { + let delay = self + .random() + .next_int_between_inclusive(20, 40) + .unwrap_or(20); + self.schedule_tick(neighbour_pos, block, delay); + } + } + return; + } + } + let delay = self + .random() + .next_int_between_inclusive(20, 40) + .unwrap_or(20); + self.schedule_tick(pos, block, delay); + } + fn frosted_slightly_melt(&mut self, pos: BlockPos, state: BlockStateId) -> bool { + let b = self.b; + let age = b.table.int(state, b.props.age); + if age < 3 { + self.set_block(pos, b.table.set_int(state, b.props.age, age + 1), 2); + false + } else { + self.ice_melt(pos); + true + } + } + + // ---- crops and plants ---- + + /// `CropBlock.getGrowthSpeed`. + pub(crate) fn crop_growth_speed(&self, block: super::states::BlockId, pos: BlockPos) -> f32 { + let b = self.b; + let mut speed = 1.0f32; + let under = below(pos); + for xx in -1..=1 { + for zz in -1..=1 { + let mut block_speed = 0.0f32; + let state = self.state(under.offset(xx, 0, zz)); + if b.in_set(state, &b.tags.grows_crops) { + block_speed = 1.0; + if b.table.int(state, b.props.moisture) > 0 { + block_speed = 3.0; + } + } + if xx != 0 || zz != 0 { + block_speed /= 4.0; + } + speed += block_speed; + } + } + let is = |at: BlockPos| b.is_block(self.state(at), block); + let (n, s, w, e) = ( + rel(pos, Direction::North), + rel(pos, Direction::South), + rel(pos, Direction::West), + rel(pos, Direction::East), + ); + let horizontal = is(w) || is(e); + let vertical = is(n) || is(s); + let diagonal = is(rel(w, Direction::North)) + || is(rel(e, Direction::North)) + || is(rel(e, Direction::South)) + || is(rel(w, Direction::South)); + if (horizontal && vertical) || diagonal { + speed /= 2.0; + } + speed + } + fn crop_random_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + if self.raw_brightness(pos, 0) < 9 { + return; + } + let age = b.table.int(state, b.props.age); + let max = b.table.int_range(state, b.props.age).map_or(7, |r| r.1); + if age < max { + let speed = self.crop_growth_speed(b.block(state), pos); + if self.rand_int((25.0 / speed) as i32 + 1) == 0 { + self.set_block(pos, b.table.set_int(state, b.props.age, age + 1), 2); + } + } + } + fn stem_random_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + if self.raw_brightness(pos, 0) < 9 { + return; + } + let speed = self.crop_growth_speed(b.block(state), pos); + if self.rand_int((25.0 / speed) as i32 + 1) != 0 { + return; + } + let age = b.table.int(state, b.props.age); + if age < 7 { + self.set_block(pos, b.table.set_int(state, b.props.age, age + 1), 2); + return; + } + let direction = HORIZONTAL[self.rand_int(4) as usize]; + let relative = rel(pos, direction); + let data = b.data(state); + let below_state = self.below_state(relative); + if b.is_air(self.state(relative)) + && data + .support_tag2 + .as_ref() + .is_some_and(|tag| b.in_set(below_state, tag)) + { + if let (Some(fruit), Some(stem)) = (data.link, data.link2) { + self.set_block_and_update(relative, b.default_of(fruit)); + self.set_block_and_update( + pos, + b.table + .set_dir(b.default_of(stem), b.props.facing, direction), + ); + } + } + } + /// `PitcherCropBlock.grow`. + pub(crate) fn pitcher_grow(&mut self, state: BlockStateId, pos: BlockPos, increase: i32) { + let b = self.b; + let p = b.props; + let (lower_pos, lower) = if b.table.text(state, p.half) == "upper" { + let below_pos = below(pos); + let below_state = self.state(below_pos); + if !b.is_block(below_state, b.named.pitcher_crop) + || b.table.text(below_state, p.half) != "lower" + { + return; + } + (below_pos, below_state) + } else { + (pos, state) + }; + let new_age = b.table.int(lower, p.age) + increase; + let can_grow = b.table.int(lower, p.age) < 4 + && self.raw_brightness(lower_pos, 0) >= 8 + && self.is_inside_build_height(lower_pos.y + 1) + && (new_age < 3 || { + let upper = self.state(above(lower_pos)); + b.is_air(upper) || b.is_block(upper, b.named.pitcher_crop) + }); + if !can_grow { + return; + } + let grown = b.table.set_int(lower, p.age, new_age); + self.set_block(lower_pos, grown, 2); + if new_age >= 3 { + let upper_pos = above(lower_pos); + let upper = b.table.set_text(grown, p.half, "upper"); + let upper = b + .table + .with_bool(upper, p.waterlogged, self.is_water_at(upper_pos)) + .unwrap_or(upper); + self.set_block(upper_pos, upper, 3); + } + } + fn growing_plant_can_grow_into(&self, plant: BlockStateId, state: BlockStateId) -> bool { + let b = self.b; + let data = b.data(plant); + if data.is(Class::Kelp) { + b.is_block(state, b.named.water) && b.fluid(state).amount() == 8 + } else { + // NetherVines.isValidGrowthState / CaveVines: air only. + b.is_air(state) + } + } + fn growing_plant_grow_into_state(&mut self, state: BlockStateId) -> BlockStateId { + let b = self.b; + let next = b.table.cycle(state, b.props.age); + if b.instance_of(state, Class::CaveVines) { + let berries = self.random().next_float() < 0.11; + return b.table.set_bool(next, b.props.berries, berries); + } + next + } + fn cactus_random_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let block = b.block(state); + let above_pos = above(pos); + if !self.is_empty_block(above_pos) { + return; + } + let mut height = 1; + let age = b.table.int(state, b.props.age); + while b.is_block(self.state(pos.offset(0, -height, 0)), block) { + height += 1; + if height == 3 && age == 15 { + return; + } + } + if age == 8 && self.can_survive(b.default_of(block), above_pos) { + let chance = if height >= 3 { 0.25 } else { 0.1 }; + if self.random().next_double() <= chance { + self.set_block_and_update(above_pos, b.default_of(b.named.cactus_flower)); + } + } else if age == 15 && height < 3 { + self.set_block_and_update(above_pos, b.default_of(block)); + let reset = b.table.set_int(state, b.props.age, 0); + self.set_block(pos, reset, 260); + self.neighbor_changed_full(reset, above_pos, block, false); + } + if age < 15 { + self.set_block(pos, b.table.set_int(state, b.props.age, age + 1), 260); + } + } + fn farmland_random_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let moisture = b.table.int(state, b.props.moisture); + let mut near_water = false; + 'search: for x in -4..=4 { + for y in 0..=1 { + for z in -4..=4 { + if b.is_water_fluid(self.fluid_at(pos.offset(x, y, z)).kind()) { + near_water = true; + break 'search; + } + } + } + } + if !near_water && !self.level.is_raining_at(above(pos)) { + if moisture > 0 { + self.set_block( + pos, + b.table.set_int(state, b.props.moisture, moisture - 1), + 2, + ); + } else if !b.in_set(self.above_state(pos), &b.tags.maintains_farmland) { + self.turn_to_base_block(pos, state); + } + } else if moisture < 7 { + self.set_block(pos, b.table.set_int(state, b.props.moisture, 7), 2); + } + } + /// `SaplingBlock.advanceTree`. + pub(crate) fn sapling_advance_tree(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + if b.table.int(state, b.props.stage) == 0 { + self.set_block(pos, b.table.cycle(state, b.props.stage), 260); + } else if let Some(grower) = b.data(state).feature.clone() { + self.emit(LevelEvent::GrowTree { pos, state, grower }); + } + } + fn mushroom_random_tick(&mut self, state: BlockStateId, mut pos: BlockPos) { + let b = self.b; + if self.rand_int(25) != 0 { + return; + } + // canSpread: at most four of this mushroom within a 9x3x9 box. + let block = b.block(state); + let mut max = 5; + for x in -4..=4 { + for y in -1..=1 { + for z in -4..=4 { + if b.is_block(self.state(pos.offset(x, y, z)), block) { + max -= 1; + if max <= 0 { + return; + } + } + } + } + } + let mut offset = self.mushroom_offset(pos); + for _ in 0..4 { + if self.is_empty_block(offset) && self.can_survive(state, offset) { + pos = offset; + } + offset = self.mushroom_offset(pos); + } + if self.is_empty_block(offset) && self.can_survive(state, offset) { + self.set_block(offset, state, 2); + } + } + fn mushroom_offset(&mut self, pos: BlockPos) -> BlockPos { + let x = self.rand_int(3) - 1; + let y = self.rand_int(2) - self.rand_int(2); + let z = self.rand_int(3) - 1; + pos.offset(x, y, z) + } + /// `LightEngine.getLightDampeningInto(state, above, UP, above.dampening) < 15`. + fn top_face_lets_light(&self, state: BlockStateId, above_state: BlockStateId) -> bool { + let b = self.b; + let occluding = |s: BlockStateId| { + b.has_flag(s, state_flags::CAN_OCCLUDE) + && b.has_flag(s, super::data::state_flags::SHAPE_OCCLUSION) + }; + let dampening = i32::from(b.facts(above_state).dampening); + let from_full = occluding(state) && b.collision_face_full(state, Direction::Up); + let to_full = occluding(above_state) && b.collision_face_full(above_state, Direction::Down); + let into = if !occluding(state) && !occluding(above_state) { + dampening + } else if from_full || to_full { + 16 + } else { + dampening + }; + into < 15 + } + fn can_be_nylium(&self, state: BlockStateId, pos: BlockPos) -> bool { + self.top_face_lets_light(state, self.above_state(pos)) + } + fn snowy_can_stay_alive(&self, state: BlockStateId, pos: BlockPos) -> bool { + let b = self.b; + let above_state = self.above_state(pos); + if b.is_block(above_state, b.named.snow) && b.table.int(above_state, b.props.layers) == 1 { + return true; + } + if b.fluid(above_state).is_full() { + return false; + } + self.top_face_lets_light(state, above_state) + } + fn spreading_snowy_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let base = b.data(state).link.unwrap_or(b.named.dirt); + if !self.snowy_can_stay_alive(state, pos) { + self.set_block_and_update(pos, b.default_of(base)); + return; + } + if self.max_local_raw_brightness(above(pos)) < 9 { + return; + } + let default = b.default_of(b.block(state)); + for _ in 0..4 { + let x = self.rand_int(3) - 1; + let y = self.rand_int(5) - 3; + let z = self.rand_int(3) - 1; + let test = pos.offset(x, y, z); + if b.is_block(self.state(test), base) + && self.snowy_can_stay_alive(default, test) + && !b.is_water_fluid(self.fluid_at(above(test)).kind()) + { + let snowy = b.in_set(self.above_state(test), &b.tags.snow); + self.set_block_and_update(test, b.table.set_bool(default, b.props.snowy, snowy)); + } + } + } + fn budding_amethyst_tick(&mut self, pos: BlockPos) { + let b = self.b; + if self.rand_int(5) != 0 { + return; + } + let direction = Direction::ALL[self.rand_int(6) as usize]; + let grow = rel(pos, direction); + let relative = self.state(grow); + let name = |n: &str| b.table.block_by_name(n); + let stages = [ + "minecraft:small_amethyst_bud", + "minecraft:medium_amethyst_bud", + "minecraft:large_amethyst_bud", + "minecraft:amethyst_cluster", + ]; + let fluid = b.fluid(relative); + let can_cluster_grow = + b.is_air(relative) || (b.is_block(relative, b.named.water) && fluid.amount() == 8); + let next = if can_cluster_grow { + name(stages[0]) + } else { + let mut found = None; + for i in 0..3 { + if name(stages[i]).is_some_and(|s| b.is_block(relative, s)) + && b.facing(relative) == direction + { + found = name(stages[i + 1]); + } + } + found + }; + if let Some(next) = next { + let state = b + .table + .set_dir(b.default_of(next), b.props.facing, direction); + let state = b.table.set_bool( + state, + b.props.waterlogged, + fluid == crate::fluid::FluidState::WATER, + ); + self.set_block_and_update(grow, state); + } + } + fn bamboo_sapling_grow(&mut self, pos: BlockPos) { + let b = self.b; + let bamboo = b.default_of(b.named.bamboo); + let state = b.table.set_text(bamboo, b.props.leaves, "small"); + self.set_block(above(pos), state, 3); + } + fn bamboo_height_below(&self, pos: BlockPos) -> i32 { + let mut height = 0; + while height < 16 + && self.b.is_block( + self.state(pos.offset(0, -(height + 1), 0)), + self.b.named.bamboo, + ) + { + height += 1; + } + height + } + fn bamboo_height_above(&self, pos: BlockPos) -> i32 { + let mut height = 0; + while height < 16 + && self.b.is_block( + self.state(pos.offset(0, height + 1, 0)), + self.b.named.bamboo, + ) + { + height += 1; + } + height + } + /// `BambooStalkBlock.growBamboo`. + fn bamboo_grow(&mut self, state: BlockStateId, pos: BlockPos, height: i32) { + let b = self.b; + let p = b.props; + let below_state = self.below_state(pos); + let below_two = pos.offset(0, -2, 0); + let below_two_state = self.state(below_two); + let mut leaves = "none"; + if height >= 1 { + if !b.is_block(below_state, b.named.bamboo) + || b.table.text(below_state, p.leaves) == "none" + { + leaves = "small"; + } else if b.is_block(below_state, b.named.bamboo) + && b.table.text(below_state, p.leaves) != "none" + { + leaves = "large"; + if b.is_block(below_two_state, b.named.bamboo) { + self.set_block( + below(pos), + b.table.set_text(below_state, p.leaves, "small"), + 3, + ); + self.set_block( + below_two, + b.table.set_text(below_two_state, p.leaves, "none"), + 3, + ); + } + } + } + let age = if b.table.int(state, p.age) != 1 && !b.is_block(below_two_state, b.named.bamboo) + { + 0 + } else { + 1 + }; + let stage = if (height < 11 || self.random().next_float() >= 0.25) && height != 15 { + 0 + } else { + 1 + }; + let next = b.table.set_int( + b.table.set_int( + b.table + .set_text(b.default_of(b.named.bamboo), p.leaves, leaves), + p.age, + age, + ), + p.stage, + stage, + ); + let _ = self.bamboo_height_above(pos); + self.set_block(above(pos), next, 3); + } + /// `VineBlock.randomTick`. + fn vine_random_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let p = b.props; + let block = b.block(state); + if self.rand_int(4) != 0 { + return; + } + let direction = Direction::ALL[self.rand_int(6) as usize]; + let above_pos = above(pos); + let default = b.default_of(block); + if super::query::is_horizontal(direction) + && !b.table.bool(state, self.direction_prop(direction)) + { + if !self.vine_can_spread(pos, block) { + return; + } + let test = rel(pos, direction); + let edge = self.state(test); + if b.is_air(edge) { + let cw = super::query::clockwise(direction); + let ccw = super::query::counter_clockwise(direction); + let cw_face = b.table.bool(state, self.direction_prop(cw)); + let ccw_face = b.table.bool(state, self.direction_prop(ccw)); + let cw_test = rel(test, cw); + let ccw_test = rel(test, ccw); + if cw_face && b.multiface_can_attach(self.state(cw_test), cw) { + self.set_block( + test, + b.table.set_bool(default, self.direction_prop(cw), true), + 2, + ); + } else if ccw_face && b.multiface_can_attach(self.state(ccw_test), ccw) { + self.set_block( + test, + b.table.set_bool(default, self.direction_prop(ccw), true), + 2, + ); + } else { + let opposite = direction.opposite(); + if cw_face + && self.is_empty_block(cw_test) + && b.multiface_can_attach(self.rel_state(pos, cw), opposite) + { + self.set_block( + cw_test, + b.table + .set_bool(default, self.direction_prop(opposite), true), + 2, + ); + } else if ccw_face + && self.is_empty_block(ccw_test) + && b.multiface_can_attach(self.rel_state(pos, ccw), opposite) + { + self.set_block( + ccw_test, + b.table + .set_bool(default, self.direction_prop(opposite), true), + 2, + ); + } else if self.random().next_float() < 0.05 + && b.multiface_can_attach(self.state(above(test)), Direction::Up) + { + self.set_block(test, b.table.set_bool(default, p.up, true), 2); + } + } + } else if b.multiface_can_attach(edge, direction) { + self.set_block( + pos, + b.table + .set_bool(state, self.direction_prop(direction), true), + 2, + ); + } + return; + } + if direction == Direction::Up && pos.y < self.level.max_y() - 1 { + if b.multiface_can_attach(self.state(above_pos), Direction::Up) { + self.set_block(pos, b.table.set_bool(state, p.up, true), 2); + return; + } + if self.is_empty_block(above_pos) { + if !self.vine_can_spread(pos, block) { + return; + } + let mut above_state = state; + for d in HORIZONTAL { + if self.random().next_boolean() + || !b.multiface_can_attach(self.state(rel(above_pos, d)), d) + { + above_state = b.table.set_bool(above_state, self.direction_prop(d), false); + } + } + if HORIZONTAL + .into_iter() + .any(|d| b.table.bool(above_state, self.direction_prop(d))) + { + self.set_block(above_pos, above_state, 2); + } + return; + } + } + if pos.y > self.level.min_y() { + let below_pos = below(pos); + let below_state = self.state(below_pos); + if b.is_air(below_state) || b.is_block(below_state, block) { + let before = if b.is_air(below_state) { + default + } else { + below_state + }; + let mut after = before; + for d in HORIZONTAL { + if self.random().next_boolean() && b.table.bool(state, self.direction_prop(d)) { + after = b.table.set_bool(after, self.direction_prop(d), true); + } + } + if before != after + && HORIZONTAL + .into_iter() + .any(|d| b.table.bool(after, self.direction_prop(d))) + { + self.set_block(below_pos, after, 2); + } + } + } + } + fn vine_can_spread(&self, pos: BlockPos, block: super::states::BlockId) -> bool { + let mut max = 5; + for x in -4..=4 { + for y in -1..=1 { + for z in -4..=4 { + if self.b.is_block(self.state(pos.offset(x, y, z)), block) { + max -= 1; + if max <= 0 { + return false; + } + } + } + } + } + true + } + /// `ChorusFlowerBlock.randomTick`. + fn chorus_flower_random_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let b = self.b; + let p = b.props; + let block = b.block(state); + let plant = b.named.chorus_plant; + let above_pos = above(pos); + if !self.is_empty_block(above_pos) || above_pos.y > self.level.max_y() - 1 { + return; + } + let age = b.table.int(state, p.age); + if age >= 5 { + return; + } + let mut grow_up = false; + let mut pillar_on_support = false; + let below_state = self.below_state(pos); + if b.in_set(below_state, &b.tags.supports_chorus_flower) { + grow_up = true; + } else if b.is_block(below_state, plant) { + let mut height = 1; + for _ in 0..4 { + let test = self.state(pos.offset(0, -(height + 1), 0)); + if !b.is_block(test, plant) { + if b.in_set(test, &b.tags.supports_chorus_flower) { + pillar_on_support = true; + } + break; + } + height += 1; + } + if height < 2 || height <= self.rand_int(if pillar_on_support { 5 } else { 4 }) { + grow_up = true; + } + } else if b.is_air(below_state) { + 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))) + }; + 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.level_event(1033, above_pos, 0); + } else if age < 4 { + let mut attempts = self.rand_int(4); + if pillar_on_support { + attempts += 1; + } + let mut branched = false; + 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, + ); + self.level_event(1033, target, 0); + branched = true; + } + } + if branched { + let connected = self.chorus_plant_with_connections(pos, plant_state); + self.set_block(pos, connected, 2); + } else { + self.set_block(pos, b.table.set_int(state, p.age, 5), 2); + self.level_event(1034, pos, 0); + } + } else { + self.set_block(pos, b.table.set_int(state, p.age, 5), 2); + self.level_event(1034, pos, 0); + } + } + /// `ServerLevel.tickPrecipitation` at a column whose top (motion-blocking + /// heightmap) position and biome answers are supplied by the caller. + pub(crate) fn precipitation_tick(&mut self, info: Precipitation) { + let b = self.b; + let p = b.props; + let top = info.top; + let below_pos = below(top); + if info.freezes_below { + self.set_block_and_update(below_pos, b.default_of(b.named.ice)); + } + if !self.level.is_raining() { + return; + } + let max_height = self.level.game_rules().max_snow_accumulation_height; + if max_height > 0 && info.snows_at_top { + let state = self.state(top); + if b.is_block(state, b.named.snow) { + let layers = b.table.int(state, p.layers); + if layers < max_height.min(8) { + self.set_block_and_update(top, b.table.set_int(state, p.layers, layers + 1)); + } + } else { + self.set_block_and_update(top, b.default_of(b.named.snow)); + } + } + if info.kind != PrecipitationKind::None { + let below_state = self.state(below_pos); + let data = b.data(below_state); + let chance = match info.kind { + PrecipitationKind::Rain => 0.05, + PrecipitationKind::Snow => 0.1, + PrecipitationKind::None => 0.0, + }; + 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 + }; + 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)); + 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"); + } + } + } + } + /// `ChangeOverTimeBlock.changeOverTime` for weathering copper. + fn copper_change_over_time(&mut self, state: BlockStateId, pos: BlockPos) { + if self.random().next_float() >= 0.056_888_89 { + return; + } + let b = self.b; + let own = b.data(state).weather; + let (mut same, mut older) = (0, 0); + for x in -4i32..=4 { + for y in -4i32..=4 { + for z in -4i32..=4 { + if x.abs() + y.abs() + z.abs() > 4 || (x == 0 && y == 0 && z == 0) { + continue; + } + let other = self.state(pos.offset(x, y, z)); + let data = b.data(other); + if !data.implements(super::classes::Interface::WeatheringCopper) { + continue; + } + match data.weather.cmp(&own) { + std::cmp::Ordering::Less => return, + std::cmp::Ordering::Greater => older += 1, + std::cmp::Ordering::Equal => same += 1, + } + } + } + } + let chance = (older + 1) as f32 / (older + same + 1) as f32; + let modifier = if own == 0 { 0.75 } else { 1.0 }; + if self.random().next_float() < chance * chance * modifier { + if let Some(next) = self.copper_next(state) { + self.set_block_and_update(pos, next); + } + } + } + /// `WeatheringCopper.getNext` by registry naming. + pub(crate) fn copper_next(&self, state: BlockStateId) -> Option { + let b = self.b; + let name = &*b.table.info(b.block(state)).name; + let path = name.strip_prefix("minecraft:")?; + let next = if path == "copper_block" { + "exposed_copper".to_owned() + } else if let Some(rest) = path.strip_prefix("exposed_") { + format!("weathered_{rest}") + } else if let Some(rest) = path.strip_prefix("weathered_") { + format!("oxidized_{rest}") + } else if path.starts_with("oxidized_") || path.starts_with("waxed_") { + return None; + } else { + format!("exposed_{path}") + }; + let block = b.table.block_by_name(&format!("minecraft:{next}"))?; + Some(b.table.with_properties_of(block, state)) + } +} + +/// `Biome.Precipitation` at a position. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PrecipitationKind { + None, + Rain, + Snow, +} +/// Biome answers for one precipitation tick (`ServerLevel.tickPrecipitation`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Precipitation { + /// `getHeightmapPos(MOTION_BLOCKING, pos)`. + pub top: BlockPos, + /// `biome.shouldFreeze(level, top.below())`. + pub freezes_below: bool, + /// `biome.shouldSnow(level, top)`. + pub snows_at_top: bool, + /// `biome.getPrecipitationAt(top.below(), seaLevel)`. + pub kind: PrecipitationKind, +} + +impl Behaviours { + /// Run due scheduled ticks for the level's current game time, in vanilla + /// order: block ticks then fluid ticks (65536 each at most). + pub fn tick_scheduled(&self, level: &mut L, ticks: &mut Ticks) { + let time = level.game_time(); + 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() + { + ticks.handling_tick = false; + return; + } + } + while let Ok(Some(tick)) = ticks.blocks.next_tick() { + let mut sim = self.sim(level, ticks); + let state = sim.state(tick.pos); + if u32::from(self.block(state).0) == tick.kind.0 { + sim.tick_block(state, tick.pos); + } + } + let _ = ticks.blocks.finish_tick(); + { + let level_ref: &L = level; + if ticks + .fluids + .begin_tick(time, 65536, |chunk: ChunkPos| { + level_ref.is_ticking_chunk(chunk) + }) + .is_err() + { + ticks.handling_tick = false; + return; + } + } + while let Ok(Some(tick)) = ticks.fluids.next_tick() { + let mut sim = self.sim(level, ticks); + let fluid = self.fluid(sim.state(tick.pos)).kind(); + if TickTypeId(fluid as u32) == tick.kind { + sim.fluid_tick(tick.pos); + } + } + let _ = ticks.fluids.finish_tick(); + ticks.handling_tick = false; + } + /// Random-tick one chunk (`ServerLevel.tickChunk` block part). `sections` + /// yields the minimum block Y of every section the caller considers + /// randomly ticking (vanilla: sections containing randomly-ticking states), + /// in ascending order. Draws `randomTickSpeed` positions per section. + pub fn tick_chunk_random( + &self, + level: &mut L, + ticks: &mut Ticks, + chunk: ChunkPos, + sections: impl IntoIterator, + ) { + let speed = level.game_rules().random_tick_speed; + if speed <= 0 { + return; + } + let (min_x, min_z) = (chunk.x * 16, chunk.z * 16); + for _ in 0..speed { + if level.random().next_int_bound(48).unwrap_or(1) == 0 { + let pos = ticks.block_random_pos(min_x, 0, min_z, 15); + if let Some(info) = level.precipitation(pos) { + self.sim(level, ticks).precipitation_tick(info); + } + } + } + for min_y in sections { + for _ in 0..speed { + let pos = ticks.block_random_pos(min_x, min_y, min_z, 15); + self.sim(level, ticks).random_tick_at(pos); + } + } + } + /// Random-tick a single position (block then fluid), as `tickChunk` does. + pub fn random_tick( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) { + self.sim(level, ticks).random_tick_at(pos); + } + /// Run one scheduled block tick at `pos` immediately (no queue check). + pub fn scheduled_block_tick( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + sim.tick_block(state, pos); + } + /// Run one scheduled fluid tick at `pos` immediately. + pub fn scheduled_fluid_tick( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) { + self.sim(level, ticks).fluid_tick(pos); + } +} diff --git a/crates/horizon-world/src/level/ticks.rs b/crates/horizon-world/src/level/ticks.rs new file mode 100644 index 000000000..c6be4282f --- /dev/null +++ b/crates/horizon-world/src/level/ticks.rs @@ -0,0 +1,141 @@ +//! Per-level mutable simulation state: scheduled block and fluid ticks plus the +//! in-flight neighbour-update queue and the random-tick position generator. +use super::{states::BlockId, update::NeighborUpdater}; +use crate::fluid::FluidKind; +use horizon_core::{ + position::{BlockPos, ChunkPos}, + ticks::{ + ChunkTicks, LevelTicks, ScheduleResult, ScheduledTick, TickError, TickPriority, TickTypeId, + }, +}; + +/// Owned by the caller next to its chunk storage. Chunks must be registered +/// with [`Ticks::add_chunk`] before ticks can be scheduled in them, mirroring +/// vanilla's `LevelTicks.allContainers` (scheduling elsewhere is dropped). +pub struct Ticks { + /// Block ticks keyed by `BlockId` (vanilla Block registry ID). + pub blocks: LevelTicks, + /// Fluid ticks keyed by vanilla Fluid registry ID (`FluidKind as u32`). + pub fluids: LevelTicks, + sub_tick: i64, + /// `Level.randValue`, the LCG behind `getBlockRandomPos`. + pub random_tick_value: i32, + pub(crate) updater: NeighborUpdater, + /// `ComparatorBlockEntity.output` per comparator position (block-entity + /// state owned by the level; persist it with the chunk if desired). + pub comparator_outputs: std::collections::HashMap, + /// `RedstoneTorchBlock.RECENT_TOGGLES` (position, game time). + pub torch_toggles: Vec<(BlockPos, i64)>, + /// Moving-piston block entities in ticker order (render and collide + /// moving blocks from these; see `piston_shape`). + pub moving_pistons: Vec<(BlockPos, super::pistons::MovingPiston)>, + pub(crate) next_block_entity_id: u64, + /// `ServerLevel.blockEvents`, run by `Behaviours::run_block_events`. + pub block_events: Vec, + /// `ServerLevel.isHandlingTick` (true while scheduled ticks run). + pub(crate) handling_tick: bool, +} +impl Default for Ticks { + fn default() -> Self { + Self::new(0) + } +} +impl Ticks { + /// `random_tick_seed` seeds `Level.randValue` (vanilla draws it from a + /// thread-local random at level construction). + pub fn new(random_tick_seed: i32) -> Self { + Self { + blocks: LevelTicks::default(), + fluids: LevelTicks::default(), + sub_tick: 0, + random_tick_value: random_tick_seed, + updater: NeighborUpdater::default(), + comparator_outputs: Default::default(), + torch_toggles: Vec::new(), + moving_pistons: Vec::new(), + next_block_entity_id: 0, + block_events: Vec::new(), + handling_tick: false, + } + } + /// Register a loaded chunk's saved block and fluid ticks. + 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) + } + /// Register a chunk without saved ticks. + pub fn add_empty_chunk(&mut self, pos: ChunkPos) -> Result<(), TickError> { + self.add_chunk(pos, ChunkTicks::default(), ChunkTicks::default()) + } + pub fn remove_chunk(&mut self, pos: ChunkPos) -> (Option, Option) { + (self.blocks.remove_chunk(pos), self.fluids.remove_chunk(pos)) + } + /// `ServerLevel.nextSubTickCount`, shared by block and fluid ticks. + pub fn next_sub_tick(&mut self) -> i64 { + let value = self.sub_tick; + self.sub_tick = self.sub_tick.wrapping_add(1); + value + } + pub fn schedule_block( + &mut self, + game_time: i64, + pos: BlockPos, + block: BlockId, + delay: i32, + priority: TickPriority, + ) -> ScheduleResult { + let tick = ScheduledTick { + kind: TickTypeId(u32::from(block.0)), + pos, + trigger_tick: game_time.wrapping_add(i64::from(delay)), + priority, + sub_tick_order: self.next_sub_tick(), + }; + self.blocks.schedule(tick) + } + 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, + trigger_tick: game_time.wrapping_add(i64::from(delay)), + priority: TickPriority::Normal, + sub_tick_order: self.next_sub_tick(), + }; + 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))) + } + 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))) + } + /// `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); + let value = self.random_tick_value >> 2; + 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 new file mode 100644 index 000000000..b981e1a6f --- /dev/null +++ b/crates/horizon-world/src/level/update.rs @@ -0,0 +1,547 @@ +//! `Level.setBlock`, `LevelChunk.setBlockState` and the +//! `CollectingNeighborUpdater` that orders neighbour and shape updates. +use super::{LevelAccess, LevelEvent, Sim, flags, states::BlockId}; +use crate::{fluid::FluidState, registry::BlockStateId}; +use horizon_core::{ + geometry::Direction, + position::BlockPos, + random::LegacyRandom, + ticks::{ScheduleResult, TickPriority}, +}; + +/// `NeighborUpdater.UPDATE_ORDER`. +pub(crate) const UPDATE_ORDER: [Direction; 6] = [ + Direction::West, + Direction::East, + Direction::Down, + Direction::Up, + Direction::North, + Direction::South, +]; +/// `BlockBehaviour.UPDATE_SHAPE_ORDER`. +pub(crate) const UPDATE_SHAPE_ORDER: [Direction; 6] = [ + Direction::West, + Direction::East, + Direction::North, + Direction::South, + Direction::Down, + Direction::Up, +]; +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; + +pub(crate) fn rel(pos: BlockPos, direction: Direction) -> BlockPos { + let [x, y, z] = direction.normal(); + pos.offset(x, y, z) +} +pub(crate) fn above(pos: BlockPos) -> BlockPos { + pos.offset(0, 1, 0) +} +pub(crate) fn below(pos: BlockPos) -> BlockPos { + pos.offset(0, -1, 0) +} + +#[derive(Clone, Copy, Debug)] +enum Update { + Shape { + direction: Direction, + neighbor_state: BlockStateId, + pos: BlockPos, + neighbor_pos: BlockPos, + flags: i32, + limit: i32, + }, + Simple { + pos: BlockPos, + block: BlockId, + }, + Full { + state: BlockStateId, + pos: BlockPos, + block: BlockId, + moved: bool, + }, + Multi { + source: BlockPos, + block: BlockId, + skip: Option, + index: usize, + }, +} + +enum Step { + Shape { + direction: Direction, + neighbor_state: BlockStateId, + pos: BlockPos, + neighbor_pos: BlockPos, + flags: i32, + limit: i32, + }, + Neighbor { + state: Option, + pos: BlockPos, + block: BlockId, + moved: bool, + }, +} + +#[derive(Default)] +pub(crate) struct NeighborUpdater { + stack: Vec, + added: Vec, + count: i32, +} + +impl Update { + /// `runNext`: the update to execute now and whether more remain. + fn next(&mut self) -> (Step, bool) { + match *self { + Self::Shape { + direction, + neighbor_state, + pos, + neighbor_pos, + flags, + limit, + } => ( + Step::Shape { + direction, + neighbor_state, + pos, + neighbor_pos, + flags, + limit, + }, + false, + ), + Self::Simple { pos, block } => ( + Step::Neighbor { + state: None, + pos, + block, + moved: false, + }, + false, + ), + Self::Full { + state, + pos, + block, + moved, + } => ( + Step::Neighbor { + state: Some(state), + pos, + block, + moved, + }, + false, + ), + Self::Multi { + source, + block, + skip, + ref mut index, + } => { + let direction = UPDATE_ORDER[*index]; + *index += 1; + if *index < UPDATE_ORDER.len() && Some(UPDATE_ORDER[*index]) == skip { + *index += 1; + } + ( + Step::Neighbor { + state: None, + pos: rel(source, direction), + block, + moved: false, + }, + *index < UPDATE_ORDER.len(), + ) + } + } + } +} + +impl Sim<'_, L> { + pub fn state(&self, pos: BlockPos) -> BlockStateId { + self.level.block_state(pos) + } + pub fn fluid_at(&self, pos: BlockPos) -> FluidState { + self.b.fluid(self.state(pos)) + } + pub fn random(&mut self) -> &mut LegacyRandom { + self.level.random() + } + pub fn emit(&mut self, event: LevelEvent) { + self.level.emit(event); + } + pub fn level_event(&mut self, id: i32, pos: BlockPos, data: i32) { + self.level.emit(LevelEvent::LevelEvent { id, pos, data }); + } + pub fn sound(&mut self, pos: BlockPos, sound: &std::sync::Arc, volume: f32, pitch: f32) { + self.level.emit(LevelEvent::Sound { + pos, + sound: sound.clone(), + volume, + pitch, + }); + } + pub fn game_event(&mut self, pos: BlockPos, event: &'static str) { + self.level.emit(LevelEvent::GameEvent { pos, event }); + } + pub fn block_of(&self, state: BlockStateId) -> BlockId { + self.b.table.block(state) + } + pub fn is_in_valid_bounds(&self, pos: BlockPos) -> bool { + pos.y >= self.level.min_y() + && pos.y < self.level.max_y() + && (-30_000_000..30_000_000).contains(&pos.x) + && (-30_000_000..30_000_000).contains(&pos.z) + } + + // ---- scheduled ticks ---- + 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 { + 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 { + let time = self.level.game_time(); + self.ticks.schedule_fluid(time, pos, fluid, delay) + } + + // ---- Level.setBlock ---- + pub fn set_block(&mut self, pos: BlockPos, state: BlockStateId, flags: i32) -> bool { + self.set_block_limit(pos, state, flags, flags::UPDATE_LIMIT) + } + 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 { + if !self.is_in_valid_bounds(pos) || !self.level.is_loaded(pos) { + return false; + } + let Some(old) = self.chunk_set_block_state(pos, state, update_flags) else { + return false; + }; + let new = self.state(pos); + if new == state { + 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) + { + 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); + 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); + } + } + 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 { + let current = self.state(pos); + if current == state { + return None; + } + let old = self.level.set_raw(pos, state)?; + if old == state { + return None; + } + let new_block = self.block_of(state); + let block_changed = self.block_of(old) != new_block; + if block_changed && self.block_of(old) == self.b.named.moving_piston { + // PistonMovingBlockEntity.preRemoveSideEffects -> finalTick; the + // block is already replaced, so only the entity goes away. + 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)) + && (update_flags & flags::UPDATE_NEIGHBORS != 0 || moved) + { + self.affect_neighbors_after_removal(old, pos, moved); + } + if self.block_of(self.state(pos)) != new_block { + return None; + } + if update_flags & flags::UPDATE_SKIP_ON_PLACE == 0 { + self.on_place(state, pos, old, moved); + } + Some(old) + } + /// `Level.removeBlock`. + pub fn remove_block(&mut self, pos: BlockPos, moved_by_piston: bool) -> bool { + let fluid = self.fluid_at(pos); + let legacy = self.b.legacy_block(fluid); + self.set_block(pos, legacy, 3 | if moved_by_piston { 64 } else { 0 }) + } + /// `Level.destroyBlock(pos, dropResources, null, limit)`. + pub fn destroy_block(&mut self, pos: BlockPos, drop: bool, limit: i32) -> bool { + let state = self.state(pos); + if self.b.is_air(state) { + return false; + } + self.level_event(2001, pos, state.0 as i32); + if drop { + self.drop_resources(state, pos); + } + let fluid = self.fluid_at(pos); + let legacy = self.b.legacy_block(fluid); + let destroyed = self.set_block_limit(pos, legacy, 3, limit); + if destroyed { + self.game_event(pos, "minecraft:block_destroy"); + } + destroyed + } + pub fn drop_resources(&mut self, state: BlockStateId, pos: BlockPos) { + if self.level.game_rules().block_drops { + self.emit(LevelEvent::DropResources { pos, state }); + } + } + /// `Block.updateOrDestroy`. + 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, + ); + } + } + } + /// `Block.updateFromNeighbourShapes`. + 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); + let neighbour_state = self.state(neighbour); + new = self.update_shape(new, pos, direction, neighbour, neighbour_state); + } + new + } + /// `BlockStateBase.updateNeighbourShapes`. + 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, + ); + } + } + + // ---- neighbour updater ---- + pub fn update_neighbors_at(&mut self, pos: BlockPos, block: BlockId) { + self.add_and_run(Update::Multi { + source: pos, + block, + skip: None, + index: 0, + }); + } + pub fn update_neighbors_at_except(&mut self, pos: BlockPos, block: BlockId, skip: Direction) { + let index = usize::from(UPDATE_ORDER[0] == skip); + self.add_and_run(Update::Multi { + source: pos, + block, + skip: Some(skip), + index, + }); + } + 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_shape_changed( + &mut self, + direction: Direction, + pos: BlockPos, + neighbor_pos: BlockPos, + neighbor_state: BlockStateId, + update_flags: i32, + limit: i32, + ) { + self.add_and_run(Update::Shape { + direction, + neighbor_state, + pos, + neighbor_pos, + flags: update_flags, + limit, + }); + } + fn add_and_run(&mut self, update: Update) { + let updater = &mut self.ticks.updater; + let running = updater.count > 0; + let too_many = updater.count >= MAX_CHAINED_NEIGHBOR_UPDATES; + updater.count += 1; + if !too_many { + if running { + updater.added.push(update); + } else { + updater.stack.push(update); + } + } + if !running { + self.run_updates(); + } + } + fn run_updates(&mut self) { + loop { + let updater = &mut self.ticks.updater; + if updater.stack.is_empty() && updater.added.is_empty() { + break; + } + while let Some(update) = updater.added.pop() { + updater.stack.push(update); + } + while let Some(top) = self.ticks.updater.stack.last_mut() { + let (step, more) = top.next(); + self.execute(step); + if !more { + self.ticks.updater.stack.pop(); + break; + } + if !self.ticks.updater.added.is_empty() { + break; + } + } + } + let updater = &mut self.ticks.updater; + updater.stack.clear(); + updater.added.clear(); + updater.count = 0; + } + fn execute(&mut self, step: Step) { + match step { + Step::Shape { + direction, + neighbor_state, + pos, + neighbor_pos, + flags: update_flags, + limit, + } => { + let current = self.state(pos); + 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); + self.update_or_destroy(current, new, pos, update_flags, limit); + } + } + Step::Neighbor { + state, + pos, + block, + moved, + } => { + let state = state.unwrap_or_else(|| self.state(pos)); + self.neighbor_changed(state, pos, block, moved); + } + } + } + /// `Level.updateNeighbourForOutputSignal`. + pub fn update_neighbour_for_output_signal(&mut self, pos: BlockPos, block: BlockId) { + for direction in super::update::HORIZONTAL { + let mut relative = rel(pos, direction); + if !self.level.is_loaded(relative) { + continue; + } + let mut state = self.state(relative); + if self.b.table.is(state, self.b.named.comparator) { + self.neighbor_changed_full(state, relative, block, false); + } else if self.is_redstone_conductor(state, relative) { + relative = rel(relative, direction); + state = self.state(relative); + if self.b.table.is(state, self.b.named.comparator) { + self.neighbor_changed_full(state, relative, block, false); + } + } + } + } +} diff --git a/crates/horizon-world/src/lib.rs b/crates/horizon-world/src/lib.rs index 6857e263e..bf49481b1 100644 --- a/crates/horizon-world/src/lib.rs +++ b/crates/horizon-world/src/lib.rs @@ -72,6 +72,7 @@ pub mod item_use_catalog; pub mod item_use_lifecycle; pub mod item_use_start; pub mod java_hash_map; +pub mod level; pub mod liquid_collision; pub mod live_attribute_updates; pub mod living_air; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockBehaviourExporter.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockBehaviourExporter.java new file mode 100644 index 000000000..4a475133b --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockBehaviourExporter.java @@ -0,0 +1,255 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.lang.reflect.RecordComponent; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.Optional; +import net.minecraft.SharedConstants; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.EmptyBlockGetter; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.SoundType; +import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.SupportType; +import net.minecraft.world.level.material.FlowingFluid; +import net.minecraft.world.level.material.Fluid; + +/** + * Original exporter of the block-behaviour inputs Horizon's level simulation needs: + * every block's class chain and immutable instance configuration (read reflectively), + * per-state support/redstone/fluid facts from vanilla's accessors over an empty level, + * fire odds and block-item placement bindings. No behaviour is evaluated here. + */ +public final class VanillaBlockBehaviourExporter { + private static JsonElement value(Object v, int depth) { + if (v == null) { + return JsonNull.INSTANCE; + } else if (v instanceof Boolean b) { + return new JsonPrimitive(b); + } else if (v instanceof Number n) { + return new JsonPrimitive(n); + } else if (v instanceof String || v instanceof Character) { + return new JsonPrimitive(v.toString()); + } else if (v instanceof Enum e) { + return new JsonPrimitive(e.name()); + } else if (v instanceof Block b) { + return new JsonPrimitive(BuiltInRegistries.BLOCK.getKey(b).toString()); + } else if (v instanceof BlockState s) { + var o = new JsonObject(); + o.addProperty("state", Block.getId(s)); + return o; + } else if (v instanceof Item i) { + return new JsonPrimitive(BuiltInRegistries.ITEM.getKey(i).toString()); + } else if (v instanceof Fluid f) { + return new JsonPrimitive(BuiltInRegistries.FLUID.getKey(f).toString()); + } else if (v instanceof SoundEvent s) { + return new JsonPrimitive(s.location().toString()); + } else if (v instanceof Identifier id) { + return new JsonPrimitive(id.toString()); + } else if (v instanceof ResourceKey key) { + return new JsonPrimitive(key.identifier().toString()); + } else if (v instanceof TagKey tag) { + return new JsonPrimitive("#" + tag.location()); + } else if (v instanceof Holder holder) { + if (holder.isBound() && depth > 0) { + return value(holder.value(), depth - 1); + } + return holder.unwrapKey().map(k -> new JsonPrimitive(k.identifier().toString())).orElse(JsonNull.INSTANCE); + } else if (v instanceof Optional optional) { + return optional.isPresent() ? value(optional.get(), depth) : JsonNull.INSTANCE; + } else if (depth > 0 && v instanceof java.util.Map map) { + var o = new JsonObject(); + for (var entry : map.entrySet()) { + var key = value(entry.getKey(), 0); + o.add(key.isJsonPrimitive() ? key.getAsString() : key.toString(), value(entry.getValue(), depth - 1)); + } + return o; + } else if (depth > 0 && v.getClass().isRecord()) { + var o = new JsonObject(); + for (RecordComponent component : v.getClass().getRecordComponents()) { + try { + component.getAccessor().setAccessible(true); + o.add(component.getName(), value(component.getAccessor().invoke(v), depth - 1)); + } catch (Exception e) { + o.addProperty(component.getName(), ""); + } + } + return o; + } else if (depth > 0 && v instanceof SoundType sound) { + var o = new JsonObject(); + o.addProperty("volume", sound.getVolume()); + o.addProperty("pitch", sound.getPitch()); + o.addProperty("break", sound.getBreakSound().location().toString()); + o.addProperty("place", sound.getPlaceSound().location().toString()); + return o; + } else if (v instanceof net.minecraft.core.particles.ParticleType particle) { + return new JsonPrimitive(BuiltInRegistries.PARTICLE_TYPE.getKey(particle).toString()); + } else if (depth > 0 && v.getClass().getName().startsWith("net.minecraft.world.level.block.grower.")) { + return fields(v, Object.class); + } + return new JsonPrimitive("<" + v.getClass().getSimpleName() + ">"); + } + + private static JsonObject fields(Object instance, Class top) { + var o = new JsonObject(); + for (Class c = instance.getClass(); c != null && c != top; c = c.getSuperclass()) { + for (Field field : c.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers()) || o.has(field.getName())) { + continue; + } + try { + field.setAccessible(true); + o.add(field.getName(), value(field.get(instance), 3)); + } catch (Exception e) { + o.addProperty(field.getName(), ""); + } + } + } + return o; + } + + private static JsonArray chain(Class c, Class top) { + var result = new JsonArray(); + for (; c != null && c != top; c = c.getSuperclass()) { + result.add(c.getSimpleName()); + } + return result; + } + + private static JsonArray blocks() { + var blocks = new JsonArray(); + for (Block block : BuiltInRegistries.BLOCK) { + var o = new JsonObject(); + o.addProperty("name", BuiltInRegistries.BLOCK.getKey(block).toString()); + o.add("class", chain(block.getClass(), BlockBehaviour.class)); + var interfaces = new JsonArray(); + for (Class c = block.getClass(); c != null; c = c.getSuperclass()) { + for (Class i : c.getInterfaces()) { + interfaces.add(i.getSimpleName()); + } + } + o.add("interfaces", interfaces); + o.add("fields", fields(block, Block.class)); + o.addProperty("dynamic_shape", block.hasDynamicShape()); + o.addProperty("item", BuiltInRegistries.ITEM.getKey(block.asItem()).toString()); + blocks.add(o); + } + return blocks; + } + + private static final SupportType[] SUPPORTS = {SupportType.FULL, SupportType.CENTER, SupportType.RIGID}; + + private static JsonArray states() { + var states = new JsonArray(); + var level = EmptyBlockGetter.INSTANCE; + for (BlockState state : Block.BLOCK_STATE_REGISTRY) { + var o = new JsonArray(); + int sturdy = 0; + for (int s = 0; s < SUPPORTS.length; s++) { + for (Direction d : Direction.values()) { + try { + if (state.isFaceSturdy(level, BlockPos.ZERO, d, SUPPORTS[s])) { + sturdy |= 1 << (s * 6 + d.ordinal()); + } + } catch (Exception e) { + sturdy |= 1 << 30; + } + } + } + int flags = 0; + if (state.isSolid()) flags |= 1; + if (state.isAir()) flags |= 2; + try { + if (state.isRedstoneConductor(level, BlockPos.ZERO)) flags |= 4; + } catch (Exception e) { + flags |= 1 << 20; + } + if (state.isSignalSource()) flags |= 8; + if (state.hasAnalogOutputSignal()) flags |= 16; + try { + if (state.getCollisionShape(level, BlockPos.ZERO).isEmpty()) flags |= 32; + } catch (Exception e) { + flags |= 1 << 21; + } + try { + if (state.isSuffocating(level, BlockPos.ZERO)) flags |= 64; + } catch (Exception e) { + flags |= 1 << 22; + } + var fluid = state.getFluidState(); + int fluidId = BuiltInRegistries.FLUID.getId(fluid.getType()); + int fluidAmount = fluid.getAmount(); + boolean falling = fluid.hasProperty(FlowingFluid.FALLING) && fluid.getValue(FlowingFluid.FALLING); + // Weak/strong signals over an empty level, packed 4 bits per direction. + long weak = 0; + long strong = 0; + boolean signalError = false; + if (state.isSignalSource()) { + for (Direction d : Direction.values()) { + try { + weak |= ((long) state.getSignal(level, BlockPos.ZERO, d) & 15) << (4 * d.ordinal()); + strong |= ((long) state.getDirectSignal(level, BlockPos.ZERO, d) & 15) << (4 * d.ordinal()); + } catch (Exception e) { + signalError = true; + } + } + } + o.add(sturdy); + o.add(flags); + o.add(fluidId); + o.add(fluidAmount); + o.add(falling); + o.add(weak); + o.add(strong); + o.add(signalError); + o.add(state.instrument().name()); + states.add(o); + } + return states; + } + + private static JsonObject items() { + var items = new JsonObject(); + for (Item item : BuiltInRegistries.ITEM) { + if (!(item instanceof BlockItem)) { + continue; + } + var o = new JsonObject(); + o.add("class", chain(item.getClass(), Item.class)); + o.add("fields", fields(item, Item.class)); + items.add(BuiltInRegistries.ITEM.getKey(item).toString(), o); + } + return items; + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + var result = new JsonObject(); + result.add("blocks", blocks()); + result.add("states", states()); + result.add("items", items()); + var fluids = new JsonArray(); + for (Fluid fluid : BuiltInRegistries.FLUID) { + fluids.add(BuiltInRegistries.FLUID.getKey(fluid).toString()); + } + result.add("fluids", fluids); + result.add("fire", fields(Blocks.FIRE, Block.class)); + Files.writeString(Path.of(args[0]), new Gson().toJson(result), StandardCharsets.UTF_8); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLevelShapeOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLevelShapeOracle.java new file mode 100644 index 000000000..e3ff99b24 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLevelShapeOracle.java @@ -0,0 +1,133 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import com.mojang.serialization.JsonOps; +import java.io.PrintWriter; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Proxy; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.tags.*; +import net.minecraft.util.RandomSource; +import net.minecraft.world.attribute.EnvironmentAttributeReader; +import net.minecraft.world.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.Fluid; +import net.minecraft.world.ticks.LevelTickAccess; +import net.minecraft.world.ticks.TickPriority; + +/** + * Native BlockState.updateShape and canSurvive over small generated neighbourhoods. + * The level is a reflective LevelReader over the case cells; scheduled ticks requested + * through ScheduledTickAccess are recorded instead of queued. + */ +public final class VanillaLevelShapeOracle { + 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>(); + try (var files = Files.list(dir)) { + for (var file : (Iterable) files::iterator) { + var name = file.getFileName().toString().replace(".json", ""); + var parsed = TagFile.CODEC.parse(JsonOps.INSTANCE, JsonParser.parseString(Files.readString(file))).getOrThrow(); + var entries = new ArrayList(); + for (var entry : parsed.entries()) entries.add(new TagLoader.EntryWithSource(entry, "vanilla")); + definitions.put(Identifier.parse("minecraft:" + name), entries); + } + } + var tags = new HashMap, List>>(); + loader.build(definitions).forEach((id, values) -> tags.put(TagKey.create(Registries.FLUID, id), List.copyOf(values))); + registry.prepareTagReload(new TagLoader.LoadResult<>(Registries.FLUID, tags)).apply(); + } + + public static void main(String[] args) throws Exception { + 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()); + bindFluidTags(resources.resolve("data/minecraft/tags/fluid")); + var registryAccess = RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); + var air = net.minecraft.world.level.block.Blocks.AIR.defaultBlockState(); + 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 cells = new HashMap(); + for (var cell : f.getAsJsonArray("cells")) { + var c = cell.getAsJsonArray(); + cells.put(new BlockPos(c.get(0).getAsInt(), c.get(1).getAsInt(), c.get(2).getAsInt()), Block.stateById(c.get(3).getAsInt())); + } + int light = f.get("light").getAsInt(); + var noTicks = (LevelTickAccess) Proxy.newProxyInstance(LevelTickAccess.class.getClassLoader(), new Class[]{LevelTickAccess.class}, (proxy, method, values) -> { + if (method.getReturnType() == boolean.class) return false; + if (method.getReturnType() == int.class) return 0; + return null; + }); + var level = (LevelReader) Proxy.newProxyInstance(LevelReader.class.getClassLoader(), new Class[]{LevelReader.class}, (proxy, method, values) -> { + switch (method.getName()) { + case "getBlockState": return cells.getOrDefault((BlockPos) values[0], air); + case "getFluidState": return cells.getOrDefault((BlockPos) values[0], air).getFluidState(); + case "getBlockEntity": return null; + case "getRawBrightness": return Math.max(0, light - (int) values[1]); + case "getMaxLocalRawBrightness": return light; + case "getBrightness": return light; + case "isClientSide": return false; + case "registryAccess": return registryAccess; + case "enabledFeatures": return net.minecraft.world.flag.FeatureFlags.DEFAULT_FLAGS; + case "environmentAttributes": return EnvironmentAttributeReader.EMPTY; + case "getMinY": return -64; + case "getHeight": return values == null || values.length == 0 ? 384 : null; + case "getSkyDarken": return 0; + case "hashCode": return System.identityHashCode(proxy); + case "equals": return proxy == values[0]; + default: + if (method.isDefault()) return InvocationHandler.invokeDefault(proxy, method, values); + throw new AssertionError(method.toString()); + } + }); + var scheduled = new TreeSet(); + var ticks = (ScheduledTickAccess) Proxy.newProxyInstance(ScheduledTickAccess.class.getClassLoader(), new Class[]{ScheduledTickAccess.class}, (proxy, method, values) -> { + switch (method.getName()) { + case "scheduleTick": { + var pos = (BlockPos) values[0]; + String type = values[1] instanceof Block block ? BuiltInRegistries.BLOCK.getKey(block).toString() : BuiltInRegistries.FLUID.getKey((Fluid) values[1]).toString(); + int priority = values.length > 3 ? ((TickPriority) values[3]).getValue() : 0; + scheduled.add(type + "@" + pos.getX() + "," + pos.getY() + "," + pos.getZ() + "+" + values[2] + "p" + priority); + return null; + } + case "getBlockTicks": + case "getFluidTicks": + return noTicks; + default: + throw new AssertionError(method.toString()); + } + }); + RandomSource random = new LegacyRandomSource(f.get("seed").getAsLong()); + var p = f.getAsJsonArray("pos"); + var pos = new BlockPos(p.get(0).getAsInt(), p.get(1).getAsInt(), p.get(2).getAsInt()); + var state = cells.getOrDefault(pos, air); + var direction = Direction.from3DDataValue(f.get("dir").getAsInt()); + var neighbourPos = pos.relative(direction); + String shape; + try { + var result = state.updateShape(level, ticks, pos, direction, neighbourPos, level.getBlockState(neighbourPos), random); + shape = Integer.toString(Block.getId(result)); + } catch (RuntimeException | AssertionError e) { + shape = "error " + e.getClass().getSimpleName(); + } + String survive; + try { + survive = Boolean.toString(state.canSurvive(level, pos)); + } catch (RuntimeException | AssertionError e) { + survive = "error"; + } + out.println("shape " + shape + " ticks " + String.join(" ", scheduled) + " survive " + survive); + } + } + } +} 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/prepare_native_client.py b/tools/prepare_native_client.py index 0e2f881f0..651fcae4f 100644 --- a/tools/prepare_native_client.py +++ b/tools/prepare_native_client.py @@ -248,6 +248,22 @@ def main(): subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaGameplayFactsExporter', str(gameplay)], check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) + # Block classes, instance configuration and per-state support/signal/fluid + # facts for horizon-world's level behaviour (level::Behaviours::load). + behaviours = root / 'block-behaviours.json' + behaviour_oracle = oracle.with_name('VanillaBlockBehaviourExporter.java') + behaviour_sources = base.source_hashes([behaviour_oracle]) + if not (previous.get('behaviour_exporters_sha256') == behaviour_sources and behaviours.exists() + and previous.get('server_sha256') == origin['server_sha256']): + classes = lab.LOCAL / 'block-behaviours' / 'classes'; classes.mkdir(parents=True, exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + with (root / 'behaviour-export.log').open('w') as log: + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', + '-cp', dependencies, '-d', str(classes), str(behaviour_oracle)], + check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) + subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.VanillaBlockBehaviourExporter', str(behaviours)], + check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) items = root / 'items.json' if not items.exists() or previous.get('server_sha256') != origin['server_sha256']: # Vanilla's own data generator reports every item's default components. @@ -289,6 +305,7 @@ def main(): 'model_state_exporters_sha256': binding_sources, 'gameplay_exporters_sha256': gameplay_sources, 'entity_model_exporters_sha256': entity_sources, + 'behaviour_exporters_sha256': behaviour_sources, 'model_states_sha256': lab.digest(model_states, 'sha256'), 'data_version': version['world_version'], 'facts_sha256': lab.digest(facts, 'sha256'), 'block_tags_sha256': lab.digest(root / 'block-tags.json', 'sha256'), 'resource_files': count}) 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() diff --git a/tools/test_level_shape_parity.py b/tools/test_level_shape_parity.py new file mode 100644 index 000000000..2817d4681 --- /dev/null +++ b/tools/test_level_shape_parity.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Compare horizon-world's level updateShape/canSurvive port with pinned vanilla. + +Generates random 5x5x5 neighbourhoods around a random block state, evaluates +BlockState.updateShape towards one neighbour and canSurvive with the native +oracle (VanillaLevelShapeOracle) and with Behaviours (level_shape_fixture), +and reports every differing case. +""" +import argparse +import json +import os +import random +import subprocess +from pathlib import Path +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + +# Blocks whose updateShape needs a full level (portal frames) are skipped. +SKIP = {'minecraft:nether_portal', 'minecraft:moving_piston'} + + +def generate(resources, count, seed): + facts = json.loads((resources / 'facts.json').read_text()) + states = facts['states'] + by_block = {} + for index, state in enumerate(states): + by_block.setdefault(state[0], []).append(index) + names = [name for name in by_block if name not in SKIP] + 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:farmland']] + rng = random.Random(seed) + cases = [] + for _ in range(count): + block = rng.choice(names) + center = rng.choice(by_block[block]) + related = by_block[block] + cells = [] + for x in range(-2, 3): + for y in range(-2, 3): + for z in range(-2, 3): + if (x, y, z) == (0, 0, 0): + cells.append([0, 0, 0, center]) + continue + roll = rng.random() + if roll < 0.35: + continue + if roll < 0.55: + cells.append([x, y, z, rng.choice(common)]) + elif roll < 0.75: + cells.append([x, y, z, rng.choice(related)]) + else: + other = rng.choice(names) + cells.append([x, y, z, rng.choice(by_block[other])]) + cases.append({'seed': rng.randrange(1 << 40), 'light': rng.randrange(16), 'pos': [0, 0, 0], + 'dir': rng.randrange(6), 'cells': cells, 'block': block}) + 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-shape-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 / 'VanillaLevelShapeOracle.java', parity / 'VanillaHeightmapOracle.java'] + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies, + '-d', str(classes), *map(str, sources)], check=True) + subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.VanillaLevelShapeOracle', str(resources), str(work / 'cases.jsonl'), + str(work / 'native.txt')], check=True) + subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'level_shape_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['block'], []).append((case, a, b)) + total = sum(len(v) for v in differences.values()) + for block, items in sorted(differences.items(), key=lambda item: -len(item[1])): + case, a, b = items[0] + print(f'{block}: {len(items)} differing; e.g. dir={case["dir"]}\n native {a}\n rust {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()