diff --git a/crates/horizon-world/examples/structure_blocks.rs b/crates/horizon-world/examples/structure_blocks.rs index 1f79d4ca2..6b333a301 100644 --- a/crates/horizon-world/examples/structure_blocks.rs +++ b/crates/horizon-world/examples/structure_blocks.rs @@ -61,7 +61,17 @@ fn main() -> Result<(), Error> { } } let mut region: [ProtoChunk; 9] = region.try_into().map_err(|_| "region size")?; - worker.decorate(&mut region)?; + let stats = if std::env::var_os("HORIZON_TERRAIN_ONLY").is_some() { + Default::default() + } else { + worker.decorate(&mut region)? + }; + if stats.failed > 0 { + eprintln!( + "chunk {cx} {cz}: {} structure placements failed", + stats.failed + ); + } let chunk = ®ion[4]; println!("chunk {cx} {cz}"); let (min, height) = (chunk.terrain.min_y(), chunk.terrain.height()); diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index f2f3699da..91caa24f1 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -180,6 +180,9 @@ pub struct GeneratorData { /// Templates, processor lists and per-state template transforms. pub(super) structures: Option>, pub(super) structure_resources: Option, + /// Block shape-update behaviour (`block-behaviours.json` next to the + /// worldgen directory) for template placement's neighbor updates. + pub(super) behaviours: Option>, } type Bundle = BTreeMap; fn read_bundle(dir: &Path, name: &str) -> Result { @@ -425,7 +428,13 @@ impl GeneratorData { }), _ => None, }; + let behaviours = dir + .parent() + .filter(|root| root.join("block-behaviours.json").exists()) + .and_then(|root| crate::level::Behaviours::load(registry, root).ok()) + .map(Arc::new); Ok(Arc::new(Self { + behaviours, structure_resources, structures, registry, diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index f803e1500..67139a43a 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -313,6 +313,8 @@ impl Decoration { zone: GenerationWriteZone::new(center, 1), decoration: self, temperatures: &mut worker.temperatures, + behaviours: data.behaviours.as_deref(), + build: (generation.min_y, generation.min_y + generation.height), }; let mut stats = DecorateStats::default(); let blocks = self.blocks; @@ -428,6 +430,68 @@ struct World<'a> { zone: GenerationWriteZone, decoration: &'a Decoration, temperatures: &'a mut [BiomeTemperature], + behaviours: Option<&'a crate::level::Behaviours>, + /// Inclusive minimum and exclusive maximum build height. + build: (i32, i32), +} +/// Read-only `LevelAccess` view of the decoration region for +/// `BlockState.updateShape` (writes go through `World::set_block`). +struct ShapeLevel<'w, 'a> { + world: &'w World<'a>, + random: horizon_core::random::LegacyRandom, +} +impl crate::level::LevelAccess for ShapeLevel<'_, '_> { + fn block_state(&self, pos: BlockPos) -> BlockStateId { + self.world + .region + .block([pos.x, pos.y, pos.z]) + .unwrap_or(BlockStateId(0)) + } + fn set_raw(&mut self, _: BlockPos, _: BlockStateId) -> Option { + None + } + fn is_loaded(&self, pos: BlockPos) -> bool { + self.world.region.block([pos.x, pos.y, pos.z]).is_ok() + } + fn min_y(&self) -> i32 { + self.world.build.0 + } + fn max_y(&self) -> i32 { + self.world.build.1 + } + fn random(&mut self) -> &mut horizon_core::random::LegacyRandom { + &mut self.random + } + fn game_time(&self) -> i64 { + 0 + } +} +impl World<'_> { + /// `BlockState.updateShape` of the state at `pos` against `neighbor`. + fn shape_update( + &self, + behaviours: &crate::level::Behaviours, + state: BlockStateId, + pos: [i32; 3], + direction: Direction, + neighbor_pos: [i32; 3], + neighbor: BlockStateId, + ) -> BlockStateId { + let mut level = ShapeLevel { + world: self, + random: horizon_core::random::LegacyRandom::new(0), + }; + let mut ticks = crate::level::Ticks::new(0); + behaviours.update_shape( + &mut level, + &mut ticks, + state, + BlockPos::new(pos[0], pos[1], pos[2]), + direction, + BlockPos::new(neighbor_pos[0], neighbor_pos[1], neighbor_pos[2]), + neighbor, + ) + } } impl DecorationWorld for World<'_> { type Error = RegionError; @@ -622,6 +686,81 @@ impl PlacementContext for World<'_> { fn world_seed(&mut self) -> Result { self.region.world_seed() } + fn update_shape_at_face( + &mut self, + position: [i32; 3], + direction: Direction, + flags: i32, + ) -> Result<(), PlacementQueryError> { + let Some(behaviours) = self.behaviours else { + return Ok(()); + }; + let n = direction.normal(); + let neighbor_pos = [position[0] + n[0], position[1] + n[1], position[2] + n[2]]; + let state = self.region.block(position).map_err(query)?; + let neighbor = self.region.block(neighbor_pos).map_err(query)?; + let new_state = self.shape_update( + behaviours, + state, + position, + direction, + neighbor_pos, + neighbor, + ); + if new_state != state { + self.set_block(position, new_state, flags & !1) + .map_err(query)?; + } + let new_neighbor = self.shape_update( + behaviours, + neighbor, + neighbor_pos, + direction.opposite(), + position, + new_state, + ); + if new_neighbor != neighbor { + self.set_block(neighbor_pos, new_neighbor, flags & !1) + .map_err(query)?; + } + Ok(()) + } + fn update_from_neighbour_shapes( + &mut self, + position: [i32; 3], + flags: i32, + ) -> Result<(), PlacementQueryError> { + let Some(behaviours) = self.behaviours else { + return Ok(()); + }; + let state = self.region.block(position).map_err(query)?; + // Block.UPDATE_SHAPE_ORDER. + let mut new_state = state; + for direction in [ + Direction::West, + Direction::East, + Direction::North, + Direction::South, + Direction::Down, + Direction::Up, + ] { + let n = direction.normal(); + let neighbor_pos = [position[0] + n[0], position[1] + n[1], position[2] + n[2]]; + let neighbor = self.region.block(neighbor_pos).map_err(query)?; + new_state = self.shape_update( + behaviours, + new_state, + position, + direction, + neighbor_pos, + neighbor, + ); + } + if new_state != state { + self.set_block(position, new_state, flags).map_err(query)?; + } + Ok(()) + } fn ensure_can_write(&mut self, position: [i32; 3]) -> Result { Ok(self .zone diff --git a/crates/horizon-world/src/worldgen/placement/context.rs b/crates/horizon-world/src/worldgen/placement/context.rs index 227d890f1..1cfb98c81 100644 --- a/crates/horizon-world/src/worldgen/placement/context.rs +++ b/crates/horizon-world/src/worldgen/placement/context.rs @@ -39,6 +39,16 @@ pub trait PlacementContext { ) -> Result<(), PlacementQueryError> { Ok(()) } + /// Block.updateFromNeighbourShapes for the state at `position`, written + /// with `flags` when it changes. Worlds without block shape-update + /// behavior accept this as a no-op. + fn update_from_neighbour_shapes( + &mut self, + _position: [i32; 3], + _flags: i32, + ) -> Result<(), PlacementQueryError> { + Ok(()) + } /// WorldGenRegion.ensureCanWrite: horizontal write radius and upgrade height. fn ensure_can_write(&mut self, _position: [i32; 3]) -> Result { Ok(true) diff --git a/crates/horizon-world/src/worldgen/structure/jigsaw.rs b/crates/horizon-world/src/worldgen/structure/jigsaw.rs index d78c12f57..f360e6a4e 100644 --- a/crates/horizon-world/src/worldgen/structure/jigsaw.rs +++ b/crates/horizon-world/src/worldgen/structure/jigsaw.rs @@ -483,9 +483,12 @@ fn place_element( }) }; let mut settings = PlaceSettings::new(rotation); + settings.known_shape = true; settings.bounding_box = Some(chunk_box); settings.waterlogging = override_liquid.unwrap_or(waterlogging); - settings.processors.push(ignore); + if !*legacy { + settings.processors.push(ignore); + } settings.processors.push(&Processor::JigsawReplacement); settings.processors.extend(processors.0.iter()); if *projection == Projection::TerrainMatching { @@ -496,6 +499,11 @@ fn place_element( offset: -1, })); } + // LegacySinglePoolElement pops the structure-block ignore and + // appends STRUCTURE_AND_AIR last, after jigsaw replacement. + if *legacy { + settings.processors.push(ignore); + } place_in_world( world, resources, diff --git a/crates/horizon-world/src/worldgen/structure/processor.rs b/crates/horizon-world/src/worldgen/structure/processor.rs index 45fb5c36e..728658bfe 100644 --- a/crates/horizon-world/src/worldgen/structure/processor.rs +++ b/crates/horizon-world/src/worldgen/structure/processor.rs @@ -314,6 +314,9 @@ pub struct PlaceSettings<'a> { pub processors: Vec<&'a Processor>, pub waterlogging: bool, pub random: Option<&'a mut dyn ProcessorRandom>, + /// StructurePlaceSettings.knownShape: skip the neighbor shape updates + /// after placement (jigsaw pieces). + pub known_shape: bool, } impl<'a> PlaceSettings<'a> { pub fn new(rotation: Rotation) -> Self { @@ -325,6 +328,7 @@ impl<'a> PlaceSettings<'a> { processors: Vec::new(), waterlogging: true, random: None, + known_shape: false, } } pub fn with_processors(mut self, list: &'a ProcessorList) -> Self { @@ -746,6 +750,7 @@ pub fn place_in_world( .unwrap(); let mut to_fill = Vec::new(); let mut locked = Vec::new(); + let mut placed = Vec::new(); let world_err = |_| PlacementQueryError::Failed("template write".into()); for info in infos { if settings @@ -769,6 +774,7 @@ pub fn place_in_world( if !world.set_block(info.pos, state, flags).map_err(world_err)? { continue; } + placed.push(info.pos); if let Some(mut nbt) = info.nbt { if resources.transforms.loot_container(state) { let seed = match loot_random.as_deref_mut() { @@ -820,5 +826,87 @@ pub fn place_in_world( } to_fill = remaining; } + if !settings.known_shape && !placed.is_empty() { + update_shape_at_edge(world, &placed, flags)?; + for &pos in &placed { + world.update_from_neighbour_shapes(pos, flags & !1 | 16)?; + } + } Ok(true) } + +/// StructureTemplate.updateShapeAtEdge over the placed positions' voxel +/// shape (DiscreteVoxelShape.forAllFaces order: X-Y rows along Z, then +/// Z-X rows along Y, then Y-Z rows along X). +fn update_shape_at_edge( + world: &mut W, + placed: &[[i32; 3]], + flags: i32, +) -> Result<(), PlacementQueryError> { + use horizon_core::geometry::Direction; + let mut min = placed[0]; + let mut max = placed[0]; + for p in placed { + for i in 0..3 { + min[i] = min[i].min(p[i]); + max[i] = max[i].max(p[i]); + } + } + let size: [i32; 3] = std::array::from_fn(|i| max[i] - min[i] + 1); + let index = |[x, y, z]: [i32; 3]| ((x * size[1] + y) * size[2] + z) as usize; + let mut bits = vec![false; size.iter().map(|v| *v as usize).product()]; + for p in placed { + bits[index(std::array::from_fn(|i| p[i] - min[i]))] = true; + } + let full = |p: [i32; 3]| (0..3).all(|i| (0..size[i]).contains(&p[i])) && bits[index(p)]; + type Map = fn(i32, i32, i32) -> [i32; 3]; + let passes: [(Direction, Direction, i32, i32, i32, Map); 3] = [ + ( + Direction::North, + Direction::South, + size[0], + size[1], + size[2], + |a, b, c| [a, b, c], + ), + ( + Direction::Down, + Direction::Up, + size[2], + size[0], + size[1], + |a, b, c| [b, c, a], + ), + ( + Direction::West, + Direction::East, + size[1], + size[2], + size[0], + |a, b, c| [c, a, b], + ), + ]; + for (negative, positive, a_size, b_size, c_size, map) in passes { + for a in 0..a_size { + for b in 0..b_size { + let mut last = false; + for c in 0..=c_size { + let here = c != c_size && full(map(a, b, c)); + let face = if !last && here { + Some((negative, map(a, b, c))) + } else if last && !here { + Some((positive, map(a, b, c - 1))) + } else { + None + }; + if let Some((direction, local)) = face { + let p = std::array::from_fn(|i| min[i] + local[i]); + world.update_shape_at_face(p, direction, flags)?; + } + last = here; + } + } + } + } + Ok(()) +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructurePlacementOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructurePlacementOracle.java index 3376f92ac..7c1462676 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructurePlacementOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructurePlacementOracle.java @@ -45,6 +45,26 @@ import net.minecraft.world.level.storage.LevelStorageSource; public final class VanillaStructurePlacementOracle { private static final class Ignored extends RuntimeException {} + /** + * Allocated without a constructor: no feature flags are enabled, so + * EntityType.create returns null and structure entities are skipped as + * Horizon skips them, while block placement continues. + */ + private static final class NoEntityLevel extends net.minecraft.server.level.ServerLevel { + private NoEntityLevel() { + super(null, null, null, null, null, null, false, 0L, null, false); + } + static long seed; + @Override + public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { + return net.minecraft.world.flag.FeatureFlagSet.of(); + } + @Override + public long getSeed() { + return seed; + } + } + public static void main(String[] args) throws Exception { SharedConstants.tryDetectVersion();Bootstrap.bootStrap(); Path out=Path.of(args[0]);long seed=Long.parseLong(args[1]);String dimension=args[2]; @@ -76,6 +96,9 @@ public final class VanillaStructurePlacementOracle { var climate=randomState.createClimateSampler(net.minecraft.world.level.levelgen.densityfunction.SamplerContext.builder().enableCaches().build()); var structures=world.lookupOrThrow(Registries.STRUCTURE); var factory=PalettedContainerFactory.create(access); + var unsafeField=Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");unsafeField.setAccessible(true);Object unsafe=unsafeField.get(null); + NoEntityLevel.seed=seed; + var noEntities=(net.minecraft.server.level.ServerLevel)unsafe.getClass().getMethod("allocateInstance",Class.class).invoke(unsafe,NoEntityLevel.class); try(var w=new PrintWriter(Files.newBufferedWriter(out,StandardCharsets.UTF_8))) { for(int t=3;tnet.minecraft.world.level.dimension.BuiltinDimensionTypes.NETHER;case "the_end"->net.minecraft.world.level.dimension.BuiltinDimensionTypes.END;default->net.minecraft.world.level.dimension.BuiltinDimensionTypes.OVERWORLD;}).value(); @@ -223,6 +246,7 @@ public final class VanillaStructurePlacementOracle { for(var e:entities.values()) { var p=e.getBlockPos();String table="-",lootSeed="-"; if(e instanceof RandomizableContainer rc&&rc.getLootTable()!=null){table=rc.getLootTable().identifier().toString();lootSeed=Long.toString(rc.getLootTableSeed());} + if(e instanceof net.minecraft.world.level.block.entity.BrushableBlockEntity){try{var f=e.getClass().getDeclaredField("lootTable");f.setAccessible(true);var key=(net.minecraft.resources.ResourceKey)f.get(e);var s=e.getClass().getDeclaredField("lootTableSeed");s.setAccessible(true);if(key!=null){table=key.identifier().toString();lootSeed=Long.toString(s.getLong(e));}}catch(ReflectiveOperationException ex){throw new RuntimeException(ex);}} w.println("be "+p.getX()+" "+p.getY()+" "+p.getZ()+" "+BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(e.getType())+" "+table+" "+lootSeed); } } diff --git a/tools/compare_structure_blocks.py b/tools/compare_structure_blocks.py index 2b0d1b162..92966b21d 100644 --- a/tools/compare_structure_blocks.py +++ b/tools/compare_structure_blocks.py @@ -52,7 +52,9 @@ def parse(lines): elif t[0] == 'y' and current: chunks[current]['rows'][int(t[1])] = t[2:] elif t[0] == 'be' and current: - chunks[current]['be'].append(' '.join(t[1:])) + # Position, loot table and seed; the block entity type follows + # from the (separately compared) block state. + chunks[current]['be'].append(' '.join(t[1:4] + t[5:])) return chunks @@ -77,6 +79,7 @@ def main(): check=True, cwd=lab.ROOT) rust_out = subprocess.run([str(lab.ROOT/'target/fast/examples/structure_blocks'), resources, seed, dimension, *targets], check=True, capture_output=True, text=True).stdout + (build_dir()/'rust.txt').write_text(rust_out) rust = parse(rust_out.splitlines()) names = state_names(resources) failed = 0