diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFitPinTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFitPinTest.java new file mode 100644 index 000000000..98929ec6a --- /dev/null +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFitPinTest.java @@ -0,0 +1,574 @@ +package art.arcane.iris.nativegen; + +import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord; +import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; +import com.mojang.datafixers.util.Either; +import net.minecraft.SharedConstants; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderSet; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.server.Bootstrap; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.WorldGenLevel; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.Rotation; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.GenerationStep; +import net.minecraft.world.level.levelgen.structure.BoundingBox; +import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece; +import net.minecraft.world.level.levelgen.structure.Structure; +import net.minecraft.world.level.levelgen.structure.StructurePiece; +import net.minecraft.world.level.levelgen.structure.StructureStart; +import net.minecraft.world.level.levelgen.structure.TerrainAdjustment; +import net.minecraft.world.level.levelgen.structure.pieces.PiecesContainer; +import net.minecraft.world.level.levelgen.structure.pools.JigsawJunction; +import net.minecraft.world.level.levelgen.structure.pools.LegacySinglePoolElement; +import net.minecraft.world.level.levelgen.structure.pools.SinglePoolElement; +import net.minecraft.world.level.levelgen.structure.pools.StructurePoolElement; +import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool; +import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidPiece; +import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidStructure; +import net.minecraft.world.level.levelgen.structure.templatesystem.LiquidSettings; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorList; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.IntBinaryOperator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Pins the blocks the native structure fit leaves in one decorated chunk for each terrain mode, so the fit can move + * without changing what a world generates. Every scenario builds an uneven terrain with water, caves, ores and trees, + * starts with real pieces and inline templates, and fit records written the way ownership records persist them. It + * then runs the chunk's fit in the generator's order (terrain fitting for every start, then each start's pieces and + * stilts, then the foundation repair) with a fixed stand-in for the platform's piece placement, and hashes every block + * that differs from the untouched terrain. + */ +public class NativeStructureFitPinTest { + private static final long WORLD_SEED = 8675309L; + private static final int SEA_LEVEL = 61; + private static final BoundingBox CHUNK_AREA = new BoundingBox(0, -63, 0, 15, 318, 15); + private static final String NO_STILTS = "null"; + private static final String SOURCE_TERRAIN = "{}"; + + private static final Map PINNED = Map.ofEntries( + Map.entry("encase", "1371:5448f4c7083265eaa032022d"), + Map.entry("source-bury", "1662:a826097850d8e5e4ebe324d7"), + Map.entry("source-encapsulate", "4907:206093fc3b11fe5e4678a04d"), + Map.entry("source-beard", "721:bc95c2ac5138738846f342fd"), + Map.entry("vacuum", "667:302305ab38330cc32cd42123"), + Map.entry("carve", "11573:7c238685fe13c6a7c115863c"), + Map.entry("stilts", "903:9c949d85eb9882f87f478478") + ); + + @BeforeClass + public static void bootstrapMinecraft() { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + } + + @Test + public void everyScenarioLeavesThePinnedBlocks() throws Exception { + Map actual = new LinkedHashMap<>(); + actual.put("encase", fit(encase())); + actual.put("source-bury", fit(sourceBury())); + actual.put("source-encapsulate", fit(sourceEncapsulate())); + actual.put("source-beard", fit(sourceBeard())); + actual.put("vacuum", fit(vacuum())); + actual.put("carve", fit(carve())); + actual.put("stilts", fit(stilts())); + StringBuilder report = new StringBuilder(); + actual.forEach((name, hash) -> report.append(" Map.entry(\"").append(name) + .append("\", \"").append(hash).append("\"),\n")); + assertEquals("Pinned fit hashes changed:\n" + report, PINNED, actual); + } + + @Test + public void everyScenarioChangesTheTerrain() throws Exception { + for (Scenario scenario : List.of(encase(), sourceBury(), sourceEncapsulate(), sourceBeard(), vacuum(), carve(), stilts())) { + String hash = fit(scenario); + assertTrue(scenario.name() + " left the terrain untouched", !hash.startsWith("0:")); + } + } + + private static String fit(Scenario scenario) throws Exception { + TerrainWorld terrain = new TerrainWorld(); + WorldGenLevel world = terrain.level(); + fitChunk(world, scenario); + return terrain.changedBlocksHash(CHUNK_AREA); + } + + /** The chunk's fit in the order the generators run it; the platform's placement is {@link #placePieces}. */ + private static void fitChunk(WorldGenLevel world, Scenario scenario) { + IntBinaryOperator surface = TerrainWorld::surfaceY; + List targets = new ArrayList<>(); + List decisions = new ArrayList<>(); + for (FitTarget target : scenario.targets()) { + IrisNativeStructureDecision decision = new NativeStructureOwnershipRecord.DecisionSnapshot( + target.stiltJson(), target.terrainJson()).restore(); + decisions.add(decision); + targets.add(new NativeStructureTerrainIntegrator.TerrainTarget(target.structureId(), target.start(), + NativeStructureTerrainIntegrator.resolveNativeTerrain(target.start(), decision.terrain()))); + } + NativeStructureSurfaceFitter.VacuumFoundationPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures( + world, CHUNK_AREA, targets, surface); + NativeStructurePostProcessor.prepareTerrain(world, CHUNK_AREA, targets, NativeStructureFitPinTest::noPalette); + for (int index = 0; index < targets.size(); index++) { + FitTarget target = scenario.targets().get(index); + placePieces(world, target); + if (decisions.get(index).stilt() != null) { + NativeStructureFoundationBuilder.placeStilts(world, CHUNK_AREA, target.structureId(), target.start(), + decisions.get(index).stilt(), NativeStructureFitPinTest::noPalette, surface, + !NativeStructureVegetationClearer.isUndergroundStep(target.start().getStructure().step())); + } + } + NativeStructureSurfaceFitter.repairVacuumFoundations(world, CHUNK_AREA, plan); + } + + private static BlockState noPalette(Object palette, Object rng, int x, int y, int z) { + throw new AssertionError("The pinned scenarios use the default fill blocks, never a palette"); + } + + /** + * A fixed stand-in for the platform placing a start's pieces in the chunk: template pieces write their template + * blocks turned with the piece (jigsaws as air, structure voids not at all), other pieces a sandstone floor and + * walls. Only blocks inside the chunk are written, as the platform clips them. + */ + private static void placePieces(WorldGenLevel world, FitTarget target) { + BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); + for (StructurePiece piece : target.start().getPieces()) { + List blocks = target.templates().get(piece); + if (blocks == null) { + placeShell(world, piece.getBoundingBox(), position); + continue; + } + PoolElementStructurePiece poolPiece = (PoolElementStructurePiece) piece; + StructurePlaceSettings settings = new StructurePlaceSettings().setRotation(poolPiece.getRotation()); + for (StructureTemplate.StructureBlockInfo block : blocks) { + if (block.state().is(Blocks.STRUCTURE_VOID)) { + continue; + } + BlockPos at = poolPiece.getPosition().offset(StructureTemplate.calculateRelativePosition(settings, block.pos())); + if (!CHUNK_AREA.isInside(at)) { + continue; + } + BlockState state = block.state().is(Blocks.JIGSAW) + ? Blocks.AIR.defaultBlockState() : block.state().rotate(poolPiece.getRotation()); + world.setBlock(position.set(at), state, 2); + } + } + } + + private static void placeShell(WorldGenLevel world, BoundingBox box, BlockPos.MutableBlockPos position) { + for (int x = box.minX(); x <= box.maxX(); x++) { + for (int z = box.minZ(); z <= box.maxZ(); z++) { + for (int y = box.minY(); y <= Math.min(box.maxY(), box.minY() + 3); y++) { + boolean wall = x == box.minX() || x == box.maxX() || z == box.minZ() || z == box.maxZ(); + if ((y == box.minY() || wall) && CHUNK_AREA.isInside(position.set(x, y, z))) { + world.setBlock(position, Blocks.SANDSTONE.defaultBlockState(), 2); + } + } + } + } + } + + private static Scenario encase() { + return new Scenario("encase", List.of( + pyramid("minecraft:stronghold", GenerationStep.Decoration.STRONGHOLDS, TerrainAdjustment.BURY, 2, 2, 14, + NO_STILTS, "{\"mode\":\"ENCASE\",\"horizontalPadding\":2,\"ceilingPadding\":2,\"floorPadding\":1}"), + pyramid("minecraft:trial_chambers", GenerationStep.Decoration.UNDERGROUND_STRUCTURES, TerrainAdjustment.ENCAPSULATE, + 4, -12, -8, NO_STILTS, "{\"mode\":\"ENCASE\"}"))); + } + + private static Scenario sourceBury() { + TemplateStart start = new TemplateStart("minecraft:ancient_city", GenerationStep.Decoration.UNDERGROUND_STRUCTURES, + TerrainAdjustment.BURY); + PoolElementStructurePiece room = start.single(room(7, 5, 7), new BoundingBox(2, 30, 2, 8, 34, 8), 1, Rotation.NONE); + room.addJunction(new JigsawJunction(5, 31, 9, 0, StructureTemplatePool.Projection.RIGID)); + start.single(path(3, 5), new BoundingBox(6, 31, 9, 8, 31, 13), 0, Rotation.NONE, + StructureTemplatePool.Projection.TERRAIN_MATCHING); + start.legacy(airPocket(4, 4, 4), new BoundingBox(10, 28, 10, 13, 31, 13), 1, Rotation.NONE); + start.single(room(5, 6, 4), new BoundingBox(1, 58, 11, 5, 63, 14), 1, Rotation.NONE); + return new Scenario("source-bury", List.of(start.target(NO_STILTS, SOURCE_TERRAIN))); + } + + private static Scenario sourceEncapsulate() { + return new Scenario("source-encapsulate", List.of( + pyramid("minecraft:ocean_ruin_cold", GenerationStep.Decoration.SURFACE_STRUCTURES, TerrainAdjustment.ENCAPSULATE, + -3, 1, 55, NO_STILTS, SOURCE_TERRAIN))); + } + + private static Scenario sourceBeard() { + TemplateStart village = new TemplateStart("minecraft:village_plains", GenerationStep.Decoration.SURFACE_STRUCTURES, + TerrainAdjustment.BEARD_THIN); + PoolElementStructurePiece house = village.single(room(6, 6, 6), new BoundingBox(1, 64, 1, 6, 69, 6), 1, Rotation.NONE); + house.addJunction(new JigsawJunction(7, 63, 3, 0, StructureTemplatePool.Projection.TERRAIN_MATCHING)); + PoolElementStructurePiece road = village.single(path(3, 8), new BoundingBox(7, 63, 2, 9, 63, 9), 0, Rotation.NONE, + StructureTemplatePool.Projection.TERRAIN_MATCHING); + road.addJunction(new JigsawJunction(8, 63, 10, 0, StructureTemplatePool.Projection.RIGID)); + village.single(room(5, 5, 5), new BoundingBox(9, 60, 9, 13, 64, 13), 1, Rotation.NONE); + village.single(floor(3, 3), new BoundingBox(10, 62, 10, 12, 66, 12), 1, Rotation.NONE); + village.legacy(airPocket(3, 3, 3), new BoundingBox(2, 65, 11, 4, 67, 13), 1, Rotation.NONE); + return new Scenario("source-beard", List.of( + village.target(NO_STILTS, SOURCE_TERRAIN), + pyramid("minecraft:desert_pyramid", GenerationStep.Decoration.SURFACE_STRUCTURES, TerrainAdjustment.BEARD_BOX, + -14, 9, 61, NO_STILTS, SOURCE_TERRAIN))); + } + + private static Scenario vacuum() { + TemplateStart village = new TemplateStart("minecraft:village_taiga", GenerationStep.Decoration.SURFACE_STRUCTURES, + TerrainAdjustment.NONE); + PoolElementStructurePiece houseA = village.single(room(5, 5, 5), new BoundingBox(2, 68, 2, 6, 72, 6), 1, Rotation.NONE); + houseA.addJunction(new JigsawJunction(7, 66, 6, 0, StructureTemplatePool.Projection.RIGID)); + village.single(voidedRoom(4, 4, 4), new BoundingBox(9, 65, 8, 12, 68, 11), 1, Rotation.CLOCKWISE_90); + village.single(path(2, 6), new BoundingBox(7, 64, 1, 8, 64, 6), 0, Rotation.NONE, + StructureTemplatePool.Projection.TERRAIN_MATCHING); + village.single(room(4, 3, 4), new BoundingBox(13, 70, 12, 16, 72, 15), 1, Rotation.NONE); + return new Scenario("vacuum", List.of( + village.target(NO_STILTS, "{\"mode\":\"VACUUM\"}"), + pyramid("minecraft:igloo", GenerationStep.Decoration.SURFACE_STRUCTURES, TerrainAdjustment.BEARD_THIN, + 8, -10, 64, NO_STILTS, "{\"mode\":\"PRESERVE\"}"))); + } + + private static Scenario carve() { + TemplateStart eroded = new TemplateStart("minecraft:mineshaft", GenerationStep.Decoration.UNDERGROUND_STRUCTURES, + TerrainAdjustment.NONE); + eroded.single(room(6, 5, 6), new BoundingBox(3, 2, 3, 8, 6, 8), 1, Rotation.NONE); + eroded.single(voidedRoom(4, 4, 4), new BoundingBox(9, 4, 2, 12, 7, 5), 1, Rotation.NONE); + return new Scenario("carve", List.of( + eroded.target(NO_STILTS, "{\"mode\":\"FORCE_CARVE\",\"shape\":\"ERODED\",\"horizontalPadding\":6," + + "\"ceilingPadding\":4,\"floorPadding\":1,\"erosionStrength\":0.9,\"erosionFrequency\":0.08,\"lobeStrength\":0.7}"), + pyramid("minecraft:buried_treasure", GenerationStep.Decoration.UNDERGROUND_STRUCTURES, TerrainAdjustment.NONE, + -6, 4, 30, NO_STILTS, "{\"mode\":\"BORE\",\"horizontalPadding\":2,\"ceilingPadding\":3}"), + pyramid("minecraft:trail_ruins", GenerationStep.Decoration.UNDERGROUND_STRUCTURES, TerrainAdjustment.NONE, + 2, -9, -40, NO_STILTS, "{\"mode\":\"FORCE_CARVE\",\"shape\":\"ROUNDED\",\"horizontalPadding\":3," + + "\"ceilingPadding\":2,\"floorPadding\":2}"), + pyramid("minecraft:swamp_hut", GenerationStep.Decoration.UNDERGROUND_STRUCTURES, TerrainAdjustment.NONE, + -10, -2, 44, NO_STILTS, "{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":1,\"floorPadding\":1}"))); + } + + private static Scenario stilts() { + TemplateStart hut = new TemplateStart("minecraft:pillager_outpost", GenerationStep.Decoration.SURFACE_STRUCTURES, + TerrainAdjustment.NONE); + hut.single(room(5, 4, 5), new BoundingBox(9, 71, 1, 13, 74, 5), 1, Rotation.NONE); + hut.single(floor(4, 4), new BoundingBox(1, 69, 10, 4, 72, 13), 1, Rotation.COUNTERCLOCKWISE_90); + return new Scenario("stilts", List.of( + pyramid("minecraft:jungle_pyramid", GenerationStep.Decoration.SURFACE_STRUCTURES, TerrainAdjustment.NONE, + -12, -14, 70, "{\"maxDepth\":16,\"spacing\":2,\"palette\":null}", "{\"mode\":\"PRESERVE\"}"), + pyramid("minecraft:stronghold", GenerationStep.Decoration.STRONGHOLDS, TerrainAdjustment.NONE, + -2, -3, 24, "{\"maxDepth\":6,\"spacing\":1,\"palette\":null}", "{\"mode\":\"PRESERVE\"}"), + hut.target("{\"maxDepth\":64,\"spacing\":1,\"palette\":null}", "{\"mode\":\"VACUUM\"}"))); + } + + private static FitTarget pyramid(String structureId, GenerationStep.Decoration step, TerrainAdjustment adjustment, + int x, int z, int minY, String stiltJson, String terrainJson) { + StructurePiece piece = new DesertPyramidPiece(RandomSource.create(7L), x, z); + piece.move(0, minY - piece.getBoundingBox().minY(), 0); + StructureStart start = new StructureStart(structure(step, adjustment), new ChunkPos(0, 0), 0, + new PiecesContainer(List.of(piece))); + return new FitTarget(structureId, start, Map.of(), stiltJson, terrainJson); + } + + private static Structure structure(GenerationStep.Decoration step, TerrainAdjustment adjustment) { + return new DesertPyramidStructure(new Structure.StructureSettings(HolderSet.empty(), Map.of(), step, adjustment)); + } + + /** A room: a stone floor, plank walls with a doorway and a glass window, air inside, a slab roof. */ + private static List room(int width, int height, int depth) { + List blocks = new ArrayList<>(); + for (int x = 0; x < width; x++) { + for (int z = 0; z < depth; z++) { + for (int y = 0; y < height; y++) { + boolean wall = x == 0 || z == 0 || x == width - 1 || z == depth - 1; + BlockState state; + if (y == 0) { + state = Blocks.COBBLESTONE.defaultBlockState(); + } else if (y == height - 1) { + state = Blocks.OAK_SLAB.defaultBlockState(); + } else if (wall && x == width / 2 && z == 0 && y < 3) { + state = Blocks.AIR.defaultBlockState(); + } else if (wall) { + state = y == 2 && z == depth / 2 ? Blocks.GLASS.defaultBlockState() : Blocks.OAK_PLANKS.defaultBlockState(); + } else { + state = Blocks.AIR.defaultBlockState(); + } + blocks.add(block(x, y, z, state)); + } + } + } + return blocks; + } + + /** A room whose middle columns are structure void and whose corner holds a jigsaw. */ + private static List voidedRoom(int width, int height, int depth) { + List blocks = new ArrayList<>(); + for (StructureTemplate.StructureBlockInfo block : room(width, height, depth)) { + BlockPos pos = block.pos(); + boolean middle = pos.getX() > 0 && pos.getX() < width - 1 && pos.getZ() > 0 && pos.getZ() < depth - 1; + if (middle && pos.getY() > 0) { + blocks.add(block(pos.getX(), pos.getY(), pos.getZ(), Blocks.STRUCTURE_VOID.defaultBlockState())); + } else if (pos.getX() == 0 && pos.getZ() == 0 && pos.getY() == 0) { + blocks.add(block(0, 0, 0, Blocks.JIGSAW.defaultBlockState())); + } else { + blocks.add(block); + } + } + return blocks; + } + + private static List path(int width, int depth) { + List blocks = new ArrayList<>(); + for (int x = 0; x < width; x++) { + for (int z = 0; z < depth; z++) { + blocks.add(block(x, 0, z, Blocks.DIRT_PATH.defaultBlockState())); + } + } + return blocks; + } + + private static List floor(int width, int depth) { + List blocks = new ArrayList<>(); + for (int x = 0; x < width; x++) { + for (int z = 0; z < depth; z++) { + blocks.add(block(x, 0, z, (x + z) % 2 == 0 ? Blocks.STONE_BRICKS.defaultBlockState() : Blocks.MOSSY_COBBLESTONE.defaultBlockState())); + } + } + return blocks; + } + + private static List airPocket(int width, int height, int depth) { + List blocks = new ArrayList<>(); + for (int x = 0; x < width; x++) { + for (int z = 0; z < depth; z++) { + for (int y = 0; y < height; y++) { + blocks.add(block(x, y, z, y == 0 && x == 0 ? Blocks.BRICKS.defaultBlockState() : Blocks.AIR.defaultBlockState())); + } + } + } + return blocks; + } + + private static StructureTemplate.StructureBlockInfo block(int x, int y, int z, BlockState state) { + return new StructureTemplate.StructureBlockInfo(new BlockPos(x, y, z), state, null); + } + + private static StructureTemplate template(List blocks) { + try { + Constructor constructor = + StructureTemplate.Palette.class.getDeclaredConstructor(List.class); + if (!constructor.trySetAccessible()) { + throw new IllegalStateException("StructureTemplate.Palette is not accessible"); + } + StructureTemplate template = new StructureTemplate(); + template.palettes.add(constructor.newInstance(blocks)); + return template; + } catch (ReflectiveOperationException error) { + throw new IllegalStateException(error); + } + } + + private record Scenario(String name, List targets) { + } + + /** A start in the chunk with its fit as an ownership record persists it, and the template blocks of its pieces. */ + private record FitTarget(String structureId, StructureStart start, + Map> templates, + String stiltJson, String terrainJson) { + } + + /** Builds a jigsaw start from template pieces, remembering each piece's template blocks for the placement stand-in. */ + private static final class TemplateStart { + private final String structureId; + private final Structure structure; + private final List pieces = new ArrayList<>(); + private final Map> templates = new IdentityHashMap<>(); + + private TemplateStart(String structureId, GenerationStep.Decoration step, TerrainAdjustment adjustment) { + this.structureId = structureId; + this.structure = structure(step, adjustment); + } + + PoolElementStructurePiece single(List blocks, BoundingBox bounds, + int groundLevelDelta, Rotation rotation) { + return single(blocks, bounds, groundLevelDelta, rotation, StructureTemplatePool.Projection.RIGID); + } + + PoolElementStructurePiece single(List blocks, BoundingBox bounds, + int groundLevelDelta, Rotation rotation, + StructureTemplatePool.Projection projection) { + return add(new InlineSinglePoolElement(template(blocks), projection), blocks, bounds, groundLevelDelta, rotation); + } + + PoolElementStructurePiece legacy(List blocks, BoundingBox bounds, + int groundLevelDelta, Rotation rotation) { + return add(new InlineLegacyPoolElement(template(blocks)), blocks, bounds, groundLevelDelta, rotation); + } + + private PoolElementStructurePiece add(StructurePoolElement element, List blocks, + BoundingBox bounds, int groundLevelDelta, Rotation rotation) { + PoolElementStructurePiece piece = new PoolElementStructurePiece(null, element, + new BlockPos(bounds.minX(), bounds.minY(), bounds.minZ()), groundLevelDelta, rotation, bounds, + LiquidSettings.APPLY_WATERLOGGING); + pieces.add(piece); + templates.put(piece, blocks); + return piece; + } + + FitTarget target(String stiltJson, String terrainJson) { + StructureStart start = new StructureStart(structure, new ChunkPos(0, 0), 0, new PiecesContainer(List.copyOf(pieces))); + return new FitTarget(structureId, start, templates, stiltJson, terrainJson); + } + } + + private static final class InlineSinglePoolElement extends SinglePoolElement { + private InlineSinglePoolElement(StructureTemplate template, StructureTemplatePool.Projection projection) { + super(Either.right(template), Holder.direct(new StructureProcessorList(List.of())), projection, + Optional.empty()); + } + } + + private static final class InlineLegacyPoolElement extends LegacySinglePoolElement { + private InlineLegacyPoolElement(StructureTemplate template) { + super(Either.right(template), Holder.direct(new StructureProcessorList(List.of())), + StructureTemplatePool.Projection.RIGID, Optional.empty()); + } + } + + /** + * An uneven terrain computed per block, with the fit's writes kept on top: grass over dirt over stone (deepslate + * below 0), a sea at {@link #SEA_LEVEL}, a flooded cave and a dry cave, scattered iron ore and two trees. + */ + private static final class TerrainWorld { + private final Map written = new HashMap<>(); + + static int surfaceY(int x, int z) { + return 62 + (int) Math.round(3D * Math.sin(x * 0.35D) + 2D * Math.cos(z * 0.27D)); + } + + static BlockState natural(int x, int y, int z) { + int surface = surfaceY(x, z); + if (insideSphere(x, y, z, 8, 20, 8, 6)) { + return y <= 17 ? Blocks.WATER.defaultBlockState() : Blocks.AIR.defaultBlockState(); + } + if (insideSphere(x, y, z, 4, -6, 11, 4)) { + return Blocks.AIR.defaultBlockState(); + } + BlockState tree = tree(x, y, z); + if (tree != null) { + return tree; + } + if (y > surface) { + return y <= SEA_LEVEL ? Blocks.WATER.defaultBlockState() : Blocks.AIR.defaultBlockState(); + } + if (y == surface) { + return surface < SEA_LEVEL ? Blocks.SAND.defaultBlockState() : Blocks.GRASS_BLOCK.defaultBlockState(); + } + if (y >= surface - 3) { + return Blocks.DIRT.defaultBlockState(); + } + if (Math.floorMod(x + z, 11) == 0 && Math.floorMod(y, 7) == 0) { + return Blocks.IRON_ORE.defaultBlockState(); + } + return y < 0 ? Blocks.DEEPSLATE.defaultBlockState() : Blocks.STONE.defaultBlockState(); + } + + private static BlockState tree(int x, int y, int z) { + for (int[] trunk : new int[][]{{12, 3}, {5, 13}}) { + int base = surfaceY(trunk[0], trunk[1]); + if (base < SEA_LEVEL) { + continue; + } + if (x == trunk[0] && z == trunk[1] && y > base && y <= base + 4) { + return Blocks.OAK_LOG.defaultBlockState(); + } + if (Math.abs(x - trunk[0]) <= 1 && Math.abs(z - trunk[1]) <= 1 && y >= base + 4 && y <= base + 5 + && !(x == trunk[0] && z == trunk[1] && y == base + 4)) { + return Blocks.OAK_LEAVES.defaultBlockState(); + } + } + return null; + } + + private static boolean insideSphere(int x, int y, int z, int cx, int cy, int cz, int radius) { + int dx = x - cx; + int dy = y - cy; + int dz = z - cz; + return dx * dx + dy * dy + dz * dz <= radius * radius; + } + + BlockState get(int x, int y, int z) { + BlockState state = written.get(new BlockPos(x, y, z)); + return state == null ? natural(x, y, z) : state; + } + + /** The heightmap the platform's processors read: one above the highest block that is not air. */ + int heightmapY(int x, int z) { + for (int y = CHUNK_AREA.maxY(); y >= CHUNK_AREA.minY() - 1; y--) { + if (!get(x, y, z).isAir()) { + return y + 1; + } + } + return CHUNK_AREA.minY() - 1; + } + + WorldGenLevel level() { + InvocationHandler handler = (proxy, method, arguments) -> switch (method.getName()) { + case "getBlockState" -> { + BlockPos position = (BlockPos) arguments[0]; + yield get(position.getX(), position.getY(), position.getZ()); + } + case "setBlock" -> { + written.put(((BlockPos) arguments[0]).immutable(), (BlockState) arguments[1]); + yield true; + } + case "getSeed" -> WORLD_SEED; + case "getHeight" -> heightmapY((int) arguments[1], (int) arguments[2]); + case "getLevel" -> null; + case "holderLookup" -> BuiltInRegistries.BLOCK; + case "hashCode" -> System.identityHashCode(proxy); + case "equals" -> proxy == arguments[0]; + case "toString" -> "fit-pin-world"; + default -> throw new UnsupportedOperationException(method.toString()); + }; + return (WorldGenLevel) Proxy.newProxyInstance( + WorldGenLevel.class.getClassLoader(), new Class[]{WorldGenLevel.class}, handler); + } + + String changedBlocksHash(BoundingBox area) throws Exception { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + int changed = 0; + for (int x = area.minX(); x <= area.maxX(); x++) { + for (int z = area.minZ(); z <= area.maxZ(); z++) { + for (int y = area.minY(); y <= area.maxY(); y++) { + BlockState state = get(x, y, z); + if (state == natural(x, y, z)) { + continue; + } + changed++; + digest.update((x + "," + y + "," + z + "=" + state + "\n").getBytes(StandardCharsets.UTF_8)); + } + } + } + return changed + ":" + HexFormat.of().formatHex(digest.digest()).substring(0, 24); + } + } +} diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureLayoutPinTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureLayoutPinTest.java new file mode 100644 index 000000000..e6898a220 --- /dev/null +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureLayoutPinTest.java @@ -0,0 +1,190 @@ +package art.arcane.iris.nativegen; + +import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord; +import art.arcane.iris.engine.object.structure.IrisStructureYBand; +import com.google.gson.Gson; +import net.minecraft.SharedConstants; +import net.minecraft.core.HolderSet; +import net.minecraft.server.Bootstrap; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.levelgen.GenerationStep; +import net.minecraft.world.level.levelgen.structure.BoundingBox; +import net.minecraft.world.level.levelgen.structure.Structure; +import net.minecraft.world.level.levelgen.structure.StructurePiece; +import net.minecraft.world.level.levelgen.structure.StructureStart; +import net.minecraft.world.level.levelgen.structure.TerrainAdjustment; +import net.minecraft.world.level.levelgen.structure.pieces.PiecesContainer; +import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidPiece; +import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidStructure; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.IntBinaryOperator; + +import static org.junit.Assert.assertEquals; + +/** + * Pins where the platform's own starts end up vertically for each adjustment the dimension can give them (shift, + * band, keeping the platform's height, burial under the terrain), and which chunks a start reaches for each terrain + * fit, so both can move without changing what a world generates. + */ +public class NativeStructureLayoutPinTest { + private static final Gson GSON = new Gson(); + private static final int SEA_LEVEL = 61; + private static final int WORLD_MIN_Y = -64; + private static final int WORLD_MAX_Y_EXCLUSIVE = 320; + private static final IntBinaryOperator SURFACE = (x, z) -> 62 + Math.floorMod(x * 7 + z * 3, 11) - 5; + private static final int[][] CHUNKS = {{0, 0}, {3, -5}, {-11, 7}}; + + private static final List PINNED_SHIFTS = List.of( + "none minecraft:stronghold 0,0 offset 0 minY 50", + "none minecraft:desert_pyramid 0,0 offset -6 minY 58", + "none minecraft:stronghold 3,-5 offset 0 minY 50", + "none minecraft:desert_pyramid 3,-5 offset -6 minY 58", + "none minecraft:stronghold -11,7 offset 0 minY 50", + "none minecraft:desert_pyramid -11,7 offset -6 minY 58", + "shift minecraft:stronghold 0,0 offset 5 minY 55", + "shift minecraft:desert_pyramid 0,0 offset -1 minY 63", + "shift minecraft:stronghold 3,-5 offset 5 minY 55", + "shift minecraft:desert_pyramid 3,-5 offset -1 minY 63", + "shift minecraft:stronghold -11,7 offset 5 minY 55", + "shift minecraft:desert_pyramid -11,7 offset -1 minY 63", + "burial minecraft:stronghold 0,0 offset -8 minY 42", + "burial minecraft:desert_pyramid 0,0 offset -13 minY 51", + "burial minecraft:stronghold 3,-5 offset -8 minY 42", + "burial minecraft:desert_pyramid 3,-5 offset -13 minY 51", + "burial minecraft:stronghold -11,7 offset -8 minY 42", + "burial minecraft:desert_pyramid -11,7 offset -13 minY 51", + "burial-unshifted minecraft:stronghold 0,0 offset -8 minY 42", + "burial-unshifted minecraft:desert_pyramid 0,0 offset -6 minY 58", + "burial-unshifted minecraft:stronghold 3,-5 offset -8 minY 42", + "burial-unshifted minecraft:desert_pyramid 3,-5 offset -6 minY 58", + "burial-unshifted minecraft:stronghold -11,7 offset -8 minY 42", + "burial-unshifted minecraft:desert_pyramid -11,7 offset -6 minY 58", + "kept minecraft:stronghold 0,0 offset 3 minY 53", + "kept minecraft:desert_pyramid 0,0 offset -3 minY 61", + "kept minecraft:stronghold 3,-5 offset 3 minY 53", + "kept minecraft:desert_pyramid 3,-5 offset -3 minY 61", + "kept minecraft:stronghold -11,7 offset 3 minY 53", + "kept minecraft:desert_pyramid -11,7 offset -3 minY 61", + "band minecraft:stronghold 0,0 offset -94 minY -44", + "band minecraft:desert_pyramid 0,0 offset -6 minY 58", + "band minecraft:stronghold 3,-5 offset -58 minY -8", + "band minecraft:desert_pyramid 3,-5 offset -6 minY 58", + "band minecraft:stronghold -11,7 offset -96 minY -46", + "band minecraft:desert_pyramid -11,7 offset -6 minY 58", + "narrow-band minecraft:stronghold 0,0 offset -46 minY 4", + "narrow-band minecraft:desert_pyramid 0,0 offset -2 minY 62", + "narrow-band minecraft:stronghold 3,-5 offset -46 minY 4", + "narrow-band minecraft:desert_pyramid 3,-5 offset -2 minY 62", + "narrow-band minecraft:stronghold -11,7 offset -46 minY 4", + "narrow-band minecraft:desert_pyramid -11,7 offset -2 minY 62", + "kept-over-band minecraft:stronghold 0,0 offset 2 minY 52", + "kept-over-band minecraft:desert_pyramid 0,0 offset -4 minY 60", + "kept-over-band minecraft:stronghold 3,-5 offset 2 minY 52", + "kept-over-band minecraft:desert_pyramid 3,-5 offset -4 minY 60", + "kept-over-band minecraft:stronghold -11,7 offset 2 minY 52", + "kept-over-band minecraft:desert_pyramid -11,7 offset -4 minY 60"); + private static final List PINNED_REACHES = List.of( + "{} NONE 32,40,-48 52,54,-28", + "{} BEARD_THIN 20,28,-60 64,66,-16", + "{} BURY 20,28,-60 64,66,-16", + "{\"mode\":\"PRESERVE\"} NONE 32,40,-48 52,54,-28", + "{\"mode\":\"PRESERVE\"} BEARD_THIN 32,40,-48 52,54,-28", + "{\"mode\":\"PRESERVE\"} BURY 32,40,-48 52,54,-28", + "{\"mode\":\"VACUUM\"} NONE 20,40,-60 64,54,-16", + "{\"mode\":\"VACUUM\"} BEARD_THIN 20,40,-60 64,54,-16", + "{\"mode\":\"VACUUM\"} BURY 20,40,-60 64,54,-16", + "{\"mode\":\"ENCASE\",\"horizontalPadding\":4} NONE 28,40,-52 56,54,-24", + "{\"mode\":\"ENCASE\",\"horizontalPadding\":4} BEARD_THIN 28,40,-52 56,54,-24", + "{\"mode\":\"ENCASE\",\"horizontalPadding\":4} BURY 28,40,-52 56,54,-24", + "{\"mode\":\"BORE\",\"horizontalPadding\":20} NONE 12,40,-68 72,54,-8", + "{\"mode\":\"BORE\",\"horizontalPadding\":20} BEARD_THIN 12,40,-68 72,54,-8", + "{\"mode\":\"BORE\",\"horizontalPadding\":20} BURY 12,40,-68 72,54,-8", + "{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":112} NONE -80,40,-160 164,54,84", + "{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":112} BEARD_THIN -80,40,-160 164,54,84", + "{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":112} BURY -80,40,-160 164,54,84", + "{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":0} NONE 32,40,-48 52,54,-28", + "{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":0} BEARD_THIN 32,40,-48 52,54,-28", + "{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":0} BURY 32,40,-48 52,54,-28"); + + @BeforeClass + public static void bootstrapMinecraft() { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + } + + @Test + public void platformStartsMoveWhereTheirAdjustmentSays() { + List actual = new ArrayList<>(); + for (Adjustment adjustment : adjustments()) { + for (int[] chunkXZ : CHUNKS) { + ChunkPos chunk = new ChunkPos(chunkXZ[0], chunkXZ[1]); + for (String structureId : List.of("minecraft:stronghold", "minecraft:desert_pyramid")) { + StructureStart start = start(chunk, structureId.equals("minecraft:stronghold") ? 50 : 64, + TerrainAdjustment.NONE); + int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(start, structureId, + adjustment.yShift(), SEA_LEVEL, WORLD_MIN_Y, WORLD_MAX_Y_EXCLUSIVE, adjustment.underground(), + adjustment.keepsSourceY(), band(adjustment.bandJson()), SURFACE); + actual.add(adjustment.name() + " " + structureId + " " + chunk.x() + "," + chunk.z() + + " offset " + offset + " minY " + start.getBoundingBox().minY()); + } + } + } + assertEquals("Pinned shifts changed:\n" + String.join("\n", quoted(actual)), PINNED_SHIFTS, actual); + } + + @Test + public void startsReachTheChunksTheirTerrainFitSays() { + List actual = new ArrayList<>(); + for (String terrainJson : List.of("{}", "{\"mode\":\"PRESERVE\"}", "{\"mode\":\"VACUUM\"}", + "{\"mode\":\"ENCASE\",\"horizontalPadding\":4}", "{\"mode\":\"BORE\",\"horizontalPadding\":20}", + "{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":112}", "{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":0}")) { + for (TerrainAdjustment adjustment : List.of(TerrainAdjustment.NONE, TerrainAdjustment.BEARD_THIN, TerrainAdjustment.BURY)) { + StructureStart start = start(new ChunkPos(2, -3), 40, adjustment); + BoundingBox bounds = NativeStructureReferenceEnvelope.referenceBounds(start, start.getStructure(), + NativeStructureTerrainIntegrator.resolveNativeTerrain(start, + new NativeStructureOwnershipRecord.DecisionSnapshot("null", terrainJson).restore().terrain()), + "minecraft:village_plains"); + actual.add(terrainJson + " " + adjustment + " " + bounds.minX() + "," + bounds.minY() + "," + bounds.minZ() + + " " + bounds.maxX() + "," + bounds.maxY() + "," + bounds.maxZ()); + } + } + assertEquals("Pinned reaches changed:\n" + String.join("\n", quoted(actual)), PINNED_REACHES, actual); + } + + private static List quoted(List lines) { + return lines.stream().map(line -> " \"" + line.replace("\"", "\\\"") + "\",").toList(); + } + + private static List adjustments() { + return List.of( + new Adjustment("none", 0, null, false, false), + new Adjustment("shift", 5, null, false, false), + new Adjustment("burial", -7, null, false, true), + new Adjustment("burial-unshifted", 0, null, false, true), + new Adjustment("kept", 3, null, true, true), + new Adjustment("band", 0, "{\"min\":-50,\"max\":20}", false, true), + new Adjustment("narrow-band", 4, "{\"min\":10,\"max\":12}", false, false), + new Adjustment("kept-over-band", 2, "{\"min\":-40,\"max\":80}", true, false)); + } + + private static IrisStructureYBand band(String json) { + return json == null ? null : GSON.fromJson(json, IrisStructureYBand.class); + } + + private static StructureStart start(ChunkPos chunk, int minY, TerrainAdjustment adjustment) { + Structure structure = new DesertPyramidStructure(new Structure.StructureSettings( + HolderSet.empty(), Map.of(), GenerationStep.Decoration.SURFACE_STRUCTURES, adjustment)); + StructurePiece piece = new DesertPyramidPiece(RandomSource.create(7L), chunk.getMinBlockX(), chunk.getMinBlockZ()); + piece.move(0, minY - piece.getBoundingBox().minY(), 0); + return new StructureStart(structure, chunk, 0, new PiecesContainer(List.of(piece))); + } + + private record Adjustment(String name, int yShift, String bandJson, boolean keepsSourceY, boolean underground) { + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/object/placement/ObjectPlaceModePinTest.java b/core/src/test/java/art/arcane/iris/engine/object/placement/ObjectPlaceModePinTest.java new file mode 100644 index 000000000..0ff9e13fd --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/object/placement/ObjectPlaceModePinTest.java @@ -0,0 +1,301 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.BuiltInPack; +import art.arcane.iris.core.modules.ModuleObjectPlacement; +import art.arcane.iris.core.modules.PlatformBlockStates; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; +import art.arcane.iris.engine.object.prefab.TileData; +import art.arcane.iris.engine.object.terrain.carving.CarveResult; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.spi.IrisPlatform; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.spi.PlatformRegistries; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.host.LoadedPack; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Pins the blocks every object placement mode writes for one object on a fixed, uneven terrain with a cave ceiling + * above it, so the modes can move into other code without changing what a world generates. Each mode places the same + * object at the same column with the same seed; the writes, in order, are hashed. A mismatch prints every mode's hash. + */ +public class ObjectPlaceModePinTest { + private static final int OBJECT_X = 41; + private static final int OBJECT_Z = -24; + private static final int CEILING_Y = 110; + private static final int CAVE_FLOOR_Y = 70; + private static final long PLACEMENT_SEED = 1337L; + private static final long WORLD_SEED = 7L; + private static final int WORLD_HEIGHT = 256; + + private static final Map PINNED = pinned(); + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private final Map registryStates = new HashMap<>(); + private IrisData data; + private Engine engine; + private LoadedPack pack; + + @Before + public void bindPlatform() throws IOException { + IrisPlatforms.unbind(); + PlatformRegistries registries = mock(PlatformRegistries.class); + when(registries.block(anyString())).thenAnswer(invocation -> registryState(invocation.getArgument(0))); + IrisPlatform platform = mock(IrisPlatform.class); + when(platform.registries()).thenReturn(registries); + IrisPlatforms.bind(platform); + + engine = mock(Engine.class); + when(engine.getHeight()).thenReturn(WORLD_HEIGHT); + when(engine.getDimension()).thenReturn(mock(IrisDimension.class)); + BuiltInPack.seedWorld(engine, WORLD_SEED); + data = mock(IrisData.class); + when(data.getEngine()).thenReturn(engine); + pack = BuiltInPack.serve(data, folder, List.of()); + } + + @After + public void unbindPlatform() { + pack.close(); + IrisPlatforms.unbind(); + } + + @Test + public void everyModeWritesThePinnedBlocks() { + Map actual = new LinkedHashMap<>(); + for (ObjectPlaceMode mode : ObjectPlaceMode.values()) { + actual.put(mode, hash(place(mode))); + } + StringBuilder report = new StringBuilder(); + actual.forEach((mode, hash) -> report.append(" Map.entry(ObjectPlaceMode.").append(mode) + .append(", \"").append(hash).append("\"),\n")); + assertEquals("Pinned placement hashes changed:\n" + report, PINNED, actual); + } + + private List place(ObjectPlaceMode mode) { + TerrainPlacer placer = new TerrainPlacer(engine); + IrisObjectPlacement config = new IrisObjectPlacement(); + config.setMode(mode); + config.setRequireSurfaceSupport(false); + config.setTranslate(new IrisObjectTranslate().setY(mode == ObjectPlaceMode.FLOATING ? 140 : 2)); + CarveResult cave = isCaveMode(mode) ? new CarveResult(CAVE_FLOOR_Y, CEILING_Y) : null; + int requestedY = requestedY(mode); + ModuleObjectPlacement.place(pinnedObject(), OBJECT_X, requestedY, OBJECT_Z, placer, config, + new RNG(PLACEMENT_SEED), null, cave, data); + return placer.writes(); + } + + private static boolean isCaveMode(ObjectPlaceMode mode) { + return mode == ObjectPlaceMode.ORGANIC_STILT || mode == ObjectPlaceMode.CEILING_HANG; + } + + /** Cave modes and structure pieces are placed at a height, the way their callers place them; the rest sample. */ + private static int requestedY(ObjectPlaceMode mode) { + return switch (mode) { + case CEILING_HANG -> CEILING_Y - 9; + case ORGANIC_STILT -> CAVE_FLOOR_Y + 12; + case STRUCTURE_PIECE -> 90; + default -> -1; + }; + } + + /** A 5x4x5 object with a stepped, holed bottom, a mix of materials and an air pocket. */ + private IrisObject pinnedObject() { + IrisObject object = new IrisObject(5, 4, 5); + PlatformBlockState stone = registryState("minecraft:stone"); + PlatformBlockState planks = registryState("minecraft:oak_planks"); + PlatformBlockState glass = registryState("minecraft:glass"); + for (int x = 0; x < 5; x++) { + for (int z = 0; z < 5; z++) { + if ((x + z) % 4 != 3) { + object.setUnsigned(x, 0, z, (x * z) % 3 == 0 ? stone : planks); + } + for (int y = 1; y < 4; y++) { + boolean shell = x == 0 || x == 4 || z == 0 || z == 4 || y == 3; + if (shell && !(x == 2 && z == 0 && y < 3)) { + object.setUnsigned(x, y, z, y == 2 && (x == 0 || x == 4) ? glass : planks); + } + } + } + } + return object; + } + + private PlatformBlockState registryState(String key) { + String normalized = key.toLowerCase(); + String namespaced = normalized.contains(":") ? normalized : "minecraft:" + normalized; + return registryStates.computeIfAbsent(namespaced, value -> state(value, isSolidKey(value))); + } + + private static boolean isSolidKey(String key) { + return !key.contains("air") && !key.contains("water") && !key.contains("snow"); + } + + private static PlatformBlockState state(String key, boolean solid) { + PlatformBlockState state = mock(PlatformBlockState.class); + when(state.key()).thenReturn(key); + when(state.materialKey()).thenReturn(key); + when(state.isSolid()).thenReturn(solid); + when(state.isOccluding()).thenReturn(solid); + when(state.isAir()).thenReturn(key.contains("air")); + return state; + } + + private static String hash(List writes) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (String write : writes) { + digest.update(write.getBytes(StandardCharsets.UTF_8)); + digest.update((byte) '\n'); + } + return writes.size() + ":" + HexFormat.of().formatHex(digest.digest()).substring(0, 24); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + /** Uneven terrain: stone up to a height that changes with the column, air above, a stone roof from {@link #CEILING_Y}. */ + private static int terrainHeight(int x, int z) { + return 64 + Math.floorMod(x * 3 + z * 5, 7) - 3; + } + + private final class TerrainPlacer implements IObjectPlacer { + private final Engine engine; + private final Map written = new HashMap<>(); + private final List writes = new ArrayList<>(); + + private TerrainPlacer(Engine engine) { + this.engine = engine; + } + + List writes() { + return writes; + } + + @Override + public int getHighest(int x, int z, IrisData data) { + return terrainHeight(x, z); + } + + @Override + public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) { + return terrainHeight(x, z); + } + + @Override + public void set(int x, int y, int z, PlatformBlockState state) { + writes.add(x + "," + y + "," + z + "=" + PlatformBlockStates.namespaced(state.key())); + written.put(x + ":" + y + ":" + z, state); + } + + @Override + public PlatformBlockState get(int x, int y, int z) { + PlatformBlockState state = written.get(x + ":" + y + ":" + z); + if (state != null) { + return state; + } + return y <= terrainHeight(x, z) || y >= CEILING_Y ? registryState("minecraft:stone") : registryState("minecraft:air"); + } + + @Override + public boolean isPreventingDecay() { + return false; + } + + @Override + public boolean isCarved(int x, int y, int z) { + return false; + } + + @Override + public boolean isSolid(int x, int y, int z) { + return get(x, y, z).isSolid(); + } + + @Override + public boolean isUnderwater(int x, int z) { + return false; + } + + @Override + public int getFluidHeight() { + return 0; + } + + @Override + public boolean isDebugSmartBore() { + return false; + } + + @Override + public void setTile(int x, int y, int z, TileData tile) { + } + + @Override + public void setData(int x, int y, int z, T data) { + } + + @Override + public T getData(int x, int y, int z, Class type) { + return null; + } + + @Override + public Engine getEngine() { + return engine; + } + } + + private static Map pinned() { + return Map.ofEntries( + Map.entry(ObjectPlaceMode.CENTER_HEIGHT, "74:2502f2a09e5b13834de5ddfe"), + Map.entry(ObjectPlaceMode.MAX_HEIGHT, "74:3990440aae1bbacece06254f"), + Map.entry(ObjectPlaceMode.FAST_MAX_HEIGHT, "74:67a78ba6ece4c11e182d012b"), + Map.entry(ObjectPlaceMode.MIN_HEIGHT, "74:4f179fb8e183fb1d0dfd889e"), + Map.entry(ObjectPlaceMode.FAST_MIN_HEIGHT, "74:8e351f8c8df9e3665e5ddb3d"), + Map.entry(ObjectPlaceMode.STILT, "167:538fc49de1a5d3eac9bd5c9d"), + Map.entry(ObjectPlaceMode.FAST_STILT, "129:28fa04ed8d905af6c9bdd427"), + Map.entry(ObjectPlaceMode.MIN_STILT, "82:53c0de1267c70d8dd823cb83"), + Map.entry(ObjectPlaceMode.FAST_MIN_STILT, "90:1fb5736f3a271ce2e092944d"), + Map.entry(ObjectPlaceMode.CENTER_STILT, "113:1ce601c29f74e3a1f7bd5eb5"), + Map.entry(ObjectPlaceMode.ERODE_STILT, "81:c167e68ce8ffb1c1fafbd1e7"), + Map.entry(ObjectPlaceMode.ORGANIC_STILT, "306:dcc079da485dfbdbf7d9dbe4"), + Map.entry(ObjectPlaceMode.CEILING_HANG, "101:0b814f84a454fd06038c4af0"), + Map.entry(ObjectPlaceMode.VACUUM, "319:02e27e3e68f71e141022d6d3"), + Map.entry(ObjectPlaceMode.VACUUM_HIGH, "586:696ef3ec248ecaedbd22f66a"), + Map.entry(ObjectPlaceMode.VACUUM_FAST, "113:497ca8f7cec844d8d71c190f"), + Map.entry(ObjectPlaceMode.VACUUM_ORGANIC, "317:7c80d5296b018678983138aa"), + Map.entry(ObjectPlaceMode.VACUUM_WAVY, "528:709f4a142c37d361b73456cd"), + Map.entry(ObjectPlaceMode.PAINT, "74:c74db6c9f40eca3898f5f520"), + Map.entry(ObjectPlaceMode.FLOATING, "74:a117d1024b91539bb4700ed5"), + Map.entry(ObjectPlaceMode.STRUCTURE_PIECE, "74:c6c8aa8c3668f885320582ea") + ); + } +}