From 0b3556f09cccc3d4c61829bd7f402cfad65c4f89 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 03:50:45 +0200 Subject: [PATCH] Platform starts fit through a neutral bridge to iris:structure Core asks the pack's VanillaStructures providers (ModuleVanillaStructures) for rules, starts, the shift of each platform start and every module's reach, and runs the built-in fit through ModuleStructureFitting, which turns the platform's chunk into the API's StructureFit. minecraft-common's NativeStructureFitBridge hands Bukkit and the modded loaders' starts, processed template cells, template columns and legacy air to it; the platform helpers that held the fit (surface fitter, terrain integrator, support and foundation builders, post processor) are gone. The host only moves, clamps, wraps and places starts. Ownership records keep their binary layout: the two texts that held the stilts and terrain JSON now hold the start's memo, which the module writes in the same JSON, so records written before read the same. A recorded reference envelope only grows when today's reaches are wider. Tests: the fit's rules are tested in core against stated cells; the bridge and the fit end to end on the NMS harness; the object place mode and native structure fit pins stay identical. --- .../core/nms/v26_2_R1/IrisChunkGenerator.java | 120 +- ...IrisChunkGeneratorFailureContractTest.java | 20 +- ...nkGeneratorMonumentLocateContractTest.java | 29 +- .../nativegen/NativeStructureFactoryTest.java | 11 +- .../NativeStructureFitBridgeTest.java | 1218 +++++++++ .../nativegen/NativeStructureFitPinTest.java | 50 +- .../NativeStructureLayoutPinTest.java | 96 +- ...tiveStructureOwnershipFingerprintTest.java | 16 +- .../NativeStructureOwnershipRecoveryTest.java | 79 +- ...ativeStructurePostProcessorEncaseTest.java | 547 ---- ...iveStructurePostProcessorMonumentTest.java | 29 +- ...turePostProcessorScatteredFeatureTest.java | 26 +- ...ucturePostProcessorSurfaceTerrainTest.java | 2375 ----------------- ...eStructurePostProcessorVegetationTest.java | 15 - .../NativeStructureVolumeIndexTest.java | 4 +- .../iris/core/commands/CommandFind.java | 39 +- .../iris/core/commands/CommandStructure.java | 15 +- ...risStructureLocateCommandContractTest.java | 28 +- .../nativegen/NativeStructureFactory.java | 70 +- .../nativegen/NativeStructureFitBridge.java | 454 ++++ .../NativeStructureFoundationBuilder.java | 212 -- .../NativeStructureOwnershipFingerprint.java | 2 +- .../NativeStructureOwnershipRecovery.java | 59 +- .../NativeStructurePostProcessor.java | 66 - .../NativeStructureReferenceEnvelope.java | 69 +- .../NativeStructureReferenceRepair.java | 22 +- .../NativeStructureStartInjector.java | 17 +- .../NativeStructureSurfaceFitter.java | 921 ------- .../NativeStructureSurfaceSupportBuilder.java | 299 --- .../NativeStructureTemplateOccupancy.java | 64 +- .../NativeStructureTerrainIntegrator.java | 1096 -------- .../NativeStructureVerticalPlacer.java | 131 +- .../nativegen/NativeStructureVolumeIndex.java | 20 +- .../iris/modded/IrisModdedChunkGenerator.java | 2 +- .../modded/ModdedNativeStructureStage.java | 131 +- .../iris/modded/WorldCheckStiltAudit.java | 121 + .../iris/modded/WorldCheckStructureAudit.java | 23 +- .../command/ModdedCommandSuggestions.java | 15 +- .../modded/command/ModdedLocateCommands.java | 27 +- .../command/ModdedUnregisteredStructures.java | 11 +- .../NativeStructureFailureContractTest.java | 18 +- .../IrisModdedStructureCommandTest.java | 21 +- .../NativeStructureReferenceRepairTest.java | 42 +- .../NativeStructureVacuumParityTest.java | 81 +- build.gradle | 4 +- .../arcane/iris/core/modules/IrisValues.java | 40 +- .../core/modules/ModuleStructureFitting.java | 430 +++ .../core/modules/ModuleVanillaStructures.java | 183 +- .../framework/NativeJigsawOverrides.java | 21 + .../engine/framework/NativeStartMemo.java | 14 + .../framework/NativeStartPlacement.java | 31 + .../NativeStructureGenerationPolicy.java | 32 +- .../NativeStructureGenerationStatus.java | 26 + .../framework/NativeStructureLayouts.java | 29 + .../NativeStructureOwnershipRecord.java | 87 +- .../framework/NativeStructureReach.java | 10 + .../framework/NativeStructureStartPlan.java | 23 +- .../framework/nativefit/NativeFitBlocks.java | 29 + .../framework/nativefit/NativeFitBox.java | 5 + .../framework/nativefit/NativeFitChunk.java | 31 + .../framework/nativefit/NativeFitPiece.java | 29 + .../framework/nativefit/NativeFitStart.java | 28 + .../framework/nativefit/NativeFitTrait.java | 15 + .../nativefit/NativeStructureFitting.java | 32 + .../nativefit/NativeTemplateCells.java | 9 + .../specialhandlers/StructureHandler.java | 15 +- .../structure/StructureFitSettingsTest.java | 142 + .../PackBeforeThePortDecodingTest.java | 4 +- .../StructureSettingsDecodingTest.java | 33 +- .../core/project/SchemaBuilderParityTest.java | 29 +- .../IrisStructureLocatorContractTest.java | 29 +- .../NativeStructureGenerationPolicyTest.java | 134 +- .../NativeStructureOwnershipRecordTest.java | 102 +- .../NativeStructureOwnershipStoreTest.java | 29 +- .../framework/NativeStructureStartsTest.java | 33 +- .../NativeStructureVolumeSuppressionTest.java | 15 +- .../structure/ImportedStructuresTest.java | 64 +- .../structure/NativeStartPlannerTest.java | 30 +- .../framework/structure/fit/FitFixture.java | 300 +++ .../structure/fit/FoundationStiltsTest.java | 33 + .../structure/fit/RigidSupportTest.java | 198 ++ .../structure/fit/StartLayoutsTest.java | 227 ++ .../structure/fit/SurfaceFittingTest.java | 261 ++ .../structure/fit/TerrainIntegrationTest.java | 496 ++++ .../IrisStructureFoundationWriteTest.java | 53 +- .../StructureCarveEnvelopeTest.java | 18 +- ...isStructurePlacementCarveSettingsTest.java | 149 -- .../IrisStructureStiltSettingsTest.java | 50 - .../structure/IrisStructureYBandTest.java | 54 - .../specialhandlers/StructureHandlerTest.java | 12 +- 90 files changed, 5278 insertions(+), 7051 deletions(-) create mode 100644 adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFitBridgeTest.java delete mode 100644 adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorEncaseTest.java delete mode 100644 adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorSurfaceTerrainTest.java create mode 100644 adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureFitBridge.java delete mode 100644 adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureFoundationBuilder.java delete mode 100644 adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructurePostProcessor.java delete mode 100644 adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureSurfaceFitter.java delete mode 100644 adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureSurfaceSupportBuilder.java delete mode 100644 adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureTerrainIntegrator.java create mode 100644 adapters/modded-common/src/main/java/art/arcane/iris/modded/WorldCheckStiltAudit.java create mode 100644 core/src/main/java/art/arcane/iris/core/modules/ModuleStructureFitting.java create mode 100644 core/src/main/java/art/arcane/iris/engine/framework/NativeJigsawOverrides.java create mode 100644 core/src/main/java/art/arcane/iris/engine/framework/NativeStartMemo.java create mode 100644 core/src/main/java/art/arcane/iris/engine/framework/NativeStartPlacement.java create mode 100644 core/src/main/java/art/arcane/iris/engine/framework/NativeStructureGenerationStatus.java create mode 100644 core/src/main/java/art/arcane/iris/engine/framework/NativeStructureLayouts.java create mode 100644 core/src/main/java/art/arcane/iris/engine/framework/NativeStructureReach.java create mode 100644 core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitBlocks.java create mode 100644 core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitBox.java create mode 100644 core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitChunk.java create mode 100644 core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitPiece.java create mode 100644 core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitStart.java create mode 100644 core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitTrait.java create mode 100644 core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeStructureFitting.java create mode 100644 core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeTemplateCells.java create mode 100644 core/src/test/java/art/arcane/iris/builtin/structure/StructureFitSettingsTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/framework/structure/fit/FitFixture.java create mode 100644 core/src/test/java/art/arcane/iris/engine/framework/structure/fit/FoundationStiltsTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/framework/structure/fit/RigidSupportTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/framework/structure/fit/StartLayoutsTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFittingTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegrationTest.java delete mode 100644 core/src/test/java/art/arcane/iris/engine/object/structure/IrisStructurePlacementCarveSettingsTest.java delete mode 100644 core/src/test/java/art/arcane/iris/engine/object/structure/IrisStructureStiltSettingsTest.java delete mode 100644 core/src/test/java/art/arcane/iris/engine/object/structure/IrisStructureYBandTest.java diff --git a/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGenerator.java b/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGenerator.java index fcc9a81dc..dcb04a573 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGenerator.java +++ b/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGenerator.java @@ -7,34 +7,29 @@ import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord; import art.arcane.iris.engine.framework.NativeStructureStartPlan; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; +import art.arcane.iris.engine.framework.NativeStructureLayouts; +import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting; import art.arcane.iris.engine.IrisEngine; import art.arcane.iris.engine.platform.BukkitChunkGenerator; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; +import art.arcane.iris.nativegen.NativeStructureFitBridge; import art.arcane.iris.nativegen.NativeStructureGenerationException; import art.arcane.iris.nativegen.NativeStructureStartInjector; import art.arcane.iris.nativegen.NativeStructureReferenceEnvelope; import art.arcane.iris.nativegen.NativeStructureLocateResults; import art.arcane.iris.nativegen.NativeStructureLocatePersistence; import art.arcane.iris.nativegen.NativeStructureOwnershipRecovery; -import art.arcane.iris.nativegen.NativeStructurePostProcessor; import art.arcane.iris.nativegen.NativeStructureReferenceRepair; -import art.arcane.iris.nativegen.NativeStructureSurfaceFitter; -import art.arcane.iris.nativegen.NativeStructureTerrainIntegrator; import art.arcane.iris.nativegen.NativeStructureVegetationClearer; import art.arcane.iris.nativegen.NativeStructureVerticalPlacer; import art.arcane.iris.nativegen.NativeStructureVanillaLocator; import art.arcane.iris.nativegen.NativeStructureVolumeIndex; import art.arcane.iris.nativegen.WorldgenTerrainHeightmaps; import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.IrisCustomData; import art.arcane.iris.util.common.reflect.WrappedField; import art.arcane.iris.util.common.reflect.WrappedReturningMethod; import art.arcane.iris.util.project.context.IrisContext; -import art.arcane.volmlib.util.math.RNG; import com.mojang.datafixers.util.Pair; import com.mojang.serialization.MapCodec; import net.minecraft.core.BlockPos; @@ -87,9 +82,7 @@ import net.minecraft.world.level.levelgen.structure.StructureStart; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; import org.bukkit.World; import org.bukkit.craftbukkit.CraftWorld; -import org.bukkit.craftbukkit.block.data.CraftBlockData; import org.bukkit.craftbukkit.generator.CustomChunkGenerator; -import org.bukkit.block.data.BlockData; import org.spigotmc.SpigotWorldConfig; import javax.annotation.Nullable; @@ -288,9 +281,7 @@ public class IrisChunkGenerator extends CustomChunkGenerator { throw new IllegalStateException("Native structure filtering received an unregistered structure holder"); } String key = id.toString(); - IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, - key, NativeStructureVegetationClearer.isUndergroundStep(holder.value().step())); - if (!decision.generate()) { + if (!NativeStructureGenerationPolicy.generates(engine, key)) { continue; } candidates.add(new NativeLocateCandidate(holder, key)); @@ -405,33 +396,32 @@ public class IrisChunkGenerator extends CustomChunkGenerator { "resolution", null, chunkPos.x(), chunkPos.z()); } boolean undergroundStep = NativeStructureVegetationClearer.isUndergroundStep(structure.step()); - IrisNativeStructureDecision decision; + boolean generates; try { - decision = NativeStructureGenerationPolicy.resolve(engine, - structureId, undergroundStep); + generates = NativeStructureGenerationPolicy.generates(engine, structureId); } catch (Throwable error) { throw NativeStructureGenerationException.failure( "policy resolution", structureId, chunkPos.x(), chunkPos.z(), error); } - if (!decision.generate()) { + if (!generates) { access.setStartForStructure(structure, StructureStart.INVALID_START); continue; } try { + IntBinaryOperator surface = (x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight(); + int shift = NativeStructureLayouts.shift(engine, NativeStructureVerticalPlacer.placementOf( + start, structureId, undergroundStep, access.getMinY(), surface)); NativeStructureVerticalPlacer.applyVerticalPlacement( start, structureId, - decision.yShift(), + shift, getSeaLevel(), access.getMinY(), access.getMinY() + access.getHeight(), - undergroundStep, - decision.preserveSourceY(), - decision.yBand(), - (x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight()); + surface); StructureStart wrapped = NativeStructureReferenceEnvelope.wrapForPublication( start, structure, start.getReferences(), - NativeStructureTerrainIntegrator.resolveNativeTerrain(start, decision.terrain()), + NativeStructureLayouts.reaches(engine, structureId, undergroundStep, null), structureId); access.setStartForStructure(structure, wrapped); } catch (Throwable error) { @@ -822,7 +812,7 @@ public class IrisChunkGenerator extends CustomChunkGenerator { List placementGroups = new ArrayList<>(); List heightmapStarts = new ArrayList<>(); List vegetationTargets = new ArrayList<>(); - List terrainTargets = new ArrayList<>(); + List fitTargets = new ArrayList<>(); for (int step = 0; step < steps; step++) { int index = 0; for (Structure structure : byStep.get(step)) { @@ -833,25 +823,20 @@ public class IrisChunkGenerator extends CustomChunkGenerator { "resolution", null, chunkPos.x(), chunkPos.z()); } try { - IrisNativeStructureDecision sourceDecision = NativeStructureGenerationPolicy.resolve(engine, - structureId, NativeStructureVegetationClearer.isUndergroundStep(structure.step())); + boolean platformGenerates = NativeStructureGenerationPolicy.generates(engine, structureId); List starts = structureManager.startsForStructure(sectionPos, structure); List resolvedPlacements = new ArrayList<>(starts.size()); for (StructureStart start : starts) { NativeStructureOwnershipRecord ownership = NativeStructureOwnershipRecovery.resolve( engine, world.getLevel(), structureId, structure, start); - IrisNativeStructureDecision decision = - ownership == null ? sourceDecision : ownership.restoredDecision(); - if (!decision.generate()) { + if (ownership == null && !platformGenerates) { continue; } - resolvedPlacements.add(new NativePlacement(start, decision)); + resolvedPlacements.add(new NativePlacement(start, ownership != null)); heightmapStarts.add(start); - terrainTargets.add(new NativeStructureTerrainIntegrator.TerrainTarget( - structureId, start, - NativeStructureTerrainIntegrator.resolveNativeTerrain( - start, decision.terrain()))); + fitTargets.add(new NativeStructureFitBridge.FitTarget(structureId, start, + ownership == null ? null : ownership.restoredMemo())); vegetationTargets.add(start); } if (!resolvedPlacements.isEmpty()) { @@ -881,44 +866,29 @@ public class IrisChunkGenerator extends CustomChunkGenerator { "vegetation cleanup", nativeStructureBatchContext(placementGroups), chunkPos.x(), chunkPos.z(), error); } - NativeStructureSurfaceFitter.VacuumFoundationPlan vacuumFoundationPlan; + NativeStructureFitting.Session fit; try { - vacuumFoundationPlan = NativeStructureSurfaceFitter.prepareSurfaceStructures( - world, area, terrainTargets, - (x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight()); + fit = NativeStructureFitting.of(engine).beforePieces(NativeStructureFitBridge.chunk( + world, area, fitTargets, (x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight())); } catch (Throwable error) { throw NativeStructureGenerationException.failure( - "terrain integration", nativeStructureBatchContext(placementGroups), - chunkPos.x(), chunkPos.z(), error); - } - try { - NativeStructurePostProcessor.prepareTerrain( - world, area, terrainTargets, this::resolvePaletteBlock); - } catch (Throwable error) { - throw NativeStructureGenerationException.failure( - "terrain preparation", nativeStructureBatchContext(placementGroups), + "terrain fitting", nativeStructureBatchContext(placementGroups), chunkPos.x(), chunkPos.z(), error); } + int placed = 0; for (NativePlacementGroup group : placementGroups) { random.setFeatureSeed(decoSeed, group.featureIndex(), group.step()); try { for (NativePlacement placement : group.placements()) { placeVanillaStructure(world, structureManager, random, area, chunkPos, - group.structureId(), placement.start(), placement.decision()); + group.structureId(), placement); + fit.afterPieces(placed++); } } catch (Throwable error) { throw NativeStructureGenerationException.failure( "placement", group.structureId(), chunkPos.x(), chunkPos.z(), error); } } - try { - NativeStructureSurfaceFitter.repairVacuumFoundations( - world, area, vacuumFoundationPlan); - } catch (Throwable error) { - throw NativeStructureGenerationException.failure( - "foundation repair", nativeStructureBatchContext(placementGroups), - chunkPos.x(), chunkPos.z(), error); - } } private static String nativeStructureBatchContext(List placementGroups) { @@ -936,20 +906,29 @@ public class IrisChunkGenerator extends CustomChunkGenerator { } private void placeVanillaStructure(WorldGenLevel world, StructureManager structureManager, WorldgenRandom random, - BoundingBox area, ChunkPos chunkPos, String structureId, StructureStart start, - IrisNativeStructureDecision decision) { + BoundingBox area, ChunkPos chunkPos, String structureId, + NativePlacement placement) { WorldGenLevel boundedWorld = NativeStructureWorldgenAccess.create( world, chunkPos, worldgenSurfaceHeight(), worldgenFloorHeight()); world.setCurrentlyGenerating(() -> "Iris native structure " + structureId); try { - NativeStructurePostProcessor.place(boundedWorld, structureManager, this, random, area, chunkPos, - structureId, start, decision, this::resolvePaletteBlock, - (x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight()); + StructureStart start = placement.start(); + NativeStructureVerticalPlacer.ensureMonumentSeaLevelAlignment(start, structureId, + () -> placement.recorded() ? 0 : platformShift(start, structureId, world.getMinY()), + getSeaLevel(), area.minY(), area.maxY() + 1); + start.placeInChunk(boundedWorld, structureManager, this, random, area, chunkPos); } finally { world.setCurrentlyGenerating(null); } } + /** The shift the pack's modules give the platform's own start, as when the start was published. */ + private int platformShift(StructureStart start, String structureId, int bottomY) { + return NativeStructureLayouts.shift(engine, NativeStructureVerticalPlacer.placementOf(start, structureId, + NativeStructureVegetationClearer.isUndergroundStep(start.getStructure().step()), bottomY, + (x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight())); + } + private List> structuresByStep(Registry registry) { StructureStepCache cached = structureStepCache; if (cached != null && cached.registry() == registry) { @@ -977,22 +956,6 @@ public class IrisChunkGenerator extends CustomChunkGenerator { } } - private BlockState resolvePaletteBlock(IrisMaterialPalette palette, RNG rng, int x, int y, int z) { - PlatformBlockState platformState = palette.get(rng, x, y, z, engine.getData()); - if (platformState == null || !(platformState.nativeHandle() instanceof BlockData blockData)) { - throw new IllegalStateException("Configured native structure palette did not resolve a Bukkit block at " - + x + "," + y + "," + z); - } - if (blockData instanceof IrisCustomData customData) { - blockData = customData.getBase(); - } - if (blockData instanceof CraftBlockData craftBlockData) { - return craftBlockData.getState(); - } - throw new IllegalStateException("Configured native structure palette resolved unsupported Bukkit block data " - + blockData.getClass().getName() + " at " + x + "," + y + "," + z); - } - private BoundingBox writableArea(ChunkAccess chunk) { ChunkPos cp = chunk.getPos(); int i = cp.getMinBlockX(); @@ -1205,7 +1168,8 @@ public class IrisChunkGenerator extends CustomChunkGenerator { void publish() throws IllegalAccessException; } - private record NativePlacement(StructureStart start, IrisNativeStructureDecision decision) { + /** A start placed in the chunk, and whether a module placed it (its ownership record kept its fit). */ + private record NativePlacement(StructureStart start, boolean recorded) { } private record NativePlacementGroup(String structureId, int featureIndex, int step, diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGeneratorFailureContractTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGeneratorFailureContractTest.java index 311be5cd1..3f25b21a4 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGeneratorFailureContractTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGeneratorFailureContractTest.java @@ -64,20 +64,18 @@ public class IrisChunkGeneratorFailureContractTest { assertTrue(adjustment.contains("\"vertical adjustment\"")); assertFalse(adjustment.contains("IrisLogging.reportError")); assertTrue(placement.contains("\"resolution\"")); - assertTrue(placement.contains("\"terrain integration\"")); - assertTrue(placement.contains("\"terrain preparation\"")); - assertTrue(placement.contains("\"foundation repair\"")); + assertTrue(placement.contains("\"terrain fitting\"")); assertFalse(placement.contains("\"terrain carving\"")); assertTrue(placement.contains("\"vegetation cleanup\"")); assertTrue(placement.contains("\"placement\"")); assertTrue(placement.contains("because structure generation is disabled outside the pack")); - assertTrue(placement.contains("prepareSurfaceStructures")); + assertTrue(placement.contains(".beforePieces(")); assertTrue(placement.contains("clearIntersectingVegetation")); assertTrue(placement.indexOf("clearIntersectingVegetation") - < placement.indexOf("prepareSurfaceStructures")); - assertTrue(placement.indexOf("prepareSurfaceStructures") + < placement.indexOf(".beforePieces(")); + assertTrue(placement.indexOf(".beforePieces(") < placement.indexOf("for (NativePlacementGroup group")); - assertTrue(placement.indexOf("repairVacuumFoundations") + assertTrue(placement.indexOf("fit.afterPieces(") > placement.indexOf("for (NativePlacementGroup group")); assertFalse(placement.contains("IrisLogging.reportError")); } @@ -215,7 +213,7 @@ public class IrisChunkGeneratorFailureContractTest { assertEquals(1, occurrences(source, "WorldgenTerrainHeightmaps.primeTerrain(")); assertTrue(placement.contains("WorldgenTerrainHeightmaps.primeStructurePlacement(")); assertTrue(placement.indexOf("WorldgenTerrainHeightmaps.primeStructurePlacement(") - < placement.indexOf("prepareSurfaceStructures")); + < placement.indexOf(".beforePieces(")); assertTrue(fill.contains("requireGenerationLease(\"bukkit_nms_chunk_pipeline\")")); assertTrue(source.contains("int minY = chunk.getMinY() + 1;")); } @@ -443,7 +441,7 @@ public class IrisChunkGeneratorFailureContractTest { @Test public void worldgenHeightmapPrimingLivesInTheSharedNativegenSources() throws IOException { - Path nativegen = Path.of(System.getProperty("iris.nativeStructurePostProcessorSource")).getParent(); + Path nativegen = Path.of(System.getProperty("iris.nativeStructureFitBridgeSource")).getParent(); Path shared = nativegen.resolve("WorldgenTerrainHeightmaps.java"); assertTrue("Worldgen heightmap priming must be shared with the modded loaders through " @@ -470,11 +468,11 @@ public class IrisChunkGeneratorFailureContractTest { String placement = source.substring(placementStart, placementEnd); int ownershipResolution = placement.indexOf( "NativeStructureOwnershipRecovery.resolve("); - int persistedDecision = placement.indexOf("ownership.restoredDecision()", ownershipResolution); + int persistedDecision = placement.indexOf("ownership.restoredMemo()", ownershipResolution); int adjustmentStart = source.indexOf("private void adjustGeneratedStructures"); int adjustmentEnd = source.indexOf("public ChunkGeneratorStructureState createState", adjustmentStart); String adjustment = source.substring(adjustmentStart, adjustmentEnd); - Path nativegen = Path.of(System.getProperty("iris.nativeStructurePostProcessorSource")).getParent(); + Path nativegen = Path.of(System.getProperty("iris.nativeStructureFitBridgeSource")).getParent(); String factory = Files.readString(nativegen.resolve("NativeStructureFactory.java")).replace("\r\n", "\n"); String injector = Files.readString(nativegen.resolve("NativeStructureStartInjector.java")).replace("\r\n", "\n"); String recovery = Files.readString(nativegen.resolve("NativeStructureOwnershipRecovery.java")).replace("\r\n", "\n"); diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGeneratorMonumentLocateContractTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGeneratorMonumentLocateContractTest.java index 3b4b2f4af..2a5511bfc 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGeneratorMonumentLocateContractTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/IrisChunkGeneratorMonumentLocateContractTest.java @@ -45,7 +45,7 @@ public class IrisChunkGeneratorMonumentLocateContractTest { int reachabilityStart = source.indexOf("private Set reachableStructureKeys", filterStart); assertTrue(reachabilityStart > filterStart); String filterMethod = source.substring(filterStart, reachabilityStart); - int policyFilter = filterMethod.indexOf("if (!decision.generate())"); + int policyFilter = filterMethod.indexOf("if (!NativeStructureGenerationPolicy.generates(engine, key))"); int filterContinue = filterMethod.indexOf("continue;", policyFilter); int emptyNativePartition = filterMethod.indexOf("if (candidates.isEmpty())", filterContinue); int reachabilityLookup = filterMethod.indexOf("reachableStructureKeys(level)", emptyNativePartition); @@ -119,7 +119,7 @@ public class IrisChunkGeneratorMonumentLocateContractTest { @Test public void nativePredictionIsReadOnlyUntilTheWinnerIsCommitted() throws IOException { - Path nativegen = Path.of(System.getProperty("iris.nativeStructurePostProcessorSource")).getParent(); + Path nativegen = Path.of(System.getProperty("iris.nativeStructureFitBridgeSource")).getParent(); String source = Files.readString(nativegen.resolve("NativeStructureVanillaLocator.java")).replace("\r\n", "\n"); int predictionStart = source.indexOf("private static Candidate predictAt("); int candidateStart = source.indexOf("public static final class Candidate", predictionStart); @@ -131,33 +131,10 @@ public class IrisChunkGeneratorMonumentLocateContractTest { assertTrue(candidate.contains("committed.compareAndSet(false, true)")); } - @Test - public void stiltSupportUsesPlacedSolidOccupancyWithoutSnapshotDifferenceRequirement() throws IOException { - Path processor = Path.of(System.getProperty("iris.nativeStructurePostProcessorSource")); - String source = Files.readString(processor).replace("\r\n", "\n"); - String foundation = Files.readString( - processor.resolveSibling("NativeStructureFoundationBuilder.java")).replace("\r\n", "\n"); - int placement = source.indexOf("start.placeInChunk(world, structureManager, generator"); - int stiltPlacement = source.indexOf("placeStilts(world, area, structureId, start", placement); - int stiltDefinition = foundation.indexOf("static void placeStilts("); - int occupancyCheck = foundation.indexOf("if (state.isSolid())", stiltDefinition); - int terrainFloor = foundation.indexOf("Math.max(terrainY,", stiltDefinition); - - assertTrue(placement >= 0); - assertTrue(stiltPlacement > placement); - assertTrue(stiltDefinition >= 0); - assertTrue(occupancyCheck > stiltDefinition); - assertTrue(terrainFloor > stiltDefinition); - assertFalse(source.contains("state.equals(")); - assertFalse(foundation.contains("state.equals(")); - assertFalse(source.contains("snapshot.states")); - assertFalse(foundation.contains("snapshot.states")); - } - @Test public void verticalPlacementMovesPiecesMonumentChildrenJigsawJunctionsAndCachedBoundsTogether() throws IOException { String source = Files.readString( - Path.of(System.getProperty("iris.nativeStructurePostProcessorSource")) + Path.of(System.getProperty("iris.nativeStructureFitBridgeSource")) .resolveSibling("NativeStructureVerticalPlacer.java")).replace("\r\n", "\n"); int placementStart = source.indexOf("public static int applyVerticalPlacement"); int shiftStart = source.indexOf("public static int applyVerticalShift", placementStart); diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFactoryTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFactoryTest.java index 02922ab1e..e1d62dddc 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFactoryTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFactoryTest.java @@ -1,7 +1,7 @@ package art.arcane.iris.nativegen; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConfiguration; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; +import art.arcane.iris.engine.framework.NativeJigsawOverrides; +import art.arcane.iris.engine.framework.NativeStructureReach; import com.mojang.datafixers.util.Either; import com.mojang.datafixers.util.Pair; import com.mojang.serialization.MapCodec; @@ -98,7 +98,8 @@ public class NativeStructureFactoryTest { new Structure.StructureSettings(HolderSet.empty())); assertThrows(IllegalStateException.class, () -> NativeStructureFactory.configure( - null, source, new IrisJigsawConfiguration(), false, 80)); + null, source, new NativeJigsawOverrides("", "", null, null, null, null, + NativeJigsawOverrides.SOURCE, null, null, NativeJigsawOverrides.SOURCE), false, 80)); } @Test @@ -303,11 +304,11 @@ public class NativeStructureFactoryTest { ); StructureStart boundaryResult = NativeStructureReferenceEnvelope.wrapForPublication( - boundary, source, 0, new IrisStructureTerrain(), "test:boundary_content"); + boundary, source, 0, List.of(NativeStructureReach.PLATFORM), "test:boundary_content"); StructureStart result = NativeStructureReferenceEnvelope.wrapForPublication( oversized, source, 0, - new IrisStructureTerrain(), + List.of(NativeStructureReach.PLATFORM), "test:oversized_content"); assertTrue(boundaryResult.isValid()); diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFitBridgeTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFitBridgeTest.java new file mode 100644 index 000000000..7f8b6643b --- /dev/null +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFitBridgeTest.java @@ -0,0 +1,1218 @@ +package art.arcane.iris.nativegen; + +import art.arcane.iris.engine.framework.NativeStartMemo; +import art.arcane.iris.engine.framework.NativeStructureReach; +import art.arcane.iris.engine.framework.nativefit.NativeFitPiece; +import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting; +import art.arcane.iris.engine.framework.nativefit.NativeTemplateCells; +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.nbt.CompoundTag; +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.ListPoolElement; +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.AlwaysTrueTest; +import net.minecraft.world.level.levelgen.structure.templatesystem.BlockStateMatchTest; +import net.minecraft.world.level.levelgen.structure.templatesystem.LiquidSettings; +import net.minecraft.world.level.levelgen.structure.templatesystem.ProcessorRule; +import net.minecraft.world.level.levelgen.structure.templatesystem.RuleProcessor; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessor; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorList; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; +import net.minecraft.world.level.levelgen.placement.PlacedFeature; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Modifier; +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.IntBinaryOperator; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * The platform half of the structure fit: what the bridge reads off the platform's starts (processed template cells, + * template columns, legacy template air) and the blocks the built-in {@code iris:structure} fit then changes through + * it, on in-memory worlds. The fit's own rules are tested in core against stated cells. + */ +public class NativeStructureFitBridgeTest { + private static final long TEST_SEED = 8675309L; + private static final int WORLD_MIN_Y = -64; + private static final int WORLD_HEIGHT = 384; + private static final int SUPPORT_SURFACE_Y = 62; + + @BeforeClass + public static void bootstrapMinecraft() { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + } + + @Test + public void shallowUndergroundBeardBoxDoesNotMutateTheTopSurface() throws Exception { + PoolElementStructurePiece piece = rigidTemplatePiece( + new InlineSinglePoolElement(template(List.of( + block(0, 1, 0, Blocks.DEEPSLATE_BRICKS.defaultBlockState())))), + new BoundingBox(0, 67, 0, 0, 74, 0), 1, Rotation.NONE); + Structure structure = new DesertPyramidStructure( + new Structure.StructureSettings( + HolderSet.empty(), Map.of(), + GenerationStep.Decoration.UNDERGROUND_DECORATION, + TerrainAdjustment.BEARD_BOX)); + StructureStart start = new StructureStart( + structure, new ChunkPos(0, 0), 0, + new PiecesContainer(List.of(piece))); + BoundingBox area = new BoundingBox(0, 48, 0, 0, 80, 0); + Map blocks = flatTerrain(area, 64); + Map before = new HashMap<>(blocks); + + fit( + world(blocks), area, List.of(target(start, "SOURCE")), + (x, z) -> 64); + + assertEquals(before, blocks); + } + + @Test + public void projectedCenterAndRigidChildrenUseProcessedFoundationCells() throws Exception { + Structure structure = new DesertPyramidStructure( + new Structure.StructureSettings( + HolderSet.empty(), Map.of(), + GenerationStep.Decoration.SURFACE_STRUCTURES, + TerrainAdjustment.BEARD_BOX)); + PoolElementStructurePiece center = rigidTemplatePiece( + new InlineSinglePoolElement(template(List.of( + block(1, 1, 1, Blocks.COBBLESTONE.defaultBlockState())))), + new BoundingBox(0, 71, 0, 3, 80, 3), 1, Rotation.NONE); + PoolElementStructurePiece child = rigidTemplatePiece( + new InlineSinglePoolElement(template(List.of( + block(1, 7, 1, Blocks.COBBLESTONE.defaultBlockState())))), + new BoundingBox(10, 65, 0, 13, 76, 3), 7, Rotation.NONE); + StructureStart start = new StructureStart( + structure, new ChunkPos(0, 0), 0, + new PiecesContainer(List.of(center, child))); + BoundingBox area = new BoundingBox(0, 60, 0, 15, 90, 15); + Map blocks = new HashMap<>(); + for (int x = area.minX(); x <= area.maxX(); x++) { + for (int z = area.minZ(); z <= area.maxZ(); z++) { + put(blocks, x, 64, z, Blocks.DIRT.defaultBlockState()); + put(blocks, x, 65, z, Blocks.GRASS_BLOCK.defaultBlockState()); + } + } + + List targets = List.of( + new NativeStructureFitBridge.FitTarget("nova_structures:tavern_oak", start, memo("SOURCE"))); + fit( + world(blocks), area, targets, + (x, z) -> 65); + + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 1, 71, 1)); + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 11, 71, 1)); + assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 11, 70, 1)); + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 2, 65, 2)); + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 12, 65, 2)); + } + + @Test + public void sparseRigidFootprintsIgnoreAirAndSolidsAboveTheGroundPlane() throws Exception { + StructureTemplate sparseTemplate = template(List.of( + block(0, 1, 0, Blocks.COBBLESTONE.defaultBlockState()), + block(15, 1, 0, Blocks.AIR.defaultBlockState()), + block(30, 5, 0, Blocks.STONE.defaultBlockState()))); + PoolElementStructurePiece piece = rigidTemplatePiece( + new InlineSinglePoolElement(sparseTemplate), + new BoundingBox(0, 68, 0, 30, 76, 0), 1, Rotation.NONE); + StructureStart start = rigidSurfaceStart( + List.of(piece), TerrainAdjustment.BEARD_THIN); + BoundingBox area = new BoundingBox(0, 52, 0, 30, 80, 0); + Map blocks = flatTerrain(area, 64); + + fit( + world(blocks), area, List.of(target(start, "SOURCE")), + (x, z) -> 64); + + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 68, 0)); + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 15, 64, 0)); + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 30, 64, 0)); + } + + @Test + public void extremeRigidFoundationGapDoesNotCreateATerrainPillar() throws Exception { + StructureTemplate template = template(List.of( + block(0, 1, 0, Blocks.COBBLESTONE.defaultBlockState()))); + PoolElementStructurePiece piece = rigidTemplatePiece( + new InlineSinglePoolElement(template), + new BoundingBox(0, 90, 0, 0, 96, 0), 1, Rotation.NONE); + StructureStart start = rigidSurfaceStart( + List.of(piece), TerrainAdjustment.BEARD_THIN); + BoundingBox area = new BoundingBox(0, 30, 0, 0, 100, 0); + Map blocks = flatTerrain(area, 40); + + fit( + world(blocks), area, List.of(target(start, "SOURCE")), + (x, z) -> 40); + + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 46, 0)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 47, 0)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 89, 0)); + } + + @Test + public void terrainMatchingFootprintsFollowProcessedLowestSolidColumns() throws Exception { + StructureTemplate pathTemplate = template(List.of( + block(0, 0, 0, Blocks.AIR.defaultBlockState()), + block(0, 2, 0, Blocks.DIRT.defaultBlockState()), + block(15, 0, 0, Blocks.AIR.defaultBlockState()), + block(30, 0, 0, Blocks.DIRT.defaultBlockState()), + block(45, 0, 0, Blocks.DANDELION.defaultBlockState()))); + InlineSinglePoolElement element = new InlineSinglePoolElement( + pathTemplate, List.of(), StructureTemplatePool.Projection.TERRAIN_MATCHING); + PoolElementStructurePiece piece = rigidTemplatePiece( + element, new BoundingBox(0, 68, 0, 45, 74, 0), 1, Rotation.NONE); + StructureStart start = rigidSurfaceStart( + List.of(piece), TerrainAdjustment.BEARD_THIN); + BoundingBox area = new BoundingBox(0, 52, 0, 45, 76, 0); + Map blocks = flatTerrain(area, 64); + blocks.remove(new BlockPos(0, 63, 0)); + blocks.remove(new BlockPos(0, 64, 0)); + put(blocks, 0, 59, 0, Blocks.DIRT.defaultBlockState()); + put(blocks, 0, 60, 0, Blocks.GRASS_BLOCK.defaultBlockState()); + put(blocks, 30, 71, 0, Blocks.DIRT.defaultBlockState()); + put(blocks, 30, 72, 0, Blocks.GRASS_BLOCK.defaultBlockState()); + + fit( + world(blocks), area, List.of(target(start, "SOURCE")), + (x, z) -> x == 0 ? 60 : x == 30 ? 72 : 64); + + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 61, 0)); + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 30, 71, 0)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 30, 72, 0)); + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 15, 64, 0)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 15, 65, 0)); + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 45, 64, 0)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 45, 65, 0)); + } + + @Test + public void vacuumFitsOnlyProcessedSolidTemplateColumns() throws Exception { + StructureTemplate sparseTemplate = template(List.of( + block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()), + block(15, 0, 0, Blocks.STONE.defaultBlockState()))); + InlineSinglePoolElement element = new InlineSinglePoolElement( + sparseTemplate, List.of(replaceBlockProcessor( + Blocks.STONE.defaultBlockState(), Blocks.AIR.defaultBlockState()))); + PoolElementStructurePiece piece = rigidTemplatePiece( + element, new BoundingBox(0, 64, 0, 15, 70, 3), 1, Rotation.NONE); + StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); + BoundingBox area = new BoundingBox(0, 56, 0, 15, 72, 3); + Map blocks = flatTerrain(area, 60); + + fit( + world(blocks), area, + List.of(target(start, "VACUUM")), + (x, z) -> 60); + + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 64, 0)); + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 63, 0)); + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 15, 60, 0)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 15, 61, 0)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 15, 64, 0)); + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 15, 60, 3)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 15, 64, 3)); + } + + @Test + public void vacuumSupportsGroundDeltaZeroFoundations() throws Exception { + StructureTemplate template = template(List.of( + block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); + PoolElementStructurePiece piece = rigidTemplatePiece( + new InlineSinglePoolElement(template), + new BoundingBox(0, 66, 0, 0, 70, 0), 0, Rotation.NONE); + StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); + BoundingBox area = new BoundingBox(0, 54, 0, 3, 72, 3); + Map blocks = flatTerrain(area, 60); + + fit( + world(blocks), area, + List.of(target(start, "VACUUM")), + (x, z) -> 60); + + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 65, 0)); + assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 64, 0)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 66, 0)); + } + + @Test + public void vacuumFindsActualTerrainBelowNominalOpenAirSurface() throws Exception { + StructureTemplate template = template(List.of( + block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); + PoolElementStructurePiece piece = rigidTemplatePiece( + new InlineSinglePoolElement(template), + new BoundingBox(0, 75, 0, 0, 81, 0), 2, Rotation.NONE); + StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); + BoundingBox area = new BoundingBox(0, 54, 0, 3, 84, 3); + Map blocks = flatTerrain(area, 60); + + fit( + world(blocks), area, + List.of(target(start, "VACUUM")), + (x, z) -> 80); + + for (int y = 61; y <= 74; y++) { + assertFalse(state(blocks, 0, y, 0).isAir()); + } + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 74, 0)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 75, 0)); + } + + @Test + public void vacuumSupportsFoundationBelowHigherNaturalSurface() throws Exception { + StructureTemplate template = template(List.of( + block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); + PoolElementStructurePiece piece = rigidTemplatePiece( + new InlineLegacyPoolElement(template), + new BoundingBox(0, 75, 0, 0, 81, 0), 2, Rotation.NONE); + StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); + BoundingBox area = new BoundingBox(0, 54, 0, 15, 84, 3); + Map blocks = flatTerrain(area, 60); + put(blocks, 0, 78, 0, Blocks.DIRT.defaultBlockState()); + put(blocks, 0, 79, 0, Blocks.GRASS_BLOCK.defaultBlockState()); + + fit( + world(blocks), area, + List.of(target(start, "VACUUM")), + (x, z) -> 79); + + for (int y = 61; y <= 74; y++) { + assertFalse(state(blocks, 0, y, 0).isAir()); + } + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 75, 0)); + assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 78, 0)); + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 79, 0)); + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 15, 60, 0)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 15, 61, 0)); + } + + @Test + public void vacuumRepairUsesOnlyProcessedSolidFoundationColumns() throws Exception { + StructureTemplate template = template(List.of( + block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()), + block(1, 0, 0, Blocks.STONE.defaultBlockState()), + block(2, 0, 0, Blocks.AIR.defaultBlockState()), + block(2, 2, 0, Blocks.COBBLESTONE.defaultBlockState()))); + InlineSinglePoolElement element = new InlineSinglePoolElement( + template, List.of(replaceBlockProcessor( + Blocks.STONE.defaultBlockState(), Blocks.AIR.defaultBlockState()))); + PoolElementStructurePiece piece = rigidTemplatePiece( + element, new BoundingBox(0, 65, 0, 2, 72, 0), 1, Rotation.NONE); + StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); + BoundingBox area = new BoundingBox(0, 54, 0, 3, 74, 3); + Map blocks = flatTerrain(area, 60); + + NativeStructureFitting.Session plan = fit( + world(blocks), area, + List.of(target(start, "VACUUM")), + (x, z) -> 60); + for (int y = 61; y <= 64; y++) { + put(blocks, 0, y, 0, Blocks.CAVE_AIR.defaultBlockState()); + } + put(blocks, 0, 65, 0, Blocks.COBBLESTONE.defaultBlockState()); + put(blocks, 1, 65, 0, Blocks.COBBLESTONE.defaultBlockState()); + put(blocks, 2, 67, 0, Blocks.COBBLESTONE.defaultBlockState()); + BlockState processorAirSupport = state(blocks, 1, 64, 0); + BlockState authoredAirSupport = state(blocks, 2, 66, 0); + + plan.afterPieces(0); + + for (int y = 61; y <= 64; y++) { + assertFalse(state(blocks, 0, y, 0).isAir()); + } + assertEquals(processorAirSupport, state(blocks, 1, 64, 0)); + assertEquals(authoredAirSupport, state(blocks, 2, 66, 0)); + } + + @Test + public void vacuumRepairPreservesOverlappingAuthoredInterior() throws Exception { + PoolElementStructurePiece lower = rigidTemplatePiece( + new InlineLegacyPoolElement(template(List.of( + block(0, 0, 0, Blocks.AIR.defaultBlockState()), + block(0, 1, 0, Blocks.AIR.defaultBlockState())))), + new BoundingBox(0, 61, 0, 0, 62, 0), 0, Rotation.NONE); + PoolElementStructurePiece upper = rigidTemplatePiece( + new InlineLegacyPoolElement(template(List.of( + block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState())))), + new BoundingBox(0, 65, 0, 0, 70, 0), 0, Rotation.NONE); + StructureStart start = rigidSurfaceStart( + List.of(lower, upper), TerrainAdjustment.NONE); + BoundingBox area = new BoundingBox(0, 54, 0, 3, 72, 3); + Map blocks = flatTerrain(area, 60); + + NativeStructureFitting.Session plan = fit( + world(blocks), area, + List.of(target(start, "VACUUM")), + (x, z) -> 60); + put(blocks, 0, 65, 0, Blocks.COBBLESTONE.defaultBlockState()); + + plan.afterPieces(0); + + for (int y = 61; y <= 64; y++) { + assertTrue(state(blocks, 0, y, 0).isAir()); + } + } + + @Test + public void vacuumRepairIsStableAcrossSplitChunkAreas() throws Exception { + StructureTemplate template = template(List.of( + block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()), + block(1, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); + PoolElementStructurePiece piece = rigidTemplatePiece( + new InlineLegacyPoolElement(template), + new BoundingBox(15, 65, 0, 16, 70, 0), 1, Rotation.NONE); + StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); + NativeStructureFitBridge.FitTarget target = + target(start, "VACUUM"); + BoundingBox wideArea = new BoundingBox(0, 54, 0, 31, 72, 15); + BoundingBox westArea = new BoundingBox(0, 54, 0, 15, 72, 15); + BoundingBox eastArea = new BoundingBox(16, 54, 0, 31, 72, 15); + Map wideBlocks = flatTerrain(wideArea, 60); + Map splitBlocks = flatTerrain(wideArea, 60); + + NativeStructureFitting.Session widePlan = fit( + world(wideBlocks), wideArea, List.of(target), (x, z) -> 60); + NativeStructureFitting.Session westPlan = fit( + world(splitBlocks), westArea, List.of(target), (x, z) -> 60); + NativeStructureFitting.Session eastPlan = fit( + world(splitBlocks), eastArea, List.of(target), (x, z) -> 60); + for (int x = 15; x <= 16; x++) { + for (int y = 61; y <= 64; y++) { + put(wideBlocks, x, y, 0, Blocks.CAVE_AIR.defaultBlockState()); + put(splitBlocks, x, y, 0, Blocks.CAVE_AIR.defaultBlockState()); + } + put(wideBlocks, x, 65, 0, Blocks.COBBLESTONE.defaultBlockState()); + put(splitBlocks, x, 65, 0, Blocks.COBBLESTONE.defaultBlockState()); + } + + widePlan.afterPieces(0); + eastPlan.afterPieces(0); + westPlan.afterPieces(0); + + assertEquals(wideBlocks, splitBlocks); + } + + @Test + public void vacuumNeverLowersExistingTerrainAroundSparsePieces() throws Exception { + StructureTemplate sparseTemplate = template(List.of( + block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); + PoolElementStructurePiece piece = rigidTemplatePiece( + new InlineSinglePoolElement(sparseTemplate), + new BoundingBox(0, 56, 0, 7, 62, 7), 1, Rotation.NONE); + StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); + BoundingBox area = new BoundingBox(0, 48, 0, 7, 70, 7); + Map blocks = flatTerrain(area, 60); + Map originalBlocks = new HashMap<>(blocks); + + fit( + world(blocks), area, + List.of(target(start, "VACUUM")), + (x, z) -> 60); + + assertEquals(originalBlocks, blocks); + } + + @Test + public void vacuumDoesNotRaiseTerrainToRoofsAboveLegacyAir() throws Exception { + StructureTemplate template = template(List.of( + block(0, 0, 0, Blocks.AIR.defaultBlockState()), + block(0, 2, 0, Blocks.COBBLESTONE.defaultBlockState()))); + PoolElementStructurePiece piece = rigidTemplatePiece( + new InlineLegacyPoolElement(template), + new BoundingBox(0, 66, 0, 7, 72, 7), 1, Rotation.NONE); + StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); + BoundingBox area = new BoundingBox(0, 54, 0, 15, 74, 15); + Map blocks = flatTerrain(area, 60); + Map originalBlocks = new HashMap<>(blocks); + + fit( + world(blocks), area, + List.of(target(start, "VACUUM")), + (x, z) -> 60); + + assertEquals(originalBlocks, blocks); + } + + @Test + public void vacuumCapsNeighborTaperAtAuthoredAirGroundPlanes() throws Exception { + PoolElementStructurePiece roof = rigidTemplatePiece( + new InlineSinglePoolElement(template(List.of( + block(0, 0, 0, Blocks.AIR.defaultBlockState()), + block(0, 2, 0, Blocks.COBBLESTONE.defaultBlockState())))), + new BoundingBox(1, 66, 0, 1, 72, 0), 1, Rotation.NONE); + PoolElementStructurePiece highChild = rigidTemplatePiece( + new InlineSinglePoolElement(template(List.of( + block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState())))), + new BoundingBox(0, 90, 0, 0, 94, 0), 1, Rotation.NONE); + StructureStart start = rigidSurfaceStart( + List.of(roof, highChild), TerrainAdjustment.NONE); + BoundingBox area = new BoundingBox(0, 54, 0, 15, 96, 15); + Map blocks = flatTerrain(area, 60); + + fit( + world(blocks), area, + List.of(target(start, "VACUUM")), + (x, z) -> 60); + + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 1, 66, 0)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 1, 67, 0)); + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 89, 0)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 90, 0)); + } + + @Test + public void vacuumDoesNotAnchorRoofsAboveProcessorCreatedAir() throws Exception { + StructureTemplate template = template(List.of( + block(0, 0, 0, Blocks.STONE.defaultBlockState()), + block(0, 2, 0, Blocks.COBBLESTONE.defaultBlockState()))); + PoolElementStructurePiece piece = rigidTemplatePiece( + new InlineSinglePoolElement(template, List.of(replaceBlockProcessor( + Blocks.STONE.defaultBlockState(), Blocks.AIR.defaultBlockState()))), + new BoundingBox(0, 66, 0, 7, 72, 7), 1, Rotation.NONE); + StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); + BoundingBox area = new BoundingBox(0, 54, 0, 15, 74, 15); + Map blocks = flatTerrain(area, 60); + Map originalBlocks = new HashMap<>(blocks); + + fit( + world(blocks), area, + List.of(target(start, "VACUUM")), + (x, z) -> 60); + + assertEquals(originalBlocks, blocks); + } + + @Test + public void vacuumDoesNotTreatSparseRoofCellsAsFoundations() throws Exception { + StructureTemplate template = template(List.of( + block(0, 0, 0, Blocks.SANDSTONE.defaultBlockState()), + block(1, 20, 0, Blocks.SANDSTONE.defaultBlockState()))); + PoolElementStructurePiece piece = rigidTemplatePiece( + new InlineSinglePoolElement(template), + new BoundingBox(0, 66, 0, 20, 100, 20), 1, Rotation.NONE); + StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); + BoundingBox area = new BoundingBox(0, 54, 0, 20, 102, 20); + Map blocks = flatTerrain(area, 60); + + fit( + world(blocks), area, + List.of(target(start, "VACUUM")), + (x, z) -> 60); + + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 65, 0)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 66, 0)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 1, 67, 0)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 1, 86, 0)); + } + + @Test + public void vacuumDoesNotFlattenTerrainMatchingPoolPieces() throws Exception { + StructureTemplate template = template(List.of( + block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); + PoolElementStructurePiece piece = rigidTemplatePiece( + new InlineSinglePoolElement( + template, List.of(), + StructureTemplatePool.Projection.TERRAIN_MATCHING), + new BoundingBox(0, 68, 0, 15, 72, 15), 1, Rotation.NONE); + StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); + BoundingBox area = new BoundingBox(0, 54, 0, 15, 74, 15); + Map blocks = flatTerrain(area, 60); + Map originalBlocks = new HashMap<>(blocks); + + fit( + world(blocks), area, + List.of(target(start, "VACUUM")), + (x, z) -> 60); + + assertEquals(originalBlocks, blocks); + } + + @Test + public void vacuumRetainsJunctionSmoothingForRigidFeaturePieces() { + StructurePoolElement feature = StructurePoolElement.feature( + Holder.direct(null)) + .apply(StructureTemplatePool.Projection.RIGID); + PoolElementStructurePiece piece = rigidTemplatePiece( + feature, new BoundingBox(4, 66, 4, 4, 70, 4), 1, Rotation.NONE); + piece.addJunction(new JigsawJunction( + 4, 66, 4, 0, StructureTemplatePool.Projection.RIGID)); + StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); + BoundingBox area = new BoundingBox(0, 54, 0, 15, 72, 15); + Map blocks = flatTerrain(area, 60); + + fit( + world(blocks), area, + List.of(target(start, "VACUUM")), + (x, z) -> 60); + + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 4, 61, 4)); + } + + @Test + public void vacuumDoesNotInventNonPoolBoundingBoxFootprints() { + StructureStart start = desertStart(TerrainAdjustment.NONE); + BoundingBox bounds = start.getBoundingBox(); + BoundingBox area = new BoundingBox( + bounds.minX() - 12, 40, bounds.minZ() - 12, + bounds.maxX() + 12, bounds.maxY() + 12, bounds.maxZ() + 12); + Map blocks = flatTerrain(area, 50); + Map originalBlocks = new HashMap<>(blocks); + + fit( + world(blocks), area, + List.of(target(start, "VACUUM")), + (x, z) -> 50); + + assertEquals(originalBlocks, blocks); + } + + @Test + public void vacuumContinuouslySupportsProcessedChildBases() throws Exception { + PoolElementStructurePiece center = rigidTemplatePiece( + new InlineSinglePoolElement(template(List.of( + block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState())))), + new BoundingBox(0, 60, 0, 0, 64, 0), 1, Rotation.NONE); + StructureTemplate childTemplate = template(List.of( + block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); + PoolElementStructurePiece child = rigidTemplatePiece( + new InlineSinglePoolElement(childTemplate), + new BoundingBox(10, 66, 0, 10, 72, 0), 1, Rotation.NONE); + StructureStart start = rigidSurfaceStart( + List.of(center, child), TerrainAdjustment.NONE); + BoundingBox area = new BoundingBox(0, 54, 0, 15, 74, 3); + Map blocks = flatTerrain(area, 60); + + fit( + world(blocks), area, + List.of(target(start, "VACUUM")), + (x, z) -> 60); + + for (int y = 61; y <= 65; y++) { + assertFalse(state(blocks, 10, y, 0).isAir()); + } + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 10, 65, 0)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 10, 66, 0)); + } + + @Test + public void vacuumSurfaceFittingIsStableAcrossSplitChunkAreas() throws Exception { + StructureTemplate template = template(List.of( + block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()), + block(1, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); + PoolElementStructurePiece piece = rigidTemplatePiece( + new InlineSinglePoolElement(template), + new BoundingBox(15, 66, 0, 16, 72, 0), 1, Rotation.NONE); + StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); + NativeStructureFitBridge.FitTarget target = + target(start, "VACUUM"); + BoundingBox wideArea = new BoundingBox(0, 54, 0, 31, 74, 15); + BoundingBox westArea = new BoundingBox(0, 54, 0, 15, 74, 15); + BoundingBox eastArea = new BoundingBox(16, 54, 0, 31, 74, 15); + Map wideBlocks = flatTerrain(wideArea, 60); + Map splitBlocks = flatTerrain(wideArea, 60); + Map reverseSplitBlocks = flatTerrain(wideArea, 60); + + fit( + world(wideBlocks), wideArea, List.of(target), (x, z) -> 60); + fit( + world(splitBlocks), westArea, List.of(target), (x, z) -> 60); + fit( + world(splitBlocks), eastArea, List.of(target), (x, z) -> 60); + fit( + world(reverseSplitBlocks), eastArea, List.of(target), (x, z) -> 60); + fit( + world(reverseSplitBlocks), westArea, List.of(target), (x, z) -> 60); + + assertEquals(wideBlocks, splitBlocks); + assertEquals(wideBlocks, reverseSplitBlocks); + } + + @Test + public void stackedRigidPiecesPreserveTheLowerProcessedFoundation() throws Exception { + Structure structure = new DesertPyramidStructure( + new Structure.StructureSettings( + HolderSet.empty(), Map.of(), + GenerationStep.Decoration.SURFACE_STRUCTURES, + TerrainAdjustment.BEARD_BOX)); + PoolElementStructurePiece lower = rigidTemplatePiece( + new InlineSinglePoolElement(template(List.of( + block(2, 1, 2, Blocks.COBBLESTONE.defaultBlockState())))), + new BoundingBox(0, 62, 0, 4, 65, 4), 1, Rotation.NONE); + PoolElementStructurePiece upper = rigidTemplatePiece( + new InlineSinglePoolElement(template(List.of( + block(2, 1, 2, Blocks.COBBLESTONE.defaultBlockState())))), + new BoundingBox(0, 66, 0, 4, 78, 4), 1, Rotation.NONE); + StructureStart start = new StructureStart( + structure, new ChunkPos(0, 0), 0, + new PiecesContainer(List.of(upper, lower))); + BoundingBox area = new BoundingBox(0, 58, 0, 4, 78, 4); + Map blocks = new HashMap<>(); + for (int x = area.minX(); x <= area.maxX(); x++) { + for (int z = area.minZ(); z <= area.maxZ(); z++) { + put(blocks, x, 59, z, Blocks.DIRT.defaultBlockState()); + put(blocks, x, 60, z, Blocks.GRASS_BLOCK.defaultBlockState()); + } + } + + WorldGenLevel world = world(blocks); + List targets = + List.of(target(start, "SOURCE")); + fit( + world, area, targets, (x, z) -> 60); + + assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 2, 62, 2)); + assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 2, 65, 2)); + } + + @Test + public void singlePoolTemplateFieldMatchesTheRuntimeContract() { + Field field = NativeStructureReflection.resolveSinglePoolTemplateField(); + + assertEquals(SinglePoolElement.class, field.getDeclaringClass()); + assertEquals(Either.class, field.getType()); + assertTrue(Modifier.isProtected(field.getModifiers())); + assertTrue(Modifier.isFinal(field.getModifiers())); + assertFalse(Modifier.isStatic(field.getModifiers())); + assertTrue(field.trySetAccessible()); + } + + @Test + public void legacyAirAndUpperOccupancyAreReportedPerPiece() throws Exception { + PoolElementStructurePiece lower = rigidTemplatePiece(new InlineLegacyPoolElement(template(List.of( + block(0, 0, 0, Blocks.AIR.defaultBlockState()), block(1, 0, 0, Blocks.AIR.defaultBlockState())))), + new BoundingBox(0, 62, 0, 1, 65, 0), 1, Rotation.NONE); + PoolElementStructurePiece upper = rigidTemplatePiece(new InlineLegacyPoolElement(template(List.of( + block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()), + block(1, 0, 0, Blocks.COBBLESTONE.defaultBlockState())))), + new BoundingBox(0, 64, 0, 1, 70, 0), 1, Rotation.NONE); + BoundingBox area = new BoundingBox(0, 58, 0, 1, 72, 0); + + assertEquals(List.of("0,62,0", "1,62,0"), legacyAir(lower, area)); + assertEquals(List.of("0,64,0=minecraft:cobblestone", "1,64,0=minecraft:cobblestone"), cells(upper, area)); + } + + @Test + public void rotatedCellsKeepAirVoidFluidAndJigsawAtTheirRotatedPositions() throws Exception { + List blocks = new ArrayList<>(); + blocks.add(block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState())); + blocks.add(block(1, 0, 0, Blocks.AIR.defaultBlockState())); + blocks.add(block(2, 0, 0, Blocks.STRUCTURE_VOID.defaultBlockState())); + blocks.add(block(3, 0, 0, Blocks.WATER.defaultBlockState())); + blocks.add(block(4, 0, 0, Blocks.JIGSAW.defaultBlockState())); + PoolElementStructurePiece upper = rigidTemplatePiece(new InlineSinglePoolElement(template(blocks)), + new BoundingBox(10, 64, 10, 10, 70, 14), 1, Rotation.CLOCKWISE_90); + + assertEquals(List.of("10,64,10=minecraft:cobblestone", "10,64,11=minecraft:air", "10,64,12=minecraft:structure_void", + "10,64,13=minecraft:water", "10,64,14=minecraft:jigsaw"), cells(upper, new BoundingBox(10, 64, 10, 10, 64, 14))); + } + + @Test + public void listElementsOverlayTheirCellsInDeclaredOrder() throws Exception { + InlineLegacyPoolElement legacy = new InlineLegacyPoolElement(template(List.of( + block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()), + block(1, 0, 0, Blocks.COBBLESTONE.defaultBlockState())))); + InlineSinglePoolElement single = new InlineSinglePoolElement(template(List.of( + block(0, 0, 0, Blocks.AIR.defaultBlockState()), + block(1, 0, 0, Blocks.STONE.defaultBlockState())))); + PoolElementStructurePiece upper = rigidTemplatePiece( + new ListPoolElement(List.of(legacy, single), StructureTemplatePool.Projection.RIGID), + new BoundingBox(0, 64, 0, 1, 70, 0), 1, Rotation.NONE); + + assertEquals(List.of("0,64,0=minecraft:air", "1,64,0=minecraft:stone"), cells(upper, new BoundingBox(0, 64, 0, 1, 64, 0))); + } + + @Test + public void laterLegacyAirDoesNotOverlayAnEarlierListSolid() throws Exception { + ListPoolElement list = new ListPoolElement(List.of( + new InlineSinglePoolElement(template(List.of(block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState())))), + new InlineLegacyPoolElement(template(List.of(block(0, 0, 0, Blocks.AIR.defaultBlockState()))))), + StructureTemplatePool.Projection.RIGID); + PoolElementStructurePiece upper = rigidTemplatePiece(list, new BoundingBox(0, 64, 0, 0, 70, 0), 1, Rotation.NONE); + + assertEquals(List.of("0,64,0=minecraft:cobblestone"), cells(upper, new BoundingBox(0, 64, 0, 0, 64, 0))); + } + + @Test + public void processorCreatedAirAndFluidAreReportedAsProcessed() throws Exception { + InlineSinglePoolElement element = new InlineSinglePoolElement(template(List.of( + block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()), + block(1, 0, 0, Blocks.STONE.defaultBlockState()))), List.of( + replaceBlockProcessor(Blocks.COBBLESTONE.defaultBlockState(), Blocks.AIR.defaultBlockState()), + replaceBlockProcessor(Blocks.STONE.defaultBlockState(), Blocks.WATER.defaultBlockState()))); + PoolElementStructurePiece upper = rigidTemplatePiece(element, new BoundingBox(0, 64, 0, 1, 70, 0), 1, Rotation.NONE); + + assertEquals(List.of("0,64,0=minecraft:air", "1,64,0=minecraft:water"), cells(upper, new BoundingBox(0, 64, 0, 1, 64, 0))); + } + + @Test + public void aJigsawIsReportedAsItsFinalState() throws Exception { + CompoundTag jigsawData = new CompoundTag(); + jigsawData.putString("final_state", "minecraft:cobblestone"); + StructureTemplate template = template(List.of(new StructureTemplate.StructureBlockInfo( + BlockPos.ZERO, Blocks.JIGSAW.defaultBlockState(), jigsawData))); + PoolElementStructurePiece upper = rigidTemplatePiece(new InlineSinglePoolElement(template), + new BoundingBox(0, 64, 0, 0, 70, 0), 1, Rotation.NONE); + + assertEquals(List.of("0,64,0=minecraft:cobblestone"), cells(upper, new BoundingBox(0, 64, 0, 0, 64, 0))); + } + + @Test + public void templateBackedColumnsUseTheTemplateAirComplement() throws Exception { + StructureTemplate template = template(List.of( + block(0, 0, 0, Blocks.AIR.defaultBlockState()), + block(0, 1, 0, Blocks.AIR.defaultBlockState()), + block(0, 2, 0, Blocks.DEEPSLATE_BRICKS.defaultBlockState()), + block(1, 0, 0, Blocks.STRUCTURE_VOID.defaultBlockState()), + block(1, 1, 0, Blocks.DEEPSLATE.defaultBlockState()), + block(1, 2, 0, Blocks.DEEPSLATE.defaultBlockState()))); + + Map columns = columns(rigidTemplatePiece(new InlineSinglePoolElement(template), + new BoundingBox(0, 0, 0, 1, 2, 0), 0, Rotation.NONE)); + + assertEquals(2, columns.size()); + assertArrayEquals(new int[]{2, 2}, columns.get(0L)); + assertArrayEquals(new int[]{1, 2}, columns.get(1L << 32)); + } + + @Test + public void fullyVoidTemplateColumnsAreNotCarveSources() throws Exception { + StructureTemplate template = template(List.of( + block(0, 0, 0, Blocks.AIR.defaultBlockState()), + block(0, 1, 0, Blocks.STRUCTURE_VOID.defaultBlockState()))); + + assertTrue(columns(rigidTemplatePiece(new InlineSinglePoolElement(template), + new BoundingBox(0, 0, 0, 0, 1, 0), 0, Rotation.NONE)).isEmpty()); + } + + @Test + public void nonTemplatePiecesFallBackToTheirBoundingBoxColumns() { + StructurePiece piece = desertStart().getPieces().getFirst(); + BoundingBox bounds = piece.getBoundingBox(); + + Map columns = columns(piece); + + assertEquals(bounds.getXSpan() * bounds.getZSpan(), columns.size()); + assertArrayEquals(new int[]{bounds.minY(), bounds.maxY()}, + columns.get((long) bounds.minX() << 32 | bounds.minZ() & 0xffffffffL)); + } + + @Test + public void rotatedLegacyTemplateAirIsReportedOnlyInsideTheChunk() throws Exception { + StructureTemplate.StructureBlockInfo clear = block(1, 0, 0, Blocks.AIR.defaultBlockState()); + StructureTemplate.StructureBlockInfo belowFloor = block(0, -1, 0, Blocks.AIR.defaultBlockState()); + StructureTemplate.StructureBlockInfo outsideChunk = block(3, 0, 0, Blocks.AIR.defaultBlockState()); + BlockPos origin = new BlockPos(10, 80, 10); + StructurePlaceSettings settings = new StructurePlaceSettings().setRotation(Rotation.CLOCKWISE_90); + BlockPos clearPosition = origin.offset(StructureTemplate.calculateRelativePosition(settings, clear.pos())); + BlockPos belowFloorPosition = origin.offset(StructureTemplate.calculateRelativePosition(settings, belowFloor.pos())); + BlockPos outsidePosition = origin.offset(StructureTemplate.calculateRelativePosition(settings, outsideChunk.pos())); + BoundingBox area = BoundingBox.fromCorners(clearPosition, belowFloorPosition); + PoolElementStructurePiece piece = new PoolElementStructurePiece(null, + new InlineLegacyPoolElement(template(List.of(clear, belowFloor, outsideChunk))), origin, 1, + Rotation.CLOCKWISE_90, new BoundingBox(origin), LiquidSettings.APPLY_WATERLOGGING); + + Set air = new HashSet<>(); + for (int[] position : bridged(piece).legacyAir(NativeStructureFitBridge.box(area))) { + air.add(new BlockPos(position[0], position[1], position[2])); + } + + assertFalse(area.isInside(outsidePosition)); + assertEquals(Set.of(clearPosition, belowFloorPosition), air); + } + + @Test + public void runtimeTemplatesResolveWithoutATemplateManager() { + StructureTemplate runtimeTemplate = new StructureTemplate(); + + assertEquals(runtimeTemplate, NativeStructureReflection.resolveTemplateReference(Either.right(runtimeTemplate), null)); + } + + @Test + public void terrainReachPersistsHorizontalReferenceCoverage() { + StructureStart generated = desertStart(); + BoundingBox content = generated.getBoundingBox(); + List reach = List.of(new NativeStructureReach(false, 24)); + + StructureStart wrapped = NativeStructureReferenceEnvelope.wrap(generated, generated.getStructure(), 0, reach); + BoundingBox referenceBounds = NativeStructureReferenceEnvelope.referenceBounds(wrapped, wrapped.getStructure(), reach); + + assertEquals(content, NativeStructureReferenceEnvelope.contentBounds(wrapped)); + assertEquals(content, wrapped.getBoundingBox()); + assertEquals(content.minX() - 24, referenceBounds.minX()); + assertEquals(content.minZ() - 24, referenceBounds.minZ()); + assertEquals(content.maxX() + 24, referenceBounds.maxX()); + assertEquals(content.maxZ() + 24, referenceBounds.maxZ()); + assertEquals(generated.getPieces().size(), wrapped.getPieces().size()); + } + + @Test + public void theWidestReachOfAllModulesWins() { + StructureStart generated = desertStart(TerrainAdjustment.NONE); + BoundingBox content = NativeStructureReferenceEnvelope.contentBounds(generated); + + BoundingBox references = NativeStructureReferenceEnvelope.referenceBounds(generated, generated.getStructure(), + List.of(new NativeStructureReach(false, 12), new NativeStructureReach(false, 4))); + + assertEquals(content.minX() - 12, references.minX()); + assertEquals(content.maxX() + 12, references.maxX()); + assertEquals(content.minZ() - 12, references.minZ()); + assertEquals(content.maxZ() + 12, references.maxZ()); + } + + @Test + public void terrainReachClipsOptionalCoverageWithoutDroppingContent() { + StructureStart generated = desertStart(); + ChunkPos origin = generated.getChunkPos(); + BoundingBox content = NativeStructureReferenceEnvelope.contentBounds(generated); + List reach = List.of(new NativeStructureReach(false, 124)); + + BoundingBox references = NativeStructureReferenceEnvelope.referenceBounds( + generated, generated.getStructure(), reach, "test:clipped_terrain"); + StructureStart published = NativeStructureReferenceEnvelope.wrapForPublication( + generated, generated.getStructure(), 0, reach, "test:clipped_terrain"); + + assertEquals(Math.max(content.minX() - 124, (origin.x() - 8) << 4), references.minX()); + assertEquals(Math.min(content.maxX() + 124, ((origin.x() + 8) << 4) + 15), references.maxX()); + assertEquals(Math.max(content.minZ() - 124, (origin.z() - 8) << 4), references.minZ()); + assertEquals(Math.min(content.maxZ() + 124, ((origin.z() + 8) << 4) + 15), references.maxZ()); + assertTrue(references.isInside(content.getCenter())); + assertTrue(published.isValid()); + } + + @Test + public void aShiftPastTheWorldFloorClampsInsteadOfAborting() { + StructureStart start = desertStart(); + int minY = start.getBoundingBox().minY(); + int worldMinY = minY - 4; + + int offset = NativeStructureVerticalPlacer.applyVerticalShift(start, "minecraft:desert_pyramid", -40, worldMinY, 320); + + assertEquals(-4, offset); + assertEquals(worldMinY, start.getBoundingBox().minY()); + } + + @Test + public void naturalBlockFollowsTheVanillaDimensionTerrain() { + assertEquals(Blocks.NETHERRACK.defaultBlockState(), NativeStructureFitBridge.naturalBlock( + net.minecraft.world.level.Level.NETHER, null, null, 64)); + assertEquals(Blocks.END_STONE.defaultBlockState(), NativeStructureFitBridge.naturalBlock( + net.minecraft.world.level.Level.END, null, null, 64)); + assertEquals(Blocks.STONE.defaultBlockState(), NativeStructureFitBridge.naturalBlock( + net.minecraft.world.level.Level.OVERWORLD, null, null, 64)); + assertEquals(Blocks.DEEPSLATE.defaultBlockState(), NativeStructureFitBridge.naturalBlock( + net.minecraft.world.level.Level.OVERWORLD, null, null, -1)); + net.minecraft.resources.ResourceKey custom = net.minecraft.resources.ResourceKey.create( + net.minecraft.core.registries.Registries.DIMENSION, net.minecraft.resources.Identifier.parse("iris:custom_nether")); + assertEquals(Blocks.NETHERRACK.defaultBlockState(), NativeStructureFitBridge.naturalBlock( + custom, net.minecraft.world.level.dimension.BuiltinDimensionTypes.NETHER, null, 64)); + assertEquals(Blocks.END_STONE.defaultBlockState(), NativeStructureFitBridge.naturalBlock( + custom, net.minecraft.world.level.dimension.BuiltinDimensionTypes.END, null, 64)); + } + + @Test + public void piecesReportTheirProjectionAsTheirKind() { + PoolElementStructurePiece rigid = rigidTemplatePiece(new InlineSinglePoolElement(new StructureTemplate()), + new BoundingBox(0, 0, 0, 0, 0, 0), 0, Rotation.NONE); + PoolElementStructurePiece matching = rigidTemplatePiece(new InlineSinglePoolElement(new StructureTemplate(), + List.of(), StructureTemplatePool.Projection.TERRAIN_MATCHING), new BoundingBox(0, 0, 0, 0, 0, 0), 0, Rotation.NONE); + + assertEquals("RIGID", bridged(rigid).kind()); + assertEquals("TERRAIN_MATCHING", bridged(matching).kind()); + assertEquals("FIXED", bridged(desertStart().getPieces().getFirst()).kind()); + } + + /** Runs the built-in fit through the bridge before the chunk's pieces are placed. */ + private static NativeStructureFitting.Session fit(WorldGenLevel world, BoundingBox area, + List targets, + IntBinaryOperator surfaceHeight) { + return BuiltInFitting.FITTING.beforePieces(NativeStructureFitBridge.chunk(world, area, targets, surfaceHeight)); + } + + /** The positions the fit changed in {@code blocks}, on the support terrain's surface. */ + private static Set supportWritten(Map blocks, BoundingBox area, + List targets) { + Map before = new HashMap<>(blocks); + fit(world(blocks), area, targets, (x, z) -> SUPPORT_SURFACE_Y); + Set written = new HashSet<>(); + Set positions = new HashSet<>(before.keySet()); + positions.addAll(blocks.keySet()); + for (BlockPos position : positions) { + if (!state(before, position.getX(), position.getY(), position.getZ()) + .equals(state(blocks, position.getX(), position.getY(), position.getZ()))) { + written.add(position.asLong()); + } + } + return written; + } + + private static NativeStructureFitBridge.FitTarget target(StructureStart start, String terrainMode) { + return new NativeStructureFitBridge.FitTarget("nova_structures:tavern_oak", start, memo(terrainMode)); + } + + private static NativeStartMemo memo(String terrainMode) { + return new NativeStartMemo("{\"mode\":\"" + terrainMode + "\"}", "null"); + } + + /** {@code piece} as the bridge hands it to the fit. */ + private static NativeFitPiece bridged(StructurePiece piece) { + StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); + return NativeStructureFitBridge.chunk(world(new HashMap<>()), piece.getBoundingBox(), + List.of(target(start, "SOURCE")), (x, z) -> 0).starts().getFirst().pieces().getFirst(); + } + + private static Map columns(StructurePiece piece) { + Map columns = new HashMap<>(); + bridged(piece).columns((x, z, minY, maxY) -> columns.put((long) x << 32 | z & 0xffffffffL, new int[]{minY, maxY})); + return columns; + } + + /** The processed cells the bridge reports for {@code piece} inside {@code region}, sorted, "removed" for a block a processor removed. */ + private static List cells(PoolElementStructurePiece piece, BoundingBox region) { + NativeTemplateCells cells = bridged(piece).cells(NativeStructureFitBridge.box(region)); + List described = new ArrayList<>(); + for (int index = 0; index < cells.states().length; index++) { + BlockState state = cells.states()[index]; + described.add(cells.xs()[index] + "," + cells.ys()[index] + "," + cells.zs()[index] + "=" + + (state == null ? "removed" : BuiltInRegistries.BLOCK.getKey(state.getBlock()))); + } + described.sort(null); + return described; + } + + private static List legacyAir(PoolElementStructurePiece piece, BoundingBox clip) { + List air = new ArrayList<>(); + for (int[] position : bridged(piece).legacyAir(NativeStructureFitBridge.box(clip))) { + air.add(position[0] + "," + position[1] + "," + position[2]); + } + air.sort(null); + return air; + } + + private static final class BuiltInFitting { + private static final NativeStructureFitting FITTING = NativeStructureFitting.builtInModules(); + } + + private static PoolElementStructurePiece rigidTemplatePiece( + StructurePoolElement element, BoundingBox bounds, + int groundLevelDelta, Rotation rotation) { + return new PoolElementStructurePiece( + null, element, + new BlockPos(bounds.minX(), bounds.minY(), bounds.minZ()), + groundLevelDelta, rotation, bounds, + LiquidSettings.APPLY_WATERLOGGING); + } + + private static StructureStart rigidSurfaceStart(List pieces) { + return rigidSurfaceStart(pieces, TerrainAdjustment.BEARD_BOX); + } + + private static StructureStart rigidSurfaceStart( + List pieces, TerrainAdjustment adjustment) { + Structure structure = new DesertPyramidStructure( + new Structure.StructureSettings( + HolderSet.empty(), Map.of(), + GenerationStep.Decoration.SURFACE_STRUCTURES, + adjustment)); + List structurePieces = new ArrayList<>(pieces); + return new StructureStart( + structure, new ChunkPos(0, 0), 0, + new PiecesContainer(structurePieces)); + } + + 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 Map supportTerrain(int minimumX, int maximumX) { + Map blocks = new HashMap<>(); + for (int x = minimumX; x <= maximumX; x++) { + put(blocks, x, 61, 0, Blocks.DIRT.defaultBlockState()); + put(blocks, x, 62, 0, Blocks.GRASS_BLOCK.defaultBlockState()); + } + return blocks; + } + + private static Map flatTerrain(BoundingBox area, int surfaceY) { + Map blocks = new HashMap<>(); + for (int x = area.minX(); x <= area.maxX(); x++) { + for (int z = area.minZ(); z <= area.maxZ(); z++) { + put(blocks, x, surfaceY - 1, z, Blocks.DIRT.defaultBlockState()); + put(blocks, x, surfaceY, z, Blocks.GRASS_BLOCK.defaultBlockState()); + } + } + return blocks; + } + + private static StructureTemplate template( + List blocks) throws Exception { + Constructor constructor = + StructureTemplate.Palette.class.getDeclaredConstructor(List.class); + assertTrue(constructor.trySetAccessible()); + StructureTemplate.Palette palette = constructor.newInstance(blocks); + StructureTemplate template = new StructureTemplate(); + template.palettes.add(palette); + return template; + } + + private static final class InlineSinglePoolElement extends SinglePoolElement { + private InlineSinglePoolElement(StructureTemplate template) { + this(template, List.of()); + } + + private InlineSinglePoolElement( + StructureTemplate template, List processors) { + this(template, processors, StructureTemplatePool.Projection.RIGID); + } + + private InlineSinglePoolElement( + StructureTemplate template, List processors, + StructureTemplatePool.Projection projection) { + super(Either.right(template), + Holder.direct(new StructureProcessorList(processors)), + 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()); + } + } + + private static StructureProcessor replaceBlockProcessor(BlockState source, BlockState replacement) { + // Vanilla RuleProcessor instead of a custom StructureProcessor subtype: StructureProcessor + // is an abstract class on 26.1.2 and an interface on 26.2, so a direct subtype cannot + // compile against both dev bundles. BlockStateMatchTest matches the exact source state, + // matching the previous custom processor's identity-equality semantics. + return new RuleProcessor(List.of(new ProcessorRule( + new BlockStateMatchTest(source), AlwaysTrueTest.INSTANCE, replacement))); + } + + private static StructureStart desertStart() { + return desertStart(TerrainAdjustment.NONE); + } + + private static StructureStart desertStart(TerrainAdjustment adjustment) { + Structure structure = new DesertPyramidStructure( + new Structure.StructureSettings( + HolderSet.empty(), Map.of(), + GenerationStep.Decoration.SURFACE_STRUCTURES, adjustment)); + DesertPyramidPiece piece = new DesertPyramidPiece(RandomSource.create(7L), 0, 0); + return new StructureStart( + structure, new ChunkPos(0, 0), 0, new PiecesContainer(List.of(piece))); + } + + private static WorldGenLevel world(Map blocks) { + InvocationHandler handler = (proxy, method, arguments) -> { + String methodName = method.getName(); + if (methodName.equals("getBlockState")) { + BlockPos position = (BlockPos) arguments[0]; + return state(blocks, position.getX(), position.getY(), position.getZ()); + } + if (methodName.equals("setBlock")) { + BlockPos position = (BlockPos) arguments[0]; + BlockState blockState = (BlockState) arguments[1]; + put(blocks, position.getX(), position.getY(), position.getZ(), blockState); + return true; + } + if (methodName.equals("getSeed")) { + return TEST_SEED; + } + if (methodName.equals("getHeight") && arguments == null) { + return WORLD_HEIGHT; + } + if (methodName.equals("getHeight")) { + int x = (int) arguments[1]; + int z = (int) arguments[2]; + int highest = Integer.MIN_VALUE; + for (Map.Entry entry : blocks.entrySet()) { + BlockPos position = entry.getKey(); + if (position.getX() == x && position.getZ() == z + && !entry.getValue().isAir()) { + highest = Math.max(highest, position.getY()); + } + } + return highest == Integer.MIN_VALUE ? 0 : highest + 1; + } + if (methodName.equals("getMinY")) { + return WORLD_MIN_Y; + } + if (methodName.equals("getLevel")) { + return null; + } + if (methodName.equals("holderLookup")) { + return BuiltInRegistries.BLOCK; + } + if (methodName.equals("hashCode")) { + return System.identityHashCode(proxy); + } + if (methodName.equals("equals")) { + return proxy == arguments[0]; + } + if (methodName.equals("toString")) { + return "fit-bridge-test-world"; + } + throw new UnsupportedOperationException(method.toString()); + }; + return (WorldGenLevel) Proxy.newProxyInstance( + WorldGenLevel.class.getClassLoader(), new Class[]{WorldGenLevel.class}, handler); + } + + private static void put(Map blocks, + int x, int y, int z, BlockState state) { + blocks.put(new BlockPos(x, y, z), state); + } + + private static BlockState state(Map blocks, int x, int y, int z) { + return blocks.getOrDefault(new BlockPos(x, y, z), Blocks.AIR.defaultBlockState()); + } +} 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 index 98929ec6a..0840a9626 100644 --- 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 @@ -1,7 +1,7 @@ package art.arcane.iris.nativegen; -import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; +import art.arcane.iris.engine.framework.NativeStartMemo; +import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting; import com.mojang.datafixers.util.Either; import net.minecraft.SharedConstants; import net.minecraft.core.BlockPos; @@ -61,12 +61,15 @@ import static org.junit.Assert.assertTrue; * 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. + * that differs from the untouched terrain. The hashes were taken from the platform-side fit before it moved into the + * structure module; they now run through the platform bridge and the built-in modules. */ 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 int WORLD_MIN_Y = -64; + private static final int WORLD_HEIGHT = 384; + private static final BoundingBox CHUNK_AREA = new BoundingBox(0, WORLD_MIN_Y + 1, 0, 15, WORLD_MIN_Y + WORLD_HEIGHT - 2, 15); private static final String NO_STILTS = "null"; private static final String SOURCE_TERRAIN = "{}"; @@ -117,35 +120,27 @@ public class NativeStructureFitPinTest { return terrain.changedBlocksHash(CHUNK_AREA); } - /** The chunk's fit in the order the generators run it; the platform's placement is {@link #placePieces}. */ + /** + * The chunk's fit in the order the generators run it, through the platform bridge and the built-in modules: the + * fit before any piece, then each start's pieces ({@link #placePieces}) and its fit after them. + */ private static void fitChunk(WorldGenLevel world, Scenario scenario) { - IntBinaryOperator surface = TerrainWorld::surfaceY; - List targets = new ArrayList<>(); - List decisions = new ArrayList<>(); + List targets = 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()))); + targets.add(new NativeStructureFitBridge.FitTarget(target.structureId(), target.start(), + new NativeStartMemo(target.terrainJson(), target.stiltJson()))); } - NativeStructureSurfaceFitter.VacuumFoundationPlan plan = NativeStructureSurfaceFitter.prepareSurfaceStructures( - world, CHUNK_AREA, targets, surface); - NativeStructurePostProcessor.prepareTerrain(world, CHUNK_AREA, targets, NativeStructureFitPinTest::noPalette); + NativeStructureFitting.Session fit = BuiltInFitting.FITTING.beforePieces( + NativeStructureFitBridge.chunk(world, CHUNK_AREA, targets, TerrainWorld::surfaceY)); 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())); - } + placePieces(world, scenario.targets().get(index)); + fit.afterPieces(index); } - 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"); + /** The built-in modules load once for every scenario. */ + private static final class BuiltInFitting { + private static final NativeStructureFitting FITTING = NativeStructureFitting.builtInModules(); } /** @@ -541,7 +536,8 @@ public class NativeStructureFitPinTest { yield true; } case "getSeed" -> WORLD_SEED; - case "getHeight" -> heightmapY((int) arguments[1], (int) arguments[2]); + case "getMinY" -> WORLD_MIN_Y; + case "getHeight" -> arguments == null ? WORLD_HEIGHT : heightmapY((int) arguments[1], (int) arguments[2]); case "getLevel" -> null; case "holderLookup" -> BuiltInRegistries.BLOCK; case "hashCode" -> System.identityHashCode(proxy); 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 index e6898a220..d7650256e 100644 --- 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 @@ -1,8 +1,6 @@ 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 art.arcane.iris.engine.framework.NativeStructureReach; import net.minecraft.SharedConstants; import net.minecraft.core.HolderSet; import net.minecraft.server.Bootstrap; @@ -21,6 +19,7 @@ import org.junit.BeforeClass; import org.junit.Test; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.IntBinaryOperator; @@ -30,15 +29,18 @@ 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. + * fit. The values were taken before the fit moved into the structure module; since then the module answers the shift + * and the reach ({@code StartLayoutsPinTest} in core pins those answers for the same starts) and the platform side, + * pinned here, aligns, moves and references the starts with them. */ 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 Map ADJUSTMENT_SHIFTS = adjustmentShifts(); + private static final Map TERRAIN_REACHES = terrainReaches(); private static final List PINNED_SHIFTS = List.of( "none minecraft:stronghold 0,0 offset 0 minY 50", @@ -118,63 +120,68 @@ public class NativeStructureLayoutPinTest { Bootstrap.bootStrap(); } + /** + * The module's shift for a stronghold is the move it makes; for a desert temple, which the platform aligns to the + * terrain itself, it is the adjustment's own shift on top of that alignment. + */ @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()); - } - } + for (String pinned : PINNED_SHIFTS) { + String[] parts = pinned.split(" "); + String structureId = parts[1]; + String[] chunkXZ = parts[2].split(","); + ChunkPos chunk = new ChunkPos(Integer.parseInt(chunkXZ[0]), Integer.parseInt(chunkXZ[1])); + boolean stronghold = structureId.equals("minecraft:stronghold"); + int moduleShift = stronghold ? Integer.parseInt(parts[4]) : ADJUSTMENT_SHIFTS.get(parts[0]); + StructureStart start = start(chunk, stronghold ? 50 : 64, TerrainAdjustment.NONE); + int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(start, structureId, moduleShift, + SEA_LEVEL, WORLD_MIN_Y, WORLD_MAX_Y_EXCLUSIVE, SURFACE); + actual.add(parts[0] + " " + structureId + " " + parts[2] + " offset " + offset + + " minY " + start.getBoundingBox().minY()); } - assertEquals("Pinned shifts changed:\n" + String.join("\n", quoted(actual)), PINNED_SHIFTS, actual); + assertEquals(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 (Map.Entry fit : TERRAIN_REACHES.entrySet()) { 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() + List.of(fit.getValue()), "minecraft:village_plains"); + actual.add(fit.getKey() + " " + 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); + assertEquals(PINNED_REACHES, actual); } - private static List quoted(List lines) { - return lines.stream().map(line -> " \"" + line.replace("\"", "\\\"") + "\",").toList(); + private static Map adjustmentShifts() { + Map shifts = new LinkedHashMap<>(); + shifts.put("none", 0); + shifts.put("shift", 5); + shifts.put("burial", -7); + shifts.put("burial-unshifted", 0); + shifts.put("kept", 3); + shifts.put("band", 0); + shifts.put("narrow-band", 4); + shifts.put("kept-over-band", 2); + return shifts; } - 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); + /** What the structure module answers for each terrain fit (pinned in core by {@code StartLayoutsPinTest}). */ + private static Map terrainReaches() { + Map reaches = new LinkedHashMap<>(); + reaches.put("{}", NativeStructureReach.PLATFORM); + reaches.put("{\"mode\":\"PRESERVE\"}", new NativeStructureReach(false, 0)); + reaches.put("{\"mode\":\"VACUUM\"}", new NativeStructureReach(false, 12)); + reaches.put("{\"mode\":\"ENCASE\",\"horizontalPadding\":4}", new NativeStructureReach(false, 4)); + reaches.put("{\"mode\":\"BORE\",\"horizontalPadding\":20}", new NativeStructureReach(false, 20)); + reaches.put("{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":112}", new NativeStructureReach(false, 112)); + reaches.put("{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":0}", new NativeStructureReach(false, 0)); + return reaches; } private static StructureStart start(ChunkPos chunk, int minY, TerrainAdjustment adjustment) { @@ -184,7 +191,4 @@ public class NativeStructureLayoutPinTest { 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/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureOwnershipFingerprintTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureOwnershipFingerprintTest.java index 8b2f9c7a1..be33195a7 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureOwnershipFingerprintTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureOwnershipFingerprintTest.java @@ -4,8 +4,8 @@ import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord; import art.arcane.iris.engine.framework.NativeStructureStartPlan; import art.arcane.iris.engine.framework.StructurePlacementGrid; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; +import art.arcane.iris.engine.framework.NativeStartMemo; +import art.arcane.iris.engine.framework.NativeStructureReach; import net.minecraft.SharedConstants; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -63,9 +63,7 @@ public class NativeStructureOwnershipFingerprintTest { NativeStructureVerticalPlacer.alignOceanMonumentToSeaLevel( generated, 0, 80, -64, 320); int alignedLocatorY = NativeStructureOwnershipFingerprint.locatorY(generated); - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.FORCE_CARVE) - .setHorizontalPadding(24); + List terrain = List.of(new NativeStructureReach(false, 24)); StructureStart wrapped = NativeStructureReferenceEnvelope.wrap( generated, structure, @@ -127,9 +125,7 @@ public class NativeStructureOwnershipFingerprintTest { StructureStart generated = monumentStart(structure, origin, seed); NativeStructureVerticalPlacer.alignOceanMonumentToSeaLevel( generated, 0, 80, -64, 320); - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.FORCE_CARVE) - .setHorizontalPadding(24); + List terrain = List.of(new NativeStructureReach(false, 24)); StructureStart wrapped = NativeStructureReferenceEnvelope.wrap( generated, structure, @@ -247,7 +243,7 @@ public class NativeStructureOwnershipFingerprintTest { private static NativeStructureStartPlan plan(ChunkPos origin, int baseY) { return new NativeStructureStartPlan("minecraft:monument", origin.x(), origin.z(), baseY, false, false, StructurePlacementGrid.placementIdentity(new IrisStructurePlacement().setPlacementId("monument-test")), - null, null, new IrisStructureTerrain()); + null, new NativeStartMemo("{\"mode\":\"SOURCE\"}", "null")); } private static NativeStructureOwnershipRecord ownership( @@ -257,7 +253,7 @@ public class NativeStructureOwnershipFingerprintTest { start, plan(origin, NativeStructureReferenceEnvelope.contentBounds(start).minY()), NativeStructureReferenceEnvelope.referenceBounds( - start, structure, new IrisStructureTerrain()) + start, structure, List.of(NativeStructureReach.PLATFORM)) ); } diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureOwnershipRecoveryTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureOwnershipRecoveryTest.java index 4922b1463..ef15b816f 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureOwnershipRecoveryTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureOwnershipRecoveryTest.java @@ -3,9 +3,9 @@ package art.arcane.iris.nativegen; import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord; import art.arcane.iris.engine.framework.NativeStructureStartPlan; import art.arcane.iris.engine.framework.StructurePlacementGrid; +import art.arcane.iris.engine.framework.NativeStartMemo; +import art.arcane.iris.engine.framework.NativeStructureReach; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; import net.minecraft.SharedConstants; import net.minecraft.core.Direction; import net.minecraft.core.HolderSet; @@ -61,7 +61,7 @@ public class NativeStructureOwnershipRecoveryTest { NativeStructureOwnershipRecord recovered = NativeStructureOwnershipRecovery.proveCandidate( "minecraft:monument", structure, reloaded, - plan, expected, false); + plan, expected, false, reaches(plan)); assertNotNull(recovered); assertEquals(plan.placementIdentity(), @@ -69,9 +69,7 @@ public class NativeStructureOwnershipRecoveryTest { assertEquals(expectedLocatorY, recovered.locatorY()); assertNotEquals(NativeStructureOwnershipFingerprint.locatorY(reloaded), recovered.locatorY()); - assertEquals(IrisStructureTerrainMode.FORCE_CARVE, - recovered.restoredDecision().terrain().resolvedMode()); - assertEquals(24, recovered.restoredDecision().terrain().getHorizontalPadding()); + assertEquals(plan.memo(), recovered.restoredMemo()); assertTrue(recovered.referenceMinChunkX() < NativeStructureReferenceEnvelope.contentBounds(reloaded).minX() >> 4); } @@ -87,7 +85,7 @@ public class NativeStructureOwnershipRecoveryTest { NativeStructureOwnershipRecord recovered = NativeStructureOwnershipRecovery.proveCandidate( "minecraft:monument", structure, natural, - plan, natural, true); + plan, natural, true, reaches(plan)); assertNull(recovered); } @@ -112,10 +110,10 @@ public class NativeStructureOwnershipRecoveryTest { changedIdentity.placementIdentity()); assertNull(NativeStructureOwnershipRecovery.proveCandidate( "minecraft:monument", structure, expected, - changedIdentity, expected, false)); + changedIdentity, expected, false, reaches(changedIdentity))); assertNull(NativeStructureOwnershipRecovery.proveCandidate( "minecraft:monument", structure, changedGeometry, - plan(origin, "geometry-check", 0), expected, false)); + plan(origin, "geometry-check", 0), expected, false, reaches(plan(origin, "geometry-check", 0)))); } @Test @@ -127,7 +125,7 @@ public class NativeStructureOwnershipRecoveryTest { NativeStructureOwnershipRecord recovered = NativeStructureOwnershipRecovery.proveCandidate( "minecraft:monument", structure, expected, - plan(origin, "fingerprint-check", 16), expected, false); + plan(origin, "fingerprint-check", 16), expected, false, reaches(plan(origin, "fingerprint-check", 16))); assertNotNull(recovered); StructureStart moved = monumentStart(structure, origin, seed); @@ -146,14 +144,14 @@ public class NativeStructureOwnershipRecoveryTest { OceanMonumentStructure structure = structure(); StructureStart start = monumentStart(structure, origin, seed); NativeStructureStartPlan plan = plan( - origin, "vacuum-envelope-refresh", IrisStructureTerrainMode.VACUUM, 0); + origin, "vacuum-envelope-refresh", "VACUUM", 0); BoundingBox content = NativeStructureReferenceEnvelope.contentBounds(start); NativeStructureOwnershipRecord stale = NativeStructureOwnershipFingerprint.capture( structureKey, start, plan, content); NativeStructureOwnershipRecord refreshed = NativeStructureOwnershipRecovery.refreshReferenceEnvelope( - structureKey, structure, start, stale); + structureKey, structure, start, stale, reaches(plan)); assertNotNull(refreshed); assertNotEquals(stale, refreshed); @@ -163,18 +161,16 @@ public class NativeStructureOwnershipRecoveryTest { assertEquals(stale.baseY(), refreshed.baseY()); assertEquals(stale.locatorY(), refreshed.locatorY()); assertEquals(stale.contentFingerprint(), refreshed.contentFingerprint()); - assertEquals(stale.decision(), refreshed.decision()); - assertEquals(IrisStructureTerrainMode.VACUUM, - refreshed.restoredDecision().terrain().resolvedMode()); + assertEquals(stale.memo(), refreshed.memo()); BoundingBox expected = NativeStructureReferenceEnvelope.referenceBounds( - start, structure, plan.terrain(), structureKey); + start, structure, reaches(plan), structureKey); assertEquals(expected.minX() >> 4, refreshed.referenceMinChunkX()); assertEquals(expected.maxX() >> 4, refreshed.referenceMaxChunkX()); assertEquals(expected.minZ() >> 4, refreshed.referenceMinChunkZ()); assertEquals(expected.maxZ() >> 4, refreshed.referenceMaxChunkZ()); assertTrue(hasExpandedCoverage(stale, refreshed)); assertSame(refreshed, NativeStructureOwnershipRecovery.refreshReferenceEnvelope( - structureKey, structure, start, refreshed)); + structureKey, structure, start, refreshed, reaches(plan))); } @Test @@ -185,7 +181,7 @@ public class NativeStructureOwnershipRecoveryTest { OceanMonumentStructure structure = structure(); StructureStart expected = monumentStart(structure, origin, seed); NativeStructureStartPlan plan = plan( - origin, "vacuum-content-check", IrisStructureTerrainMode.VACUUM, 0); + origin, "vacuum-content-check", "VACUUM", 0); NativeStructureOwnershipRecord stale = NativeStructureOwnershipFingerprint.capture( structureKey, expected, plan, NativeStructureReferenceEnvelope.contentBounds(expected)); @@ -195,7 +191,7 @@ public class NativeStructureOwnershipRecoveryTest { } assertNull(NativeStructureOwnershipRecovery.refreshReferenceEnvelope( - structureKey, structure, moved, stale)); + structureKey, structure, moved, stale, reaches(plan))); } @Test @@ -207,12 +203,27 @@ public class NativeStructureOwnershipRecoveryTest { StructureStart start = monumentStart(structure, origin, seed); NativeStructureStartPlan plan = plan(origin, "current-force-carve", 24); BoundingBox envelope = NativeStructureReferenceEnvelope.referenceBounds( - start, structure, plan.terrain(), structureKey); + start, structure, reaches(plan), structureKey); NativeStructureOwnershipRecord ownership = NativeStructureOwnershipFingerprint.capture( structureKey, start, plan, envelope); assertSame(ownership, NativeStructureOwnershipRecovery.refreshReferenceEnvelope( - structureKey, structure, start, ownership)); + structureKey, structure, start, ownership, reaches(plan))); + } + + @Test + public void aRecordedEnvelopeWiderThanTodaysReachNeverShrinks() { + String structureKey = "minecraft:monument"; + long seed = 927451L; + ChunkPos origin = new ChunkPos(3, 8); + OceanMonumentStructure structure = structure(); + StructureStart start = monumentStart(structure, origin, seed); + NativeStructureStartPlan plan = plan(origin, "wide-force-carve", 24); + NativeStructureOwnershipRecord ownership = NativeStructureOwnershipFingerprint.capture(structureKey, start, plan, + NativeStructureReferenceEnvelope.referenceBounds(start, structure, reaches(plan), structureKey)); + + assertSame(ownership, NativeStructureOwnershipRecovery.refreshReferenceEnvelope( + structureKey, structure, start, ownership, List.of(NativeStructureReach.PLATFORM))); } @Test @@ -230,16 +241,16 @@ public class NativeStructureOwnershipRecoveryTest { piece.move(shiftX, 0, 0); } NativeStructureStartPlan plan = plan( - origin, "clipped-vacuum", IrisStructureTerrainMode.VACUUM, 0); + origin, "clipped-vacuum", "VACUUM", 0); BoundingBox envelope = NativeStructureReferenceEnvelope.referenceBounds( - start, structure, plan.terrain(), structureKey); + start, structure, reaches(plan), structureKey); NativeStructureOwnershipRecord ownership = NativeStructureOwnershipFingerprint.capture( structureKey, start, plan, envelope); assertEquals(origin.x() + NativeStructureOwnershipRecord.MAX_REFERENCE_DISTANCE_CHUNKS, ownership.referenceMaxChunkX()); assertSame(ownership, NativeStructureOwnershipRecovery.refreshReferenceEnvelope( - structureKey, structure, start, ownership)); + structureKey, structure, start, ownership, reaches(plan))); } private static OceanMonumentStructure structure() { @@ -267,17 +278,15 @@ public class NativeStructureOwnershipRecoveryTest { private static NativeStructureStartPlan plan(ChunkPos origin, String placementId, int horizontalPadding) { - return plan(origin, placementId, - IrisStructureTerrainMode.FORCE_CARVE, horizontalPadding); + return plan(origin, placementId, "FORCE_CARVE", horizontalPadding); } + /** A start the structure module placed with a terrain fit of {@code terrainMode}, as its memo records it. */ private static NativeStructureStartPlan plan(ChunkPos origin, String placementId, - IrisStructureTerrainMode terrainMode, + String terrainMode, int horizontalPadding) { - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setMode(terrainMode) - .setHorizontalPadding(horizontalPadding); + String terrain = "{\"mode\":\"" + terrainMode + "\",\"horizontalPadding\":" + horizontalPadding + "}"; return new NativeStructureStartPlan( "minecraft:monument", origin.x(), @@ -288,11 +297,17 @@ public class NativeStructureOwnershipRecoveryTest { false, StructurePlacementGrid.placementIdentity(new IrisStructurePlacement().setPlacementId(placementId)), null, - null, - terrain + new NativeStartMemo(terrain, "null") ); } + /** The reach the structure module gives the plan's terrain fit: VACUUM its 12-block falloff, else the padding. */ + private static List reaches(NativeStructureStartPlan plan) { + String terrain = plan.memo().terrain(); + int padding = Integer.parseInt(terrain.replaceAll(".*\"horizontalPadding\":(\\d+).*", "$1")); + return List.of(new NativeStructureReach(false, terrain.contains("VACUUM") ? 12 : padding)); + } + private static boolean hasExpandedCoverage( NativeStructureOwnershipRecord stale, NativeStructureOwnershipRecord refreshed) { diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorEncaseTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorEncaseTest.java deleted file mode 100644 index 597f28474..000000000 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorEncaseTest.java +++ /dev/null @@ -1,547 +0,0 @@ -package art.arcane.iris.nativegen; - -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; -import art.arcane.iris.engine.object.structure.IrisStructureYBand; -import art.arcane.volmlib.util.math.RNG; -import net.minecraft.SharedConstants; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Holder; -import net.minecraft.core.HolderSet; -import net.minecraft.core.registries.Registries; -import net.minecraft.resources.Identifier; -import net.minecraft.resources.ResourceKey; -import net.minecraft.server.Bootstrap; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.Level; -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.dimension.BuiltinDimensionTypes; -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.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.BlockIgnoreProcessor; -import net.minecraft.world.level.levelgen.structure.templatesystem.LiquidSettings; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorList; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.IOException; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Proxy; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.BitSet; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; - -public class NativeStructurePostProcessorEncaseTest { - private static final long TEST_SEED = 1234L; - - @BeforeClass - public static void bootstrapMinecraft() { - SharedConstants.tryDetectVersion(); - Bootstrap.bootStrap(); - } - - @Test - public void encaseFillsAirAndLiquidWithoutOverwritingExistingTerrain() { - StructureStart start = start(TerrainAdjustment.BURY, 64); - BoundingBox bounds = start.getPieces().getFirst().getBoundingBox(); - BoundingBox area = new BoundingBox( - bounds.minX() - 1, bounds.minY() - 1, bounds.minZ() - 1, - bounds.maxX() + 1, bounds.maxY() + 1, bounds.maxZ() + 1); - Map blocks = new HashMap<>(); - put(blocks, bounds.minX(), bounds.minY(), bounds.minZ(), Blocks.DIRT.defaultBlockState()); - put(blocks, bounds.maxX(), bounds.minY(), bounds.maxZ(), Blocks.WATER.defaultBlockState()); - - NativeStructureTerrainIntegrator.integrateTerrain( - world(blocks), area, "minecraft:stronghold", start, - new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.ENCASE) - .setHorizontalPadding(1) - .setCeilingPadding(1) - .setFloorPadding(1), - null); - - assertEquals(Blocks.DIRT.defaultBlockState(), - state(blocks, bounds.minX(), bounds.minY(), bounds.minZ())); - assertEquals(Blocks.STONE.defaultBlockState(), - state(blocks, bounds.maxX(), bounds.minY(), bounds.maxZ())); - assertEquals(Blocks.STONE.defaultBlockState(), - state(blocks, bounds.minX() - 1, bounds.minY() - 1, bounds.minZ() - 1)); - assertEquals(Blocks.STONE.defaultBlockState(), - state(blocks, bounds.maxX() + 1, bounds.maxY() + 1, bounds.maxZ() + 1)); - } - - @Test - public void defaultEncasePaletteSplitsStoneAboveZeroAndDeepslateBelow() { - StructureStart start = start(TerrainAdjustment.BURY, -1); - BoundingBox bounds = start.getPieces().getFirst().getBoundingBox(); - Map blocks = new HashMap<>(); - - NativeStructureTerrainIntegrator.integrateTerrain( - world(blocks), bounds, "minecraft:stronghold", start, - new IrisStructureTerrain().setMode(IrisStructureTerrainMode.ENCASE), - null); - - assertEquals(-1, bounds.minY()); - assertEquals(Blocks.DEEPSLATE.defaultBlockState(), - state(blocks, bounds.minX(), -1, bounds.minZ())); - assertEquals(Blocks.STONE.defaultBlockState(), - state(blocks, bounds.minX(), 0, bounds.minZ())); - } - - @Test - public void defaultEncaseMaterialFollowsVanillaDimensionTerrain() { - assertEquals(Blocks.NETHERRACK.defaultBlockState(), - NativeStructureTerrainIntegrator.defaultEncaseBlock(Level.NETHER, 64)); - assertEquals(Blocks.END_STONE.defaultBlockState(), - NativeStructureTerrainIntegrator.defaultEncaseBlock(Level.END, 64)); - assertEquals(Blocks.STONE.defaultBlockState(), - NativeStructureTerrainIntegrator.defaultEncaseBlock(Level.OVERWORLD, 64)); - } - - @Test - public void sourceEncaseMaterialFollowsNearbyIrisTerrain() { - Map blocks = new HashMap<>(); - BlockPos fill = new BlockPos(4, 64, 8); - put(blocks, fill.getX() + 3, fill.getY(), fill.getZ(), Blocks.TUFF.defaultBlockState()); - - assertEquals(Blocks.TUFF.defaultBlockState(), - NativeStructureTerrainIntegrator.sourceEncaseBlock(world(blocks), fill)); - } - - @Test - public void sourceMaterialSnapshotIgnoresPreviouslyDecoratedAdjacentChunks() { - Map blocks = new HashMap<>(); - BlockPos fill = new BlockPos(0, 64, 8); - put(blocks, -1, 64, 8, Blocks.OAK_PLANKS.defaultBlockState()); - put(blocks, 3, 64, 8, Blocks.TUFF.defaultBlockState()); - WorldGenLevel world = world(blocks); - NativeStructureTerrainIntegrator.SourceTerrainSnapshot sourceTerrain = - sourceSnapshot(world, new BoundingBox(0, 64, 0, 15, 64, 15)); - - assertEquals(Blocks.TUFF.defaultBlockState(), - NativeStructureTerrainIntegrator.sourceEncaseBlock( - world, fill, sourceTerrain)); - } - - @Test - public void sourceMaterialSnapshotIsStableAcrossEarlierFillsInTheSameChunk() { - Map blocks = new HashMap<>(); - BlockPos fill = new BlockPos(0, 64, 8); - put(blocks, 3, 64, 8, Blocks.TUFF.defaultBlockState()); - WorldGenLevel world = world(blocks); - NativeStructureTerrainIntegrator.SourceTerrainSnapshot sourceTerrain = - sourceSnapshot(world, new BoundingBox(0, 64, 0, 15, 64, 15)); - put(blocks, 1, 64, 8, Blocks.OAK_PLANKS.defaultBlockState()); - - assertEquals(Blocks.TUFF.defaultBlockState(), - NativeStructureTerrainIntegrator.sourceEncaseBlock( - world, fill, sourceTerrain)); - } - - @Test - public void sourceMaterialRejectsStructureBlocksAndOresBeforeDimensionFallback() { - Map blocks = new HashMap<>(); - BlockPos fill = new BlockPos(4, -20, 8); - put(blocks, 3, -20, 8, Blocks.OAK_PLANKS.defaultBlockState()); - put(blocks, 5, -20, 8, Blocks.STONE_BRICKS.defaultBlockState()); - put(blocks, 4, -20, 7, Blocks.IRON_ORE.defaultBlockState()); - - assertEquals(Blocks.DEEPSLATE.defaultBlockState(), - NativeStructureTerrainIntegrator.sourceEncaseBlock(world(blocks), fill)); - } - - @Test - public void sourceMaterialSnapshotOnlyAllocatesActualFillLayers() { - StructureStart start = start(TerrainAdjustment.BURY, 64); - BoundingBox area = new BoundingBox(0, -2032, 0, 15, 2030, 15); - NativeStructureTerrainIntegrator.SourceTerrainSnapshot sourceTerrain = - NativeStructureTerrainIntegrator.captureSourceTerrain( - world(new HashMap<>()), area, - List.of(new NativeStructureTerrainIntegrator.TerrainTarget( - "test:bounded-snapshot", start, - new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE)))); - - assertNotNull(sourceTerrain); - assertEquals(23 * 16 * 16, sourceTerrain.sampledCells()); - } - - @Test - public void customDimensionKeyUsesRegisteredVanillaDimensionType() { - ResourceKey customDimension = ResourceKey.create( - Registries.DIMENSION, Identifier.parse("iris:custom_nether")); - - assertEquals(Blocks.NETHERRACK.defaultBlockState(), - NativeStructureTerrainIntegrator.defaultEncaseBlock( - customDimension, BuiltinDimensionTypes.NETHER, null, 64)); - assertEquals(Blocks.END_STONE.defaultBlockState(), - NativeStructureTerrainIntegrator.defaultEncaseBlock( - customDimension, BuiltinDimensionTypes.END, null, 64)); - } - - @Test - public void configuredEncasePaletteReplacesTheDefaultMaterial() { - StructureStart start = start(TerrainAdjustment.BURY, 64); - BoundingBox bounds = start.getPieces().getFirst().getBoundingBox(); - Map blocks = new HashMap<>(); - IrisMaterialPalette palette = new IrisMaterialPalette().qclear().qadd("minecraft:tuff"); - - NativeStructureTerrainIntegrator.integrateTerrain( - world(blocks), bounds, "minecraft:stronghold", start, - new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.ENCASE) - .setEncasePalette(palette), - NativeStructurePostProcessorEncaseTest::tuffBlock); - - assertEquals(Blocks.TUFF.defaultBlockState(), - state(blocks, bounds.minX(), bounds.minY(), bounds.minZ())); - } - - @Test - public void encaseFillRunsBeforeNativePlacement() throws IOException { - String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n"); - int prepareTerrain = source.indexOf("NativeStructurePostProcessor.prepareTerrain("); - int placementLoop = source.indexOf("for (NativePlacementGroup group : placementGroups)", prepareTerrain); - int placement = source.indexOf("placeVanillaStructure(world, structureManager, random", placementLoop); - - assertTrue(prepareTerrain >= 0); - assertTrue(placementLoop > prepareTerrain); - assertTrue(placement > placementLoop); - } - - @Test - public void omittedTerrainConfigurationRetainsSourceSemantics() { - for (TerrainAdjustment adjustment : TerrainAdjustment.values()) { - IrisStructureTerrain resolved = NativeStructureTerrainIntegrator.resolveNativeTerrain( - start(adjustment, 64), null); - - assertEquals(IrisStructureTerrainMode.SOURCE, resolved.resolvedMode()); - } - } - - @Test - public void sourceBuryUsesTheVanillaSixByTwelveInfluenceEnvelope() { - StructureStart start = start(TerrainAdjustment.BURY, 64); - BoundingBox bounds = start.getPieces().getFirst().getBoundingBox(); - int groundY = bounds.minY(); - BoundingBox area = new BoundingBox( - bounds.minX() - 7, groundY - 13, bounds.minZ(), - bounds.maxX(), groundY + 13, bounds.maxZ()); - Map blocks = new HashMap<>(); - - NativeStructureTerrainIntegrator.integrateTerrain( - world(blocks), area, "test:bury", start, - new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE), null); - - assertEquals(Blocks.STONE.defaultBlockState(), - state(blocks, bounds.minX() - 5, groundY, bounds.minZ())); - assertEquals(Blocks.STONE.defaultBlockState(), - state(blocks, bounds.minX(), groundY + 11, bounds.minZ())); - assertEquals(Blocks.AIR.defaultBlockState(), - state(blocks, bounds.minX() - 6, groundY, bounds.minZ())); - assertEquals(Blocks.AIR.defaultBlockState(), - state(blocks, bounds.minX(), groundY + 12, bounds.minZ())); - assertEquals(Blocks.AIR.defaultBlockState(), - state(blocks, bounds.minX() - 7, groundY, bounds.minZ())); - assertEquals(Blocks.AIR.defaultBlockState(), - state(blocks, bounds.minX(), groundY + 13, bounds.minZ())); - } - - @Test - public void sourceEncapsulateWrapsTheFullPieceBounds() { - StructureStart start = start(TerrainAdjustment.ENCAPSULATE, 64); - BoundingBox bounds = start.getPieces().getFirst().getBoundingBox(); - BoundingBox area = new BoundingBox( - bounds.minX() - 13, bounds.minY(), bounds.minZ(), - bounds.maxX(), bounds.maxY() + 13, bounds.maxZ()); - Map blocks = new HashMap<>(); - - NativeStructureTerrainIntegrator.integrateTerrain( - world(blocks), area, "test:encapsulate", start, - new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE), null); - - assertEquals(Blocks.STONE.defaultBlockState(), - state(blocks, bounds.minX() - 11, bounds.minY(), bounds.minZ())); - assertEquals(Blocks.STONE.defaultBlockState(), - state(blocks, bounds.minX(), bounds.maxY() + 11, bounds.minZ())); - assertEquals(Blocks.AIR.defaultBlockState(), - state(blocks, bounds.minX() - 12, bounds.minY(), bounds.minZ())); - assertEquals(Blocks.AIR.defaultBlockState(), - state(blocks, bounds.minX(), bounds.maxY() + 12, bounds.minZ())); - assertEquals(Blocks.AIR.defaultBlockState(), - state(blocks, bounds.minX() - 13, bounds.minY(), bounds.minZ())); - assertEquals(Blocks.AIR.defaultBlockState(), - state(blocks, bounds.minX(), bounds.maxY() + 13, bounds.minZ())); - } - - @Test - public void sourceTerrainDensityOnlyUsesRigidPoolPieces() { - PoolElementStructurePiece terrainMatching = poolPiece(StructureTemplatePool.Projection.TERRAIN_MATCHING); - PoolElementStructurePiece rigid = poolPiece(StructureTemplatePool.Projection.RIGID); - - assertFalse(NativeStructureTerrainIntegrator.isSourceRigidPiece(terrainMatching)); - assertTrue(NativeStructureTerrainIntegrator.isSourceRigidPiece(rigid)); - } - - @Test - public void sourceJunctionTerrainUsesTheStrictLowerTwelveBlockEnvelope() { - assertTrue(NativeStructureTerrainIntegrator.insideSourceJunctionEnvelope(0, -1, 0)); - assertTrue(NativeStructureTerrainIntegrator.insideSourceJunctionEnvelope(0, -11, 0)); - assertFalse(NativeStructureTerrainIntegrator.insideSourceJunctionEnvelope(0, 0, 0)); - assertFalse(NativeStructureTerrainIntegrator.insideSourceJunctionEnvelope(0, -12, 0)); - assertFalse(NativeStructureTerrainIntegrator.insideSourceJunctionEnvelope(12, -1, 0)); - } - - @Test - public void explicitTerrainConfigurationWinsOverAutoEncase() { - IrisStructureTerrain configured = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.PRESERVE); - - assertSame(configured, NativeStructureTerrainIntegrator.resolveNativeTerrain( - start(TerrainAdjustment.BURY, 64), configured)); - } - - @Test - public void legacyTemplateAirIsClearedAfterEveryTerrainFillPath() { - IrisStructureTerrain source = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.SOURCE); - IrisStructureTerrain preserve = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.PRESERVE); - IrisStructureTerrain encase = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.ENCASE); - - assertTrue(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir( - start(TerrainAdjustment.BURY, 64), source)); - assertTrue(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir( - start(TerrainAdjustment.BEARD_BOX, 64), source)); - assertTrue(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir( - start(TerrainAdjustment.NONE, 64), encase)); - assertFalse(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir( - start(TerrainAdjustment.NONE, 64), source)); - assertFalse(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir( - start(TerrainAdjustment.BURY, 64), preserve)); - } - - @Test - public void encaseReservesTheNeighborChunkEnvelope() { - StructureStart generated = start(TerrainAdjustment.BURY, 64); - BoundingBox sourceBounds = generated.getBoundingBox(); - BoundingBox content = NativeStructureReferenceEnvelope.contentBounds(generated); - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.ENCASE) - .setHorizontalPadding(4); - - StructureStart wrapped = NativeStructureReferenceEnvelope.wrap( - generated, - generated.getStructure(), - 0, - terrain); - BoundingBox referenceBounds = NativeStructureReferenceEnvelope.referenceBounds( - wrapped, wrapped.getStructure(), terrain); - - assertEquals(sourceBounds, wrapped.getBoundingBox()); - assertEquals(content.minX() - 4, referenceBounds.minX()); - assertEquals(content.maxX() + 4, referenceBounds.maxX()); - assertEquals(content.minZ() - 4, referenceBounds.minZ()); - assertEquals(content.maxZ() + 4, referenceBounds.maxZ()); - assertEquals(generated.getPieces().size(), wrapped.getPieces().size()); - } - - @Test - public void referenceEnvelopeRejectsChunkCoordinateOverflow() { - StructureStart generated = start(TerrainAdjustment.NONE, 64); - StructureStart extreme = new StructureStart( - generated.getStructure(), new ChunkPos(Integer.MAX_VALUE, 0), 0, - new PiecesContainer(generated.getPieces())); - - assertThrows(IllegalStateException.class, () -> - NativeStructureReferenceEnvelope.referenceBounds( - extreme, extreme.getStructure(), new IrisStructureTerrain())); - } - - @Test - public void explicitTerrainEnvelopeDoesNotInheritSourceAdjustment() { - StructureStart generated = start(TerrainAdjustment.BURY, 64); - BoundingBox content = NativeStructureReferenceEnvelope.contentBounds(generated); - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.ENCASE) - .setHorizontalPadding(112); - - StructureStart wrapped = NativeStructureReferenceEnvelope.wrap( - generated, generated.getStructure(), 0, terrain); - BoundingBox referenceBounds = NativeStructureReferenceEnvelope.referenceBounds( - wrapped, wrapped.getStructure(), terrain); - - assertEquals(content.minX() - 112, referenceBounds.minX()); - assertEquals(content.maxX() + 112, referenceBounds.maxX()); - } - - @Test - public void yBandRelocatesTheStartMidpointDeterministically() { - IrisStructureYBand band = new IrisStructureYBand().setMin(-120).setMax(-20); - StructureStart first = start(TerrainAdjustment.BURY, 64); - StructureStart second = start(TerrainAdjustment.BURY, 64); - - NativeStructureVerticalPlacer.applyVerticalShift( - first, -64, -256, 320, true, false, band, (x, z) -> 40); - NativeStructureVerticalPlacer.applyVerticalShift( - second, -64, -256, 320, true, false, band, (x, z) -> 40); - - BoundingBox bounds = first.getBoundingBox(); - assertEquals(bounds.minY(), second.getBoundingBox().minY()); - assertTrue(bounds.minY() >= -120); - assertTrue(bounds.maxY() <= -20); - - int repeated = NativeStructureVerticalPlacer.applyVerticalShift( - first, -64, -256, 320, true, false, band, (x, z) -> 40); - assertEquals(0, repeated); - } - - @Test - public void yBandClampsWhenTheBandCannotContainTheStructure() { - IrisStructureYBand band = new IrisStructureYBand().setMin(-50).setMax(-45); - StructureStart start = start(TerrainAdjustment.BURY, 64); - - NativeStructureVerticalPlacer.applyVerticalShift( - start, 0, -256, 320, true, false, band, (x, z) -> 40); - - BoundingBox bounds = start.getBoundingBox(); - int midpoint = bounds.minY() + (bounds.maxY() - bounds.minY()) / 2; - assertTrue(midpoint >= -50); - assertTrue(midpoint <= -45); - } - - @Test - public void yBandReplacesBothTheBlindShiftAndBurial() { - IrisStructureYBand band = new IrisStructureYBand().setMin(-64).setMax(-64); - StructureStart start = start(TerrainAdjustment.BURY, 64); - BoundingBox bounds = start.getBoundingBox(); - int height = bounds.maxY() - bounds.minY(); - - NativeStructureVerticalPlacer.applyVerticalShift( - start, -200, -256, 320, true, false, band, (x, z) -> 40); - - assertEquals(-64 - height / 2, start.getBoundingBox().minY()); - } - - @Test - public void preserveSourceYWinsOverTheConfiguredBand() { - IrisStructureYBand band = new IrisStructureYBand().setMin(-120).setMax(-20); - StructureStart start = start(TerrainAdjustment.BURY, 64); - int minY = start.getBoundingBox().minY(); - - int offset = NativeStructureVerticalPlacer.applyVerticalShift( - start, 0, -256, 320, true, true, band, (x, z) -> 40); - - assertEquals(0, offset); - assertEquals(minY, start.getBoundingBox().minY()); - } - - private static BlockState tuffBlock(IrisMaterialPalette palette, RNG rng, int x, int y, int z) { - assertNotNull(palette); - assertNotNull(rng); - return Blocks.TUFF.defaultBlockState(); - } - - private static StructureStart start(TerrainAdjustment adjustment, int minY) { - Structure structure = new DesertPyramidStructure(new Structure.StructureSettings( - HolderSet.empty(), Map.of(), GenerationStep.Decoration.STRONGHOLDS, adjustment)); - StructurePiece piece = new DesertPyramidPiece(RandomSource.create(7L), 0, 0); - piece.move(0, minY - piece.getBoundingBox().minY(), 0); - return new StructureStart( - structure, new ChunkPos(0, 0), 0, new PiecesContainer(List.of(piece))); - } - - private static PoolElementStructurePiece poolPiece(StructureTemplatePool.Projection projection) { - BlockPos position = new BlockPos(0, 64, 0); - StructurePoolElement element = StructurePoolElement.single( - "minecraft:empty", - Holder.direct(new StructureProcessorList(List.of( - BlockIgnoreProcessor.STRUCTURE_AND_AIR))), - LiquidSettings.APPLY_WATERLOGGING - ).apply(projection); - return new PoolElementStructurePiece( - null, - element, - position, - 0, - Rotation.NONE, - new BoundingBox(position), - LiquidSettings.APPLY_WATERLOGGING); - } - - private static WorldGenLevel world(Map blocks) { - InvocationHandler handler = (proxy, method, arguments) -> { - String methodName = method.getName(); - if (methodName.equals("getBlockState")) { - BlockPos position = (BlockPos) arguments[0]; - return state(blocks, position.getX(), position.getY(), position.getZ()); - } - if (methodName.equals("setBlock")) { - BlockPos position = (BlockPos) arguments[0]; - BlockState blockState = (BlockState) arguments[1]; - put(blocks, position.getX(), position.getY(), position.getZ(), blockState); - return true; - } - if (methodName.equals("getSeed")) { - return TEST_SEED; - } - if (methodName.equals("getLevel")) { - return null; - } - if (methodName.equals("hashCode")) { - return System.identityHashCode(proxy); - } - if (methodName.equals("equals")) { - return proxy == arguments[0]; - } - if (methodName.equals("toString")) { - return "encase-test-world"; - } - throw new UnsupportedOperationException(method.toString()); - }; - return (WorldGenLevel) Proxy.newProxyInstance( - WorldGenLevel.class.getClassLoader(), new Class[]{WorldGenLevel.class}, handler); - } - - private static NativeStructureTerrainIntegrator.SourceTerrainSnapshot sourceSnapshot( - WorldGenLevel world, BoundingBox area) { - BitSet requiredLayers = new BitSet(area.getYSpan()); - requiredLayers.set(0, area.getYSpan()); - return NativeStructureTerrainIntegrator.SourceTerrainSnapshot.capture( - world, area, requiredLayers); - } - - private static void put(Map blocks, - int x, int y, int z, BlockState state) { - blocks.put(new BlockPos(x, y, z), state); - } - - private static BlockState state(Map blocks, int x, int y, int z) { - return blocks.getOrDefault(new BlockPos(x, y, z), Blocks.AIR.defaultBlockState()); - } -} diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorMonumentTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorMonumentTest.java index 86001ddfd..b3f82a2f4 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorMonumentTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorMonumentTest.java @@ -1,7 +1,6 @@ package art.arcane.iris.nativegen; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; +import art.arcane.iris.engine.framework.NativeStructureReach; import net.minecraft.SharedConstants; import net.minecraft.core.Direction; import net.minecraft.core.HolderSet; @@ -41,7 +40,7 @@ public class NativeStructurePostProcessorMonumentTest { StructureStart start = monumentStart(1337L); int offset = NativeStructureVerticalPlacer.applyVerticalPlacement( - start, "minecraft:monument", 0, 63, -64, 320, false, false, null, (x, z) -> 0); + start, "minecraft:monument", 0, 63, -64, 320, (x, z) -> 0); assertEquals(0, offset); assertEquals(39, start.getBoundingBox().minY()); @@ -57,7 +56,7 @@ public class NativeStructurePostProcessorMonumentTest { BoundingBox cachedBounds = start.getBoundingBox(); int offset = NativeStructureVerticalPlacer.applyVerticalPlacement( - start, "minecraft:monument", 0, 50, -256, 512, false, false, null, (x, z) -> 0); + start, "minecraft:monument", 0, 50, -256, 512, (x, z) -> 0); assertEquals(-13, offset); assertSame(cachedBounds, start.getBoundingBox()); @@ -71,7 +70,7 @@ public class NativeStructurePostProcessorMonumentTest { } int repeatedOffset = NativeStructureVerticalPlacer.applyVerticalPlacement( - start, "minecraft:monument", 0, 50, -256, 512, false, false, null, (x, z) -> 0); + start, "minecraft:monument", 0, 50, -256, 512, (x, z) -> 0); assertEquals(0, repeatedOffset); } @@ -80,7 +79,7 @@ public class NativeStructurePostProcessorMonumentTest { StructureStart start = monumentStart(1337L); int offset = NativeStructureVerticalPlacer.applyVerticalPlacement( - start, "minecraft:monument", 3, 50, -256, 512, false, false, null, (x, z) -> 0); + start, "minecraft:monument", 3, 50, -256, 512, (x, z) -> 0); assertEquals(-10, offset); assertEquals(29, start.getBoundingBox().minY()); @@ -94,13 +93,10 @@ public class NativeStructurePostProcessorMonumentTest { start, start.getStructure(), 0, - new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.FORCE_CARVE) - .setHorizontalPadding(4)); + List.of(new NativeStructureReach(false, 4))); int offset = NativeStructureVerticalPlacer.applyVerticalPlacement( - wrapped, "minecraft:monument", 0, 63, -64, 320, - false, false, null, (x, z) -> 0); + wrapped, "minecraft:monument", 0, 63, -64, 320, (x, z) -> 0); assertEquals(0, offset); assertEquals(1, wrapped.getPieces().size()); @@ -112,7 +108,7 @@ public class NativeStructurePostProcessorMonumentTest { ChunkPos chunkPos = new ChunkPos(0, 0); StructureStart initial = monumentStart(seed); NativeStructureVerticalPlacer.applyVerticalPlacement( - initial, "minecraft:monument", 0, 50, -256, 512, false, false, null, (x, z) -> 0); + initial, "minecraft:monument", 0, 50, -256, 512, (x, z) -> 0); PiecesContainer regenerated = OceanMonumentStructure.regeneratePiecesAfterLoad( chunkPos, seed, new PiecesContainer(initial.getPieces())); @@ -121,7 +117,7 @@ public class NativeStructurePostProcessorMonumentTest { assertEquals(39, reloaded.getBoundingBox().minY()); int offset = NativeStructureVerticalPlacer.applyVerticalPlacement( - reloaded, "minecraft:monument", 0, 50, -256, 512, false, false, null, (x, z) -> 0); + reloaded, "minecraft:monument", 0, 50, -256, 512, (x, z) -> 0); assertEquals(-13, offset); assertEquals(26, reloaded.getBoundingBox().minY()); assertEquals(48, reloaded.getBoundingBox().maxY()); @@ -133,8 +129,7 @@ public class NativeStructurePostProcessorMonumentTest { ChunkPos chunkPos = new ChunkPos(0, 0); StructureStart initial = monumentStart(seed); NativeStructureVerticalPlacer.applyVerticalPlacement( - initial, "minecraft:monument", 0, 50, -256, 512, - false, false, null, (x, z) -> 0); + initial, "minecraft:monument", 0, 50, -256, 512, (x, z) -> 0); PiecesContainer regenerated = OceanMonumentStructure.regeneratePiecesAfterLoad( chunkPos, seed, new PiecesContainer(initial.getPieces())); StructureStart reloaded = new StructureStart( @@ -147,7 +142,7 @@ public class NativeStructurePostProcessorMonumentTest { futures.add(executor.submit(() -> { release.await(); NativeStructureVerticalPlacer.ensureMonumentSeaLevelAlignment( - reloaded, "minecraft:monument", 0, 50, -256, 512); + reloaded, "minecraft:monument", () -> 0, 50, -256, 512); return null; })); } @@ -168,7 +163,7 @@ public class NativeStructurePostProcessorMonumentTest { StructureStart start = monumentStart(1337L); try { NativeStructureVerticalPlacer.applyVerticalPlacement( - start, "minecraft:monument", 0, -50, -64, 320, false, false, null, (x, z) -> 0); + start, "minecraft:monument", 0, -50, -64, 320, (x, z) -> 0); } catch (IllegalStateException error) { assertTrue(error.getMessage().contains("cannot align")); return; diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorScatteredFeatureTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorScatteredFeatureTest.java index c560dc1b4..2acb12b73 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorScatteredFeatureTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorScatteredFeatureTest.java @@ -11,6 +11,7 @@ import net.minecraft.world.level.levelgen.structure.ScatteredFeaturePiece; 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; @@ -46,8 +47,7 @@ public class NativeStructurePostProcessorScatteredFeatureTest { BoundingBox footprint = piece.getBoundingBox(); int offset = NativeStructureVerticalPlacer.applyVerticalPlacement( - start, "minecraft:desert_pyramid", 0, 63, -64, 320, false, false, null, - (x, z) -> x == footprint.maxX() && z == footprint.maxZ() ? 64 : 92); + start, "minecraft:desert_pyramid", 0, 63, -64, 320, (x, z) -> x == footprint.maxX() && z == footprint.maxZ() ? 64 : 92); assertEquals(1, offset); assertSame(cachedBounds, start.getBoundingBox()); @@ -64,8 +64,7 @@ public class NativeStructurePostProcessorScatteredFeatureTest { BoundingBox footprint = piece.getBoundingBox(); int offset = NativeStructureVerticalPlacer.applyVerticalPlacement( - start, "minecraft:jungle_pyramid", 4, 63, -64, 320, false, false, null, - (x, z) -> x == footprint.minX() && z == footprint.minZ() ? 88 : 70); + start, "minecraft:jungle_pyramid", 4, 63, -64, 320, (x, z) -> x == footprint.minX() && z == footprint.minZ() ? 88 : 70); assertEquals(11, offset); assertEquals(75, piece.getBoundingBox().minY()); @@ -79,9 +78,9 @@ public class NativeStructurePostProcessorScatteredFeatureTest { StructureStart start = desertStart(piece); int initialOffset = NativeStructureVerticalPlacer.applyVerticalPlacement( - start, "minecraft:desert_pyramid", 0, 63, -64, 320, false, false, null, (x, z) -> 80); + start, "minecraft:desert_pyramid", 0, 63, -64, 320, (x, z) -> 80); int repeatedOffset = NativeStructureVerticalPlacer.applyVerticalPlacement( - start, "minecraft:desert_pyramid", 0, 63, -64, 320, false, false, null, (x, z) -> 80); + start, "minecraft:desert_pyramid", 0, 63, -64, 320, (x, z) -> 80); assertEquals(17, initialOffset); assertEquals(0, repeatedOffset); @@ -94,7 +93,7 @@ public class NativeStructurePostProcessorScatteredFeatureTest { StructureStart start = desertStart(piece); int offset = NativeStructureVerticalPlacer.applyVerticalPlacement( - start, "minecraft:desert_pyramid", 0, 63, -64, 320, false, false, null, (x, z) -> 318); + start, "minecraft:desert_pyramid", 0, 63, -64, 320, (x, z) -> 318); assertEquals(241, offset); assertEquals(305, piece.getBoundingBox().minY()); @@ -110,14 +109,13 @@ public class NativeStructurePostProcessorScatteredFeatureTest { StructureStart jungleStart = jungleStart(jungle); StructureStart swampStart = swampStart(swamp); - assertFalse(NativeStructureSurfaceFitter.requiresSurfaceTerrain(desertStart)); - assertFalse(NativeStructureSurfaceFitter.requiresSurfaceTerrain(jungleStart)); - assertFalse(NativeStructureSurfaceFitter.requiresSurfaceTerrain(swampStart)); + assertEquals(TerrainAdjustment.NONE, desertStart.getStructure().terrainAdaptation()); + assertEquals(TerrainAdjustment.NONE, jungleStart.getStructure().terrainAdaptation()); + assertEquals(TerrainAdjustment.NONE, swampStart.getStructure().terrainAdaptation()); AtomicInteger terrainQueries = new AtomicInteger(); int offset = NativeStructureVerticalPlacer.applyVerticalPlacement( - swampStart, "minecraft:swamp_hut", 0, 63, -64, 320, false, false, null, - (x, z) -> terrainQueries.incrementAndGet()); + swampStart, "minecraft:swamp_hut", 0, 63, -64, 320, (x, z) -> terrainQueries.incrementAndGet()); assertEquals(0, offset); assertEquals(0, terrainQueries.get()); assertEquals(64, swamp.getBoundingBox().minY()); @@ -142,7 +140,7 @@ public class NativeStructurePostProcessorScatteredFeatureTest { int pyramidMinY = pyramidOverride.getBoundingBox().minY(); int pyramidOffset = NativeStructureVerticalPlacer.applyVerticalPlacement( pyramidOverride, "minecraft:desert_pyramid", 5, - 63, -64, 320, false, false, null, (x, z) -> 200); + 63, -64, 320, (x, z) -> 200); assertEquals(5, pyramidOffset); assertEquals(pyramidMinY + 5, pyramidOverride.getBoundingBox().minY()); @@ -151,7 +149,7 @@ public class NativeStructurePostProcessorScatteredFeatureTest { new SwampHutPiece(RandomSource.create(47L), 0, 0)); int monumentMinY = monumentOverride.getBoundingBox().minY(); NativeStructureVerticalPlacer.ensureMonumentSeaLevelAlignment( - monumentOverride, "minecraft:monument", 0, 40, -64, 320); + monumentOverride, "minecraft:monument", () -> 0, 40, -64, 320); assertEquals(monumentMinY, monumentOverride.getBoundingBox().minY()); } diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorSurfaceTerrainTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorSurfaceTerrainTest.java deleted file mode 100644 index 8fb803452..000000000 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorSurfaceTerrainTest.java +++ /dev/null @@ -1,2375 +0,0 @@ -package art.arcane.iris.nativegen; - -import art.arcane.iris.engine.mantle.components.StructureCarvingFootprint; -import art.arcane.iris.engine.object.structure.IrisStructureCarveShape; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; -import com.mojang.datafixers.util.Either; -import com.mojang.serialization.Codec; -import net.minecraft.SharedConstants; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Holder; -import net.minecraft.core.HolderSet; -import net.minecraft.core.IdMapper; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.server.Bootstrap; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.LevelHeightAccessor; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.block.Block; -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.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.LevelChunkSection; -import net.minecraft.world.level.chunk.PalettedContainer; -import net.minecraft.world.level.chunk.PalettedContainerFactory; -import net.minecraft.world.level.chunk.ProtoChunk; -import net.minecraft.world.level.chunk.Strategy; -import net.minecraft.world.level.chunk.UpgradeData; -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.ListPoolElement; -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.templatesystem.AlwaysTrueTest; -import net.minecraft.world.level.levelgen.structure.templatesystem.BlockStateMatchTest; -import net.minecraft.world.level.levelgen.structure.templatesystem.LiquidSettings; -import net.minecraft.world.level.levelgen.structure.templatesystem.ProcessorRule; -import net.minecraft.world.level.levelgen.structure.templatesystem.RuleProcessor; -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.StructurePlaceSettings; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorList; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessor; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; -import net.minecraft.world.level.levelgen.placement.PlacedFeature; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Modifier; -import java.lang.reflect.Proxy; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; - -public class NativeStructurePostProcessorSurfaceTerrainTest { - private static final int SLAB_DEPTH = 128; - private static final int SLAB_MIN_Y = 64; - private static final int SLAB_PADDING = 14; - private static final int SLAB_WIDTH = 16; - private static final long TEST_SEED = 8675309L; - - @BeforeClass - public static void bootstrapMinecraft() { - SharedConstants.tryDetectVersion(); - Bootstrap.bootStrap(); - } - - @Test - public void sourceBeardAdjustmentsPrepareOnlyAtTheSurfaceStructuresStep() { - assertTrue(NativeStructureSurfaceFitter.shouldPrepareSurfaceTerrain( - TerrainAdjustment.BEARD_THIN, GenerationStep.Decoration.SURFACE_STRUCTURES)); - assertFalse(NativeStructureSurfaceFitter.shouldPrepareSurfaceTerrain( - TerrainAdjustment.BEARD_BOX, GenerationStep.Decoration.FLUID_SPRINGS)); - assertFalse(NativeStructureSurfaceFitter.shouldPrepareSurfaceTerrain( - TerrainAdjustment.BEARD_THIN, GenerationStep.Decoration.UNDERGROUND_STRUCTURES)); - assertFalse(NativeStructureSurfaceFitter.shouldPrepareSurfaceTerrain( - TerrainAdjustment.BEARD_BOX, GenerationStep.Decoration.UNDERGROUND_DECORATION)); - assertFalse(NativeStructureSurfaceFitter.shouldPrepareSurfaceTerrain( - TerrainAdjustment.BEARD_THIN, GenerationStep.Decoration.STRONGHOLDS)); - } - - @Test - public void nonBeardAdjustmentsDoNotPrepareSurfaceTerrain() { - assertFalse(NativeStructureSurfaceFitter.shouldPrepareSurfaceTerrain( - TerrainAdjustment.BURY, GenerationStep.Decoration.SURFACE_STRUCTURES)); - assertFalse(NativeStructureSurfaceFitter.shouldPrepareSurfaceTerrain( - TerrainAdjustment.ENCAPSULATE, GenerationStep.Decoration.SURFACE_STRUCTURES)); - assertFalse(NativeStructureSurfaceFitter.shouldPrepareSurfaceTerrain( - TerrainAdjustment.NONE, GenerationStep.Decoration.FLUID_SPRINGS)); - } - - @Test - public void shallowUndergroundBeardBoxDoesNotMutateTheTopSurface() throws Exception { - PoolElementStructurePiece piece = rigidTemplatePiece( - new InlineSinglePoolElement(template(List.of( - block(0, 1, 0, Blocks.DEEPSLATE_BRICKS.defaultBlockState())))), - new BoundingBox(0, 67, 0, 0, 74, 0), 1, Rotation.NONE); - Structure structure = new DesertPyramidStructure( - new Structure.StructureSettings( - HolderSet.empty(), Map.of(), - GenerationStep.Decoration.UNDERGROUND_DECORATION, - TerrainAdjustment.BEARD_BOX)); - StructureStart start = new StructureStart( - structure, new ChunkPos(0, 0), 0, - new PiecesContainer(List.of(piece))); - BoundingBox area = new BoundingBox(0, 48, 0, 0, 80, 0); - Map blocks = flatTerrain(area, 64); - Map before = new HashMap<>(blocks); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, List.of(surfaceTarget(start)), - (x, z) -> 64); - - assertEquals(before, blocks); - } - - @Test - public void explicitTerrainOverrideDisablesSourceBeardFitting() { - StructureStart start = desertStart(TerrainAdjustment.BEARD_BOX); - - assertTrue(NativeStructureSurfaceFitter.requiresSurfaceTerrain( - new NativeStructureTerrainIntegrator.TerrainTarget( - "test:beard_box", start, - new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE)))); - assertFalse(NativeStructureSurfaceFitter.requiresSurfaceTerrain( - new NativeStructureTerrainIntegrator.TerrainTarget( - "test:beard_box", start, - new IrisStructureTerrain().setMode(IrisStructureTerrainMode.PRESERVE)))); - } - - @Test - public void explicitVacuumUsesIndependentTerrainFittingWithoutAuthoredAdaptation() { - StructureStart none = desertStart(TerrainAdjustment.NONE); - StructureStart box = desertStart(TerrainAdjustment.BEARD_BOX); - NativeStructureTerrainIntegrator.TerrainTarget sourceNone = - new NativeStructureTerrainIntegrator.TerrainTarget( - "test:none", none, - new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE)); - NativeStructureTerrainIntegrator.TerrainTarget vacuumNone = - new NativeStructureTerrainIntegrator.TerrainTarget( - "test:none", none, - new IrisStructureTerrain().setMode(IrisStructureTerrainMode.VACUUM)); - NativeStructureTerrainIntegrator.TerrainTarget vacuumBox = - new NativeStructureTerrainIntegrator.TerrainTarget( - "test:box", box, - new IrisStructureTerrain().setMode(IrisStructureTerrainMode.VACUUM)); - - assertFalse(NativeStructureSurfaceFitter.requiresSurfaceTerrain(sourceNone)); - assertTrue(NativeStructureSurfaceFitter.requiresSurfaceTerrain(vacuumNone)); - assertTrue(NativeStructureSurfaceFitter.requiresSurfaceTerrain(vacuumBox)); - assertFalse(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir( - none, vacuumNone.terrain())); - } - - @Test - public void sourceSurfaceAnchorMeetsOneBlockBelowTheAuthoredGroundPlane() { - BoundingBox bounds = new BoundingBox(0, 64, 0, 4, 90, 4); - NativeStructureSurfaceFitter.SurfaceAnchor anchor = - NativeStructureSurfaceFitter.surfaceAnchor(bounds, 68, 2); - - assertEquals(67, anchor.meetY()); - assertEquals(0, anchor.minX()); - assertEquals(4, anchor.maxX()); - assertEquals(0, anchor.minZ()); - assertEquals(4, anchor.maxZ()); - } - - @Test - public void rigidFootprintsBoundTerrainAcrossGapsLargerThanTheBeardKernel() { - NativeStructureSurfaceFitter.SurfaceAnchor rigid = anchor(72, 2); - NativeStructureSurfaceFitter.SurfaceAnchor junction = anchor(72, 1); - - assertEquals(46, NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(rigid), 2, 2, 40)); - assertEquals(46, NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(junction), 2, 2, 40)); - } - - @Test - public void beardSkirtBoundsAndGradesUpwardAndDownwardSymmetrically() { - int originalY = 64; - NativeStructureSurfaceFitter.SurfaceAnchor high = anchor(96, 2); - NativeStructureSurfaceFitter.SurfaceAnchor low = anchor(32, 2); - int[] raised = new int[13]; - int[] lowered = new int[13]; - for (int outset = 0; outset <= 12; outset++) { - int x = 4 + outset; - raised[outset] = NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(high), x, 2, originalY); - lowered[outset] = NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(low), x, 2, originalY); - } - - assertArrayEquals( - new int[]{70, 69, 68, 67, 67, 66, 66, 65, 65, 64, 64, 64, 64}, - raised); - assertArrayEquals( - new int[]{58, 59, 60, 61, 61, 62, 62, 63, 63, 64, 64, 64, 64}, - lowered); - for (int outset = 0; outset <= 12; outset++) { - assertEquals(raised[outset] - originalY, originalY - lowered[outset]); - } - } - - @Test - public void projectedCenterAndRigidChildrenUseProcessedFoundationCells() throws Exception { - Structure structure = new DesertPyramidStructure( - new Structure.StructureSettings( - HolderSet.empty(), Map.of(), - GenerationStep.Decoration.SURFACE_STRUCTURES, - TerrainAdjustment.BEARD_BOX)); - PoolElementStructurePiece center = rigidTemplatePiece( - new InlineSinglePoolElement(template(List.of( - block(1, 1, 1, Blocks.COBBLESTONE.defaultBlockState())))), - new BoundingBox(0, 71, 0, 3, 80, 3), 1, Rotation.NONE); - PoolElementStructurePiece child = rigidTemplatePiece( - new InlineSinglePoolElement(template(List.of( - block(1, 7, 1, Blocks.COBBLESTONE.defaultBlockState())))), - new BoundingBox(10, 65, 0, 13, 76, 3), 7, Rotation.NONE); - StructureStart start = new StructureStart( - structure, new ChunkPos(0, 0), 0, - new PiecesContainer(List.of(center, child))); - BoundingBox area = new BoundingBox(0, 60, 0, 15, 90, 15); - Map blocks = new HashMap<>(); - for (int x = area.minX(); x <= area.maxX(); x++) { - for (int z = area.minZ(); z <= area.maxZ(); z++) { - put(blocks, x, 64, z, Blocks.DIRT.defaultBlockState()); - put(blocks, x, 65, z, Blocks.GRASS_BLOCK.defaultBlockState()); - } - } - - List targets = List.of( - new NativeStructureTerrainIntegrator.TerrainTarget( - "nova_structures:tavern_oak", start, - new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE))); - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, targets, - (x, z) -> 65); - - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 1, 71, 1)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 11, 71, 1)); - assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 11, 70, 1)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 2, 65, 2)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 12, 65, 2)); - } - - @Test - public void sparseRigidFootprintsIgnoreAirAndSolidsAboveTheGroundPlane() throws Exception { - StructureTemplate sparseTemplate = template(List.of( - block(0, 1, 0, Blocks.COBBLESTONE.defaultBlockState()), - block(15, 1, 0, Blocks.AIR.defaultBlockState()), - block(30, 5, 0, Blocks.STONE.defaultBlockState()))); - PoolElementStructurePiece piece = rigidTemplatePiece( - new InlineSinglePoolElement(sparseTemplate), - new BoundingBox(0, 68, 0, 30, 76, 0), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart( - List.of(piece), TerrainAdjustment.BEARD_THIN); - BoundingBox area = new BoundingBox(0, 52, 0, 30, 80, 0); - Map blocks = flatTerrain(area, 64); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, List.of(surfaceTarget(start)), - (x, z) -> 64); - - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 68, 0)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 15, 64, 0)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 30, 64, 0)); - } - - @Test - public void extremeRigidFoundationGapDoesNotCreateATerrainPillar() throws Exception { - StructureTemplate template = template(List.of( - block(0, 1, 0, Blocks.COBBLESTONE.defaultBlockState()))); - PoolElementStructurePiece piece = rigidTemplatePiece( - new InlineSinglePoolElement(template), - new BoundingBox(0, 90, 0, 0, 96, 0), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart( - List.of(piece), TerrainAdjustment.BEARD_THIN); - BoundingBox area = new BoundingBox(0, 30, 0, 0, 100, 0); - Map blocks = flatTerrain(area, 40); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, List.of(surfaceTarget(start)), - (x, z) -> 40); - - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 46, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 47, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 89, 0)); - } - - @Test - public void terrainMatchingFootprintsFollowProcessedLowestSolidColumns() throws Exception { - StructureTemplate pathTemplate = template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState()), - block(0, 2, 0, Blocks.DIRT.defaultBlockState()), - block(15, 0, 0, Blocks.AIR.defaultBlockState()), - block(30, 0, 0, Blocks.DIRT.defaultBlockState()), - block(45, 0, 0, Blocks.DANDELION.defaultBlockState()))); - InlineSinglePoolElement element = new InlineSinglePoolElement( - pathTemplate, List.of(), StructureTemplatePool.Projection.TERRAIN_MATCHING); - PoolElementStructurePiece piece = rigidTemplatePiece( - element, new BoundingBox(0, 68, 0, 45, 74, 0), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart( - List.of(piece), TerrainAdjustment.BEARD_THIN); - BoundingBox area = new BoundingBox(0, 52, 0, 45, 76, 0); - Map blocks = flatTerrain(area, 64); - blocks.remove(new BlockPos(0, 63, 0)); - blocks.remove(new BlockPos(0, 64, 0)); - put(blocks, 0, 59, 0, Blocks.DIRT.defaultBlockState()); - put(blocks, 0, 60, 0, Blocks.GRASS_BLOCK.defaultBlockState()); - put(blocks, 30, 71, 0, Blocks.DIRT.defaultBlockState()); - put(blocks, 30, 72, 0, Blocks.GRASS_BLOCK.defaultBlockState()); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, List.of(surfaceTarget(start)), - (x, z) -> x == 0 ? 60 : x == 30 ? 72 : 64); - - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 61, 0)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 30, 71, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 30, 72, 0)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 15, 64, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 15, 65, 0)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 45, 64, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 45, 65, 0)); - } - - @Test - public void vacuumFitsOnlyProcessedSolidTemplateColumns() throws Exception { - StructureTemplate sparseTemplate = template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()), - block(15, 0, 0, Blocks.STONE.defaultBlockState()))); - InlineSinglePoolElement element = new InlineSinglePoolElement( - sparseTemplate, List.of(replaceBlockProcessor( - Blocks.STONE.defaultBlockState(), Blocks.AIR.defaultBlockState()))); - PoolElementStructurePiece piece = rigidTemplatePiece( - element, new BoundingBox(0, 64, 0, 15, 70, 3), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 56, 0, 15, 72, 3); - Map blocks = flatTerrain(area, 60); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, - List.of(surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - (x, z) -> 60); - - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 64, 0)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 63, 0)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 15, 60, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 15, 61, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 15, 64, 0)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 15, 60, 3)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 15, 64, 3)); - } - - @Test - public void vacuumSupportsGroundDeltaZeroFoundations() throws Exception { - StructureTemplate template = template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); - PoolElementStructurePiece piece = rigidTemplatePiece( - new InlineSinglePoolElement(template), - new BoundingBox(0, 66, 0, 0, 70, 0), 0, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 54, 0, 3, 72, 3); - Map blocks = flatTerrain(area, 60); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, - List.of(surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - (x, z) -> 60); - - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 65, 0)); - assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 64, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 66, 0)); - } - - @Test - public void vacuumFindsActualTerrainBelowNominalOpenAirSurface() throws Exception { - StructureTemplate template = template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); - PoolElementStructurePiece piece = rigidTemplatePiece( - new InlineSinglePoolElement(template), - new BoundingBox(0, 75, 0, 0, 81, 0), 2, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 54, 0, 3, 84, 3); - Map blocks = flatTerrain(area, 60); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, - List.of(surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - (x, z) -> 80); - - for (int y = 61; y <= 74; y++) { - assertFalse(state(blocks, 0, y, 0).isAir()); - } - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 74, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 75, 0)); - } - - @Test - public void vacuumSupportsFoundationBelowHigherNaturalSurface() throws Exception { - StructureTemplate template = template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); - PoolElementStructurePiece piece = rigidTemplatePiece( - new InlineLegacyPoolElement(template), - new BoundingBox(0, 75, 0, 0, 81, 0), 2, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 54, 0, 15, 84, 3); - Map blocks = flatTerrain(area, 60); - put(blocks, 0, 78, 0, Blocks.DIRT.defaultBlockState()); - put(blocks, 0, 79, 0, Blocks.GRASS_BLOCK.defaultBlockState()); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, - List.of(surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - (x, z) -> 79); - - for (int y = 61; y <= 74; y++) { - assertFalse(state(blocks, 0, y, 0).isAir()); - } - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 75, 0)); - assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 78, 0)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 79, 0)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 15, 60, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 15, 61, 0)); - } - - @Test - public void vacuumRepairUsesOnlyProcessedSolidFoundationColumns() throws Exception { - StructureTemplate template = template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()), - block(1, 0, 0, Blocks.STONE.defaultBlockState()), - block(2, 0, 0, Blocks.AIR.defaultBlockState()), - block(2, 2, 0, Blocks.COBBLESTONE.defaultBlockState()))); - InlineSinglePoolElement element = new InlineSinglePoolElement( - template, List.of(replaceBlockProcessor( - Blocks.STONE.defaultBlockState(), Blocks.AIR.defaultBlockState()))); - PoolElementStructurePiece piece = rigidTemplatePiece( - element, new BoundingBox(0, 65, 0, 2, 72, 0), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 54, 0, 3, 74, 3); - Map blocks = flatTerrain(area, 60); - - NativeStructureSurfaceFitter.VacuumFoundationPlan plan = - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, - List.of(surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - (x, z) -> 60); - for (int y = 61; y <= 64; y++) { - put(blocks, 0, y, 0, Blocks.CAVE_AIR.defaultBlockState()); - } - put(blocks, 0, 65, 0, Blocks.COBBLESTONE.defaultBlockState()); - put(blocks, 1, 65, 0, Blocks.COBBLESTONE.defaultBlockState()); - put(blocks, 2, 67, 0, Blocks.COBBLESTONE.defaultBlockState()); - BlockState processorAirSupport = state(blocks, 1, 64, 0); - BlockState authoredAirSupport = state(blocks, 2, 66, 0); - - NativeStructureSurfaceFitter.repairVacuumFoundations( - world(blocks), area, plan); - - for (int y = 61; y <= 64; y++) { - assertFalse(state(blocks, 0, y, 0).isAir()); - } - assertEquals(processorAirSupport, state(blocks, 1, 64, 0)); - assertEquals(authoredAirSupport, state(blocks, 2, 66, 0)); - } - - @Test - public void vacuumRepairPreservesOverlappingAuthoredInterior() throws Exception { - PoolElementStructurePiece lower = rigidTemplatePiece( - new InlineLegacyPoolElement(template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState()), - block(0, 1, 0, Blocks.AIR.defaultBlockState())))), - new BoundingBox(0, 61, 0, 0, 62, 0), 0, Rotation.NONE); - PoolElementStructurePiece upper = rigidTemplatePiece( - new InlineLegacyPoolElement(template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState())))), - new BoundingBox(0, 65, 0, 0, 70, 0), 0, Rotation.NONE); - StructureStart start = rigidSurfaceStart( - List.of(lower, upper), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 54, 0, 3, 72, 3); - Map blocks = flatTerrain(area, 60); - - NativeStructureSurfaceFitter.VacuumFoundationPlan plan = - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, - List.of(surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - (x, z) -> 60); - put(blocks, 0, 65, 0, Blocks.COBBLESTONE.defaultBlockState()); - - NativeStructureSurfaceFitter.repairVacuumFoundations( - world(blocks), area, plan); - - for (int y = 61; y <= 64; y++) { - assertTrue(state(blocks, 0, y, 0).isAir()); - } - } - - @Test - public void vacuumRepairIsStableAcrossSplitChunkAreas() throws Exception { - StructureTemplate template = template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()), - block(1, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); - PoolElementStructurePiece piece = rigidTemplatePiece( - new InlineLegacyPoolElement(template), - new BoundingBox(15, 65, 0, 16, 70, 0), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); - NativeStructureTerrainIntegrator.TerrainTarget target = - surfaceTarget(start, IrisStructureTerrainMode.VACUUM); - BoundingBox wideArea = new BoundingBox(0, 54, 0, 31, 72, 15); - BoundingBox westArea = new BoundingBox(0, 54, 0, 15, 72, 15); - BoundingBox eastArea = new BoundingBox(16, 54, 0, 31, 72, 15); - Map wideBlocks = flatTerrain(wideArea, 60); - Map splitBlocks = flatTerrain(wideArea, 60); - - NativeStructureSurfaceFitter.VacuumFoundationPlan widePlan = - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(wideBlocks), wideArea, List.of(target), (x, z) -> 60); - NativeStructureSurfaceFitter.VacuumFoundationPlan westPlan = - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(splitBlocks), westArea, List.of(target), (x, z) -> 60); - NativeStructureSurfaceFitter.VacuumFoundationPlan eastPlan = - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(splitBlocks), eastArea, List.of(target), (x, z) -> 60); - for (int x = 15; x <= 16; x++) { - for (int y = 61; y <= 64; y++) { - put(wideBlocks, x, y, 0, Blocks.CAVE_AIR.defaultBlockState()); - put(splitBlocks, x, y, 0, Blocks.CAVE_AIR.defaultBlockState()); - } - put(wideBlocks, x, 65, 0, Blocks.COBBLESTONE.defaultBlockState()); - put(splitBlocks, x, 65, 0, Blocks.COBBLESTONE.defaultBlockState()); - } - - NativeStructureSurfaceFitter.repairVacuumFoundations( - world(wideBlocks), wideArea, widePlan); - NativeStructureSurfaceFitter.repairVacuumFoundations( - world(splitBlocks), eastArea, eastPlan); - NativeStructureSurfaceFitter.repairVacuumFoundations( - world(splitBlocks), westArea, westPlan); - - assertEquals(wideBlocks, splitBlocks); - } - - @Test - public void vacuumNeverLowersExistingTerrainAroundSparsePieces() throws Exception { - StructureTemplate sparseTemplate = template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); - PoolElementStructurePiece piece = rigidTemplatePiece( - new InlineSinglePoolElement(sparseTemplate), - new BoundingBox(0, 56, 0, 7, 62, 7), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 48, 0, 7, 70, 7); - Map blocks = flatTerrain(area, 60); - Map originalBlocks = new HashMap<>(blocks); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, - List.of(surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - (x, z) -> 60); - - assertEquals(originalBlocks, blocks); - } - - @Test - public void vacuumDoesNotRaiseTerrainToRoofsAboveLegacyAir() throws Exception { - StructureTemplate template = template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState()), - block(0, 2, 0, Blocks.COBBLESTONE.defaultBlockState()))); - PoolElementStructurePiece piece = rigidTemplatePiece( - new InlineLegacyPoolElement(template), - new BoundingBox(0, 66, 0, 7, 72, 7), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 54, 0, 15, 74, 15); - Map blocks = flatTerrain(area, 60); - Map originalBlocks = new HashMap<>(blocks); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, - List.of(surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - (x, z) -> 60); - - assertEquals(originalBlocks, blocks); - } - - @Test - public void vacuumCapsNeighborTaperAtAuthoredAirGroundPlanes() throws Exception { - PoolElementStructurePiece roof = rigidTemplatePiece( - new InlineSinglePoolElement(template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState()), - block(0, 2, 0, Blocks.COBBLESTONE.defaultBlockState())))), - new BoundingBox(1, 66, 0, 1, 72, 0), 1, Rotation.NONE); - PoolElementStructurePiece highChild = rigidTemplatePiece( - new InlineSinglePoolElement(template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState())))), - new BoundingBox(0, 90, 0, 0, 94, 0), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart( - List.of(roof, highChild), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 54, 0, 15, 96, 15); - Map blocks = flatTerrain(area, 60); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, - List.of(surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - (x, z) -> 60); - - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 1, 66, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 1, 67, 0)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 89, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 90, 0)); - } - - @Test - public void vacuumDoesNotAnchorRoofsAboveProcessorCreatedAir() throws Exception { - StructureTemplate template = template(List.of( - block(0, 0, 0, Blocks.STONE.defaultBlockState()), - block(0, 2, 0, Blocks.COBBLESTONE.defaultBlockState()))); - PoolElementStructurePiece piece = rigidTemplatePiece( - new InlineSinglePoolElement(template, List.of(replaceBlockProcessor( - Blocks.STONE.defaultBlockState(), Blocks.AIR.defaultBlockState()))), - new BoundingBox(0, 66, 0, 7, 72, 7), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 54, 0, 15, 74, 15); - Map blocks = flatTerrain(area, 60); - Map originalBlocks = new HashMap<>(blocks); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, - List.of(surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - (x, z) -> 60); - - assertEquals(originalBlocks, blocks); - } - - @Test - public void vacuumDoesNotTreatSparseRoofCellsAsFoundations() throws Exception { - StructureTemplate template = template(List.of( - block(0, 0, 0, Blocks.SANDSTONE.defaultBlockState()), - block(1, 20, 0, Blocks.SANDSTONE.defaultBlockState()))); - PoolElementStructurePiece piece = rigidTemplatePiece( - new InlineSinglePoolElement(template), - new BoundingBox(0, 66, 0, 20, 100, 20), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 54, 0, 20, 102, 20); - Map blocks = flatTerrain(area, 60); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, - List.of(surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - (x, z) -> 60); - - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 65, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 66, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 1, 67, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 1, 86, 0)); - } - - @Test - public void vacuumDoesNotFlattenTerrainMatchingPoolPieces() throws Exception { - StructureTemplate template = template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); - PoolElementStructurePiece piece = rigidTemplatePiece( - new InlineSinglePoolElement( - template, List.of(), - StructureTemplatePool.Projection.TERRAIN_MATCHING), - new BoundingBox(0, 68, 0, 15, 72, 15), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 54, 0, 15, 74, 15); - Map blocks = flatTerrain(area, 60); - Map originalBlocks = new HashMap<>(blocks); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, - List.of(surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - (x, z) -> 60); - - assertEquals(originalBlocks, blocks); - } - - @Test - public void vacuumRetainsJunctionSmoothingForRigidFeaturePieces() { - StructurePoolElement feature = StructurePoolElement.feature( - Holder.direct(null)) - .apply(StructureTemplatePool.Projection.RIGID); - PoolElementStructurePiece piece = rigidTemplatePiece( - feature, new BoundingBox(4, 66, 4, 4, 70, 4), 1, Rotation.NONE); - piece.addJunction(new JigsawJunction( - 4, 66, 4, 0, StructureTemplatePool.Projection.RIGID)); - StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 54, 0, 15, 72, 15); - Map blocks = flatTerrain(area, 60); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, - List.of(surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - (x, z) -> 60); - - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 4, 61, 4)); - } - - @Test - public void vacuumDoesNotInventNonPoolBoundingBoxFootprints() { - StructureStart start = desertStart(TerrainAdjustment.NONE); - BoundingBox bounds = start.getBoundingBox(); - BoundingBox area = new BoundingBox( - bounds.minX() - 12, 40, bounds.minZ() - 12, - bounds.maxX() + 12, bounds.maxY() + 12, bounds.maxZ() + 12); - Map blocks = flatTerrain(area, 50); - Map originalBlocks = new HashMap<>(blocks); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, - List.of(surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - (x, z) -> 50); - - assertEquals(originalBlocks, blocks); - } - - @Test - public void vacuumBudgetExhaustionSkipsFittingWithoutFailing() throws Exception { - PoolElementStructurePiece piece = rigidTemplatePiece( - new InlineSinglePoolElement(template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState())))), - new BoundingBox(0, 66, 0, 0, 70, 0), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 54, 0, 15, 72, 15); - Map blocks = flatTerrain(area, 60); - Map originalBlocks = new HashMap<>(blocks); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, - List.of(surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - (x, z) -> 60, 1); - - assertEquals(originalBlocks, blocks); - } - - @Test - public void vacuumContinuouslySupportsProcessedChildBases() throws Exception { - PoolElementStructurePiece center = rigidTemplatePiece( - new InlineSinglePoolElement(template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState())))), - new BoundingBox(0, 60, 0, 0, 64, 0), 1, Rotation.NONE); - StructureTemplate childTemplate = template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); - PoolElementStructurePiece child = rigidTemplatePiece( - new InlineSinglePoolElement(childTemplate), - new BoundingBox(10, 66, 0, 10, 72, 0), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart( - List.of(center, child), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 54, 0, 15, 74, 3); - Map blocks = flatTerrain(area, 60); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(blocks), area, - List.of(surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - (x, z) -> 60); - - for (int y = 61; y <= 65; y++) { - assertFalse(state(blocks, 10, y, 0).isAir()); - } - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 10, 65, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 10, 66, 0)); - } - - @Test - public void vacuumSurfaceFittingIsStableAcrossSplitChunkAreas() throws Exception { - StructureTemplate template = template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()), - block(1, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); - PoolElementStructurePiece piece = rigidTemplatePiece( - new InlineSinglePoolElement(template), - new BoundingBox(15, 66, 0, 16, 72, 0), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(piece), TerrainAdjustment.NONE); - NativeStructureTerrainIntegrator.TerrainTarget target = - surfaceTarget(start, IrisStructureTerrainMode.VACUUM); - BoundingBox wideArea = new BoundingBox(0, 54, 0, 31, 74, 15); - BoundingBox westArea = new BoundingBox(0, 54, 0, 15, 74, 15); - BoundingBox eastArea = new BoundingBox(16, 54, 0, 31, 74, 15); - Map wideBlocks = flatTerrain(wideArea, 60); - Map splitBlocks = flatTerrain(wideArea, 60); - Map reverseSplitBlocks = flatTerrain(wideArea, 60); - - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(wideBlocks), wideArea, List.of(target), (x, z) -> 60); - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(splitBlocks), westArea, List.of(target), (x, z) -> 60); - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(splitBlocks), eastArea, List.of(target), (x, z) -> 60); - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(reverseSplitBlocks), eastArea, List.of(target), (x, z) -> 60); - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world(reverseSplitBlocks), westArea, List.of(target), (x, z) -> 60); - - assertEquals(wideBlocks, splitBlocks); - assertEquals(wideBlocks, reverseSplitBlocks); - } - - @Test - public void surfaceAnchorCapsInsideAndIsUnchangedAtRadius() { - NativeStructureSurfaceFitter.SurfaceAnchor anchor = anchor(72, 2); - - assertEquals(70, NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(anchor), 2, 2, 64)); - assertEquals(64, NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(anchor), 16, 2, 64)); - assertEquals(64, NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(anchor), 17, 2, 64)); - } - - @Test - public void surfaceAnchorRaisesAndLowersThroughTheTaper() { - NativeStructureSurfaceFitter.SurfaceAnchor raised = anchor(68, 2); - NativeStructureSurfaceFitter.SurfaceAnchor lowered = anchor(64, 2); - - assertEquals(65, NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(raised), 10, 2, 64)); - assertEquals(67, NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(lowered), 10, 2, 68)); - } - - @Test - public void containingRigidFloorsHaveDeterministicPriority() { - NativeStructureSurfaceFitter.SurfaceAnchor rigid = anchor(70, 2); - NativeStructureSurfaceFitter.SurfaceAnchor junction = anchor(74, 1); - - assertEquals(70, NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(rigid, junction), 2, 2, 64)); - assertEquals(70, NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(junction, rigid), 2, 2, 64)); - - NativeStructureSurfaceFitter.SurfaceAnchor weakTie = anchor(58, 1); - NativeStructureSurfaceFitter.SurfaceAnchor strongTie = anchor(70, 2); - assertEquals(70, NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(weakTie, strongTie), 2, 2, 64)); - assertEquals(70, NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(strongTie, weakTie), 2, 2, 64)); - } - - @Test - public void postClearSupportUsesUpperOccupancyOverLowerLegacyAir() throws Exception { - StructureTemplate lowerTemplate = template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState()), - block(1, 0, 0, Blocks.AIR.defaultBlockState()))); - StructureTemplate upperTemplate = template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()), - block(1, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); - PoolElementStructurePiece lower = rigidTemplatePiece( - new InlineLegacyPoolElement(lowerTemplate), - new BoundingBox(0, 62, 0, 1, 65, 0), 1, Rotation.NONE); - PoolElementStructurePiece upper = rigidTemplatePiece( - new InlineLegacyPoolElement(upperTemplate), - new BoundingBox(0, 64, 0, 1, 70, 0), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(lower, upper)); - BoundingBox area = new BoundingBox(0, 58, 0, 1, 72, 0); - Map blocks = new HashMap<>(); - for (int x = 0; x <= 1; x++) { - put(blocks, x, 61, 0, Blocks.DIRT.defaultBlockState()); - put(blocks, x, 62, 0, Blocks.GRASS_BLOCK.defaultBlockState()); - } - put(blocks, 1, 63, 0, Blocks.DIRT.defaultBlockState()); - - Set written = NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(blocks), area, List.of(surfaceTarget(start)), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - - assertEquals(Set.of(BlockPos.asLong(0, 63, 0)), written); - assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 63, 0)); - assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 1, 63, 0)); - } - - @Test - public void rotatedLowestAuthoredVoidFluidAirAndJigsawColumnsRemainOpen() throws Exception { - List upperBlocks = new ArrayList<>(); - upperBlocks.add(block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState())); - upperBlocks.add(block(1, 0, 0, Blocks.AIR.defaultBlockState())); - upperBlocks.add(block(2, 0, 0, Blocks.STRUCTURE_VOID.defaultBlockState())); - upperBlocks.add(block(3, 0, 0, Blocks.WATER.defaultBlockState())); - upperBlocks.add(block(4, 0, 0, Blocks.JIGSAW.defaultBlockState())); - for (int x = 1; x <= 4; x++) { - upperBlocks.add(block(x, 1, 0, Blocks.STONE.defaultBlockState())); - } - StructureTemplate upperTemplate = template(upperBlocks); - PoolElementStructurePiece lower = rigidTemplatePiece( - new InlineLegacyPoolElement(template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState())))), - new BoundingBox(10, 62, 10, 10, 65, 14), 1, Rotation.NONE); - PoolElementStructurePiece upper = rigidTemplatePiece( - new InlineSinglePoolElement(upperTemplate), - new BoundingBox(10, 64, 10, 10, 70, 14), 1, - Rotation.CLOCKWISE_90); - StructureStart start = rigidSurfaceStart(List.of(lower, upper)); - BoundingBox area = new BoundingBox(10, 58, 10, 10, 72, 14); - Map blocks = new HashMap<>(); - for (int z = 10; z <= 14; z++) { - put(blocks, 10, 61, z, Blocks.DIRT.defaultBlockState()); - put(blocks, 10, 62, z, Blocks.GRASS_BLOCK.defaultBlockState()); - } - - Set written = NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(blocks), area, List.of(surfaceTarget(start)), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - - StructurePlaceSettings settings = new StructurePlaceSettings() - .setRotation(Rotation.CLOCKWISE_90); - BlockPos origin = upper.getPosition(); - BlockPos supportedBase = origin.offset( - StructureTemplate.calculateRelativePosition(settings, BlockPos.ZERO)); - assertEquals(Set.of(supportedBase.below().asLong()), written); - assertEquals(Blocks.DIRT.defaultBlockState(), state( - blocks, supportedBase.getX(), supportedBase.getY() - 1, supportedBase.getZ())); - for (int localX = 1; localX <= 4; localX++) { - BlockPos vetoedBase = origin.offset(StructureTemplate.calculateRelativePosition( - settings, new BlockPos(localX, 0, 0))); - assertEquals(Blocks.AIR.defaultBlockState(), state( - blocks, vetoedBase.getX(), vetoedBase.getY() - 1, vetoedBase.getZ())); - } - } - - @Test - public void listElementsUseDeclaredOverlayOrderForLowestAuthoredCells() throws Exception { - InlineLegacyPoolElement legacy = new InlineLegacyPoolElement(template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()), - block(1, 0, 0, Blocks.COBBLESTONE.defaultBlockState())))); - InlineSinglePoolElement single = new InlineSinglePoolElement(template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState()), - block(1, 0, 0, Blocks.STONE.defaultBlockState())))); - ListPoolElement list = new ListPoolElement( - List.of(legacy, single), StructureTemplatePool.Projection.RIGID); - PoolElementStructurePiece lower = rigidTemplatePiece( - new InlineLegacyPoolElement(template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState())))), - new BoundingBox(0, 62, 0, 1, 65, 0), 1, Rotation.NONE); - PoolElementStructurePiece upper = rigidTemplatePiece( - list, new BoundingBox(0, 64, 0, 1, 70, 0), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(lower, upper)); - BoundingBox area = new BoundingBox(0, 58, 0, 1, 72, 0); - Map blocks = new HashMap<>(); - for (int x = 0; x <= 1; x++) { - put(blocks, x, 61, 0, Blocks.DIRT.defaultBlockState()); - put(blocks, x, 62, 0, Blocks.GRASS_BLOCK.defaultBlockState()); - } - - Set written = NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(blocks), area, List.of(surfaceTarget(start)), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - - assertEquals(Set.of(BlockPos.asLong(1, 63, 0)), written); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 63, 0)); - assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 1, 63, 0)); - } - - @Test - public void surfaceSupportIsChunkClippedAndStableAcrossSplitAreas() throws Exception { - StructureTemplate upperTemplate = template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()), - block(1, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); - PoolElementStructurePiece lower = rigidTemplatePiece( - new InlineLegacyPoolElement(template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState())))), - new BoundingBox(15, 62, 0, 16, 65, 0), 1, Rotation.NONE); - PoolElementStructurePiece upper = rigidTemplatePiece( - new InlineSinglePoolElement(upperTemplate), - new BoundingBox(15, 64, 0, 16, 70, 0), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(lower, upper)); - BoundingBox wideArea = new BoundingBox(0, 58, 0, 31, 72, 15); - BoundingBox westArea = new BoundingBox(0, 58, 0, 15, 72, 15); - BoundingBox eastArea = new BoundingBox(16, 58, 0, 31, 72, 15); - Map wideBlocks = supportTerrain(15, 16); - Map splitBlocks = supportTerrain(15, 16); - - Set wide = NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(wideBlocks), wideArea, List.of(surfaceTarget(start)), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - Set split = new HashSet<>( - NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(splitBlocks), westArea, List.of(surfaceTarget(start)), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager)); - assertEquals(Blocks.AIR.defaultBlockState(), state(splitBlocks, 16, 63, 0)); - split.addAll(NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(splitBlocks), eastArea, List.of(surfaceTarget(start)), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager)); - - assertEquals(Set.of( - BlockPos.asLong(15, 63, 0), BlockPos.asLong(16, 63, 0)), wide); - assertEquals(wide, split); - assertEquals(wideBlocks, splitBlocks); - } - - @Test - public void supportNeverPairsRigidAnchorsAcrossStarts() throws Exception { - PoolElementStructurePiece lower = rigidTemplatePiece( - new InlineLegacyPoolElement(template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState())))), - new BoundingBox(0, 62, 0, 0, 65, 0), 1, Rotation.NONE); - PoolElementStructurePiece upper = rigidTemplatePiece( - new InlineSinglePoolElement(template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState())))), - new BoundingBox(0, 64, 0, 0, 70, 0), 1, Rotation.NONE); - StructureStart lowerStart = rigidSurfaceStart(List.of(lower)); - StructureStart upperStart = rigidSurfaceStart(List.of(upper)); - BoundingBox area = new BoundingBox(0, 58, 0, 0, 72, 0); - Map blocks = supportTerrain(0, 0); - - assertTrue(NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(blocks), area, List.of(surfaceTarget(lowerStart)), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager).isEmpty()); - assertTrue(NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(blocks), area, List.of(surfaceTarget(upperStart)), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager).isEmpty()); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 63, 0)); - } - - @Test - public void vacuumSupportsUnauthoredTerrainModesButLongMeetGapsRemainOpen() throws Exception { - StructureTemplate upperTemplate = template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()))); - PoolElementStructurePiece lower = rigidTemplatePiece( - new InlineLegacyPoolElement(template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState())))), - new BoundingBox(0, 62, 0, 0, 65, 0), 1, Rotation.NONE); - PoolElementStructurePiece upper = rigidTemplatePiece( - new InlineSinglePoolElement(upperTemplate), - new BoundingBox(0, 64, 0, 0, 70, 0), 1, Rotation.NONE); - StructureStart vacuumStart = rigidSurfaceStart( - List.of(lower, upper), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 58, 0, 0, 72, 0); - Map vacuumBlocks = supportTerrain(0, 0); - - Set vacuumWritten = NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(vacuumBlocks), area, - List.of(surfaceTarget(vacuumStart, IrisStructureTerrainMode.VACUUM)), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - - assertEquals(Set.of(BlockPos.asLong(0, 63, 0)), vacuumWritten); - assertTrue(NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(supportTerrain(0, 0)), area, - List.of(surfaceTarget(vacuumStart, IrisStructureTerrainMode.SOURCE)), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager).isEmpty()); - - PoolElementStructurePiece distantUpper = rigidTemplatePiece( - new InlineSinglePoolElement(upperTemplate), - new BoundingBox(0, 65, 0, 0, 71, 0), 1, Rotation.NONE); - StructureStart distantStart = rigidSurfaceStart( - List.of(lower, distantUpper), TerrainAdjustment.NONE); - assertTrue(NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(supportTerrain(0, 0)), area, - List.of(surfaceTarget(distantStart, IrisStructureTerrainMode.VACUUM)), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager).isEmpty()); - } - - @Test - public void threeRigidPlanesCannotBuildAnUpwardSupportChain() throws Exception { - PoolElementStructurePiece lower = rigidTemplatePiece( - new InlineLegacyPoolElement(template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState())))), - new BoundingBox(0, 62, 0, 0, 65, 0), 1, Rotation.NONE); - PoolElementStructurePiece middle = rigidTemplatePiece( - new InlineSinglePoolElement(template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState())))), - new BoundingBox(0, 64, 0, 0, 69, 0), 0, Rotation.NONE); - PoolElementStructurePiece upper = rigidTemplatePiece( - new InlineSinglePoolElement(template(List.of( - block(0, 0, 0, Blocks.STONE.defaultBlockState())))), - new BoundingBox(0, 65, 0, 0, 70, 0), 0, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(lower, middle, upper)); - BoundingBox area = new BoundingBox(0, 58, 0, 0, 72, 0); - Map blocks = supportTerrain(0, 0); - - Set written = NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(blocks), area, List.of(surfaceTarget(start)), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - - assertEquals(Set.of(BlockPos.asLong(0, 63, 0)), written); - assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 63, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 64, 0)); - } - - @Test - public void reversingTargetsCannotCreateCrossStartSupportChains() throws Exception { - PoolElementStructurePiece ground = rigidTemplatePiece( - new InlineLegacyPoolElement(template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState())))), - new BoundingBox(0, 62, 0, 0, 65, 0), 1, Rotation.NONE); - PoolElementStructurePiece middle = rigidTemplatePiece( - new InlineSinglePoolElement(template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState())))), - new BoundingBox(0, 64, 0, 0, 69, 0), 0, Rotation.NONE); - PoolElementStructurePiece raisedGround = rigidTemplatePiece( - new InlineLegacyPoolElement(template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState())))), - new BoundingBox(0, 64, 0, 0, 69, 0), 0, Rotation.NONE); - PoolElementStructurePiece upper = rigidTemplatePiece( - new InlineSinglePoolElement(template(List.of( - block(0, 0, 0, Blocks.STONE.defaultBlockState())))), - new BoundingBox(0, 65, 0, 0, 70, 0), 0, Rotation.NONE); - StructureStart lowerStart = rigidSurfaceStart(List.of(ground, middle)); - StructureStart upperStart = rigidSurfaceStart(List.of(raisedGround, upper)); - BoundingBox area = new BoundingBox(0, 58, 0, 0, 72, 0); - Map forwardBlocks = supportTerrain(0, 0); - Map reverseBlocks = supportTerrain(0, 0); - NativeStructureTerrainIntegrator.TerrainTarget lowerTarget = surfaceTarget(lowerStart); - NativeStructureTerrainIntegrator.TerrainTarget upperTarget = surfaceTarget(upperStart); - - Set forward = NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(forwardBlocks), area, List.of(lowerTarget, upperTarget), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - Set reverse = NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(reverseBlocks), area, List.of(upperTarget, lowerTarget), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - - assertEquals(Set.of(BlockPos.asLong(0, 63, 0)), forward); - assertEquals(forward, reverse); - assertEquals(forwardBlocks, reverseBlocks); - assertEquals(Blocks.AIR.defaultBlockState(), state(forwardBlocks, 0, 64, 0)); - } - - @Test - public void preserveDuplicateCannotSuppressVacuumSupport() throws Exception { - PoolElementStructurePiece lower = rigidTemplatePiece( - new InlineLegacyPoolElement(template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState())))), - new BoundingBox(0, 62, 0, 0, 65, 0), 1, Rotation.NONE); - PoolElementStructurePiece upper = rigidTemplatePiece( - new InlineSinglePoolElement(template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState())))), - new BoundingBox(0, 64, 0, 0, 70, 0), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart( - List.of(lower, upper), TerrainAdjustment.NONE); - BoundingBox area = new BoundingBox(0, 58, 0, 0, 72, 0); - Map blocks = supportTerrain(0, 0); - - Set written = NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(blocks), area, List.of( - surfaceTarget(start, IrisStructureTerrainMode.PRESERVE), - surfaceTarget(start, IrisStructureTerrainMode.VACUUM)), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - - assertEquals(Set.of(BlockPos.asLong(0, 63, 0)), written); - } - - @Test - public void processorCreatedAirAndFluidVetoSurfaceSupport() throws Exception { - StructureTemplate upperTemplate = template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState()), - block(1, 0, 0, Blocks.STONE.defaultBlockState()))); - InlineSinglePoolElement upperElement = new InlineSinglePoolElement( - upperTemplate, List.of( - replaceBlockProcessor( - Blocks.COBBLESTONE.defaultBlockState(), - Blocks.AIR.defaultBlockState()), - replaceBlockProcessor( - Blocks.STONE.defaultBlockState(), - Blocks.WATER.defaultBlockState()))); - PoolElementStructurePiece lower = rigidTemplatePiece( - new InlineLegacyPoolElement(template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState())))), - new BoundingBox(0, 62, 0, 1, 65, 0), 1, Rotation.NONE); - PoolElementStructurePiece upper = rigidTemplatePiece( - upperElement, new BoundingBox(0, 64, 0, 1, 70, 0), - 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(lower, upper)); - BoundingBox area = new BoundingBox(0, 58, 0, 1, 72, 0); - Map blocks = supportTerrain(0, 1); - - Set written = NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(blocks), area, List.of(surfaceTarget(start)), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - - assertTrue(written.isEmpty()); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 0, 63, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 1, 63, 0)); - } - - @Test - public void solidJigsawFinalStateCreatesSurfaceSupport() throws Exception { - CompoundTag jigsawData = new CompoundTag(); - jigsawData.putString("final_state", "minecraft:cobblestone"); - StructureTemplate upperTemplate = template(List.of( - new StructureTemplate.StructureBlockInfo( - BlockPos.ZERO, Blocks.JIGSAW.defaultBlockState(), jigsawData))); - PoolElementStructurePiece lower = rigidTemplatePiece( - new InlineLegacyPoolElement(template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState())))), - new BoundingBox(0, 62, 0, 0, 65, 0), 1, Rotation.NONE); - PoolElementStructurePiece upper = rigidTemplatePiece( - new InlineSinglePoolElement(upperTemplate), - new BoundingBox(0, 64, 0, 0, 70, 0), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(lower, upper)); - BoundingBox area = new BoundingBox(0, 58, 0, 0, 72, 0); - Map blocks = supportTerrain(0, 0); - - Set written = NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(blocks), area, List.of(surfaceTarget(start)), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - - assertEquals(Set.of(BlockPos.asLong(0, 63, 0)), written); - assertEquals(Blocks.DIRT.defaultBlockState(), state(blocks, 0, 63, 0)); - } - - @Test - public void laterLegacyAirDoesNotOverlayEarlierListSolid() throws Exception { - InlineSinglePoolElement solid = new InlineSinglePoolElement(template(List.of( - block(0, 0, 0, Blocks.COBBLESTONE.defaultBlockState())))); - InlineLegacyPoolElement legacyAir = new InlineLegacyPoolElement(template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState())))); - ListPoolElement list = new ListPoolElement( - List.of(solid, legacyAir), StructureTemplatePool.Projection.RIGID); - PoolElementStructurePiece lower = rigidTemplatePiece( - new InlineLegacyPoolElement(template(List.of( - block(0, 0, 0, Blocks.AIR.defaultBlockState())))), - new BoundingBox(0, 62, 0, 0, 65, 0), 1, Rotation.NONE); - PoolElementStructurePiece upper = rigidTemplatePiece( - list, new BoundingBox(0, 64, 0, 0, 70, 0), 1, Rotation.NONE); - StructureStart start = rigidSurfaceStart(List.of(lower, upper)); - BoundingBox area = new BoundingBox(0, 58, 0, 0, 72, 0); - Map blocks = supportTerrain(0, 0); - - Set written = NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world(blocks), area, List.of(surfaceTarget(start)), - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - - assertEquals(Set.of(BlockPos.asLong(0, 63, 0)), written); - } - - @Test - public void stackedRigidPiecesPreserveTheLowerProcessedFoundation() throws Exception { - Structure structure = new DesertPyramidStructure( - new Structure.StructureSettings( - HolderSet.empty(), Map.of(), - GenerationStep.Decoration.SURFACE_STRUCTURES, - TerrainAdjustment.BEARD_BOX)); - PoolElementStructurePiece lower = rigidTemplatePiece( - new InlineSinglePoolElement(template(List.of( - block(2, 1, 2, Blocks.COBBLESTONE.defaultBlockState())))), - new BoundingBox(0, 62, 0, 4, 65, 4), 1, Rotation.NONE); - PoolElementStructurePiece upper = rigidTemplatePiece( - new InlineSinglePoolElement(template(List.of( - block(2, 1, 2, Blocks.COBBLESTONE.defaultBlockState())))), - new BoundingBox(0, 66, 0, 4, 78, 4), 1, Rotation.NONE); - StructureStart start = new StructureStart( - structure, new ChunkPos(0, 0), 0, - new PiecesContainer(List.of(upper, lower))); - BoundingBox area = new BoundingBox(0, 58, 0, 4, 78, 4); - Map blocks = new HashMap<>(); - for (int x = area.minX(); x <= area.maxX(); x++) { - for (int z = area.minZ(); z <= area.maxZ(); z++) { - put(blocks, x, 59, z, Blocks.DIRT.defaultBlockState()); - put(blocks, x, 60, z, Blocks.GRASS_BLOCK.defaultBlockState()); - } - } - - WorldGenLevel world = world(blocks); - List targets = - List.of(surfaceTarget(start)); - NativeStructureSurfaceFitter.prepareSurfaceStructures( - world, area, targets, (x, z) -> 60); - - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 2, 62, 2)); - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, 2, 65, 2)); - } - - @Test - public void containingFootprintOverridesAnAdjacentPiecesFalloff() { - NativeStructureSurfaceFitter.SurfaceAnchor local = - new NativeStructureSurfaceFitter.SurfaceAnchor(0, 4, 0, 4, 66, 2); - NativeStructureSurfaceFitter.SurfaceAnchor adjacent = - new NativeStructureSurfaceFitter.SurfaceAnchor(5, 9, 0, 4, 70, 2); - - assertEquals(69, NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(adjacent), 4, 2, 64)); - assertEquals(66, NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(local, adjacent), 4, 2, 64)); - assertEquals(66, NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(adjacent, local), 4, 2, 64)); - } - - @Test - public void opposingFalloffsBlendWithoutAnAbruptMidpointSeam() { - NativeStructureSurfaceFitter.SurfaceAnchor high = - new NativeStructureSurfaceFitter.SurfaceAnchor(0, 0, 0, 0, 70, 2); - NativeStructureSurfaceFitter.SurfaceAnchor low = - new NativeStructureSurfaceFitter.SurfaceAnchor(12, 12, 0, 0, 58, 2); - int previous = NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(high, low), 0, 0, 64); - - for (int x = 1; x <= 12; x++) { - int forward = NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(high, low), x, 0, 64); - int reversed = NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(low, high), x, 0, 64); - assertEquals(forward, reversed); - assertTrue(Math.abs(forward - previous) <= 6); - previous = forward; - } - assertEquals(64, NativeStructureSurfaceFitter.resolveSurfaceTarget( - List.of(high, low), 6, 0, 64)); - } - - @Test - public void surfaceColumnsMutateTerrainAndRemoveUnsupportedDecoration() { - Map lowered = new HashMap<>(); - put(lowered, 0, 61, 0, Blocks.STONE.defaultBlockState()); - put(lowered, 0, 62, 0, Blocks.DIRT.defaultBlockState()); - put(lowered, 0, 63, 0, Blocks.DIRT.defaultBlockState()); - put(lowered, 0, 64, 0, Blocks.GRASS_BLOCK.defaultBlockState()); - put(lowered, 0, 65, 0, Blocks.DANDELION.defaultBlockState()); - - NativeStructureSurfaceFitter.applySurfaceColumn( - world(lowered), new BlockPos.MutableBlockPos(), - 0, 0, 64, 62, -64, 319); - - assertEquals(Blocks.STONE.defaultBlockState(), state(lowered, 0, 61, 0)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(lowered, 0, 62, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(lowered, 0, 63, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(lowered, 0, 64, 0)); - assertEquals(Blocks.AIR.defaultBlockState(), state(lowered, 0, 65, 0)); - - Map raised = new HashMap<>(); - put(raised, 0, 63, 0, Blocks.DIRT.defaultBlockState()); - put(raised, 0, 64, 0, Blocks.GRASS_BLOCK.defaultBlockState()); - put(raised, 0, 65, 0, Blocks.DANDELION.defaultBlockState()); - - NativeStructureSurfaceFitter.applySurfaceColumn( - world(raised), new BlockPos.MutableBlockPos(), - 0, 0, 64, 68, -64, 319); - - assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 65, 0)); - assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 66, 0)); - assertEquals(Blocks.DIRT.defaultBlockState(), state(raised, 0, 67, 0)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(raised, 0, 68, 0)); - } - - @Test - public void rigidSurfaceBaseClosesAOneBlockSubsurfaceGap() { - Map blocks = new HashMap<>(); - put(blocks, 0, 62, 0, Blocks.STONE.defaultBlockState()); - put(blocks, 0, 64, 0, Blocks.GRASS_BLOCK.defaultBlockState()); - - NativeStructureSurfaceFitter.applySurfaceColumn( - world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 64, 64, -64, 319, true); - - assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 63, 0)); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), state(blocks, 0, 64, 0)); - } - - @Test - public void rigidSurfaceBaseReconstructsAMissingMeetLayer() { - Map blocks = new HashMap<>(); - put(blocks, 0, 62, 0, Blocks.STONE.defaultBlockState()); - - NativeStructureSurfaceFitter.applySurfaceColumn( - world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 64, 64, -64, 319, true); - - assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 63, 0)); - assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, 64, 0)); - } - - @Test - public void rigidSurfaceBaseReconstructsAMissingMeetLayerAtTheWorldFloor() { - Map blocks = new HashMap<>(); - - NativeStructureSurfaceFitter.applySurfaceColumn( - world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, -64, -64, -64, 319, true); - - assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, 0, -64, 0)); - } - - @Test - public void raisedSurfaceTerrainDoesNotSliceTreeBlocks() { - Map blocks = new HashMap<>(); - BlockState log = Blocks.OAK_LOG.defaultBlockState(); - BlockState leaves = Blocks.OAK_LEAVES.defaultBlockState(); - put(blocks, 0, 63, 0, Blocks.DIRT.defaultBlockState()); - put(blocks, 0, 64, 0, Blocks.GRASS_BLOCK.defaultBlockState()); - put(blocks, 0, 66, 0, log); - put(blocks, 0, 68, 0, leaves); - - NativeStructureSurfaceFitter.applySurfaceColumn( - world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 64, 68, -64, 319); - - assertEquals(log, state(blocks, 0, 66, 0)); - assertEquals(leaves, state(blocks, 0, 68, 0)); - } - - @Test - public void clearedIntersectingTreeCellsBecomeRaisedTerrainSupport() { - ProtoChunk chunk = new ProtoChunk( - new ChunkPos(0, 0), UpgradeData.EMPTY, - LevelHeightAccessor.create(-64, 384), containerFactory(), null); - write(chunk, 0, 63, 0, Blocks.DIRT.defaultBlockState()); - write(chunk, 0, 64, 0, Blocks.GRASS_BLOCK.defaultBlockState()); - write(chunk, 0, 66, 0, Blocks.OAK_LOG.defaultBlockState()); - write(chunk, 0, 68, 0, Blocks.OAK_LEAVES.defaultBlockState()); - WorldGenLevel world = world(chunk); - BoundingBox area = new BoundingBox(0, 63, 0, 0, 68, 0); - - NativeStructureVegetationClearer.clearIntersectingVegetation( - world, chunk, area, List.of(desertStart())); - NativeStructureSurfaceFitter.applySurfaceColumn( - world, new BlockPos.MutableBlockPos(), - 0, 0, 64, 68, -64, 319); - - assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 65, 0))); - assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 66, 0))); - assertEquals(Blocks.DIRT.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 67, 0))); - assertEquals(Blocks.GRASS_BLOCK.defaultBlockState(), chunk.getBlockState(new BlockPos(0, 68, 0))); - } - - @Test - public void loweredFluidColumnsRemainFluidFilled() { - Map blocks = new HashMap<>(); - put(blocks, 0, 62, 0, Blocks.DIRT.defaultBlockState()); - put(blocks, 0, 63, 0, Blocks.DIRT.defaultBlockState()); - put(blocks, 0, 64, 0, Blocks.GRAVEL.defaultBlockState()); - put(blocks, 0, 65, 0, Blocks.WATER.defaultBlockState()); - - NativeStructureSurfaceFitter.applySurfaceColumn( - world(blocks), new BlockPos.MutableBlockPos(), - 0, 0, 64, 62, -64, 319); - - assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 63, 0)); - assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 64, 0)); - assertEquals(Blocks.WATER.defaultBlockState(), state(blocks, 0, 65, 0)); - assertEquals(Blocks.GRAVEL.defaultBlockState(), state(blocks, 0, 62, 0)); - } - - @Test - public void preserveSourceYSkipsBurialAndKeepsTheVanillaStartY() { - StructureStart start = desertStart(); - int minY = start.getBoundingBox().minY(); - - int offset = NativeStructureVerticalPlacer.applyVerticalShift( - start, 0, -64, 320, true, true, null, (x, z) -> 40); - - assertEquals(0, offset); - assertEquals(minY, start.getBoundingBox().minY()); - } - - @Test - public void preserveSourceYStillAppliesAnExplicitShift() { - StructureStart start = desertStart(); - int minY = start.getBoundingBox().minY(); - - int offset = NativeStructureVerticalPlacer.applyVerticalShift( - start, -8, -64, 320, true, true, null, (x, z) -> 40); - - assertEquals(-8, offset); - assertEquals(minY - 8, start.getBoundingBox().minY()); - } - - @Test - public void burialStillSinksTheStructureBelowTheLowestTerrainColumn() { - StructureStart start = desertStart(); - int minY = start.getBoundingBox().minY(); - int maxY = start.getBoundingBox().maxY(); - int expected = 40 - 1 - maxY; - - int offset = NativeStructureVerticalPlacer.applyVerticalShift( - start, 0, -64, 320, true, false, null, (x, z) -> 40); - - assertEquals(expected, offset); - assertEquals(minY + expected, start.getBoundingBox().minY()); - } - - @Test - public void unfittableBurialClampsToTheWorldFloorInsteadOfAborting() { - StructureStart start = desertStart(); - int minY = start.getBoundingBox().minY(); - int worldMinY = minY - 4; - - int offset = NativeStructureVerticalPlacer.applyVerticalShift( - start, 0, worldMinY, 320, true, false, null, (x, z) -> worldMinY); - - assertEquals(-4, offset); - assertEquals(worldMinY, start.getBoundingBox().minY()); - } - - @Test - public void nativeVacuumLeavesPieceBlocksForSurfaceFitting() { - StructureStart start = desertStart(); - BoundingBox bounds = start.getPieces().getFirst().getBoundingBox(); - Map blocks = new HashMap<>(); - put(blocks, bounds.minX(), bounds.minY(), bounds.minZ(), Blocks.STONE.defaultBlockState()); - - NativeStructureTerrainIntegrator.integrateTerrain( - world(blocks), bounds, "minecraft:desert_pyramid", start, - new IrisStructureTerrain().setMode(IrisStructureTerrainMode.VACUUM), null); - - assertEquals(Blocks.STONE.defaultBlockState(), - state(blocks, bounds.minX(), bounds.minY(), bounds.minZ())); - } - - @Test - public void nativeForceCarveHonorsConfiguredPadding() { - StructureStart start = desertStart(); - BoundingBox bounds = start.getPieces().getFirst().getBoundingBox(); - BoundingBox area = new BoundingBox( - bounds.minX() - 1, bounds.minY(), bounds.minZ() - 1, - bounds.maxX() + 1, bounds.maxY() + 1, bounds.maxZ() + 1); - Map blocks = new HashMap<>(); - put(blocks, bounds.maxX() + 1, bounds.minY(), bounds.maxZ(), - Blocks.STONE.defaultBlockState()); - put(blocks, bounds.maxX(), bounds.maxY() + 1, bounds.maxZ(), - Blocks.STONE.defaultBlockState()); - - NativeStructureTerrainIntegrator.integrateTerrain( - world(blocks), area, "minecraft:desert_pyramid", start, - new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.FORCE_CARVE) - .setHorizontalPadding(1) - .setCeilingPadding(1), null); - - assertEquals(Blocks.AIR.defaultBlockState(), - state(blocks, bounds.maxX() + 1, bounds.minY(), bounds.maxZ())); - assertEquals(Blocks.AIR.defaultBlockState(), - state(blocks, bounds.maxX(), bounds.maxY() + 1, bounds.maxZ())); - } - - @Test - public void nativeForceCarveUsesPieceUnionInsteadOfCombinedBounds() { - Structure structure = new DesertPyramidStructure( - new Structure.StructureSettings(HolderSet.empty())); - DesertPyramidPiece first = new DesertPyramidPiece(RandomSource.create(7L), 0, 0); - DesertPyramidPiece second = new DesertPyramidPiece(RandomSource.create(8L), 0, 0); - second.move(64, 0, 0); - StructureStart start = new StructureStart( - structure, new ChunkPos(0, 0), 0, - new PiecesContainer(List.of(first, second))); - BoundingBox firstBounds = first.getBoundingBox(); - BoundingBox secondBounds = second.getBoundingBox(); - int gapX = (firstBounds.maxX() + secondBounds.minX()) / 2; - int y = firstBounds.minY(); - int z = firstBounds.minZ(); - BoundingBox area = new BoundingBox( - firstBounds.minX(), y, z, - secondBounds.maxX(), y, z); - Map blocks = new HashMap<>(); - put(blocks, firstBounds.minX(), y, z, Blocks.STONE.defaultBlockState()); - put(blocks, gapX, y, z, Blocks.STONE.defaultBlockState()); - - NativeStructureTerrainIntegrator.integrateTerrain( - world(blocks), area, "minecraft:ancient_city", start, - new IrisStructureTerrain().setMode(IrisStructureTerrainMode.FORCE_CARVE), null); - - assertEquals(Blocks.AIR.defaultBlockState(), - state(blocks, firstBounds.minX(), y, z)); - assertEquals(Blocks.STONE.defaultBlockState(), - state(blocks, gapX, y, z)); - } - - @Test - public void templateBackedColumnsUseTheTemplateAirComplement() throws Exception { - StructureTemplate template = template(List.of( - new StructureTemplate.StructureBlockInfo( - new BlockPos(0, 0, 0), Blocks.AIR.defaultBlockState(), null), - new StructureTemplate.StructureBlockInfo( - new BlockPos(0, 1, 0), Blocks.AIR.defaultBlockState(), null), - new StructureTemplate.StructureBlockInfo( - new BlockPos(0, 2, 0), Blocks.DEEPSLATE_BRICKS.defaultBlockState(), null), - new StructureTemplate.StructureBlockInfo( - new BlockPos(1, 0, 0), Blocks.STRUCTURE_VOID.defaultBlockState(), null), - new StructureTemplate.StructureBlockInfo( - new BlockPos(1, 1, 0), Blocks.DEEPSLATE.defaultBlockState(), null), - new StructureTemplate.StructureBlockInfo( - new BlockPos(1, 2, 0), Blocks.DEEPSLATE.defaultBlockState(), null))); - Map columns = new HashMap<>(); - - assertTrue(NativeStructureTerrainIntegrator.emitTemplateColumns( - List.of(template), new BlockPos(0, 0, 0), Rotation.NONE, - new BoundingBox(0, 0, 0, 1, 2, 0), - (x, z, minY, maxY) -> columns.put((long) x << 32 | z & 0xffffffffL, - new int[]{minY, maxY}))); - - assertEquals(2, columns.size()); - assertArrayEquals(new int[]{2, 2}, columns.get(0L)); - assertArrayEquals(new int[]{1, 2}, columns.get(1L << 32)); - } - - @Test - public void fullyVoidTemplateColumnsAreNotCarveSources() throws Exception { - StructureTemplate template = template(List.of( - new StructureTemplate.StructureBlockInfo( - new BlockPos(0, 0, 0), Blocks.AIR.defaultBlockState(), null), - new StructureTemplate.StructureBlockInfo( - new BlockPos(0, 1, 0), Blocks.STRUCTURE_VOID.defaultBlockState(), null))); - Map columns = new HashMap<>(); - - assertTrue(NativeStructureTerrainIntegrator.emitTemplateColumns( - List.of(template), new BlockPos(0, 0, 0), Rotation.NONE, - new BoundingBox(0, 0, 0, 0, 1, 0), - (x, z, minY, maxY) -> columns.put((long) x << 32 | z & 0xffffffffL, - new int[]{minY, maxY}))); - - assertTrue(columns.isEmpty()); - } - - @Test - public void nonTemplatePiecesFallBackToTheirBoundingBoxColumns() { - StructureStart start = desertStart(); - BoundingBox bounds = start.getPieces().getFirst().getBoundingBox(); - - StructureCarvingFootprint footprint = NativeStructureTerrainIntegrator.carveFootprint( - start, 4, NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - - assertEquals(bounds.minX() - 4, footprint.minX()); - assertEquals(bounds.maxX() + 4, footprint.maxX()); - assertEquals(bounds.minZ() - 4, footprint.minZ()); - assertEquals(bounds.maxZ() + 4, footprint.maxZ()); - assertEquals(0L, footprint.distanceSquaredAt(bounds.minX(), bounds.minZ())); - assertEquals(32L, footprint.distanceSquaredAt(bounds.minX() - 4, bounds.minZ() - 4)); - assertEquals(bounds.minY(), footprint.sourceMinYAt(bounds.minX(), bounds.minZ())); - assertEquals(bounds.maxY(), footprint.sourceMaxYAt(bounds.minX(), bounds.minZ())); - } - - @Test - public void carveFootprintIsComputedOncePerStartAndPadding() { - StructureStart start = desertStart(); - - StructureCarvingFootprint first = NativeStructureTerrainIntegrator.carveFootprint( - start, 6, NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - StructureCarvingFootprint repeated = NativeStructureTerrainIntegrator.carveFootprint( - start, 6, NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - StructureCarvingFootprint widened = NativeStructureTerrainIntegrator.carveFootprint( - start, 7, NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - StructureCarvingFootprint other = NativeStructureTerrainIntegrator.carveFootprint( - desertStart(), 6, NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - - assertSame(first, repeated); - assertNotSame(first, widened); - assertNotSame(first, other); - } - - @Test - public void concurrentCarveRequestsShareOneFootprintBuild() throws Exception { - StructureStart start = desertStart(); - int requestCount = 16; - ExecutorService executor = Executors.newFixedThreadPool(requestCount); - CountDownLatch ready = new CountDownLatch(requestCount); - CountDownLatch release = new CountDownLatch(1); - List> futures = new ArrayList<>(); - try { - for (int request = 0; request < requestCount; request++) { - futures.add(executor.submit(() -> { - ready.countDown(); - release.await(); - return NativeStructureTerrainIntegrator.carveFootprint( - start, 11, - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - })); - } - assertTrue(ready.await(5, TimeUnit.SECONDS)); - release.countDown(); - StructureCarvingFootprint expected = futures.getFirst().get(); - for (Future future : futures) { - assertSame(expected, future.get()); - } - } finally { - executor.shutdownNow(); - } - } - - @Test - public void carveFootprintCacheStaysInsideItsCellBudget() { - for (int index = 0; index < 40; index++) { - NativeStructureTerrainIntegrator.carveFootprint( - desertStart(), 128, - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager); - } - - assertTrue(NativeStructureTerrainIntegrator.cachedCarveFootprintCells() - <= NativeStructureTerrainIntegrator.maximumCachedCarveFootprintCells()); - } - - @Test - public void organicCarveNeverCutsBelowTheColumnSupportingFloor() { - StructureStart start = desertStart(); - BoundingBox bounds = start.getPieces().getFirst().getBoundingBox(); - NativeStructureTerrainIntegrator.OrganicCarve carve = organicCarve(start, 6); - BoundingBox area = new BoundingBox( - bounds.minX() - 6, bounds.minY() - 4, bounds.minZ() - 6, - bounds.maxX() + 6, bounds.maxY() + 12, bounds.maxZ() + 6); - Map blocks = fill(area); - - NativeStructureTerrainIntegrator.carveOrganicColumns(world(blocks), area, carve); - - int centerX = bounds.minX() + bounds.getXSpan() / 2; - int centerZ = bounds.minZ() + bounds.getZSpan() / 2; - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, centerX, bounds.minY(), centerZ)); - for (int x = area.minX(); x <= area.maxX(); x++) { - for (int z = area.minZ(); z <= area.maxZ(); z++) { - for (int y = area.minY(); y < bounds.minY(); y++) { - assertEquals(Blocks.STONE.defaultBlockState(), state(blocks, x, y, z)); - } - } - } - } - - @Test - public void lobedCarveStaysInsideTheUniformCarveAndRemovesLess() { - StructureStart start = desertStart(); - BoundingBox bounds = start.getPieces().getFirst().getBoundingBox(); - BoundingBox area = new BoundingBox( - bounds.minX() - 10, bounds.minY(), bounds.minZ() - 10, - bounds.maxX() + 10, bounds.maxY() + 12, bounds.maxZ() + 10); - Map uniformBlocks = fill(area); - Map lobedBlocks = fill(area); - - NativeStructureTerrainIntegrator.carveOrganicColumns( - world(uniformBlocks), area, organicCarve(start, 10, 0D)); - NativeStructureTerrainIntegrator.carveOrganicColumns( - world(lobedBlocks), area, organicCarve(start, 10, 0.85D)); - - int uniform = 0; - int lobed = 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++) { - boolean uniformAir = state(uniformBlocks, x, y, z).isAir(); - boolean lobedAir = state(lobedBlocks, x, y, z).isAir(); - assertTrue("lobe carved outside the uniform padding at " - + x + "," + y + "," + z, uniformAir || !lobedAir); - uniform += uniformAir ? 1 : 0; - lobed += lobedAir ? 1 : 0; - } - } - } - - assertTrue(lobed > 0); - assertTrue("uniform " + uniform + " lobed " + lobed, lobed < uniform); - } - - @Test - public void lobedCarveDepthWandersAlongAStraightFootprintEdge() { - int[] uniform = slabEdgeCarveDepths(0D); - int[] lobed = slabEdgeCarveDepths(0.85D); - - assertTrue("uniform depths wander " + span(uniform), span(uniform) <= 2); - assertTrue("lobed depths wander " + span(lobed), span(lobed) >= 6); - for (int depth : lobed) { - assertTrue(depth >= 0 && depth <= SLAB_PADDING); - } - } - - @Test - public void organicCarveIsIdenticalAcrossNeighboringChunkContexts() { - StructureStart start = desertStart(); - BoundingBox bounds = start.getPieces().getFirst().getBoundingBox(); - BoundingBox wide = new BoundingBox( - bounds.minX() - 6, bounds.minY(), bounds.minZ() - 6, - bounds.maxX() + 6, bounds.maxY() + 12, bounds.maxZ() + 6); - BoundingBox narrow = new BoundingBox( - bounds.maxX() - 3, bounds.minY(), bounds.maxZ() - 3, - bounds.maxX() + 6, bounds.maxY() + 12, bounds.maxZ() + 6); - Map wideBlocks = fill(wide); - Map narrowBlocks = fill(narrow); - - // Each chunk context rebuilds its own noise channels from the shared start identity. - NativeStructureTerrainIntegrator.carveOrganicColumns( - world(wideBlocks), wide, organicCarve(start, 6)); - NativeStructureTerrainIntegrator.carveOrganicColumns( - world(narrowBlocks), narrow, organicCarve(start, 6)); - - int carved = 0; - for (int x = narrow.minX(); x <= narrow.maxX(); x++) { - for (int z = narrow.minZ(); z <= narrow.maxZ(); z++) { - for (int y = narrow.minY(); y <= narrow.maxY(); y++) { - BlockState expected = state(wideBlocks, x, y, z); - assertEquals(expected, state(narrowBlocks, x, y, z)); - if (expected.isAir()) { - carved++; - } - } - } - } - assertTrue(carved > 0); - } - - @Test - public void erodedForceCarveShrinkwrapsWithoutUnderminingTheFloor() { - StructureStart start = desertStart(); - BoundingBox bounds = start.getPieces().getFirst().getBoundingBox(); - BoundingBox area = new BoundingBox( - bounds.minX() - 6, bounds.minY() - 2, bounds.minZ() - 6, - bounds.maxX() + 6, bounds.maxY() + 12, bounds.maxZ() + 6); - Map blocks = fill(area); - int centerX = bounds.minX() + bounds.getXSpan() / 2; - int centerZ = bounds.minZ() + bounds.getZSpan() / 2; - - NativeStructureTerrainIntegrator.integrateTerrain( - world(blocks), area, "minecraft:ancient_city", start, - new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.FORCE_CARVE) - .setShape(IrisStructureCarveShape.ERODED) - .setHorizontalPadding(6) - .setCeilingPadding(8) - .setFloorPadding(0) - .setErosionStrength(1D) - .setErosionFrequency(0.05D), null); - - assertEquals(Blocks.AIR.defaultBlockState(), state(blocks, centerX, bounds.minY(), centerZ)); - assertEquals(Blocks.STONE.defaultBlockState(), - state(blocks, centerX, bounds.minY() - 1, centerZ)); - assertEquals(Blocks.STONE.defaultBlockState(), - state(blocks, area.minX(), area.maxY(), area.minZ())); - } - - @Test - public void sparseStiltGridIsDeterministicAndPreflightsGround() { - assertTrue(NativeStructureFoundationBuilder.isStiltColumn(0, 0, 4)); - assertTrue(NativeStructureFoundationBuilder.isStiltColumn(-4, 8, 4)); - assertFalse(NativeStructureFoundationBuilder.isStiltColumn(1, 0, 4)); - assertTrue(NativeStructureFoundationBuilder.isStiltColumn(1, 1, 1)); - - Map blocks = new HashMap<>(); - put(blocks, 0, 7, 0, Blocks.DEEPSLATE.defaultBlockState()); - put(blocks, 0, 8, 0, Blocks.SCULK_VEIN.defaultBlockState()); - BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); - - assertEquals(7, NativeStructureFoundationBuilder.findStiltAnchorY( - world(blocks), 0, 0, 10, 2, -64, -64, position)); - assertEquals(Integer.MIN_VALUE, NativeStructureFoundationBuilder.findStiltAnchorY( - world(blocks), 0, 0, 10, 1, -64, -64, position)); - assertEquals(Integer.MIN_VALUE, NativeStructureFoundationBuilder.findStiltAnchorY( - world(new HashMap<>()), 0, 0, 10, 64, -64, -64, position)); - } - - @Test - public void nativeTerrainEnvelopePersistsHorizontalReferenceCoverage() { - StructureStart generated = desertStart(); - BoundingBox content = generated.getBoundingBox(); - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.FORCE_CARVE) - .setHorizontalPadding(24); - - StructureStart wrapped = NativeStructureReferenceEnvelope.wrap( - generated, - generated.getStructure(), - 0, - terrain); - BoundingBox referenceBounds = NativeStructureReferenceEnvelope.referenceBounds( - wrapped, wrapped.getStructure(), terrain); - - assertEquals(content, NativeStructureReferenceEnvelope.contentBounds(wrapped)); - assertEquals(content, wrapped.getBoundingBox()); - assertEquals(content.minX() - 24, referenceBounds.minX()); - assertEquals(content.minZ() - 24, referenceBounds.minZ()); - assertEquals(content.maxX() + 24, referenceBounds.maxX()); - assertEquals(content.maxZ() + 24, referenceBounds.maxZ()); - assertEquals(generated.getPieces().size(), wrapped.getPieces().size()); - } - - @Test - public void nativeVacuumReservesItsFixedSurfaceFalloff() { - StructureStart generated = desertStart(TerrainAdjustment.NONE); - BoundingBox content = NativeStructureReferenceEnvelope.contentBounds(generated); - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.VACUUM) - .setHorizontalPadding(64); - - BoundingBox references = NativeStructureReferenceEnvelope.referenceBounds( - generated, generated.getStructure(), terrain); - - assertEquals(content.minX() - NativeStructureSurfaceFitter.surfaceTerrainRadius(), - references.minX()); - assertEquals(content.maxX() + NativeStructureSurfaceFitter.surfaceTerrainRadius(), - references.maxX()); - assertEquals(content.minZ() - NativeStructureSurfaceFitter.surfaceTerrainRadius(), - references.minZ()); - assertEquals(content.maxZ() + NativeStructureSurfaceFitter.surfaceTerrainRadius(), - references.maxZ()); - } - - @Test - public void nativeTerrainEnvelopeClipsOptionalCoverageWithoutDroppingContent() { - StructureStart generated = desertStart(); - ChunkPos origin = generated.getChunkPos(); - BoundingBox content = NativeStructureReferenceEnvelope.contentBounds(generated); - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.FORCE_CARVE) - .setHorizontalPadding(124); - - BoundingBox references = NativeStructureReferenceEnvelope.referenceBounds( - generated, generated.getStructure(), terrain, "test:clipped_terrain"); - StructureStart published = NativeStructureReferenceEnvelope.wrapForPublication( - generated, generated.getStructure(), 0, terrain, "test:clipped_terrain"); - - assertEquals(Math.max(content.minX() - 124, (origin.x() - 8) << 4), references.minX()); - assertEquals(Math.min(content.maxX() + 124, ((origin.x() + 8) << 4) + 15), references.maxX()); - assertEquals(Math.max(content.minZ() - 124, (origin.z() - 8) << 4), references.minZ()); - assertEquals(Math.min(content.maxZ() + 124, ((origin.z() + 8) << 4) + 15), references.maxZ()); - assertTrue(references.isInside(content.getCenter())); - assertTrue(published.isValid()); - assertEquals(1, generated.getPieces().size()); - } - - @Test - public void singlePoolTemplateFieldMatchesTheRuntimeContract() { - Field field = NativeStructureReflection.resolveSinglePoolTemplateField(); - - assertEquals(SinglePoolElement.class, field.getDeclaringClass()); - assertEquals(Either.class, field.getType()); - assertTrue(Modifier.isProtected(field.getModifiers())); - assertTrue(Modifier.isFinal(field.getModifiers())); - assertFalse(Modifier.isStatic(field.getModifiers())); - assertTrue(field.trySetAccessible()); - } - - @Test - public void runtimeTemplatesAndLegacyAirUseTheExactContract() { - StructureTemplate runtimeTemplate = new StructureTemplate(); - - assertEquals(runtimeTemplate, NativeStructureReflection.resolveTemplateReference( - Either.right(runtimeTemplate), null)); - assertFalse(NativeStructureTerrainIntegrator.shouldClearLegacyAir(79, 80, false)); - assertTrue(NativeStructureTerrainIntegrator.shouldClearLegacyAir(80, 80, false)); - assertTrue(NativeStructureTerrainIntegrator.shouldClearLegacyAir(96, 80, false)); - assertFalse(NativeStructureTerrainIntegrator.shouldClearLegacyAir(96, 80, true)); - } - - @Test - public void rotatedTemplateAirClearsOnlyInsideTheChunkAndAboveTheFloor() throws Exception { - StructureTemplate.StructureBlockInfo clear = new StructureTemplate.StructureBlockInfo( - new BlockPos(1, 0, 0), Blocks.AIR.defaultBlockState(), null); - StructureTemplate.StructureBlockInfo belowFloor = new StructureTemplate.StructureBlockInfo( - new BlockPos(0, -1, 0), Blocks.AIR.defaultBlockState(), null); - StructureTemplate.StructureBlockInfo outsideChunk = new StructureTemplate.StructureBlockInfo( - new BlockPos(3, 0, 0), Blocks.AIR.defaultBlockState(), null); - StructureTemplate template = template(List.of(clear, belowFloor, outsideChunk)); - BlockPos origin = new BlockPos(10, 80, 10); - StructurePlaceSettings settings = new StructurePlaceSettings().setRotation(Rotation.CLOCKWISE_90); - BlockPos clearPosition = origin.offset(StructureTemplate.calculateRelativePosition(settings, clear.pos())); - BlockPos belowFloorPosition = origin.offset( - StructureTemplate.calculateRelativePosition(settings, belowFloor.pos())); - BlockPos outsidePosition = origin.offset( - StructureTemplate.calculateRelativePosition(settings, outsideChunk.pos())); - BoundingBox area = new BoundingBox( - Math.min(clearPosition.getX(), belowFloorPosition.getX()), - Math.min(clearPosition.getY(), belowFloorPosition.getY()), - Math.min(clearPosition.getZ(), belowFloorPosition.getZ()), - Math.max(clearPosition.getX(), belowFloorPosition.getX()), - Math.max(clearPosition.getY(), belowFloorPosition.getY()), - Math.max(clearPosition.getZ(), belowFloorPosition.getZ())); - settings.setBoundingBox(area); - assertFalse(area.isInside(outsidePosition)); - Map blocks = new HashMap<>(); - blocks.put(clearPosition, Blocks.DIRT.defaultBlockState()); - blocks.put(belowFloorPosition, Blocks.DIRT.defaultBlockState()); - blocks.put(outsidePosition, Blocks.DIRT.defaultBlockState()); - - NativeStructureTerrainIntegrator.clearTemplateAir( - world(blocks), template, origin, 80, settings); - - assertEquals(Blocks.AIR.defaultBlockState(), blocks.get(clearPosition)); - assertEquals(Blocks.DIRT.defaultBlockState(), blocks.get(belowFloorPosition)); - assertEquals(Blocks.DIRT.defaultBlockState(), blocks.get(outsidePosition)); - } - - @Test - public void unrelatedPieceBoundsAreRejectedBeforeTemplateScanning() { - BoundingBox area = new BoundingBox(0, -64, 0, 15, 319, 15); - - assertTrue(NativeStructureTerrainIntegrator.intersects( - new BoundingBox(15, 60, 15, 30, 90, 30), area)); - assertFalse(NativeStructureTerrainIntegrator.intersects( - new BoundingBox(16, 60, 16, 30, 90, 30), area)); - assertFalse(NativeStructureTerrainIntegrator.intersects( - new BoundingBox(0, 320, 0, 15, 350, 15), area)); - } - - @Test - public void templateAirDoesNotEraseTreesInsideVillagePieces() throws Exception { - BlockPos origin = new BlockPos(0, 80, 0); - StructureTemplate template = template(List.of( - new StructureTemplate.StructureBlockInfo(BlockPos.ZERO, Blocks.AIR.defaultBlockState(), null))); - StructurePlaceSettings settings = new StructurePlaceSettings().setRotation(Rotation.NONE); - Map blocks = new HashMap<>(); - BlockState log = Blocks.OAK_LOG.defaultBlockState(); - blocks.put(origin, log); - - NativeStructureTerrainIntegrator.clearTemplateAir( - world(blocks), template, origin, 80, settings); - - assertEquals(log, blocks.get(origin)); - } - - private static NativeStructureSurfaceFitter.SurfaceAnchor anchor(int meetY, int strength) { - return new NativeStructureSurfaceFitter.SurfaceAnchor(0, 4, 0, 4, meetY, strength); - } - - private static PoolElementStructurePiece rigidPiece(BoundingBox bounds, int groundLevelDelta) { - StructurePoolElement element = StructurePoolElement.single( - "minecraft:empty").apply(StructureTemplatePool.Projection.RIGID); - return new PoolElementStructurePiece( - null, element, - new BlockPos(bounds.minX(), bounds.minY(), bounds.minZ()), - groundLevelDelta, Rotation.NONE, bounds, - LiquidSettings.APPLY_WATERLOGGING); - } - - private static PoolElementStructurePiece rigidTemplatePiece( - StructurePoolElement element, BoundingBox bounds, - int groundLevelDelta, Rotation rotation) { - return new PoolElementStructurePiece( - null, element, - new BlockPos(bounds.minX(), bounds.minY(), bounds.minZ()), - groundLevelDelta, rotation, bounds, - LiquidSettings.APPLY_WATERLOGGING); - } - - private static StructureStart rigidSurfaceStart(List pieces) { - return rigidSurfaceStart(pieces, TerrainAdjustment.BEARD_BOX); - } - - private static StructureStart rigidSurfaceStart( - List pieces, TerrainAdjustment adjustment) { - Structure structure = new DesertPyramidStructure( - new Structure.StructureSettings( - HolderSet.empty(), Map.of(), - GenerationStep.Decoration.SURFACE_STRUCTURES, - adjustment)); - List structurePieces = new ArrayList<>(pieces); - return new StructureStart( - structure, new ChunkPos(0, 0), 0, - new PiecesContainer(structurePieces)); - } - - private static NativeStructureTerrainIntegrator.TerrainTarget surfaceTarget( - StructureStart start) { - return surfaceTarget(start, IrisStructureTerrainMode.SOURCE); - } - - private static NativeStructureTerrainIntegrator.TerrainTarget surfaceTarget( - StructureStart start, IrisStructureTerrainMode mode) { - return new NativeStructureTerrainIntegrator.TerrainTarget( - "nova_structures:tavern_oak", start, - new IrisStructureTerrain().setMode(mode)); - } - - 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 Map supportTerrain(int minimumX, int maximumX) { - Map blocks = new HashMap<>(); - for (int x = minimumX; x <= maximumX; x++) { - put(blocks, x, 61, 0, Blocks.DIRT.defaultBlockState()); - put(blocks, x, 62, 0, Blocks.GRASS_BLOCK.defaultBlockState()); - } - return blocks; - } - - private static Map flatTerrain(BoundingBox area, int surfaceY) { - Map blocks = new HashMap<>(); - for (int x = area.minX(); x <= area.maxX(); x++) { - for (int z = area.minZ(); z <= area.maxZ(); z++) { - put(blocks, x, surfaceY - 1, z, Blocks.DIRT.defaultBlockState()); - put(blocks, x, surfaceY, z, Blocks.GRASS_BLOCK.defaultBlockState()); - } - } - return blocks; - } - - private static NativeStructureTerrainIntegrator.OrganicCarve organicCarve( - StructureStart start, int horizontalPadding) { - return organicCarve(start, horizontalPadding, 0.85D); - } - - private static NativeStructureTerrainIntegrator.OrganicCarve organicCarve( - StructureStart start, int horizontalPadding, double lobeStrength) { - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.FORCE_CARVE) - .setShape(IrisStructureCarveShape.ERODED) - .setHorizontalPadding(horizontalPadding) - .setCeilingPadding(8) - .setFloorPadding(0) - .setErosionStrength(1D) - .setErosionFrequency(0.05D) - .setLobeStrength(lobeStrength); - return NativeStructureTerrainIntegrator.organicCarve( - NativeStructureTerrainIntegrator.carveFootprint(start, horizontalPadding, - NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager), - terrain, IrisStructureCarveShape.ERODED, TEST_SEED); - } - - /** - * Outward carve depth for every column along the straight +X edge of a slab footprint, measured - * inside the source vertical span so the boundary is decided purely by the horizontal threshold. - * The slab spans several lobe wavelengths so a lobed boundary is distinguishable from a uniform one. - */ - private static int[] slabEdgeCarveDepths(double lobeStrength) { - StructureCarvingFootprint footprint = StructureCarvingFootprint.fromColumns(sink -> { - for (int x = 0; x < SLAB_WIDTH; x++) { - for (int z = 0; z < SLAB_DEPTH; z++) { - sink.column(x, z, SLAB_MIN_Y, SLAB_MIN_Y + 8); - } - } - return true; - }, SLAB_PADDING, 1_000_000); - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.FORCE_CARVE) - .setShape(IrisStructureCarveShape.ERODED) - .setHorizontalPadding(SLAB_PADDING) - .setCeilingPadding(8) - .setFloorPadding(0) - .setErosionStrength(1D) - .setErosionFrequency(0.05D) - .setLobeStrength(lobeStrength); - int transectY = SLAB_MIN_Y + 4; - BoundingBox area = new BoundingBox( - SLAB_WIDTH, transectY, 0, - SLAB_WIDTH - 1 + SLAB_PADDING, transectY, SLAB_DEPTH - 1); - Map blocks = fill(area); - - NativeStructureTerrainIntegrator.carveOrganicColumns(world(blocks), area, - NativeStructureTerrainIntegrator.organicCarve( - footprint, terrain, IrisStructureCarveShape.ERODED, TEST_SEED)); - - int[] depths = new int[SLAB_DEPTH]; - for (int z = 0; z < SLAB_DEPTH; z++) { - int depth = 0; - while (depth < SLAB_PADDING - && state(blocks, SLAB_WIDTH + depth, transectY, z).isAir()) { - depth++; - } - depths[z] = depth; - } - return depths; - } - - private static int span(int[] values) { - int lowest = Integer.MAX_VALUE; - int highest = Integer.MIN_VALUE; - for (int value : values) { - lowest = Math.min(lowest, value); - highest = Math.max(highest, value); - } - return highest - lowest; - } - - private static StructureTemplateManager forbiddenTemplateManager() { - throw new AssertionError("Bounding-box carve columns must not resolve templates"); - } - - private static Map fill(BoundingBox area) { - Map blocks = new HashMap<>(); - 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++) { - put(blocks, x, y, z, Blocks.STONE.defaultBlockState()); - } - } - } - return blocks; - } - - private static StructureTemplate template( - List blocks) throws Exception { - Constructor constructor = - StructureTemplate.Palette.class.getDeclaredConstructor(List.class); - assertTrue(constructor.trySetAccessible()); - StructureTemplate.Palette palette = constructor.newInstance(blocks); - StructureTemplate template = new StructureTemplate(); - template.palettes.add(palette); - return template; - } - - private static final class InlineSinglePoolElement extends SinglePoolElement { - private InlineSinglePoolElement(StructureTemplate template) { - this(template, List.of()); - } - - private InlineSinglePoolElement( - StructureTemplate template, List processors) { - this(template, processors, StructureTemplatePool.Projection.RIGID); - } - - private InlineSinglePoolElement( - StructureTemplate template, List processors, - StructureTemplatePool.Projection projection) { - super(Either.right(template), - Holder.direct(new StructureProcessorList(processors)), - 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()); - } - } - - private static StructureProcessor replaceBlockProcessor(BlockState source, BlockState replacement) { - // Vanilla RuleProcessor instead of a custom StructureProcessor subtype: StructureProcessor - // is an abstract class on 26.1.2 and an interface on 26.2, so a direct subtype cannot - // compile against both dev bundles. BlockStateMatchTest matches the exact source state, - // matching the previous custom processor's identity-equality semantics. - return new RuleProcessor(List.of(new ProcessorRule( - new BlockStateMatchTest(source), AlwaysTrueTest.INSTANCE, replacement))); - } - - private static StructureStart desertStart() { - return desertStart(TerrainAdjustment.NONE); - } - - private static StructureStart desertStart(TerrainAdjustment adjustment) { - Structure structure = new DesertPyramidStructure( - new Structure.StructureSettings( - HolderSet.empty(), Map.of(), - GenerationStep.Decoration.SURFACE_STRUCTURES, adjustment)); - DesertPyramidPiece piece = new DesertPyramidPiece(RandomSource.create(7L), 0, 0); - return new StructureStart( - structure, new ChunkPos(0, 0), 0, new PiecesContainer(List.of(piece))); - } - - private static WorldGenLevel world(Map blocks) { - InvocationHandler handler = (proxy, method, arguments) -> { - String methodName = method.getName(); - if (methodName.equals("getBlockState")) { - BlockPos position = (BlockPos) arguments[0]; - return state(blocks, position.getX(), position.getY(), position.getZ()); - } - if (methodName.equals("setBlock")) { - BlockPos position = (BlockPos) arguments[0]; - BlockState blockState = (BlockState) arguments[1]; - put(blocks, position.getX(), position.getY(), position.getZ(), blockState); - return true; - } - if (methodName.equals("getSeed")) { - return TEST_SEED; - } - if (methodName.equals("getHeight")) { - int x = (int) arguments[1]; - int z = (int) arguments[2]; - int highest = Integer.MIN_VALUE; - for (Map.Entry entry : blocks.entrySet()) { - BlockPos position = entry.getKey(); - if (position.getX() == x && position.getZ() == z - && !entry.getValue().isAir()) { - highest = Math.max(highest, position.getY()); - } - } - return highest == Integer.MIN_VALUE ? 0 : highest + 1; - } - if (methodName.equals("getLevel")) { - return null; - } - if (methodName.equals("holderLookup")) { - return BuiltInRegistries.BLOCK; - } - if (methodName.equals("hashCode")) { - return System.identityHashCode(proxy); - } - if (methodName.equals("equals")) { - return proxy == arguments[0]; - } - if (methodName.equals("toString")) { - return "surface-test-world"; - } - throw new UnsupportedOperationException(method.toString()); - }; - return (WorldGenLevel) Proxy.newProxyInstance( - WorldGenLevel.class.getClassLoader(), new Class[]{WorldGenLevel.class}, handler); - } - - private static WorldGenLevel world(ChunkAccess chunk) { - InvocationHandler handler = (proxy, method, arguments) -> { - String methodName = method.getName(); - if (methodName.equals("getBlockState")) { - return chunk.getBlockState((BlockPos) arguments[0]); - } - if (methodName.equals("setBlock")) { - return chunk.setBlockState( - ((BlockPos) arguments[0]).immutable(), - (BlockState) arguments[1], (int) arguments[2]) != null; - } - if (methodName.equals("getSeed")) { - return TEST_SEED; - } - if (methodName.equals("getLevel")) { - return null; - } - if (methodName.equals("holderLookup")) { - return BuiltInRegistries.BLOCK; - } - if (methodName.equals("hashCode")) { - return System.identityHashCode(proxy); - } - if (methodName.equals("equals")) { - return proxy == arguments[0]; - } - if (methodName.equals("toString")) { - return "surface-test-chunk-world"; - } - throw new UnsupportedOperationException(method.toString()); - }; - return (WorldGenLevel) Proxy.newProxyInstance( - WorldGenLevel.class.getClassLoader(), new Class[]{WorldGenLevel.class}, handler); - } - - private static void write(ProtoChunk chunk, int x, int y, int z, BlockState state) { - LevelChunkSection section = chunk.getSection(chunk.getSectionIndex(y)); - section.setBlockState(x, y & 15, z, state, false); - } - - private static PalettedContainerFactory containerFactory() { - Strategy blockStates = Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY); - BlockState air = Blocks.AIR.defaultBlockState(); - IdMapper> biomeIds = new IdMapper<>(); - Holder defaultBiome = Holder.direct((Biome) null); - biomeIds.add(defaultBiome); - Strategy> biomes = Strategy.createForBiomes(biomeIds); - Codec> biomeCodec = Codec.STRING.xmap( - name -> defaultBiome, holder -> "iris-test-biome"); - return new PalettedContainerFactory( - blockStates, - air, - PalettedContainer.codecRW(BlockState.CODEC, blockStates, air), - biomes, - defaultBiome, - PalettedContainer.codecRO(biomeCodec, biomes, defaultBiome), - PalettedContainer.codecRW(biomeCodec, biomes, defaultBiome)); - } - - private static void put(Map blocks, - int x, int y, int z, BlockState state) { - blocks.put(new BlockPos(x, y, z), state); - } - - private static BlockState state(Map blocks, int x, int y, int z) { - return blocks.getOrDefault(new BlockPos(x, y, z), Blocks.AIR.defaultBlockState()); - } -} diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorVegetationTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorVegetationTest.java index 0c464fc4d..3beeef542 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorVegetationTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructurePostProcessorVegetationTest.java @@ -173,21 +173,6 @@ public class NativeStructurePostProcessorVegetationTest { GenerationStep.Decoration.SURFACE_STRUCTURES)); } - @Test - public void undergroundStructuresUseTheLowestTerrainColumn() { - BoundingBox bounds = new BoundingBox(0, 60, 0, 1, 80, 0); - int offset = NativeStructureVerticalPlacer.resolveBuriedOffset( - bounds, 0, -64, 320, (x, z) -> x == 1 ? 76 : 100); - assertEquals(-5, offset); - } - - @Test - public void undergroundBurialClampsToTheWorldFloorInsteadOfFailing() { - BoundingBox bounds = new BoundingBox(0, 60, 0, 1, 80, 0); - assertEquals(-2, NativeStructureVerticalPlacer.resolveBuriedOffset( - bounds, 0, 58, 320, (x, z) -> x == 1 ? 76 : 100)); - } - private static void clearVegetation(ProtoChunk chunk, StructureStart start) { NativeStructureVegetationClearer.clearIntersectingVegetation( world(chunk), chunk, AREA, List.of(start)); diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureVolumeIndexTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureVolumeIndexTest.java index edda00a7b..d3a597d43 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureVolumeIndexTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureVolumeIndexTest.java @@ -123,8 +123,8 @@ public class NativeStructureVolumeIndexTest { public void vanillaVolumesAreGatedOnPackPolicy() throws Exception { String source = Files.readString(Path.of(System.getProperty("iris.nativeStructureVolumeIndexSource"))); - assertTrue(source.contains("NativeStructureGenerationPolicy.resolve(")); - assertTrue(source.contains("if (!decision.generate())")); + assertTrue(source.contains("if (!NativeStructureGenerationPolicy.generates(engine, structureId))")); + assertTrue(source.contains("NativeStructureLayouts.shift(engine")); assertTrue(source.contains("isStructureChunk(")); } diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandFind.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandFind.java index f5e506ee6..393265e19 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandFind.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandFind.java @@ -30,9 +30,8 @@ import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; import art.arcane.iris.engine.framework.StructureReachability; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; +import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; import art.arcane.iris.engine.platform.EngineBukkitOps; import art.arcane.iris.platform.bukkit.BukkitPlatform; import art.arcane.iris.spi.IrisPlatforms; @@ -144,20 +143,20 @@ public class CommandFind implements DirectorExecutor { String structureKey = structure == null ? "" : structure.trim(); Structure nativeStructure = resolveNativeStructure(structureKey); boolean registered = nativeStructure != null; - IrisNativeStructureDecision decision = registered - ? NativeStructureGenerationPolicy.resolve(e, structureKey, false) + NativeStructureGenerationStatus status = registered + ? NativeStructureGenerationPolicy.resolve(e, structureKey) : null; boolean nativePlacement = IrisStructureLocator.hasNativePlacement(e, structureKey); boolean locatableNativePlacement = IrisStructureLocator.hasLocatableNativePlacement(e, structureKey); boolean locatableEditablePlacement = ModuleServices.canLocateStructure(e, structureKey); World targetWorld = target.getWorld(); boolean nativeGenerationEnabled = targetWorld.canGenerateStructures(); - boolean requiresReachability = registered && decision.generate() - && decision.status() != NativeStructureGenerationStatus.REPLACED_BY_IRIS + boolean requiresReachability = registered && status == NativeStructureGenerationStatus.GENERATE_NATIVE + && status != NativeStructureGenerationStatus.REPLACED_BY_IRIS && nativeGenerationEnabled; boolean reachable = !requiresReachability || StructureReachability.isReachable(e, structureKey); StructureLookupRoute route = selectStructureLookupRoute( - registered, decision, nativePlacement, locatableNativePlacement, + registered, status, nativePlacement, locatableNativePlacement, locatableEditablePlacement, nativeGenerationEnabled, reachable); if (route == StructureLookupRoute.UNKNOWN) { @@ -166,7 +165,7 @@ public class CommandFind implements DirectorExecutor { } if (route == StructureLookupRoute.POLICY_DISABLED) { commandSender.sendMessage(C.RED + NativeStructureGenerationPolicy.generationStatusMessage( - structureKey, decision.status())); + structureKey, status)); return; } if (route == StructureLookupRoute.NO_ACTIVE_PLACEMENT) { @@ -273,24 +272,24 @@ public class CommandFind implements DirectorExecutor { for (Map.Entry entry : registeredKeys.entrySet()) { String normalizedKey = entry.getKey(); String key = entry.getValue(); - IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, key, false); + NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key); boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key); boolean locatableNativePlacement = IrisStructureLocator.hasLocatableNativePlacement(engine, key); boolean locatableEditablePlacement = ModuleServices.canLocateStructure(engine, key); StructureLookupRoute route = selectStructureLookupRoute( - true, decision, nativePlacement, locatableNativePlacement, + true, status, nativePlacement, locatableNativePlacement, locatableEditablePlacement, nativeGenerationEnabled, reachableKeys.contains(normalizedKey)); if (route == StructureLookupRoute.IRIS || route == StructureLookupRoute.NATIVE) { continue; } - List requiredBiomes = needsNativeReachabilityReason(route, decision) + List requiredBiomes = needsNativeReachabilityReason(route, status) ? structureHooks.structureBiomeKeys(key) : List.of(); exclusions.add(new StructureExclusion( StructureExclusionKind.EXCLUDED, key, null, describeStructureExclusion( - route, key, decision.status(), nativePlacement, + route, key, status, nativePlacement, requiredBiomes, possibleBiomeKeys))); registeredExcluded++; } @@ -418,9 +417,9 @@ public class CommandFind implements DirectorExecutor { } private static boolean needsNativeReachabilityReason( - StructureLookupRoute route, IrisNativeStructureDecision decision) { + StructureLookupRoute route, NativeStructureGenerationStatus status) { return route == StructureLookupRoute.UNREACHABLE - || route == StructureLookupRoute.NO_ACTIVE_PLACEMENT && decision.generate(); + || route == StructureLookupRoute.NO_ACTIVE_PLACEMENT && status == NativeStructureGenerationStatus.GENERATE_NATIVE; } static String describeStructureExclusion( @@ -529,7 +528,7 @@ public class CommandFind implements DirectorExecutor { } static StructureLookupRoute selectStructureLookupRoute( - boolean registered, IrisNativeStructureDecision decision, boolean nativePlacement, + boolean registered, NativeStructureGenerationStatus status, boolean nativePlacement, boolean locatableNativePlacement, boolean locatableEditablePlacement, boolean nativeGenerationEnabled, boolean reachable) { if (!registered) { @@ -537,14 +536,14 @@ public class CommandFind implements DirectorExecutor { ? StructureLookupRoute.IRIS : StructureLookupRoute.UNKNOWN; } - if (decision == null) { - throw new IllegalArgumentException("Registered structure lookup requires a generation decision"); + if (status == null) { + throw new IllegalArgumentException("Registered structure lookup requires a generation status"); } - if (!decision.generate() - && decision.status() != NativeStructureGenerationStatus.REPLACED_BY_IRIS) { + if (status != NativeStructureGenerationStatus.GENERATE_NATIVE + && status != NativeStructureGenerationStatus.REPLACED_BY_IRIS) { return StructureLookupRoute.POLICY_DISABLED; } - if (decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS) { + if (status == NativeStructureGenerationStatus.REPLACED_BY_IRIS) { if (!nativePlacement) { return locatableEditablePlacement ? StructureLookupRoute.IRIS diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStructure.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStructure.java index 6f2b3c8bc..297223617 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStructure.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStructure.java @@ -36,10 +36,9 @@ import art.arcane.iris.engine.framework.StructureReachability; import art.arcane.iris.engine.framework.structure.StructureAssemblyResult; import art.arcane.iris.engine.object.placement.IObjectPlacer; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; +import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; import art.arcane.volmlib.util.collection.KList; import art.arcane.iris.util.common.director.DirectorExecutor; import art.arcane.iris.util.common.format.C; @@ -173,13 +172,13 @@ public class CommandStructure implements DirectorExecutor { private void runVerification(Engine engine, KList structureKeys, int centerX, int centerZ, int searchRadius, VolmitSender commandSender, Player target) { KList messages = new KList<>(); - Map decisions = new HashMap<>(structureKeys.size()); + Map statuses = new HashMap<>(structureKeys.size()); boolean requiresNativeReachability = false; for (String keyName : structureKeys) { - IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, keyName, false); - decisions.put(keyName, decision); + NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, keyName); + statuses.put(keyName, status); requiresNativeReachability |= !IrisStructureLocator.isPlaced(engine, keyName) - && decision.generate(); + && status == NativeStructureGenerationStatus.GENERATE_NATIVE; } Set reachable = Set.of(); if (requiresNativeReachability) { @@ -199,7 +198,7 @@ public class CommandStructure implements DirectorExecutor { int searchLimited = 0; int errors = 0; for (String keyName : structureKeys) { - IrisNativeStructureDecision decision = decisions.get(keyName); + NativeStructureGenerationStatus status = statuses.get(keyName); if (IrisStructureLocator.isPlaced(engine, keyName)) { try { IrisStructureLocator.LocateResult result = @@ -225,7 +224,7 @@ public class CommandStructure implements DirectorExecutor { } continue; } - if (!decision.generate()) { + if (status != NativeStructureGenerationStatus.GENERATE_NATIVE) { disabled++; messages.add(C.GRAY + "[disabled] " + C.WHITE + keyName); continue; diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/IrisStructureLocateCommandContractTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/IrisStructureLocateCommandContractTest.java index 6a8f77ead..142108310 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/IrisStructureLocateCommandContractTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/IrisStructureLocateCommandContractTest.java @@ -1,8 +1,7 @@ package art.arcane.iris.core.commands; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; +import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; import org.junit.Test; import java.io.IOException; @@ -64,11 +63,11 @@ public class IrisStructureLocateCommandContractTest { false, null, false, false, false, true, true)); assertEquals(CommandFind.StructureLookupRoute.NO_ACTIVE_PLACEMENT, CommandFind.selectStructureLookupRoute( - true, decision(NativeStructureGenerationStatus.REPLACED_BY_IRIS), + true, NativeStructureGenerationStatus.REPLACED_BY_IRIS, false, false, false, true, true)); assertEquals(CommandFind.StructureLookupRoute.NO_ACTIVE_PLACEMENT, CommandFind.selectStructureLookupRoute( - true, decision(NativeStructureGenerationStatus.GENERATE_NATIVE), + true, NativeStructureGenerationStatus.GENERATE_NATIVE, true, false, false, true, false)); } @@ -79,7 +78,7 @@ public class IrisStructureLocateCommandContractTest { false, null, false, false, true, false, false)); assertEquals(CommandFind.StructureLookupRoute.IRIS, CommandFind.selectStructureLookupRoute( - true, decision(NativeStructureGenerationStatus.REPLACED_BY_IRIS), + true, NativeStructureGenerationStatus.REPLACED_BY_IRIS, false, false, true, false, false)); } @@ -87,23 +86,23 @@ public class IrisStructureLocateCommandContractTest { public void findRequiresWorldGenerationAndReachabilityForNativeRoutes() { assertEquals(CommandFind.StructureLookupRoute.WORLD_DISABLED, CommandFind.selectStructureLookupRoute( - true, decision(NativeStructureGenerationStatus.REPLACED_BY_IRIS), + true, NativeStructureGenerationStatus.REPLACED_BY_IRIS, true, true, false, false, true)); assertEquals(CommandFind.StructureLookupRoute.WORLD_DISABLED, CommandFind.selectStructureLookupRoute( - true, decision(NativeStructureGenerationStatus.GENERATE_NATIVE), + true, NativeStructureGenerationStatus.GENERATE_NATIVE, false, false, false, false, true)); assertEquals(CommandFind.StructureLookupRoute.UNREACHABLE, CommandFind.selectStructureLookupRoute( - true, decision(NativeStructureGenerationStatus.GENERATE_NATIVE), + true, NativeStructureGenerationStatus.GENERATE_NATIVE, false, false, false, true, false)); assertEquals(CommandFind.StructureLookupRoute.NATIVE, CommandFind.selectStructureLookupRoute( - true, decision(NativeStructureGenerationStatus.GENERATE_NATIVE), + true, NativeStructureGenerationStatus.GENERATE_NATIVE, true, true, false, true, false)); assertEquals(CommandFind.StructureLookupRoute.NATIVE, CommandFind.selectStructureLookupRoute( - true, decision(NativeStructureGenerationStatus.GENERATE_NATIVE), + true, NativeStructureGenerationStatus.GENERATE_NATIVE, true, false, false, true, true)); } @@ -111,7 +110,7 @@ public class IrisStructureLocateCommandContractTest { public void findHonorsPackDisableBeforePlacementRouting() { assertEquals(CommandFind.StructureLookupRoute.POLICY_DISABLED, CommandFind.selectStructureLookupRoute( - true, decision(NativeStructureGenerationStatus.DISABLED_BY_PACK), + true, NativeStructureGenerationStatus.DISABLED_BY_PACK, false, false, true, true, true)); } @@ -281,7 +280,7 @@ public class IrisStructureLocateCommandContractTest { int methodStart = source.indexOf("private void runVerification("); int methodEnd = source.indexOf("private void sendVerificationMessages(", methodStart); String method = source.substring(methodStart, methodEnd); - int policyResolution = method.indexOf("NativeStructureGenerationPolicy.resolve(engine, keyName, false)"); + int policyResolution = method.indexOf("NativeStructureGenerationPolicy.resolve(engine, keyName)"); int nativeRequirement = method.indexOf( "requiresNativeReachability |= !IrisStructureLocator.isPlaced", policyResolution); int reachabilityGuard = method.indexOf("if (requiresNativeReachability)", nativeRequirement); @@ -292,9 +291,4 @@ public class IrisStructureLocateCommandContractTest { assertTrue(reachabilityGuard > nativeRequirement); assertTrue(reachabilityLookup > reachabilityGuard); } - - private static IrisNativeStructureDecision decision(NativeStructureGenerationStatus status) { - return new IrisNativeStructureDecision( - status, 0, null, false, null, null); - } } diff --git a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureFactory.java b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureFactory.java index a40296afa..499965892 100644 --- a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureFactory.java +++ b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureFactory.java @@ -1,9 +1,8 @@ package art.arcane.iris.nativegen; +import art.arcane.iris.engine.framework.NativeJigsawOverrides; +import art.arcane.iris.engine.framework.NativeStructureReach; import art.arcane.iris.engine.framework.NativeStructureStartPlan; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConfiguration; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawHeightmap; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawLiquidSettings; import art.arcane.iris.spi.PlatformStructureHooks.JigsawSourceMetadata; import net.minecraft.core.Holder; import net.minecraft.core.RegistryAccess; @@ -25,17 +24,21 @@ import net.minecraft.world.level.levelgen.structure.StructureStart; import net.minecraft.world.level.levelgen.structure.structures.JigsawStructure; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; +import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.function.IntBinaryOperator; import java.util.function.Predicate; public final class NativeStructureFactory { + private static final String NO_HEIGHTMAP = "NONE"; private NativeStructureFactory() { } + /** The start {@code plan} describes, placed at its height; {@code reaches} are the modules' reaches around it. */ public static StructureStart generate(GenerationContext context, Holder sourceHolder, - NativeStructureStartPlan plan, int references) { + NativeStructureStartPlan plan, int references, + List reaches) { Structure source = sourceHolder.value(); Structure configured = configure( context.registryAccess(), source, plan.jigsaw(), @@ -75,9 +78,6 @@ public final class NativeStructureFactory { context.seaLevel(), context.heightAccessor().getMinY(), Math.addExact(context.heightAccessor().getMinY(), context.heightAccessor().getHeight()), - false, - false, - null, context.surfaceHeight()); positioned = generated; } @@ -88,7 +88,7 @@ public final class NativeStructureFactory { positioned, source, references, - plan.terrain(), + reaches, plan.structureKey() ); } @@ -120,7 +120,7 @@ public final class NativeStructureFactory { } static Structure configure(RegistryAccess registryAccess, Structure source, - IrisJigsawConfiguration configuration, + NativeJigsawOverrides configuration, boolean underground, int baseY) { Objects.requireNonNull(source, "Native structure source must not be null"); if (!(source instanceof JigsawStructure sourceJigsaw)) { @@ -162,36 +162,36 @@ public final class NativeStructureFactory { return structureTag; } - private static void applyConfiguration(CompoundTag tag, IrisJigsawConfiguration configuration) { + private static void applyConfiguration(CompoundTag tag, NativeJigsawOverrides configuration) { if (configuration == null) { return; } - if (configuration.getStartPool() != null && !configuration.getStartPool().isBlank()) { - tag.putString("start_pool", configuration.getStartPool().trim()); + if (configuration.startPool() != null && !configuration.startPool().isBlank()) { + tag.putString("start_pool", configuration.startPool().trim()); } - if (configuration.getStartJigsawName() != null - && !configuration.getStartJigsawName().isBlank()) { - if ("NONE".equalsIgnoreCase(configuration.getStartJigsawName().trim())) { + if (configuration.startJigsawName() != null + && !configuration.startJigsawName().isBlank()) { + if ("NONE".equalsIgnoreCase(configuration.startJigsawName().trim())) { tag.remove("start_jigsaw_name"); } else { - tag.putString("start_jigsaw_name", configuration.getStartJigsawName().trim()); + tag.putString("start_jigsaw_name", configuration.startJigsawName().trim()); } } - if (configuration.getMaxDepth() != null) { - tag.putInt("size", configuration.getMaxDepth()); + if (configuration.maxDepth() != null) { + tag.putInt("size", configuration.maxDepth()); } applyDistance(tag, configuration); - if (configuration.getUseExpansionHack() != null) { - tag.putBoolean("use_expansion_hack", configuration.getUseExpansionHack()); + if (configuration.useExpansionHack() != null) { + tag.putBoolean("use_expansion_hack", configuration.useExpansionHack()); } - applyHeightmap(tag, configuration.getProjectStartToHeightmap()); + applyHeightmap(tag, configuration.projectStartToHeightmap()); applyDimensionPadding(tag, configuration); - applyLiquidSettings(tag, configuration.getLiquidSettings()); + applyLiquidSettings(tag, configuration.liquidSettings()); } - private static void applyDistance(CompoundTag tag, IrisJigsawConfiguration configuration) { - Integer horizontal = configuration.getMaxDistanceHorizontal(); - Integer vertical = configuration.getMaxDistanceVertical(); + private static void applyDistance(CompoundTag tag, NativeJigsawOverrides configuration) { + Integer horizontal = configuration.maxDistanceHorizontal(); + Integer vertical = configuration.maxDistanceVertical(); if (horizontal == null && vertical == null) { return; } @@ -223,20 +223,20 @@ public final class NativeStructureFactory { return Math.max(0, Math.max(expansion, adjusted.maxZ() - content.maxZ())); } - private static void applyHeightmap(CompoundTag tag, IrisJigsawHeightmap heightmap) { - if (heightmap == null || heightmap == IrisJigsawHeightmap.SOURCE) { + private static void applyHeightmap(CompoundTag tag, String heightmap) { + if (heightmap == null || heightmap.equals(NativeJigsawOverrides.SOURCE)) { return; } - if (heightmap == IrisJigsawHeightmap.NONE) { + if (heightmap.equals(NO_HEIGHTMAP)) { tag.remove("project_start_to_heightmap"); return; } - tag.putString("project_start_to_heightmap", heightmap.name()); + tag.putString("project_start_to_heightmap", heightmap); } - private static void applyDimensionPadding(CompoundTag tag, IrisJigsawConfiguration configuration) { - Integer bottom = configuration.getDimensionPaddingBottom(); - Integer top = configuration.getDimensionPaddingTop(); + private static void applyDimensionPadding(CompoundTag tag, NativeJigsawOverrides configuration) { + Integer bottom = configuration.dimensionPaddingBottom(); + Integer top = configuration.dimensionPaddingTop(); if (bottom == null && top == null) { return; } @@ -260,11 +260,11 @@ public final class NativeStructureFactory { return tag.getIntOr("dimension_padding", 0); } - private static void applyLiquidSettings(CompoundTag tag, IrisJigsawLiquidSettings settings) { - if (settings == null || settings == IrisJigsawLiquidSettings.SOURCE) { + private static void applyLiquidSettings(CompoundTag tag, String settings) { + if (settings == null || settings.equals(NativeJigsawOverrides.SOURCE)) { return; } - tag.putString("liquid_settings", settings.name().toLowerCase(Locale.ROOT)); + tag.putString("liquid_settings", settings.toLowerCase(Locale.ROOT)); } public record GenerationContext( diff --git a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureFitBridge.java b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureFitBridge.java new file mode 100644 index 000000000..07e103bad --- /dev/null +++ b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureFitBridge.java @@ -0,0 +1,454 @@ +package art.arcane.iris.nativegen; + +import art.arcane.iris.engine.framework.NativeStartMemo; +import art.arcane.iris.engine.framework.nativefit.NativeFitBlocks; +import art.arcane.iris.engine.framework.nativefit.NativeFitBox; +import art.arcane.iris.engine.framework.nativefit.NativeFitChunk; +import art.arcane.iris.engine.framework.nativefit.NativeFitPiece; +import art.arcane.iris.engine.framework.nativefit.NativeFitStart; +import art.arcane.iris.engine.framework.nativefit.NativeFitTrait; +import art.arcane.iris.engine.framework.nativefit.NativeTemplateCells; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import net.minecraft.commands.arguments.blocks.BlockStateParser; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; +import net.minecraft.core.Direction; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.tags.BlockTags; +import net.minecraft.tags.TagKey; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.WorldGenLevel; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.Rotation; +import net.minecraft.world.level.block.SupportType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.levelgen.structure.BoundingBox; +import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece; +import net.minecraft.world.level.levelgen.structure.StructurePiece; +import net.minecraft.world.level.levelgen.structure.StructureStart; +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.ListPoolElement; +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.templatesystem.StructurePlaceSettings; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.IntBinaryOperator; +import java.util.function.Supplier; + +/** + * The platform's side of the modules' structure fit: a decorated chunk, its starts and their pieces, read from + * Minecraft's own structures and handed to the modules as host values ({@link NativeFitChunk}). It knows how + * Minecraft builds pieces (templates, processors, jigsaw junctions, legacy template air) but nothing of how a module + * fits them. + */ +public final class NativeStructureFitBridge { + private static final int MAX_TEMPLATE_COLUMN_CELLS = 4_194_304; + private static final List TEMPLATE_VOID_BLOCKS = List.of(Blocks.AIR, Blocks.STRUCTURE_VOID); + private static final Map> TAGS = new ConcurrentHashMap<>(); + + private NativeStructureFitBridge() { + } + + /** One start the platform places in the chunk, with the memo its ownership record kept (null for none). */ + public record FitTarget(String structureId, StructureStart start, NativeStartMemo memo) { + } + + /** + * The chunk {@code world} decorates in {@code area}, with its starts in the order the platform places them; + * {@code surfaceHeight} gives the terrain's surface per column in world heights. + */ + public static NativeFitChunk chunk(WorldGenLevel world, BoundingBox area, List targets, + IntBinaryOperator surfaceHeight) { + Supplier templates = () -> world.getLevel().getStructureManager(); + List> starts = new ArrayList<>(targets.size()); + for (FitTarget target : targets) { + starts.add(new MinecraftStart(world, target, templates)); + } + return new NativeFitChunk<>(new MinecraftBlocks(world), box(area), world.getMinY(), + world.getMinY() + world.getHeight(), world.getSeed(), surfaceHeight, y -> naturalBlock(world, y), starts); + } + + /** The block the dimension's natural terrain is made of at world height {@code y}. */ + static BlockState naturalBlock(WorldGenLevel world, int y) { + ServerLevel level = world == null ? null : world.getLevel(); + if (level == null) { + return overworldBlock(y); + } + Holder dimensionType = level.dimensionTypeRegistration(); + return naturalBlock(level.dimension(), dimensionType.unwrapKey().orElse(null), dimensionType.value(), y); + } + + static BlockState naturalBlock(ResourceKey dimension, ResourceKey dimensionTypeKey, + DimensionType dimensionType, int y) { + if (Level.NETHER.equals(dimension)) { + return Blocks.NETHERRACK.defaultBlockState(); + } + if (Level.END.equals(dimension)) { + return Blocks.END_STONE.defaultBlockState(); + } + if (BuiltinDimensionTypes.NETHER.equals(dimensionTypeKey) + || dimensionType != null && dimensionType.hasCeiling() && !dimensionType.hasSkyLight()) { + return Blocks.NETHERRACK.defaultBlockState(); + } + if (BuiltinDimensionTypes.END.equals(dimensionTypeKey) + || dimensionType != null && (dimensionType.hasEnderDragonFight() || dimensionType.hasEndFlashes())) { + return Blocks.END_STONE.defaultBlockState(); + } + return overworldBlock(y); + } + + private static BlockState overworldBlock(int y) { + return y < 0 ? Blocks.DEEPSLATE.defaultBlockState() : Blocks.STONE.defaultBlockState(); + } + + static NativeFitBox box(BoundingBox box) { + return new NativeFitBox(box.minX(), box.minY(), box.minZ(), box.maxX(), box.maxY(), box.maxZ()); + } + + static BoundingBox boundingBox(NativeFitBox box) { + return new BoundingBox(box.minX(), box.minY(), box.minZ(), box.maxX(), box.maxY(), box.maxZ()); + } + + /** Logs, wood, stems, hyphae and leaves, by tag or by the block's name. */ + static boolean isTreeBlock(BlockState state) { + return isLog(state) || isLeaves(state); + } + + private static boolean isLog(BlockState state) { + if (state.is(BlockTags.LOGS)) { + return true; + } + String path = blockPath(state); + return path.endsWith("_log") || path.endsWith("_wood") || path.endsWith("_stem") || path.endsWith("_hyphae"); + } + + private static boolean isLeaves(BlockState state) { + return state.is(BlockTags.LEAVES) || blockPath(state).endsWith("_leaves"); + } + + /** Field reads instead of a registry lookup: this runs per block probe on the hottest fit scans. */ + private static String blockPath(BlockState state) { + return state.getBlock().builtInRegistryHolder().key().identifier().getPath(); + } + + private static final class MinecraftBlocks implements NativeFitBlocks { + private final WorldGenLevel world; + private final BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); + + private MinecraftBlocks(WorldGenLevel world) { + this.world = world; + } + + @Override + public BlockState get(int x, int y, int z) { + return world.getBlockState(position.set(x, y, z)); + } + + @Override + public void set(int x, int y, int z, BlockState state) { + world.setBlock(position.set(x, y, z), state, 2); + } + + @Override + public String key(BlockState state) { + return BlockStateParser.serialize(state); + } + + @Override + public BlockState state(String key) { + try { + return BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK, key, false).blockState(); + } catch (CommandSyntaxException invalid) { + throw new IllegalArgumentException("Block state " + key + " is not one of the platform's: " + + invalid.getMessage(), invalid); + } + } + + @Override + public boolean is(BlockState state, NativeFitTrait trait) { + return switch (trait) { + case AIR -> state.isAir(); + case SOLID -> state.isSolid(); + case FLUID -> !state.getFluidState().isEmpty(); + case LOG -> isLog(state); + case LEAVES -> isLeaves(state); + }; + } + + @Override + public boolean inTag(BlockState state, String tag) { + return state.is(TAGS.computeIfAbsent(tag, id -> TagKey.create(Registries.BLOCK, Identifier.parse(id)))); + } + + @Override + public boolean sturdy(int x, int y, int z, String face) { + BlockState state = world.getBlockState(position.set(x, y, z)); + return state.isFaceSturdy(world, position, Direction.valueOf(face), SupportType.FULL); + } + + @Override + public BlockState fluid(BlockState state) { + return state.getFluidState().createLegacyBlock(); + } + } + + private static final class MinecraftStart implements NativeFitStart { + private final FitTarget target; + private final List> pieces; + + private MinecraftStart(WorldGenLevel world, FitTarget target, Supplier templates) { + this.target = target; + StructureStart start = target.start(); + BlockPos referencePosition = referencePosition(start); + List> converted = new ArrayList<>(start.getPieces().size()); + for (StructurePiece piece : start.getPieces()) { + converted.add(new MinecraftPiece(world, piece, referencePosition, templates)); + } + this.pieces = List.copyOf(converted); + } + + /** Where template processors measure from: the first piece's center, at its lowest block. */ + private static BlockPos referencePosition(StructureStart start) { + BoundingBox bounds = start.getPieces().getFirst().getBoundingBox(); + BlockPos center = bounds.getCenter(); + return new BlockPos(center.getX(), bounds.minY(), center.getZ()); + } + + @Override + public String structureKey() { + return target.structureId(); + } + + @Override + public int chunkX() { + return target.start().getChunkPos().x(); + } + + @Override + public int chunkZ() { + return target.start().getChunkPos().z(); + } + + @Override + public String step() { + return target.start().getStructure().step().name(); + } + + @Override + public String adaptation() { + return target.start().getStructure().terrainAdaptation().name(); + } + + @Override + public NativeStartMemo memo() { + return target.memo(); + } + + @Override + public List> pieces() { + return pieces; + } + + @Override + public Object key() { + return target.start(); + } + } + + private static final class MinecraftPiece implements NativeFitPiece { + private final WorldGenLevel world; + private final StructurePiece piece; + private final BlockPos referencePosition; + private final Supplier templates; + + private MinecraftPiece(WorldGenLevel world, StructurePiece piece, BlockPos referencePosition, + Supplier templates) { + this.world = world; + this.piece = piece; + this.referencePosition = referencePosition; + this.templates = templates; + } + + @Override + public NativeFitBox box() { + return NativeStructureFitBridge.box(piece.getBoundingBox()); + } + + @Override + public String kind() { + if (!(piece instanceof PoolElementStructurePiece poolPiece)) { + return "FIXED"; + } + return poolPiece.getElement().getProjection() == StructureTemplatePool.Projection.RIGID + ? "RIGID" : "TERRAIN_MATCHING"; + } + + @Override + public int groundLevelDelta() { + return piece instanceof PoolElementStructurePiece poolPiece ? poolPiece.getGroundLevelDelta() : 0; + } + + @Override + public List junctions() { + if (!(piece instanceof PoolElementStructurePiece poolPiece)) { + return List.of(); + } + List junctions = new ArrayList<>(poolPiece.getJunctions().size()); + for (JigsawJunction junction : poolPiece.getJunctions()) { + junctions.add(new int[]{junction.getSourceX(), junction.getSourceGroundY(), junction.getSourceZ()}); + } + return junctions; + } + + @Override + public NativeTemplateCells cells(NativeFitBox region) { + if (!(piece instanceof PoolElementStructurePiece poolPiece)) { + return new NativeTemplateCells<>(false, new int[0], new int[0], new int[0], new BlockState[0], 0); + } + BoundingBox processingArea = boundingBox(region); + return NativeStructureTemplateOccupancy.cells(world, poolPiece, referencePosition, processingArea, templates); + } + + @Override + public void columns(ColumnVisitor visitor) { + BoundingBox bounds = piece.getBoundingBox(); + if (piece instanceof PoolElementStructurePiece poolPiece + && emitTemplateColumns(pieceTemplates(poolPiece), poolPiece.getPosition(), poolPiece.getRotation(), + bounds, visitor)) { + return; + } + for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { + for (int x = bounds.minX(); x <= bounds.maxX(); x++) { + visitor.column(x, z, bounds.minY(), bounds.maxY()); + } + } + } + + @Override + public List legacyAir(NativeFitBox clip) { + if (!(piece instanceof PoolElementStructurePiece poolPiece)) { + return List.of(); + } + StructurePlaceSettings settings = new StructurePlaceSettings() + .setRotation(poolPiece.getRotation()) + .setBoundingBox(boundingBox(clip)); + List air = new ArrayList<>(); + collectLegacyAir(poolPiece.getElement(), poolPiece.getPosition(), settings, air); + return air; + } + + private void collectLegacyAir(StructurePoolElement element, BlockPos position, StructurePlaceSettings settings, + List air) { + if (element instanceof ListPoolElement listElement) { + for (StructurePoolElement child : listElement.getElements()) { + collectLegacyAir(child, position, settings, air); + } + return; + } + if (!(element instanceof LegacySinglePoolElement legacyElement)) { + return; + } + StructureTemplate template = NativeStructureReflection.resolveTemplate(legacyElement, templates); + for (StructureTemplate.StructureBlockInfo block : template.filterBlocks(position, settings, Blocks.AIR)) { + BlockPos at = block.pos(); + air.add(new int[]{at.getX(), at.getY(), at.getZ()}); + } + } + + private List pieceTemplates(PoolElementStructurePiece poolPiece) { + List resolved = new ArrayList<>(1); + collectElementTemplates(poolPiece.getElement(), resolved); + return resolved; + } + + private void collectElementTemplates(StructurePoolElement element, List resolved) { + if (element instanceof ListPoolElement listElement) { + for (StructurePoolElement child : listElement.getElements()) { + collectElementTemplates(child, resolved); + } + return; + } + if (element instanceof SinglePoolElement singleElement) { + resolved.add(NativeStructureReflection.resolveTemplate(singleElement, templates)); + } + } + + /** + * Per-column vertical extents from the complement of the templates' air and structure-void cells, so a carve + * tracks the actual silhouette instead of the piece's rectangular box. False when there is no template or it + * is too large to read, and the box stands in. + */ + private static boolean emitTemplateColumns(List templates, BlockPos position, + Rotation rotation, BoundingBox bounds, + ColumnVisitor visitor) { + if (templates.isEmpty()) { + return false; + } + int width = bounds.getXSpan(); + int depth = bounds.getZSpan(); + long cells = (long) width * depth * bounds.getYSpan(); + if (cells < 1L || cells > MAX_TEMPLATE_COLUMN_CELLS) { + return false; + } + StructurePlaceSettings settings = new StructurePlaceSettings().setRotation(rotation); + boolean[] voidCells = null; + for (StructureTemplate template : templates) { + boolean[] templateVoid = new boolean[(int) cells]; + for (Block ignored : TEMPLATE_VOID_BLOCKS) { + for (StructureTemplate.StructureBlockInfo info : template.filterBlocks(position, settings, ignored)) { + BlockPos voidPosition = info.pos(); + if (bounds.isInside(voidPosition)) { + templateVoid[cellIndex(bounds, width, depth, + voidPosition.getX(), voidPosition.getY(), voidPosition.getZ())] = true; + } + } + } + if (voidCells == null) { + voidCells = templateVoid; + continue; + } + for (int cell = 0; cell < voidCells.length; cell++) { + voidCells[cell] &= templateVoid[cell]; + } + } + for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { + for (int x = bounds.minX(); x <= bounds.maxX(); x++) { + int minY = Integer.MAX_VALUE; + int maxY = Integer.MIN_VALUE; + for (int y = bounds.minY(); y <= bounds.maxY(); y++) { + if (voidCells[cellIndex(bounds, width, depth, x, y, z)]) { + continue; + } + if (minY == Integer.MAX_VALUE) { + minY = y; + } + maxY = y; + } + if (minY != Integer.MAX_VALUE) { + visitor.column(x, z, minY, maxY); + } + } + } + return true; + } + + private static int cellIndex(BoundingBox bounds, int width, int depth, int x, int y, int z) { + return ((y - bounds.minY()) * depth + z - bounds.minZ()) * width + x - bounds.minX(); + } + } +} diff --git a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureFoundationBuilder.java b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureFoundationBuilder.java deleted file mode 100644 index 1af0723e1..000000000 --- a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureFoundationBuilder.java +++ /dev/null @@ -1,212 +0,0 @@ -package art.arcane.iris.nativegen; - -import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; -import art.arcane.volmlib.util.math.RNG; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.tags.BlockTags; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.SupportType; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.structure.BoundingBox; -import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece; -import net.minecraft.world.level.levelgen.structure.StructurePiece; -import net.minecraft.world.level.levelgen.structure.StructureStart; - -import java.util.ArrayList; -import java.util.BitSet; -import java.util.List; -import java.util.Objects; -import java.util.function.IntBinaryOperator; - -public final class NativeStructureFoundationBuilder { - private static final int FOUNDATION_VERTICAL_TOLERANCE = 1; - - private NativeStructureFoundationBuilder() { - } - - private static List foundationEnvelope(BoundingBox area, StructureStart start) { - BoundingBox structure = NativeStructureReferenceEnvelope.contentBounds(start); - int minX = Math.max(area.minX(), structure.minX()); - int minZ = Math.max(area.minZ(), structure.minZ()); - int maxX = Math.min(area.maxX(), structure.maxX()); - int maxZ = Math.min(area.maxZ(), structure.maxZ()); - if (minX > maxX || minZ > maxZ) { - return List.of(); - } - List pieces = start.getPieces(); - List columns = new ArrayList<>((maxX - minX + 1) * (maxZ - minZ + 1)); - BitSet envelope = new BitSet(area.getYSpan()); - for (int z = minZ; z <= maxZ; z++) { - for (int x = minX; x <= maxX; x++) { - envelope.clear(); - markFoundationEnvelope(envelope, pieces, area, x, z); - int cellCount = envelope.cardinality(); - if (cellCount == 0) { - continue; - } - int[] ys = new int[cellCount]; - int cell = 0; - for (int bit = envelope.nextSetBit(0); bit >= 0; bit = envelope.nextSetBit(bit + 1)) { - ys[cell++] = area.minY() + bit; - } - columns.add(new FoundationColumn(x, z, ys)); - } - } - return List.copyOf(columns); - } - - private static void markFoundationEnvelope(BitSet envelope, List pieces, BoundingBox area, - int x, int z) { - for (StructurePiece piece : pieces) { - BoundingBox bounds = piece.getBoundingBox(); - if (x < bounds.minX() || x > bounds.maxX() || z < bounds.minZ() || z > bounds.maxZ()) { - continue; - } - int groundY = bounds.minY(); - if (piece instanceof PoolElementStructurePiece poolPiece) { - groundY += poolPiece.getGroundLevelDelta(); - if (groundY < bounds.minY()) { - continue; - } - } - int minY = Math.max(area.minY(), bounds.minY()); - int maxY = Math.min(area.maxY(), Math.min(bounds.maxY(), groundY + FOUNDATION_VERTICAL_TOLERANCE)); - if (minY <= maxY) { - envelope.set(minY - area.minY(), maxY - area.minY() + 1); - } - } - } - - static void placeStilts(WorldGenLevel world, BoundingBox area, String structureId, - StructureStart start, IrisStructureStiltSettings settings, - NativeStructurePostProcessor.PaletteBlockResolver paletteBlockResolver, - IntBinaryOperator surfaceHeight, - boolean surfaceStructure) { - Objects.requireNonNull(surfaceHeight, "Structure stilts require an Iris terrain height resolver"); - BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); - int structureHash = structureId == null ? 0 : structureId.hashCode(); - RNG rng = new RNG(world.getSeed() ^ structureHash); - for (FoundationColumn column : foundationEnvelope(area, start)) { - if (!isStiltColumn(column.x(), column.z(), settings.getSpacing())) { - continue; - } - int foundationY = findFoundationY(world, column, position); - if (foundationY == Integer.MIN_VALUE) { - continue; - } - int terrainY = surfaceStructure - ? Math.max(area.minY(), Math.min( - area.maxY(), surfaceHeight.applyAsInt(column.x(), column.z()))) - : area.minY() - 1; - int anchorY = findStiltAnchorY( - world, column.x(), column.z(), foundationY, - Math.max(1, settings.getMaxDepth()), terrainY, area.minY(), position); - if (anchorY == Integer.MIN_VALUE) { - continue; - } - for (int y = foundationY - 1; y > anchorY; y--) { - position.set(column.x(), y, column.z()); - BlockState stilt = settings.getPalette() == null - ? Blocks.COBBLESTONE.defaultBlockState() - : Objects.requireNonNull( - paletteBlockResolver.resolve( - settings.getPalette(), rng, column.x(), y, column.z()), - "Stilt palette returned no block for " + structureId + " at " - + column.x() + "," + y + "," + column.z()); - world.setBlock(position, stilt, 2); - } - } - } - - static boolean isStiltColumn(int x, int z, int spacing) { - int resolvedSpacing = Math.max(1, spacing); - return resolvedSpacing == 1 - || Math.floorMod(x, resolvedSpacing) == 0 - && Math.floorMod(z, resolvedSpacing) == 0; - } - - static int findStiltAnchorY( - WorldGenLevel world, int x, int z, int foundationY, int maxDepth, - int terrainY, int areaMinY, BlockPos.MutableBlockPos position) { - int minimumAnchorY = Math.max( - areaMinY, Math.max(terrainY, foundationY - maxDepth - 1)); - for (int y = foundationY - 1; y >= minimumAnchorY; y--) { - BlockState state = world.getBlockState(position.set(x, y, z)); - boolean vegetation = state.is(BlockTags.LOGS) || state.is(BlockTags.LEAVES); - if (!vegetation && state.isFaceSturdy( - world, position, Direction.UP, SupportType.FULL)) { - return y; - } - } - return Integer.MIN_VALUE; - } - - public static StiltSupportAudit auditStiltSupport(WorldGenLevel world, BoundingBox area, - StructureStart start, BlockState expectedStilt, - IntBinaryOperator surfaceHeight) { - Objects.requireNonNull(expectedStilt, "Expected stilt state must not be null"); - Objects.requireNonNull(surfaceHeight, "Structure stilt audit requires an Iris terrain height resolver"); - BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); - int baseColumns = 0; - int stiltBlocks = 0; - int stiltColumns = 0; - int unsupportedColumns = 0; - for (FoundationColumn column : foundationEnvelope(area, start)) { - int foundationY = findFoundationY(world, column, position); - if (foundationY == Integer.MIN_VALUE) { - continue; - } - baseColumns++; - int terrainY = Math.max(area.minY(), Math.min( - area.maxY(), surfaceHeight.applyAsInt(column.x(), column.z()))); - boolean grounded = foundationY <= terrainY + 1; - boolean stiltColumn = false; - for (int y = foundationY - 1; y >= area.minY(); y--) { - if (y <= terrainY) { - grounded = true; - break; - } - BlockState state = world.getBlockState(position.set(column.x(), y, column.z())); - if (state.is(expectedStilt.getBlock())) { - stiltBlocks++; - stiltColumn = true; - if (y == area.minY()) { - grounded = true; - } - continue; - } - boolean vegetation = state.is(BlockTags.LOGS) || state.is(BlockTags.LEAVES); - grounded = state.isSolid() && !vegetation; - break; - } - if (stiltColumn) { - stiltColumns++; - } - if (!grounded) { - unsupportedColumns++; - } - } - return new StiltSupportAudit(baseColumns, stiltBlocks, stiltColumns, unsupportedColumns); - } - - private static int findFoundationY(WorldGenLevel world, FoundationColumn column, - BlockPos.MutableBlockPos position) { - for (int cell = 0; cell < column.ys().length; cell++) { - int y = column.ys()[cell]; - BlockState state = world.getBlockState(position.set(column.x(), y, column.z())); - if (state.isSolid()) { - return y; - } - } - return Integer.MIN_VALUE; - } - - private record FoundationColumn(int x, int z, int[] ys) { - } - - public record StiltSupportAudit(int baseColumns, int stiltBlocks, int stiltColumns, - int unsupportedColumns) { - } -} diff --git a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureOwnershipFingerprint.java b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureOwnershipFingerprint.java index 4834bc394..f11ff6d4e 100644 --- a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureOwnershipFingerprint.java +++ b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureOwnershipFingerprint.java @@ -72,7 +72,7 @@ public final class NativeStructureOwnershipFingerprint { references.minZ() >> 4, references.maxZ() >> 4, fingerprint(structureKey, resolvedStart), - resolvedPlan.decision() + resolvedPlan.memo() ); } diff --git a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureOwnershipRecovery.java b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureOwnershipRecovery.java index 100645a02..944f95e3b 100644 --- a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureOwnershipRecovery.java +++ b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureOwnershipRecovery.java @@ -1,14 +1,15 @@ package art.arcane.iris.nativegen; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.NativeStartMemo; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; +import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; +import art.arcane.iris.engine.framework.NativeStructureLayouts; +import art.arcane.iris.engine.framework.NativeStructureReach; import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord; import art.arcane.iris.engine.framework.NativeStructureOwnershipStore; import art.arcane.iris.engine.framework.NativeStructureStarts; import art.arcane.iris.engine.framework.NativeStructureStartPlan; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.core.registries.Registries; @@ -22,6 +23,7 @@ import net.minecraft.world.level.levelgen.structure.Structure; import net.minecraft.world.level.levelgen.structure.StructureStart; import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement; +import java.util.List; import java.util.Locale; import java.util.Objects; @@ -45,7 +47,8 @@ public final class NativeStructureOwnershipRecovery { engine, structureKey, origin.x(), origin.z()); if (persisted != null) { NativeStructureOwnershipRecord refreshed = refreshReferenceEnvelope( - structureKey, activeStructure, start, persisted); + structureKey, activeStructure, start, persisted, reachesOf(engine, structureKey, activeStructure, + persisted.restoredMemo())); if (refreshed != null) { if (refreshed != persisted) { NativeStructureOwnershipStore.record(engine, refreshed); @@ -67,9 +70,11 @@ public final class NativeStructureOwnershipRecovery { return null; } StructureStart expected = generateExpected( - engine, activeLevel, holder, plan, start.getReferences()); + engine, activeLevel, holder, plan, start.getReferences(), + reachesOf(engine, structureKey, activeStructure, plan.memo())); NativeStructureOwnershipRecord recovered = proveCandidate( - structureKey, activeStructure, start, plan, expected, false); + structureKey, activeStructure, start, plan, expected, false, + reachesOf(engine, structureKey, activeStructure, plan.memo())); if (recovered == null) { return null; } @@ -77,26 +82,26 @@ public final class NativeStructureOwnershipRecovery { return recovered; } + /** + * The record with its reference envelope grown to what today's reaches give its start: a module may reach further + * around its starts than when it recorded one (VACUUM's fixed falloff did), and the start must then be referenced + * from the farther chunks too. An envelope never shrinks, so no chunk that once referenced the start loses it. + */ static NativeStructureOwnershipRecord refreshReferenceEnvelope( String structureKey, Structure structure, StructureStart start, - NativeStructureOwnershipRecord ownership) { + NativeStructureOwnershipRecord ownership, List reaches) { if (structure == null || start == null || !start.isValid() || start.getStructure() != structure || ownership == null || !ownership.structureKey().equals(normalize(structureKey)) || !NativeStructureOwnershipFingerprint.matches(ownership, start)) { return null; } - IrisStructureTerrain terrain = NativeStructureTerrainIntegrator.resolveNativeTerrain( - start, ownership.restoredDecision().terrain()); - if (terrain.resolvedMode() != IrisStructureTerrainMode.VACUUM) { - return ownership; - } BoundingBox expected = NativeStructureReferenceEnvelope.referenceBounds( - start, structure, terrain, structureKey); - int referenceMinChunkX = expected.minX() >> 4; - int referenceMaxChunkX = expected.maxX() >> 4; - int referenceMinChunkZ = expected.minZ() >> 4; - int referenceMaxChunkZ = expected.maxZ() >> 4; + start, structure, reaches, structureKey); + int referenceMinChunkX = Math.min(ownership.referenceMinChunkX(), expected.minX() >> 4); + int referenceMaxChunkX = Math.max(ownership.referenceMaxChunkX(), expected.maxX() >> 4); + int referenceMinChunkZ = Math.min(ownership.referenceMinChunkZ(), expected.minZ() >> 4); + int referenceMaxChunkZ = Math.max(ownership.referenceMaxChunkZ(), expected.maxZ() >> 4); if (ownership.referenceMinChunkX() == referenceMinChunkX && ownership.referenceMaxChunkX() == referenceMaxChunkX && ownership.referenceMinChunkZ() == referenceMinChunkZ @@ -111,7 +116,7 @@ public final class NativeStructureOwnershipRecovery { static NativeStructureOwnershipRecord proveCandidate( String structureKey, Structure structure, StructureStart persisted, NativeStructureStartPlan plan, StructureStart expected, - boolean naturalStartAmbiguous) { + boolean naturalStartAmbiguous, List reaches) { if (naturalStartAmbiguous || structure == null || persisted == null || !persisted.isValid() || expected == null || !expected.isValid() @@ -122,7 +127,7 @@ public final class NativeStructureOwnershipRecovery { return null; } BoundingBox referenceEnvelope = NativeStructureReferenceEnvelope.referenceBounds( - expected, structure, plan.terrain(), structureKey); + expected, structure, reaches, structureKey); NativeStructureOwnershipRecord candidate = NativeStructureOwnershipFingerprint.capture( structureKey, expected, plan, referenceEnvelope); return NativeStructureOwnershipFingerprint.matches(candidate, persisted) @@ -141,7 +146,7 @@ public final class NativeStructureOwnershipRecovery { private static StructureStart generateExpected( Engine engine, ServerLevel level, Holder holder, - NativeStructureStartPlan plan, int references) { + NativeStructureStartPlan plan, int references, List reaches) { ChunkGeneratorStructureState state = level.getChunkSource().getGeneratorState(); ChunkGenerator generator = level.getChunkSource().getGenerator(); BiomeSource biomeSource = generator.getBiomeSource(); @@ -159,7 +164,7 @@ public final class NativeStructureOwnershipRecovery { generator.getSeaLevel(), (x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight() ); - return NativeStructureFactory.generate(generationContext, holder, plan, references); + return NativeStructureFactory.generate(generationContext, holder, plan, references, reaches); } private static boolean naturalStartIsAmbiguous( @@ -169,10 +174,8 @@ public final class NativeStructureOwnershipRecovery { if (plan.replacesPlatformStart()) { return false; } - NativeStructureGenerationStatus sourceStatus = NativeStructureGenerationPolicy.resolve( - engine, structureKey, - NativeStructureVegetationClearer.isUndergroundStep(structure.step())).status(); - if (sourceStatus == NativeStructureGenerationStatus.REPLACED_BY_IRIS) { + if (NativeStructureGenerationPolicy.resolve(engine, structureKey) + == NativeStructureGenerationStatus.REPLACED_BY_IRIS) { return false; } for (StructurePlacement placement : state.getPlacementsForStructure(holder)) { @@ -183,6 +186,12 @@ public final class NativeStructureOwnershipRecovery { return false; } + private static List reachesOf(Engine engine, String structureKey, Structure structure, + NativeStartMemo memo) { + return NativeStructureLayouts.reaches(engine, structureKey, + NativeStructureVegetationClearer.isUndergroundStep(structure.step()), memo); + } + private static String normalize(String structureKey) { return structureKey == null ? "" : structureKey.trim().toLowerCase(Locale.ROOT); } diff --git a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructurePostProcessor.java b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructurePostProcessor.java deleted file mode 100644 index 943b1f78f..000000000 --- a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructurePostProcessor.java +++ /dev/null @@ -1,66 +0,0 @@ -package art.arcane.iris.nativegen; - -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; -import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; -import art.arcane.volmlib.util.math.RNG; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.StructureManager; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.levelgen.WorldgenRandom; -import net.minecraft.world.level.levelgen.structure.BoundingBox; -import net.minecraft.world.level.levelgen.structure.StructureStart; - -import java.util.List; -import java.util.function.IntBinaryOperator; - -public final class NativeStructurePostProcessor { - private NativeStructurePostProcessor() { - } - - public static void place(WorldGenLevel world, StructureManager structureManager, ChunkGenerator generator, - WorldgenRandom random, BoundingBox area, ChunkPos chunkPos, String structureId, - StructureStart start, IrisNativeStructureDecision decision, - PaletteBlockResolver paletteBlockResolver, - IntBinaryOperator surfaceHeight) { - IrisStructureStiltSettings stilt = decision.stilt(); - NativeStructureVerticalPlacer.ensureMonumentSeaLevelAlignment(start, structureId, decision.yShift(), - generator.getSeaLevel(), area.minY(), area.maxY() + 1); - start.placeInChunk(world, structureManager, generator, random, area, chunkPos); - if (stilt != null) { - NativeStructureFoundationBuilder.placeStilts(world, area, structureId, start, stilt, - paletteBlockResolver, surfaceHeight, - !NativeStructureVegetationClearer.isUndergroundStep(start.getStructure().step())); - } - } - - public static void prepareTerrain(WorldGenLevel world, BoundingBox area, - List targets, - PaletteBlockResolver paletteBlockResolver) { - if (targets == null || targets.isEmpty()) { - return; - } - NativeStructureTerrainIntegrator.SourceTerrainSnapshot sourceTerrain = - NativeStructureTerrainIntegrator.captureSourceTerrain(world, area, targets); - for (NativeStructureTerrainIntegrator.TerrainTarget target : targets) { - NativeStructureTerrainIntegrator.integrateTerrain(world, area, target.structureId(), target.start(), - target.terrain(), paletteBlockResolver, sourceTerrain); - } - for (NativeStructureTerrainIntegrator.TerrainTarget target : targets) { - if (NativeStructureTerrainIntegrator.clearsLegacyTemplateAir( - target.start(), target.terrain())) { - NativeStructureTerrainIntegrator.clearLegacyTemplateAir( - world, area, target.start(), () -> world.getLevel().getStructureManager()); - } - } - NativeStructureSurfaceSupportBuilder.bridgeRigidPieceSupport( - world, area, targets, () -> world.getLevel().getStructureManager()); - } - - @FunctionalInterface - public interface PaletteBlockResolver { - BlockState resolve(IrisMaterialPalette palette, RNG rng, int x, int y, int z); - } -} diff --git a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureReferenceEnvelope.java b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureReferenceEnvelope.java index 03b669779..eaaba9d27 100644 --- a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureReferenceEnvelope.java +++ b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureReferenceEnvelope.java @@ -1,7 +1,6 @@ package art.arcane.iris.nativegen; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; +import art.arcane.iris.engine.framework.NativeStructureReach; import art.arcane.iris.spi.IrisLogging; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.levelgen.structure.BoundingBox; @@ -24,13 +23,13 @@ public final class NativeStructureReferenceEnvelope { } public static StructureStart wrap(StructureStart generated, Structure source, int references, - IrisStructureTerrain terrain) { - return wrap(generated, source, references, terrain, null); + List reaches) { + return wrap(generated, source, references, reaches, null); } public static StructureStart wrap(StructureStart generated, Structure source, int references, - IrisStructureTerrain terrain, String structureKey) { - referenceBounds(generated, source, terrain, structureKey); + List reaches, String structureKey) { + referenceBounds(generated, source, reaches, structureKey); return new StructureStart( source, generated.getChunkPos(), @@ -41,9 +40,9 @@ public final class NativeStructureReferenceEnvelope { public static StructureStart wrapForPublication( StructureStart generated, Structure source, int references, - IrisStructureTerrain terrain, String structureKey) { + List reaches, String structureKey) { try { - return wrap(generated, source, references, terrain, structureKey); + return wrap(generated, source, references, reaches, structureKey); } catch (UnrepresentableContentException exception) { warnSkippedContent(generated, source, structureKey); return StructureStart.INVALID_START; @@ -51,22 +50,17 @@ public final class NativeStructureReferenceEnvelope { } public static BoundingBox referenceBounds(StructureStart start, Structure source, - IrisStructureTerrain terrain) { - return referenceBounds(start, source, terrain, null); + List reaches) { + return referenceBounds(start, source, reaches, null); } + /** + * The blocks a start's references must cover: its pieces and, around them, every module's reach (the area the + * structure's own terrain adaptation covers for a platform reach), clipped to Minecraft's reference range. + */ public static BoundingBox referenceBounds(StructureStart start, Structure source, - IrisStructureTerrain terrain, + List reaches, String structureKey) { - IrisStructureTerrainMode mode = terrain == null - ? IrisStructureTerrainMode.PRESERVE : terrain.resolvedMode(); - boolean usesEnvelope = mode == IrisStructureTerrainMode.BORE - || mode == IrisStructureTerrainMode.FORCE_CARVE - || mode == IrisStructureTerrainMode.VACUUM - || mode == IrisStructureTerrainMode.ENCASE; - int horizontalPadding = mode == IrisStructureTerrainMode.VACUUM - ? NativeStructureSurfaceFitter.surfaceTerrainRadius() - : usesEnvelope ? Math.max(0, terrain.getHorizontalPadding()) : 0; BoundingBox content = contentBounds(start); if (!fitsReferenceRange(start.getChunkPos(), content)) { throw new UnrepresentableContentException("Native structure content at " @@ -74,22 +68,12 @@ public final class NativeStructureReferenceEnvelope { + " exceeds Minecraft's " + MAX_REFERENCE_DISTANCE_CHUNKS + "-chunk structure reference range"); } - BoundingBox adjustedEnvelope; + BoundingBox adjustedEnvelope = content; boolean arithmeticClipped = false; try { - BoundingBox envelope = horizontalPadding == 0 - ? content - : new BoundingBox( - Math.subtractExact(content.minX(), horizontalPadding), - content.minY(), - Math.subtractExact(content.minZ(), horizontalPadding), - Math.addExact(content.maxX(), horizontalPadding), - content.maxY(), - Math.addExact(content.maxZ(), horizontalPadding) - ); - adjustedEnvelope = mode == IrisStructureTerrainMode.SOURCE - ? source.adjustBoundingBox(content) : envelope; - adjustedEnvelope = encapsulating(adjustedEnvelope, content); + for (NativeStructureReach reach : reaches) { + adjustedEnvelope = encapsulating(adjustedEnvelope, reachEnvelope(source, content, reach)); + } } catch (ArithmeticException exception) { adjustedEnvelope = maximumReferenceBounds(start.getChunkPos(), content); arithmeticClipped = true; @@ -102,6 +86,23 @@ public final class NativeStructureReferenceEnvelope { return adjustedEnvelope; } + private static BoundingBox reachEnvelope(Structure source, BoundingBox content, NativeStructureReach reach) { + if (reach.platform()) { + return source.adjustBoundingBox(content); + } + int padding = reach.blocks(); + if (padding == 0) { + return content; + } + return new BoundingBox( + Math.subtractExact(content.minX(), padding), + content.minY(), + Math.subtractExact(content.minZ(), padding), + Math.addExact(content.maxX(), padding), + content.maxY(), + Math.addExact(content.maxZ(), padding)); + } + public static boolean contentFitsReferenceRange(StructureStart start) { try { return fitsReferenceRange(start.getChunkPos(), contentBounds(start)); diff --git a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureReferenceRepair.java b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureReferenceRepair.java index c8565aae2..9726daedf 100644 --- a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureReferenceRepair.java +++ b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureReferenceRepair.java @@ -2,9 +2,10 @@ package art.arcane.iris.nativegen; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; +import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; +import art.arcane.iris.engine.framework.NativeStructureLayouts; import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord; import art.arcane.iris.engine.framework.NativeStructureOwnershipStore; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; import art.arcane.iris.spi.IrisLogging; import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import it.unimi.dsi.fastutil.longs.LongSet; @@ -132,15 +133,12 @@ public final class NativeStructureReferenceRepair { private static boolean naturalPolicyAllows( Engine engine, String structureKey, Structure structure) { - IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve( - engine, structureKey, - NativeStructureVegetationClearer.isUndergroundStep(structure.step())); - return naturalDecisionAllows(decision); + return naturalStatusAllows(NativeStructureGenerationPolicy.resolve(engine, structureKey)); } - static boolean naturalDecisionAllows(IrisNativeStructureDecision decision) { - return Objects.requireNonNull( - decision, "Native structure decision must not be null").generate(); + static boolean naturalStatusAllows(NativeStructureGenerationStatus status) { + return Objects.requireNonNull(status, "Native structure status must not be null") + == NativeStructureGenerationStatus.GENERATE_NATIVE; } private static void invalidateStart( @@ -181,15 +179,13 @@ public final class NativeStructureReferenceRepair { if (target == null || start == null || !start.isValid()) { return false; } - IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve( - engine, structureKey, - NativeStructureVegetationClearer.isUndergroundStep(structure.step())); - if (!decision.generate()) { + if (!NativeStructureGenerationPolicy.generates(engine, structureKey)) { return false; } BoundingBox referenceBounds = NativeStructureReferenceEnvelope.referenceBounds( start, structure, - NativeStructureTerrainIntegrator.resolveNativeTerrain(start, decision.terrain()), + NativeStructureLayouts.reaches(engine, structureKey, + NativeStructureVegetationClearer.isUndergroundStep(structure.step()), null), structureKey); return referenceBounds.intersects( target.getMinBlockX(), target.getMinBlockZ(), diff --git a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureStartInjector.java b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureStartInjector.java index dc1dd3f5d..da8bd1de7 100644 --- a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureStartInjector.java +++ b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureStartInjector.java @@ -2,11 +2,13 @@ package art.arcane.iris.nativegen; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; +import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; +import art.arcane.iris.engine.framework.NativeStructureLayouts; import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord; import art.arcane.iris.engine.framework.NativeStructureOwnershipStore; +import art.arcane.iris.engine.framework.NativeStructureReach; import art.arcane.iris.engine.framework.NativeStructureStarts; import art.arcane.iris.engine.framework.NativeStructureStartPlan; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; import art.arcane.iris.spi.IrisLogging; import net.minecraft.core.Holder; import net.minecraft.core.Registry; @@ -27,6 +29,7 @@ import net.minecraft.world.level.levelgen.structure.StructureStart; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -67,10 +70,8 @@ public final class NativeStructureStartInjector { section, structure, chunk); boolean replacement = plan.replacesPlatformStart(); if (!replacement && existing != null && existing.isValid()) { - NativeStructureGenerationStatus sourceStatus = NativeStructureGenerationPolicy.resolve( - context.engine(), identifier.toString(), - NativeStructureVegetationClearer.isUndergroundStep(structure.step())).status(); - replacement = sourceStatus == NativeStructureGenerationStatus.REPLACED_BY_IRIS; + replacement = NativeStructureGenerationPolicy.resolve(context.engine(), identifier.toString()) + == NativeStructureGenerationStatus.REPLACED_BY_IRIS; } if (!replacement && existing != null && existing.isValid()) { continue; @@ -91,8 +92,10 @@ public final class NativeStructureStartInjector { (x, z) -> context.engine().getHeight(x, z, true) + context.engine().getMinHeight() ); + List reaches = NativeStructureLayouts.reaches(context.engine(), identifier.toString(), + NativeStructureVegetationClearer.isUndergroundStep(structure.step()), plan.memo()); StructureStart generated = NativeStructureFactory.generate( - generationContext, holder, plan, references); + generationContext, holder, plan, references, reaches); if (!isUsableGeneratedStart(generated)) { if (replacement) { context.structureManager().setStartForStructure( @@ -104,7 +107,7 @@ public final class NativeStructureStartInjector { continue; } BoundingBox referenceBounds = NativeStructureReferenceEnvelope.referenceBounds( - generated, structure, plan.terrain(), identifier.toString()); + generated, structure, reaches, identifier.toString()); NativeStructureOwnershipRecord ownership = NativeStructureOwnershipFingerprint.capture( identifier.toString(), generated, plan, referenceBounds); NativeStructureOwnershipStore.record(context.engine(), ownership); diff --git a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureSurfaceFitter.java b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureSurfaceFitter.java deleted file mode 100644 index 0b343facd..000000000 --- a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureSurfaceFitter.java +++ /dev/null @@ -1,921 +0,0 @@ -package art.arcane.iris.nativegen; - -import art.arcane.iris.engine.object.placement.IrisObjectVacuum; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; -import art.arcane.iris.spi.IrisLogging; -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.Blocks; -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.StructurePiece; -import net.minecraft.world.level.levelgen.structure.StructureStart; -import net.minecraft.world.level.levelgen.structure.TerrainAdjustment; -import net.minecraft.world.level.levelgen.structure.pools.JigsawJunction; -import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.IntBinaryOperator; - -public final class NativeStructureSurfaceFitter { - private static final double SURFACE_TERRAIN_FALLOFF = 2.0; - private static final long SURFACE_TERRAIN_INFLUENCE_SCALE = 1_000_000L; - private static final int SURFACE_TERRAIN_RADIUS = 12; - private static final int MAX_SOURCE_SURFACE_DELTA = 6; - private static final int MAX_SURFACE_TEMPLATE_CELLS = 4_194_304; - private static final Set WARNED_SOURCE_BUDGET = - ConcurrentHashMap.newKeySet(); - private static final Set WARNED_VACUUM_BUDGET = - ConcurrentHashMap.newKeySet(); - - private NativeStructureSurfaceFitter() { - } - - public static VacuumFoundationPlan prepareSurfaceStructures( - WorldGenLevel world, BoundingBox area, - List targets, - IntBinaryOperator surfaceHeight) { - return prepareSurfaceStructures( - world, area, targets, surfaceHeight, MAX_SURFACE_TEMPLATE_CELLS); - } - - static VacuumFoundationPlan prepareSurfaceStructures( - WorldGenLevel world, BoundingBox area, - List targets, - IntBinaryOperator surfaceHeight, int maximumTemplateCells) { - if (targets == null || targets.isEmpty()) { - return VacuumFoundationPlan.empty(); - } - Objects.requireNonNull(surfaceHeight, "Surface structure terrain fitting requires an Iris height resolver"); - List anchors = collectSourceSurfaceAnchors( - world, area, targets, maximumTemplateCells); - if (!anchors.isEmpty()) { - fitSurfaceTerrain(world, area, anchors, surfaceHeight); - } - VacuumFootprint vacuum = collectVacuumFootprint( - world, area, targets, maximumTemplateCells); - if (!vacuum.anchors().isEmpty()) { - fitVacuumTerrain(world, area, vacuum, surfaceHeight); - } - return VacuumFoundationPlan.create( - vacuum.foundationBases(), vacuum.occupiedCells(), area); - } - - public static void repairVacuumFoundations( - WorldGenLevel world, BoundingBox area, - VacuumFoundationPlan plan) { - if (plan == null || plan.foundationBases.isEmpty()) { - return; - } - BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); - for (long packedBase : plan.foundationBases) { - BlockPos base = BlockPos.of(packedBase); - if (!area.isInside(base)) { - continue; - } - BlockState baseState = world.getBlockState(position.set(base)); - if (!NativeStructureTemplateOccupancy.isSolidBase(baseState)) { - continue; - } - int supportY = findVacuumFoundationSupport( - world, area, position, base.getX(), base.getY() - 1, base.getZ()); - if (supportY == Integer.MIN_VALUE || supportY == base.getY() - 1) { - continue; - } - if (intersectsVacuumOccupancy( - plan.occupiedCells, base.getX(), base.getZ(), - supportY + 1, base.getY() - 1)) { - continue; - } - BlockState fill = resolveSurfaceMaterials( - world, position, base.getX(), base.getZ(), supportY, - area.minY()).subsurface(); - for (int y = supportY + 1; y < base.getY(); y++) { - BlockState existing = world.getBlockState( - position.set(base.getX(), y, base.getZ())); - if (existing.isAir() || !existing.getFluidState().isEmpty()) { - world.setBlock(position, fill, 2); - } - } - } - } - - static boolean shouldPrepareSurfaceTerrain(TerrainAdjustment adjustment, - GenerationStep.Decoration step) { - return step == GenerationStep.Decoration.SURFACE_STRUCTURES - && (adjustment == TerrainAdjustment.BEARD_THIN - || adjustment == TerrainAdjustment.BEARD_BOX); - } - - static int surfaceTerrainRadius() { - return SURFACE_TERRAIN_RADIUS; - } - - static int resolveSurfaceTarget(List anchors, int worldX, int worldZ, - int originalY) { - return resolveSurface(anchors, worldX, worldZ, originalY).targetY(); - } - - private static SurfaceResolution resolveSurface(List anchors, - int worldX, int worldZ, int originalY) { - int localTargetY = originalY; - SurfaceAnchor selectedLocal = null; - long totalInfluence = 0L; - long weightedTargetY = 0L; - long maximumInfluence = 0L; - for (SurfaceAnchor anchor : anchors) { - int outX = IrisObjectVacuum.outset(worldX, anchor.minX(), anchor.maxX()); - int outZ = IrisObjectVacuum.outset(worldZ, anchor.minZ(), anchor.maxZ()); - boolean containsColumn = outX == 0 && outZ == 0; - long distanceSquared = (long) outX * outX + (long) outZ * outZ; - long radiusSquared = (long) SURFACE_TERRAIN_RADIUS * SURFACE_TERRAIN_RADIUS; - if (distanceSquared > radiusSquared) { - continue; - } - double distance = Math.sqrt(distanceSquared); - double factor = Math.pow( - 1D - distance / SURFACE_TERRAIN_RADIUS, SURFACE_TERRAIN_FALLOFF); - if (factor <= 0D) { - continue; - } - int boundedTargetY = boundedSurfaceTarget(originalY, anchor.meetY()); - if (containsColumn) { - if (precedes(anchor, selectedLocal)) { - localTargetY = boundedTargetY; - selectedLocal = anchor; - } - continue; - } - long influence = Math.round(factor * SURFACE_TERRAIN_INFLUENCE_SCALE); - if (influence <= 0L) { - continue; - } - long weightedInfluence = influence * Math.max(1, anchor.strength()); - totalInfluence += weightedInfluence; - weightedTargetY += weightedInfluence * boundedTargetY; - maximumInfluence = Math.max(maximumInfluence, influence); - } - if (selectedLocal != null) { - return new SurfaceResolution( - localTargetY, - selectedLocal.strength() > 1 - && localTargetY == selectedLocal.meetY()); - } - if (totalInfluence == 0L) { - return new SurfaceResolution(originalY, false); - } - double blendedTargetY = weightedTargetY / (double) totalInfluence; - double factor = maximumInfluence / (double) SURFACE_TERRAIN_INFLUENCE_SCALE; - return new SurfaceResolution( - blendSurfaceTarget(originalY, blendedTargetY, factor), false); - } - - private static int boundedSurfaceTarget(int originalY, int meetY) { - int delta = Math.max( - -MAX_SOURCE_SURFACE_DELTA, - Math.min(MAX_SOURCE_SURFACE_DELTA, meetY - originalY)); - return originalY + delta; - } - - private static int blendSurfaceTarget(int originalY, double targetY, double factor) { - double delta = (targetY - originalY) * factor; - int magnitude = (int) Math.round(Math.abs(delta)); - return originalY + (delta < 0D ? -magnitude : magnitude); - } - - private static boolean precedes(SurfaceAnchor candidate, SurfaceAnchor selected) { - if (selected == null) { - return true; - } - if (candidate.strength() != selected.strength()) { - return candidate.strength() > selected.strength(); - } - if (candidate.meetY() != selected.meetY()) { - return candidate.meetY() < selected.meetY(); - } - if (candidate.minX() != selected.minX()) { - return candidate.minX() < selected.minX(); - } - if (candidate.minZ() != selected.minZ()) { - return candidate.minZ() < selected.minZ(); - } - if (candidate.maxX() != selected.maxX()) { - return candidate.maxX() < selected.maxX(); - } - if (candidate.maxZ() != selected.maxZ()) { - return candidate.maxZ() < selected.maxZ(); - } - return false; - } - - private static List collectSourceSurfaceAnchors( - WorldGenLevel world, BoundingBox area, - List targets, - int maximumTemplateCells) { - BoundingBox influenceArea = new BoundingBox( - area.minX() - SURFACE_TERRAIN_RADIUS, area.minY(), - area.minZ() - SURFACE_TERRAIN_RADIUS, - area.maxX() + SURFACE_TERRAIN_RADIUS, area.maxY(), - area.maxZ() + SURFACE_TERRAIN_RADIUS); - List anchors = new ArrayList<>(); - Set seenStarts = Collections.newSetFromMap( - new IdentityHashMap<>()); - for (NativeStructureTerrainIntegrator.TerrainTarget target : targets) { - if (!requiresSourceSurfaceTerrain(target)) { - continue; - } - StructureStart start = target.start(); - if (!seenStarts.add(start)) { - continue; - } - BoundingBox firstBounds = start.getPieces().getFirst().getBoundingBox(); - BlockPos firstCenter = firstBounds.getCenter(); - BlockPos referencePosition = new BlockPos( - firstCenter.getX(), firstBounds.minY(), firstCenter.getZ()); - TemplateCellBudget budget = new TemplateCellBudget(maximumTemplateCells); - boolean budgetExceeded = false; - for (StructurePiece piece : start.getPieces()) { - if (piece instanceof PoolElementStructurePiece poolPiece) { - StructureTemplatePool.Projection projection = - poolPiece.getElement().getProjection(); - if (!budgetExceeded - && (projection == StructureTemplatePool.Projection.RIGID - || projection == StructureTemplatePool.Projection.TERRAIN_MATCHING) - && intersectsHorizontally(poolPiece.getBoundingBox(), influenceArea)) { - try { - List pieceAnchors = new ArrayList<>(); - addProcessedSurfaceAnchors( - world, influenceArea, poolPiece, referencePosition, - projection, budget, pieceAnchors); - anchors.addAll(pieceAnchors); - } catch (TemplateBudgetExceeded ignored) { - budgetExceeded = true; - warnSourceBudget(target); - } - } - for (JigsawJunction junction : poolPiece.getJunctions()) { - anchors.add(new SurfaceAnchor( - junction.getSourceX(), junction.getSourceX(), - junction.getSourceZ(), junction.getSourceZ(), - junction.getSourceGroundY() - 1, 1)); - } - continue; - } - BoundingBox bounds = piece.getBoundingBox(); - anchors.add(surfaceAnchor(bounds, bounds.minY(), 2)); - } - } - return List.copyOf(anchors); - } - - private static void addProcessedSurfaceAnchors( - WorldGenLevel world, BoundingBox influenceArea, - PoolElementStructurePiece piece, BlockPos referencePosition, - StructureTemplatePool.Projection projection, - TemplateCellBudget budget, - List anchors) { - NativeStructureTemplateOccupancy.OccupancyResult occupancy = - NativeStructureTemplateOccupancy.resolve( - world, piece, referencePosition, influenceArea, - () -> world.getLevel().getStructureManager(), - influenceArea::isInside, budget::consume); - if (!occupancy.resolved()) { - return; - } - int maximumFoundationY = piece.getBoundingBox().minY() - + piece.getGroundLevelDelta(); - Map lowest = - NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells()); - for (NativeStructureTemplateOccupancy.LowestCell cell : lowest.values()) { - budget.consume(1); - if (projection == StructureTemplatePool.Projection.RIGID - && cell.y() > maximumFoundationY) { - continue; - } - int groundY = projection == StructureTemplatePool.Projection.RIGID - ? maximumFoundationY : cell.y(); - BoundingBox column = new BoundingBox( - cell.x(), groundY, cell.z(), cell.x(), groundY, cell.z()); - anchors.add(surfaceAnchor(column, groundY, 2)); - } - } - - private static void warnSourceBudget( - NativeStructureTerrainIntegrator.TerrainTarget target) { - String structureId = target.structureId() == null - ? target.start().getStructure().getClass().getName() - : target.structureId(); - if (WARNED_SOURCE_BUDGET.add(structureId)) { - IrisLogging.warn("Native structure SOURCE fitting for '" - + structureId + "' exceeded its bounded template budget; " - + "skipping remaining processed footprints for this start"); - } - } - - private static VacuumFootprint collectVacuumFootprint( - WorldGenLevel world, BoundingBox area, - List targets, - int maximumTemplateCells) { - BoundingBox influenceArea = new BoundingBox( - area.minX() - SURFACE_TERRAIN_RADIUS, area.minY(), - area.minZ() - SURFACE_TERRAIN_RADIUS, - area.maxX() + SURFACE_TERRAIN_RADIUS, area.maxY(), - area.maxZ() + SURFACE_TERRAIN_RADIUS); - Map anchors = new HashMap<>(); - Map columnCaps = new HashMap<>(); - Set foundationBases = new HashSet<>(); - Set occupiedCells = new HashSet<>(); - Set seenStarts = Collections.newSetFromMap( - new IdentityHashMap<>()); - for (NativeStructureTerrainIntegrator.TerrainTarget target : targets) { - if (target == null || target.terrain() == null - || target.terrain().resolvedMode() != IrisStructureTerrainMode.VACUUM - || target.start() == null || !target.start().isValid() - || !seenStarts.add(target.start())) { - continue; - } - StructureStart start = target.start(); - BoundingBox firstBounds = start.getPieces().getFirst().getBoundingBox(); - BlockPos firstCenter = firstBounds.getCenter(); - BlockPos referencePosition = new BlockPos( - firstCenter.getX(), firstBounds.minY(), firstCenter.getZ()); - Map targetAnchors = new HashMap<>(); - Map targetCaps = new HashMap<>(); - Set targetFoundationBases = new HashSet<>(); - Set targetOccupiedCells = new HashSet<>(); - TemplateCellBudget budget = new TemplateCellBudget(maximumTemplateCells); - try { - for (StructurePiece piece : start.getPieces()) { - BoundingBox bounds = piece.getBoundingBox(); - if (!intersectsHorizontally(bounds, influenceArea) - || !(piece instanceof PoolElementStructurePiece poolPiece) - || poolPiece.getElement().getProjection() - != StructureTemplatePool.Projection.RIGID) { - continue; - } - addVacuumJunctionAnchors( - anchors, influenceArea, poolPiece); - NativeStructureTemplateOccupancy.OccupancyResult occupancy = - NativeStructureTemplateOccupancy.resolve( - world, poolPiece, referencePosition, influenceArea, - () -> world.getLevel().getStructureManager(), - influenceArea::isInside, budget::consume); - if (!occupancy.resolved()) { - continue; - } - targetOccupiedCells.addAll(occupancy.cells().keySet()); - Map lowest = - NativeStructureTemplateOccupancy.lowestCells( - occupancy.cells()); - int groundY = bounds.minY() - + poolPiece.getGroundLevelDelta() - 1; - for (NativeStructureTemplateOccupancy.LowestCell cell : lowest.values()) { - budget.consume(1); - long column = NativeStructureTemplateOccupancy.columnKey( - cell.x(), cell.z()); - targetCaps.merge( - column, Math.min(cell.y(), groundY), Math::min); - if (cell.occupancy().blocker() - || cell.y() > groundY + 1 - || !NativeStructureTemplateOccupancy.isSolidBase( - cell.occupancy().state())) { - continue; - } - addVacuumAnchor(targetAnchors, cell.x(), cell.z(), - new VacuumAnchor(cell.y() - 1, 2)); - targetFoundationBases.add(BlockPos.asLong( - cell.x(), cell.y(), cell.z())); - } - } - } catch (TemplateBudgetExceeded ignored) { - warnVacuumBudget(target); - continue; - } - targetAnchors.forEach((column, anchor) -> anchors.merge( - column, anchor, NativeStructureSurfaceFitter::preferredVacuumAnchor)); - targetCaps.forEach((column, cap) -> columnCaps.merge( - column, cap, Math::min)); - foundationBases.addAll(targetFoundationBases); - occupiedCells.addAll(targetOccupiedCells); - } - return new VacuumFootprint( - Map.copyOf(anchors), Map.copyOf(columnCaps), - Set.copyOf(foundationBases), Set.copyOf(occupiedCells)); - } - - private static void addVacuumJunctionAnchors( - Map anchors, BoundingBox influenceArea, - PoolElementStructurePiece poolPiece) { - for (JigsawJunction junction : poolPiece.getJunctions()) { - if (junction.getSourceX() < influenceArea.minX() - || junction.getSourceX() > influenceArea.maxX() - || junction.getSourceZ() < influenceArea.minZ() - || junction.getSourceZ() > influenceArea.maxZ()) { - continue; - } - addVacuumAnchor(anchors, - junction.getSourceX(), junction.getSourceZ(), - new VacuumAnchor(junction.getSourceGroundY() - 1, 1)); - } - } - - private static void warnVacuumBudget( - NativeStructureTerrainIntegrator.TerrainTarget target) { - String structureId = target.structureId() == null - ? target.start().getStructure().getClass().getName() - : target.structureId(); - if (WARNED_VACUUM_BUDGET.add(structureId)) { - IrisLogging.warn("Native structure VACUUM fitting for '" - + structureId + "' exceeded its bounded template budget; " - + "using jigsaw junction smoothing for oversized starts"); - } - } - - private static boolean intersectsHorizontally( - BoundingBox first, BoundingBox second) { - return first.maxX() >= second.minX() && first.minX() <= second.maxX() - && first.maxZ() >= second.minZ() && first.minZ() <= second.maxZ(); - } - - private static void addVacuumAnchor( - Map anchors, int x, int z, - VacuumAnchor candidate) { - anchors.merge(NativeStructureTemplateOccupancy.columnKey(x, z), candidate, - NativeStructureSurfaceFitter::preferredVacuumAnchor); - } - - private static VacuumAnchor preferredVacuumAnchor( - VacuumAnchor first, VacuumAnchor second) { - if (first.strength() != second.strength()) { - return first.strength() > second.strength() ? first : second; - } - return first.surfaceY() <= second.surfaceY() ? first : second; - } - - static SurfaceAnchor surfaceAnchor(BoundingBox bounds, int groundY, int strength) { - return new SurfaceAnchor(bounds.minX(), bounds.maxX(), bounds.minZ(), bounds.maxZ(), - groundY - 1, strength); - } - - static boolean requiresSurfaceTerrain(StructureStart start) { - return requiresSurfaceTerrain(new NativeStructureTerrainIntegrator.TerrainTarget( - null, start, new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE))); - } - - static boolean requiresSurfaceTerrain(NativeStructureTerrainIntegrator.TerrainTarget target) { - if (target == null || target.terrain() == null) { - return false; - } - StructureStart start = target.start(); - if (start == null || !start.isValid()) { - return false; - } - IrisStructureTerrainMode mode = target.terrain().resolvedMode(); - return mode == IrisStructureTerrainMode.VACUUM - || requiresSourceSurfaceTerrain(target); - } - - private static boolean requiresSourceSurfaceTerrain( - NativeStructureTerrainIntegrator.TerrainTarget target) { - return target != null && target.terrain() != null - && target.start() != null && target.start().isValid() - && target.terrain().resolvedMode() == IrisStructureTerrainMode.SOURCE - && shouldPrepareSurfaceTerrain( - target.start().getStructure().terrainAdaptation(), - target.start().getStructure().step()); - } - - private static void fitSurfaceTerrain(WorldGenLevel world, BoundingBox area, - List anchors, - IntBinaryOperator surfaceHeight) { - int width = area.getXSpan(); - int depth = area.getZSpan(); - int[] originalHeights = new int[width * depth]; - int[] targetHeights = new int[width * depth]; - boolean[] rigidBaseSupport = new boolean[width * depth]; - for (int z = area.minZ(); z <= area.maxZ(); z++) { - for (int x = area.minX(); x <= area.maxX(); x++) { - int column = (z - area.minZ()) * width + x - area.minX(); - int originalY = Math.max(area.minY(), Math.min( - area.maxY(), surfaceHeight.applyAsInt(x, z))); - SurfaceResolution resolution = resolveSurface(anchors, x, z, originalY); - originalHeights[column] = originalY; - targetHeights[column] = Math.max(area.minY(), Math.min( - area.maxY(), resolution.targetY())); - rigidBaseSupport[column] = resolution.rigidBaseSupport(); - } - } - BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); - for (int z = area.minZ(); z <= area.maxZ(); z++) { - for (int x = area.minX(); x <= area.maxX(); x++) { - int column = (z - area.minZ()) * width + x - area.minX(); - applySurfaceColumn(world, position, x, z, - originalHeights[column], targetHeights[column], area.minY(), area.maxY(), - rigidBaseSupport[column]); - } - } - } - - private static void fitVacuumTerrain( - WorldGenLevel world, BoundingBox area, VacuumFootprint footprint, - IntBinaryOperator surfaceHeight) { - int width = area.getXSpan(); - int depth = area.getZSpan(); - int[] originalHeights = new int[width * depth]; - int[] targetHeights = new int[width * depth]; - boolean[] rigidBaseSupport = new boolean[width * depth]; - BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); - for (int z = area.minZ(); z <= area.maxZ(); z++) { - for (int x = area.minX(); x <= area.maxX(); x++) { - int column = (z - area.minZ()) * width + x - area.minX(); - int nominalY = Math.max(area.minY(), Math.min( - area.maxY(), surfaceHeight.applyAsInt(x, z))); - long columnKey = NativeStructureTemplateOccupancy.columnKey(x, z); - VacuumAnchor local = footprint.anchors().get(columnKey); - Integer cap = footprint.columnCaps().get(columnKey); - boolean suppressed = local != null && local.strength() > 1 - && cap != null && cap < local.surfaceY(); - int scanStartY = local != null && local.strength() > 1 && !suppressed - ? Math.max(area.minY(), Math.min(area.maxY(), local.surfaceY())) - : nominalY; - int originalY = resolveVacuumSurfaceHeight( - world, position, x, z, scanStartY, area.minY()); - SurfaceResolution resolution = resolveVacuumSurface( - footprint, x, z, originalY); - originalHeights[column] = originalY; - targetHeights[column] = Math.max(originalY, Math.min( - area.maxY(), resolution.targetY())); - rigidBaseSupport[column] = resolution.rigidBaseSupport() - && targetHeights[column] > originalY; - } - } - for (int z = area.minZ(); z <= area.maxZ(); z++) { - for (int x = area.minX(); x <= area.maxX(); x++) { - int column = (z - area.minZ()) * width + x - area.minX(); - applySurfaceColumn(world, position, x, z, - originalHeights[column], targetHeights[column], - area.minY(), area.maxY(), rigidBaseSupport[column]); - } - } - } - - private static int resolveVacuumSurfaceHeight( - WorldGenLevel world, BlockPos.MutableBlockPos position, - int x, int z, int nominalY, int worldMinY) { - for (int y = nominalY; y >= worldMinY; y--) { - if (isTerrainBlock(world.getBlockState(position.set(x, y, z)))) { - return y; - } - } - return nominalY; - } - - private static int findVacuumFoundationSupport( - WorldGenLevel world, BoundingBox area, - BlockPos.MutableBlockPos position, int x, int startY, int z) { - if (startY < area.minY()) { - return Integer.MIN_VALUE; - } - int maximumY = Math.min(area.maxY(), startY); - for (int y = maximumY; y >= area.minY(); y--) { - BlockState state = world.getBlockState(position.set(x, y, z)); - if (isTerrainBlock(state)) { - return y; - } - if (!state.isAir() && state.getFluidState().isEmpty()) { - return Integer.MIN_VALUE; - } - } - return Integer.MIN_VALUE; - } - - private static boolean intersectsVacuumOccupancy( - Set occupiedCells, int x, int z, int minimumY, int maximumY) { - for (int y = minimumY; y <= maximumY; y++) { - if (occupiedCells.contains(BlockPos.asLong(x, y, z))) { - return true; - } - } - return false; - } - - private static SurfaceResolution resolveVacuumSurface( - VacuumFootprint footprint, int worldX, int worldZ, int originalY) { - long column = NativeStructureTemplateOccupancy.columnKey(worldX, worldZ); - Integer cap = footprint.columnCaps().get(column); - VacuumAnchor local = footprint.anchors().get(column); - if (local != null && local.strength() > 1) { - int localTargetY = cap == null - ? local.surfaceY() : Math.min(local.surfaceY(), cap); - if (localTargetY <= originalY) { - return new SurfaceResolution(originalY, false); - } - return new SurfaceResolution( - localTargetY, localTargetY == local.surfaceY()); - } - long totalInfluence = 0L; - long weightedSurfaceY = 0L; - long maximumInfluence = 0L; - int radiusSquared = SURFACE_TERRAIN_RADIUS * SURFACE_TERRAIN_RADIUS; - for (int offsetX = -SURFACE_TERRAIN_RADIUS; - offsetX <= SURFACE_TERRAIN_RADIUS; offsetX++) { - for (int offsetZ = -SURFACE_TERRAIN_RADIUS; - offsetZ <= SURFACE_TERRAIN_RADIUS; offsetZ++) { - int horizontalDistanceSquared = offsetX * offsetX + offsetZ * offsetZ; - if (horizontalDistanceSquared > radiusSquared) { - continue; - } - VacuumAnchor anchor = footprint.anchors().get( - NativeStructureTemplateOccupancy.columnKey( - worldX + offsetX, worldZ + offsetZ)); - if (anchor == null || anchor.surfaceY() <= originalY) { - continue; - } - int verticalDistance = Math.abs(anchor.surfaceY() + 1 - originalY); - long distanceSquared = horizontalDistanceSquared - + (long) verticalDistance * verticalDistance; - double factor = 0D; - if (distanceSquared <= radiusSquared) { - factor = surfaceFactor(Math.sqrt(distanceSquared)); - } - if (anchor.strength() > 1 - && verticalDistance > SURFACE_TERRAIN_RADIUS) { - double rescueProgress = Math.min(1D, - (verticalDistance - SURFACE_TERRAIN_RADIUS) - / (double) SURFACE_TERRAIN_RADIUS); - double rescueWeight = rescueProgress * rescueProgress - * (3D - 2D * rescueProgress); - factor = Math.max(factor, - surfaceFactor(Math.sqrt(horizontalDistanceSquared)) - * rescueWeight); - } - long influence = Math.round( - factor * SURFACE_TERRAIN_INFLUENCE_SCALE); - if (influence <= 0L) { - continue; - } - long weightedInfluence = influence * Math.max(1, anchor.strength()); - totalInfluence += weightedInfluence; - weightedSurfaceY += weightedInfluence * anchor.surfaceY(); - maximumInfluence = Math.max(maximumInfluence, influence); - } - } - if (totalInfluence == 0L) { - return new SurfaceResolution(originalY, false); - } - double blendedSurfaceY = weightedSurfaceY / (double) totalInfluence; - double factor = maximumInfluence / (double) SURFACE_TERRAIN_INFLUENCE_SCALE; - int targetY = (int) Math.round( - originalY + ((blendedSurfaceY - originalY) * factor)); - if (cap != null) { - targetY = Math.min(targetY, cap); - } - return new SurfaceResolution(Math.max(originalY, targetY), false); - } - - private static double surfaceFactor(double distance) { - return Math.pow(1D - distance / SURFACE_TERRAIN_RADIUS, - SURFACE_TERRAIN_FALLOFF); - } - - static void applySurfaceColumn(WorldGenLevel world, BlockPos.MutableBlockPos position, - int x, int z, int originalY, int targetY, - int worldMinY, int worldMaxY) { - applySurfaceColumn(world, position, x, z, originalY, targetY, - worldMinY, worldMaxY, false); - } - - static void applySurfaceColumn(WorldGenLevel world, BlockPos.MutableBlockPos position, - int x, int z, int originalY, int targetY, - int worldMinY, int worldMaxY, - boolean requireRigidBaseSupport) { - if (targetY == originalY) { - if (requireRigidBaseSupport) { - ensureRigidBaseTerrain(world, position, x, z, targetY, worldMinY); - } - return; - } - SurfaceMaterials materials = resolveSurfaceMaterials(world, position, x, z, originalY, worldMinY); - if (targetY < originalY) { - BlockState clearedState = clearSurfaceDecorationAndResolveFill( - world, position, x, z, originalY, worldMaxY); - for (int y = originalY; y > targetY; y--) { - world.setBlock(position.set(x, y, z), clearedState, 2); - } - world.setBlock(position.set(x, targetY, z), materials.surface(), 2); - if (requireRigidBaseSupport) { - ensureRigidBaseTerrain(world, position, x, z, targetY, worldMinY, materials); - } - return; - } - for (int y = originalY + 1; y < targetY; y++) { - position.set(x, y, z); - if (!NativeStructureVegetationClearer.isTreeBlock(world.getBlockState(position))) { - world.setBlock(position, materials.subsurface(), 2); - } - } - position.set(x, targetY, z); - if (!NativeStructureVegetationClearer.isTreeBlock(world.getBlockState(position))) { - world.setBlock(position, materials.surface(), 2); - } - if (requireRigidBaseSupport) { - ensureRigidBaseTerrain(world, position, x, z, targetY, worldMinY, materials); - } - } - - private static void ensureRigidBaseTerrain(WorldGenLevel world, - BlockPos.MutableBlockPos position, - int x, int z, int targetY, int worldMinY) { - int supportY = targetY - 1; - boolean targetIsTerrain = isTerrainBlock(world.getBlockState(position.set(x, targetY, z))); - boolean supportIsTerrain = supportY < worldMinY - || isTerrainBlock(world.getBlockState(position.set(x, supportY, z))); - if (targetIsTerrain && supportIsTerrain) { - return; - } - SurfaceMaterials materials = resolveSurfaceMaterials( - world, position, x, z, targetY, worldMinY); - ensureRigidBaseTerrain(world, position, x, z, targetY, worldMinY, materials); - } - - private static void ensureRigidBaseTerrain(WorldGenLevel world, - BlockPos.MutableBlockPos position, - int x, int z, int targetY, int worldMinY, - SurfaceMaterials materials) { - int supportY = targetY - 1; - position.set(x, targetY, z); - if (!isTerrainBlock(world.getBlockState(position))) { - world.setBlock(position, materials.surface(), 2); - } - if (supportY < worldMinY) { - return; - } - position.set(x, supportY, z); - if (!isTerrainBlock(world.getBlockState(position))) { - world.setBlock(position, materials.subsurface(), 2); - } - } - - private static BlockState clearSurfaceDecorationAndResolveFill( - WorldGenLevel world, BlockPos.MutableBlockPos position, - int x, int z, int originalY, int worldMaxY) { - BlockState air = Blocks.AIR.defaultBlockState(); - for (int y = originalY + 1; y <= worldMaxY; y++) { - BlockState state = world.getBlockState(position.set(x, y, z)); - if (state.isAir()) { - return air; - } - if (!state.getFluidState().isEmpty()) { - BlockState fluid = state.getFluidState().createLegacyBlock(); - if (state != fluid) { - world.setBlock(position, fluid, 2); - } - return fluid; - } - if (state.isSolid() || NativeStructureVegetationClearer.isTreeBlock(state)) { - return air; - } - world.setBlock(position, air, 2); - } - return air; - } - - private static SurfaceMaterials resolveSurfaceMaterials(WorldGenLevel world, - BlockPos.MutableBlockPos position, - int x, int z, int originalY, - int worldMinY) { - BlockState surface = world.getBlockState(position.set(x, originalY, z)); - BlockState subsurface = null; - for (int y = originalY - 1; y >= worldMinY; y--) { - BlockState candidate = world.getBlockState(position.set(x, y, z)); - if (isTerrainBlock(candidate)) { - subsurface = candidate; - break; - } - } - if (subsurface == null) { - subsurface = isTerrainBlock(surface) ? surface : Blocks.STONE.defaultBlockState(); - } - if (!isTerrainBlock(surface)) { - surface = subsurface; - } - return new SurfaceMaterials(surface, subsurface); - } - - private static boolean isTerrainBlock(BlockState state) { - return state.isSolid() && !NativeStructureVegetationClearer.isTreeBlock(state); - } - - record SurfaceAnchor(int minX, int maxX, int minZ, int maxZ, int meetY, int strength) { - } - - private record SurfaceMaterials(BlockState surface, BlockState subsurface) { - } - - private record SurfaceResolution(int targetY, boolean rigidBaseSupport) { - } - - private record VacuumFootprint( - Map anchors, Map columnCaps, - Set foundationBases, Set occupiedCells) { - } - - private record VacuumAnchor(int surfaceY, int strength) { - } - - public static final class VacuumFoundationPlan { - private static final VacuumFoundationPlan EMPTY = - new VacuumFoundationPlan(List.of(), Set.of()); - - private final List foundationBases; - private final Set occupiedCells; - - private VacuumFoundationPlan( - List foundationBases, Set occupiedCells) { - this.foundationBases = foundationBases; - this.occupiedCells = occupiedCells; - } - - private static VacuumFoundationPlan empty() { - return EMPTY; - } - - private static VacuumFoundationPlan create( - Set packedBases, Set packedOccupancy, - BoundingBox area) { - if (packedBases.isEmpty()) { - return EMPTY; - } - List bases = new ArrayList<>(packedBases.size()); - Set columns = new HashSet<>(); - for (long packedBase : packedBases) { - BlockPos base = BlockPos.of(packedBase); - if (!area.isInside(base)) { - continue; - } - bases.add(packedBase); - columns.add(NativeStructureTemplateOccupancy.columnKey( - base.getX(), base.getZ())); - } - if (bases.isEmpty()) { - return EMPTY; - } - bases.sort((first, second) -> { - int yOrder = Integer.compare( - BlockPos.of(first).getY(), BlockPos.of(second).getY()); - return yOrder == 0 ? Long.compare(first, second) : yOrder; - }); - Set occupancy = new HashSet<>(); - for (long packedCell : packedOccupancy) { - BlockPos cell = BlockPos.of(packedCell); - if (columns.contains(NativeStructureTemplateOccupancy.columnKey( - cell.getX(), cell.getZ()))) { - occupancy.add(packedCell); - } - } - return new VacuumFoundationPlan( - List.copyOf(bases), Set.copyOf(occupancy)); - } - } - - private static final class TemplateCellBudget { - private final int maximum; - private int consumed; - - private TemplateCellBudget(int maximum) { - if (maximum < 0) { - throw new IllegalArgumentException( - "Native structure surface template budget cannot be negative"); - } - this.maximum = maximum; - } - - private void consume(int amount) { - if (amount < 0 || consumed > maximum - amount) { - throw TemplateBudgetExceeded.INSTANCE; - } - consumed += amount; - } - } - - private static final class TemplateBudgetExceeded extends RuntimeException { - private static final TemplateBudgetExceeded INSTANCE = - new TemplateBudgetExceeded(); - - private TemplateBudgetExceeded() { - super(null, null, false, false); - } - } -} diff --git a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureSurfaceSupportBuilder.java b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureSurfaceSupportBuilder.java deleted file mode 100644 index 27e929c11..000000000 --- a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureSurfaceSupportBuilder.java +++ /dev/null @@ -1,299 +0,0 @@ -package art.arcane.iris.nativegen; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.structure.BoundingBox; -import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece; -import net.minecraft.world.level.levelgen.structure.StructurePiece; -import net.minecraft.world.level.levelgen.structure.StructureStart; -import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Supplier; - -final class NativeStructureSurfaceSupportBuilder { - private static final int MAX_BATCH_CELLS = 524_288; - private static final int MAX_BRIDGE_SPAN = 2; - - private NativeStructureSurfaceSupportBuilder() { - } - - static Set bridgeRigidPieceSupport( - WorldGenLevel world, BoundingBox area, - List targets, - Supplier templates) { - if (targets == null || targets.isEmpty()) { - return Set.of(); - } - Map planned; - try { - BatchCellBudget budget = new BatchCellBudget(); - List requests = new ArrayList<>(); - Set seenStarts = Collections.newSetFromMap( - new IdentityHashMap<>()); - for (NativeStructureTerrainIntegrator.TerrainTarget target : targets) { - if (target == null - || !NativeStructureSurfaceFitter.requiresSurfaceTerrain(target) - || !seenStarts.add(target.start())) { - continue; - } - collectTargetRequests( - world, area, target, templates, budget, requests); - } - planned = planWrites(world, area, requests, budget); - } catch (BatchBudgetExceeded ignored) { - return Set.of(); - } - if (planned.isEmpty()) { - return Set.of(); - } - List> ordered = new ArrayList<>(planned.entrySet()); - ordered.sort(Map.Entry.comparingByKey()); - Set written = new HashSet<>(); - for (Map.Entry entry : ordered) { - BlockPos position = BlockPos.of(entry.getKey()); - BlockState existing = world.getBlockState(position); - if (!existing.isSolid() - && !NativeStructureVegetationClearer.isTreeBlock(existing) - && existing.getFluidState().isEmpty() - && world.setBlock(position, entry.getValue(), 2)) { - written.add(entry.getKey()); - } - } - return Set.copyOf(written); - } - - private static void collectTargetRequests( - WorldGenLevel world, BoundingBox area, - NativeStructureTerrainIntegrator.TerrainTarget target, - Supplier templates, - BatchCellBudget budget, List requests) { - if (!NativeStructureSurfaceFitter.requiresSurfaceTerrain(target)) { - return; - } - List anchors = rigidAnchors(target.start()); - if (anchors.size() < 2) { - return; - } - BlockPos referencePos = referencePosition(target.start()); - for (RigidAnchor upper : anchors) { - Map lowerMeets = candidateLowerMeets( - area, upper, anchors, budget); - if (lowerMeets.isEmpty()) { - continue; - } - NativeStructureTemplateOccupancy.OccupancyResult occupancy = - NativeStructureTemplateOccupancy.resolve( - world, upper.piece(), referencePos, area, templates, - position -> retain(position, area, lowerMeets), budget::consume); - if (!occupancy.resolved()) { - continue; - } - Map lowest = - NativeStructureTemplateOccupancy.lowestCells(occupancy.cells()); - for (Map.Entry entry - : lowest.entrySet()) { - NativeStructureTemplateOccupancy.LowestCell cell = entry.getValue(); - Integer lowerMeet = lowerMeets.get(entry.getKey()); - if (lowerMeet == null || cell.occupancy().blocker() - || !NativeStructureTemplateOccupancy.isSolidBase( - cell.occupancy().state()) - || cell.y() - lowerMeet < 2 - || cell.y() - lowerMeet > MAX_BRIDGE_SPAN) { - continue; - } - budget.consume(1); - requests.add(new SupportRequest( - cell.x(), cell.z(), lowerMeet, cell.y())); - } - } - } - - private static List rigidAnchors(StructureStart start) { - List anchors = new ArrayList<>(); - for (StructurePiece piece : start.getPieces()) { - if (!(piece instanceof PoolElementStructurePiece poolPiece) - || poolPiece.getElement().getProjection() - != StructureTemplatePool.Projection.RIGID) { - continue; - } - BoundingBox bounds = poolPiece.getBoundingBox(); - int meetY = bounds.minY() + poolPiece.getGroundLevelDelta() - 1; - anchors.add(new RigidAnchor(poolPiece, bounds, meetY)); - } - return List.copyOf(anchors); - } - - private static Map candidateLowerMeets( - BoundingBox area, RigidAnchor upper, List anchors, - BatchCellBudget budget) { - Map lowerMeets = new HashMap<>(); - for (RigidAnchor lower : anchors) { - budget.consume(1); - int span = upper.meetY() - lower.meetY(); - if (lower.piece() == upper.piece() || span < 1 - || span > MAX_BRIDGE_SPAN - || lower.meetY() < area.minY() || lower.meetY() > area.maxY()) { - continue; - } - int minimumX = Math.max(area.minX(), - Math.max(upper.bounds().minX(), lower.bounds().minX())); - int maximumX = Math.min(area.maxX(), - Math.min(upper.bounds().maxX(), lower.bounds().maxX())); - int minimumZ = Math.max(area.minZ(), - Math.max(upper.bounds().minZ(), lower.bounds().minZ())); - int maximumZ = Math.min(area.maxZ(), - Math.min(upper.bounds().maxZ(), lower.bounds().maxZ())); - if (minimumX > maximumX || minimumZ > maximumZ) { - continue; - } - for (int x = minimumX; x <= maximumX; x++) { - for (int z = minimumZ; z <= maximumZ; z++) { - budget.consume(1); - lowerMeets.merge(columnKey(x, z), lower.meetY(), Math::max); - } - } - } - return lowerMeets; - } - - private static boolean retain( - BlockPos position, BoundingBox area, Map lowerMeets) { - if (!area.isInside(position)) { - return false; - } - Integer lowerMeet = lowerMeets.get(columnKey(position.getX(), position.getZ())); - return lowerMeet != null && position.getY() <= lowerMeet + MAX_BRIDGE_SPAN; - } - - private static Map planWrites( - WorldGenLevel world, BoundingBox area, - List requests, BatchCellBudget budget) { - List eligible = new ArrayList<>(); - Set materialKeys = new HashSet<>(); - BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); - for (SupportRequest request : requests) { - BlockState lowerTerrain = world.getBlockState(position.set( - request.x(), request.lowerMeetY(), request.z())); - if (!isTerrainSupport(lowerTerrain) - || !gapIsClear(world, area, position, request, budget)) { - continue; - } - eligible.add(request); - materialKeys.add(new MaterialKey( - request.x(), request.z(), request.lowerMeetY())); - } - Map materials = new HashMap<>(); - for (MaterialKey key : materialKeys) { - materials.put(key, resolveSupportState( - world, position, key.x(), key.z(), key.lowerMeetY(), budget)); - } - Map planned = new HashMap<>(); - Set conflicts = new HashSet<>(); - eligible.sort(Comparator.comparingInt(SupportRequest::x) - .thenComparingInt(SupportRequest::z) - .thenComparingInt(SupportRequest::lowerMeetY) - .thenComparingInt(SupportRequest::baseY)); - for (SupportRequest request : eligible) { - MaterialKey materialKey = new MaterialKey( - request.x(), request.z(), request.lowerMeetY()); - BlockState material = materials.get(materialKey); - for (int y = request.lowerMeetY() + 1; y < request.baseY(); y++) { - budget.consume(1); - long positionKey = BlockPos.asLong(request.x(), y, request.z()); - if (conflicts.contains(positionKey)) { - continue; - } - BlockState existing = planned.putIfAbsent(positionKey, material); - if (existing != null && !existing.equals(material)) { - planned.remove(positionKey); - conflicts.add(positionKey); - } - } - } - return planned; - } - - private static boolean gapIsClear( - WorldGenLevel world, BoundingBox area, BlockPos.MutableBlockPos position, - SupportRequest request, BatchCellBudget budget) { - for (int y = request.lowerMeetY() + 1; y < request.baseY(); y++) { - budget.consume(1); - if (!area.isInside(position.set(request.x(), y, request.z()))) { - return false; - } - BlockState state = world.getBlockState(position); - if (state.isSolid() || NativeStructureVegetationClearer.isTreeBlock(state) - || !state.getFluidState().isEmpty()) { - return false; - } - } - return true; - } - - private static BlockState resolveSupportState( - WorldGenLevel world, BlockPos.MutableBlockPos position, - int x, int z, int lowerMeetY, BatchCellBudget budget) { - budget.consume(1); - BlockState below = world.getBlockState(position.set(x, lowerMeetY - 1, z)); - if (isTerrainSupport(below)) { - return below; - } - return world.getBlockState(position.set(x, lowerMeetY, z)); - } - - private static boolean isTerrainSupport(BlockState state) { - return state.isSolid() - && !NativeStructureVegetationClearer.isTreeBlock(state) - && state.getFluidState().isEmpty(); - } - - private static BlockPos referencePosition(StructureStart start) { - BoundingBox bounds = start.getPieces().getFirst().getBoundingBox(); - BlockPos center = bounds.getCenter(); - return new BlockPos(center.getX(), bounds.minY(), center.getZ()); - } - - private static long columnKey(int x, int z) { - return (long) x << 32 ^ z & 0xffffffffL; - } - - private record RigidAnchor( - PoolElementStructurePiece piece, BoundingBox bounds, int meetY) { - } - - private record SupportRequest(int x, int z, int lowerMeetY, int baseY) { - } - - private record MaterialKey(int x, int z, int lowerMeetY) { - } - - private static final class BatchCellBudget { - private int consumed; - - private void consume(int amount) { - if (amount < 0 || consumed > MAX_BATCH_CELLS - amount) { - throw BatchBudgetExceeded.INSTANCE; - } - consumed += amount; - } - } - - private static final class BatchBudgetExceeded extends RuntimeException { - private static final BatchBudgetExceeded INSTANCE = new BatchBudgetExceeded(); - - private BatchBudgetExceeded() { - super(null, null, false, false); - } - } -} diff --git a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureTemplateOccupancy.java b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureTemplateOccupancy.java index f904a2127..7b30bb1d0 100644 --- a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureTemplateOccupancy.java +++ b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureTemplateOccupancy.java @@ -1,5 +1,6 @@ package art.arcane.iris.nativegen; +import art.arcane.iris.engine.framework.nativefit.NativeTemplateCells; import net.minecraft.core.BlockPos; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.block.Blocks; @@ -74,44 +75,34 @@ final class NativeStructureTemplateOccupancy { return new OccupancyResult(true, occupancy); } - static Map lowestCells(Map occupancy) { - Map lowest = new HashMap<>(); - for (Map.Entry entry : occupancy.entrySet()) { - OccupancyCell cell = entry.getValue(); - BlockPos position = BlockPos.of(entry.getKey()); - long column = columnKey(position.getX(), position.getZ()); - LowestCell current = lowest.get(column); - if (current == null || position.getY() < current.y()) { - lowest.put(column, new LowestCell( - position.getX(), position.getY(), position.getZ(), cell)); - } + /** + * The piece's processed template blocks inside {@code region}, processed against the world as it is now, as the + * modules' fit reads them: removed blocks have no state, and the count of template blocks read is reported. + */ + static NativeTemplateCells cells( + WorldGenLevel world, PoolElementStructurePiece piece, BlockPos referencePosition, BoundingBox region, + Supplier templates) { + int[] readBlocks = {0}; + OccupancyResult occupancy = resolve(world, piece, referencePosition, region, templates, region::isInside, + amount -> readBlocks[0] = Math.addExact(readBlocks[0], amount)); + if (!occupancy.resolved()) { + return new NativeTemplateCells<>(false, new int[0], new int[0], new int[0], new BlockState[0], 0); } - return lowest; - } - - static Map lowestProcessedSolidCells(Map occupancy) { - Map lowest = new HashMap<>(); - for (Map.Entry entry : occupancy.entrySet()) { - OccupancyCell cell = entry.getValue(); - if (cell.blocker() || !isSolidBase(cell.state())) { - continue; - } + int size = occupancy.cells().size(); + int[] xs = new int[size]; + int[] ys = new int[size]; + int[] zs = new int[size]; + BlockState[] states = new BlockState[size]; + int cell = 0; + for (Map.Entry entry : occupancy.cells().entrySet()) { BlockPos position = BlockPos.of(entry.getKey()); - long column = columnKey(position.getX(), position.getZ()); - LowestCell current = lowest.get(column); - if (current == null || position.getY() < current.y()) { - lowest.put(column, new LowestCell( - position.getX(), position.getY(), position.getZ(), cell)); - } + xs[cell] = position.getX(); + ys[cell] = position.getY(); + zs[cell] = position.getZ(); + states[cell] = entry.getValue().state(); + cell++; } - return lowest; - } - - static boolean isSolidBase(BlockState state) { - return state != null && state.isSolid() - && !state.is(Blocks.STRUCTURE_VOID) - && !state.is(Blocks.JIGSAW) - && state.getFluidState().isEmpty(); + return new NativeTemplateCells<>(true, xs, ys, zs, states, readBlocks[0]); } static long columnKey(int x, int z) { @@ -154,9 +145,6 @@ final class NativeStructureTemplateOccupancy { record OccupancyCell(BlockState state, boolean blocker) { } - record LowestCell(int x, int y, int z, OccupancyCell occupancy) { - } - private record LeafPlacement( StructurePlaceSettings settings, List rawBlocks, diff --git a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureTerrainIntegrator.java b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureTerrainIntegrator.java deleted file mode 100644 index aad330d20..000000000 --- a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureTerrainIntegrator.java +++ /dev/null @@ -1,1096 +0,0 @@ -package art.arcane.iris.nativegen; - -import art.arcane.iris.engine.mantle.components.StructureCarveEnvelope; -import art.arcane.iris.engine.mantle.components.StructureCarvingFootprint; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.structure.IrisStructureCarveShape; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.math.RNG; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Holder; -import net.minecraft.resources.ResourceKey; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.tags.BlockTags; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.Block; -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.dimension.BuiltinDimensionTypes; -import net.minecraft.world.level.dimension.DimensionType; -import net.minecraft.world.level.levelgen.structure.BoundingBox; -import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece; -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.pools.JigsawJunction; -import net.minecraft.world.level.levelgen.structure.pools.LegacySinglePoolElement; -import net.minecraft.world.level.levelgen.structure.pools.ListPoolElement; -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.templatesystem.StructurePlaceSettings; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; - -import java.util.ArrayList; -import java.util.BitSet; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.WeakHashMap; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Supplier; - -public final class NativeStructureTerrainIntegrator { - private static final long CARVE_CEILING_ROLL_SIGNATURE = 0x2A17L; - private static final long CARVE_FLOOR_ROLL_SIGNATURE = 0x5B3DL; - private static final long CARVE_LOBE_SIGNATURE = 0x7C41L; - private static final int MAX_CACHED_CARVE_CELLS = 2_000_000; - private static final int MAX_CARVE_COLUMNS = 2_000_000; - private static final int MAX_TEMPLATE_OCCUPANCY_CELLS = 4_194_304; - private static final int SOURCE_BURY_HORIZONTAL_RADIUS = 6; - private static final int SOURCE_BURY_VERTICAL_RADIUS = 12; - private static final int SOURCE_ENCAPSULATE_RADIUS = 12; - private static final int SOURCE_JUNCTION_RADIUS = 12; - private static final int SOURCE_MATERIAL_SAMPLE_RADIUS = 8; - private static final List TEMPLATE_VOID_BLOCKS = List.of(Blocks.AIR, Blocks.STRUCTURE_VOID); - private static final Set VANILLA_SOURCE_TERRAIN_BLOCKS = Set.of( - Blocks.STONE, Blocks.GRANITE, Blocks.DIORITE, Blocks.ANDESITE, - Blocks.TUFF, Blocks.DEEPSLATE, Blocks.NETHERRACK, Blocks.BASALT, - Blocks.BLACKSTONE, Blocks.DIRT, Blocks.COARSE_DIRT, Blocks.ROOTED_DIRT, - Blocks.GRASS_BLOCK, Blocks.PODZOL, Blocks.MYCELIUM, Blocks.MUD, - Blocks.MOSS_BLOCK, Blocks.SAND, Blocks.RED_SAND, Blocks.TERRACOTTA, - Blocks.CRIMSON_NYLIUM, Blocks.WARPED_NYLIUM, Blocks.SNOW_BLOCK, - Blocks.ICE, Blocks.PACKED_ICE, Blocks.BLUE_ICE, Blocks.SOUL_SAND, - Blocks.SOUL_SOIL, Blocks.END_STONE, Blocks.GRAVEL, Blocks.CLAY, - Blocks.CALCITE, Blocks.DRIPSTONE_BLOCK, Blocks.SANDSTONE, - Blocks.RED_SANDSTONE, Blocks.SCULK); - // Weakly keyed on the StructureStart so retired starts (world unload, generation done) - // are collectable instead of pinned forever by a process-wide static; values hold only - // primitives, so there is no value-to-key cycle defeating the weak keys. - private static final Map> CARVE_FOOTPRINTS = - new WeakHashMap<>(16); - private static final ConcurrentHashMap> - CARVE_FOOTPRINT_BUILDS = new ConcurrentHashMap<>(); - private static int cachedCarveCells; - - private NativeStructureTerrainIntegrator() { - } - - public static IrisStructureTerrain resolveNativeTerrain(StructureStart start, - IrisStructureTerrain configuredTerrain) { - return configuredTerrain == null - ? new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE) - : configuredTerrain; - } - - static void integrateTerrain(WorldGenLevel world, BoundingBox area, String structureId, - StructureStart start, IrisStructureTerrain configuredTerrain, - NativeStructurePostProcessor.PaletteBlockResolver paletteBlockResolver) { - SourceTerrainSnapshot sourceTerrain = requiresSourceTerrainFill(start, configuredTerrain) - ? captureSourceTerrain(world, area, start, configuredTerrain) : null; - integrateTerrain(world, area, structureId, start, configuredTerrain, - paletteBlockResolver, sourceTerrain); - } - - static void integrateTerrain(WorldGenLevel world, BoundingBox area, String structureId, - StructureStart start, IrisStructureTerrain configuredTerrain, - NativeStructurePostProcessor.PaletteBlockResolver paletteBlockResolver, - SourceTerrainSnapshot sourceTerrain) { - IrisStructureTerrain terrain = configuredTerrain == null - ? new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE) - : configuredTerrain; - IrisStructureTerrainMode mode = terrain.resolvedMode(); - if (mode == IrisStructureTerrainMode.SOURCE) { - integrateSourceTerrain(world, area, start, sourceTerrain); - return; - } - if (mode == IrisStructureTerrainMode.PRESERVE) { - return; - } - if (mode == IrisStructureTerrainMode.VACUUM) { - return; - } - if (mode == IrisStructureTerrainMode.ENCASE) { - encasePieces(world, area, structureId, start, terrain, paletteBlockResolver); - return; - } - if (mode != IrisStructureTerrainMode.BORE && mode != IrisStructureTerrainMode.FORCE_CARVE) { - throw new IllegalStateException("Native structure terrain mode " + mode - + " is not implemented for '" + structureId + "'"); - } - IrisStructureCarveShape shape = mode == IrisStructureTerrainMode.BORE - ? IrisStructureCarveShape.BOX : terrain.resolvedShape(); - if (shape == IrisStructureCarveShape.BOX) { - carvePieceBoxes(world, area, start, terrain); - return; - } - carveOrganicColumns(world, area, organicCarve( - carveFootprint(start, Math.max(0, terrain.getHorizontalPadding()), - () -> world.getLevel().getStructureManager()), - terrain, shape, carveNoiseIdentity(world, structureId, start))); - } - - static SourceTerrainSnapshot captureSourceTerrain( - WorldGenLevel world, BoundingBox area, List targets) { - BitSet requiredLayers = new BitSet(area.getYSpan()); - boolean requiresSnapshot = false; - for (TerrainTarget target : targets) { - if (target != null && requiresSourceTerrainFill(target.start(), target.terrain())) { - requiresSnapshot = true; - markSourceTerrainLayers(area, target.start(), target.terrain(), requiredLayers); - } - } - return requiresSnapshot ? SourceTerrainSnapshot.capture(world, area, requiredLayers) : null; - } - - private static SourceTerrainSnapshot captureSourceTerrain( - WorldGenLevel world, BoundingBox area, StructureStart start, - IrisStructureTerrain configuredTerrain) { - BitSet requiredLayers = new BitSet(area.getYSpan()); - markSourceTerrainLayers(area, start, configuredTerrain, requiredLayers); - return SourceTerrainSnapshot.capture(world, area, requiredLayers); - } - - private static void markSourceTerrainLayers( - BoundingBox area, StructureStart start, IrisStructureTerrain configuredTerrain, - BitSet requiredLayers) { - if (!requiresSourceTerrainFill(start, configuredTerrain)) { - return; - } - TerrainAdjustment adjustment = start.getStructure().terrainAdaptation(); - for (StructurePiece piece : start.getPieces()) { - if (!isSourceRigidPiece(piece)) { - continue; - } - BoundingBox bounds = piece.getBoundingBox(); - long horizontalDistanceSquared = minimumHorizontalDistanceSquared(area, bounds); - if (adjustment == TerrainAdjustment.BURY) { - long remainingDistanceSquared = (long) SOURCE_BURY_VERTICAL_RADIUS - * SOURCE_BURY_VERTICAL_RADIUS - 1L - horizontalDistanceSquared * 4L; - if (remainingDistanceSquared < 0L) { - continue; - } - int verticalRadius = (int) Math.floor(Math.sqrt(remainingDistanceSquared)); - long groundY = bounds.minY(); - if (piece instanceof PoolElementStructurePiece poolPiece) { - groundY += poolPiece.getGroundLevelDelta(); - } - markLayers(area, requiredLayers, - groundY - verticalRadius, groundY + verticalRadius); - } else { - long remainingDistanceSquared = (long) SOURCE_ENCAPSULATE_RADIUS - * SOURCE_ENCAPSULATE_RADIUS - 1L - horizontalDistanceSquared; - if (remainingDistanceSquared < 0L) { - continue; - } - int verticalRadius = (int) Math.floor(Math.sqrt(remainingDistanceSquared)); - markLayers(area, requiredLayers, - (long) bounds.minY() - verticalRadius, - (long) bounds.maxY() + verticalRadius); - } - } - markSourceJunctionLayers(area, start, requiredLayers); - } - - private static void markSourceJunctionLayers( - BoundingBox area, StructureStart start, BitSet requiredLayers) { - Set anchors = sourceJunctionAnchors(start); - for (JunctionAnchor anchor : anchors) { - long deltaX = intervalDistance(area.minX(), area.maxX(), anchor.x(), anchor.x()); - long deltaZ = intervalDistance(area.minZ(), area.maxZ(), anchor.z(), anchor.z()); - long horizontalDistanceSquared = deltaX * deltaX + deltaZ * deltaZ; - long remainingDistanceSquared = (long) SOURCE_JUNCTION_RADIUS - * SOURCE_JUNCTION_RADIUS - 1L - horizontalDistanceSquared; - if (remainingDistanceSquared < 1L) { - continue; - } - int verticalRadius = (int) Math.floor(Math.sqrt(remainingDistanceSquared)); - markLayers(area, requiredLayers, - (long) anchor.y() - verticalRadius, (long) anchor.y() - 1L); - } - } - - private static long minimumHorizontalDistanceSquared(BoundingBox area, BoundingBox bounds) { - long deltaX = intervalDistance(area.minX(), area.maxX(), bounds.minX(), bounds.maxX()); - long deltaZ = intervalDistance(area.minZ(), area.maxZ(), bounds.minZ(), bounds.maxZ()); - return deltaX * deltaX + deltaZ * deltaZ; - } - - private static long intervalDistance(int firstMin, int firstMax, int secondMin, int secondMax) { - if (firstMax < secondMin) { - return (long) secondMin - firstMax; - } - if (firstMin > secondMax) { - return (long) firstMin - secondMax; - } - return 0L; - } - - private static void markLayers( - BoundingBox area, BitSet requiredLayers, long minimumY, long maximumY) { - long clippedMinimumY = Math.max(area.minY(), minimumY); - long clippedMaximumY = Math.min(area.maxY(), maximumY); - if (clippedMinimumY > clippedMaximumY) { - return; - } - int fromIndex = Math.toIntExact(clippedMinimumY - area.minY()); - int toIndex = Math.toIntExact(clippedMaximumY - area.minY() + 1L); - requiredLayers.set(fromIndex, toIndex); - } - - private static boolean requiresSourceTerrainFill( - StructureStart start, IrisStructureTerrain configuredTerrain) { - if (start == null || !start.isValid()) { - return false; - } - IrisStructureTerrain terrain = configuredTerrain == null - ? new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE) - : configuredTerrain; - if (terrain.resolvedMode() != IrisStructureTerrainMode.SOURCE) { - return false; - } - TerrainAdjustment adjustment = start.getStructure().terrainAdaptation(); - return adjustment == TerrainAdjustment.BURY - || adjustment == TerrainAdjustment.ENCAPSULATE; - } - - static boolean clearsLegacyTemplateAir(StructureStart start, IrisStructureTerrain terrain) { - if (start == null || !start.isValid() || terrain == null) { - return false; - } - IrisStructureTerrainMode mode = terrain.resolvedMode(); - return mode == IrisStructureTerrainMode.ENCASE - || mode == IrisStructureTerrainMode.SOURCE - && start.getStructure().terrainAdaptation() != TerrainAdjustment.NONE; - } - - private static void integrateSourceTerrain(WorldGenLevel world, BoundingBox area, - StructureStart start, - SourceTerrainSnapshot sourceTerrain) { - if (start == null || !start.isValid()) { - return; - } - TerrainAdjustment adjustment = start.getStructure().terrainAdaptation(); - if (adjustment == TerrainAdjustment.BURY) { - fillBuriedTerrain(world, area, start, requireSourceTerrain( - world, area, start, sourceTerrain)); - } else if (adjustment == TerrainAdjustment.ENCAPSULATE) { - fillEncapsulatedTerrain(world, area, start, requireSourceTerrain( - world, area, start, sourceTerrain)); - } - } - - private static SourceTerrainSnapshot requireSourceTerrain( - WorldGenLevel world, BoundingBox area, StructureStart start, - SourceTerrainSnapshot sourceTerrain) { - return sourceTerrain == null - ? captureSourceTerrain(world, area, start, null) : sourceTerrain; - } - - private static void fillBuriedTerrain(WorldGenLevel world, BoundingBox area, - StructureStart start, - SourceTerrainSnapshot sourceTerrain) { - BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); - for (StructurePiece piece : start.getPieces()) { - if (!isSourceRigidPiece(piece)) { - continue; - } - BoundingBox bounds = piece.getBoundingBox(); - int groundY = bounds.minY(); - if (piece instanceof PoolElementStructurePiece poolPiece) { - groundY += poolPiece.getGroundLevelDelta(); - } - int minX = Math.max(area.minX(), bounds.minX() - SOURCE_BURY_HORIZONTAL_RADIUS); - int maxX = Math.min(area.maxX(), bounds.maxX() + SOURCE_BURY_HORIZONTAL_RADIUS); - int minY = Math.max(area.minY(), groundY - SOURCE_BURY_VERTICAL_RADIUS); - int maxY = Math.min(area.maxY(), groundY + SOURCE_BURY_VERTICAL_RADIUS); - int minZ = Math.max(area.minZ(), bounds.minZ() - SOURCE_BURY_HORIZONTAL_RADIUS); - int maxZ = Math.min(area.maxZ(), bounds.maxZ() + SOURCE_BURY_HORIZONTAL_RADIUS); - for (int x = minX; x <= maxX; x++) { - int outX = outset(x, bounds.minX(), bounds.maxX()); - for (int z = minZ; z <= maxZ; z++) { - int outZ = outset(z, bounds.minZ(), bounds.maxZ()); - for (int y = minY; y <= maxY; y++) { - int vertical = Math.abs(y - groundY); - if (!insideBurialEnvelope(outX, vertical, outZ)) { - continue; - } - fillEncaseable(world, position.set(x, y, z), sourceTerrain); - } - } - } - } - fillSourceJunctionTerrain(world, area, start, position, sourceTerrain); - } - - private static void fillEncapsulatedTerrain(WorldGenLevel world, BoundingBox area, - StructureStart start, - SourceTerrainSnapshot sourceTerrain) { - BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); - for (StructurePiece piece : start.getPieces()) { - if (!isSourceRigidPiece(piece)) { - continue; - } - BoundingBox bounds = piece.getBoundingBox(); - int minX = Math.max(area.minX(), bounds.minX() - SOURCE_ENCAPSULATE_RADIUS); - int maxX = Math.min(area.maxX(), bounds.maxX() + SOURCE_ENCAPSULATE_RADIUS); - int minY = Math.max(area.minY(), bounds.minY() - SOURCE_ENCAPSULATE_RADIUS); - int maxY = Math.min(area.maxY(), bounds.maxY() + SOURCE_ENCAPSULATE_RADIUS); - int minZ = Math.max(area.minZ(), bounds.minZ() - SOURCE_ENCAPSULATE_RADIUS); - int maxZ = Math.min(area.maxZ(), bounds.maxZ() + SOURCE_ENCAPSULATE_RADIUS); - for (int x = minX; x <= maxX; x++) { - int outX = outset(x, bounds.minX(), bounds.maxX()); - for (int z = minZ; z <= maxZ; z++) { - int outZ = outset(z, bounds.minZ(), bounds.maxZ()); - for (int y = minY; y <= maxY; y++) { - int outY = outset(y, bounds.minY(), bounds.maxY()); - if (!insideEncapsulationEnvelope(outX, outY, outZ)) { - continue; - } - fillEncaseable(world, position.set(x, y, z), sourceTerrain); - } - } - } - } - fillSourceJunctionTerrain(world, area, start, position, sourceTerrain); - } - - static boolean insideBurialEnvelope(int outX, int verticalDistance, int outZ) { - long horizontalSquared = (long) outX * outX + (long) outZ * outZ; - long verticalSquared = (long) verticalDistance * verticalDistance; - return horizontalSquared * 4L + verticalSquared - < (long) SOURCE_BURY_VERTICAL_RADIUS * SOURCE_BURY_VERTICAL_RADIUS; - } - - static boolean insideEncapsulationEnvelope(int outX, int outY, int outZ) { - return (long) outX * outX + (long) outY * outY + (long) outZ * outZ - < (long) SOURCE_ENCAPSULATE_RADIUS * SOURCE_ENCAPSULATE_RADIUS; - } - - static boolean isSourceRigidPiece(StructurePiece piece) { - if (piece == null) { - return false; - } - return !(piece instanceof PoolElementStructurePiece poolPiece) - || poolPiece.getElement().getProjection() == StructureTemplatePool.Projection.RIGID; - } - - static boolean insideSourceJunctionEnvelope(int deltaX, int deltaY, int deltaZ) { - if (deltaY >= 0) { - return false; - } - return (long) deltaX * deltaX + (long) deltaY * deltaY + (long) deltaZ * deltaZ - < (long) SOURCE_JUNCTION_RADIUS * SOURCE_JUNCTION_RADIUS; - } - - private static void fillSourceJunctionTerrain(WorldGenLevel world, BoundingBox area, - StructureStart start, - BlockPos.MutableBlockPos position, - SourceTerrainSnapshot sourceTerrain) { - Set anchors = sourceJunctionAnchors(start); - for (JunctionAnchor anchor : anchors) { - int minX = Math.max(area.minX(), anchor.x() - SOURCE_JUNCTION_RADIUS + 1); - int maxX = Math.min(area.maxX(), anchor.x() + SOURCE_JUNCTION_RADIUS - 1); - int minY = Math.max(area.minY(), anchor.y() - SOURCE_JUNCTION_RADIUS + 1); - int maxY = Math.min(area.maxY(), anchor.y() - 1); - int minZ = Math.max(area.minZ(), anchor.z() - SOURCE_JUNCTION_RADIUS + 1); - int maxZ = Math.min(area.maxZ(), anchor.z() + SOURCE_JUNCTION_RADIUS - 1); - for (int x = minX; x <= maxX; x++) { - int deltaX = x - anchor.x(); - for (int z = minZ; z <= maxZ; z++) { - int deltaZ = z - anchor.z(); - for (int y = minY; y <= maxY; y++) { - if (insideSourceJunctionEnvelope(deltaX, y - anchor.y(), deltaZ)) { - fillEncaseable(world, position.set(x, y, z), sourceTerrain); - } - } - } - } - } - } - - private static Set sourceJunctionAnchors(StructureStart start) { - Set anchors = new HashSet<>(); - for (StructurePiece piece : start.getPieces()) { - if (!(piece instanceof PoolElementStructurePiece poolPiece)) { - continue; - } - for (JigsawJunction junction : poolPiece.getJunctions()) { - anchors.add(new JunctionAnchor( - junction.getSourceX(), junction.getSourceGroundY(), junction.getSourceZ())); - } - } - return anchors; - } - - private static int outset(int value, int minimum, int maximum) { - if (value < minimum) { - return minimum - value; - } - return Math.max(0, value - maximum); - } - - private static void fillEncaseable(WorldGenLevel world, BlockPos position, - SourceTerrainSnapshot sourceTerrain) { - if (isEncaseable(world.getBlockState(position))) { - world.setBlock(position, sourceEncaseBlock(world, position, sourceTerrain), 2); - } - } - - static BlockState sourceEncaseBlock(WorldGenLevel world, BlockPos position) { - int minX = Math.subtractExact(position.getX(), SOURCE_MATERIAL_SAMPLE_RADIUS); - int minZ = Math.subtractExact(position.getZ(), SOURCE_MATERIAL_SAMPLE_RADIUS); - int maxX = Math.addExact(position.getX(), SOURCE_MATERIAL_SAMPLE_RADIUS); - int maxZ = Math.addExact(position.getZ(), SOURCE_MATERIAL_SAMPLE_RADIUS); - BoundingBox sampleArea = new BoundingBox(minX, position.getY(), minZ, - maxX, position.getY(), maxZ); - BitSet requiredLayers = new BitSet(1); - requiredLayers.set(0); - SourceTerrainSnapshot sourceTerrain = SourceTerrainSnapshot.capture( - world, sampleArea, requiredLayers); - return sourceEncaseBlock(world, position, sourceTerrain); - } - - static BlockState sourceEncaseBlock(WorldGenLevel world, BlockPos position, - SourceTerrainSnapshot sourceTerrain) { - BlockPos.MutableBlockPos probe = new BlockPos.MutableBlockPos(); - for (int distance = 1; distance <= SOURCE_MATERIAL_SAMPLE_RADIUS; distance++) { - BlockState sampled = sourceTerrain.stateAt(probe.set( - position.getX() - distance, position.getY(), position.getZ())); - if (sampled != null) { - return sampled; - } - sampled = sourceTerrain.stateAt(probe.set( - position.getX() + distance, position.getY(), position.getZ())); - if (sampled != null) { - return sampled; - } - sampled = sourceTerrain.stateAt(probe.set( - position.getX(), position.getY(), position.getZ() - distance)); - if (sampled != null) { - return sampled; - } - sampled = sourceTerrain.stateAt(probe.set( - position.getX(), position.getY(), position.getZ() + distance)); - if (sampled != null) { - return sampled; - } - } - return defaultEncaseBlock(world, position.getY()); - } - - private static BlockState sourceTerrainBlock(BlockState state) { - if (!state.isSolid() || NativeStructureVegetationClearer.isTreeBlock(state)) { - return null; - } - return VANILLA_SOURCE_TERRAIN_BLOCKS.contains(state.getBlock()) - || state.is(BlockTags.BASE_STONE_OVERWORLD) - || state.is(BlockTags.BASE_STONE_NETHER) - || state.is(BlockTags.SUBSTRATE_OVERWORLD) - || state.is(BlockTags.DIRT) - || state.is(BlockTags.SAND) - || state.is(BlockTags.TERRACOTTA) - || state.is(BlockTags.MUD) - || state.is(BlockTags.MOSS_BLOCKS) - || state.is(BlockTags.GRASS_BLOCKS) - || state.is(BlockTags.NYLIUM) - || state.is(BlockTags.SNOW) - || state.is(BlockTags.ICE) - || state.is(BlockTags.CORAL_BLOCKS) - || state.is(BlockTags.SOUL_FIRE_BASE_BLOCKS) - ? state : null; - } - - static List contentPieceBounds(StructureStart start) { - List bounds = new ArrayList<>(start.getPieces().size()); - for (StructurePiece piece : start.getPieces()) { - bounds.add(piece.getBoundingBox()); - } - return List.copyOf(bounds); - } - - /** - * Per-column occupancy of the whole start, cached because a single structure spans many chunks and - * every one of them carves against the same shrinkwrapped footprint. - */ - static StructureCarvingFootprint carveFootprint(StructureStart start, int horizontalPadding, - Supplier templates) { - CarveFootprintKey key = new CarveFootprintKey(start, horizontalPadding); - StructureCarvingFootprint cached = cachedCarveFootprint(key); - if (cached != null) { - return cached; - } - CompletableFuture build = new CompletableFuture<>(); - CompletableFuture active = CARVE_FOOTPRINT_BUILDS.putIfAbsent(key, build); - if (active != null) { - return awaitCarveFootprint(active); - } - // Close the check-then-claim window: a racer whose cache check missed before the - // previous builder cached can claim the build slot after that builder retired it, - // and would rebuild a second instance without this re-check. - StructureCarvingFootprint published = cachedCarveFootprint(key); - if (published != null) { - build.complete(published); - CARVE_FOOTPRINT_BUILDS.remove(key, build); - return published; - } - try { - StructureCarvingFootprint footprint = StructureCarvingFootprint.fromColumns( - sink -> emitCarveColumns(start, templates, sink), horizontalPadding, MAX_CARVE_COLUMNS); - if (footprint == null) { - throw new IllegalStateException("Native structure carve footprint is empty or exceeds " - + MAX_CARVE_COLUMNS + " columns"); - } - cacheCarveFootprint(key, footprint); - build.complete(footprint); - return footprint; - } catch (RuntimeException | Error error) { - build.completeExceptionally(error); - throw error; - } finally { - CARVE_FOOTPRINT_BUILDS.remove(key, build); - } - } - - static int cachedCarveFootprintCells() { - synchronized (CARVE_FOOTPRINTS) { - cachedCarveCells = liveCarveCells(); - return cachedCarveCells; - } - } - - private static int liveCarveCells() { - int total = 0; - for (Map perStart : CARVE_FOOTPRINTS.values()) { - for (CachedCarveFootprint cached : perStart.values()) { - total += cached.cells(); - } - } - return total; - } - - static int maximumCachedCarveFootprintCells() { - return MAX_CACHED_CARVE_CELLS; - } - - private static StructureCarvingFootprint cachedCarveFootprint(CarveFootprintKey key) { - synchronized (CARVE_FOOTPRINTS) { - Map perStart = CARVE_FOOTPRINTS.get(key.start()); - CachedCarveFootprint cached = perStart == null ? null : perStart.get(key.padding()); - return cached == null ? null : cached.footprint(); - } - } - - private static StructureCarvingFootprint awaitCarveFootprint( - CompletableFuture future) { - return NativeBuildFutures.awaitBuild(future, "Native structure carve footprint build"); - } - - private static void cacheCarveFootprint(CarveFootprintKey key, - StructureCarvingFootprint footprint) { - int cells = Math.multiplyExact(footprint.width(), footprint.depth()); - synchronized (CARVE_FOOTPRINTS) { - // Weak keys expunge silently as the GC drops retired starts; re-derive the live - // total so the cell budget tracks reality instead of drifting. - cachedCarveCells = liveCarveCells(); - Map perStart = - CARVE_FOOTPRINTS.computeIfAbsent(key.start(), ignored -> new LinkedHashMap<>(4)); - CachedCarveFootprint previous = perStart.remove(key.padding()); - if (previous != null) { - cachedCarveCells -= previous.cells(); - } - Iterator>> eviction = - CARVE_FOOTPRINTS.entrySet().iterator(); - while (cachedCarveCells + cells > MAX_CACHED_CARVE_CELLS && eviction.hasNext()) { - Map.Entry> victim = eviction.next(); - if (victim.getKey() == key.start()) { - continue; - } - for (CachedCarveFootprint evicted : victim.getValue().values()) { - cachedCarveCells -= evicted.cells(); - } - eviction.remove(); - } - perStart.put(key.padding(), new CachedCarveFootprint(footprint, cells)); - cachedCarveCells += cells; - } - } - - static OrganicCarve organicCarve(StructureCarvingFootprint footprint, IrisStructureTerrain terrain, - IrisStructureCarveShape shape, long identity) { - double strength = terrain.resolvedErosionStrength(); - double lobeStrength = terrain.resolvedLobeStrength(); - RNG noiseRng = new RNG(identity); - CNG blob = null; - CNG ceilingRoll = null; - CNG floorRoll = null; - CNG lobe = null; - if (shape == IrisStructureCarveShape.ERODED && strength > 0D) { - blob = CNG.signature(noiseRng); - ceilingRoll = CNG.signature(noiseRng.nextParallelRNG(CARVE_CEILING_ROLL_SIGNATURE)); - floorRoll = CNG.signature(noiseRng.nextParallelRNG(CARVE_FLOOR_ROLL_SIGNATURE)); - } - if (shape == IrisStructureCarveShape.ERODED && lobeStrength > 0D) { - // A plain single octave channel: the fractured signature noise has no usable low frequency band. - lobe = new CNG(noiseRng.nextParallelRNG(CARVE_LOBE_SIGNATURE), 1D, 1); - } - return new OrganicCarve(footprint, shape, - Math.max(0, terrain.getHorizontalPadding()), - Math.max(0, terrain.getCeilingPadding()), - Math.max(0, terrain.getFloorPadding()), - strength, terrain.resolvedErosionFrequency(), blob, ceilingRoll, floorRoll, - lobe, terrain.resolvedLobeFrequency(), lobeStrength); - } - - static void carveOrganicColumns(WorldGenLevel world, BoundingBox area, OrganicCarve carve) { - StructureCarvingFootprint footprint = carve.footprint(); - int minX = Math.max(area.minX(), footprint.minX()); - int maxX = Math.min(area.maxX(), footprint.maxX()); - int minZ = Math.max(area.minZ(), footprint.minZ()); - int maxZ = Math.min(area.maxZ(), footprint.maxZ()); - if (minX > maxX || minZ > maxZ) { - return; - } - boolean eroded = carve.blob() != null; - BlockState air = Blocks.AIR.defaultBlockState(); - BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); - for (int z = minZ; z <= maxZ; z++) { - for (int x = minX; x <= maxX; x++) { - int index = footprint.indexAt(x, z); - long horizontalDistanceSquared = footprint.distanceSquaredAt(index); - double sideReach = StructureCarveEnvelope.lobedSideReach(carve.lobe(), - carve.lobeFrequency(), carve.lobeStrength(), x, z, carve.horizontalPadding()); - double sideReachSquared = sideReach * sideReach; - if (horizontalDistanceSquared > sideReachSquared) { - continue; - } - double normalizedHorizontal = sideReachSquared == 0D - ? 0D : horizontalDistanceSquared / sideReachSquared; - int sourceMinY = footprint.sourceMinYAt(index); - int sourceMaxY = footprint.sourceMaxYAt(index); - double upReach = eroded - ? StructureCarveEnvelope.lobedUpReach(carve.lobe(), carve.lobeFrequency(), - carve.lobeStrength(), x, z, - StructureCarveEnvelope.erodedUpReach(carve.ceilingRoll(), - carve.frequency(), carve.strength(), x, z, - carve.ceilingPadding())) - : Math.max(1D, carve.ceilingPadding()); - double floorReach = eroded - ? StructureCarveEnvelope.erodedDownReach(carve.floorRoll(), carve.frequency(), - carve.strength(), x, z, carve.floorPadding()) - : carve.floorPadding(); - int columnMinY = Math.max(area.minY(), sourceMinY - (int) Math.floor(floorReach)); - int columnMaxY = Math.min(area.maxY(), - sourceMaxY + (eroded ? (int) Math.ceil(upReach) : carve.ceilingPadding())); - double downReach = Math.max(1D, floorReach); - for (int y = columnMinY; y <= columnMaxY; y++) { - double normalizedVertical = StructureCarveEnvelope.normalizedVerticalDistance( - y, sourceMinY, sourceMaxY, upReach, downReach); - double distanceSquared = normalizedHorizontal - + normalizedVertical * normalizedVertical; - if (distanceSquared > 1D) { - continue; - } - if (distanceSquared > 0D && eroded) { - double noise = carve.blob().fitDouble(0D, 1D, - x * carve.frequency(), y * carve.frequency(), z * carve.frequency()); - if (!StructureCarveEnvelope.shouldCarveOverboreCell( - carve.shape(), distanceSquared, noise, carve.strength())) { - continue; - } - } - world.setBlock(position.set(x, y, z), air, 2); - } - } - } - } - - private static boolean emitCarveColumns(StructureStart start, - Supplier templates, - StructureCarvingFootprint.ColumnSink sink) { - for (StructurePiece piece : start.getPieces()) { - BoundingBox bounds = piece.getBoundingBox(); - if (!(piece instanceof PoolElementStructurePiece poolPiece) - || !emitTemplateColumns(pieceTemplates(poolPiece, templates), - poolPiece.getPosition(), poolPiece.getRotation(), bounds, sink)) { - emitBoxColumns(bounds, sink); - } - } - return true; - } - - /** - * Derives per-column vertical extents from the complement of the template's air and structure-void - * cells, so a carve tracks the actual silhouette instead of the piece's rectangular bounding box. - */ - static boolean emitTemplateColumns(List templates, BlockPos position, - Rotation rotation, BoundingBox bounds, - StructureCarvingFootprint.ColumnSink sink) { - if (templates.isEmpty()) { - return false; - } - int width = bounds.getXSpan(); - int depth = bounds.getZSpan(); - long cells = (long) width * depth * bounds.getYSpan(); - if (cells < 1L || cells > MAX_TEMPLATE_OCCUPANCY_CELLS) { - return false; - } - StructurePlaceSettings settings = new StructurePlaceSettings().setRotation(rotation); - boolean[] voidCells = null; - for (StructureTemplate template : templates) { - boolean[] templateVoid = new boolean[(int) cells]; - for (Block ignored : TEMPLATE_VOID_BLOCKS) { - for (StructureTemplate.StructureBlockInfo info - : template.filterBlocks(position, settings, ignored)) { - BlockPos voidPosition = info.pos(); - if (bounds.isInside(voidPosition)) { - templateVoid[templateCellIndex(bounds, width, depth, - voidPosition.getX(), voidPosition.getY(), voidPosition.getZ())] = true; - } - } - } - if (voidCells == null) { - voidCells = templateVoid; - continue; - } - for (int cell = 0; cell < voidCells.length; cell++) { - voidCells[cell] &= templateVoid[cell]; - } - } - for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { - for (int x = bounds.minX(); x <= bounds.maxX(); x++) { - int minY = Integer.MAX_VALUE; - int maxY = Integer.MIN_VALUE; - for (int y = bounds.minY(); y <= bounds.maxY(); y++) { - if (voidCells[templateCellIndex(bounds, width, depth, x, y, z)]) { - continue; - } - if (minY == Integer.MAX_VALUE) { - minY = y; - } - maxY = y; - } - if (minY != Integer.MAX_VALUE) { - sink.column(x, z, minY, maxY); - } - } - } - return true; - } - - private static void emitBoxColumns(BoundingBox bounds, StructureCarvingFootprint.ColumnSink sink) { - for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { - for (int x = bounds.minX(); x <= bounds.maxX(); x++) { - sink.column(x, z, bounds.minY(), bounds.maxY()); - } - } - } - - private static int templateCellIndex(BoundingBox bounds, int width, int depth, - int x, int y, int z) { - return ((y - bounds.minY()) * depth + z - bounds.minZ()) * width + x - bounds.minX(); - } - - private static List pieceTemplates(PoolElementStructurePiece poolPiece, - Supplier templates) { - List resolved = new ArrayList<>(1); - collectElementTemplates(poolPiece.getElement(), templates, resolved); - return resolved; - } - - private static void collectElementTemplates(StructurePoolElement element, - Supplier templates, - List resolved) { - if (element instanceof ListPoolElement listElement) { - for (StructurePoolElement child : listElement.getElements()) { - collectElementTemplates(child, templates, resolved); - } - return; - } - if (element instanceof SinglePoolElement singleElement) { - resolved.add(NativeStructureReflection.resolveTemplate(singleElement, templates)); - } - } - - private static long carveNoiseIdentity(WorldGenLevel world, String structureId, - StructureStart start) { - return world.getSeed() - ^ ((long) start.getChunkPos().x() * 341873128712L) - ^ ((long) start.getChunkPos().z() * 132897987541L) - ^ (structureId == null ? 0 : structureId.hashCode()); - } - - private static void encasePieces(WorldGenLevel world, BoundingBox area, String structureId, - StructureStart start, IrisStructureTerrain terrain, - NativeStructurePostProcessor.PaletteBlockResolver paletteBlockResolver) { - IrisMaterialPalette palette = terrain.getEncasePalette(); - RNG rng = null; - if (palette != null) { - Objects.requireNonNull(paletteBlockResolver, - "Native structure encase palette requires a platform block resolver"); - rng = new RNG(world.getSeed() ^ (structureId == null ? 0 : structureId.hashCode())); - } - BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); - for (BoundingBox bounds : contentPieceBounds(start)) { - BoundingBox shell = paddedPieceArea(area, bounds, terrain); - if (shell == null) { - continue; - } - for (int x = shell.minX(); x <= shell.maxX(); x++) { - for (int z = shell.minZ(); z <= shell.maxZ(); z++) { - for (int y = shell.minY(); y <= shell.maxY(); y++) { - BlockState existing = world.getBlockState(position.set(x, y, z)); - if (!isEncaseable(existing)) { - continue; - } - BlockState fill = palette == null - ? defaultEncaseBlock(world, y) - : Objects.requireNonNull( - paletteBlockResolver.resolve(palette, rng, x, y, z), - "Encase palette returned no block for " + structureId + " at " - + x + "," + y + "," + z); - world.setBlock(position, fill, 2); - } - } - } - } - } - - static boolean isEncaseable(BlockState state) { - return state.isAir() || !state.getFluidState().isEmpty(); - } - - static BlockState defaultEncaseBlock(int y) { - return y < 0 ? Blocks.DEEPSLATE.defaultBlockState() : Blocks.STONE.defaultBlockState(); - } - - static BlockState defaultEncaseBlock(WorldGenLevel world, int y) { - ServerLevel level = world == null ? null : world.getLevel(); - if (level == null) { - return defaultEncaseBlock(y); - } - Holder dimensionType = level.dimensionTypeRegistration(); - ResourceKey dimensionTypeKey = dimensionType.unwrapKey().orElse(null); - return defaultEncaseBlock(level.dimension(), dimensionTypeKey, dimensionType.value(), y); - } - - static BlockState defaultEncaseBlock(ResourceKey dimension, int y) { - return defaultEncaseBlock(dimension, null, null, y); - } - - static BlockState defaultEncaseBlock(ResourceKey dimension, - ResourceKey dimensionTypeKey, - DimensionType dimensionType, int y) { - if (Level.NETHER.equals(dimension)) { - return Blocks.NETHERRACK.defaultBlockState(); - } - if (Level.END.equals(dimension)) { - return Blocks.END_STONE.defaultBlockState(); - } - if (BuiltinDimensionTypes.NETHER.equals(dimensionTypeKey) - || dimensionType != null && dimensionType.hasCeiling() && !dimensionType.hasSkyLight()) { - return Blocks.NETHERRACK.defaultBlockState(); - } - if (BuiltinDimensionTypes.END.equals(dimensionTypeKey) - || dimensionType != null && (dimensionType.hasEnderDragonFight() - || dimensionType.hasEndFlashes())) { - return Blocks.END_STONE.defaultBlockState(); - } - return defaultEncaseBlock(y); - } - - private static void carvePieceBoxes(WorldGenLevel world, BoundingBox area, StructureStart start, - IrisStructureTerrain terrain) { - BlockState air = Blocks.AIR.defaultBlockState(); - BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); - for (BoundingBox bounds : contentPieceBounds(start)) { - BoundingBox carve = paddedPieceArea(area, bounds, terrain); - if (carve == null) { - continue; - } - for (int x = carve.minX(); x <= carve.maxX(); x++) { - for (int z = carve.minZ(); z <= carve.maxZ(); z++) { - for (int y = carve.minY(); y <= carve.maxY(); y++) { - world.setBlock(position.set(x, y, z), air, 2); - } - } - } - } - } - - private static BoundingBox paddedPieceArea(BoundingBox area, BoundingBox bounds, - IrisStructureTerrain terrain) { - int horizontalPadding = Math.max(0, terrain.getHorizontalPadding()); - int minX = Math.max(area.minX(), bounds.minX() - horizontalPadding); - int minY = Math.max(area.minY(), bounds.minY() - Math.max(0, terrain.getFloorPadding())); - int minZ = Math.max(area.minZ(), bounds.minZ() - horizontalPadding); - int maxX = Math.min(area.maxX(), bounds.maxX() + horizontalPadding); - int maxY = Math.min(area.maxY(), bounds.maxY() + Math.max(0, terrain.getCeilingPadding())); - int maxZ = Math.min(area.maxZ(), bounds.maxZ() + horizontalPadding); - if (minX > maxX || minY > maxY || minZ > maxZ) { - return null; - } - return new BoundingBox(minX, minY, minZ, maxX, maxY, maxZ); - } - - static void clearLegacyTemplateAir(WorldGenLevel world, BoundingBox area, - StructureStart start, - Supplier templates) { - for (StructurePiece piece : start.getPieces()) { - if (!(piece instanceof PoolElementStructurePiece poolPiece) - || poolPiece.getElement().getProjection() != StructureTemplatePool.Projection.RIGID - || !intersects(poolPiece.getBoundingBox(), area)) { - continue; - } - int groundY = poolPiece.getBoundingBox().minY() + poolPiece.getGroundLevelDelta(); - StructurePlaceSettings settings = new StructurePlaceSettings() - .setRotation(poolPiece.getRotation()) - .setBoundingBox(area); - clearLegacyTemplateAir(world, poolPiece.getElement(), poolPiece.getPosition(), - groundY, settings, templates); - } - } - - private static void clearLegacyTemplateAir(WorldGenLevel world, StructurePoolElement element, - BlockPos position, int groundY, - StructurePlaceSettings settings, - Supplier templates) { - if (element instanceof ListPoolElement listElement) { - for (StructurePoolElement child : listElement.getElements()) { - clearLegacyTemplateAir(world, child, position, groundY, settings, templates); - } - return; - } - if (!(element instanceof LegacySinglePoolElement legacyElement)) { - return; - } - StructureTemplate template = NativeStructureReflection.resolveTemplate(legacyElement, templates); - clearTemplateAir(world, template, position, groundY, settings); - } - - static void clearTemplateAir(WorldGenLevel world, StructureTemplate template, - BlockPos position, int groundY, - StructurePlaceSettings settings) { - List airBlocks = template.filterBlocks( - position, settings, Blocks.AIR); - BlockState air = Blocks.AIR.defaultBlockState(); - for (StructureTemplate.StructureBlockInfo airBlock : airBlocks) { - BlockPos airPosition = airBlock.pos(); - BlockState existingState = world.getBlockState(airPosition); - if (shouldClearLegacyAir( - airPosition.getY(), groundY, existingState.isAir()) - && !NativeStructureVegetationClearer.isTreeBlock(existingState)) { - world.setBlock(airPosition, air, 2); - } - } - } - - static boolean shouldClearLegacyAir(int airY, int groundY, boolean existingAir) { - return airY >= groundY && !existingAir; - } - - static boolean intersects(BoundingBox first, BoundingBox second) { - return first.maxX() >= second.minX() && first.minX() <= second.maxX() - && first.maxY() >= second.minY() && first.minY() <= second.maxY() - && first.maxZ() >= second.minZ() && first.minZ() <= second.maxZ(); - } - - // StructureStart has no value equality, so the key pins the exact start instance a chunk carves against. - private record CarveFootprintKey(StructureStart start, int padding) { - } - - private record CachedCarveFootprint(StructureCarvingFootprint footprint, int cells) { - } - - private record JunctionAnchor(int x, int y, int z) { - } - - static final class SourceTerrainSnapshot { - private final BoundingBox area; - private final int width; - private final BlockState[][] statesByLayer; - private final int sampledCells; - - private SourceTerrainSnapshot(BoundingBox area, int width, - BlockState[][] statesByLayer, int sampledCells) { - this.area = area; - this.width = width; - this.statesByLayer = statesByLayer; - this.sampledCells = sampledCells; - } - - static SourceTerrainSnapshot capture( - WorldGenLevel world, BoundingBox area, BitSet requiredLayers) { - Objects.requireNonNull(world, "Source terrain snapshot requires a generation level"); - Objects.requireNonNull(area, "Source terrain snapshot requires writable bounds"); - Objects.requireNonNull(requiredLayers, "Source terrain snapshot requires sampled layers"); - int width = area.getXSpan(); - int depth = area.getZSpan(); - int height = area.getYSpan(); - int horizontalCells = Math.multiplyExact(width, depth); - BlockState[][] statesByLayer = new BlockState[height][]; - int sampledCells = 0; - BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); - for (int layer = requiredLayers.nextSetBit(0); - layer >= 0; layer = requiredLayers.nextSetBit(layer + 1)) { - if (layer >= height) { - throw new IllegalArgumentException( - "Source terrain snapshot layer exceeds writable bounds: " + layer); - } - BlockState[] states = new BlockState[horizontalCells]; - statesByLayer[layer] = states; - sampledCells = Math.addExact(sampledCells, horizontalCells); - int y = Math.addExact(area.minY(), layer); - for (int z = area.minZ(); z <= area.maxZ(); z++) { - for (int x = area.minX(); x <= area.maxX(); x++) { - int index = (z - area.minZ()) * width + x - area.minX(); - states[index] = sourceTerrainBlock( - world.getBlockState(position.set(x, y, z))); - } - } - } - return new SourceTerrainSnapshot(new BoundingBox( - area.minX(), area.minY(), area.minZ(), - area.maxX(), area.maxY(), area.maxZ()), width, - statesByLayer, sampledCells); - } - - BlockState stateAt(BlockPos position) { - if (!area.isInside(position)) { - return null; - } - BlockState[] states = statesByLayer[position.getY() - area.minY()]; - if (states == null) { - return null; - } - int index = (position.getZ() - area.minZ()) * width - + position.getX() - area.minX(); - return states[index]; - } - - int sampledCells() { - return sampledCells; - } - } - - record OrganicCarve(StructureCarvingFootprint footprint, IrisStructureCarveShape shape, - int horizontalPadding, int ceilingPadding, int floorPadding, - double strength, double frequency, CNG blob, CNG ceilingRoll, CNG floorRoll, - CNG lobe, double lobeFrequency, double lobeStrength) { - } - - public record TerrainTarget(String structureId, StructureStart start, - IrisStructureTerrain terrain) { - } -} diff --git a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureVerticalPlacer.java b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureVerticalPlacer.java index 5076d3ad5..3404edbf4 100644 --- a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureVerticalPlacer.java +++ b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureVerticalPlacer.java @@ -1,10 +1,8 @@ package art.arcane.iris.nativegen; +import art.arcane.iris.engine.framework.NativeStartPlacement; import art.arcane.iris.engine.framework.StructureVerticalBounds; -import art.arcane.iris.engine.object.structure.IrisStructureYBand; import art.arcane.iris.spi.IrisLogging; -import art.arcane.volmlib.util.math.RNG; -import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.LevelHeightAccessor; import net.minecraft.world.level.levelgen.structure.BoundingBox; import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece; @@ -25,33 +23,47 @@ import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.function.IntBinaryOperator; +import java.util.function.IntSupplier; public final class NativeStructureVerticalPlacer { private static final String DESERT_PYRAMID_ID = "minecraft:desert_pyramid"; private static final String JUNGLE_PYRAMID_ID = "minecraft:jungle_pyramid"; - private static final int MAX_BURIAL_COLUMNS = 2_000_000; private static final int MONUMENT_BASE_BELOW_SEA_LEVEL = 24; private static final String OCEAN_MONUMENT_ID = "minecraft:monument"; - private static final int UNDERGROUND_SURFACE_CLEARANCE = 1; private NativeStructureVerticalPlacer() { } - public static int applyVerticalPlacement(StructureStart start, String structureId, int requestedOffset, + /** + * Moves the platform's start {@code shift} blocks up (negative: down), as the modules asked, inside the world: an + * ocean monument and a desert or jungle temple are aligned first (to the sea level, to the terrain) and shifted from + * there. Returns how far the start moved. + */ + public static int applyVerticalPlacement(StructureStart start, String structureId, int shift, int seaLevel, int worldMinY, int worldMaxYExclusive, - boolean underground, boolean preserveSourceY, - IrisStructureYBand yBand, IntBinaryOperator surfaceHeight) { if (isOceanMonument(start, structureId)) { return alignOceanMonumentToSeaLevel( - start, requestedOffset, seaLevel, worldMinY, worldMaxYExclusive); + start, shift, seaLevel, worldMinY, worldMaxYExclusive); } if (isAdjustedScatteredStructure(start, structureId)) { return alignScatteredStructureToSurface( - start, structureId, requestedOffset, worldMinY, worldMaxYExclusive, surfaceHeight); + start, structureId, shift, worldMinY, worldMaxYExclusive, surfaceHeight); } - return applyVerticalShift(start, requestedOffset, worldMinY, worldMaxYExclusive, - underground, preserveSourceY, yBand, surfaceHeight); + return applyVerticalShift(start, structureId, shift, worldMinY, worldMaxYExclusive); + } + + /** + * The platform start as the modules see it before it is published: its bounds, whether the platform generates it + * underground and whether the host aligns it itself. + */ + public static NativeStartPlacement placementOf(StructureStart start, String structureId, boolean underground, + int bottomY, IntBinaryOperator surfaceHeight) { + BoundingBox bounds = start.getBoundingBox(); + return new NativeStartPlacement(structureId, start.getChunkPos().x(), start.getChunkPos().z(), + bounds.minX(), bounds.minY(), bounds.minZ(), bounds.maxX(), bounds.maxY(), bounds.maxZ(), + underground, isOceanMonument(start, structureId) || isAdjustedScatteredStructure(start, structureId), + bottomY, surfaceHeight); } public static StructureStart relocateToMinY(StructureStart start, Structure source, int targetMinY, @@ -115,15 +127,16 @@ public final class NativeStructureVerticalPlacer { return offsetY; } - public static int applyVerticalShift(StructureStart start, int requestedOffset, int worldMinY, - int worldMaxYExclusive, boolean underground, - boolean preserveSourceY, IrisStructureYBand yBand, - IntBinaryOperator surfaceHeight) { + /** Moves the start {@code shift} blocks, less where it would leave the world. Returns how far it moved. */ + public static int applyVerticalShift(StructureStart start, String structureId, int shift, int worldMinY, + int worldMaxYExclusive) { BoundingBox bounds = start.getBoundingBox(); - int resolvedOffset = resolveShiftOffset(start, bounds, requestedOffset, worldMinY, - worldMaxYExclusive, underground, preserveSourceY, yBand, surfaceHeight); int offsetY = StructureVerticalBounds.clampOffset( - bounds.minY(), bounds.maxY(), resolvedOffset, worldMinY, worldMaxYExclusive); + bounds.minY(), bounds.maxY(), shift, worldMinY, worldMaxYExclusive); + if (offsetY != shift) { + IrisLogging.warn("Native structure " + structureId + " at " + bounds.minX() + "," + bounds.minZ() + + " clamped to the world's height: wanted a shift of " + shift + ", used " + offsetY); + } if (offsetY == 0) { return 0; } @@ -131,23 +144,6 @@ public final class NativeStructureVerticalPlacer { return offsetY; } - private static int resolveShiftOffset(StructureStart start, BoundingBox bounds, int requestedOffset, - int worldMinY, int worldMaxYExclusive, boolean underground, - boolean preserveSourceY, IrisStructureYBand yBand, - IntBinaryOperator surfaceHeight) { - if (preserveSourceY) { - return requestedOffset; - } - if (yBand != null) { - return resolveYBandOffset(bounds, yBand, start.getChunkPos()); - } - if (underground) { - return resolveBuriedOffset( - bounds, requestedOffset, worldMinY, worldMaxYExclusive, surfaceHeight); - } - return requestedOffset; - } - static int alignOceanMonumentToSeaLevel(StructureStart start, int configuredOffset, int seaLevel, int worldMinY, int worldMaxYExclusive) { OceanMonumentPieces.MonumentBuilding building = requireOceanMonumentBuilding(start); @@ -169,15 +165,16 @@ public final class NativeStructureVerticalPlacer { return offsetY; } - static void ensureMonumentSeaLevelAlignment(StructureStart start, String structureId, - int configuredOffset, int seaLevel, - int worldMinY, int worldMaxYExclusive) { + /** Keeps an ocean monument at the sea level, shifted by {@code shift}, before each chunk places its pieces. */ + public static void ensureMonumentSeaLevelAlignment(StructureStart start, String structureId, + IntSupplier shift, int seaLevel, + int worldMinY, int worldMaxYExclusive) { if (!isOceanMonument(start, structureId)) { return; } synchronized (start) { alignOceanMonumentToSeaLevel( - start, configuredOffset, seaLevel, worldMinY, worldMaxYExclusive); + start, shift.getAsInt(), seaLevel, worldMinY, worldMaxYExclusive); } } @@ -327,58 +324,4 @@ public final class NativeStructureVerticalPlacer { } return List.copyOf(pieces); } - - static int resolveYBandOffset(BoundingBox bounds, IrisStructureYBand yBand, ChunkPos startChunk) { - Objects.requireNonNull(bounds, "Native structure bounds must not be null"); - Objects.requireNonNull(startChunk, "Native structure Y band requires a start chunk"); - int target = yBandTargetMidpointY( - bounds.minY(), bounds.maxY(), yBand.resolvedMin(), yBand.resolvedMax(), startChunk); - return Math.subtractExact(target, midpointY(bounds.minY(), bounds.maxY())); - } - - static int yBandTargetMidpointY(int minY, int maxY, int bandMin, int bandMax, ChunkPos startChunk) { - int height = Math.subtractExact(maxY, minY); - int lowest = Math.addExact(bandMin, height / 2); - int highest = Math.subtractExact(bandMax, height - height / 2); - if (lowest > highest) { - // The band is shorter than the structure, so only its midpoint can be honoured. - return Math.floorDiv(Math.addExact(bandMin, bandMax), 2); - } - int span = highest - lowest + 1; - if (span == 1) { - return lowest; - } - long identity = (long) startChunk.x() * 341873128712L ^ (long) startChunk.z() * 132897987541L; - return lowest + new RNG(identity).nextInt(span); - } - - private static int midpointY(int minY, int maxY) { - return minY + (maxY - minY) / 2; - } - - static int resolveBuriedOffset(BoundingBox bounds, int requestedOffset, int worldMinY, - int worldMaxYExclusive, IntBinaryOperator surfaceHeight) { - Objects.requireNonNull(bounds, "Native structure bounds must not be null"); - Objects.requireNonNull(surfaceHeight, "Underground native structure requires a terrain height resolver"); - long width = (long) bounds.maxX() - bounds.minX() + 1L; - long depth = (long) bounds.maxZ() - bounds.minZ() + 1L; - if (width <= 0L || depth <= 0L || width > MAX_BURIAL_COLUMNS / depth) { - throw new IllegalStateException("Underground native structure burial footprint is invalid or exceeds " - + MAX_BURIAL_COLUMNS + " columns"); - } - int maximumOffset = requestedOffset; - for (int x = bounds.minX(); x <= bounds.maxX(); x++) { - for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { - int allowedTopY = surfaceHeight.applyAsInt(x, z) - UNDERGROUND_SURFACE_CLEARANCE; - maximumOffset = Math.min(maximumOffset, allowedTopY - bounds.maxY()); - } - } - int clampedOffset = StructureVerticalBounds.clampOffset( - bounds.minY(), bounds.maxY(), maximumOffset, worldMinY, worldMaxYExclusive); - if (clampedOffset > maximumOffset) { - IrisLogging.warn("Native structure burial at " + bounds.minX() + "," + bounds.minZ() - + " clamped to world floor: wanted " + maximumOffset + ", used " + clampedOffset); - } - return clampedOffset; - } } diff --git a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureVolumeIndex.java b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureVolumeIndex.java index 8367cc695..8c4b4821f 100644 --- a/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureVolumeIndex.java +++ b/adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureVolumeIndex.java @@ -2,11 +2,11 @@ package art.arcane.iris.nativegen; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; +import art.arcane.iris.engine.framework.NativeStructureLayouts; import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord; import art.arcane.iris.engine.framework.NativeStructureStarts; import art.arcane.iris.engine.framework.NativeStructureStartPlan; import art.arcane.iris.engine.framework.NativeStructureVolume; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.collection.KList; import net.minecraft.core.Holder; @@ -182,10 +182,6 @@ public final class NativeStructureVolumeIndex { KList target = volumes; for (NativeStructureStartPlan plan : plans) { - IrisNativeStructureDecision decision = plan.decision(); - if (!decision.generate()) { - continue; - } Identifier identifier = Identifier.tryParse(plan.structureKey()); if (identifier == null) { continue; @@ -197,7 +193,9 @@ public final class NativeStructureVolumeIndex { String structureId = identifier.toString(); try { StructureStart generated = NativeStructureFactory.generate( - generationContext(engine, bindings), registry.wrapAsHolder(structure), plan, 0); + generationContext(engine, bindings), registry.wrapAsHolder(structure), plan, 0, + NativeStructureLayouts.reaches(engine, structureId, + NativeStructureVegetationClearer.isUndergroundStep(structure.step()), plan.memo())); target = appendPieces(target, structureId, generated); } catch (RuntimeException | Error error) { warnOnce(structureId, error); @@ -229,9 +227,7 @@ public final class NativeStructureVolumeIndex { String structureId = identifier.toString(); boolean undergroundStep = NativeStructureVegetationClearer.isUndergroundStep(structure.step()); try { - IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve( - engine, structureId, undergroundStep); - if (!decision.generate()) { + if (!NativeStructureGenerationPolicy.generates(engine, structureId)) { continue; } StructureStart generated = structure.generate( @@ -254,13 +250,11 @@ public final class NativeStructureVolumeIndex { NativeStructureVerticalPlacer.applyVerticalPlacement( generated, structureId, - decision.yShift(), + NativeStructureLayouts.shift(engine, NativeStructureVerticalPlacer.placementOf( + generated, structureId, undergroundStep, worldMinY, surfaceHeight)), bindings.generator().getSeaLevel(), worldMinY, worldMaxYExclusive, - undergroundStep, - decision.preserveSourceY(), - decision.yBand(), surfaceHeight); target = appendPieces(target, structureId, generated); } catch (RuntimeException | Error error) { diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/IrisModdedChunkGenerator.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/IrisModdedChunkGenerator.java index 088f82936..3beda8396 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/IrisModdedChunkGenerator.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/IrisModdedChunkGenerator.java @@ -974,7 +974,7 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator { } } - Integer worldCheckStructureShift(String structureId, ChunkPos startChunk) { + ModdedNativeStructureStage.WorldCheckShift worldCheckStructureShift(String structureId, ChunkPos startChunk) { return nativeStructures.worldCheckStructureShift(structureId, startChunk); } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedNativeStructureStage.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedNativeStructureStage.java index 4f9f17e70..77a0c0b66 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedNativeStructureStage.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedNativeStructureStage.java @@ -21,25 +21,21 @@ package art.arcane.iris.modded; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; +import art.arcane.iris.engine.framework.NativeStructureLayouts; +import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting; import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord; import art.arcane.iris.engine.framework.NativeStructureStartPlan; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; import art.arcane.iris.nativegen.NativeStructureGenerationException; import art.arcane.iris.nativegen.NativeStructureLocatePersistence; import art.arcane.iris.nativegen.NativeStructureLocateResults; import art.arcane.iris.nativegen.NativeStructureOwnershipRecovery; -import art.arcane.iris.nativegen.NativeStructurePostProcessor; +import art.arcane.iris.nativegen.NativeStructureFitBridge; import art.arcane.iris.nativegen.NativeStructureReferenceEnvelope; -import art.arcane.iris.nativegen.NativeStructureSurfaceFitter; -import art.arcane.iris.nativegen.NativeStructureTerrainIntegrator; import art.arcane.iris.nativegen.NativeStructureVegetationClearer; import art.arcane.iris.nativegen.NativeStructureVerticalPlacer; import art.arcane.iris.nativegen.NativeStructureVanillaLocator; import art.arcane.iris.nativegen.NativeStructureVolumeIndex; import art.arcane.iris.nativegen.WorldgenTerrainHeightmaps; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.math.RNG; import com.mojang.datafixers.util.Pair; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; @@ -88,7 +84,7 @@ final class ModdedNativeStructureStage { private static final boolean WORLD_CHECK_ENABLED = Boolean.getBoolean("iris.worldcheck"); private final IrisModdedChunkGenerator generator; - private final ConcurrentHashMap worldCheckStructureShifts = new ConcurrentHashMap<>(); + private final ConcurrentHashMap worldCheckStructureShifts = new ConcurrentHashMap<>(); private volatile StructureStepCache structureStepCache; ModdedNativeStructureStage(IrisModdedChunkGenerator generator) { @@ -206,9 +202,8 @@ final class ModdedNativeStructureStage { throw new IllegalStateException("Native structure filtering received an unregistered structure holder"); } String key = id.toString(); - IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(current, - key, NativeStructureVegetationClearer.isUndergroundStep(holder.value().step())); - if (!decision.generate() || !generator.structureBiomeSource.isStructureReachable(holder)) { + if (!NativeStructureGenerationPolicy.generates(current, key) + || !generator.structureBiomeSource.isStructureReachable(holder)) { continue; } kept.add(holder); @@ -231,7 +226,7 @@ final class ModdedNativeStructureStage { } if (configuredStarts.containsKey(structure)) { recordWorldCheckStructureShift( - configuredStarts.get(structure).structureKey(), start.getChunkPos(), 0); + configuredStarts.get(structure).structureKey(), start.getChunkPos(), 0, 0); continue; } Identifier id = registry.getKey(structure); @@ -241,34 +236,34 @@ final class ModdedNativeStructureStage { "resolution", null, chunkPos.x(), chunkPos.z()); } boolean undergroundStep = NativeStructureVegetationClearer.isUndergroundStep(structure.step()); - IrisNativeStructureDecision decision; + boolean generates; try { - decision = NativeStructureGenerationPolicy.resolve(current, - structureId, undergroundStep); + generates = NativeStructureGenerationPolicy.generates(current, structureId); } catch (Throwable error) { throw NativeStructureGenerationException.failure( "policy resolution", structureId, chunkPos.x(), chunkPos.z(), error); } - if (!decision.generate()) { + if (!generates) { chunk.setStartForStructure(structure, StructureStart.INVALID_START); continue; } + int shift; int offsetY; try { + IntBinaryOperator surface = (x, z) -> current.getHeight(x, z, true) + current.getMinHeight(); + shift = NativeStructureLayouts.shift(current, NativeStructureVerticalPlacer.placementOf( + start, structureId, undergroundStep, chunk.getMinY(), surface)); offsetY = NativeStructureVerticalPlacer.applyVerticalPlacement( start, structureId, - decision.yShift(), + shift, generator.getSeaLevel(), chunk.getMinY(), chunk.getMinY() + chunk.getHeight(), - undergroundStep, - decision.preserveSourceY(), - decision.yBand(), - (x, z) -> current.getHeight(x, z, true) + current.getMinHeight()); + surface); StructureStart wrapped = NativeStructureReferenceEnvelope.wrapForPublication( start, structure, start.getReferences(), - NativeStructureTerrainIntegrator.resolveNativeTerrain(start, decision.terrain()), + NativeStructureLayouts.reaches(current, structureId, undergroundStep, null), structureId); chunk.setStartForStructure(structure, wrapped); if (!wrapped.isValid()) { @@ -278,7 +273,7 @@ final class ModdedNativeStructureStage { throw NativeStructureGenerationException.failure( "vertical adjustment", structureId, chunkPos.x(), chunkPos.z(), error); } - recordWorldCheckStructureShift(structureId, start.getChunkPos(), offsetY); + recordWorldCheckStructureShift(structureId, start.getChunkPos(), shift, offsetY); } } @@ -306,7 +301,7 @@ final class ModdedNativeStructureStage { List placementGroups = new ArrayList<>(); List heightmapStarts = new ArrayList<>(); List vegetationTargets = new ArrayList<>(); - List terrainTargets = new ArrayList<>(); + List fitTargets = new ArrayList<>(); for (int step = 0; step < steps; step++) { int index = 0; for (Structure structure : byStep.get(step)) { @@ -317,25 +312,20 @@ final class ModdedNativeStructureStage { "resolution", null, chunkPos.x(), chunkPos.z()); } try { - IrisNativeStructureDecision sourceDecision = NativeStructureGenerationPolicy.resolve(current, - structureId, NativeStructureVegetationClearer.isUndergroundStep(structure.step())); + boolean platformGenerates = NativeStructureGenerationPolicy.generates(current, structureId); List starts = structureManager.startsForStructure(sectionPos, structure); List resolvedPlacements = new ArrayList<>(starts.size()); for (StructureStart start : starts) { NativeStructureOwnershipRecord ownership = NativeStructureOwnershipRecovery.resolve( current, world.getLevel(), structureId, structure, start); - IrisNativeStructureDecision decision = - ownership == null ? sourceDecision : ownership.restoredDecision(); - if (!decision.generate()) { + if (ownership == null && !platformGenerates) { continue; } - resolvedPlacements.add(new NativePlacement(start, decision)); + resolvedPlacements.add(new NativePlacement(start, ownership != null)); heightmapStarts.add(start); - terrainTargets.add(new NativeStructureTerrainIntegrator.TerrainTarget( - structureId, start, - NativeStructureTerrainIntegrator.resolveNativeTerrain( - start, decision.terrain()))); + fitTargets.add(new NativeStructureFitBridge.FitTarget(structureId, start, + ownership == null ? null : ownership.restoredMemo())); vegetationTargets.add(start); } if (!resolvedPlacements.isEmpty()) { @@ -373,44 +363,29 @@ final class ModdedNativeStructureStage { "vegetation cleanup", nativeStructureBatchContext(placementGroups), chunkPos.x(), chunkPos.z(), error); } - NativeStructureSurfaceFitter.VacuumFoundationPlan vacuumFoundationPlan; + NativeStructureFitting.Session fit; try { - vacuumFoundationPlan = NativeStructureSurfaceFitter.prepareSurfaceStructures( - world, area, terrainTargets, - (x, z) -> current.getHeight(x, z, true) + current.getMinHeight()); + fit = NativeStructureFitting.of(current).beforePieces(NativeStructureFitBridge.chunk( + world, area, fitTargets, (x, z) -> current.getHeight(x, z, true) + current.getMinHeight())); } catch (Throwable error) { throw NativeStructureGenerationException.failure( - "terrain integration", nativeStructureBatchContext(placementGroups), - chunkPos.x(), chunkPos.z(), error); - } - try { - NativeStructurePostProcessor.prepareTerrain( - world, area, terrainTargets, this::resolvePaletteBlock); - } catch (Throwable error) { - throw NativeStructureGenerationException.failure( - "terrain preparation", nativeStructureBatchContext(placementGroups), + "terrain fitting", nativeStructureBatchContext(placementGroups), chunkPos.x(), chunkPos.z(), error); } + int placed = 0; for (NativePlacementGroup group : placementGroups) { random.setFeatureSeed(decorationSeed, group.featureIndex(), group.step()); try { for (NativePlacement placement : group.placements()) { placeVanillaStructure(world, structureManager, random, area, chunkPos, - group.structureId(), placement.start(), placement.decision()); + group.structureId(), placement); + fit.afterPieces(placed++); } } catch (Throwable error) { throw NativeStructureGenerationException.failure( "placement", group.structureId(), chunkPos.x(), chunkPos.z(), error); } } - try { - NativeStructureSurfaceFitter.repairVacuumFoundations( - world, area, vacuumFoundationPlan); - } catch (Throwable error) { - throw NativeStructureGenerationException.failure( - "foundation repair", nativeStructureBatchContext(placementGroups), - chunkPos.x(), chunkPos.z(), error); - } } static void visitExistingPois(ChunkAccess chunk, BiConsumer visitor) { @@ -433,8 +408,7 @@ final class ModdedNativeStructureStage { private void placeVanillaStructure(WorldGenLevel world, StructureManager structureManager, WorldgenRandom random, BoundingBox area, ChunkPos chunkPos, - String structureId, StructureStart start, - IrisNativeStructureDecision decision) { + String structureId, NativePlacement placement) { Engine current = generator.engine(); int runtimeMinY = world.getMinY(); WorldGenLevel boundedWorld = ModdedNativeStructureWorldgenAccess.create( @@ -443,15 +417,23 @@ final class ModdedNativeStructureStage { worldgenFloorHeight(current, runtimeMinY)); world.setCurrentlyGenerating(() -> "Iris native structure " + structureId); try { - NativeStructurePostProcessor.place( - boundedWorld, structureManager, generator, random, area, chunkPos, - structureId, start, decision, this::resolvePaletteBlock, - (x, z) -> current.getHeight(x, z, true) + current.getMinHeight()); + StructureStart start = placement.start(); + NativeStructureVerticalPlacer.ensureMonumentSeaLevelAlignment(start, structureId, + () -> placement.recorded() ? 0 : platformShift(current, start, structureId, runtimeMinY), + generator.getSeaLevel(), area.minY(), area.maxY() + 1); + start.placeInChunk(boundedWorld, structureManager, generator, random, area, chunkPos); } finally { world.setCurrentlyGenerating(null); } } + /** The shift the pack's modules give the platform's own start, as when the start was published. */ + private static int platformShift(Engine current, StructureStart start, String structureId, int bottomY) { + return NativeStructureLayouts.shift(current, NativeStructureVerticalPlacer.placementOf(start, structureId, + NativeStructureVegetationClearer.isUndergroundStep(start.getStructure().step()), bottomY, + (x, z) -> current.getHeight(x, z, true) + current.getMinHeight())); + } + private List> structuresByStep(Registry registry) { StructureStepCache cached = structureStepCache; if (cached != null && cached.registry() == registry) { @@ -479,17 +461,19 @@ final class ModdedNativeStructureStage { } } - private void recordWorldCheckStructureShift(String structureId, ChunkPos startChunk, int offsetY) { + private void recordWorldCheckStructureShift(String structureId, ChunkPos startChunk, int requestedShift, + int appliedShift) { if (!WORLD_CHECK_ENABLED || structureId == null) { return; } if (worldCheckStructureShifts.size() >= WORLD_CHECK_SHIFT_RECORD_LIMIT) { worldCheckStructureShifts.clear(); } - worldCheckStructureShifts.put(new NativeStructureStartKey(structureId, startChunk.pack()), offsetY); + worldCheckStructureShifts.put(new NativeStructureStartKey(structureId, startChunk.pack()), + new WorldCheckShift(requestedShift, appliedShift)); } - Integer worldCheckStructureShift(String structureId, ChunkPos startChunk) { + WorldCheckShift worldCheckStructureShift(String structureId, ChunkPos startChunk) { if (structureId == null || startChunk == null) { return null; } @@ -500,16 +484,6 @@ final class ModdedNativeStructureStage { worldCheckStructureShifts.clear(); } - private BlockState resolvePaletteBlock(IrisMaterialPalette palette, RNG rng, - int x, int y, int z) { - PlatformBlockState platformState = palette.get(rng, x, y, z, generator.engine().getData()); - if (platformState == null || !(platformState.nativeHandle() instanceof BlockState blockState)) { - throw new IllegalStateException("Configured native structure palette did not resolve a Minecraft block at " - + x + "," + y + "," + z); - } - return blockState; - } - private BoundingBox writableArea(ChunkAccess chunk) { ChunkPos chunkPos = chunk.getPos(); int minX = chunkPos.getMinBlockX(); @@ -530,7 +504,12 @@ final class ModdedNativeStructureStage { private record NativeStructureStartKey(String structureId, long chunkPosition) { } - private record NativePlacement(StructureStart start, IrisNativeStructureDecision decision) { + /** A start placed in the chunk, and whether a module placed it (its ownership record kept its fit). */ + private record NativePlacement(StructureStart start, boolean recorded) { + } + + /** The shift the pack's modules asked for a platform start, and the shift generation applied. */ + record WorldCheckShift(int requested, int applied) { } private record NativePlacementGroup(String structureId, int featureIndex, int step, diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/WorldCheckStiltAudit.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/WorldCheckStiltAudit.java new file mode 100644 index 000000000..6000eeb1c --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/WorldCheckStiltAudit.java @@ -0,0 +1,121 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.modded; + +import art.arcane.iris.nativegen.NativeStructureReferenceEnvelope; +import net.minecraft.core.BlockPos; +import net.minecraft.tags.BlockTags; +import net.minecraft.world.level.WorldGenLevel; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.structure.BoundingBox; +import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece; +import net.minecraft.world.level.levelgen.structure.StructurePiece; +import net.minecraft.world.level.levelgen.structure.StructureStart; + +import java.util.function.IntBinaryOperator; + +/** + * The world check's reading of a placed structure's stilts: per column of the structure's foundation (each piece's + * ground level and the block above it), whether the lowest solid foundation block stands on terrain, on stilts of the + * expected block reaching terrain, or on nothing. It reads the generated world, independently of the fit that built + * the stilts. + */ +final class WorldCheckStiltAudit { + private static final int FOUNDATION_VERTICAL_TOLERANCE = 1; + + private WorldCheckStiltAudit() { + } + + static Result audit(WorldGenLevel world, BoundingBox area, StructureStart start, BlockState expectedStilt, + IntBinaryOperator surfaceHeight) { + BoundingBox structure = NativeStructureReferenceEnvelope.contentBounds(start); + int minX = Math.max(area.minX(), structure.minX()); + int minZ = Math.max(area.minZ(), structure.minZ()); + int maxX = Math.min(area.maxX(), structure.maxX()); + int maxZ = Math.min(area.maxZ(), structure.maxZ()); + Result result = Result.NONE; + for (int z = minZ; z <= maxZ; z++) { + for (int x = minX; x <= maxX; x++) { + int foundationY = foundationY(world, area, start, x, z); + if (foundationY != Integer.MIN_VALUE) { + int terrainY = Math.max(area.minY(), Math.min(area.maxY(), surfaceHeight.applyAsInt(x, z))); + result = result.plus(column(world, area, x, z, foundationY, terrainY, expectedStilt)); + } + } + } + return result; + } + + private static Result column(WorldGenLevel world, BoundingBox area, int x, int z, int foundationY, int terrainY, + BlockState expectedStilt) { + BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); + boolean grounded = foundationY <= terrainY + 1; + int stiltBlocks = 0; + for (int y = foundationY - 1; y >= area.minY(); y--) { + if (y <= terrainY) { + grounded = true; + break; + } + BlockState state = world.getBlockState(position.set(x, y, z)); + if (state.is(expectedStilt.getBlock())) { + stiltBlocks++; + grounded |= y == area.minY(); + continue; + } + grounded = state.isSolid() && !state.is(BlockTags.LOGS) && !state.is(BlockTags.LEAVES); + break; + } + return new Result(1, stiltBlocks, stiltBlocks > 0 ? 1 : 0, grounded ? 0 : 1); + } + + /** The lowest solid block of the column inside a piece's ground level band; MIN_VALUE when there is none. */ + private static int foundationY(WorldGenLevel world, BoundingBox area, StructureStart start, int x, int z) { + BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos(); + int lowest = Integer.MIN_VALUE; + for (StructurePiece piece : start.getPieces()) { + BoundingBox bounds = piece.getBoundingBox(); + if (x < bounds.minX() || x > bounds.maxX() || z < bounds.minZ() || z > bounds.maxZ()) { + continue; + } + int groundY = bounds.minY() + (piece instanceof PoolElementStructurePiece poolPiece + ? poolPiece.getGroundLevelDelta() : 0); + int minY = Math.max(area.minY(), bounds.minY()); + int maxY = Math.min(area.maxY(), Math.min(bounds.maxY(), groundY + FOUNDATION_VERTICAL_TOLERANCE)); + if (groundY < bounds.minY()) { + continue; + } + for (int y = minY; y <= maxY && (lowest == Integer.MIN_VALUE || y < lowest); y++) { + if (world.getBlockState(position.set(x, y, z)).isSolid()) { + lowest = y; + break; + } + } + } + return lowest; + } + + record Result(int baseColumns, int stiltBlocks, int stiltColumns, int unsupportedColumns) { + static final Result NONE = new Result(0, 0, 0, 0); + + Result plus(Result other) { + return new Result(baseColumns + other.baseColumns, stiltBlocks + other.stiltBlocks, + stiltColumns + other.stiltColumns, unsupportedColumns + other.unsupportedColumns); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/WorldCheckStructureAudit.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/WorldCheckStructureAudit.java index c70c5442f..23640370c 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/WorldCheckStructureAudit.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/WorldCheckStructureAudit.java @@ -18,10 +18,8 @@ package art.arcane.iris.modded; + import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; -import art.arcane.iris.nativegen.NativeStructureFoundationBuilder; import art.arcane.iris.nativegen.NativeStructureVegetationClearer; import com.mojang.datafixers.util.Pair; import net.minecraft.core.BlockPos; @@ -206,20 +204,20 @@ final class WorldCheckStructureAudit { return new StructureCheckResult(false, null); } - IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve( - generator.commandEngine(), foundKey.toString(), - NativeStructureVegetationClearer.isUndergroundStep(structure.step())); - Integer appliedShift = generator.worldCheckStructureShift(foundKey.toString(), start.getChunkPos()); + ModdedNativeStructureStage.WorldCheckShift recorded = + generator.worldCheckStructureShift(foundKey.toString(), start.getChunkPos()); + int requestedShift = recorded == null ? 0 : recorded.requested(); + Integer appliedShift = recorded == null ? null : recorded.applied(); BoundingBox shiftedBounds = start.getBoundingBox(); boolean verticalShiftOk = WorldCheckPredicates.verticalShiftMatches( - decision.yShift(), appliedShift, shiftedBounds.minY(), shiftedBounds.maxY(), + requestedShift, appliedShift, shiftedBounds.minY(), shiftedBounds.maxY(), level.getMinY(), level.getMaxY()); WorldCheckPredicates.qaEvent("structure_vertical_shift", check.label(), verticalShiftOk, - "configured=" + decision.yShift() + ",applied=" + "requested=" + requestedShift + ",applied=" + (appliedShift == null ? "unrecorded" : appliedShift)); if (!verticalShiftOk) { ModdedIrisLog.error("[worldcheck] {} expected vertical shift {} but generation recorded {}", - check.label(), decision.yShift(), appliedShift); + check.label(), requestedShift, appliedShift); } FootprintAudit footprint = auditFootprint(level, structure, start, check, foundKey); @@ -571,9 +569,8 @@ final class WorldCheckStructureAudit { Engine engine = irisGenerator.commandEngine(); IntBinaryOperator surfaceHeight = (x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight(); - NativeStructureFoundationBuilder.StiltSupportAudit foundation = - NativeStructureFoundationBuilder.auditStiltSupport( - level, area, start, Blocks.COBBLESTONE.defaultBlockState(), surfaceHeight); + WorldCheckStiltAudit.Result foundation = WorldCheckStiltAudit.audit( + level, area, start, Blocks.COBBLESTONE.defaultBlockState(), surfaceHeight); foundationBaseColumns = foundation.baseColumns(); foundationBlocks = foundation.stiltBlocks(); foundationColumns = foundation.stiltColumns(); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandSuggestions.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandSuggestions.java index c1043634d..d245afaab 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandSuggestions.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandSuggestions.java @@ -26,8 +26,7 @@ import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; import art.arcane.iris.engine.framework.StructureReachability; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; +import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; import art.arcane.iris.modded.IrisModdedChunkGenerator; import art.arcane.iris.modded.ModdedEngineBootstrap; import art.arcane.iris.modded.ModdedServerLevels; @@ -133,14 +132,14 @@ final class ModdedCommandSuggestions { for (Identifier identifier : registry.keySet()) { String key = identifier.toString(); registeredKeys.add(normalizeKey(key)); - IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, key, false); + NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key); boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key); boolean locatableNativePlacement = nativePlacement && IrisStructureLocator.hasLocatableNativePlacement(engine, key); boolean locatableEditableReplacement = !nativePlacement - && decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS + && status == NativeStructureGenerationStatus.REPLACED_BY_IRIS && ModuleServices.canLocateStructure(engine, key); - if (isEligibleRegisteredStructure(decision, nativePlacement, + if (isEligibleRegisteredStructure(status, nativePlacement, locatableNativePlacement, locatableEditableReplacement, reachableNativeKeys.contains(normalizeKey(key)), nativeGenerationEnabled)) { nativeKeys.add(key); @@ -157,17 +156,17 @@ final class ModdedCommandSuggestions { return builder.buildFuture(); } - static boolean isEligibleRegisteredStructure(IrisNativeStructureDecision decision, + static boolean isEligibleRegisteredStructure(NativeStructureGenerationStatus status, boolean nativePlacement, boolean locatableNativePlacement, boolean locatableEditableReplacement, boolean reachable, boolean nativeGenerationEnabled) { - if (decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS) { + if (status == NativeStructureGenerationStatus.REPLACED_BY_IRIS) { return locatableEditableReplacement || nativeGenerationEnabled && nativePlacement && locatableNativePlacement; } - return nativeGenerationEnabled && decision.generate() + return nativeGenerationEnabled && status == NativeStructureGenerationStatus.GENERATE_NATIVE && (reachable || nativePlacement && locatableNativePlacement); } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedLocateCommands.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedLocateCommands.java index 0c54ecbc0..69a50a126 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedLocateCommands.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedLocateCommands.java @@ -31,9 +31,8 @@ import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; import art.arcane.iris.engine.framework.StructureReachability; import art.arcane.iris.engine.framework.WrongEngineBroException; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; +import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; import art.arcane.iris.modded.IrisModdedChunkGenerator; import art.arcane.iris.util.project.context.IrisContext; import art.arcane.volmlib.util.localization.MessageArgument; @@ -166,21 +165,21 @@ final class ModdedLocateCommands { return 0; } NativeStructureTarget target = resolved.get(); - IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, target.key(), false); + NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, target.key()); boolean nativeGenerationEnabled = source.getServer().getWorldGenSettings().options().generateStructures(); boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, target.key()); boolean locatableNativePlacement = nativePlacement && IrisStructureLocator.hasLocatableNativePlacement(engine, target.key()); boolean locatableEditableReplacement = !nativePlacement - && decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS + && status == NativeStructureGenerationStatus.REPLACED_BY_IRIS && ModuleServices.canLocateStructure(engine, target.key()); boolean reachable = StructureReachability.isReachable(engine, target.key()); if (!ModdedCommandSuggestions.isEligibleRegisteredStructure( - decision, nativePlacement, locatableNativePlacement, locatableEditableReplacement, + status, nativePlacement, locatableNativePlacement, locatableEditableReplacement, reachable, nativeGenerationEnabled)) { IrisModdedCommands.fail(source, registeredStructureUnavailableMessage( - target.key(), target.availability(), decision, + target.key(), target.availability(), status, nativePlacement, locatableNativePlacement, nativeGenerationEnabled, reachable)); return 0; @@ -196,14 +195,14 @@ final class ModdedLocateCommands { static String registeredStructureUnavailableMessage( String key, NativeStructureAvailability nativeAvailability, - IrisNativeStructureDecision decision, + NativeStructureGenerationStatus status, boolean nativePlacement, boolean locatableNativePlacement, boolean nativeGenerationEnabled, boolean reachable) { - if (!decision.generate() - && decision.status() != NativeStructureGenerationStatus.REPLACED_BY_IRIS) { - return NativeStructureGenerationPolicy.generationStatusMessage(key, decision.status()); + if (status != NativeStructureGenerationStatus.GENERATE_NATIVE + && status != NativeStructureGenerationStatus.REPLACED_BY_IRIS) { + return NativeStructureGenerationPolicy.generationStatusMessage(key, status); } - if (decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS) { + if (status == NativeStructureGenerationStatus.REPLACED_BY_IRIS) { if (nativePlacement && !nativeGenerationEnabled) { return withInactiveNativePlacement( nativeUnavailableMessage(key, NativeStructureAvailability.WORLD_DISABLED), @@ -408,9 +407,9 @@ final class ModdedLocateCommands { Engine engine, String key, Holder.Reference holder) { boolean worldEnabled = source.getServer().getWorldGenSettings().options().generateStructures(); - IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, key, false); - boolean selected = decision.status() != NativeStructureGenerationStatus.DISABLED_BY_PACK; - boolean suppressed = decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS; + NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key); + boolean selected = status != NativeStructureGenerationStatus.DISABLED_BY_PACK; + boolean suppressed = status == NativeStructureGenerationStatus.REPLACED_BY_IRIS; boolean biomeFilterEmpty = holder.value().biomes().stream().findAny().isEmpty(); ChunkGenerator chunkGenerator = level.getChunkSource().getGenerator(); boolean biomeReachable = chunkGenerator instanceof IrisModdedChunkGenerator irisGenerator diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedUnregisteredStructures.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedUnregisteredStructures.java index 42ccf8c52..7ca305d19 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedUnregisteredStructures.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedUnregisteredStructures.java @@ -24,8 +24,7 @@ import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; import art.arcane.iris.engine.framework.StructureReachability; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; +import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.Holder; import net.minecraft.core.Registry; @@ -107,16 +106,16 @@ final class ModdedUnregisteredStructures { key, "The live structure registry contains this key but has no bound structure holder.")); continue; } - IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, key, false); + NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key); boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key); boolean locatableNativePlacement = nativePlacement && IrisStructureLocator.hasLocatableNativePlacement(engine, key); boolean locatableEditableReplacement = !nativePlacement - && decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS + && status == NativeStructureGenerationStatus.REPLACED_BY_IRIS && ModuleServices.canLocateStructure(engine, key); boolean reachable = reachableNativeKeys.contains(normalizedKey); if (ModdedCommandSuggestions.isEligibleRegisteredStructure( - decision, nativePlacement, locatableNativePlacement, + status, nativePlacement, locatableNativePlacement, locatableEditableReplacement, reachable, nativeGenerationEnabled)) { eligibleRegisteredKeys.add(normalizedKey); continue; @@ -124,7 +123,7 @@ final class ModdedUnregisteredStructures { ModdedLocateCommands.NativeStructureAvailability availability = ModdedLocateCommands.nativeAvailability(source, level, engine, key, holder.get()); String reason = ModdedLocateCommands.registeredStructureUnavailableMessage( - key, availability, decision, nativePlacement, locatableNativePlacement, + key, availability, status, nativePlacement, locatableNativePlacement, nativeGenerationEnabled, reachable); excluded.put(normalizedKey, new ExcludedStructure(ReportStatus.EXCLUDED, key, reason)); } diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/NativeStructureFailureContractTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/NativeStructureFailureContractTest.java index 7ee5f5f67..3263ce79c 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/NativeStructureFailureContractTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/NativeStructureFailureContractTest.java @@ -63,22 +63,20 @@ public class NativeStructureFailureContractTest { int placementEnd = source.indexOf("private static String nativeStructureBatchContext", placementStart); String placement = source.substring(placementStart, placementEnd); - assertTrue(placement.contains("\"terrain integration\"")); - assertTrue(placement.contains("\"terrain preparation\"")); - assertTrue(placement.contains("\"foundation repair\"")); + assertTrue(placement.contains("\"terrain fitting\"")); assertFalse(placement.contains("\"terrain carving\"")); assertTrue(placement.contains("visitExistingPois(chunk")); assertTrue(placement.contains("level.updatePOIOnBlockStateChange(")); assertTrue(placement.contains("Blocks.AIR.defaultBlockState(), state")); assertTrue(placement.indexOf("visitExistingPois(chunk") < placement.indexOf("WorldgenTerrainHeightmaps.primeStructurePlacement(")); - assertTrue(placement.contains("prepareSurfaceStructures")); + assertTrue(placement.contains(".beforePieces(")); assertTrue(placement.contains("clearIntersectingVegetation")); assertTrue(placement.indexOf("clearIntersectingVegetation") - < placement.indexOf("prepareSurfaceStructures")); - assertTrue(placement.indexOf("prepareSurfaceStructures") + < placement.indexOf(".beforePieces(")); + assertTrue(placement.indexOf(".beforePieces(") < placement.indexOf("for (NativePlacementGroup group")); - assertTrue(placement.indexOf("repairVacuumFoundations") + assertTrue(placement.indexOf("fit.afterPieces(") > placement.indexOf("for (NativePlacementGroup group")); } @@ -94,7 +92,7 @@ public class NativeStructureFailureContractTest { assertTrue(placement.contains("\"heightmap priming\"")); assertTrue(placement.contains("heightmapStarts.add(start);")); assertTrue(placement.indexOf("WorldgenTerrainHeightmaps.primeStructurePlacement(") - < placement.indexOf("prepareSurfaceStructures")); + < placement.indexOf(".beforePieces(")); assertTrue(source.contains("generationEngine.getHeight(x, z, false) + runtimeMinY + 1")); assertTrue(source.contains("generationEngine.getHeight(x, z, true) + runtimeMinY + 1")); assertTrue(source.contains("int minY = chunk.getMinY() + 1;")); @@ -108,8 +106,8 @@ public class NativeStructureFailureContractTest { String placement = source.substring(placementStart, placementEnd); assertTrue(placement.contains("ModdedNativeStructureWorldgenAccess.create(")); - assertTrue(placement.contains("NativeStructurePostProcessor.place(\n boundedWorld")); - assertFalse(placement.contains("NativeStructurePostProcessor.place(world,")); + assertTrue(placement.contains("start.placeInChunk(boundedWorld,")); + assertFalse(placement.contains("start.placeInChunk(world,")); assertTrue(placement.contains("world.setCurrentlyGenerating(null);")); } diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedStructureCommandTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedStructureCommandTest.java index d1befc6f1..7805aad0c 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedStructureCommandTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedStructureCommandTest.java @@ -1,7 +1,6 @@ package art.arcane.iris.modded.command; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; +import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; import art.arcane.iris.nativegen.NativeStructureLocateResults; import com.mojang.datafixers.util.Pair; import net.minecraft.core.BlockPos; @@ -74,11 +73,9 @@ public class IrisModdedStructureCommandTest { @Test public void registeredStructureEligibilityMatchesGotoAndSuggestions() { - IrisNativeStructureDecision nativeDecision = decision(NativeStructureGenerationStatus.GENERATE_NATIVE); - IrisNativeStructureDecision replacementDecision = decision( - NativeStructureGenerationStatus.REPLACED_BY_IRIS); - IrisNativeStructureDecision disabledDecision = decision( - NativeStructureGenerationStatus.DISABLED_BY_PACK); + NativeStructureGenerationStatus nativeDecision = NativeStructureGenerationStatus.GENERATE_NATIVE; + NativeStructureGenerationStatus replacementDecision = NativeStructureGenerationStatus.REPLACED_BY_IRIS; + NativeStructureGenerationStatus disabledDecision = NativeStructureGenerationStatus.DISABLED_BY_PACK; assertTrue(ModdedCommandSuggestions.isEligibleRegisteredStructure( nativeDecision, false, false, false, true, true)); @@ -161,7 +158,7 @@ public class IrisModdedStructureCommandTest { String combined = ModdedLocateCommands.registeredStructureUnavailableMessage( "towns_and_towers:exclusive", ModdedLocateCommands.NativeStructureAvailability.EMPTY_BIOME_FILTER, - decision(NativeStructureGenerationStatus.GENERATE_NATIVE), + NativeStructureGenerationStatus.GENERATE_NATIVE, true, false, true, false); assertTrue(combined.contains("resolves to zero registered biomes")); assertTrue(combined.contains("matching Iris nativeStructures placement is also configured")); @@ -203,7 +200,7 @@ public class IrisModdedStructureCommandTest { assertFalse(method.contains("IrisStructureLocator.locatableKeys(engine)")); assertTrue(method.contains("ModuleServices.locatableStructures(engine)")); assertTrue(method.contains("StructureReachability.reachableKeys(engine)")); - assertTrue(method.contains("NativeStructureGenerationPolicy.resolve(engine, key, false)")); + assertTrue(method.contains("NativeStructureGenerationPolicy.resolve(engine, key)")); assertTrue(method.contains("IrisStructureLocator.hasLocatableNativePlacement(engine, key)")); assertTrue(method.contains("ModuleServices.canLocateStructure(engine, key)")); assertTrue(method.contains("reachableNativeKeys.contains(normalizeKey(key))")); @@ -260,7 +257,7 @@ public class IrisModdedStructureCommandTest { int editableIrisLookup = method.indexOf( "ModuleServices.canLocateStructure(engine, key)", nativeResolution); int policyResolution = method.indexOf( - "NativeStructureGenerationPolicy.resolve(engine, target.key(), false)", editableIrisLookup); + "NativeStructureGenerationPolicy.resolve(engine, target.key())", editableIrisLookup); int eligibilityCheck = method.indexOf( "ModdedCommandSuggestions.isEligibleRegisteredStructure(", policyResolution); int replacementLocate = method.indexOf( @@ -330,8 +327,4 @@ public class IrisModdedStructureCommandTest { .resolve("../modded-common/src/main/java") .normalize(); } - - private IrisNativeStructureDecision decision(NativeStructureGenerationStatus status) { - return new IrisNativeStructureDecision(status, 0, null, false, null, null); - } } diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/nativegen/NativeStructureReferenceRepairTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/nativegen/NativeStructureReferenceRepairTest.java index 9c25e219c..faff9f564 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/nativegen/NativeStructureReferenceRepairTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/nativegen/NativeStructureReferenceRepairTest.java @@ -9,10 +9,8 @@ import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord; import art.arcane.iris.engine.framework.NativeStructureOwnershipStore; import art.arcane.iris.engine.framework.NativeStructureStartPlan; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; +import art.arcane.iris.engine.framework.NativeStructureReach; +import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; import com.github.benmanes.caffeine.cache.Cache; import net.minecraft.SharedConstants; import net.minecraft.core.Direction; @@ -56,7 +54,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; @@ -81,9 +78,7 @@ public class NativeStructureReferenceRepairTest { StructureStart generated = monumentStart(structure, origin, seed); NativeStructureVerticalPlacer.alignOceanMonumentToSeaLevel( generated, 0, 80, -64, 320); - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.FORCE_CARVE) - .setHorizontalPadding(24); + List terrain = List.of(new NativeStructureReach(false, 24)); StructureStart wrapped = NativeStructureReferenceEnvelope.wrap( generated, structure, @@ -108,19 +103,9 @@ public class NativeStructureReferenceRepairTest { @Test public void deniedNaturalStartsCannotEnterCollisionArbitration() { - IrisNativeStructureDecision enabled = new IrisNativeStructureDecision( - NativeStructureGenerationStatus.GENERATE_NATIVE, - 0, null, false, null, new IrisStructureTerrain()); - IrisNativeStructureDecision disabled = new IrisNativeStructureDecision( - NativeStructureGenerationStatus.DISABLED_BY_PACK, - 0, null, false, null, new IrisStructureTerrain()); - IrisNativeStructureDecision replaced = new IrisNativeStructureDecision( - NativeStructureGenerationStatus.REPLACED_BY_IRIS, - 0, null, false, null, new IrisStructureTerrain()); - - assertTrue(NativeStructureReferenceRepair.naturalDecisionAllows(enabled)); - assertFalse(NativeStructureReferenceRepair.naturalDecisionAllows(disabled)); - assertFalse(NativeStructureReferenceRepair.naturalDecisionAllows(replaced)); + assertTrue(NativeStructureReferenceRepair.naturalStatusAllows(NativeStructureGenerationStatus.GENERATE_NATIVE)); + assertFalse(NativeStructureReferenceRepair.naturalStatusAllows(NativeStructureGenerationStatus.DISABLED_BY_PACK)); + assertFalse(NativeStructureReferenceRepair.naturalStatusAllows(NativeStructureGenerationStatus.REPLACED_BY_IRIS)); } @Test @@ -134,9 +119,7 @@ public class NativeStructureReferenceRepairTest { StructureStart generated = monumentStart(structure, origin, seed); NativeStructureVerticalPlacer.alignOceanMonumentToSeaLevel( generated, 0, 80, -64, 320); - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.FORCE_CARVE) - .setHorizontalPadding(24); + List terrain = List.of(new NativeStructureReach(false, 24)); StructureStart start = NativeStructureReferenceEnvelope.wrap( generated, structure, 0, terrain); NativeStructureOwnershipRecord ownership = NativeStructureOwnershipFingerprint.capture( @@ -145,10 +128,9 @@ public class NativeStructureReferenceRepairTest { plan(origin, NativeStructureReferenceEnvelope.contentBounds(start).minY()), NativeStructureReferenceEnvelope.referenceBounds(start, structure, terrain)); Engine engine = engine(new IrisDimension(), packWithoutModules()); - IrisNativeStructureDecision currentDecision = new IrisNativeStructureDecision( - NativeStructureGenerationStatus.DISABLED_BY_PACK, 0, null, false, null, null); + NativeStructureGenerationStatus currentStatus = NativeStructureGenerationStatus.DISABLED_BY_PACK; - assertFalse(NativeStructureReferenceRepair.naturalDecisionAllows(currentDecision)); + assertFalse(NativeStructureReferenceRepair.naturalStatusAllows(currentStatus)); ProtoChunk originChunk = emptyChunk(origin); originChunk.setStartForStructure(structure, start); @@ -164,8 +146,8 @@ public class NativeStructureReferenceRepairTest { installOwnership(engine, ownership); try (MockedStatic policy = mockStatic(NativeStructureGenerationPolicy.class)) { - policy.when(() -> NativeStructureGenerationPolicy.resolve(any(), eq(structureKey), anyBoolean())) - .thenReturn(currentDecision); + policy.when(() -> NativeStructureGenerationPolicy.resolve(any(), eq(structureKey))) + .thenReturn(currentStatus); WorldGenLevel level = worldGenLevel( registry, serverLevel, originChunk, emptyScannedChunk); ProtoChunk coveredChunk = emptyChunk(coveredTarget); @@ -210,7 +192,7 @@ public class NativeStructureReferenceRepairTest { private static NativeStructureStartPlan plan(ChunkPos origin, int baseY) { return new NativeStructureStartPlan("minecraft:monument", origin.x(), origin.z(), baseY, false, false, - MONUMENT_PLACEMENT_IDENTITY, null, null, new IrisStructureTerrain()); + MONUMENT_PLACEMENT_IDENTITY, null, null); } private static ChunkPos outsideLiveBounds(NativeStructureOwnershipRecord ownership, diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/nativegen/NativeStructureVacuumParityTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/nativegen/NativeStructureVacuumParityTest.java index 78af72766..ce62982a7 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/nativegen/NativeStructureVacuumParityTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/nativegen/NativeStructureVacuumParityTest.java @@ -1,13 +1,19 @@ package art.arcane.iris.nativegen; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; +import art.arcane.iris.engine.framework.NativeStartMemo; +import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting; import net.minecraft.SharedConstants; +import net.minecraft.core.BlockPos; 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.state.BlockState; 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.StructureStart; import net.minecraft.world.level.levelgen.structure.TerrainAdjustment; @@ -17,13 +23,20 @@ import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidStru import org.junit.BeforeClass; import org.junit.Test; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Proxy; +import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; +/** The modded loaders fit the platform's starts with the same built-in fit as Bukkit, through the shared bridge. */ public class NativeStructureVacuumParityTest { + private static final int SURFACE_Y = 50; + private static final int WORLD_MIN_Y = -64; + private static final int WORLD_HEIGHT = 384; + @BeforeClass public static void bootstrapMinecraftRegistries() { SharedConstants.tryDetectVersion(); @@ -31,21 +44,53 @@ public class NativeStructureVacuumParityTest { } @Test - public void explicitVacuumUsesNonCarvingSurfaceFittingOnModdedLoaders() { - Structure structure = new DesertPyramidStructure( - new Structure.StructureSettings( - HolderSet.empty(), Map.of(), - GenerationStep.Decoration.SURFACE_STRUCTURES, TerrainAdjustment.NONE)); + public void explicitVacuumNeitherCarvesNorInventsFootprintsForPiecesWithoutTemplates() { + Structure structure = new DesertPyramidStructure(new Structure.StructureSettings( + HolderSet.empty(), Map.of(), GenerationStep.Decoration.SURFACE_STRUCTURES, TerrainAdjustment.NONE)); DesertPyramidPiece piece = new DesertPyramidPiece(RandomSource.create(7L), 0, 0); - StructureStart start = new StructureStart( - structure, new ChunkPos(0, 0), 0, new PiecesContainer(List.of(piece))); - NativeStructureTerrainIntegrator.TerrainTarget target = - new NativeStructureTerrainIntegrator.TerrainTarget( - "test:vacuum", start, - new IrisStructureTerrain().setMode(IrisStructureTerrainMode.VACUUM)); + StructureStart start = new StructureStart(structure, new ChunkPos(0, 0), 0, new PiecesContainer(List.of(piece))); + BoundingBox bounds = start.getBoundingBox(); + BoundingBox area = new BoundingBox(bounds.minX() - 12, 40, bounds.minZ() - 12, + bounds.maxX() + 12, bounds.maxY() + 12, bounds.maxZ() + 12); + Map blocks = flatTerrain(area); + Map original = new HashMap<>(blocks); - assertTrue(NativeStructureSurfaceFitter.requiresSurfaceTerrain(target)); - assertFalse(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir( - start, target.terrain())); + NativeStructureFitting.builtInModules().beforePieces(NativeStructureFitBridge.chunk(world(blocks), area, + List.of(new NativeStructureFitBridge.FitTarget("test:vacuum", start, + new NativeStartMemo("{\"mode\":\"VACUUM\"}", "null"))), (x, z) -> SURFACE_Y)); + + assertEquals(original, blocks); + } + + private static Map flatTerrain(BoundingBox area) { + Map blocks = new HashMap<>(); + for (int x = area.minX(); x <= area.maxX(); x++) { + for (int z = area.minZ(); z <= area.maxZ(); z++) { + blocks.put(new BlockPos(x, SURFACE_Y - 1, z), Blocks.DIRT.defaultBlockState()); + blocks.put(new BlockPos(x, SURFACE_Y, z), Blocks.GRASS_BLOCK.defaultBlockState()); + } + } + return blocks; + } + + private static WorldGenLevel world(Map blocks) { + InvocationHandler handler = (proxy, method, arguments) -> switch (method.getName()) { + case "getBlockState" -> blocks.getOrDefault(arguments[0], Blocks.AIR.defaultBlockState()); + case "setBlock" -> { + blocks.put(((BlockPos) arguments[0]).immutable(), (BlockState) arguments[1]); + yield true; + } + case "getSeed" -> 1L; + case "getMinY" -> WORLD_MIN_Y; + case "getHeight" -> WORLD_HEIGHT; + case "getLevel" -> null; + case "holderLookup" -> BuiltInRegistries.BLOCK; + case "hashCode" -> System.identityHashCode(proxy); + case "equals" -> proxy == arguments[0]; + case "toString" -> "vacuum-parity-world"; + default -> throw new UnsupportedOperationException(method.toString()); + }; + return (WorldGenLevel) Proxy.newProxyInstance( + WorldGenLevel.class.getClassLoader(), new Class[]{WorldGenLevel.class}, handler); } } diff --git a/build.gradle b/build.gradle index 1be834057..8a835c8fe 100644 --- a/build.gradle +++ b/build.gradle @@ -127,8 +127,8 @@ nmsBindings.each { key, value -> rootProject.file("adapters/bukkit/nms/${key}/src/main/java/art/arcane/iris/core/nms/${key}/IrisChunkGenerator.java").absolutePath) systemProperty('iris.nmsBindingSource', rootProject.file("adapters/bukkit/nms/${key}/src/main/java/art/arcane/iris/core/nms/${key}/NMSBinding.java").absolutePath) - systemProperty('iris.nativeStructurePostProcessorSource', - rootProject.file('adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructurePostProcessor.java').absolutePath) + systemProperty('iris.nativeStructureFitBridgeSource', + rootProject.file('adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureFitBridge.java').absolutePath) systemProperty('iris.nativeStructureStartInjectorSource', rootProject.file('adapters/minecraft-common/src/main/java/art/arcane/iris/nativegen/NativeStructureStartInjector.java').absolutePath) systemProperty('iris.nativeStructureGenerationKeysSource', diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisValues.java b/core/src/main/java/art/arcane/iris/core/modules/IrisValues.java index 79b618810..0ece2069d 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisValues.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisValues.java @@ -23,23 +23,14 @@ import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.noise.IrisStyledRange; import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureYBand; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConfiguration; import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.value.IrisRange; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; -import com.google.gson.Gson; import com.volmit.block.BlockSpec; import com.volmit.block.PaletteSpec; import com.volmit.config.Range; import com.volmit.noise.StyledRange; -import com.volmit.vanilla.JigsawOverrides; -import com.volmit.vanilla.StructureStilts; -import com.volmit.vanilla.StructureTerrain; -import com.volmit.vanilla.YBand; import com.volmit.world.BlockPosition; import java.util.Map; @@ -57,12 +48,7 @@ public final class IrisValues { Map.entry(com.volmit.noise.NoiseStyle.class.getName(), IrisGeneratorStyle.class), Map.entry(StyledRange.class.getName(), IrisStyledRange.class), Map.entry(Range.class.getName(), IrisRange.class), - Map.entry(BlockPosition.class.getName(), IrisPosition.class), - Map.entry(StructureTerrain.class.getName(), IrisStructureTerrain.class), - Map.entry(StructureStilts.class.getName(), IrisStructureStiltSettings.class), - Map.entry(YBand.class.getName(), IrisStructureYBand.class), - Map.entry(JigsawOverrides.class.getName(), IrisJigsawConfiguration.class)); - private static final Gson SAME_JSON = new Gson(); + Map.entry(BlockPosition.class.getName(), IrisPosition.class)); private IrisValues() { } @@ -94,30 +80,6 @@ public final class IrisValues { return new IrisMaterialPalette().setStyle(generatorStyle(spec.style())).setZoom(spec.zoom()).setPalette(blocks); } - /** {@code terrain} as the terrain fitting Iris's native structure placement applies. */ - public static IrisStructureTerrain structureTerrain(StructureTerrain terrain) { - return sameJson(terrain, IrisStructureTerrain.class); - } - - /** {@code stilts} as the foundation columns Iris's native structure placement builds. */ - public static IrisStructureStiltSettings structureStilts(StructureStilts stilts) { - return sameJson(stilts, IrisStructureStiltSettings.class); - } - - public static IrisStructureYBand yBand(YBand band) { - return sameJson(band, IrisStructureYBand.class); - } - - /** {@code overrides} as the jigsaw configuration Iris applies to a platform jigsaw definition. */ - public static IrisJigsawConfiguration jigsawConfiguration(JigsawOverrides overrides) { - return sameJson(overrides, IrisJigsawConfiguration.class); - } - - /** The structure fit classes are plain values whose JSON is the API type's, so the conversion is a JSON round trip. */ - private static T sameJson(Object apiValue, Class irisClass) { - return SAME_JSON.fromJson(SAME_JSON.toJsonTree(apiValue), irisClass); - } - /** Iris's maps hold no null values; a JSON null in a map reads as absent, as it does for Iris's own fields. */ private static KMap irisMap(Map values) { KMap map = new KMap<>(); diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleStructureFitting.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleStructureFitting.java new file mode 100644 index 000000000..282c40a81 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleStructureFitting.java @@ -0,0 +1,430 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.NativeStartMemo; +import art.arcane.iris.engine.framework.nativefit.NativeFitBlocks; +import art.arcane.iris.engine.framework.nativefit.NativeFitBox; +import art.arcane.iris.engine.framework.nativefit.NativeFitChunk; +import art.arcane.iris.engine.framework.nativefit.NativeFitPiece; +import art.arcane.iris.engine.framework.nativefit.NativeFitStart; +import art.arcane.iris.engine.framework.nativefit.NativeFitTrait; +import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting; +import art.arcane.iris.engine.framework.nativefit.NativeTemplateCells; +import com.volmit.block.BlockFace; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.host.DiscoveredModule; +import com.volmit.host.LoadedModules; +import com.volmit.host.ServiceRegistration; +import com.volmit.mantle.BlockBox; +import com.volmit.resource.ResourceId; +import com.volmit.service.VanillaStructures; +import com.volmit.vanilla.PieceKind; +import com.volmit.vanilla.StartMemo; +import com.volmit.vanilla.StructureFit; +import com.volmit.vanilla.StructureStep; +import com.volmit.vanilla.TemplateCells; +import com.volmit.vanilla.TerrainAdaptation; +import com.volmit.world.BlockAccess; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +/** + * The pack's {@link VanillaStructures} providers fitting the platform's starts into a chunk: the platform code's view + * of the chunk ({@link NativeFitChunk}) as an API {@link StructureFit}, its native block states translated to API + * states and back through caches, so a provider can read and write blocks without allocating per block. + */ +public final class ModuleStructureFitting implements NativeStructureFitting { + private static final Map API_STATES = new ConcurrentHashMap<>(); + private static final Map NATIVE_STATES = new ConcurrentHashMap<>(); + private static final Map NATIVE_TRAITS = new ConcurrentHashMap<>(); + private static final Map TRAITS = new EnumMap<>(Map.of( + BlockTrait.AIR, NativeFitTrait.AIR, BlockTrait.SOLID, NativeFitTrait.SOLID, + BlockTrait.FLUID, NativeFitTrait.FLUID, BlockTrait.LOG, NativeFitTrait.LOG, + BlockTrait.LEAVES, NativeFitTrait.LEAVES)); + + private final List providers; + private final Supplier world; + + private ModuleStructureFitting(List providers, Supplier world) { + this.providers = providers; + this.world = world; + } + + public static NativeStructureFitting of(Engine engine) { + return new ModuleStructureFitting(ModuleVanillaStructures.providersOf(engine.getData()), + () -> engine.getGeneration().world()); + } + + public static NativeStructureFitting builtInModules() { + List modules = IrisModuleHost.builtInModules().stream().map(DiscoveredModule::builtIn).toList(); + LoadedModules loaded = LoadedModules.load(modules, Map.of(), List.of(IrisModuleHost.HOST_TYPE_PACKAGE), List.of()); + return new ModuleStructureFitting(loaded.catalog().registrations(VanillaStructures.class), () -> { + throw new IllegalStateException("The built-in modules fit outside a world here: a start needs its memo" + + " and a fit without palettes"); + }); + } + + @Override + public Session beforePieces(NativeFitChunk chunk) { + ChunkFit fit = new ChunkFit<>(chunk, world); + for (ServiceRegistration registration : providers) { + ModuleVanillaStructures.ask(registration, "fitting structures into chunk " + fit.chunkName(), provider -> { + provider.beforePieces(fit); + return Boolean.TRUE; + }); + } + return startIndex -> { + StructureFit.Start placed = fit.starts().get(startIndex); + for (ServiceRegistration registration : providers) { + ModuleVanillaStructures.ask(registration, "fitting " + placed.structure() + " into chunk " + fit.chunkName(), + provider -> { + provider.afterPieces(fit, placed); + return Boolean.TRUE; + }); + } + }; + } + + @SuppressWarnings("unchecked") + private static S nativeState(NativeFitBlocks blocks, BlockState state) { + return (S) NATIVE_STATES.computeIfAbsent(state, key -> blocks.state(key.key())); + } + + private static BlockState apiState(NativeFitBlocks blocks, S state) { + BlockState known = API_STATES.get(state); + if (known != null) { + return known; + } + return API_STATES.computeIfAbsent(state, key -> BlockState.parse(PlatformBlockStates.namespaced(blocks.key(state)))); + } + + private static boolean nativeTrait(NativeFitBlocks blocks, S state, NativeFitTrait trait) { + int traits = NATIVE_TRAITS.computeIfAbsent(state, key -> { + int bits = 0; + for (NativeFitTrait each : NativeFitTrait.values()) { + if (blocks.is(state, each)) { + bits |= 1 << each.ordinal(); + } + } + return bits; + }); + return (traits & 1 << trait.ordinal()) != 0; + } + + /** One chunk's fit in the API's terms: heights above the dimension's bottom, maxima exclusive. */ + private static final class ChunkFit implements StructureFit { + private final NativeFitChunk chunk; + private final Supplier world; + private final Access blocks; + private final List starts; + private final Map, Object> states = new HashMap<>(); + + private ChunkFit(NativeFitChunk chunk, Supplier world) { + this.chunk = chunk; + this.world = world; + this.blocks = new Access<>(chunk); + List converted = new ArrayList<>(chunk.starts().size()); + for (NativeFitStart start : chunk.starts()) { + converted.add(new HostStart<>(start, chunk)); + } + this.starts = List.copyOf(converted); + } + + String chunkName() { + return (chunk.area().minX() >> 4) + "," + (chunk.area().minZ() >> 4); + } + + @Override + public PackWorld world() { + return world.get(); + } + + @Override + public long seed() { + return chunk.seed(); + } + + @Override + public BlockBox area() { + return apiBox(chunk.area(), chunk.bottomY()); + } + + @Override + public int bottomY() { + return chunk.bottomY(); + } + + @Override + public BlockAccess blocks() { + return blocks; + } + + @Override + public int surfaceY(int x, int z) { + return chunk.surfaceY().applyAsInt(x, z) - chunk.bottomY(); + } + + @Override + public BlockState naturalBlock(int y) { + return apiState(chunk.blocks(), chunk.naturalBlock().apply(y + chunk.bottomY())); + } + + @Override + public List starts() { + return starts; + } + + @Override + public T state(Class type, Supplier create) { + Object known = states.get(type); + if (known == null) { + known = create.get(); + states.put(type, known); + } + return type.cast(known); + } + } + + /** The chunk column's blocks: the area's columns from the dimension's bottom to its top. */ + private static final class Access implements BlockAccess { + private final NativeFitBlocks blocks; + private final int bottomY; + private final BlockBox bounds; + private final Map written = new IdentityHashMap<>(); + + private Access(NativeFitChunk chunk) { + this.blocks = chunk.blocks(); + this.bottomY = chunk.bottomY(); + NativeFitBox area = chunk.area(); + this.bounds = new BlockBox(area.minX(), 0, area.minZ(), area.maxX() + 1, chunk.topY() - bottomY, area.maxZ() + 1); + } + + @Override + public BlockBox bounds() { + return bounds; + } + + @Override + public BlockState get(int x, int y, int z) { + requireInside(x, y, z); + return apiState(blocks, blocks.get(x, y + bottomY, z)); + } + + @Override + public void column(int x, int z, int fromY, BlockState[] into) { + for (int index = 0; index < into.length; index++) { + into[index] = get(x, fromY + index, z); + } + } + + @Override + public void set(int x, int y, int z, BlockState state) { + requireInside(x, y, z); + blocks.set(x, y + bottomY, z, nativeOf(state)); + } + + @Override + public boolean is(BlockState state, BlockTrait trait) { + NativeFitTrait nativeTrait = TRAITS.get(trait); + if (nativeTrait == null) { + throw new UnsupportedOperationException("A structure fit answers only " + TRAITS.keySet() + ", not " + trait); + } + return nativeTrait(blocks, nativeOf(state), nativeTrait); + } + + @Override + public boolean inTag(BlockState state, ResourceId tag) { + return blocks.inTag(nativeOf(state), tag.toString()); + } + + @Override + public boolean sturdy(int x, int y, int z, BlockFace face) { + requireInside(x, y, z); + return blocks.sturdy(x, y + bottomY, z, face.name()); + } + + @Override + public BlockState fluid(BlockState state) { + return apiState(blocks, blocks.fluid(nativeOf(state))); + } + + private S nativeOf(BlockState state) { + S known = written.get(state); + if (known == null) { + known = nativeState(blocks, state); + written.put(state, known); + } + return known; + } + + private void requireInside(int x, int y, int z) { + if (!bounds.contains(x, y, z)) { + throw new IndexOutOfBoundsException("Block " + x + ", " + y + ", " + z + " is outside the fitted chunk " + bounds); + } + } + } + + private static final class HostStart implements StructureFit.Start { + private final NativeFitStart start; + private final ResourceId structure; + private final List pieces; + + private HostStart(NativeFitStart start, NativeFitChunk chunk) { + this.start = start; + this.structure = ResourceId.parse(start.structureKey()); + List converted = new ArrayList<>(start.pieces().size()); + for (NativeFitPiece piece : start.pieces()) { + converted.add(new HostPiece<>(piece, chunk)); + } + this.pieces = List.copyOf(converted); + } + + @Override + public ResourceId structure() { + return structure; + } + + @Override + public int chunkX() { + return start.chunkX(); + } + + @Override + public int chunkZ() { + return start.chunkZ(); + } + + @Override + public StructureStep step() { + return StructureStep.valueOf(start.step()); + } + + @Override + public TerrainAdaptation adaptation() { + return TerrainAdaptation.valueOf(start.adaptation()); + } + + @Override + public Optional memo() { + NativeStartMemo memo = start.memo(); + return memo == null ? Optional.empty() : Optional.of(new StartMemo(memo.terrain(), memo.foundation())); + } + + @Override + public List pieces() { + return pieces; + } + + @Override + public Object key() { + return start.key(); + } + } + + private static final class HostPiece implements StructureFit.Piece { + private final NativeFitPiece piece; + private final NativeFitChunk chunk; + private final int bottomY; + + private HostPiece(NativeFitPiece piece, NativeFitChunk chunk) { + this.piece = piece; + this.chunk = chunk; + this.bottomY = chunk.bottomY(); + } + + @Override + public BlockBox box() { + return apiBox(piece.box(), bottomY); + } + + @Override + public PieceKind kind() { + return PieceKind.valueOf(piece.kind()); + } + + @Override + public int groundLevelDelta() { + return piece.groundLevelDelta(); + } + + @Override + public List junctions() { + List junctions = new ArrayList<>(piece.junctions().size()); + for (int[] junction : piece.junctions()) { + junctions.add(new BlockPosition(junction[0], junction[1] - bottomY, junction[2])); + } + return junctions; + } + + @Override + public TemplateCells cells(BlockBox region) { + NativeTemplateCells cells = piece.cells(nativeBox(region, bottomY)); + if (!cells.resolved()) { + return TemplateCells.UNRESOLVED; + } + int size = cells.states().length; + int[] ys = new int[size]; + BlockState[] states = new BlockState[size]; + for (int cell = 0; cell < size; cell++) { + ys[cell] = cells.ys()[cell] - bottomY; + S state = cells.states()[cell]; + states[cell] = state == null ? null : apiState(chunk.blocks(), state); + } + return TemplateCells.of(cells.xs(), ys, cells.zs(), states, cells.readBlocks()); + } + + @Override + public void columns(StructureFit.ColumnVisitor visitor) { + piece.columns((x, z, minY, maxY) -> visitor.column(x, z, minY - bottomY, maxY - bottomY)); + } + + @Override + public List legacyAir(BlockBox clip) { + List air = piece.legacyAir(nativeBox(clip, bottomY)); + List positions = new ArrayList<>(air.size()); + for (int[] position : air) { + positions.add(new BlockPosition(position[0], position[1] - bottomY, position[2])); + } + return positions; + } + } + + private static BlockBox apiBox(NativeFitBox box, int bottomY) { + return new BlockBox(box.minX(), box.minY() - bottomY, box.minZ(), box.maxX() + 1, box.maxY() + 1 - bottomY, + box.maxZ() + 1); + } + + private static NativeFitBox nativeBox(BlockBox box, int bottomY) { + return new NativeFitBox(box.minX(), box.minY() + bottomY, box.minZ(), box.maxX() - 1, box.maxY() - 1 + bottomY, + box.maxZ() - 1); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleVanillaStructures.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleVanillaStructures.java index aac2d7add..1c1a6d3c8 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleVanillaStructures.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleVanillaStructures.java @@ -20,17 +20,24 @@ package art.arcane.iris.core.modules; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.NativeJigsawOverrides; +import art.arcane.iris.engine.framework.NativeStartMemo; +import art.arcane.iris.engine.framework.NativeStartPlacement; +import art.arcane.iris.engine.framework.NativeStructureReach; import art.arcane.iris.engine.framework.NativeStructureStartPlan; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import com.volmit.config.PackSettings; import com.volmit.host.DiscoveredModule; -import com.volmit.host.VanillaStructureHookRegistration; +import com.volmit.host.ServiceRegistration; +import com.volmit.mantle.BlockBox; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; -import com.volmit.vanilla.VanillaStructureAdjustment; +import com.volmit.service.VanillaStructures; +import com.volmit.vanilla.JigsawOverrides; +import com.volmit.vanilla.PlatformStart; +import com.volmit.vanilla.StartMemo; +import com.volmit.vanilla.StartReach; import com.volmit.vanilla.VanillaStructureContext; -import com.volmit.vanilla.VanillaStructureHook; import com.volmit.vanilla.VanillaStructureRule; import com.volmit.vanilla.VanillaStructureSetup; import com.volmit.vanilla.VanillaStructureStart; @@ -43,31 +50,31 @@ import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.OptionalInt; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; /** - * What the pack's modules want for the platform's own structures, asked through their vanilla structure hooks in module - * id order: per structure in one engine's world the combined rule ({@link VanillaStructureRule#and}) and adjustment - * ({@link VanillaStructureAdjustment#then}), kept per engine and pack snapshot so a hotload or a reload of the pack's - * resources asks again; per chunk the starts modules place, converted to the host's plans; and per dimension, before a - * world exists, the combined setup ({@link VanillaStructureSetup#and}). The platform side applies the results on Bukkit - * and the modded platforms alike. + * What the pack's modules want for the platform's own structures, asked through their {@link VanillaStructures} + * providers in module id order: per structure in one engine's world the combined rule ({@link VanillaStructureRule#and}), + * kept per engine and pack snapshot so a hotload or a reload of the pack's resources asks again; per chunk the starts + * modules place, converted to the host's plans; per platform start the shift every module gives it and every module's + * reach; and per dimension, before a world exists, the combined setup ({@link VanillaStructureSetup#and}). The platform + * side applies the results on Bukkit and the modded platforms alike. */ public final class ModuleVanillaStructures { private static final Map WORLDS = Collections.synchronizedMap(new WeakHashMap<>()); private static final int START_TERRAIN_REACH_BLOCKS = 8; private final PackResources snapshot; - private final List hooks; + private final List providers; private final VanillaStructureContext world; private final Map rules = new ConcurrentHashMap<>(); - private final Map adjustments = new ConcurrentHashMap<>(); private ModuleVanillaStructures(Engine engine, PackResources snapshot) { this.snapshot = snapshot; - this.hooks = hooksOf(engine.getData()); + this.providers = providersOf(engine.getData()); this.world = new World(snapshot, new IrisPackSettings(engine)); } @@ -76,45 +83,72 @@ public final class ModuleVanillaStructures { return of(engine).rule(structureKey); } - /** - * The combined adjustment of the pack's modules for the platform's own starts of {@code structureKey} in - * {@code engine}'s world; {@code underground} is whether the platform generates it in an underground step. - */ - public static VanillaStructureAdjustment adjustmentFor(Engine engine, String structureKey, boolean underground) { - return of(engine).adjustment(structureKey, underground); - } - /** * The starts the pack's modules place in chunk {@code chunkX, chunkZ} of {@code engine}'s world, in module id order, - * as the host's plans: world heights, Iris's fit and jigsaw classes. + * as the host's plans: world heights, the platform's jigsaw changes and the modules' memos. */ public static List startsAt(Engine engine, int chunkX, int chunkZ) { StartContext context = new StartContext(engine.getGeneration().world(), new IrisTerrainSampler(engine, new PackResourceIds(engine.getData().getDataFolder()), chunkX << 4, chunkZ << 4, START_TERRAIN_REACH_BLOCKS)); List plans = new ArrayList<>(); - for (VanillaStructureHookRegistration registration : hooksOf(engine.getData())) { + for (ServiceRegistration registration : providersOf(engine.getData())) { for (VanillaStructureStart start : ask(registration, "placing starts in chunk " + chunkX + "," + chunkZ, - hook -> hook.starts(chunkX, chunkZ, context))) { + provider -> provider.starts(chunkX, chunkZ, context))) { plans.add(plan(registration.module(), start, chunkX, chunkZ, engine.getMinHeight())); } } return List.copyOf(plans); } + /** The shifts every module of the pack gives the platform's own start {@code start}, added up. */ + public static int shiftOf(Engine engine, NativeStartPlacement start) { + ModuleVanillaStructures structures = of(engine); + Optional structure = structureId(start.structureKey()); + if (structure.isEmpty()) { + return 0; + } + PlatformStart platformStart = new HostPlatformStart(structure.get(), start); + int shift = 0; + for (ServiceRegistration registration : structures.providers) { + shift = Math.addExact(shift, ask(registration, "moving vanilla structure " + structure.get(), + provider -> provider.shift(platformStart, structures.world))); + } + return shift; + } + + /** Every module's reach around a start of {@code structureKey}, placed by a module with {@code memo} or by the platform. */ + public static List reachesOf(Engine engine, String structureKey, boolean underground, + NativeStartMemo memo) { + ModuleVanillaStructures structures = of(engine); + Optional structure = structureId(structureKey); + if (structure.isEmpty()) { + return List.of(NativeStructureReach.PLATFORM); + } + Optional startMemo = Optional.ofNullable(memo).map(note -> new StartMemo(note.terrain(), note.foundation())); + List reaches = new ArrayList<>(structures.providers.size()); + for (ServiceRegistration registration : structures.providers) { + StartReach reach = ask(registration, "reaching around vanilla structure " + structure.get(), + provider -> provider.reach(structure.get(), underground, startMemo, structures.world)); + reaches.add(new NativeStructureReach(reach.platform(), reach.blocks())); + } + return reaches.isEmpty() ? List.of(NativeStructureReach.PLATFORM) : List.copyOf(reaches); + } + /** The combined setup of the pack's modules for {@code dimension} of the pack {@code data} serves, before any world exists. */ public static VanillaStructureSetup setupFor(IrisData data, IrisDimension dimension) { VanillaStructureContext context = new World(data.getPackResources(), new DimensionSettings(data, dimension)); VanillaStructureSetup combined = VanillaStructureSetup.UNCHANGED; - for (VanillaStructureHookRegistration registration : hooksOf(data)) { + for (ServiceRegistration registration : providersOf(data)) { combined = combined.and(ask(registration, "setting up the vanilla structures of dimension " + dimension.getLoadKey(), - hook -> hook.setup(context))); + provider -> provider.setup(context))); } return combined; } - private static List hooksOf(IrisData data) { - return data.getModules().pack().catalog().vanillaStructureHooks(); + /** The pack's {@link VanillaStructures} providers with the modules that registered them, in module id order. */ + static List providersOf(IrisData data) { + return data.getModules().pack().catalog().registrations(VanillaStructures.class); } private static ModuleVanillaStructures of(Engine engine) { @@ -132,10 +166,6 @@ public final class ModuleVanillaStructures { return rules.computeIfAbsent(structureKey, this::askRules); } - private VanillaStructureAdjustment adjustment(String structureKey, boolean underground) { - return adjustments.computeIfAbsent(new AdjustedStructure(structureKey, underground), this::askAdjustments); - } - /** A key that is no resource id names no structure a module could decide over. */ private VanillaStructureRule askRules(String structureKey) { Optional structure = structureId(structureKey); @@ -143,28 +173,14 @@ public final class ModuleVanillaStructures { return VanillaStructureRule.GENERATE; } VanillaStructureRule combined = VanillaStructureRule.GENERATE; - for (VanillaStructureHookRegistration registration : hooks) { + for (ServiceRegistration registration : providers) { VanillaStructureRule rule = ask(registration, "deciding over vanilla structure " + structure.get(), - hook -> hook.rule(structure.get(), world)); + provider -> provider.rule(structure.get(), world)); combined = combined.and(rule); } return combined; } - private VanillaStructureAdjustment askAdjustments(AdjustedStructure adjusted) { - Optional structure = structureId(adjusted.key()); - if (structure.isEmpty()) { - return VanillaStructureAdjustment.NONE; - } - VanillaStructureAdjustment combined = VanillaStructureAdjustment.NONE; - for (VanillaStructureHookRegistration registration : hooks) { - VanillaStructureAdjustment adjustment = ask(registration, "adjusting vanilla structure " + structure.get(), - hook -> hook.adjustment(structure.get(), adjusted.underground(), world)); - combined = combined.then(adjustment); - } - return combined; - } - private static Optional structureId(String structureKey) { try { return Optional.of(ResourceId.parse(structureKey)); @@ -173,12 +189,11 @@ public final class ModuleVanillaStructures { } } - /** One hook's answer to {@code question}; a hook that throws or answers nothing fails naming its module. */ - private static T ask(VanillaStructureHookRegistration registration, String question, - Function answer) { + /** One provider's answer to {@code question}; a provider that throws or answers nothing fails naming its module. */ + static T ask(ServiceRegistration registration, String question, Function answer) { T result; try { - result = answer.apply(registration.hook()); + result = answer.apply((VanillaStructures) registration.provider()); } catch (RuntimeException failure) { throw new IllegalStateException("Module " + registration.module() + " failed " + question + ": " + failure, failure); } @@ -202,18 +217,72 @@ public final class ModuleVanillaStructures { start.isUnderground(), start.replacesPlatformStart(), start.identity(), - start.jigsaw().map(IrisValues::jigsawConfiguration).orElse(null), - start.fit().stilts().map(IrisValues::structureStilts).orElse(null), - start.fit().terrain().map(IrisValues::structureTerrain).orElseGet(IrisStructureTerrain::new)); + start.jigsaw().map(ModuleVanillaStructures::jigsaw).orElse(null), + start.memo().map(memo -> new NativeStartMemo(memo.terrain(), memo.foundation())).orElse(null)); } - /** The world the hooks decide for: the engine's pack snapshot and the settings its dimension reaches. */ + private static NativeJigsawOverrides jigsaw(JigsawOverrides overrides) { + return new NativeJigsawOverrides( + overrides.startPool(), + overrides.startJigsawName(), + boxed(overrides.maxDepth()), + boxed(overrides.maxDistanceHorizontal()), + boxed(overrides.maxDistanceVertical()), + overrides.useExpansionHack().orElse(null), + overrides.projectStartToHeightmap().name(), + boxed(overrides.dimensionPaddingBottom()), + boxed(overrides.dimensionPaddingTop()), + overrides.liquidSettings().name()); + } + + private static Integer boxed(OptionalInt value) { + return value.isPresent() ? value.getAsInt() : null; + } + + /** The world the providers decide for: the engine's pack snapshot and the settings its dimension reaches. */ private record World(PackResources resources, PackSettings settings) implements VanillaStructureContext { } private record StartContext(PackWorld world, TerrainSampler terrain) implements VanillaStructureStartContext { } - private record AdjustedStructure(String key, boolean underground) { + /** A platform start in the API's heights: above the dimension's bottom, maxima exclusive. */ + private record HostPlatformStart(ResourceId structure, NativeStartPlacement start) implements PlatformStart { + @Override + public int chunkX() { + return start.chunkX(); + } + + @Override + public int chunkZ() { + return start.chunkZ(); + } + + @Override + public BlockBox bounds() { + int bottom = start.bottomY(); + return new BlockBox(start.minX(), start.minY() - bottom, start.minZ(), + start.maxX() + 1, start.maxY() + 1 - bottom, start.maxZ() + 1); + } + + @Override + public boolean underground() { + return start.underground(); + } + + @Override + public boolean aligned() { + return start.aligned(); + } + + @Override + public int bottomY() { + return start.bottomY(); + } + + @Override + public int surfaceY(int x, int z) { + return start.surfaceY().applyAsInt(x, z) - start.bottomY(); + } } } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/NativeJigsawOverrides.java b/core/src/main/java/art/arcane/iris/engine/framework/NativeJigsawOverrides.java new file mode 100644 index 000000000..17c4a25b1 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/NativeJigsawOverrides.java @@ -0,0 +1,21 @@ +package art.arcane.iris.engine.framework; + +/** + * Changes a module makes to a jigsaw structure's registered definition before the platform assembles a start of it, + * as the platform code applies them: a blank text or a null value keeps the definition's own. The heightmap and liquid + * settings are the names of the API's {@code JigsawOverrides} constants ({@code SOURCE} keeps the definition's). + */ +public record NativeJigsawOverrides( + String startPool, + String startJigsawName, + Integer maxDepth, + Integer maxDistanceHorizontal, + Integer maxDistanceVertical, + Boolean useExpansionHack, + String projectStartToHeightmap, + Integer dimensionPaddingBottom, + Integer dimensionPaddingTop, + String liquidSettings +) { + public static final String SOURCE = "SOURCE"; +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/NativeStartMemo.java b/core/src/main/java/art/arcane/iris/engine/framework/NativeStartMemo.java new file mode 100644 index 000000000..8b1d82e99 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/NativeStartMemo.java @@ -0,0 +1,14 @@ +package art.arcane.iris.engine.framework; + +import java.util.Objects; + +/** + * What a module noted about a start it placed, as the host keeps it: two texts in the module's own format, one about + * the start's terrain and one about its foundation. The host never reads them. + */ +public record NativeStartMemo(String terrain, String foundation) { + public NativeStartMemo { + Objects.requireNonNull(terrain, "terrain"); + Objects.requireNonNull(foundation, "foundation"); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/NativeStartPlacement.java b/core/src/main/java/art/arcane/iris/engine/framework/NativeStartPlacement.java new file mode 100644 index 000000000..9fce929b7 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/NativeStartPlacement.java @@ -0,0 +1,31 @@ +package art.arcane.iris.engine.framework; + +import java.util.Objects; +import java.util.function.IntBinaryOperator; + +/** + * One of the platform's own starts before the host publishes it, as the platform code sees it: its structure, start + * chunk, the box around its pieces in world heights (every bound inclusive), whether the platform generates it in an + * underground step, whether the host aligns it itself (an ocean monument to the sea level, a desert or jungle temple + * to the terrain), the world's bottom height and the terrain's surface height per column in world heights. + */ +public record NativeStartPlacement( + String structureKey, + int chunkX, + int chunkZ, + int minX, + int minY, + int minZ, + int maxX, + int maxY, + int maxZ, + boolean underground, + boolean aligned, + int bottomY, + IntBinaryOperator surfaceY +) { + public NativeStartPlacement { + Objects.requireNonNull(structureKey, "structureKey"); + Objects.requireNonNull(surfaceY, "surfaceY"); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureGenerationPolicy.java b/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureGenerationPolicy.java index 71fb8a50a..df06dd73e 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureGenerationPolicy.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureGenerationPolicy.java @@ -18,44 +18,32 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.core.modules.IrisValues; import art.arcane.iris.core.modules.ModuleVanillaStructures; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; -import com.volmit.vanilla.VanillaStructureAdjustment; -import com.volmit.vanilla.VanillaStructureFit; import com.volmit.vanilla.VanillaStructureRule; import java.util.Objects; /** - * Whether the platform generates one of its own structures in an engine's world, and how its starts are adjusted, the - * same on every platform: the rule and adjustment the pack's modules give the structure through their vanilla - * structure hooks ({@link ModuleVanillaStructures}). A structure a module blocks does not generate; one a module - * places itself is reported as replaced, so find, goto and verify locate the module's placement. + * Whether the platform generates one of its own structures in an engine's world, the same on every platform: the rule + * the pack's modules give the structure through their {@code VanillaStructures} providers + * ({@link ModuleVanillaStructures}). A structure a module blocks does not generate; one a module places itself is + * reported as replaced, so find, goto and verify locate the module's placement. */ public final class NativeStructureGenerationPolicy { private NativeStructureGenerationPolicy() { } - public static IrisNativeStructureDecision resolve(Engine engine, String structureKey, - boolean undergroundStep) { + public static NativeStructureGenerationStatus resolve(Engine engine, String structureKey) { Engine activeEngine = Objects.requireNonNull(engine, "Native structure policy requires an engine"); if (structureKey == null || structureKey.isBlank()) { - return decision(NativeStructureGenerationStatus.INVALID_REGISTRY_KEY, VanillaStructureAdjustment.NONE); + return NativeStructureGenerationStatus.INVALID_REGISTRY_KEY; } - VanillaStructureRule rule = ModuleVanillaStructures.ruleFor(activeEngine, structureKey); - VanillaStructureAdjustment adjustment = ModuleVanillaStructures.adjustmentFor(activeEngine, structureKey, undergroundStep); - return decision(status(rule), adjustment); + return status(ModuleVanillaStructures.ruleFor(activeEngine, structureKey)); } - private static IrisNativeStructureDecision decision(NativeStructureGenerationStatus status, - VanillaStructureAdjustment adjustment) { - VanillaStructureFit fit = adjustment.fit(); - return new IrisNativeStructureDecision(status, adjustment.yShift(), - adjustment.yBand().map(IrisValues::yBand).orElse(null), adjustment.keepsSourceY(), - fit.stilts().map(IrisValues::structureStilts).orElse(null), - fit.terrain().map(IrisValues::structureTerrain).orElse(null)); + /** Whether the platform generates {@code structureKey} itself in {@code engine}'s world. */ + public static boolean generates(Engine engine, String structureKey) { + return resolve(engine, structureKey) == NativeStructureGenerationStatus.GENERATE_NATIVE; } private static NativeStructureGenerationStatus status(VanillaStructureRule rule) { diff --git a/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureGenerationStatus.java b/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureGenerationStatus.java new file mode 100644 index 000000000..f9c09aaac --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureGenerationStatus.java @@ -0,0 +1,26 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.framework; + +public enum NativeStructureGenerationStatus { + GENERATE_NATIVE, + DISABLED_BY_PACK, + REPLACED_BY_IRIS, + INVALID_REGISTRY_KEY +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureLayouts.java b/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureLayouts.java new file mode 100644 index 000000000..5a69afd3c --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureLayouts.java @@ -0,0 +1,29 @@ +package art.arcane.iris.engine.framework; + +import art.arcane.iris.core.modules.ModuleVanillaStructures; + +import java.util.List; + +/** + * Where the platform's own starts sit and how far around their pieces the pack's modules change the terrain, as the + * platform code asks before it publishes a start: the shift every module gives a start, added up, and every module's + * reach. + */ +public final class NativeStructureLayouts { + private NativeStructureLayouts() { + } + + /** How far the pack's modules move {@code start} up (negative: down), before the platform keeps it inside the world. */ + public static int shift(Engine engine, NativeStartPlacement start) { + return ModuleVanillaStructures.shiftOf(engine, start); + } + + /** + * How far every module of the pack changes the terrain around a start of {@code structureKey}: a start a module + * placed, with the {@code memo} it gave it, or one of the platform's own (null memo). + */ + public static List reaches(Engine engine, String structureKey, boolean underground, + NativeStartMemo memo) { + return ModuleVanillaStructures.reachesOf(engine, structureKey, underground, memo); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureOwnershipRecord.java b/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureOwnershipRecord.java index b79190a3a..a7281d5e8 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureOwnershipRecord.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureOwnershipRecord.java @@ -1,10 +1,5 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; -import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; -import com.google.gson.Gson; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -32,7 +27,7 @@ public record NativeStructureOwnershipRecord( int referenceMinChunkZ, int referenceMaxChunkZ, String contentFingerprint, - DecisionSnapshot decision + MemoSnapshot memo ) { public static final int CURRENT_SCHEMA = 2; public static final int MAX_REFERENCE_DISTANCE_CHUNKS = 8; @@ -69,7 +64,7 @@ public record NativeStructureOwnershipRecord( if (!contentFingerprint.matches("[0-9a-f]{64}")) { throw new IllegalArgumentException("Native structure content fingerprint must be SHA-256 hex"); } - decision = Objects.requireNonNull(decision, "Native structure decision snapshot must not be null"); + memo = Objects.requireNonNull(memo, "Native structure memo snapshot must not be null"); } public static NativeStructureOwnershipRecord create(String structureKey, @@ -89,7 +84,7 @@ public record NativeStructureOwnershipRecord( int referenceMinChunkZ, int referenceMaxChunkZ, String contentFingerprint, - IrisNativeStructureDecision decision) { + NativeStartMemo memo) { return new NativeStructureOwnershipRecord( CURRENT_SCHEMA, structureKey, @@ -109,7 +104,7 @@ public record NativeStructureOwnershipRecord( referenceMinChunkZ, referenceMaxChunkZ, contentFingerprint, - DecisionSnapshot.capture(decision) + MemoSnapshot.of(memo) ); } @@ -140,7 +135,7 @@ public record NativeStructureOwnershipRecord( referenceMinChunkZ, referenceMaxChunkZ, contentFingerprint, - decision + memo ); } @@ -148,8 +143,9 @@ public record NativeStructureOwnershipRecord( return new OwnershipKey(structureKey, originChunkX, originChunkZ); } - public IrisNativeStructureDecision restoredDecision() { - return decision.restore(); + /** The memo the module gave the start when it placed it; null when it gave none. */ + public NativeStartMemo restoredMemo() { + return memo.restore(); } void write(DataOutputStream output) throws IOException { @@ -171,7 +167,7 @@ public record NativeStructureOwnershipRecord( output.writeInt(referenceMinChunkZ); output.writeInt(referenceMaxChunkZ); writeString(output, contentFingerprint, MAX_FINGERPRINT_BYTES, "content fingerprint"); - decision.write(output); + memo.write(output); } static NativeStructureOwnershipRecord read(DataInputStream input) throws IOException { @@ -199,7 +195,7 @@ public record NativeStructureOwnershipRecord( input.readInt(), input.readInt(), readString(input, MAX_FINGERPRINT_BYTES, "content fingerprint"), - DecisionSnapshot.read(input) + MemoSnapshot.read(input) ); } catch (IllegalArgumentException exception) { throw new IOException("Native structure ownership record is invalid", exception); @@ -251,56 +247,39 @@ public record NativeStructureOwnershipRecord( } } - public record DecisionSnapshot(String stiltJson, String terrainJson) { - private static final Gson GSON = new Gson(); - private static final int MAX_JSON_BYTES = 65_536; + /** + * The start's memo as the record stores it: the foundation text, then the terrain text. Records written before + * memos existed hold the JSON of the start's stilts and terrain fit in these two places, which is what the module + * writes as its memo, so they read the same. A start without a memo stores two empty texts. + */ + public record MemoSnapshot(String foundation, String terrain) { + private static final int MAX_MEMO_BYTES = 65_536; + private static final MemoSnapshot NONE = new MemoSnapshot("", ""); - public DecisionSnapshot { - stiltJson = Objects.requireNonNull(stiltJson, "Native structure stilt snapshot must not be null"); - terrainJson = Objects.requireNonNull(terrainJson, "Native structure terrain snapshot must not be null"); - requireUtf8Limit(stiltJson, MAX_JSON_BYTES, "stilt snapshot"); - requireUtf8Limit(terrainJson, MAX_JSON_BYTES, "terrain snapshot"); + public MemoSnapshot { + foundation = Objects.requireNonNull(foundation, "Native structure foundation memo must not be null"); + terrain = Objects.requireNonNull(terrain, "Native structure terrain memo must not be null"); + requireUtf8Limit(foundation, MAX_MEMO_BYTES, "foundation memo"); + requireUtf8Limit(terrain, MAX_MEMO_BYTES, "terrain memo"); } - public static DecisionSnapshot capture(IrisNativeStructureDecision decision) { - IrisNativeStructureDecision resolved = Objects.requireNonNull( - decision, "Native structure decision must not be null"); - if (!resolved.generate()) { - throw new IllegalArgumentException("Only generated native structure decisions can be persisted"); - } - return new DecisionSnapshot( - GSON.toJson(resolved.stilt()), - GSON.toJson(Objects.requireNonNullElseGet( - resolved.terrain(), IrisStructureTerrain::new)) - ); + public static MemoSnapshot of(NativeStartMemo memo) { + return memo == null ? NONE : new MemoSnapshot(memo.foundation(), memo.terrain()); } - public IrisNativeStructureDecision restore() { - IrisStructureStiltSettings stilt = "null".equals(stiltJson) - ? null : GSON.fromJson(stiltJson, IrisStructureStiltSettings.class); - IrisStructureTerrain terrain = GSON.fromJson(terrainJson, IrisStructureTerrain.class); - if (terrain == null) { - throw new IllegalStateException("Persisted native structure terrain snapshot is null"); - } - return new IrisNativeStructureDecision( - NativeStructureGenerationStatus.GENERATE_NATIVE, - 0, - null, - false, - stilt, - terrain - ); + public NativeStartMemo restore() { + return equals(NONE) ? null : new NativeStartMemo(terrain, foundation); } void write(DataOutputStream output) throws IOException { - writeString(output, stiltJson, MAX_JSON_BYTES, "stilt snapshot"); - writeString(output, terrainJson, MAX_JSON_BYTES, "terrain snapshot"); + writeString(output, foundation, MAX_MEMO_BYTES, "foundation memo"); + writeString(output, terrain, MAX_MEMO_BYTES, "terrain memo"); } - static DecisionSnapshot read(DataInputStream input) throws IOException { - return new DecisionSnapshot( - readString(input, MAX_JSON_BYTES, "stilt snapshot"), - readString(input, MAX_JSON_BYTES, "terrain snapshot") + static MemoSnapshot read(DataInputStream input) throws IOException { + return new MemoSnapshot( + readString(input, MAX_MEMO_BYTES, "foundation memo"), + readString(input, MAX_MEMO_BYTES, "terrain memo") ); } } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureReach.java b/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureReach.java new file mode 100644 index 000000000..1cb19d805 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureReach.java @@ -0,0 +1,10 @@ +package art.arcane.iris.engine.framework; + +/** + * How far around a start's pieces a module changes the terrain: the area the platform's own terrain adaptation of the + * structure covers ({@link #platform()}), or a number of blocks around the pieces. The platform code hands the start + * to every chunk any module's reach covers. + */ +public record NativeStructureReach(boolean platform, int blocks) { + public static final NativeStructureReach PLATFORM = new NativeStructureReach(true, 0); +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureStartPlan.java b/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureStartPlan.java index 243c6dc7c..8588b8563 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureStartPlan.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/NativeStructureStartPlan.java @@ -1,19 +1,13 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConfiguration; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; - import java.util.Objects; /** * One start of a platform structure a module places, as the platform code builds it: the structure key, the start * chunk, the world base Y (the structure's lowest block when underground, the planned surface otherwise), whether it - * takes the chunk from a platform start of the same structure, the identity of what placed it, and Iris's jigsaw, - * stilt and terrain classes for the module's jigsaw overrides and fit. {@code jigsaw} and {@code stilt} may be null; - * {@code terrain} is never null ({@code SOURCE} when the module states none). + * takes the chunk from a platform start of the same structure, the identity of what placed it, the changes to the + * jigsaw definition it is assembled with (null for none), and the memo the module gave it (null for none), which the + * ownership record keeps for every later chunk of the start. */ public record NativeStructureStartPlan( String structureKey, @@ -23,17 +17,10 @@ public record NativeStructureStartPlan( boolean underground, boolean replacesPlatformStart, long placementIdentity, - IrisJigsawConfiguration jigsaw, - IrisStructureStiltSettings stilt, - IrisStructureTerrain terrain + NativeJigsawOverrides jigsaw, + NativeStartMemo memo ) { public NativeStructureStartPlan { Objects.requireNonNull(structureKey, "Native structure start plan requires a structure key"); - Objects.requireNonNull(terrain, "Native structure start plan requires a terrain fit"); - } - - /** The platform decision this start is generated under: generated natively with the start's own fit. */ - public IrisNativeStructureDecision decision() { - return new IrisNativeStructureDecision(NativeStructureGenerationStatus.GENERATE_NATIVE, 0, null, false, stilt, terrain); } } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitBlocks.java b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitBlocks.java new file mode 100644 index 000000000..1bbb0a310 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitBlocks.java @@ -0,0 +1,29 @@ +package art.arcane.iris.engine.framework.nativefit; + +/** + * The live blocks of the chunk the platform decorates, in the platform's own block states {@code S}, at world + * coordinates, and the questions a structure fit asks about them. + */ +public interface NativeFitBlocks { + S get(int x, int y, int z); + + /** Replaces the block without updating neighbours, the way the platform's decoration writes. */ + void set(int x, int y, int z, S state); + + /** The state's key with its properties, such as {@code minecraft:oak_stairs[facing=east,half=bottom]}. */ + String key(S state); + + /** The state {@link #key} names. */ + S state(String key); + + boolean is(S state, NativeFitTrait trait); + + /** Whether the state is in the platform's block tag {@code tag}, such as {@code minecraft:logs}. */ + boolean inTag(S state, String tag); + + /** Whether the block at the position can carry a full block on its face named {@code face} ({@code UP} ...). */ + boolean sturdy(int x, int y, int z, String face); + + /** The block of the fluid the state holds; air when it holds none. */ + S fluid(S state); +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitBox.java b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitBox.java new file mode 100644 index 000000000..915cf4c3e --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitBox.java @@ -0,0 +1,5 @@ +package art.arcane.iris.engine.framework.nativefit; + +/** A box of world blocks as the platform measures it: world heights, every bound inclusive. */ +public record NativeFitBox(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitChunk.java b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitChunk.java new file mode 100644 index 000000000..2080a136b --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitChunk.java @@ -0,0 +1,31 @@ +package art.arcane.iris.engine.framework.nativefit; + +import java.util.List; +import java.util.Objects; +import java.util.function.IntBinaryOperator; +import java.util.function.IntFunction; + +/** + * One chunk the platform decorates with structure starts, as the platform code hands it to the modules' fit: its live + * blocks, the area it writes ({@code area}, world heights, inclusive), the world's bottom and top heights, the world + * seed, the terrain's surface height per column and the platform's natural block per height (both world heights), and + * the starts in the order the platform places them. + */ +public record NativeFitChunk( + NativeFitBlocks blocks, + NativeFitBox area, + int bottomY, + int topY, + long seed, + IntBinaryOperator surfaceY, + IntFunction naturalBlock, + List> starts +) { + public NativeFitChunk { + Objects.requireNonNull(blocks, "blocks"); + Objects.requireNonNull(area, "area"); + Objects.requireNonNull(surfaceY, "surfaceY"); + Objects.requireNonNull(naturalBlock, "naturalBlock"); + starts = List.copyOf(starts); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitPiece.java b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitPiece.java new file mode 100644 index 000000000..afdb8cdee --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitPiece.java @@ -0,0 +1,29 @@ +package art.arcane.iris.engine.framework.nativefit; + +import java.util.List; + +/** A piece of a start, as the platform code reads it, in world heights. */ +public interface NativeFitPiece { + NativeFitBox box(); + + /** {@code FIXED}, {@code RIGID} or {@code TERRAIN_MATCHING}, the names of the API's {@code PieceKind}. */ + String kind(); + + int groundLevelDelta(); + + /** Each jigsaw junction's source X, ground height and Z. */ + List junctions(); + + NativeTemplateCells cells(NativeFitBox region); + + void columns(ColumnVisitor visitor); + + /** The positions ({@code {x, y, z}}) of the legacy template air inside {@code clip}. */ + List legacyAir(NativeFitBox clip); + + /** Receives one vertical span per column, both heights inclusive world heights. */ + @FunctionalInterface + interface ColumnVisitor { + void column(int x, int z, int minY, int maxY); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitStart.java b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitStart.java new file mode 100644 index 000000000..e15a207a1 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitStart.java @@ -0,0 +1,28 @@ +package art.arcane.iris.engine.framework.nativefit; + +import art.arcane.iris.engine.framework.NativeStartMemo; + +import java.util.List; + +/** A start the platform places in the chunk it decorates, as the platform code reads it. */ +public interface NativeFitStart { + String structureKey(); + + int chunkX(); + + int chunkZ(); + + /** The name of the platform's decoration step, as the API's {@code StructureStep} names it. */ + String step(); + + /** The name of the structure definition's terrain adaptation, as the API's {@code TerrainAdaptation} names it. */ + String adaptation(); + + /** The memo the module that placed the start gave it; null for the platform's own starts. */ + NativeStartMemo memo(); + + List> pieces(); + + /** The same object for this start every chunk, for as long as the platform keeps the start. */ + Object key(); +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitTrait.java b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitTrait.java new file mode 100644 index 000000000..d9055e4c0 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeFitTrait.java @@ -0,0 +1,15 @@ +package art.arcane.iris.engine.framework.nativefit; + +/** The block questions a structure fit asks the platform about a state. */ +public enum NativeFitTrait { + /** Air. */ + AIR, + /** What the platform counts as solid. */ + SOLID, + /** Holds a fluid: a source, a flowing fluid or a waterlogged block. */ + FLUID, + /** A log, wood, stem or hyphae, by tag or by name. */ + LOG, + /** Leaves, by tag or by name. */ + LEAVES +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeStructureFitting.java b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeStructureFitting.java new file mode 100644 index 000000000..27d660cb9 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeStructureFitting.java @@ -0,0 +1,32 @@ +package art.arcane.iris.engine.framework.nativefit; + +import art.arcane.iris.core.modules.ModuleStructureFitting; +import art.arcane.iris.engine.framework.Engine; + +/** + * The pack's modules fitting a chunk's structure starts into the terrain, around the platform placing their pieces: + * {@link #beforePieces} once before any piece of the chunk is placed, then {@link Session#afterPieces} after each + * start's pieces, in the order of the chunk's starts. + */ +public interface NativeStructureFitting { + Session beforePieces(NativeFitChunk chunk); + + /** The modules of {@code engine}'s pack, fitting in its world. */ + static NativeStructureFitting of(Engine engine) { + return ModuleStructureFitting.of(engine); + } + + /** + * Iris's built-in modules outside any world, for starts whose fit their memo records and whose fit uses no palette; + * a fit that needs the world or the pack's resources fails. For tools and tests that drive the platform side alone. + */ + static NativeStructureFitting builtInModules() { + return ModuleStructureFitting.builtInModules(); + } + + /** One chunk's fit, between its starts' placements. */ + interface Session { + /** Called after the platform placed the pieces of the chunk's start number {@code startIndex}. */ + void afterPieces(int startIndex); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeTemplateCells.java b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeTemplateCells.java new file mode 100644 index 000000000..4088d02fc --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeTemplateCells.java @@ -0,0 +1,9 @@ +package art.arcane.iris.engine.framework.nativefit; + +/** + * A piece's processed template blocks inside a region, at world positions: {@code states[i]} is the block at + * {@code (xs[i], ys[i], zs[i])}, null where the processors removed the template's block. {@code resolved} is false for + * a piece without a template. {@code readBlocks} counts the template blocks the platform read and processed. + */ +public record NativeTemplateCells(boolean resolved, int[] xs, int[] ys, int[] zs, S[] states, int readBlocks) { +} diff --git a/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandler.java b/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandler.java index 29ef5ebab..01bb99b2d 100644 --- a/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandler.java +++ b/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandler.java @@ -23,8 +23,7 @@ import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; import art.arcane.iris.engine.framework.StructureReachability; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; +import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.PlatformStructureHooks; import art.arcane.iris.util.common.director.DirectorParameterHandler; @@ -116,27 +115,27 @@ public class StructureHandler implements DirectorParameterHandler { private static boolean isEligibleRegisteredKey(Engine engine, String key, String normalizedKey, Set reachableKeys, boolean nativeGenerationEnabled) { - IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, key, false); + NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key); boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key); boolean locatableNativePlacement = nativePlacement && IrisStructureLocator.hasLocatableNativePlacement(engine, key); boolean locatableEditableReplacement = !nativePlacement - && decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS + && status == NativeStructureGenerationStatus.REPLACED_BY_IRIS && ModuleServices.canLocateStructure(engine, key); return isEligibleRegisteredKey( - decision, nativePlacement, locatableNativePlacement, locatableEditableReplacement, + status, nativePlacement, locatableNativePlacement, locatableEditableReplacement, reachableKeys.contains(normalizedKey), nativeGenerationEnabled); } - static boolean isEligibleRegisteredKey(IrisNativeStructureDecision decision, boolean nativePlacement, + static boolean isEligibleRegisteredKey(NativeStructureGenerationStatus status, boolean nativePlacement, boolean locatableNativePlacement, boolean locatableEditableReplacement, boolean reachable, boolean nativeGenerationEnabled) { - if (decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS) { + if (status == NativeStructureGenerationStatus.REPLACED_BY_IRIS) { return locatableEditableReplacement || nativeGenerationEnabled && nativePlacement && locatableNativePlacement; } - return nativeGenerationEnabled && decision.generate() + return nativeGenerationEnabled && status == NativeStructureGenerationStatus.GENERATE_NATIVE && (reachable || (nativePlacement && locatableNativePlacement)); } diff --git a/core/src/test/java/art/arcane/iris/builtin/structure/StructureFitSettingsTest.java b/core/src/test/java/art/arcane/iris/builtin/structure/StructureFitSettingsTest.java new file mode 100644 index 000000000..3c277bb4e --- /dev/null +++ b/core/src/test/java/art/arcane/iris/builtin/structure/StructureFitSettingsTest.java @@ -0,0 +1,142 @@ +package art.arcane.iris.builtin.structure; + +import com.google.gson.Gson; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import org.junit.Test; + +import java.lang.reflect.Field; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** The terrain fit, stilts and Y band settings of {@code iris:structure} as packs write them. */ +public class StructureFitSettingsTest { + private static final Gson JSON = new Gson(); + + @Test + public void terrainDefaultsToSourceWithBoxCarving() { + StructureTerrain terrain = terrain("{}"); + + assertEquals(StructureTerrainMode.SOURCE, terrain.resolvedMode()); + assertEquals(StructureCarveShape.BOX, terrain.resolvedShape()); + assertEquals(0.8D, terrain.resolvedErosionStrength(), 0D); + assertEquals(0.07D, terrain.resolvedErosionFrequency(), 0D); + assertEquals(0.021D, terrain.resolvedLobeFrequency(), 1.0E-12D); + assertEquals(0.85D, terrain.resolvedLobeStrength(), 0D); + assertTrue(terrain.encasePalette().isEmpty()); + } + + @Test + public void lobeFrequencyAutoDerivesFromErosionFrequencyUntilAuthored() { + assertEquals(0.015D, terrain("{\"erosionFrequency\":0.05}").resolvedLobeFrequency(), 1.0E-12D); + assertEquals(0.015D, terrain("{\"erosionFrequency\":0.05,\"lobeFrequency\":\"NaN\"}").resolvedLobeFrequency(), 1.0E-12D); + assertEquals(0.015D, terrain("{\"erosionFrequency\":0.05,\"lobeFrequency\":-1}").resolvedLobeFrequency(), 1.0E-12D); + assertEquals(0.04D, terrain("{\"erosionFrequency\":0.05,\"lobeFrequency\":0.04}").resolvedLobeFrequency(), 0D); + assertEquals(1D, terrain("{\"erosionFrequency\":0.05,\"lobeFrequency\":2}").resolvedLobeFrequency(), 0D); + } + + @Test + public void lobeStrengthClampsToTheAuthoredBand() { + assertEquals(0.85D, terrain("{\"lobeStrength\":\"NaN\"}").resolvedLobeStrength(), 0D); + assertEquals(0D, terrain("{\"lobeStrength\":-1}").resolvedLobeStrength(), 0D); + assertEquals(1D, terrain("{\"lobeStrength\":2}").resolvedLobeStrength(), 0D); + assertEquals(0.4D, terrain("{\"lobeStrength\":0.4}").resolvedLobeStrength(), 0D); + } + + @Test + public void carveShapesExposeTheirMaximumCeilingScale() { + assertEquals(1D, StructureCarveShape.BOX.maximumCeilingScale(), 0D); + assertEquals(1D, StructureCarveShape.ROUNDED.maximumCeilingScale(), 0D); + assertEquals(1.8D, StructureCarveShape.ERODED.maximumCeilingScale(), 0D); + assertEquals(10, StructureCarveShape.BOX.maximumCeilingExtension(10)); + assertEquals(10, StructureCarveShape.ROUNDED.maximumCeilingExtension(10)); + assertEquals(18, StructureCarveShape.ERODED.maximumCeilingExtension(10)); + assertEquals(10, StructureCarveShape.ERODED.maximumCeilingExtension(10, 0D)); + assertEquals(14, StructureCarveShape.ERODED.maximumCeilingExtension(10, 0.5D)); + assertEquals(0, StructureCarveShape.ERODED.maximumCeilingExtension(0)); + } + + @Test + public void nullAndNonFiniteValuesResolveToDefaults() { + StructureTerrain terrain = terrain("{\"shape\":null,\"erosionStrength\":\"NaN\",\"erosionFrequency\":\"Infinity\"}"); + + assertEquals(StructureCarveShape.BOX, terrain.resolvedShape()); + assertEquals(0.8D, terrain.resolvedErosionStrength(), 0D); + assertEquals(0.07D, terrain.resolvedErosionFrequency(), 0D); + StructureTerrain negative = terrain("{\"erosionStrength\":\"-Infinity\",\"erosionFrequency\":\"NaN\"}"); + assertEquals(0.8D, negative.resolvedErosionStrength(), 0D); + assertEquals(0.07D, negative.resolvedErosionFrequency(), 0D); + } + + @Test + public void finiteValuesClampToAuthoredBounds() { + StructureTerrain low = terrain("{\"erosionStrength\":-1,\"erosionFrequency\":0}"); + StructureTerrain high = terrain("{\"erosionStrength\":2,\"erosionFrequency\":2}"); + + assertEquals(0D, low.resolvedErosionStrength(), 0D); + assertEquals(0.001D, low.resolvedErosionFrequency(), 0D); + assertEquals(1D, high.resolvedErosionStrength(), 0D); + assertEquals(1D, high.resolvedErosionFrequency(), 0D); + } + + @Test + public void encaseModeCarriesAnOptionalPaletteOverride() { + StructureTerrain encase = terrain("{\"mode\":\"ENCASE\",\"encasePalette\":{\"palette\":[{\"block\":\"minecraft:tuff\"}]}}"); + + assertEquals(StructureTerrainMode.ENCASE, encase.resolvedMode()); + assertEquals("minecraft:tuff", encase.encasePalette().orElseThrow().palette().getFirst().block()); + } + + @Test + public void stiltsDefaultToACobblestoneFoundation() { + StructureStilts stilts = new StructureStilts(); + + assertEquals(64, stilts.maxDepth()); + assertEquals(1, stilts.spacing()); + assertFalse(stilts.supportNonOccluding()); + assertEquals(1, stilts.palette().orElseThrow().palette().size()); + assertEquals("minecraft:cobblestone", stilts.palette().orElseThrow().palette().getFirst().block()); + } + + @Test + public void bandBoundsResolveInOrderEvenWhenReversed() { + StructureYBand band = JSON.fromJson("{\"min\":-20,\"max\":-120}", StructureYBand.class); + StructureYBand collapsed = JSON.fromJson("{\"min\":-64,\"max\":-64}", StructureYBand.class); + + assertEquals(-120, band.resolvedMin()); + assertEquals(-20, band.resolvedMax()); + assertEquals(-64, collapsed.resolvedMin()); + assertEquals(-64, collapsed.resolvedMax()); + } + + @Test + public void numericSchemaBoundsMatchRuntimeBounds() throws NoSuchFieldException { + assertBounds(StructureTerrain.class, "erosionStrength", 0D, 1D); + assertBounds(StructureTerrain.class, "erosionFrequency", 0.001D, 1D); + assertBounds(StructureTerrain.class, "lobeFrequency", 0D, 1D); + assertBounds(StructureTerrain.class, "lobeStrength", 0D, 1D); + assertBounds(StructureStilts.class, "maxDepth", 1D, 4064D); + assertBounds(StructureStilts.class, "spacing", 1D, 64D); + assertBounds(StructureYBand.class, "min", -4064D, 4064D); + assertBounds(StructureYBand.class, "max", -4064D, 4064D); + } + + private static StructureTerrain terrain(String json) { + return JSON.fromJson(json, StructureTerrain.class); + } + + private static void assertBounds(Class type, String fieldName, double expectedMinimum, double expectedMaximum) + throws NoSuchFieldException { + Field field = type.getDeclaredField(fieldName); + MinNumber minimum = field.getAnnotation(MinNumber.class); + MaxNumber maximum = field.getAnnotation(MaxNumber.class); + + assertNotNull(minimum); + assertNotNull(maximum); + assertEquals(expectedMinimum, minimum.value(), 0D); + assertEquals(expectedMaximum, maximum.value(), 0D); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/modules/PackBeforeThePortDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/PackBeforeThePortDecodingTest.java index c7f6424ef..69b1b2204 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/PackBeforeThePortDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/PackBeforeThePortDecodingTest.java @@ -30,7 +30,7 @@ import com.volmit.FeatureAttachment.Target; import com.volmit.block.BlockSpec; import com.volmit.host.LoadedPack; import com.volmit.host.ModuleHost; -import com.volmit.vanilla.StructureTerrain; +import art.arcane.iris.builtin.structure.StructureTerrainMode; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -139,7 +139,7 @@ public class PackBeforeThePortDecodingTest { assertTrue(structures.datapackOverrides()); assertEquals(4, structures.adjustments().size()); assertEquals(List.of("minecraft:stronghold"), structures.adjustments().getFirst().match()); - assertEquals(StructureTerrain.Mode.ENCASE, structures.adjustments().getFirst().terrain().orElseThrow().mode()); + assertEquals(StructureTerrainMode.ENCASE, structures.adjustments().getFirst().terrain().orElseThrow().resolvedMode()); assertEquals(-64, structures.adjustments().get(1).yShift()); assertTrue(structures.adjustments().get(2).preserveSourceY()); assertEquals(2, structures.adjustments().get(3).stilt().orElseThrow().maxDepth()); diff --git a/core/src/test/java/art/arcane/iris/core/modules/StructureSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/StructureSettingsDecodingTest.java index 60a26827a..7fff48ad5 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/StructureSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/StructureSettingsDecodingTest.java @@ -2,16 +2,14 @@ package art.arcane.iris.core.modules; import art.arcane.iris.builtin.structure.StructureAdjustment; import art.arcane.iris.builtin.structure.StructureSettings; -import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; +import art.arcane.iris.builtin.structure.StructureTerrain; +import art.arcane.iris.builtin.structure.StructureTerrainMode; import art.arcane.volmlib.util.json.JSONObject; import com.google.gson.Gson; import com.volmit.FeatureAttachment.Target; import com.volmit.block.BlockSpec; import com.volmit.host.LoadedPack; import com.volmit.host.ModuleHost; -import com.volmit.vanilla.StructureTerrain; -import com.volmit.vanilla.YBand; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -21,7 +19,6 @@ import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.nio.file.Path; import java.util.List; -import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -93,29 +90,31 @@ public class StructureSettingsDecodingTest { List adjustments = settings.adjustments(); assertEquals(4, adjustments.size()); StructureAdjustment stronghold = adjustments.getFirst(); - assertEquals(Optional.of(YBand.of(-120, -20)), stronghold.yBand()); + assertEquals(-120, stronghold.yBand().orElseThrow().resolvedMin()); + assertEquals(-20, stronghold.yBand().orElseThrow().resolvedMax()); StructureTerrain terrain = stronghold.terrain().orElseThrow(); - assertEquals(StructureTerrain.Mode.ENCASE, terrain.mode()); + assertEquals(StructureTerrainMode.ENCASE, terrain.resolvedMode()); assertEquals(4, terrain.horizontalPadding()); assertEquals(BlockSpec.of("minecraft:stone_bricks").withWeight(6), terrain.encasePalette().orElseThrow().palette().getFirst()); assertEquals(-64, adjustments.get(1).yShift()); assertTrue(adjustments.get(2).preserveSourceY()); assertEquals(2, adjustments.get(3).stilt().orElseThrow().maxDepth()); - assertEquals(List.of(BlockSpec.of("minecraft:dirt")), adjustments.get(3).stilt().orElseThrow().palette().palette()); + assertEquals(List.of(BlockSpec.of("minecraft:dirt")), adjustments.get(3).stilt().orElseThrow().palette().orElseThrow().palette()); } + /** Starts remember their fit as the JSON of these settings, so the settings must write back what the pack wrote. */ @Test - public void fitsBecomeTheIrisClassesTheOldDimensionFieldReadFromTheSameJson() { - JSONObject json = new JSONObject(MIGRATED_DIMENSION).getJSONObject("importedStructures").getJSONArray("adjustments").getJSONObject(0); - JSONObject stiltJson = new JSONObject(MIGRATED_DIMENSION).getJSONObject("importedStructures").getJSONArray("adjustments") - .getJSONObject(3).getJSONObject("stilt"); - List adjustments = settings(MIGRATED_DIMENSION).adjustments(); + public void fitsWriteBackTheJsonThePackWrote() { + JSONObject adjustments = new JSONObject(MIGRATED_DIMENSION).getJSONObject("importedStructures"); + JSONObject terrainJson = adjustments.getJSONArray("adjustments").getJSONObject(0).getJSONObject("terrain"); + JSONObject stiltJson = adjustments.getJSONArray("adjustments").getJSONObject(3).getJSONObject("stilt"); + List decoded = settings(MIGRATED_DIMENSION).adjustments(); Gson gson = new Gson(); - assertEquals(gson.toJson(gson.fromJson(json.getJSONObject("terrain").toString(), IrisStructureTerrain.class)), - gson.toJson(IrisValues.structureTerrain(adjustments.getFirst().terrain().orElseThrow()))); - assertEquals(gson.toJson(gson.fromJson(stiltJson.toString(), IrisStructureStiltSettings.class)), - gson.toJson(IrisValues.structureStilts(adjustments.get(3).stilt().orElseThrow()))); + assertEquals(gson.toJson(gson.fromJson(terrainJson.toString(), StructureTerrain.class)), + gson.toJson(decoded.getFirst().terrain().orElseThrow())); + assertEquals(gson.toJson(gson.fromJson(stiltJson.toString(), art.arcane.iris.builtin.structure.StructureStilts.class)), + gson.toJson(decoded.get(3).stilt().orElseThrow())); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/project/SchemaBuilderParityTest.java b/core/src/test/java/art/arcane/iris/core/project/SchemaBuilderParityTest.java index df16969b2..4d715378a 100644 --- a/core/src/test/java/art/arcane/iris/core/project/SchemaBuilderParityTest.java +++ b/core/src/test/java/art/arcane/iris/core/project/SchemaBuilderParityTest.java @@ -183,10 +183,6 @@ public class SchemaBuilderParityTest { JSONObject erosionFrequency = terrainProperties.getJSONObject("erosionFrequency"); JSONObject lobeFrequency = terrainProperties.getJSONObject("lobeFrequency"); JSONObject lobeStrength = terrainProperties.getJSONObject("lobeStrength"); - String carveShapeDefinition = carveShape.getString("$ref") - .substring("#/definitions/".length()); - String terrainModeDefinition = terrainMode.getString("$ref") - .substring("#/definitions/".length()); assertTrue(properties.has("structures")); assertTrue(properties.has("nativeStructures")); @@ -195,9 +191,8 @@ public class SchemaBuilderParityTest { "The editable structures backend supports SOURCE, PRESERVE, BORE, and FORCE_CARVE. " + "The nativeStructures backend supports every terrain mode.")); assertEquals(List.of("SOURCE", "PRESERVE", "BORE", "FORCE_CARVE", "VACUUM", "ENCASE"), - oneOfValues(schema.getJSONObject("definitions"), terrainModeDefinition)); - assertEquals(List.of("BOX", "ROUNDED", "ERODED"), oneOfValues( - schema.getJSONObject("definitions"), carveShapeDefinition)); + values(terrainMode.getJSONArray("enum"))); + assertEquals(List.of("BOX", "ROUNDED", "ERODED"), values(carveShape.getJSONArray("enum"))); assertEquals(0D, erosionStrength.getDouble("minimum"), 0D); assertEquals(1D, erosionStrength.getDouble("maximum"), 0D); assertEquals(0.001D, erosionFrequency.getDouble("minimum"), 0D); @@ -237,19 +232,18 @@ public class SchemaBuilderParityTest { } @Test - public void structureSettingsRenderTheirFitsWithIrisDefinitionsOfTheSameJson() throws IOException { + public void structureSettingsRenderTheirFitsWithTheModulesDefinitions() throws IOException { JSONObject schema = new SchemaBuilder(IrisDimension.class, structureSchemaData(structureSettingsSchema())).construct(); JSONObject definitions = schema.getJSONObject("definitions"); JSONObject settings = definitions.getJSONObject(definitionKey(rootProperties(schema).getJSONObject("importedStructures"))) .getJSONObject("properties"); JSONObject adjustment = definitions.getJSONObject(definitionKey(settings.getJSONObject("adjustments").getJSONObject("items"))) .getJSONObject("properties"); - JSONObject band = irisDefinition(definitions, adjustment.getJSONObject("yBand")).getJSONObject("properties"); - JSONObject stilt = irisDefinition(definitions, adjustment.getJSONObject("stilt")).getJSONObject("properties"); - JSONObject terrain = irisDefinition(definitions, adjustment.getJSONObject("terrain")).getJSONObject("properties"); + JSONObject band = definitions.getJSONObject(definitionKey(adjustment.getJSONObject("yBand"))).getJSONObject("properties"); + JSONObject stilt = definitions.getJSONObject(definitionKey(adjustment.getJSONObject("stilt"))).getJSONObject("properties"); + JSONObject terrain = definitions.getJSONObject(definitionKey(adjustment.getJSONObject("terrain"))).getJSONObject("properties"); - assertEquals("obj-art-arcane-iris-engine-object-structure-irisstructureyband", - definitionKey(definitions.getJSONObject(definitionKey(adjustment.getJSONObject("yBand"))))); + assertEquals("module-art-arcane-iris-builtin-structure-structureyband", definitionKey(adjustment.getJSONObject("yBand"))); assertEquals("boolean", adjustment.getJSONObject("preserveSourceY").getString("type")); assertEquals(-4064, band.getJSONObject("min").getInt("minimum")); assertEquals(4064, band.getJSONObject("max").getInt("maximum")); @@ -477,10 +471,6 @@ public class SchemaBuilderParityTest { } /** The definition an API value type's reference leads to: the module's, which refers to Iris's own. */ - private static JSONObject irisDefinition(JSONObject definitions, JSONObject reference) { - return definitions.getJSONObject(definitionKey(definitions.getJSONObject(definitionKey(reference)))); - } - private static String definitionKey(JSONObject reference) { return reference.getString("$ref").substring("#/definitions/".length()); } @@ -490,7 +480,10 @@ public class SchemaBuilderParityTest { } private static List enumValues(JSONObject definitions, String key) { - JSONArray array = definitions.getJSONObject(key).getJSONArray("enum"); + return values(definitions.getJSONObject(key).getJSONArray("enum")); + } + + private static List values(JSONArray array) { List values = new ArrayList<>(array.length()); for (int index = 0; index < array.length(); index++) { values.add(array.getString(index)); diff --git a/core/src/test/java/art/arcane/iris/engine/framework/IrisStructureLocatorContractTest.java b/core/src/test/java/art/arcane/iris/engine/framework/IrisStructureLocatorContractTest.java index 21ef5fad8..32dceb65c 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/IrisStructureLocatorContractTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/IrisStructureLocatorContractTest.java @@ -18,6 +18,9 @@ package art.arcane.iris.engine.framework; +import art.arcane.iris.builtin.structure.StructureTerrain; +import com.google.gson.Gson; + import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.core.modules.ModuleResourceFixture; @@ -35,10 +38,7 @@ import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode; -import art.arcane.iris.engine.object.structure.IrisStructureCarveShape; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression; import art.arcane.iris.engine.object.structure.StructureDistribution; import art.arcane.volmlib.util.collection.KList; @@ -652,27 +652,22 @@ public class IrisStructureLocatorContractTest { placement.setUnderground(true); placement.setMinHeight(-64); placement.setMaxHeight(100); - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.FORCE_CARVE) - .setHorizontalPadding(2) - .setCeilingPadding(20) - .setShape(IrisStructureCarveShape.ERODED); - placement.setTerrain(terrain); + placement.setTerrain(forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":20,\"shape\":\"ERODED\"")); KList pieces = new KList<>(); pieces.add(piece(0, 60, 0, 1, 80, 1)); assertEquals(Integer.valueOf(-14), IrisStructureLocator.resolveUndergroundBurialShift( engine, pieces, placement, 60, -63, 319)); - terrain.setErosionStrength(0D); + placement.setTerrain(forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":20,\"shape\":\"ERODED\",\"erosionStrength\":0")); assertEquals(Integer.valueOf(-1), IrisStructureLocator.resolveUndergroundBurialShift( engine, pieces, placement, 60, -63, 319)); - terrain.setShape(IrisStructureCarveShape.ROUNDED); + placement.setTerrain(forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":20,\"shape\":\"ROUNDED\",\"erosionStrength\":0")); assertEquals(Integer.valueOf(-1), IrisStructureLocator.resolveUndergroundBurialShift( engine, pieces, placement, 60, -63, 319)); - terrain.setCeilingPadding(0); + placement.setTerrain(forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":0,\"shape\":\"ROUNDED\",\"erosionStrength\":0")); assertEquals(Integer.valueOf(0), IrisStructureLocator.resolveUndergroundBurialShift( engine, pieces, placement, 60, -63, 319)); } @@ -686,11 +681,7 @@ public class IrisStructureLocatorContractTest { .setUnderground(true) .setMinHeight(-64) .setMaxHeight(100) - .setTerrain(new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.FORCE_CARVE) - .setShape(IrisStructureCarveShape.ROUNDED) - .setHorizontalPadding(0) - .setCeilingPadding(0)); + .setTerrain(forceCarve("\"shape\":\"ROUNDED\",\"horizontalPadding\":0,\"ceilingPadding\":0")); KList pieces = new KList<>(); pieces.add(piece(4, 60, 7, 4, 80, 7)); @@ -867,4 +858,8 @@ public class IrisStructureLocatorContractTest { int nearestOriginX, int nearestOriginZ) { } + + private static StructureTerrain forceCarve(String options) { + return new Gson().fromJson("{\"mode\":\"FORCE_CARVE\"," + options + "}", StructureTerrain.class); + } } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureGenerationPolicyTest.java b/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureGenerationPolicyTest.java index c9ab3cbbd..a40c052e7 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureGenerationPolicyTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureGenerationPolicyTest.java @@ -8,11 +8,8 @@ import art.arcane.iris.core.modules.ModuleSettings; import art.arcane.iris.core.modules.IrisPackResources; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression; import art.arcane.volmlib.util.collection.KList; import com.volmit.FeatureRegistry; @@ -20,16 +17,15 @@ import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.host.LoadedPack; import com.volmit.stage.StageGraph; -import com.volmit.block.BlockSpec; -import com.volmit.block.PaletteSpec; +import art.arcane.iris.builtin.structure.StructureTerrain; +import art.arcane.iris.core.modules.ModuleVanillaStructures; +import com.google.gson.Gson; import com.volmit.resource.ResourceId; -import com.volmit.vanilla.StructureStilts; -import com.volmit.vanilla.StructureTerrain; -import com.volmit.vanilla.VanillaStructureAdjustment; +import com.volmit.service.VanillaStructures; +import com.volmit.vanilla.PlatformStart; +import com.volmit.vanilla.StartMemo; +import com.volmit.vanilla.StartReach; import com.volmit.vanilla.VanillaStructureContext; -import com.volmit.vanilla.VanillaStructureFit; -import com.volmit.vanilla.VanillaStructureHook; -import com.volmit.vanilla.YBand; import com.volmit.vanilla.VanillaStructureRule; import org.junit.After; import org.junit.Rule; @@ -39,6 +35,7 @@ import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; @@ -82,17 +79,16 @@ public class NativeStructureGenerationPolicyTest { Engine engine = engineWithDisabledNamespaceAndRegionPlacement("nova_structures:tavern_oak"); assertEquals(NativeStructureGenerationStatus.REPLACED_BY_IRIS, - NativeStructureGenerationPolicy.resolve(engine, "nova_structures:tavern_oak", false).status()); + NativeStructureGenerationPolicy.resolve(engine, "nova_structures:tavern_oak")); } @Test public void disabledKeyWithoutPlacementStaysDisabled() throws IOException { Engine engine = engineWithDisabledNamespaceAndRegionPlacement("nova_structures:tavern_oak"); - IrisNativeStructureDecision decision = - NativeStructureGenerationPolicy.resolve(engine, "nova_structures:witch_villa", false); - assertEquals(NativeStructureGenerationStatus.DISABLED_BY_PACK, decision.status()); - assertFalse(decision.generate()); + assertEquals(NativeStructureGenerationStatus.DISABLED_BY_PACK, + NativeStructureGenerationPolicy.resolve(engine, "nova_structures:witch_villa")); + assertFalse(NativeStructureGenerationPolicy.generates(engine, "nova_structures:witch_villa")); } @Test @@ -102,12 +98,12 @@ public class NativeStructureGenerationPolicyTest { Engine engine = engine(settings, regionPlacement("nova_structures:tavern_oak"), new KList<>(), List.of()); assertEquals(NativeStructureGenerationStatus.DISABLED_BY_PACK, - NativeStructureGenerationPolicy.resolve(engine, "minecraft:ruined_portal", false).status()); + NativeStructureGenerationPolicy.resolve(engine, "minecraft:ruined_portal")); assertEquals(NativeStructureGenerationStatus.GENERATE_NATIVE, - NativeStructureGenerationPolicy.resolve(engine, "minecraft:ruined_portal_nether", false).status()); + NativeStructureGenerationPolicy.resolve(engine, "minecraft:ruined_portal_nether")); } - /** The pilot of the vanilla structure hook: suppression now comes from the iris:structure module's rule. */ + /** Suppression comes from the iris:structure module's rule. */ @Test public void aStructureAnIrisPlacementReplacesIsBlockedByTheStructureModule() throws IOException { IrisStructurePlacement replacement = new IrisStructurePlacement().setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE); @@ -116,99 +112,105 @@ public class NativeStructureGenerationPolicyTest { dimensionPlacements.add(replacement); Engine engine = engine(allowingEverything(), new KList<>(), dimensionPlacements, List.of()); - IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, "minecraft:village_plains", false); - assertEquals(NativeStructureGenerationStatus.REPLACED_BY_IRIS, decision.status()); - assertFalse(decision.generate()); + assertEquals(NativeStructureGenerationStatus.REPLACED_BY_IRIS, + NativeStructureGenerationPolicy.resolve(engine, "minecraft:village_plains")); + assertFalse(NativeStructureGenerationPolicy.generates(engine, "minecraft:village_plains")); assertEquals(NativeStructureGenerationStatus.GENERATE_NATIVE, - NativeStructureGenerationPolicy.resolve(engine, "minecraft:village_desert", false).status()); + NativeStructureGenerationPolicy.resolve(engine, "minecraft:village_desert")); } @Test public void aStructureAPlacementAlsoPlacesStillGeneratesNatively() throws IOException { Engine engine = engine(allowingEverything(), regionPlacement("minecraft:village_plains"), new KList<>(), List.of()); - assertTrue(NativeStructureGenerationPolicy.resolve(engine, "minecraft:village_plains", false).generate()); + assertTrue(NativeStructureGenerationPolicy.generates(engine, "minecraft:village_plains")); } @Test - public void packModulesBlockOrReplaceStructuresThroughTheirHooks() throws IOException { - Engine engine = engine(allowingEverything(), new KList<>(), new KList<>(), List.of(new HookModule((structure, world) -> + public void packModulesBlockOrReplaceStructuresThroughTheirRules() throws IOException { + Engine engine = engine(allowingEverything(), new KList<>(), new KList<>(), List.of(new ProviderModule(ruling((structure, world) -> switch (structure.path()) { case "pillager_outpost" -> VanillaStructureRule.BLOCK; case "igloo" -> VanillaStructureRule.REPLACE; default -> VanillaStructureRule.GENERATE; - }))); + })))); assertEquals(NativeStructureGenerationStatus.DISABLED_BY_PACK, - NativeStructureGenerationPolicy.resolve(engine, "minecraft:pillager_outpost", false).status()); + NativeStructureGenerationPolicy.resolve(engine, "minecraft:pillager_outpost")); assertEquals(NativeStructureGenerationStatus.REPLACED_BY_IRIS, - NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo", false).status()); + NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo")); assertEquals(NativeStructureGenerationStatus.GENERATE_NATIVE, - NativeStructureGenerationPolicy.resolve(engine, "minecraft:mansion", false).status()); + NativeStructureGenerationPolicy.resolve(engine, "minecraft:mansion")); } @Test - public void hooksAreAskedOncePerStructureAndPackSnapshot() throws IOException { + public void rulesAreAskedOncePerStructureAndPackSnapshot() throws IOException { AtomicInteger asked = new AtomicInteger(); - Engine engine = engine(allowingEverything(), new KList<>(), new KList<>(), List.of(new HookModule((structure, world) -> { + Engine engine = engine(allowingEverything(), new KList<>(), new KList<>(), List.of(new ProviderModule(ruling((structure, world) -> { asked.incrementAndGet(); return VanillaStructureRule.GENERATE; - }))); + })))); - NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo", false); - NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo", true); + NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo"); + NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo"); assertEquals(1, asked.get()); IrisData data = engine.getData(); IrisPackResources reloaded = new IrisPackResources(data); when(data.getPackResources()).thenReturn(reloaded); - NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo", false); + NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo"); assertEquals("a new snapshot asks again", 2, asked.get()); } @Test - public void aHookThatFailsNamesItsModule() throws IOException { - Engine engine = engine(allowingEverything(), new KList<>(), new KList<>(), List.of(new HookModule((structure, world) -> { + public void aProviderThatFailsNamesItsModule() throws IOException { + Engine engine = engine(allowingEverything(), new KList<>(), new KList<>(), List.of(new ProviderModule(ruling((structure, world) -> { throw new IllegalArgumentException("broken"); - }))); + })))); IllegalStateException failure = assertThrows(IllegalStateException.class, - () -> NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo", false)); + () -> NativeStructureGenerationPolicy.resolve(engine, "minecraft:igloo")); assertTrue(failure.getMessage(), failure.getMessage().startsWith( "Module test:hook from host classpath failed deciding over vanilla structure minecraft:igloo: ")); } @Test - public void adjustmentsOfTheSettingsAndOfPackModulesReachTheDecisionAsIrisClasses() throws IOException { - StructureTerrain bore = StructureTerrain.of(StructureTerrain.Mode.BORE).withPadding(6, 2, 1); + public void shiftsAndReachesOfTheSettingsAndOfPackModulesAddUpPerModule() throws IOException { + StructureTerrain bore = new Gson().fromJson("{\"mode\":\"BORE\",\"horizontalPadding\":6}", StructureTerrain.class); StructureSettings settings = new StructureSettings(List.of(), List.of(), -32, true, List.of(), List.of( - new StructureAdjustment(List.of("minecraft:stronghold"), 4, YBand.of(-20, -100), false, null, bore))); - StructureStilts stilts = StructureStilts.of(PaletteSpec.of(List.of(BlockSpec.of("minecraft:stone_bricks")))).withSpacing(2); - Engine engine = engine(settings, new KList<>(), new KList<>(), List.of(new HookModule(new VanillaStructureHook() { + new StructureAdjustment(List.of("minecraft:stronghold"), 4, null, true, null, bore))); + Engine engine = engine(settings, new KList<>(), new KList<>(), List.of(new ProviderModule(new VanillaStructures() { @Override - public VanillaStructureRule rule(ResourceId structure, VanillaStructureContext context) { - return VanillaStructureRule.GENERATE; + public int shift(PlatformStart start, VanillaStructureContext context) { + return -1; } @Override - public VanillaStructureAdjustment adjustment(ResourceId structure, boolean underground, VanillaStructureContext context) { - return VanillaStructureAdjustment.NONE.shifted(-1).keepingSourceY() - .withFit(VanillaStructureFit.SOURCE.withStilts(stilts)); + public StartReach reach(ResourceId structure, boolean underground, Optional memo, + VanillaStructureContext context) { + return StartReach.blocks(3); } }))); - IrisNativeStructureDecision stronghold = NativeStructureGenerationPolicy.resolve(engine, "minecraft:stronghold", true); + assertEquals(-29, ModuleVanillaStructures.shiftOf(engine, placement("minecraft:stronghold", true))); + assertEquals(List.of(new NativeStructureReach(false, 6), new NativeStructureReach(false, 3)), + ModuleVanillaStructures.reachesOf(engine, "minecraft:stronghold", true, null)); + assertEquals(-1, ModuleVanillaStructures.shiftOf(engine, placement("minecraft:village_plains", false))); + assertEquals(List.of(NativeStructureReach.PLATFORM, new NativeStructureReach(false, 3)), + ModuleVanillaStructures.reachesOf(engine, "minecraft:village_plains", false, null)); + } - assertEquals(-29, stronghold.yShift()); - assertTrue(stronghold.preserveSourceY()); - assertEquals(-100, stronghold.yBand().resolvedMin()); - assertEquals(IrisStructureTerrainMode.BORE, stronghold.terrain().resolvedMode()); - assertEquals(6, stronghold.terrain().getHorizontalPadding()); - assertEquals(2, stronghold.stilt().getSpacing()); - assertEquals("minecraft:stone_bricks", stronghold.stilt().getPalette().getPalette().getFirst().getBlock()); - IrisNativeStructureDecision village = NativeStructureGenerationPolicy.resolve(engine, "minecraft:village_plains", false); - assertEquals(-1, village.yShift()); - assertEquals(null, village.terrain()); + private static NativeStartPlacement placement(String structureKey, boolean underground) { + return new NativeStartPlacement(structureKey, 0, 0, 0, 10, 0, 20, 30, 20, underground, false, -64, (x, z) -> 100); + } + + private static VanillaStructures ruling(RuleAnswer rule) { + return new VanillaStructures() { + @Override + public VanillaStructureRule rule(ResourceId structure, VanillaStructureContext context) { + return rule.decide(structure, context); + } + }; } private Engine engineWithDisabledNamespaceAndRegionPlacement(String placedKey) throws IOException { @@ -251,8 +253,12 @@ public class NativeStructureGenerationPolicyTest { return engine; } - /** A pack module whose only part is a vanilla structure hook. */ - private record HookModule(VanillaStructureHook hook) implements IrisModule { + private interface RuleAnswer { + VanillaStructureRule decide(ResourceId structure, VanillaStructureContext context); + } + + /** A pack module whose only part is a vanilla structures provider. */ + private record ProviderModule(VanillaStructures provider) implements IrisModule { @Override public ModuleInfo info() { return ModuleInfo.of("test:hook", "Hook", "1"); @@ -264,7 +270,7 @@ public class NativeStructureGenerationPolicyTest { @Override public void register(FeatureRegistry registry) { - registry.registerVanillaStructureHook(hook); + registry.registerService(VanillaStructures.class, provider); } } } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureOwnershipRecordTest.java b/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureOwnershipRecordTest.java index 1556c6c87..19c7fd3c3 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureOwnershipRecordTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureOwnershipRecordTest.java @@ -1,11 +1,9 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; -import art.arcane.iris.engine.object.structure.IrisStructureCarveShape; -import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; +import art.arcane.iris.builtin.structure.StructureCarveShape; +import art.arcane.iris.builtin.structure.StructureTerrainMode; +import art.arcane.iris.engine.framework.structure.NativeStructureFit; +import com.volmit.vanilla.StartMemo; import org.junit.Test; import java.io.ByteArrayInputStream; @@ -45,46 +43,42 @@ public class NativeStructureOwnershipRecordTest { assertEquals(crypt, restored.find("nova_structures:undead_crypt", 4, -7)); } + /** The stilts and terrain fit JSON records written before memos hold, as the old Iris classes wrote them. */ @Test - public void decisionSnapshotFreezesTerrainAndStiltSettings() { - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.FORCE_CARVE) - .setHorizontalPadding(9) - .setCeilingPadding(3) - .setFloorPadding(2) - .setShape(IrisStructureCarveShape.ERODED) - .setErosionStrength(0.42D) - .setErosionFrequency(0.17D) - .setLobeFrequency(0.03D) - .setLobeStrength(0.61D); - IrisStructureStiltSettings stilt = new IrisStructureStiltSettings() - .setMaxDepth(91) - .setSpacing(4) - .setSupportNonOccluding(true); - IrisNativeStructureDecision source = new IrisNativeStructureDecision( - NativeStructureGenerationStatus.GENERATE_NATIVE, - 0, - null, - false, - stilt, - terrain - ); + public void recordsWrittenBeforeMemosReadAsTheStructureModulesMemo() throws Exception { + String stilts = "{\"maxDepth\":91,\"palette\":{\"style\":{\"style\":\"STATIC\",\"cellularFrequency\":0.0," + + "\"cellularZoom\":1.0,\"zoom\":1.0,\"multiplier\":1.0,\"exponent\":1.0,\"cacheSize\":0},\"zoom\":5.0," + + "\"palette\":[{\"block\":\"minecraft:stone_bricks\",\"debug\":false,\"weight\":2," + + "\"data\":{\"waterlogged\":false},\"tileData\":{}}]},\"spacing\":4,\"supportNonOccluding\":true}"; + String terrain = "{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":9,\"ceilingPadding\":3,\"floorPadding\":2," + + "\"shape\":\"ERODED\",\"erosionStrength\":0.42,\"erosionFrequency\":0.17,\"lobeFrequency\":0.03," + + "\"lobeStrength\":0.61}"; + ByteArrayOutputStream encoded = new ByteArrayOutputStream(); + new NativeStructureOwnershipRecord.MemoSnapshot(stilts, terrain).write(new DataOutputStream(encoded)); - NativeStructureOwnershipRecord.DecisionSnapshot snapshot = - NativeStructureOwnershipRecord.DecisionSnapshot.capture(source); - terrain.setHorizontalPadding(1); - stilt.setMaxDepth(2); - IrisNativeStructureDecision restored = snapshot.restore(); + NativeStartMemo memo = NativeStructureOwnershipRecord.MemoSnapshot.read( + new DataInputStream(new ByteArrayInputStream(encoded.toByteArray()))).restore(); + NativeStructureFit fit = NativeStructureFit.of(new StartMemo(memo.terrain(), memo.foundation())); - assertTrue(restored.generate()); - assertEquals(IrisStructureTerrainMode.FORCE_CARVE, restored.terrain().resolvedMode()); - assertEquals(IrisStructureCarveShape.ERODED, restored.terrain().resolvedShape()); - assertEquals(9, restored.terrain().getHorizontalPadding()); - assertEquals(0.42D, restored.terrain().getErosionStrength(), 0D); - assertNotNull(restored.stilt()); - assertEquals(91, restored.stilt().getMaxDepth()); - assertEquals(4, restored.stilt().getSpacing()); - assertTrue(restored.stilt().isSupportNonOccluding()); + assertEquals(StructureTerrainMode.FORCE_CARVE, fit.terrain().resolvedMode()); + assertEquals(StructureCarveShape.ERODED, fit.terrain().resolvedShape()); + assertEquals(9, fit.terrain().horizontalPadding()); + assertEquals(0.42D, fit.terrain().resolvedErosionStrength(), 0D); + assertEquals(0.61D, fit.terrain().resolvedLobeStrength(), 0D); + assertEquals(91, fit.stilts().maxDepth()); + assertEquals(4, fit.stilts().spacing()); + assertTrue(fit.stilts().supportNonOccluding()); + assertEquals("minecraft:stone_bricks", fit.stilts().palette().orElseThrow().palette().getFirst().block()); + assertEquals(2, fit.stilts().palette().orElseThrow().palette().getFirst().weight()); + } + + @Test + public void aStartWithoutAMemoRoundTripsWithoutOne() throws Exception { + ByteArrayOutputStream encoded = new ByteArrayOutputStream(); + NativeStructureOwnershipRecord.MemoSnapshot.of(null).write(new DataOutputStream(encoded)); + + assertNull(NativeStructureOwnershipRecord.MemoSnapshot.read( + new DataInputStream(new ByteArrayInputStream(encoded.toByteArray()))).restore()); } @Test @@ -120,7 +114,7 @@ public class NativeStructureOwnershipRecordTest { assertEquals(original.contentMaxZ(), refreshed.contentMaxZ()); assertEquals(original.locatorY(), refreshed.locatorY()); assertEquals(original.contentFingerprint(), refreshed.contentFingerprint()); - assertEquals(original.decision(), refreshed.decision()); + assertEquals(original.memo(), refreshed.memo()); assertEquals(-6, refreshed.referenceMinChunkX()); assertEquals(0, refreshed.referenceMaxChunkX()); assertEquals(6, refreshed.referenceMinChunkZ()); @@ -184,8 +178,8 @@ public class NativeStructureOwnershipRecordTest { Map oversized = new LinkedHashMap<>(); - NativeStructureOwnershipRecord.DecisionSnapshot largeDecision = - new NativeStructureOwnershipRecord.DecisionSnapshot( + NativeStructureOwnershipRecord.MemoSnapshot largeDecision = + new NativeStructureOwnershipRecord.MemoSnapshot( "null", "{\"unused\":\"" + "x".repeat(65_000) + "\"}" ); @@ -298,7 +292,8 @@ public class NativeStructureOwnershipRecordTest { @Test public void nullableStiltRoundTripsAsNull() { NativeStructureOwnershipRecord record = record("test:no_stilt", 0, 0, 1L); - assertNull(record.restoredDecision().stilt()); + NativeStartMemo memo = record.restoredMemo(); + assertNull(NativeStructureFit.of(new StartMemo(memo.terrain(), memo.foundation())).stilts()); } @Test @@ -369,15 +364,8 @@ public class NativeStructureOwnershipRecordTest { ); } - private static NativeStructureOwnershipRecord.DecisionSnapshot decision() { - return NativeStructureOwnershipRecord.DecisionSnapshot.capture( - new IrisNativeStructureDecision( - NativeStructureGenerationStatus.GENERATE_NATIVE, - 0, - null, - false, - null, - new IrisStructureTerrain() - )); + private static NativeStructureOwnershipRecord.MemoSnapshot decision() { + StartMemo memo = NativeStructureFit.NONE.memo(); + return NativeStructureOwnershipRecord.MemoSnapshot.of(new NativeStartMemo(memo.terrain(), memo.foundation())); } } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureOwnershipStoreTest.java b/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureOwnershipStoreTest.java index c2a5a9592..a42aa200c 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureOwnershipStoreTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureOwnershipStoreTest.java @@ -1,8 +1,5 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; import org.junit.Test; import java.util.Map; @@ -49,9 +46,9 @@ public class NativeStructureOwnershipStoreTest { Engine engine = engine(); TestStorage storage = new TestStorage(); NativeStructureOwnershipRecord stale = record("test:replacement", 2, 3, 11L, - new IrisStructureTerrain().setHorizontalPadding(2), 8); + terrain(2), 8); NativeStructureOwnershipRecord current = record("test:replacement", 2, 3, 11L, - new IrisStructureTerrain().setHorizontalPadding(9), 8); + terrain(9), 8); long origin = NativeStructureOwnershipStore.pack(2, 3); long target = NativeStructureOwnershipStore.pack(3, 4); storage.write(origin, current); @@ -63,7 +60,7 @@ public class NativeStructureOwnershipStoreTest { 3, 4, current.structureKey(), 2, 3); assertEquals(current, resolved); - assertEquals(9, resolved.restoredDecision().terrain().getHorizontalPadding()); + assertEquals(terrain(9), resolved.restoredMemo().terrain()); assertEquals(stale.contentFingerprint(), resolved.contentFingerprint()); assertEquals(stale, storage.find(target, stale)); } @@ -409,18 +406,18 @@ public class NativeStructureOwnershipStoreTest { private static NativeStructureOwnershipRecord record(String key, int originX, int originZ, long placementIdentity) { - return record(key, originX, originZ, placementIdentity, new IrisStructureTerrain(), 8); + return record(key, originX, originZ, placementIdentity, "{}", 8); } private static NativeStructureOwnershipRecord record(String key, int originX, int originZ, long placementIdentity, int referenceRadius) { - return record(key, originX, originZ, placementIdentity, new IrisStructureTerrain(), referenceRadius); + return record(key, originX, originZ, placementIdentity, "{}", referenceRadius); } private static NativeStructureOwnershipRecord record(String key, int originX, int originZ, long placementIdentity, - IrisStructureTerrain terrain, + String terrain, int referenceRadius) { return new NativeStructureOwnershipRecord( NativeStructureOwnershipRecord.CURRENT_SCHEMA, @@ -441,18 +438,14 @@ public class NativeStructureOwnershipStoreTest { originZ - referenceRadius, originZ + referenceRadius, FINGERPRINT, - NativeStructureOwnershipRecord.DecisionSnapshot.capture( - new IrisNativeStructureDecision( - NativeStructureGenerationStatus.GENERATE_NATIVE, - 0, - null, - false, - null, - terrain - )) + new NativeStructureOwnershipRecord.MemoSnapshot("null", terrain) ); } + private static String terrain(int horizontalPadding) { + return "{\"horizontalPadding\":" + horizontalPadding + "}"; + } + private static class TestStorage implements NativeStructureOwnershipStore.Storage { protected final Map chunks = new ConcurrentHashMap<>(); protected volatile int flushes; diff --git a/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureStartsTest.java b/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureStartsTest.java index 379c17edd..a8bdc26ed 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureStartsTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureStartsTest.java @@ -3,20 +3,16 @@ package art.arcane.iris.engine.framework; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.BuiltInPack; import art.arcane.iris.core.modules.ModuleSettings; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.structure.IrisStructureCarveShape; +import art.arcane.iris.builtin.structure.StructureStilts; +import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; -import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; import art.arcane.iris.engine.object.structure.StructureDistribution; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConfiguration; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawHeightmap; import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.volmlib.util.collection.KList; import com.google.gson.Gson; import com.volmit.host.LoadedPack; +import com.volmit.vanilla.JigsawOverrides; import org.junit.After; import org.junit.Rule; import org.junit.Test; @@ -133,13 +129,13 @@ public class NativeStructureStartsTest { @Test public void fitsAndJigsawOverridesReachThePlatformWithTheirJsonUnchanged() throws IOException { - IrisStructureTerrain terrain = new IrisStructureTerrain().setMode(IrisStructureTerrainMode.FORCE_CARVE) - .setShape(IrisStructureCarveShape.ERODED).setHorizontalPadding(12).setErosionStrength(0.4D) - .setEncasePalette(new IrisMaterialPalette().qclear().qadd("minecraft:deepslate").qadd("minecraft:tuff")); - IrisStructureStiltSettings stilt = new IrisStructureStiltSettings().setMaxDepth(40).setSpacing(2) - .setPalette(new IrisMaterialPalette().qclear().qadd("minecraft:stone_bricks")); - IrisJigsawConfiguration jigsaw = new IrisJigsawConfiguration().setStartPool("minecraft:village/plains/town_centers") - .setMaxDepth(5).setProjectStartToHeightmap(IrisJigsawHeightmap.OCEAN_FLOOR_WG).setUseExpansionHack(false); + StructureTerrain terrain = GSON.fromJson("{\"mode\":\"FORCE_CARVE\",\"shape\":\"ERODED\",\"horizontalPadding\":12," + + "\"erosionStrength\":0.4,\"encasePalette\":{\"palette\":[{\"block\":\"minecraft:deepslate\"}," + + "{\"block\":\"minecraft:tuff\"}]}}", StructureTerrain.class); + StructureStilts stilt = GSON.fromJson("{\"maxDepth\":40,\"spacing\":2," + + "\"palette\":{\"palette\":[{\"block\":\"minecraft:stone_bricks\"}]}}", StructureStilts.class); + JigsawOverrides jigsaw = JigsawOverrides.none().withStartPool("minecraft:village/plains/town_centers") + .withMaxDepth(5).withHeightmap(JigsawOverrides.Heightmap.OCEAN_FLOOR_WG).withExpansionHack(false); IrisStructurePlacement fitted = placement("fitted", true, -40, -20, 1D, source("minecraft:ancient_city", 1) .setJigsaw(jigsaw)).setTerrain(terrain).setStilt(stilt); KList placements = new KList<>(); @@ -148,11 +144,10 @@ public class NativeStructureStartsTest { NativeStructureStartPlan plan = NativeStructureStarts.matchingPlan(engine, "MINECRAFT:ANCIENT_CITY", 0, 0); - assertEquals(GSON.toJson(terrain), GSON.toJson(plan.terrain())); - assertEquals(GSON.toJson(stilt), GSON.toJson(plan.stilt())); - assertEquals(GSON.toJson(jigsaw), GSON.toJson(plan.jigsaw())); - assertEquals(GSON.toJson(new NativeStructureStartPlan(plan.structureKey(), 0, 0, plan.baseY(), true, false, - StructurePlacementGrid.placementIdentity(fitted), jigsaw, stilt, terrain).decision()), GSON.toJson(plan.decision())); + assertEquals(new NativeStartMemo(GSON.toJson(terrain), GSON.toJson(stilt)), plan.memo()); + assertEquals(new NativeJigsawOverrides("minecraft:village/plains/town_centers", "", 5, null, null, false, + "OCEAN_FLOOR_WG", null, null, NativeJigsawOverrides.SOURCE), plan.jigsaw()); + assertEquals(StructurePlacementGrid.placementIdentity(fitted), plan.placementIdentity()); assertNull(NativeStructureStarts.matchingPlan(engine, "minecraft:stronghold", 0, 0)); } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureVolumeSuppressionTest.java b/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureVolumeSuppressionTest.java index 118e6e067..dc0e3c784 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureVolumeSuppressionTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureVolumeSuppressionTest.java @@ -4,7 +4,6 @@ import art.arcane.iris.builtin.structure.StructureSettings; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.BuiltInPack; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; import art.arcane.volmlib.util.collection.KList; import com.volmit.host.LoadedPack; import org.junit.After; @@ -41,9 +40,9 @@ public class NativeStructureVolumeSuppressionTest { Engine engine = engine(); assertFalse(NativeStructureGenerationPolicy - .resolve(engine, "minecraft:village_swamp", false).generate()); + .generates(engine, "minecraft:village_swamp")); assertFalse(NativeStructureGenerationPolicy - .resolve(engine, "minecraft:village_plains", false).generate()); + .generates(engine, "minecraft:village_plains")); } @Test @@ -51,15 +50,7 @@ public class NativeStructureVolumeSuppressionTest { Engine engine = engine(); assertTrue(NativeStructureGenerationPolicy - .resolve(engine, "towns_and_towers:village_swamp", false).generate()); - } - - @Test - public void plannedModuleStartsContributeVolumesThroughTheirOwnDecision() { - NativeStructureStartPlan plan = new NativeStructureStartPlan("minecraft:ancient_city", 3, 5, -30, true, false, 7L, - null, null, new IrisStructureTerrain()); - - assertTrue(plan.decision().generate()); + .generates(engine, "towns_and_towers:village_swamp")); } private Engine engine() throws IOException { diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/ImportedStructuresTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/ImportedStructuresTest.java index a7849afca..0c0ab6eaf 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/structure/ImportedStructuresTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/ImportedStructuresTest.java @@ -3,26 +3,24 @@ package art.arcane.iris.engine.framework.structure; import art.arcane.iris.builtin.structure.StructureAdjustment; import art.arcane.iris.builtin.structure.StructureSetFrequency; import art.arcane.iris.builtin.structure.StructureSettings; -import com.volmit.block.BlockSpec; -import com.volmit.block.PaletteSpec; +import art.arcane.iris.builtin.structure.StructureStilts; +import art.arcane.iris.builtin.structure.StructureTerrain; +import art.arcane.iris.builtin.structure.StructureTerrainMode; +import art.arcane.iris.builtin.structure.StructureYBand; import com.volmit.resource.ResourceId; -import com.volmit.vanilla.StructureStilts; -import com.volmit.vanilla.StructureTerrain; -import com.volmit.vanilla.VanillaStructureAdjustment; -import com.volmit.vanilla.YBand; import com.google.gson.Gson; import org.junit.Test; import java.util.List; -import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; /** What a dimension's iris:structure settings say about the platform's own structures (was IrisImportedStructureControlTest). */ public class ImportedStructuresTest { - private static final StructureStilts COBBLE = StructureStilts.of(PaletteSpec.of(List.of(BlockSpec.of("minecraft:cobblestone")))); + private static final Gson JSON = new Gson(); @Test public void defaultSettingsGenerateEveryStructureAndChangeNothing() { @@ -30,7 +28,7 @@ public class ImportedStructuresTest { assertFalse(defaults.disables("minecraft:village_plains")); assertFalse(defaults.disables("nova_structures:desert_temple")); - assertEquals(VanillaStructureAdjustment.NONE, defaults.adjustment("minecraft:stronghold", true)); + assertEquals(NativeStructureFit.NONE, defaults.adjustment("minecraft:stronghold", true)); assertEquals(1D, defaults.setup().frequency(ResourceId.parse("minecraft:villages")), 0D); assertFalse(defaults.setup().protectsVanillaDefinitions()); } @@ -95,31 +93,31 @@ public class ImportedStructuresTest { @Test public void theLastMatchingTerrainBandAndStiltWin() { - StructureTerrain encase = StructureTerrain.of(StructureTerrain.Mode.ENCASE).withPadding(4, 0, 0); - StructureStilts deep = COBBLE.withMaxDepth(96); + StructureTerrain encase = terrain("{\"mode\":\"ENCASE\",\"horizontalPadding\":4}"); + StructureStilts deep = stilts(96); + StructureYBand band = JSON.fromJson("{\"min\":-120,\"max\":-20}", StructureYBand.class); ImportedStructures imported = imported(settings(List.of(), List.of(), 0, true, List.of(), List.of( - adjustment(List.of("minecraft:stronghold"), 0, null, false, COBBLE.withMaxDepth(32), - StructureTerrain.of(StructureTerrain.Mode.SOURCE)), - adjustment(List.of("minecraft:stronghold"), 0, YBand.of(-120, -20), false, null, encase), + adjustment(List.of("minecraft:stronghold"), 0, null, false, stilts(32), terrain("{\"mode\":\"SOURCE\"}")), + adjustment(List.of("minecraft:stronghold"), 0, band, false, null, encase), adjustment(List.of("minecraft:stronghold"), 0, null, false, deep, null)))); - VanillaStructureAdjustment stronghold = imported.adjustment("minecraft:stronghold", true); - assertEquals(Optional.of(encase), stronghold.fit().terrain()); - assertEquals(Optional.of(deep), stronghold.fit().stilts()); - assertEquals(Optional.of(YBand.of(-120, -20)), stronghold.yBand()); - assertEquals(VanillaStructureAdjustment.NONE, imported.adjustment("minecraft:trial_chambers", true)); + NativeStructureFit stronghold = imported.adjustment("minecraft:stronghold", true); + assertSame(encase, stronghold.terrain()); + assertSame(deep, stronghold.stilts()); + assertSame(band, stronghold.yBand()); + assertEquals(NativeStructureFit.NONE, imported.adjustment("minecraft:trial_chambers", true)); } @Test public void aLaterSpecificAdjustmentOverridesANamespaceTerrain() { ImportedStructures imported = imported(settings(List.of(), List.of(), 0, true, List.of(), List.of( - adjustment(List.of("towns_and_towers:"), 0, null, false, null, StructureTerrain.of(StructureTerrain.Mode.VACUUM)), + adjustment(List.of("towns_and_towers:"), 0, null, false, null, terrain("{\"mode\":\"VACUUM\"}")), adjustment(List.of("towns_and_towers:village_ocean", "towns_and_towers:mimic_desert"), 0, null, false, null, - StructureTerrain.of(StructureTerrain.Mode.PRESERVE))))); + terrain("{\"mode\":\"PRESERVE\"}"))))); - assertEquals(StructureTerrain.Mode.VACUUM, mode(imported, "towns_and_towers:village_forest")); - assertEquals(StructureTerrain.Mode.PRESERVE, mode(imported, "towns_and_towers:village_ocean")); - assertEquals(StructureTerrain.Mode.PRESERVE, mode(imported, "towns_and_towers:mimic_desert")); + assertEquals(StructureTerrainMode.VACUUM, mode(imported, "towns_and_towers:village_forest")); + assertEquals(StructureTerrainMode.PRESERVE, mode(imported, "towns_and_towers:village_ocean")); + assertEquals(StructureTerrainMode.PRESERVE, mode(imported, "towns_and_towers:mimic_desert")); } @Test @@ -127,7 +125,7 @@ public class ImportedStructuresTest { ImportedStructures imported = imported(settings(List.of(), List.of(), -64, true, List.of(), List.of( adjustment(List.of("minecraft:mineshaft"), 4, null, true, null, null)))); - VanillaStructureAdjustment mesa = imported.adjustment("minecraft:mineshaft_mesa", true); + NativeStructureFit mesa = imported.adjustment("minecraft:mineshaft_mesa", true); assertTrue(mesa.keepsSourceY()); assertEquals(-60, mesa.yShift()); assertFalse(imported.adjustment("minecraft:stronghold", true).keepsSourceY()); @@ -141,12 +139,20 @@ public class ImportedStructuresTest { ImportedStructures imported = imported(nulls); assertFalse(imported.disables("minecraft:monument")); - assertEquals(VanillaStructureAdjustment.NONE, imported.adjustment("minecraft:monument", false)); + assertEquals(NativeStructureFit.NONE, imported.adjustment("minecraft:monument", false)); assertTrue(imported.setup().frequencies().isEmpty()); } - private static StructureTerrain.Mode mode(ImportedStructures imported, String key) { - return imported.adjustment(key, false).fit().terrain().orElseThrow().mode(); + private static StructureTerrainMode mode(ImportedStructures imported, String key) { + return imported.adjustment(key, false).terrain().resolvedMode(); + } + + private static StructureTerrain terrain(String json) { + return JSON.fromJson(json, StructureTerrain.class); + } + + private static StructureStilts stilts(int maxDepth) { + return JSON.fromJson("{\"maxDepth\":" + maxDepth + "}", StructureStilts.class); } private static ImportedStructures imported(StructureSettings settings) { @@ -159,7 +165,7 @@ public class ImportedStructuresTest { return new StructureSettings(disabled, disabledExact, undergroundYShift, datapackOverrides, frequencies, adjustments); } - private static StructureAdjustment adjustment(List match, int yShift, YBand band, boolean preserveSourceY, + private static StructureAdjustment adjustment(List match, int yShift, StructureYBand band, boolean preserveSourceY, StructureStilts stilt, StructureTerrain terrain) { return new StructureAdjustment(match, yShift, band, preserveSourceY, stilt, terrain); } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/NativeStartPlannerTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/NativeStartPlannerTest.java index 307ba26de..58bd07011 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/structure/NativeStartPlannerTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/NativeStartPlannerTest.java @@ -3,11 +3,13 @@ package art.arcane.iris.engine.framework.structure; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.SeedManager; import art.arcane.iris.engine.framework.StructurePlacementGrid; -import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConfiguration; +import art.arcane.iris.builtin.structure.StructureStilts; +import art.arcane.iris.builtin.structure.StructureTerrain; +import art.arcane.iris.builtin.structure.StructureTerrainMode; +import com.google.gson.Gson; +import com.volmit.vanilla.JigsawOverrides; import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression; import com.volmit.resource.ResourceId; -import com.volmit.vanilla.StructureTerrain; import com.volmit.vanilla.VanillaStructureStart; import java.util.List; import java.util.Optional; @@ -17,8 +19,6 @@ import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; import art.arcane.iris.engine.object.structure.StructureDistribution; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; @@ -83,31 +83,31 @@ public class NativeStartPlannerTest { @Test public void aPlanBecomesAStartWithHeightsAboveTheBottomAndThePlacementsFitAndIdentity() { - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.FORCE_CARVE) - .setHorizontalPadding(24); + Gson json = new Gson(); + StructureTerrain terrain = json.fromJson("{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":24}", StructureTerrain.class); IrisStructurePlacement placement = nativePlacement() .setUnderground(true) .setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE) .setTerrain(terrain) - .setStilt(new IrisStructureStiltSettings().setSpacing(3)); - placement.getNativeStructures().getFirst().setJigsaw(new IrisJigsawConfiguration().setMaxDepth(4)); + .setStilt(json.fromJson("{\"spacing\":3}", StructureStilts.class)); + placement.getNativeStructures().getFirst().setJigsaw(JigsawOverrides.none().withMaxDepth(4)); NativeStartPlanner.Plan plan = new NativeStartPlanner.Plan( placement, placement.getNativeStructures().getFirst(), 3, 5, -30); - VanillaStructureStart start = StructureVanillaHook.start(plan, -64); + VanillaStructureStart start = StructureVanillaStructures.start(plan, -64); assertEquals(ResourceId.parse("minecraft:ancient_city"), start.structure()); assertEquals(34, start.y()); assertTrue(start.isUnderground()); assertTrue(start.replacesPlatformStart()); assertEquals(StructurePlacementGrid.placementIdentity(placement), start.identity()); - assertEquals(StructureTerrain.Mode.FORCE_CARVE, start.fit().terrain().orElseThrow().mode()); - assertEquals(24, start.fit().terrain().orElseThrow().horizontalPadding()); - assertEquals(3, start.fit().stilts().orElseThrow().spacing()); + NativeStructureFit fit = NativeStructureFit.of(start.memo().orElseThrow()); + assertEquals(StructureTerrainMode.FORCE_CARVE, fit.terrain().resolvedMode()); + assertEquals(24, fit.terrain().horizontalPadding()); + assertEquals(3, fit.stilts().spacing()); assertEquals(OptionalInt.of(4), start.jigsaw().orElseThrow().maxDepth()); assertEquals("a source without jigsaw overrides has none", Optional.empty(), - StructureVanillaHook.start(new NativeStartPlanner.Plan(nativePlacement(), + StructureVanillaStructures.start(new NativeStartPlanner.Plan(nativePlacement(), nativePlacement().getNativeStructures().getFirst(), 0, 0, 70), -64).jigsaw()); } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/FitFixture.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/FitFixture.java new file mode 100644 index 000000000..e34f61ce9 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/FitFixture.java @@ -0,0 +1,300 @@ +package art.arcane.iris.engine.framework.structure.fit; + +import art.arcane.iris.engine.framework.structure.NativeStructureFit; +import com.google.gson.Gson; +import com.volmit.block.BlockFace; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.mantle.BlockBox; +import com.volmit.resource.ResourceId; +import com.volmit.vanilla.PieceKind; +import com.volmit.vanilla.StartMemo; +import com.volmit.vanilla.StructureFit; +import com.volmit.vanilla.StructureStep; +import com.volmit.vanilla.TemplateCells; +import com.volmit.vanilla.TerrainAdaptation; +import com.volmit.world.BlockAccess; +import com.volmit.world.BlockPosition; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * Structure fit components outside a platform: an in-memory world in world heights whose block answers follow the + * platform's for the blocks the tests use, and pieces whose template cells the test states the way the platform would + * process them. + */ +final class FitFixture { + static final int BOTTOM_Y = -64; + static final int TOP_Y = 320; + static final BlockState AIR = state("air"); + static final BlockState STONE = state("stone"); + static final BlockState DIRT = state("dirt"); + static final BlockState GRASS = state("grass_block"); + static final BlockState COBBLESTONE = state("cobblestone"); + static final BlockState WATER = state("water"); + static final BlockState OAK_LOG = state("oak_log"); + static final BlockState OAK_LEAVES = state("oak_leaves"); + private static final Gson JSON = new Gson(); + private static final Set NOT_SOLID = Set.of("air", "cave_air", "water", "lava", "short_grass", "dandelion", + "structure_void", "vine", "sculk_vein"); + private static final Map> TAGS = Map.of( + "minecraft:logs", Set.of("oak_log", "spruce_log", "oak_wood"), + "minecraft:leaves", Set.of("oak_leaves", "spruce_leaves"), + "minecraft:base_stone_overworld", Set.of("stone", "deepslate", "tuff", "granite", "diorite", "andesite"), + "minecraft:dirt", Set.of("dirt", "grass_block", "podzol", "coarse_dirt"), + "minecraft:sand", Set.of("sand", "red_sand")); + + private FitFixture() { + } + + static BlockState state(String path) { + return new BlockState("minecraft:" + path); + } + + /** A world of blocks keyed by world position, air where nothing is set. */ + static final class World implements BlockAccess { + private final Map blocks = new HashMap<>(); + private final Box bounds; + + World(Box columns) { + this.bounds = new Box(columns.minX(), BOTTOM_Y, columns.minZ(), columns.maxX(), TOP_Y - 1, columns.maxZ()); + } + + void put(int x, int y, int z, BlockState state) { + blocks.put(new BlockPosition(x, y, z), state); + } + + BlockState at(int x, int y, int z) { + return blocks.getOrDefault(new BlockPosition(x, y, z), AIR); + } + + Map snapshot() { + return Map.copyOf(blocks); + } + + /** Grass at {@code surfaceY} over a dirt layer, in every column of {@code area}. */ + World flat(Box area, int surfaceY) { + for (int x = area.minX(); x <= area.maxX(); x++) { + for (int z = area.minZ(); z <= area.maxZ(); z++) { + put(x, surfaceY - 1, z, DIRT); + put(x, surfaceY, z, GRASS); + } + } + return this; + } + + FitBlocks fitBlocks() { + return new FitBlocks(this, BOTTOM_Y); + } + + @Override + public BlockBox bounds() { + return bounds.toApi(BOTTOM_Y); + } + + @Override + public BlockState get(int x, int y, int z) { + return at(x, y + BOTTOM_Y, z); + } + + @Override + public void column(int x, int z, int fromY, BlockState[] into) { + for (int index = 0; index < into.length; index++) { + into[index] = get(x, fromY + index, z); + } + } + + @Override + public void set(int x, int y, int z, BlockState state) { + put(x, y + BOTTOM_Y, z, state); + } + + @Override + public boolean is(BlockState state, BlockTrait trait) { + String path = state.material().path(); + return switch (trait) { + case AIR -> path.endsWith("air"); + case SOLID -> !NOT_SOLID.contains(path); + case FLUID -> path.equals("water") || path.equals("lava") + || "true".equals(state.properties().get("waterlogged")); + case LOG -> path.endsWith("_log") || path.endsWith("_wood") || path.endsWith("_stem"); + case LEAVES -> path.endsWith("_leaves"); + default -> throw new UnsupportedOperationException(trait.name()); + }; + } + + @Override + public boolean inTag(BlockState state, ResourceId tag) { + return TAGS.getOrDefault(tag.toString(), Set.of()).contains(state.material().path()); + } + + @Override + public boolean sturdy(int x, int y, int z, BlockFace face) { + BlockState state = get(x, y, z); + return is(state, BlockTrait.SOLID) && !is(state, BlockTrait.LEAVES); + } + + @Override + public BlockState fluid(BlockState state) { + return is(state, BlockTrait.FLUID) ? WATER : AIR; + } + } + + /** A piece; its cells are the processed template blocks the test states (null for a block a processor removed). */ + static final class Piece implements StructureFit.Piece { + private final Box box; + private final PieceKind kind; + private final int groundLevelDelta; + private final List junctions = new ArrayList<>(); + private final List cells = new ArrayList<>(); + private final List legacyAir = new ArrayList<>(); + private boolean template; + + Piece(Box box, PieceKind kind, int groundLevelDelta) { + this.box = box; + this.kind = kind; + this.groundLevelDelta = groundLevelDelta; + } + + static Piece rigid(Box box, int groundLevelDelta) { + return new Piece(box, PieceKind.RIGID, groundLevelDelta); + } + + static Piece fixed(Box box) { + return new Piece(box, PieceKind.FIXED, 0); + } + + Piece cell(int x, int y, int z, BlockState state) { + template = true; + cells.add(new Cell(x, y, z, state)); + return this; + } + + Piece junction(int x, int groundY, int z) { + junctions.add(new BlockPosition(x, groundY - BOTTOM_Y, z)); + return this; + } + + Piece legacyAir(int x, int y, int z) { + legacyAir.add(new BlockPosition(x, y - BOTTOM_Y, z)); + return this; + } + + @Override + public BlockBox box() { + return box.toApi(BOTTOM_Y); + } + + @Override + public PieceKind kind() { + return kind; + } + + @Override + public int groundLevelDelta() { + return groundLevelDelta; + } + + @Override + public List junctions() { + return List.copyOf(junctions); + } + + @Override + public TemplateCells cells(BlockBox region) { + if (!template) { + return TemplateCells.UNRESOLVED; + } + Box worldRegion = Box.of(region, BOTTOM_Y); + List inside = cells.stream().filter(cell -> worldRegion.contains(cell.x(), cell.y(), cell.z())).toList(); + int[] xs = inside.stream().mapToInt(Cell::x).toArray(); + int[] ys = inside.stream().mapToInt(cell -> cell.y() - BOTTOM_Y).toArray(); + int[] zs = inside.stream().mapToInt(Cell::z).toArray(); + BlockState[] states = inside.stream().map(Cell::state).toArray(BlockState[]::new); + return TemplateCells.of(xs, ys, zs, states, cells.size() * 2); + } + + @Override + public void columns(StructureFit.ColumnVisitor visitor) { + for (int z = box.minZ(); z <= box.maxZ(); z++) { + for (int x = box.minX(); x <= box.maxX(); x++) { + visitor.column(x, z, box.minY() - BOTTOM_Y, box.maxY() - BOTTOM_Y); + } + } + } + + @Override + public List legacyAir(BlockBox clip) { + Box worldClip = Box.of(clip, BOTTOM_Y); + return legacyAir.stream() + .filter(air -> worldClip.contains(air.x(), air.y() + BOTTOM_Y, air.z())) + .toList(); + } + } + + private record Cell(int x, int y, int z, BlockState state) { + } + + /** A start of the structure fit, with the terrain fit JSON a memo would carry and no stilts. */ + static FitStart start(String terrainJson, TerrainAdaptation adaptation, StructureStep step, Piece... pieces) { + return start(terrainJson, "null", adaptation, step, pieces); + } + + static FitStart start(String terrainJson, String stiltsJson, TerrainAdaptation adaptation, StructureStep step, + Piece... pieces) { + StartMemo memo = new StartMemo(terrainJson, stiltsJson); + StructureFit.Start start = new StructureFit.Start() { + private final Object key = new Object(); + + @Override + public ResourceId structure() { + return ResourceId.parse("test:structure"); + } + + @Override + public int chunkX() { + return 0; + } + + @Override + public int chunkZ() { + return 0; + } + + @Override + public StructureStep step() { + return step; + } + + @Override + public TerrainAdaptation adaptation() { + return adaptation; + } + + @Override + public Optional memo() { + return Optional.of(memo); + } + + @Override + public List pieces() { + return List.of(pieces); + } + + @Override + public Object key() { + return key; + } + }; + return new FitStart(start, NativeStructureFit.of(memo), BOTTOM_Y); + } + + static String json(Object value) { + return JSON.toJson(value); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/FoundationStiltsTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/FoundationStiltsTest.java new file mode 100644 index 000000000..db84f3ace --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/FoundationStiltsTest.java @@ -0,0 +1,33 @@ +package art.arcane.iris.engine.framework.structure.fit; + +import org.junit.Test; + +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.BOTTOM_Y; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.state; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class FoundationStiltsTest { + private static final Box COLUMN = new Box(0, 0, 0, 0, 0, 0); + + @Test + public void sparseStiltGridIsDeterministic() { + assertTrue(FoundationStilts.isStiltColumn(0, 0, 4)); + assertTrue(FoundationStilts.isStiltColumn(-4, 8, 4)); + assertFalse(FoundationStilts.isStiltColumn(1, 0, 4)); + assertTrue(FoundationStilts.isStiltColumn(1, 1, 1)); + } + + @Test + public void stiltsOnlyAnchorOnSturdyGroundWithinTheirDepth() { + FitFixture.World world = new FitFixture.World(COLUMN); + world.put(0, 7, 0, state("deepslate")); + world.put(0, 8, 0, state("sculk_vein")); + + assertEquals(7, FoundationStilts.findStiltAnchorY(world.fitBlocks(), 0, 0, 10, 2, BOTTOM_Y, BOTTOM_Y)); + assertEquals(Integer.MIN_VALUE, FoundationStilts.findStiltAnchorY(world.fitBlocks(), 0, 0, 10, 1, BOTTOM_Y, BOTTOM_Y)); + assertEquals(Integer.MIN_VALUE, FoundationStilts.findStiltAnchorY( + new FitFixture.World(COLUMN).fitBlocks(), 0, 0, 10, 64, BOTTOM_Y, BOTTOM_Y)); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/RigidSupportTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/RigidSupportTest.java new file mode 100644 index 000000000..48139edf7 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/RigidSupportTest.java @@ -0,0 +1,198 @@ +package art.arcane.iris.engine.framework.structure.fit; + +import com.volmit.block.BlockState; +import com.volmit.vanilla.StructureStep; +import com.volmit.vanilla.TerrainAdaptation; +import org.junit.Test; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.AIR; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.COBBLESTONE; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.DIRT; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.GRASS; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.WATER; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.state; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * The support bridged between two rigid pieces of one surface start whose ground planes are two blocks apart. Each + * test states the template cells the platform would process for the pieces. + */ +public class RigidSupportTest { + private static final String SOURCE = "{\"mode\":\"SOURCE\"}"; + private static final String VACUUM = "{\"mode\":\"VACUUM\"}"; + private static final String PRESERVE = "{\"mode\":\"PRESERVE\"}"; + + @Test + public void upperOccupancyIsSupportedOverTheLowerPiecesGround() { + Box area = new Box(0, 58, 0, 1, 72, 0); + FitFixture.World world = supportTerrain(area); + world.put(1, 63, 0, DIRT); + FitStart start = beard(lower(0, 1, AIR), upper(0, 1, 64, COBBLESTONE)); + + Set written = RigidSupport.bridgeRigidPieceSupport(world.fitBlocks(), area, List.of(start)); + + assertEquals(Set.of(TemplateFootprint.packedPosition(0, 63, 0)), written); + assertEquals(DIRT, world.at(0, 63, 0)); + assertEquals(DIRT, world.at(1, 63, 0)); + } + + @Test + public void lowestAirVoidFluidAndRemovedCellsVetoSupport() { + Box area = new Box(0, 58, 0, 4, 72, 0); + FitFixture.World world = supportTerrain(area); + FitFixture.Piece upper = FitFixture.Piece.rigid(new Box(0, 64, 0, 4, 70, 0), 1) + .cell(0, 64, 0, COBBLESTONE) + .cell(1, 64, 0, AIR) + .cell(2, 64, 0, state("structure_void")) + .cell(3, 64, 0, WATER) + .cell(4, 64, 0, null); + for (int x = 1; x <= 4; x++) { + upper.cell(x, 65, 0, state("stone")); + } + FitStart start = beard(lower(0, 4, AIR), upper); + + Set written = RigidSupport.bridgeRigidPieceSupport(world.fitBlocks(), area, List.of(start)); + + assertEquals(Set.of(TemplateFootprint.packedPosition(0, 63, 0)), written); + for (int x = 1; x <= 4; x++) { + assertEquals(AIR, world.at(x, 63, 0)); + } + } + + @Test + public void supportIsChunkClippedAndStableAcrossSplitAreas() { + Box wideArea = new Box(0, 58, 0, 31, 72, 15); + Box westArea = new Box(0, 58, 0, 15, 72, 15); + Box eastArea = new Box(16, 58, 0, 31, 72, 15); + FitFixture.World wide = supportTerrain(new Box(15, 58, 0, 16, 72, 0)); + FitFixture.World split = supportTerrain(new Box(15, 58, 0, 16, 72, 0)); + FitStart start = beard(lower(15, 16, AIR), upper(15, 16, 64, COBBLESTONE)); + + Set wideWritten = RigidSupport.bridgeRigidPieceSupport(wide.fitBlocks(), wideArea, List.of(start)); + Set splitWritten = new HashSet<>( + RigidSupport.bridgeRigidPieceSupport(split.fitBlocks(), westArea, List.of(start))); + assertEquals(AIR, split.at(16, 63, 0)); + splitWritten.addAll(RigidSupport.bridgeRigidPieceSupport(split.fitBlocks(), eastArea, List.of(start))); + + assertEquals(Set.of(TemplateFootprint.packedPosition(15, 63, 0), TemplateFootprint.packedPosition(16, 63, 0)), + wideWritten); + assertEquals(wideWritten, splitWritten); + assertEquals(wide.snapshot(), split.snapshot()); + } + + @Test + public void supportNeverPairsRigidAnchorsAcrossStarts() { + Box area = new Box(0, 58, 0, 0, 72, 0); + FitFixture.World world = supportTerrain(area); + + assertTrue(RigidSupport.bridgeRigidPieceSupport(world.fitBlocks(), area, + List.of(beard(lower(0, 0, AIR)), beard(upper(0, 0, 64, COBBLESTONE)))).isEmpty()); + assertEquals(AIR, world.at(0, 63, 0)); + } + + @Test + public void vacuumSupportsWithoutAnAuthoredAdaptationButLongMeetGapsStayOpen() { + Box area = new Box(0, 58, 0, 0, 72, 0); + FitFixture.World vacuumWorld = supportTerrain(area); + + Set written = RigidSupport.bridgeRigidPieceSupport(vacuumWorld.fitBlocks(), area, + List.of(start(VACUUM, TerrainAdaptation.NONE, lower(0, 0, AIR), upper(0, 0, 64, COBBLESTONE)))); + + assertEquals(Set.of(TemplateFootprint.packedPosition(0, 63, 0)), written); + assertTrue(RigidSupport.bridgeRigidPieceSupport(supportTerrain(area).fitBlocks(), area, + List.of(start(SOURCE, TerrainAdaptation.NONE, lower(0, 0, AIR), upper(0, 0, 64, COBBLESTONE)))).isEmpty()); + assertTrue(RigidSupport.bridgeRigidPieceSupport(supportTerrain(area).fitBlocks(), area, + List.of(start(VACUUM, TerrainAdaptation.NONE, lower(0, 0, AIR), upper(0, 0, 65, COBBLESTONE)))).isEmpty()); + } + + @Test + public void threeRigidPlanesCannotBuildAnUpwardSupportChain() { + Box area = new Box(0, 58, 0, 0, 72, 0); + FitFixture.World world = supportTerrain(area); + FitFixture.Piece middle = FitFixture.Piece.rigid(new Box(0, 64, 0, 0, 69, 0), 0).cell(0, 64, 0, COBBLESTONE); + FitFixture.Piece top = FitFixture.Piece.rigid(new Box(0, 65, 0, 0, 70, 0), 0).cell(0, 65, 0, state("stone")); + + Set written = RigidSupport.bridgeRigidPieceSupport(world.fitBlocks(), area, + List.of(beard(lower(0, 0, AIR), middle, top))); + + assertEquals(Set.of(TemplateFootprint.packedPosition(0, 63, 0)), written); + assertEquals(DIRT, world.at(0, 63, 0)); + assertEquals(AIR, world.at(0, 64, 0)); + } + + @Test + public void startOrderCannotCreateCrossStartSupportChains() { + Box area = new Box(0, 58, 0, 0, 72, 0); + FitFixture.Piece middle = FitFixture.Piece.rigid(new Box(0, 64, 0, 0, 69, 0), 0).cell(0, 64, 0, COBBLESTONE); + FitFixture.Piece raisedGround = FitFixture.Piece.rigid(new Box(0, 64, 0, 0, 69, 0), 0).cell(0, 64, 0, AIR); + FitFixture.Piece top = FitFixture.Piece.rigid(new Box(0, 65, 0, 0, 70, 0), 0).cell(0, 65, 0, state("stone")); + FitStart lowerStart = beard(lower(0, 0, AIR), middle); + FitStart upperStart = beard(raisedGround, top); + FitFixture.World forward = supportTerrain(area); + FitFixture.World reverse = supportTerrain(area); + + Set forwardWritten = RigidSupport.bridgeRigidPieceSupport(forward.fitBlocks(), area, + List.of(lowerStart, upperStart)); + Set reverseWritten = RigidSupport.bridgeRigidPieceSupport(reverse.fitBlocks(), area, + List.of(upperStart, lowerStart)); + + assertEquals(Set.of(TemplateFootprint.packedPosition(0, 63, 0)), forwardWritten); + assertEquals(forwardWritten, reverseWritten); + assertEquals(forward.snapshot(), reverse.snapshot()); + assertEquals(AIR, forward.at(0, 64, 0)); + } + + @Test + public void aPreserveDuplicateCannotSuppressVacuumSupport() { + Box area = new Box(0, 58, 0, 0, 72, 0); + FitFixture.World world = supportTerrain(area); + FitFixture.Piece lower = lower(0, 0, AIR); + FitFixture.Piece upper = upper(0, 0, 64, COBBLESTONE); + + Set written = RigidSupport.bridgeRigidPieceSupport(world.fitBlocks(), area, List.of( + start(PRESERVE, TerrainAdaptation.NONE, lower, upper), + start(VACUUM, TerrainAdaptation.NONE, lower, upper))); + + assertEquals(Set.of(TemplateFootprint.packedPosition(0, 63, 0)), written); + } + + /** A lower rigid piece from {@code minX} to {@code maxX} whose ground (y 62) holds {@code cell}. */ + private static FitFixture.Piece lower(int minX, int maxX, BlockState cell) { + FitFixture.Piece piece = FitFixture.Piece.rigid(new Box(minX, 62, 0, maxX, 65, 0), 1); + for (int x = minX; x <= maxX; x++) { + piece.cell(x, 62, 0, cell); + } + return piece; + } + + /** An upper rigid piece whose lowest layer, at {@code baseY}, holds {@code cell}; its ground is the layer under it. */ + private static FitFixture.Piece upper(int minX, int maxX, int baseY, BlockState cell) { + FitFixture.Piece piece = FitFixture.Piece.rigid(new Box(minX, baseY, 0, maxX, baseY + 6, 0), 1); + for (int x = minX; x <= maxX; x++) { + piece.cell(x, baseY, 0, cell); + } + return piece; + } + + private static FitStart beard(FitFixture.Piece... pieces) { + return start(SOURCE, TerrainAdaptation.BEARD_BOX, pieces); + } + + private static FitStart start(String terrain, TerrainAdaptation adaptation, FitFixture.Piece... pieces) { + return FitFixture.start(terrain, adaptation, StructureStep.SURFACE_STRUCTURES, pieces); + } + + private static FitFixture.World supportTerrain(Box columns) { + FitFixture.World world = new FitFixture.World(columns); + for (int x = columns.minX(); x <= columns.maxX(); x++) { + world.put(x, 61, 0, DIRT); + world.put(x, 62, 0, GRASS); + } + return world; + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/StartLayoutsTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/StartLayoutsTest.java new file mode 100644 index 000000000..94fb42512 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/StartLayoutsTest.java @@ -0,0 +1,227 @@ +package art.arcane.iris.engine.framework.structure.fit; + +import art.arcane.iris.builtin.structure.StructureTerrain; +import art.arcane.iris.builtin.structure.StructureYBand; +import art.arcane.iris.engine.framework.structure.NativeStructureFit; +import com.google.gson.Gson; +import com.volmit.mantle.BlockBox; +import com.volmit.resource.ResourceId; +import com.volmit.vanilla.PlatformStart; +import com.volmit.vanilla.StartReach; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.IntBinaryOperator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Pins the vertical shift {@code iris:structure} asks for a platform start under every adjustment a dimension can + * give it, and how far each terrain fit reaches. The host half (alignment, clamping, moving) is pinned on the platform. + */ +public class StartLayoutsTest { + private static final Gson JSON = new Gson(); + private static final int BOTTOM_Y = -64; + private static final int PYRAMID_WIDTH = 21; + private static final int PYRAMID_HEIGHT = 15; + 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 shift 0", + "none minecraft:desert_pyramid 0,0 shift 0", + "none minecraft:stronghold 3,-5 shift 0", + "none minecraft:desert_pyramid 3,-5 shift 0", + "none minecraft:stronghold -11,7 shift 0", + "none minecraft:desert_pyramid -11,7 shift 0", + "shift minecraft:stronghold 0,0 shift 5", + "shift minecraft:desert_pyramid 0,0 shift 5", + "shift minecraft:stronghold 3,-5 shift 5", + "shift minecraft:desert_pyramid 3,-5 shift 5", + "shift minecraft:stronghold -11,7 shift 5", + "shift minecraft:desert_pyramid -11,7 shift 5", + "burial minecraft:stronghold 0,0 shift -8", + "burial minecraft:desert_pyramid 0,0 shift -7", + "burial minecraft:stronghold 3,-5 shift -8", + "burial minecraft:desert_pyramid 3,-5 shift -7", + "burial minecraft:stronghold -11,7 shift -8", + "burial minecraft:desert_pyramid -11,7 shift -7", + "burial-unshifted minecraft:stronghold 0,0 shift -8", + "burial-unshifted minecraft:desert_pyramid 0,0 shift 0", + "burial-unshifted minecraft:stronghold 3,-5 shift -8", + "burial-unshifted minecraft:desert_pyramid 3,-5 shift 0", + "burial-unshifted minecraft:stronghold -11,7 shift -8", + "burial-unshifted minecraft:desert_pyramid -11,7 shift 0", + "kept minecraft:stronghold 0,0 shift 3", + "kept minecraft:desert_pyramid 0,0 shift 3", + "kept minecraft:stronghold 3,-5 shift 3", + "kept minecraft:desert_pyramid 3,-5 shift 3", + "kept minecraft:stronghold -11,7 shift 3", + "kept minecraft:desert_pyramid -11,7 shift 3", + "band minecraft:stronghold 0,0 shift -94", + "band minecraft:desert_pyramid 0,0 shift 0", + "band minecraft:stronghold 3,-5 shift -58", + "band minecraft:desert_pyramid 3,-5 shift 0", + "band minecraft:stronghold -11,7 shift -96", + "band minecraft:desert_pyramid -11,7 shift 0", + "narrow-band minecraft:stronghold 0,0 shift -46", + "narrow-band minecraft:desert_pyramid 0,0 shift 4", + "narrow-band minecraft:stronghold 3,-5 shift -46", + "narrow-band minecraft:desert_pyramid 3,-5 shift 4", + "narrow-band minecraft:stronghold -11,7 shift -46", + "narrow-band minecraft:desert_pyramid -11,7 shift 4", + "kept-over-band minecraft:stronghold 0,0 shift 2", + "kept-over-band minecraft:desert_pyramid 0,0 shift 2", + "kept-over-band minecraft:stronghold 3,-5 shift 2", + "kept-over-band minecraft:desert_pyramid 3,-5 shift 2", + "kept-over-band minecraft:stronghold -11,7 shift 2", + "kept-over-band minecraft:desert_pyramid -11,7 shift 2" + ); + + @Test + public void platformStartsShiftWhereTheirAdjustmentSays() { + List actual = new ArrayList<>(); + for (Adjustment adjustment : adjustments()) { + for (int[] chunk : CHUNKS) { + for (String structureId : List.of("minecraft:stronghold", "minecraft:desert_pyramid")) { + boolean aligned = structureId.equals("minecraft:desert_pyramid"); + int minY = aligned ? 64 : 50; + BlockBox bounds = new BlockBox(chunk[0] * 16, minY - BOTTOM_Y, chunk[1] * 16, + chunk[0] * 16 + PYRAMID_WIDTH, minY - BOTTOM_Y + PYRAMID_HEIGHT, chunk[1] * 16 + PYRAMID_WIDTH); + PlatformStart start = start(structureId, chunk, bounds, adjustment.underground(), aligned, SURFACE); + actual.add(adjustment.name() + " " + structureId + " " + chunk[0] + "," + chunk[1] + + " shift " + StartLayouts.shift(start, adjustment.fit())); + } + } + } + assertEquals(PINNED_SHIFTS, actual); + } + + @Test + public void burialKeepsTheTopABlockUnderTheLowestTerrainColumn() { + BlockBox bounds = new BlockBox(0, 60 - BOTTOM_Y, 0, 2, 81 - BOTTOM_Y, 1); + PlatformStart start = start("minecraft:stronghold", new int[]{0, 0}, bounds, true, false, + (x, z) -> x == 1 ? 76 : 100); + + assertEquals(-5, StartLayouts.shift(start, NativeStructureFit.NONE)); + } + + @Test + public void startsReachAsFarAsTheirTerrainFitChangesTerrain() { + assertEquals(StartReach.PLATFORM, StartLayouts.reach(terrain("{}"))); + assertEquals(StartReach.blocks(0), StartLayouts.reach(terrain("{\"mode\":\"PRESERVE\"}"))); + assertEquals(StartReach.blocks(12), StartLayouts.reach(terrain("{\"mode\":\"VACUUM\"}"))); + assertEquals(StartReach.blocks(4), StartLayouts.reach(terrain("{\"mode\":\"ENCASE\",\"horizontalPadding\":4}"))); + assertEquals(StartReach.blocks(20), StartLayouts.reach(terrain("{\"mode\":\"BORE\",\"horizontalPadding\":20}"))); + assertEquals(StartReach.blocks(112), + StartLayouts.reach(terrain("{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":112}"))); + assertEquals(StartReach.blocks(0), StartLayouts.reach(terrain("{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":0}"))); + } + + @Test + public void aBandMovesTheMiddleIntoItTheSameWayForTheSameChunk() { + NativeStructureFit fit = fit(-64, "{\"min\":-120,\"max\":-20}", false); + PlatformStart first = pyramidAt(64, false); + PlatformStart second = pyramidAt(64, false); + + int shift = StartLayouts.shift(first, fit); + + assertEquals(shift, StartLayouts.shift(second, fit)); + int middle = 64 + PYRAMID_HEIGHT / 2 + shift; + assertTrue(middle >= -120 && middle <= -20); + } + + @Test + public void aBandTooNarrowForTheStructureTakesItsMiddle() { + PlatformStart start = pyramidAt(64, false); + + int shift = StartLayouts.shift(start, fit(0, "{\"min\":-50,\"max\":-45}", false)); + + assertEquals(Math.floorDiv(-50 + -45, 2), 64 + (PYRAMID_HEIGHT - 1) / 2 + shift); + } + + @Test + public void aBandReplacesBothTheShiftAndTheBurial() { + PlatformStart start = pyramidAt(64, true); + + int shift = StartLayouts.shift(start, fit(-200, "{\"min\":-64,\"max\":-64}", false)); + + assertEquals(-64 - (PYRAMID_HEIGHT - 1) / 2, 64 + shift); + } + + private static StructureTerrain terrain(String json) { + return JSON.fromJson(json, StructureTerrain.class); + } + + private static List adjustments() { + return List.of( + new Adjustment("none", fit(0, null, false), false), + new Adjustment("shift", fit(5, null, false), false), + new Adjustment("burial", fit(-7, null, false), true), + new Adjustment("burial-unshifted", fit(0, null, false), true), + new Adjustment("kept", fit(3, null, true), true), + new Adjustment("band", fit(0, "{\"min\":-50,\"max\":20}", false), true), + new Adjustment("narrow-band", fit(4, "{\"min\":10,\"max\":12}", false), false), + new Adjustment("kept-over-band", fit(2, "{\"min\":-40,\"max\":80}", true), false)); + } + + private static NativeStructureFit fit(int yShift, String bandJson, boolean keepsSourceY) { + StructureYBand band = bandJson == null ? null : JSON.fromJson(bandJson, StructureYBand.class); + return new NativeStructureFit(yShift, band, keepsSourceY, null, null); + } + + private static PlatformStart pyramidAt(int minY, boolean underground) { + BlockBox bounds = new BlockBox(0, minY - BOTTOM_Y, 0, PYRAMID_WIDTH, minY - BOTTOM_Y + PYRAMID_HEIGHT, PYRAMID_WIDTH); + return start("minecraft:stronghold", new int[]{0, 0}, bounds, underground, false, (x, z) -> 40); + } + + private static PlatformStart start(String structureId, int[] chunk, BlockBox bounds, boolean underground, + boolean aligned, IntBinaryOperator worldSurface) { + return new PlatformStart() { + @Override + public ResourceId structure() { + return ResourceId.parse(structureId); + } + + @Override + public int chunkX() { + return chunk[0]; + } + + @Override + public int chunkZ() { + return chunk[1]; + } + + @Override + public BlockBox bounds() { + return bounds; + } + + @Override + public boolean underground() { + return underground; + } + + @Override + public boolean aligned() { + return aligned; + } + + @Override + public int bottomY() { + return BOTTOM_Y; + } + + @Override + public int surfaceY(int x, int z) { + return worldSurface.applyAsInt(x, z) - BOTTOM_Y; + } + }; + } + + private record Adjustment(String name, NativeStructureFit fit, boolean underground) { + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFittingTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFittingTest.java new file mode 100644 index 000000000..5b6e02a5f --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFittingTest.java @@ -0,0 +1,261 @@ +package art.arcane.iris.engine.framework.structure.fit; + +import com.volmit.vanilla.StructureStep; +import com.volmit.vanilla.TerrainAdaptation; +import org.junit.Test; + +import java.util.List; +import java.util.Map; + +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.AIR; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.COBBLESTONE; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.DIRT; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.GRASS; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.OAK_LEAVES; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.OAK_LOG; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.STONE; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.WATER; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.state; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** The surface fitting of SOURCE beard and VACUUM starts, on in-memory terrain. */ +public class SurfaceFittingTest { + private static final String SOURCE = "{\"mode\":\"SOURCE\"}"; + private static final String VACUUM = "{\"mode\":\"VACUUM\"}"; + private static final String PRESERVE = "{\"mode\":\"PRESERVE\"}"; + + @Test + public void sourceBeardAdjustmentsPrepareOnlyAtTheSurfaceStructuresStep() { + assertTrue(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_THIN, StructureStep.SURFACE_STRUCTURES)); + assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_BOX, StructureStep.FLUID_SPRINGS)); + assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_THIN, StructureStep.UNDERGROUND_STRUCTURES)); + assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_BOX, StructureStep.UNDERGROUND_DECORATION)); + assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BEARD_THIN, StructureStep.STRONGHOLDS)); + assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.BURY, StructureStep.SURFACE_STRUCTURES)); + assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.ENCAPSULATE, StructureStep.SURFACE_STRUCTURES)); + assertFalse(SurfaceFitting.shouldPrepareSurfaceTerrain(TerrainAdaptation.NONE, StructureStep.FLUID_SPRINGS)); + } + + @Test + public void explicitTerrainOverrideDisablesSourceBeardFittingAndVacuumNeedsNoAdaptation() { + FitFixture.Piece piece = FitFixture.Piece.fixed(new Box(0, 64, 0, 4, 70, 4)); + + assertTrue(SurfaceFitting.requiresSurfaceTerrain( + FitFixture.start(SOURCE, TerrainAdaptation.BEARD_BOX, StructureStep.SURFACE_STRUCTURES, piece))); + assertFalse(SurfaceFitting.requiresSurfaceTerrain( + FitFixture.start(PRESERVE, TerrainAdaptation.BEARD_BOX, StructureStep.SURFACE_STRUCTURES, piece))); + assertFalse(SurfaceFitting.requiresSurfaceTerrain( + FitFixture.start(SOURCE, TerrainAdaptation.NONE, StructureStep.SURFACE_STRUCTURES, piece))); + assertTrue(SurfaceFitting.requiresSurfaceTerrain( + FitFixture.start(VACUUM, TerrainAdaptation.NONE, StructureStep.SURFACE_STRUCTURES, piece))); + assertTrue(SurfaceFitting.requiresSurfaceTerrain( + FitFixture.start(VACUUM, TerrainAdaptation.BEARD_BOX, StructureStep.SURFACE_STRUCTURES, piece))); + assertFalse(TerrainIntegration.clearsLegacyTemplateAir( + FitFixture.start(VACUUM, TerrainAdaptation.NONE, StructureStep.SURFACE_STRUCTURES, piece))); + } + + @Test + public void sourceSurfaceAnchorMeetsOneBlockBelowTheAuthoredGroundPlane() { + SurfaceFitting.SurfaceAnchor anchor = SurfaceFitting.surfaceAnchor(new Box(0, 64, 0, 4, 90, 4), 68, 2); + + assertEquals(67, anchor.meetY()); + assertEquals(0, anchor.minX()); + assertEquals(4, anchor.maxX()); + assertEquals(0, anchor.minZ()); + assertEquals(4, anchor.maxZ()); + } + + @Test + public void rigidFootprintsBoundTerrainAcrossGapsLargerThanTheBeardKernel() { + assertEquals(46, SurfaceFitting.resolveSurfaceTarget(List.of(anchor(72, 2)), 2, 2, 40)); + assertEquals(46, SurfaceFitting.resolveSurfaceTarget(List.of(anchor(72, 1)), 2, 2, 40)); + } + + @Test + public void beardSkirtBoundsAndGradesUpwardAndDownwardSymmetrically() { + int originalY = 64; + int[] raised = new int[13]; + int[] lowered = new int[13]; + for (int outset = 0; outset <= 12; outset++) { + raised[outset] = SurfaceFitting.resolveSurfaceTarget(List.of(anchor(96, 2)), 4 + outset, 2, originalY); + lowered[outset] = SurfaceFitting.resolveSurfaceTarget(List.of(anchor(32, 2)), 4 + outset, 2, originalY); + } + + assertArrayEquals(new int[]{70, 69, 68, 67, 67, 66, 66, 65, 65, 64, 64, 64, 64}, raised); + assertArrayEquals(new int[]{58, 59, 60, 61, 61, 62, 62, 63, 63, 64, 64, 64, 64}, lowered); + } + + @Test + public void surfaceAnchorCapsInsideAndIsUnchangedAtRadius() { + SurfaceFitting.SurfaceAnchor anchor = anchor(72, 2); + + assertEquals(70, SurfaceFitting.resolveSurfaceTarget(List.of(anchor), 2, 2, 64)); + assertEquals(64, SurfaceFitting.resolveSurfaceTarget(List.of(anchor), 16, 2, 64)); + assertEquals(64, SurfaceFitting.resolveSurfaceTarget(List.of(anchor), 17, 2, 64)); + } + + @Test + public void surfaceAnchorRaisesAndLowersThroughTheTaper() { + assertEquals(65, SurfaceFitting.resolveSurfaceTarget(List.of(anchor(68, 2)), 10, 2, 64)); + assertEquals(67, SurfaceFitting.resolveSurfaceTarget(List.of(anchor(64, 2)), 10, 2, 68)); + } + + @Test + public void containingRigidFloorsHaveDeterministicPriority() { + SurfaceFitting.SurfaceAnchor rigid = anchor(70, 2); + SurfaceFitting.SurfaceAnchor junction = anchor(74, 1); + + assertEquals(70, SurfaceFitting.resolveSurfaceTarget(List.of(rigid, junction), 2, 2, 64)); + assertEquals(70, SurfaceFitting.resolveSurfaceTarget(List.of(junction, rigid), 2, 2, 64)); + SurfaceFitting.SurfaceAnchor weakTie = anchor(58, 1); + SurfaceFitting.SurfaceAnchor strongTie = anchor(70, 2); + assertEquals(70, SurfaceFitting.resolveSurfaceTarget(List.of(weakTie, strongTie), 2, 2, 64)); + assertEquals(70, SurfaceFitting.resolveSurfaceTarget(List.of(strongTie, weakTie), 2, 2, 64)); + } + + @Test + public void containingFootprintOverridesAnAdjacentPiecesFalloff() { + SurfaceFitting.SurfaceAnchor local = new SurfaceFitting.SurfaceAnchor(0, 4, 0, 4, 66, 2); + SurfaceFitting.SurfaceAnchor adjacent = new SurfaceFitting.SurfaceAnchor(5, 9, 0, 4, 70, 2); + + assertEquals(69, SurfaceFitting.resolveSurfaceTarget(List.of(adjacent), 4, 2, 64)); + assertEquals(66, SurfaceFitting.resolveSurfaceTarget(List.of(local, adjacent), 4, 2, 64)); + assertEquals(66, SurfaceFitting.resolveSurfaceTarget(List.of(adjacent, local), 4, 2, 64)); + } + + @Test + public void opposingFalloffsBlendWithoutAnAbruptMidpointSeam() { + SurfaceFitting.SurfaceAnchor high = new SurfaceFitting.SurfaceAnchor(0, 0, 0, 0, 70, 2); + SurfaceFitting.SurfaceAnchor low = new SurfaceFitting.SurfaceAnchor(12, 12, 0, 0, 58, 2); + int previous = SurfaceFitting.resolveSurfaceTarget(List.of(high, low), 0, 0, 64); + + for (int x = 1; x <= 12; x++) { + int forward = SurfaceFitting.resolveSurfaceTarget(List.of(high, low), x, 0, 64); + assertEquals(forward, SurfaceFitting.resolveSurfaceTarget(List.of(low, high), x, 0, 64)); + assertTrue(Math.abs(forward - previous) <= 6); + previous = forward; + } + assertEquals(64, SurfaceFitting.resolveSurfaceTarget(List.of(high, low), 6, 0, 64)); + } + + @Test + public void surfaceColumnsMutateTerrainAndRemoveUnsupportedDecoration() { + FitFixture.World lowered = new FitFixture.World(new Box(0, 0, 0, 0, 0, 0)); + lowered.put(0, 61, 0, STONE); + lowered.put(0, 62, 0, DIRT); + lowered.put(0, 63, 0, DIRT); + lowered.put(0, 64, 0, GRASS); + lowered.put(0, 65, 0, state("dandelion")); + + SurfaceFitting.applySurfaceColumn(lowered.fitBlocks(), 0, 0, 64, 62, -64, 319, false); + + assertEquals(STONE, lowered.at(0, 61, 0)); + assertEquals(GRASS, lowered.at(0, 62, 0)); + assertEquals(AIR, lowered.at(0, 63, 0)); + assertEquals(AIR, lowered.at(0, 64, 0)); + assertEquals(AIR, lowered.at(0, 65, 0)); + + FitFixture.World raised = new FitFixture.World(new Box(0, 0, 0, 0, 0, 0)); + raised.put(0, 63, 0, DIRT); + raised.put(0, 64, 0, GRASS); + raised.put(0, 65, 0, state("dandelion")); + + SurfaceFitting.applySurfaceColumn(raised.fitBlocks(), 0, 0, 64, 68, -64, 319, false); + + assertEquals(DIRT, raised.at(0, 65, 0)); + assertEquals(DIRT, raised.at(0, 66, 0)); + assertEquals(DIRT, raised.at(0, 67, 0)); + assertEquals(GRASS, raised.at(0, 68, 0)); + } + + @Test + public void rigidSurfaceBaseClosesAOneBlockSubsurfaceGapAndRebuildsAMissingMeetLayer() { + FitFixture.World gap = new FitFixture.World(new Box(0, 0, 0, 0, 0, 0)); + gap.put(0, 62, 0, STONE); + gap.put(0, 64, 0, GRASS); + SurfaceFitting.applySurfaceColumn(gap.fitBlocks(), 0, 0, 64, 64, -64, 319, true); + assertEquals(STONE, gap.at(0, 63, 0)); + assertEquals(GRASS, gap.at(0, 64, 0)); + + FitFixture.World missing = new FitFixture.World(new Box(0, 0, 0, 0, 0, 0)); + missing.put(0, 62, 0, STONE); + SurfaceFitting.applySurfaceColumn(missing.fitBlocks(), 0, 0, 64, 64, -64, 319, true); + assertEquals(STONE, missing.at(0, 63, 0)); + assertEquals(STONE, missing.at(0, 64, 0)); + + FitFixture.World floor = new FitFixture.World(new Box(0, 0, 0, 0, 0, 0)); + SurfaceFitting.applySurfaceColumn(floor.fitBlocks(), 0, 0, -64, -64, -64, 319, true); + assertEquals(STONE, floor.at(0, -64, 0)); + } + + @Test + public void raisedSurfaceTerrainDoesNotSliceTreeBlocks() { + FitFixture.World world = new FitFixture.World(new Box(0, 0, 0, 0, 0, 0)); + world.put(0, 63, 0, DIRT); + world.put(0, 64, 0, GRASS); + world.put(0, 66, 0, OAK_LOG); + world.put(0, 68, 0, OAK_LEAVES); + + SurfaceFitting.applySurfaceColumn(world.fitBlocks(), 0, 0, 64, 68, -64, 319, false); + + assertEquals(OAK_LOG, world.at(0, 66, 0)); + assertEquals(OAK_LEAVES, world.at(0, 68, 0)); + } + + @Test + public void loweredFluidColumnsRemainFluidFilled() { + FitFixture.World world = new FitFixture.World(new Box(0, 0, 0, 0, 0, 0)); + world.put(0, 62, 0, DIRT); + world.put(0, 63, 0, DIRT); + world.put(0, 64, 0, state("gravel")); + world.put(0, 65, 0, WATER); + + SurfaceFitting.applySurfaceColumn(world.fitBlocks(), 0, 0, 64, 62, -64, 319, false); + + assertEquals(WATER, world.at(0, 63, 0)); + assertEquals(WATER, world.at(0, 64, 0)); + assertEquals(WATER, world.at(0, 65, 0)); + assertEquals(state("gravel"), world.at(0, 62, 0)); + } + + @Test + public void vacuumBudgetExhaustionSkipsFittingWithoutFailing() { + Box area = new Box(0, 54, 0, 15, 72, 15); + FitFixture.World world = new FitFixture.World(area).flat(area, 60); + Map before = world.snapshot(); + FitStart start = FitFixture.start(VACUUM, TerrainAdaptation.NONE, StructureStep.SURFACE_STRUCTURES, + FitFixture.Piece.rigid(new Box(0, 66, 0, 0, 70, 0), 1).cell(0, 66, 0, COBBLESTONE)); + + SurfaceFitting.prepareSurfaceStructures(world.fitBlocks(), area, List.of(start), (x, z) -> 60, 1); + + assertEquals(before, world.snapshot()); + } + + @Test + public void vacuumRaisesTheTerrainToAFloatingFoundationAndRepairsItsGapAfterPlacement() { + Box area = new Box(0, 54, 0, 3, 74, 3); + FitFixture.World world = new FitFixture.World(area).flat(area, 60); + FitStart start = FitFixture.start(VACUUM, TerrainAdaptation.NONE, StructureStep.SURFACE_STRUCTURES, + FitFixture.Piece.rigid(new Box(0, 65, 0, 0, 72, 0), 1).cell(0, 65, 0, COBBLESTONE)); + + SurfaceFitting.VacuumFoundationPlan plan = SurfaceFitting.prepareSurfaceStructures( + world.fitBlocks(), area, List.of(start), (x, z) -> 60, SurfaceFitting.MAX_SURFACE_TEMPLATE_CELLS); + assertEquals(GRASS, world.at(0, 64, 0)); + for (int y = 61; y <= 64; y++) { + world.put(0, y, 0, state("cave_air")); + } + world.put(0, 65, 0, COBBLESTONE); + SurfaceFitting.repairVacuumFoundations(world.fitBlocks(), area, plan); + + for (int y = 61; y <= 64; y++) { + assertFalse(world.at(0, y, 0).material().path().endsWith("air")); + } + } + + private static SurfaceFitting.SurfaceAnchor anchor(int meetY, int strength) { + return new SurfaceFitting.SurfaceAnchor(0, 4, 0, 4, meetY, strength); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegrationTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegrationTest.java new file mode 100644 index 000000000..6d1d55229 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegrationTest.java @@ -0,0 +1,496 @@ +package art.arcane.iris.engine.framework.structure.fit; + +import art.arcane.iris.builtin.structure.StructureCarveShape; +import art.arcane.iris.builtin.structure.StructureTerrain; +import art.arcane.iris.builtin.structure.StructureTerrainMode; +import art.arcane.iris.engine.framework.structure.NativeStructureFit; +import art.arcane.iris.engine.mantle.components.StructureCarvingFootprint; +import com.google.gson.Gson; +import com.volmit.block.BlockState; +import com.volmit.vanilla.PieceKind; +import com.volmit.vanilla.StartMemo; +import com.volmit.vanilla.StructureStep; +import com.volmit.vanilla.TerrainAdaptation; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.BitSet; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.function.IntFunction; + +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.AIR; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.DIRT; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.OAK_LOG; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.STONE; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.WATER; +import static art.arcane.iris.engine.framework.structure.fit.FitFixture.state; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +/** The terrain integration of every mode but VACUUM, on in-memory terrain. */ +public class TerrainIntegrationTest { + private static final long SEED = 1234L; + private static final long CARVE_SEED = 8675309L; + private static final int SLAB_DEPTH = 128; + private static final int SLAB_MIN_Y = 64; + private static final int SLAB_PADDING = 14; + private static final int SLAB_WIDTH = 16; + private static final Gson JSON = new Gson(); + private static final IntFunction NATURAL = y -> y < 0 ? state("deepslate") : STONE; + private static final FitPalettes NO_PALETTES = (palette, seed, x, y, z) -> { + throw new AssertionError("no palette expected"); + }; + /** The box of a desert pyramid piece at y 64: 21 wide, 15 high. */ + private static final Box PYRAMID = new Box(0, 64, 0, 20, 78, 20); + + @Test + public void encaseFillsAirAndLiquidWithoutOverwritingExistingTerrain() { + Box bounds = PYRAMID; + Box area = new Box(bounds.minX() - 1, bounds.minY() - 1, bounds.minZ() - 1, + bounds.maxX() + 1, bounds.maxY() + 1, bounds.maxZ() + 1); + FitFixture.World world = new FitFixture.World(area); + world.put(bounds.minX(), bounds.minY(), bounds.minZ(), DIRT); + world.put(bounds.maxX(), bounds.minY(), bounds.maxZ(), WATER); + + integrate(world, area, start("{\"mode\":\"ENCASE\",\"horizontalPadding\":1,\"ceilingPadding\":1,\"floorPadding\":1}", + TerrainAdaptation.BURY, FitFixture.Piece.fixed(bounds))); + + assertEquals(DIRT, world.at(bounds.minX(), bounds.minY(), bounds.minZ())); + assertEquals(STONE, world.at(bounds.maxX(), bounds.minY(), bounds.maxZ())); + assertEquals(STONE, world.at(bounds.minX() - 1, bounds.minY() - 1, bounds.minZ() - 1)); + assertEquals(STONE, world.at(bounds.maxX() + 1, bounds.maxY() + 1, bounds.maxZ() + 1)); + } + + @Test + public void defaultEncaseUsesTheDimensionsNaturalBlockPerHeight() { + Box bounds = new Box(0, -1, 0, 20, 13, 20); + FitFixture.World world = new FitFixture.World(bounds); + + integrate(world, bounds, start("{\"mode\":\"ENCASE\"}", TerrainAdaptation.BURY, FitFixture.Piece.fixed(bounds))); + + assertEquals(state("deepslate"), world.at(0, -1, 0)); + assertEquals(STONE, world.at(0, 0, 0)); + } + + @Test + public void configuredEncasePaletteReplacesTheDefaultMaterialSeededPerStructure() { + FitFixture.World world = new FitFixture.World(PYRAMID); + List seeds = new ArrayList<>(); + FitPalettes tuff = (palette, seed, x, y, z) -> { + seeds.add(seed); + return state("tuff"); + }; + FitStart start = start("{\"mode\":\"ENCASE\",\"encasePalette\":{\"palette\":[{\"block\":\"tuff\"}]}}", + TerrainAdaptation.BURY, FitFixture.Piece.fixed(PYRAMID)); + + TerrainIntegration.integrateTerrain(world.fitBlocks(), PYRAMID, start, SEED, NATURAL, tuff, null); + + assertEquals(state("tuff"), world.at(0, 64, 0)); + assertEquals(SEED ^ "test:structure".hashCode(), (long) seeds.getFirst()); + } + + @Test + public void sourceMaterialFollowsNearbyTerrainAndIgnoresBlocksOutsideTheSnapshot() { + Box area = new Box(0, 64, 0, 15, 64, 15); + FitFixture.World world = new FitFixture.World(area); + world.put(-1, 64, 8, state("oak_planks")); + world.put(3, 64, 8, state("tuff")); + TerrainIntegration.SourceTerrainSnapshot snapshot = snapshot(world, area); + world.put(1, 64, 8, state("oak_planks")); + + assertEquals(state("tuff"), TerrainIntegration.sourceEncaseBlock(0, 64, 8, NATURAL, snapshot)); + } + + @Test + public void sourceMaterialRejectsStructureBlocksAndOresBeforeTheNaturalFallback() { + Box area = new Box(0, -20, 0, 15, -20, 15); + FitFixture.World world = new FitFixture.World(area); + world.put(3, -20, 8, state("oak_planks")); + world.put(5, -20, 8, state("stone_bricks")); + world.put(4, -20, 7, state("iron_ore")); + + assertEquals(state("deepslate"), TerrainIntegration.sourceEncaseBlock(4, -20, 8, NATURAL, snapshot(world, area))); + } + + @Test + public void sourceMaterialSnapshotOnlyAllocatesActualFillLayers() { + Box area = new Box(0, -2032, 0, 15, 2030, 15); + FitFixture.World world = new FitFixture.World(area); + + TerrainIntegration.SourceTerrainSnapshot snapshot = TerrainIntegration.captureSourceTerrain(world.fitBlocks(), area, + List.of(start("{\"mode\":\"SOURCE\"}", TerrainAdaptation.BURY, FitFixture.Piece.fixed(PYRAMID)))); + + assertNotNull(snapshot); + assertEquals(23 * 16 * 16, snapshot.sampledCells()); + } + + @Test + public void sourceBuryUsesTheVanillaSixByTwelveInfluenceEnvelope() { + int groundY = PYRAMID.minY(); + Box area = new Box(PYRAMID.minX() - 7, groundY - 13, PYRAMID.minZ(), PYRAMID.maxX(), groundY + 13, PYRAMID.maxZ()); + FitFixture.World world = new FitFixture.World(area); + + integrate(world, area, start("{\"mode\":\"SOURCE\"}", TerrainAdaptation.BURY, FitFixture.Piece.fixed(PYRAMID))); + + assertEquals(STONE, world.at(PYRAMID.minX() - 5, groundY, PYRAMID.minZ())); + assertEquals(STONE, world.at(PYRAMID.minX(), groundY + 11, PYRAMID.minZ())); + assertEquals(AIR, world.at(PYRAMID.minX() - 6, groundY, PYRAMID.minZ())); + assertEquals(AIR, world.at(PYRAMID.minX(), groundY + 12, PYRAMID.minZ())); + assertEquals(AIR, world.at(PYRAMID.minX() - 7, groundY, PYRAMID.minZ())); + } + + @Test + public void sourceEncapsulateWrapsTheFullPieceBounds() { + Box area = new Box(PYRAMID.minX() - 13, PYRAMID.minY(), PYRAMID.minZ(), PYRAMID.maxX(), PYRAMID.maxY() + 13, PYRAMID.maxZ()); + FitFixture.World world = new FitFixture.World(area); + + integrate(world, area, start("{\"mode\":\"SOURCE\"}", TerrainAdaptation.ENCAPSULATE, FitFixture.Piece.fixed(PYRAMID))); + + assertEquals(STONE, world.at(PYRAMID.minX() - 11, PYRAMID.minY(), PYRAMID.minZ())); + assertEquals(STONE, world.at(PYRAMID.minX(), PYRAMID.maxY() + 11, PYRAMID.minZ())); + assertEquals(AIR, world.at(PYRAMID.minX() - 12, PYRAMID.minY(), PYRAMID.minZ())); + assertEquals(AIR, world.at(PYRAMID.minX(), PYRAMID.maxY() + 12, PYRAMID.minZ())); + } + + @Test + public void sourceTerrainDensityOnlyUsesRigidAndFixedPieces() { + assertFalse(new FitPiece(new FitFixture.Piece(PYRAMID, PieceKind.TERRAIN_MATCHING, 0), FitFixture.BOTTOM_Y).isRigidOrFixed()); + assertTrue(new FitPiece(new FitFixture.Piece(PYRAMID, PieceKind.RIGID, 0), FitFixture.BOTTOM_Y).isRigidOrFixed()); + assertTrue(new FitPiece(new FitFixture.Piece(PYRAMID, PieceKind.FIXED, 0), FitFixture.BOTTOM_Y).isRigidOrFixed()); + } + + @Test + public void sourceEnvelopesAreTheVanillaOnes() { + assertTrue(TerrainIntegration.insideSourceJunctionEnvelope(0, -1, 0)); + assertTrue(TerrainIntegration.insideSourceJunctionEnvelope(0, -11, 0)); + assertFalse(TerrainIntegration.insideSourceJunctionEnvelope(0, 0, 0)); + assertFalse(TerrainIntegration.insideSourceJunctionEnvelope(0, -12, 0)); + assertFalse(TerrainIntegration.insideSourceJunctionEnvelope(12, -1, 0)); + assertTrue(TerrainIntegration.insideBurialEnvelope(5, 0, 0)); + assertFalse(TerrainIntegration.insideBurialEnvelope(6, 0, 0)); + assertTrue(TerrainIntegration.insideEncapsulationEnvelope(11, 0, 0)); + assertFalse(TerrainIntegration.insideEncapsulationEnvelope(12, 0, 0)); + } + + @Test + public void omittedTerrainRetainsSourceSemanticsAndAnExplicitTerrainWins() { + assertEquals(StructureTerrainMode.SOURCE, NativeStructureFit.NONE.resolvedTerrain().resolvedMode()); + assertEquals(StructureTerrainMode.PRESERVE, + NativeStructureFit.of(new StartMemo("{\"mode\":\"PRESERVE\"}", "null")).resolvedTerrain().resolvedMode()); + } + + @Test + public void legacyTemplateAirIsClearedAfterEveryTerrainFillPath() { + FitFixture.Piece piece = FitFixture.Piece.fixed(PYRAMID); + + assertTrue(TerrainIntegration.clearsLegacyTemplateAir(start("{\"mode\":\"SOURCE\"}", TerrainAdaptation.BURY, piece))); + assertTrue(TerrainIntegration.clearsLegacyTemplateAir(start("{\"mode\":\"SOURCE\"}", TerrainAdaptation.BEARD_BOX, piece))); + assertTrue(TerrainIntegration.clearsLegacyTemplateAir(start("{\"mode\":\"ENCASE\"}", TerrainAdaptation.NONE, piece))); + assertFalse(TerrainIntegration.clearsLegacyTemplateAir(start("{\"mode\":\"SOURCE\"}", TerrainAdaptation.NONE, piece))); + assertFalse(TerrainIntegration.clearsLegacyTemplateAir(start("{\"mode\":\"PRESERVE\"}", TerrainAdaptation.BURY, piece))); + assertFalse(TerrainIntegration.shouldClearLegacyAir(79, 80, false)); + assertTrue(TerrainIntegration.shouldClearLegacyAir(80, 80, false)); + assertTrue(TerrainIntegration.shouldClearLegacyAir(96, 80, false)); + assertFalse(TerrainIntegration.shouldClearLegacyAir(96, 80, true)); + } + + @Test + public void legacyTemplateAirClearsAboveTheGroundAndSparesTrees() { + Box area = new Box(0, 70, 0, 15, 90, 15); + FitFixture.World world = new FitFixture.World(area); + world.put(1, 80, 0, DIRT); + world.put(2, 79, 0, DIRT); + world.put(3, 80, 0, OAK_LOG); + FitFixture.Piece piece = FitFixture.Piece.rigid(new Box(0, 79, 0, 4, 85, 0), 1) + .legacyAir(1, 80, 0).legacyAir(2, 79, 0).legacyAir(3, 80, 0); + + TerrainIntegration.clearLegacyTemplateAir(world.fitBlocks(), area, + start("{\"mode\":\"SOURCE\"}", TerrainAdaptation.BEARD_THIN, piece)); + + assertEquals(AIR, world.at(1, 80, 0)); + assertEquals(DIRT, world.at(2, 79, 0)); + assertEquals(OAK_LOG, world.at(3, 80, 0)); + } + + @Test + public void vacuumLeavesPieceBlocksForTheSurfaceFitting() { + FitFixture.World world = new FitFixture.World(PYRAMID); + world.put(PYRAMID.minX(), PYRAMID.minY(), PYRAMID.minZ(), STONE); + + integrate(world, PYRAMID, start("{\"mode\":\"VACUUM\"}", TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID))); + + assertEquals(STONE, world.at(PYRAMID.minX(), PYRAMID.minY(), PYRAMID.minZ())); + } + + @Test + public void forceCarveHonorsConfiguredPadding() { + Box area = new Box(PYRAMID.minX() - 1, PYRAMID.minY(), PYRAMID.minZ() - 1, + PYRAMID.maxX() + 1, PYRAMID.maxY() + 1, PYRAMID.maxZ() + 1); + FitFixture.World world = new FitFixture.World(area); + world.put(PYRAMID.maxX() + 1, PYRAMID.minY(), PYRAMID.maxZ(), STONE); + world.put(PYRAMID.maxX(), PYRAMID.maxY() + 1, PYRAMID.maxZ(), STONE); + + integrate(world, area, start("{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":1,\"ceilingPadding\":1}", + TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID))); + + assertEquals(AIR, world.at(PYRAMID.maxX() + 1, PYRAMID.minY(), PYRAMID.maxZ())); + assertEquals(AIR, world.at(PYRAMID.maxX(), PYRAMID.maxY() + 1, PYRAMID.maxZ())); + } + + @Test + public void forceCarveUsesThePieceUnionInsteadOfTheCombinedBounds() { + Box second = new Box(64, 64, 0, 84, 78, 20); + int gapX = (PYRAMID.maxX() + second.minX()) / 2; + Box area = new Box(PYRAMID.minX(), 64, 0, second.maxX(), 64, 0); + FitFixture.World world = new FitFixture.World(area); + world.put(PYRAMID.minX(), 64, 0, STONE); + world.put(gapX, 64, 0, STONE); + + integrate(world, area, start("{\"mode\":\"FORCE_CARVE\"}", TerrainAdaptation.NONE, + FitFixture.Piece.fixed(PYRAMID), FitFixture.Piece.fixed(second))); + + assertEquals(AIR, world.at(PYRAMID.minX(), 64, 0)); + assertEquals(STONE, world.at(gapX, 64, 0)); + } + + @Test + public void carveFootprintIsComputedOncePerStartAndPadding() { + FitStart start = start("{\"mode\":\"FORCE_CARVE\"}", TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID)); + + StructureCarvingFootprint first = CarveFootprints.of(start, 6); + + assertSame(first, CarveFootprints.of(start, 6)); + assertNotSame(first, CarveFootprints.of(start, 7)); + assertNotSame(first, CarveFootprints.of( + start("{\"mode\":\"FORCE_CARVE\"}", TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID)), 6)); + assertEquals(PYRAMID.minX() - 6, first.minX()); + assertEquals(0L, first.distanceSquaredAt(PYRAMID.minX(), PYRAMID.minZ())); + assertEquals(PYRAMID.minY(), first.sourceMinYAt(PYRAMID.minX(), PYRAMID.minZ())); + assertEquals(PYRAMID.maxY(), first.sourceMaxYAt(PYRAMID.minX(), PYRAMID.minZ())); + } + + @Test + public void concurrentCarveRequestsShareOneFootprintBuild() throws Exception { + FitStart start = start("{\"mode\":\"FORCE_CARVE\"}", TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID)); + int requestCount = 16; + ExecutorService executor = Executors.newFixedThreadPool(requestCount); + CountDownLatch ready = new CountDownLatch(requestCount); + CountDownLatch release = new CountDownLatch(1); + List> futures = new ArrayList<>(); + try { + for (int request = 0; request < requestCount; request++) { + futures.add(executor.submit(() -> { + ready.countDown(); + release.await(); + return CarveFootprints.of(start, 11); + })); + } + assertTrue(ready.await(5, TimeUnit.SECONDS)); + release.countDown(); + StructureCarvingFootprint expected = futures.getFirst().get(); + for (Future future : futures) { + assertSame(expected, future.get()); + } + } finally { + executor.shutdownNow(); + } + } + + @Test + public void carveFootprintCacheStaysInsideItsCellBudget() { + for (int index = 0; index < 40; index++) { + CarveFootprints.of(start("{\"mode\":\"FORCE_CARVE\"}", TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID)), 128); + } + + assertTrue(CarveFootprints.cachedCells() <= CarveFootprints.maximumCachedCells()); + } + + @Test + public void organicCarveNeverCutsBelowTheColumnSupportingFloor() { + Box area = new Box(PYRAMID.minX() - 6, PYRAMID.minY() - 4, PYRAMID.minZ() - 6, + PYRAMID.maxX() + 6, PYRAMID.maxY() + 12, PYRAMID.maxZ() + 6); + FitFixture.World world = filled(area); + + TerrainIntegration.carveOrganicColumns(world.fitBlocks(), area, organicCarve(6, 0.85D)); + + assertEquals(AIR, world.at(PYRAMID.minX() + 10, PYRAMID.minY(), PYRAMID.minZ() + 10)); + for (int x = area.minX(); x <= area.maxX(); x++) { + for (int z = area.minZ(); z <= area.maxZ(); z++) { + for (int y = area.minY(); y < PYRAMID.minY(); y++) { + assertEquals(STONE, world.at(x, y, z)); + } + } + } + } + + @Test + public void lobedCarveStaysInsideTheUniformCarveAndRemovesLess() { + Box area = new Box(PYRAMID.minX() - 10, PYRAMID.minY(), PYRAMID.minZ() - 10, + PYRAMID.maxX() + 10, PYRAMID.maxY() + 12, PYRAMID.maxZ() + 10); + FitFixture.World uniform = filled(area); + FitFixture.World lobed = filled(area); + + TerrainIntegration.carveOrganicColumns(uniform.fitBlocks(), area, organicCarve(10, 0D)); + TerrainIntegration.carveOrganicColumns(lobed.fitBlocks(), area, organicCarve(10, 0.85D)); + + int uniformAir = 0; + int lobedAir = 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++) { + boolean uniformCarved = uniform.at(x, y, z).equals(AIR); + boolean lobedCarved = lobed.at(x, y, z).equals(AIR); + assertTrue("lobe carved outside the uniform padding at " + x + "," + y + "," + z, + uniformCarved || !lobedCarved); + uniformAir += uniformCarved ? 1 : 0; + lobedAir += lobedCarved ? 1 : 0; + } + } + } + assertTrue(lobedAir > 0); + assertTrue("uniform " + uniformAir + " lobed " + lobedAir, lobedAir < uniformAir); + } + + @Test + public void lobedCarveDepthWandersAlongAStraightFootprintEdge() { + int[] uniform = slabEdgeCarveDepths(0D); + int[] lobed = slabEdgeCarveDepths(0.85D); + + assertTrue("uniform depths wander " + span(uniform), span(uniform) <= 2); + assertTrue("lobed depths wander " + span(lobed), span(lobed) >= 6); + for (int depth : lobed) { + assertTrue(depth >= 0 && depth <= SLAB_PADDING); + } + } + + @Test + public void organicCarveIsIdenticalAcrossNeighboringChunkContexts() { + Box wide = new Box(PYRAMID.minX() - 6, PYRAMID.minY(), PYRAMID.minZ() - 6, + PYRAMID.maxX() + 6, PYRAMID.maxY() + 12, PYRAMID.maxZ() + 6); + Box narrow = new Box(PYRAMID.maxX() - 3, PYRAMID.minY(), PYRAMID.maxZ() - 3, + PYRAMID.maxX() + 6, PYRAMID.maxY() + 12, PYRAMID.maxZ() + 6); + FitFixture.World wideWorld = filled(wide); + FitFixture.World narrowWorld = filled(narrow); + + TerrainIntegration.carveOrganicColumns(wideWorld.fitBlocks(), wide, organicCarve(6, 0.85D)); + TerrainIntegration.carveOrganicColumns(narrowWorld.fitBlocks(), narrow, organicCarve(6, 0.85D)); + + int carved = 0; + for (int x = narrow.minX(); x <= narrow.maxX(); x++) { + for (int z = narrow.minZ(); z <= narrow.maxZ(); z++) { + for (int y = narrow.minY(); y <= narrow.maxY(); y++) { + BlockState expected = wideWorld.at(x, y, z); + assertEquals(expected, narrowWorld.at(x, y, z)); + carved += expected.equals(AIR) ? 1 : 0; + } + } + } + assertTrue(carved > 0); + } + + @Test + public void erodedForceCarveShrinkwrapsWithoutUnderminingTheFloor() { + Box area = new Box(PYRAMID.minX() - 6, PYRAMID.minY() - 2, PYRAMID.minZ() - 6, + PYRAMID.maxX() + 6, PYRAMID.maxY() + 12, PYRAMID.maxZ() + 6); + FitFixture.World world = filled(area); + int centerX = PYRAMID.minX() + PYRAMID.xSpan() / 2; + int centerZ = PYRAMID.minZ() + PYRAMID.zSpan() / 2; + + integrate(world, area, start("{\"mode\":\"FORCE_CARVE\",\"shape\":\"ERODED\",\"horizontalPadding\":6," + + "\"ceilingPadding\":8,\"floorPadding\":0,\"erosionStrength\":1.0,\"erosionFrequency\":0.05}", + TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID))); + + assertEquals(AIR, world.at(centerX, PYRAMID.minY(), centerZ)); + assertEquals(STONE, world.at(centerX, PYRAMID.minY() - 1, centerZ)); + assertEquals(STONE, world.at(area.minX(), area.maxY(), area.minZ())); + } + + private static void integrate(FitFixture.World world, Box area, FitStart start) { + TerrainIntegration.prepareTerrain(world.fitBlocks(), area, List.of(start), SEED, NATURAL, NO_PALETTES); + } + + private static FitStart start(String terrainJson, TerrainAdaptation adaptation, FitFixture.Piece... pieces) { + return FitFixture.start(terrainJson, adaptation, StructureStep.STRONGHOLDS, pieces); + } + + private static TerrainIntegration.SourceTerrainSnapshot snapshot(FitFixture.World world, Box area) { + BitSet layers = new BitSet(area.ySpan()); + layers.set(0, area.ySpan()); + return TerrainIntegration.SourceTerrainSnapshot.capture(world.fitBlocks(), area, layers); + } + + private static FitFixture.World filled(Box area) { + FitFixture.World world = new FitFixture.World(area); + 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++) { + world.put(x, y, z, STONE); + } + } + } + return world; + } + + private static TerrainIntegration.OrganicCarve organicCarve(int horizontalPadding, double lobeStrength) { + StructureTerrain terrain = erodedTerrain(horizontalPadding, lobeStrength); + FitStart start = start(JSON.toJson(terrain), TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID)); + return TerrainIntegration.organicCarve(CarveFootprints.of(start, horizontalPadding), terrain, + StructureCarveShape.ERODED, CARVE_SEED); + } + + private static StructureTerrain erodedTerrain(int horizontalPadding, double lobeStrength) { + return JSON.fromJson("{\"mode\":\"FORCE_CARVE\",\"shape\":\"ERODED\",\"horizontalPadding\":" + horizontalPadding + + ",\"ceilingPadding\":8,\"floorPadding\":0,\"erosionStrength\":1.0,\"erosionFrequency\":0.05," + + "\"lobeStrength\":" + lobeStrength + "}", StructureTerrain.class); + } + + /** + * Outward carve depth for every column along the straight +X edge of a slab footprint, measured inside the source + * vertical span so the boundary is decided purely by the horizontal threshold. + */ + private static int[] slabEdgeCarveDepths(double lobeStrength) { + StructureCarvingFootprint footprint = StructureCarvingFootprint.fromColumns(sink -> { + for (int x = 0; x < SLAB_WIDTH; x++) { + for (int z = 0; z < SLAB_DEPTH; z++) { + sink.column(x, z, SLAB_MIN_Y, SLAB_MIN_Y + 8); + } + } + return true; + }, SLAB_PADDING, 1_000_000); + int transectY = SLAB_MIN_Y + 4; + Box area = new Box(SLAB_WIDTH, transectY, 0, SLAB_WIDTH - 1 + SLAB_PADDING, transectY, SLAB_DEPTH - 1); + FitFixture.World world = filled(area); + + TerrainIntegration.carveOrganicColumns(world.fitBlocks(), area, TerrainIntegration.organicCarve( + footprint, erodedTerrain(SLAB_PADDING, lobeStrength), StructureCarveShape.ERODED, CARVE_SEED)); + + int[] depths = new int[SLAB_DEPTH]; + for (int z = 0; z < SLAB_DEPTH; z++) { + int depth = 0; + while (depth < SLAB_PADDING && world.at(SLAB_WIDTH + depth, transectY, z).equals(AIR)) { + depth++; + } + depths[z] = depth; + } + return depths; + } + + private static int span(int[] values) { + int lowest = Integer.MAX_VALUE; + int highest = Integer.MIN_VALUE; + for (int value : values) { + lowest = Math.min(lowest, value); + highest = Math.max(highest, value); + } + return highest - lowest; + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisStructureFoundationWriteTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisStructureFoundationWriteTest.java index 84c25e4ba..79001c814 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisStructureFoundationWriteTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisStructureFoundationWriteTest.java @@ -1,49 +1,64 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.UsableBlockPlatform; import art.arcane.iris.engine.mantle.MantleWriter; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.spi.IrisPlatform; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformRegistries; import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; +import com.volmit.block.PaletteSampler; +import org.junit.After; import org.junit.Test; import org.mockito.InOrder; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class IrisStructureFoundationWriteTest { + @After + public void unbindPlatform() { + UsableBlockPlatform.unbind(); + } + @Test public void resolvesWorldCoordinatesThenClearsCavernBeforeWritingSupport() { + UsableBlockPlatform.bind(); MantleWriter writer = mock(MantleWriter.class); - IrisMaterialPalette palette = mock(IrisMaterialPalette.class); - RNG rng = new RNG(1337L); - IrisData data = mock(IrisData.class); - PlatformBlockState deepslateBricks = mock(PlatformBlockState.class); - when(palette.get(rng, 12, -247, -18, data)).thenReturn(deepslateBricks); + List asked = new ArrayList<>(); + PaletteSampler picker = (x, y, z) -> { + asked.add((int) x + "," + (int) y + "," + (int) z); + return new BlockState("minecraft:deepslate_bricks"); + }; - StructurePlacing.writeFoundationSupport( - writer, palette, rng, data, 12, 9, -18, -256); + StructurePlacing.writeFoundationSupport(writer, picker, 12, 9, -18, -256); - InOrder order = inOrder(palette, writer); - order.verify(palette).get(rng, 12, -247, -18, data); + assertEquals(List.of("12,-247,-18"), asked); + InOrder order = inOrder(writer); order.verify(writer).clearData(12, 9, -18, MatterCavern.class); - order.verify(writer).set(12, 9, -18, deepslateBricks); + order.verify(writer).set(eq(12), eq(9), eq(-18), any(art.arcane.iris.spi.PlatformBlockState.class)); } @Test public void unresolvedPaletteFailsBeforeChangingCavernOrBlocks() { + UsableBlockPlatform.unbind(); + IrisPlatform platform = mock(IrisPlatform.class); + when(platform.registries()).thenReturn(mock(PlatformRegistries.class)); + IrisPlatforms.bind(platform); MantleWriter writer = mock(MantleWriter.class); - IrisMaterialPalette palette = mock(IrisMaterialPalette.class); - RNG rng = new RNG(1337L); - IrisData data = mock(IrisData.class); try { - StructurePlacing.writeFoundationSupport( - writer, palette, rng, data, 12, 9, -18, -256); + StructurePlacing.writeFoundationSupport(writer, (x, y, z) -> new BlockState("test:unknown"), 12, 9, -18, -256); } catch (IllegalStateException error) { assertTrue(error.getMessage().contains("12,-247,-18")); verifyNoInteractions(writer); diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelopeTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelopeTest.java index 300366f95..1b0e9391e 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelopeTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelopeTest.java @@ -1,6 +1,6 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.engine.object.structure.IrisStructureCarveShape; +import art.arcane.iris.builtin.structure.StructureCarveShape; import art.arcane.iris.util.project.noise.CNG; import art.arcane.volmlib.util.math.RNG; import org.junit.Test; @@ -13,31 +13,31 @@ public class StructureCarveEnvelopeTest { @Test public void exactStructureFootprintAlwaysCarves() { assertTrue(StructureCarveEnvelope.shouldCarveOverboreCell( - IrisStructureCarveShape.ERODED, 0D, 0D, 1D)); + StructureCarveShape.ERODED, 0D, 0D, 1D)); assertTrue(StructureCarveEnvelope.shouldCarveOverboreCell( - IrisStructureCarveShape.ROUNDED, 0D, 0D, 1D)); + StructureCarveShape.ROUNDED, 0D, 0D, 1D)); } @Test public void boxModeKeepsStraightCandidateVolume() { assertTrue(StructureCarveEnvelope.shouldCarveOverboreCell( - IrisStructureCarveShape.BOX, 100D, 0D, 1D)); + StructureCarveShape.BOX, 100D, 0D, 1D)); } @Test public void roundedModeStopsAtConfiguredReach() { assertTrue(StructureCarveEnvelope.shouldCarveOverboreCell( - IrisStructureCarveShape.ROUNDED, 1D, 0D, 1D)); + StructureCarveShape.ROUNDED, 1D, 0D, 1D)); assertFalse(StructureCarveEnvelope.shouldCarveOverboreCell( - IrisStructureCarveShape.ROUNDED, 1.000001D, 1D, 0D)); + StructureCarveShape.ROUNDED, 1.000001D, 1D, 0D)); } @Test public void zeroErosionStrengthMatchesRoundedMode() { assertTrue(StructureCarveEnvelope.shouldCarveOverboreCell( - IrisStructureCarveShape.ERODED, 1D, 0D, 0D)); + StructureCarveShape.ERODED, 1D, 0D, 0D)); assertFalse(StructureCarveEnvelope.shouldCarveOverboreCell( - IrisStructureCarveShape.ERODED, 1.000001D, 1D, 0D)); + StructureCarveShape.ERODED, 1.000001D, 1D, 0D)); } @Test @@ -68,7 +68,7 @@ public class StructureCarveEnvelopeTest { CNG roll = CNG.signature(new RNG(4242L)); for (double strength : new double[]{0.25D, 0.5D, 1D}) { - int limit = IrisStructureCarveShape.ERODED.maximumCeilingExtension(10, strength); + int limit = StructureCarveShape.ERODED.maximumCeilingExtension(10, strength); for (int x = -32; x <= 32; x++) { for (int z = -32; z <= 32; z++) { double reach = StructureCarveEnvelope.erodedUpReach(roll, 0.05D, strength, x, z, 10); diff --git a/core/src/test/java/art/arcane/iris/engine/object/structure/IrisStructurePlacementCarveSettingsTest.java b/core/src/test/java/art/arcane/iris/engine/object/structure/IrisStructurePlacementCarveSettingsTest.java deleted file mode 100644 index dfcf36a43..000000000 --- a/core/src/test/java/art/arcane/iris/engine/object/structure/IrisStructurePlacementCarveSettingsTest.java +++ /dev/null @@ -1,149 +0,0 @@ -package art.arcane.iris.engine.object.structure; - -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.structure.IrisStructureCarveShape; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import org.junit.Test; - -import java.lang.reflect.Field; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; - -public class IrisStructurePlacementCarveSettingsTest { - @Test - public void defaultsToSourceTerrainWithBoxCarving() { - IrisStructureTerrain terrain = new IrisStructureTerrain(); - - assertEquals(IrisStructureTerrainMode.SOURCE, terrain.resolvedMode()); - assertEquals(IrisStructureCarveShape.BOX, terrain.getShape()); - assertEquals(IrisStructureCarveShape.BOX, terrain.resolvedShape()); - assertEquals(0.8D, terrain.getErosionStrength(), 0D); - assertEquals(0.8D, terrain.resolvedErosionStrength(), 0D); - assertEquals(0.07D, terrain.getErosionFrequency(), 0D); - assertEquals(0.07D, terrain.resolvedErosionFrequency(), 0D); - assertEquals(0D, terrain.getLobeFrequency(), 0D); - assertEquals(0.021D, terrain.resolvedLobeFrequency(), 1.0E-12D); - assertEquals(0.85D, terrain.getLobeStrength(), 0D); - assertEquals(0.85D, terrain.resolvedLobeStrength(), 0D); - } - - @Test - public void lobeFrequencyAutoDerivesFromErosionFrequencyUntilAuthored() { - IrisStructureTerrain terrain = new IrisStructureTerrain().setErosionFrequency(0.05D); - - assertEquals(0.015D, terrain.resolvedLobeFrequency(), 1.0E-12D); - - terrain.setLobeFrequency(Double.NaN); - assertEquals(0.015D, terrain.resolvedLobeFrequency(), 1.0E-12D); - - terrain.setLobeFrequency(-1D); - assertEquals(0.015D, terrain.resolvedLobeFrequency(), 1.0E-12D); - - terrain.setLobeFrequency(0.04D); - assertEquals(0.04D, terrain.resolvedLobeFrequency(), 0D); - - terrain.setLobeFrequency(2D); - assertEquals(1D, terrain.resolvedLobeFrequency(), 0D); - } - - @Test - public void lobeStrengthClampsToTheAuthoredBand() { - IrisStructureTerrain terrain = new IrisStructureTerrain().setLobeStrength(Double.NaN); - - assertEquals(0.85D, terrain.resolvedLobeStrength(), 0D); - - terrain.setLobeStrength(-1D); - assertEquals(0D, terrain.resolvedLobeStrength(), 0D); - - terrain.setLobeStrength(2D); - assertEquals(1D, terrain.resolvedLobeStrength(), 0D); - - terrain.setLobeStrength(0.4D); - assertEquals(0.4D, terrain.resolvedLobeStrength(), 0D); - } - - @Test - public void carveShapesExposeTheirMaximumCeilingScale() { - assertEquals(1D, IrisStructureCarveShape.BOX.maximumCeilingScale(), 0D); - assertEquals(1D, IrisStructureCarveShape.ROUNDED.maximumCeilingScale(), 0D); - assertEquals(1.8D, IrisStructureCarveShape.ERODED.maximumCeilingScale(), 0D); - assertEquals(10, IrisStructureCarveShape.BOX.maximumCeilingExtension(10)); - assertEquals(10, IrisStructureCarveShape.ROUNDED.maximumCeilingExtension(10)); - assertEquals(18, IrisStructureCarveShape.ERODED.maximumCeilingExtension(10)); - assertEquals(10, IrisStructureCarveShape.ERODED.maximumCeilingExtension(10, 0D)); - assertEquals(14, IrisStructureCarveShape.ERODED.maximumCeilingExtension(10, 0.5D)); - assertEquals(0, IrisStructureCarveShape.ERODED.maximumCeilingExtension(0)); - } - - @Test - public void nullAndNonFiniteValuesResolveToDefaults() { - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setShape(null) - .setErosionStrength(Double.NaN) - .setErosionFrequency(Double.POSITIVE_INFINITY); - - assertEquals(IrisStructureCarveShape.BOX, terrain.resolvedShape()); - assertEquals(0.8D, terrain.resolvedErosionStrength(), 0D); - assertEquals(0.07D, terrain.resolvedErosionFrequency(), 0D); - - terrain.setErosionStrength(Double.NEGATIVE_INFINITY); - terrain.setErosionFrequency(Double.NaN); - - assertEquals(0.8D, terrain.resolvedErosionStrength(), 0D); - assertEquals(0.07D, terrain.resolvedErosionFrequency(), 0D); - } - - @Test - public void finiteValuesClampToAuthoredBounds() { - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setErosionStrength(-1D) - .setErosionFrequency(0D); - - assertEquals(0D, terrain.resolvedErosionStrength(), 0D); - assertEquals(0.001D, terrain.resolvedErosionFrequency(), 0D); - - terrain.setErosionStrength(2D); - terrain.setErosionFrequency(2D); - - assertEquals(1D, terrain.resolvedErosionStrength(), 0D); - assertEquals(1D, terrain.resolvedErosionFrequency(), 0D); - } - - @Test - public void encaseModeCarriesAnOptionalPaletteOverride() { - IrisStructureTerrain terrain = new IrisStructureTerrain() - .setMode(IrisStructureTerrainMode.ENCASE); - - assertEquals(IrisStructureTerrainMode.ENCASE, terrain.resolvedMode()); - assertNull(terrain.getEncasePalette()); - - IrisMaterialPalette palette = new IrisMaterialPalette().qclear().qadd("minecraft:tuff"); - assertSame(palette, terrain.setEncasePalette(palette).getEncasePalette()); - } - - @Test - public void numericSchemaBoundsMatchRuntimeBounds() throws NoSuchFieldException { - assertBounds("erosionStrength", 0D, 1D); - assertBounds("erosionFrequency", 0.001D, 1D); - assertBounds("lobeFrequency", 0D, 1D); - assertBounds("lobeStrength", 0D, 1D); - } - - private void assertBounds(String fieldName, double expectedMinimum, - double expectedMaximum) throws NoSuchFieldException { - Field field = IrisStructureTerrain.class.getDeclaredField(fieldName); - MinNumber minimum = field.getAnnotation(MinNumber.class); - MaxNumber maximum = field.getAnnotation(MaxNumber.class); - - assertNotNull(minimum); - assertNotNull(maximum); - assertEquals(expectedMinimum, minimum.value(), 0D); - assertEquals(expectedMaximum, maximum.value(), 0D); - } -} diff --git a/core/src/test/java/art/arcane/iris/engine/object/structure/IrisStructureStiltSettingsTest.java b/core/src/test/java/art/arcane/iris/engine/object/structure/IrisStructureStiltSettingsTest.java deleted file mode 100644 index cc2129104..000000000 --- a/core/src/test/java/art/arcane/iris/engine/object/structure/IrisStructureStiltSettingsTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package art.arcane.iris.engine.object.structure; - -import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import org.junit.Test; - -import java.lang.reflect.Field; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; - -public class IrisStructureStiltSettingsTest { - @Test - public void defaultsToCobblestoneFoundation() { - IrisStructureStiltSettings settings = new IrisStructureStiltSettings(); - - assertEquals(64, settings.getMaxDepth()); - assertEquals(1, settings.getSpacing()); - assertFalse(settings.isSupportNonOccluding()); - assertNotNull(settings.getPalette()); - assertEquals(1, settings.getPalette().getPalette().size()); - assertEquals("minecraft:cobblestone", settings.getPalette().getPalette().get(0).getBlock()); - } - - @Test - public void maxDepthSchemaIsBoundedToTheMaximumWorldHeight() throws NoSuchFieldException { - Field maxDepth = IrisStructureStiltSettings.class.getDeclaredField("maxDepth"); - MinNumber minimum = maxDepth.getAnnotation(MinNumber.class); - MaxNumber maximum = maxDepth.getAnnotation(MaxNumber.class); - - assertNotNull(minimum); - assertNotNull(maximum); - assertEquals(1.0, minimum.value(), 0.0); - assertEquals(4064.0, maximum.value(), 0.0); - } - - @Test - public void spacingSchemaSupportsSparseFoundations() throws NoSuchFieldException { - Field spacing = IrisStructureStiltSettings.class.getDeclaredField("spacing"); - MinNumber minimum = spacing.getAnnotation(MinNumber.class); - MaxNumber maximum = spacing.getAnnotation(MaxNumber.class); - - assertNotNull(minimum); - assertNotNull(maximum); - assertEquals(1.0, minimum.value(), 0.0); - assertEquals(64.0, maximum.value(), 0.0); - } -} diff --git a/core/src/test/java/art/arcane/iris/engine/object/structure/IrisStructureYBandTest.java b/core/src/test/java/art/arcane/iris/engine/object/structure/IrisStructureYBandTest.java deleted file mode 100644 index b4262f5e3..000000000 --- a/core/src/test/java/art/arcane/iris/engine/object/structure/IrisStructureYBandTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package art.arcane.iris.engine.object.structure; - -import art.arcane.iris.engine.object.structure.IrisStructureYBand; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import org.junit.Test; - -import java.lang.reflect.Field; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class IrisStructureYBandTest { - @Test - public void authoredBoundsResolveInOrder() { - IrisStructureYBand band = new IrisStructureYBand().setMin(-120).setMax(-20); - - assertEquals(-120, band.resolvedMin()); - assertEquals(-20, band.resolvedMax()); - } - - @Test - public void reversedBoundsNormalizeInsteadOfInverting() { - IrisStructureYBand band = new IrisStructureYBand().setMin(-20).setMax(-120); - - assertEquals(-120, band.resolvedMin()); - assertEquals(-20, band.resolvedMax()); - } - - @Test - public void collapsedBoundsResolveToASingleY() { - IrisStructureYBand band = new IrisStructureYBand().setMin(-64).setMax(-64); - - assertEquals(-64, band.resolvedMin()); - assertEquals(-64, band.resolvedMax()); - } - - @Test - public void numericSchemaBoundsCoverTheWholeBuildRange() throws NoSuchFieldException { - assertBounds("min"); - assertBounds("max"); - } - - private void assertBounds(String fieldName) throws NoSuchFieldException { - Field field = IrisStructureYBand.class.getDeclaredField(fieldName); - MinNumber minimum = field.getAnnotation(MinNumber.class); - MaxNumber maximum = field.getAnnotation(MaxNumber.class); - - assertNotNull(minimum); - assertNotNull(maximum); - assertEquals(-4064D, minimum.value(), 0D); - assertEquals(4064D, maximum.value(), 0D); - } -} diff --git a/core/src/test/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandlerTest.java b/core/src/test/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandlerTest.java index e27bb6a13..ab93959ac 100644 --- a/core/src/test/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandlerTest.java +++ b/core/src/test/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandlerTest.java @@ -13,11 +13,10 @@ import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.engine.framework.StructureReachability; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructureDecision; import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.engine.object.world.IrisWorld; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureGenerationStatus; +import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; import art.arcane.iris.engine.object.structure.StructureDistribution; import art.arcane.iris.spi.IrisPlatform; import art.arcane.iris.spi.IrisPlatforms; @@ -47,9 +46,9 @@ import static org.mockito.Mockito.when; public class StructureHandlerTest { @Test public void registeredEligibilityMatchesFindExecutionTruthTable() { - IrisNativeStructureDecision replacement = decision(NativeStructureGenerationStatus.REPLACED_BY_IRIS); - IrisNativeStructureDecision generated = decision(NativeStructureGenerationStatus.GENERATE_NATIVE); - IrisNativeStructureDecision disabled = decision(NativeStructureGenerationStatus.DISABLED_BY_PACK); + NativeStructureGenerationStatus replacement = NativeStructureGenerationStatus.REPLACED_BY_IRIS; + NativeStructureGenerationStatus generated = NativeStructureGenerationStatus.GENERATE_NATIVE; + NativeStructureGenerationStatus disabled = NativeStructureGenerationStatus.DISABLED_BY_PACK; assertTrue(StructureHandler.isEligibleRegisteredKey( replacement, false, false, true, false, false)); @@ -258,9 +257,6 @@ public class StructureHandlerTest { assertFalse(method.contains("catch (")); } - private static IrisNativeStructureDecision decision(NativeStructureGenerationStatus status) { - return new IrisNativeStructureDecision(status, 0, null, false, null, null); - } private static IrisStructurePlacement nativePlacement(String key, StructureDistribution distribution, double density) {